text:
Q: Nautilus crashes When I boot up ubuntu, the desktop is non-responsive (as in the desktop area, not unity etc, only what nautilus covers) and when I try and open nautilus it refuses to open. I have to kill it and then restart it for it to work. This works sometimes for a bit, sometimes it's fine, sometimes it even locks the whole system up. I put a script to kill nautilus on startup, however this doesn't work. This has happened 3 times today (on 3 different installs, I reinstalled each time) upon reboot after installation everything worked fine, it was only after updating did this problem occur. Any ideas how to diagnose/fix this?
It's driving me nuts -_-
(happens with nautilus and nautilus-elementary)
EDIT:
It seemed the desktop works fine, until I launch nautilus, then everything starts to become unresponsive, memory leak?

A: Are you using Ubuntu One?  Upon upgrading to Ubuntu 11.04 I was experiencing similar circumstances.  As it turns out, I was having a problem with Ubuntu One syncing.  Subsequently, for me it was a matter of getting Ubuntu One to sync properly.  Once this was accomplished, Nautilus began playing nice again.  If you suspect this might be your problem also, I can point you to the post that details the fix for Ubuntu One.

A: I had a similar problem. My Nautilus would take ages to start, and sometimes wouldn't start at all.
You seem more experienced than me, so you may have already tried my fix.
Remove nautilus from the startup applications. Log out, then log back in, then put nautilus on your start up applications.
I'm not sure how your system is set up, but be sure that you can navigate through the menus without nautilus. If you get stuck, open a terminal and type nautilus.
Hope it helps :)

A: I've encountered Nautilus crashing after release upgrading to 17.04.
Uninstall and reinstall of Nautilus have not solved the problem.
But the problem has been solved when I've reconfigured X display manager from lightdm to gdm3:
sudo dpkg-reconfigure gdm3


text:
Q: Is committing empty transactions expensive? In a certain Oracle 11.2 environment, I observe unnecessary commits, e.g.
-- some updates/inserts etc.
commit;
select * from mytable where somecond = 23;
commit;

Or even:
update mytable set foo = '42';
commit;
commit;

Thus, in both examples the 2nd commit is unnecessary, because the transaction is 'empty' - there is nothing to commit.
The question is: How expensive are those unnecessary commits?
Is the Oracle DB 'intelligent' enough to detect such empty transactions and replace those unnecessary commits with NOPs (nothing)?
Background: those redundant commits sometimes seem to come from layers of certain framework where the programmer is unaware of the 'hidden' logic - or sometimes they are just oversights. Depending on how expensive they are (in terms of DB performance) it will make sense to fix the code with high priority.

A: Empty commits are not expensive and can be ignored.  Empty commits only require a small amount of CPU and will not block other processes or prevent scalability.
A normal commit is slow because it causes data to be written to disk to ensure durability.  Database changes require REDO (in case the database crashes before the
 data can be written fully into the data files, allowing a recovery to roll foward), UNDO (so other transactions can see the data as it looked before the change),
 recording the new System Change Number to the control file, etc.  A commit does not finish until those things are written to disk.
An empty commit does not do any of those things.  They use CPU time but probably just enough to check that there are no changes that need to be made.  CPU time
 is cheap compared to writing to data files, redo logs, or control files.  It should scale well.
The below examples show that the real problem is when a COMMIT is executed after every tiny change.  The run time alone is not enough to compare these three methods.
  If you look at the waits in GV$ACTIVE_SESSION_HISTORY, or the disk I/O (from Windows Resource Monitor, Solaris truss, etc), you'll see that example #1 below
 only uses CPU.  Example #3 uses CPU, redo logs, data files, and control files.
--#1: Empty commits.
--15 seconds for 1 million commits.
--Only CPU waits, almost no I/O is generated.
begin
    for i in 1..1000000 loop
        commit;
    end loop;
end;
/

--#2: Just inserts.
--34 seconds for 1 million inserts.
--CPU waits, plus some "other" waits.
create table test1(a number);
begin
    for i in 1..1000000 loop
        insert into test1 values(1);
    end loop;
    commit;
end;
/

--#3: Inserts and commits.
--107 seconds for 1 million inserts and commits.
--Lots of CPU waits, lots of "other" waits.
begin
    for i in 1..1000000 loop
        insert into test1 values(1);
        commit;
    end loop;
end;
/

A: Yes, there is overhead even when there is nothing to commit. There are lot of things serialized when you issue the COMMIT so scalability is affected.
HUSQVIK@db> BEGIN
  2     FOR i IN 1..100000 LOOP
  3             NULL;
  4     END LOOP;
  5  END;
  6  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.00
HUSQVIK@db> BEGIN
  2     FOR i IN 1..100000 LOOP
  3             COMMIT;
  4     END LOOP;
  5  END;
  6  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:02.37

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extract XML From Binary I have a binary file that contains xmldata in bytes 2-43.
How would I go about extracting that data to a file?
I am able to extract small integer fields doing something like this:
Row.TenderNumber = BitConverter.ToInt16(Row.RawBytesraw, 44);
However, I don't know how to extract xml data from this file.
Any help is appreciated.

A: Something like this ought to work
    using (var stream = new MemoryStream(<byte[] here>))
    using (var reader = new StreamReader(stream))
    {
        var buffer = new char[41];
        stream.Seek(<offset where string begins>, SeekOrigin.Begin);
        reader.Read(buffer, 0, 41);
        <mystringVariable> = new string(buffer);
    }

I wrote it in C# but you get the idea.

A: xml data is just text with correct formatting. If you can extract bytes from file, you can convert them into string. And string can be XML.
Have a look on this question: binary file to string


text:
Q: How to count the repeated values in list based on anoth list in karate I am count the repeated values from the list
[
  "Cloud Services - Hybrid and Azure",
  "Cloud Services - Hybrid and Azure",
  "Cloud Services - Hybrid and Azure",
  "Cloud Services - Hybrid and Azure",
  "Application Development",
  "Application Development",
  "Application Development",
  "CAB Approval"
]

and i want the output to be "Cloud Services - Hybrid and Azure" = 4
karate.distinct() throws error. any help on this is much appreciated.

I tried to take unique values :

*

*json group = new java.util.HashSet(group)

A: Just use JS array operations, much simpler:
* def result = data.filter(x => x == 'Application Development')
* assert result.length == 3


text:
Q: a letter tree in C I'd like to store some data associated to words composed of simple ascii letters (a-Z)
The goal is to retrieve very quickly the data associated to a word in a future parsing.
I though about the following structure:
struct Foo {
  Foo *letter[26];
  void *data;
};

Thus, it is possible to go down through the "letter tree" while parsing a word in a string and get the associated data.
"foo" => ['f' node] -> ['o' node] -> ['o' node]

The problem is the size of the entire tree if I got many words.
Is there a way to reduce the size of the tree without losing performances?

A: What you're describeing is called trie. A compact radix tree is more compact.

A: Is there a reason you're using a tree instead of storing words in a hash table?  These will tend to use a bit more memory, but will give you near constant time performance for table lookups.


text:
Q: Dense vector on sparse matrix multiplication in tensorflow What is proper way of dense vector on sparse matrix multiplication in tensorflow?
According to documentation tf.matmul support sparse matrix multiplication, so do I need to use tf.sparse_matmul? (And also tf.sparse_tensor_dense_matmul exist, so in which cases each of them should be used?)
Also do I need to convert my sparse matrix to tf.SparseTensor ? Also it not obvious what tf.convert_to_tensor_or_sparse_tensor is doing and how to convert dense numpy matrix or scipy sparse matrix for tensorflow suitable input.
Here what I have tried(timing are for CPU):
import numpy as np
import tensorflow as tf

np.random.seed(2018)

# Parameters
n = 10*1000
m = 4*1000
p = 0.1

%%time

# Data preparation
dense_vector = np.random.rand(1,n).astype(np.float32)
print('dense_vector.shape', dense_vector.shape)
#print('dense_vector:')
#print(dense_vector)

dense_matrix = np.random.rand(n*m)
idx = np.random.choice(range(n*m), int((1.0-p)*n*m), replace=False)
dense_matrix[idx] = 0.0
dense_matrix = dense_matrix.reshape(n,m).astype(np.float32)
print('dense_matrix.shape', dense_matrix.shape)
#print('dense_matrix:')
#print(dense_matrix)

dense_vector.shape (1, 10000)
dense_matrix.shape (10000, 4000)
CPU times: user 9.8 s, sys: 2.38 s, total: 12.2 s
Wall time: 12.2 s

%%time

# Dense vector on dense matrix multiplication using numpy

res = dense_vector @ dense_matrix
print('res.shape', res.shape)
#print('res:')
#print(res)

%%time

# Dense vector on dense matrix multiplication using tensorflow tf.matmul V1

dense_vector_tf = tf.convert_to_tensor(dense_vector, np.float32)
dense_matrix_tf = tf.convert_to_tensor(dense_matrix, np.float32)
res_tf = tf.matmul(dense_vector_tf, dense_matrix_tf)

with tf.Session() as sess:
    res = sess.run(res_tf)
    print('res.shape', res.shape)
    #print('res:')
    #print(res)

res.shape (1, 4000)
CPU times: user 1.88 s, sys: 1.82 s, total: 3.7 s
Wall time: 3.54 s

%%time

# Dense vector on dense matrix multiplication using tensorflow tf.matmul V2

dense_vector_tf = tf.convert_to_tensor(dense_vector, np.float32)
dense_matrix_tf = tf.convert_to_tensor(dense_matrix, np.float32)
res_tf = tf.matmul(dense_vector_tf, dense_matrix_tf,
                   a_is_sparse=False,
                   b_is_sparse=True)

with tf.Session() as sess:
    res = sess.run(res_tf)
    print('res.shape', res.shape)
    #print('res:')
    #print(res)

res.shape (1, 4000)
CPU times: user 4.91 s, sys: 4.28 s, total: 9.19 s
Wall time: 9.07 s

%%time

# Dense vector on sparse matrix multiplication using tensorflow tf.sparse_matmul V1

dense_vector_tf = tf.convert_to_tensor(dense_vector, np.float32)
dense_matrix_tf = tf.convert_to_tensor(dense_matrix, np.float32)
res_tf = tf.sparse_matmul(dense_vector_tf, dense_matrix_tf,
                         a_is_sparse=False,
                         b_is_sparse=True)

with tf.Session() as sess:
    res = sess.run(res_tf)
    print('res.shape', res.shape)
    #print('res:')
    #print(res)

res.shape (1, 4000)
CPU times: user 4.82 s, sys: 4.18 s, total: 8.99 s
Wall time: 9 s

%%time

# Dense vector on sparse matrix multiplication using tensorflow tf.sparse_matmul V2

dense_vector_tf = tf.convert_to_tensor(dense_vector, np.float32)
dense_matrix_tf = tf.convert_to_tensor_or_sparse_tensor(dense_matrix, np.float32)
res_tf = tf.sparse_matmul(dense_vector_tf, dense_matrix_tf,
                         a_is_sparse=False,
                         b_is_sparse=True)

with tf.Session() as sess:
    res = sess.run(res_tf)
    print('res.shape', res.shape)
    #print('res:')
    #print(res)

res.shape (1, 4000)
CPU times: user 5.07 s, sys: 4.53 s, total: 9.6 s
Wall time: 9.61 s

Also I can't see any improvement using sparse matrices, what I'm doing wrong?


text:
Q: altering per-mode for a single siunitx-equation I am using siunitx in "per-mode=symbol", and that is working very well. However now I have run into an isolated case, where I need the "per"-symbol to be ^{-1}. Here is a MWE showing what I desire:
\documentclass[10pt]{article}

\usepackage[T1]{fontenc}
\usepackage{amsmath, amsthm, amssymb}
\usepackage[ansinew]{inputenc}
\usepackage[per-mode=symbol]{siunitx}

\begin{document}
\noindent A speed of $v=\SI{888}{\meter\per\second}$, this is fine. \\
\noindent A lifetime of $\Gamma=\SI{888}{\per\second}$, not OK. It should be 888 s$^{-1}$.

\end{document}

Is there a way to define for a single "instance" that it should not use per-mode=symbol?

A: The siunitx commands all take a first optional argument to apply settings locally. Thus you want
$\Gamma=\SI[per-mode=reciprocal]{888}{\per\second}$

here.


text:
Q: Error sending mail with Laravel app/Gmail in production I have this error when I try to send mail with Laravel 9 app using Gmail:

Failed to authenticate on SMTP server with username "*************@gmail.com" using the following authenticators: "LOGIN", "PLAIN", "XOAUTH2". Authenticator "LOGIN" returned "Expected response code "235" but got code "534", with message "534-5.7.9 Application-specific password required. Learn more at 534 5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor h4-20020a056830034400b0060603221274sm8631029ote.68 - gsmtp".". Authenticator "PLAIN" returned "Expected response code "235" but got code "534", with message "534-5.7.9 Application-specific password required. Learn more at 534 5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor h4-20020a056830034400b0060603221274sm8631029ote.68 - gsmtp".". Authenticator "XOAUTH2" returned "Expected response code "235" but got code "334", with message "334 eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==".".

This is my .env configuration.
MAIL_MAILER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=************@gmail.com
MAIL_PASSWORD=************
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=************@gmail.com
MAIL_FROM_NAME="Claims - *****"

I've been reading, and apparently since 5/22/2022 you can no longer activate the option to allow access to less secure applications in Gmail... so, how can we solve this? is this really my problem or another?

A: google recently changed there security protocol about less secure apps, that's why it's showing the error.


text:
Q: Cannot ignore local changes with `git checkout` command I have this:
$ git checkout -- .
$ git pull
Updating 4411c31..db4498d
error: Your local changes to the following files would be overwritten by merge:
        index.js
        utils.js
Please commit your changes or stash them before you merge.
Aborting

I keep trying git checkout -- . and it keeps giving me the same message. How do I obliterate the local changes here? I don't wish to keep my changes to index.js and utils.js.

A: My best guess would be that your files have been staged in git. That would mean that to get rid of the changes, you have to git reset HEAD . to unstage your changes, then git checkout -- . to actually get rid of them. If this is incorrect, could you please show the results of git status?


text:
Q: ASP.NET event log: populate "User" field? I'm writing to the Application event log from an ASP.NET webapp.  How can I populate the "User" field of the log entry?

A: The user that is recorded in the event log entry is the user that "owns" the thread (from a security perspective) at the time the event logging call was made. In an ASP.Net application (by default) this will be the account that ASP.Net is running under.
You can change which user a thread is running under using windows impersonation. For an example question on SO, see:
Windows Impersonation from C#
This is a non-trivial area, and not a case of simply supplying user details to the event logging call.

A: I grabbed the Username from Asp.net profile.  Then I passed it into the method.  Here I've used it in Global.asax, but the same principal should work elsewhere.
String username = User.Identity.Name;
            String pageRequested = ((HttpApplication)sender).Request.Path;

            error = Server.GetLastError().GetBaseException();

            String message = "ERROR MESSAGE: " + error.Message +
                                "\nINNER EXCEPTION: " + error.InnerException +
                                "\nSOURCE: " + error.Source +
                                "\nFORM: " + Request.Form.ToString() +
                                "\nQUERYSTRING: " + Request.QueryString.ToString() +
                                "\nTARGETSITE: " + error.TargetSite +
                                "\nSTACKTRACE: " + error.StackTrace +
                                "\nNCLWEB USERNAME: " + username +
                                "\nDATESTAMP: " + DateTime.Now;

            System.Diagnostics.EventLog.WriteEntry("NCLWeb", message, System.Diagnostics.EventLogEntryType.Error);


text:
Q: Select 1+ most recent rows Given is a table with articles. The following exemplary table contains one article in different variations:

ID     ARTICLE_NUMBER   STORE_ID   COUNTRY   TYPE   VALID_FROM
----------------------------------------------------------------
100    1                22         DE        A      2015-11-01
101    1                22         DE        A      2015-11-02
102    1                22         DE        A      2015-11-03
103    1                22         DE        A      2015-11-04
104    1                22         DE        B      2015-11-10
105    1                22         DE        B      2015-11-11
106    1                22         DE        B      2015-11-11

What I need is a query which returns just the ID of the article with

*

*article_number = 1 AND

*store_id = 22 AND

*country = 'DE' AND

*the latest valid_from timestamp.

So far, the query should return ID = 105 or 106 (both have the same valid_from date, but I want only the one or the other in my result, no matter which, but not both). AND: because there are two types for this article (A + B), I also need ID = 103 in my result set.
How must the query look like?

A: You could try the HAVING parameter in your filter and selecting MAX(ID)
Or with a subselect:
SELECT [Type],(SELECT TOP(1) ID from dbo.articles S WHERE S.[Type] = A.Type AND S.Valid_From = MAX(A.Valid_From))
FROM dbo.articles A
WHERE
    ARTICLE_NUMBER = 1
    AND STORE_ID = 22
    AND Country = 'DE'
    -- AND Valid_FROM = (SELECT MAX(VALID_FROM) FROM dbo.articles)
GROUP BY [Type]


text:
Q: How does Rühmkorff induction coil start and periodically produce sparks? I found the following pictures and equivalent circuit of the Rühmkorff induction coil:

Can someone explain the operating of this coil in a step by step fashion?

A: It's pretty straight forward:
Spring terminal T1 and adjustable terminal T2 are adjusted so that they are in contact when no current flows.
When you connect the battery to the device, current flows.
This causes a magnetic field in "soft iron core 1."
That pulls on "soft iron pole," causing it to move.  This opens the connection between the two terminals.
When the connection between the two terminals is opened, the magnetic field collapses, and the soft iron pole moves back to its resting position.
The circuit is now connected again, and the cycle repeats.
All of this happens in the primary coil of the device.
With the primary pulsing on and off, a pulsing high voltage is generated in the secondary coil.

The ignition coil on the old Ford model T worked the same way.
It used a vibration system to generate high voltage constantly.


text:
Q: Multiple Login URLs for Single Django Application I need to implement two separate login/logout URLs for my Django app, for two different types of users. My client wants to differentiate the URLs for customers and for employees, even though it's using the same user database. Mostly for branding purposes.
For employees:
/login
/logout
For customers:
/survey/login
/survey/logout
What's the best way of doing this without reinventing the whole login/logout process?

A: If there's truly no difference, just attach the auth views to the different URLs (You can have multiple URLs go to the same view).
urlpatterns = (
    (r'^login/$', 'django.contrib.auth.views.login'),
    (r'^logout/$', 'django.contrib.auth.views.logout'),
    (r'^survey/login/$', 'django.contrib.auth.views.login', {'template_name': 'survey_login.html'}),
    (r'^survey/logout/$', 'django.contrib.auth.views.logout', {'template_name': 'survey_logout.html'}), #Please notice the typo
)

A: You can point both sets of patterns to the same view functions. To handle redirects for the type of user, etc, you could look at the path or a value on your user's account to differentiate.


text:
Q: Python WTF forms, import error, no module named flask_wtf Im having trouble with flask_wtf, it keeps saying theres no module found with that name.
Ive read on another question that it could be to do with the virtual environment.
(I don't think my question is the same as that questions as Im clearly showing in my question that Ive installed flask-wtf whilst in my virtual environment. Also all the answers to that question do not seems to solve my problem, so I think if someone can solve my problem having this question active on stack exchange would be a big help to future people with this issue)
At the top of my script I have
from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from flask_wft import FlaskForm

and visual studio code is already flagging the flask_wtf as an error saying, no module named flask_wtf.
When I try and run my app.py I get
(env) (base) Benjamats-Air:helloPython benjamattesjaroen$ python3 app.py

Traceback (most recent call last):
  File "app.py", line 4, in <module>
    from flask_wft import FlaskForm
ModuleNotFoundError: No module named 'flask_wft'

So clearly I'm still in my virtual environment bellow when I try to install flask-wtf but it says its already installed.
(env) (base) Benjamats-Air:helloPython benjamattesjaroen$ pip install flask-wtf

Requirement already satisfied: flask-wtf in ./env/lib/python3.7/site-packages (0.14.2)
Requirement already satisfied: WTForms in ./env/lib/python3.7/site-packages (from flask-wtf) (2.2.1)
Requirement already satisfied: Flask in ./env/lib/python3.7/site-packages (from flask-wtf) (1.1.1)
Requirement already satisfied: itsdangerous>=0.24 in ./env/lib/python3.7/site-packages (from Flask->flask-wtf) (1.1.0)
Requirement already satisfied: click>=5.1 in ./env/lib/python3.7/site-packages (from Flask->flask-wtf) (7.0)
Requirement already satisfied: Werkzeug>=0.15 in ./env/lib/python3.7/site-packages (from Flask->flask-wtf) (0.16.0)
Requirement already satisfied: Jinja2>=2.10.1 in ./env/lib/python3.7/site-packages (from Flask->flask-wtf) (2.10.1)
Requirement already satisfied: MarkupSafe>=0.23 in ./env/lib/python3.7/site-packages (from Jinja2>=2.10.1->Flask->flask-wtf) (1.1.1)

So why then does it say theres no module named flask_wtf ?

A: I think this is a typo error.
While importing from the package, you used flask_wft, but while installing its
pip install flask-wtf. The t and f if you notice.


text:
Q: Equivalent 'cubic' method for interp3 MATLAB in python I am very frustrated because I cannot find a solution: I have to do a 3D interpolation in python using a cubic method. The MATLAB equivalent is
Vi = interp3(x,y,z,V,xi,yi,zi,'cubic')

where

x, y, z are 3D arrays in [N x N x N]
V is a 3D array in [N x N x N]
xi, yi, zi are 1D arrays [1 x M]

in my case N=69 and M=120000
Is it possible translate that code from MATLAB to python efficiently?
I tried to use scipy.interpolate.RegularGridInterpolator but it does not seem to solve my problem, because of the methods implemented and the dimensions of the arrays allowed.


text:
Q: Test AWS lambdas and layer using Jest? I have an AWS lambda API that uses a lambda layer with some helper functions.
Now, when deployed AWS forces a path for the layer that's something like /opt/nodejs/lib/helpers/awsGatewayResponses. However, locally I have another folder structure which (on my local machine) would make the path is layers/api-layer/nodejs/lib/helpers/awsGatewayResponses. (Cause I don't want to have a folder setup that /opt/nodejs/lib/...)
However, I'm setting up some tests using Jest and I've come across the issue that I have to change the imports which is of the format /opt/nodejs/lib/helpers/... to be layers/api-layer/nodejs/lib/helpers/ otherwise I will get import errors - and I don't want to make this change since it is not aligned with the actual deployed environment.
I'm looking for something that can change my paths to be layers/api-layer/nodejs/lib/helpers/ only when I'm running tests. Any ideas on how I can make some kind of dynamic import? I want to run some tests automatically on Github on commits.
Thanks in advance! Please let me know if I have to elaborate.


text:
Q: can anyone explain the FBX format for me? i use notepad++ to see the data structure of FBX model but i have some problems understanding it. Here is some info of a cube(side = 10) located in (0,0,0), can anyone tell me what do these members mean? THANKS!
Vertices: *24 {
a: -5,-5,0,5,-5,0,-5,5,0,5,5,0,-5,-5,10,5,-5,10,-5,5,10,5,5,10
}
PolygonVertexIndex: *36 {
a: 0,2,-4,3,1,-1,4,5,-8,7,6,-5,0,1,-6,5,4,-1,1,3,-8,7,5,-2,3,2,-7,6,7,-4,2,0,-5,4,6,-3
}
Edges: *18 {
a: 0,1,2,3,4,6,7,8,9,10,13,14,16,19,20,25,26,32
}
Normals: *108 {
a: 0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,-        1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,-   1,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0
}

UV: *24 {
a: 0,0,1,0,0,1,1,1,0,0,1,0,0,1,1,1,0,0,1,0,0,1,1,1
}
UVIndex: *36 {
a: 9,11,10,10,8,9,8,9,11,11,10,8,4,5,7,7,6,4,0,1,3,3,2,0,4,5,7,7,6,4,0,1,3,3,2,0
}

A: The negative vertex index indicates the end of the polygon. You can bitwise negate the negative index, to get the positive one.
In c this would be
posIndex = ~negIndex;

A:
I think these assumptions are quite reasonable, though I'm not sure
  why the PolygonVertexIndex array contains negative values (it seems
  every third index of each triangle is negative). Maybe to indicate the
  last index of a polygon, so you can have polygons which need not be
  triangles.

The one with the negative value represents the last vertex indeed.
To find out witch vertex this is, you have to negate it and subtract 1 from that value.
For example, -4 represents 3 ((-4)*(-1) - 1)

A: Even with no knowledge of the FBX format you can at least make some very reasonable guesses:

*

*The 24 values under Vertices are the 8 vertices of the cube (with 3 values representing one vertex).

*The 36 values under PolygonVertexIndex are the vertex indices (referencing the values from Vertices) for the 12 triangles making up the 6 faces of the cube.

*The 24 values under Edges are the vertex indices of the 12 edges of the cube.

*The 108 values under Normals are the 36 normals for each of the triangle corners of the 12 triangles (with 3 values representing one normal vector).

*The 24 values under UV are 12 texture coordinates (with 2 values representing one texture coordinate pair).

*The 36 values under UVIndex are the texture coordinate indices (referencing the values from UV) for the 36 triangle corners of the cube.
I think these assumptions are quite reasonable, though I'm not sure why the PolygonVertexIndex array contains negative values (it seems every third index of each triangle is negative). Maybe to indicate the last index of a polygon, so you can have polygons which need not be triangles.


text:
Q: switch to another activity with swipe is not working My requirement :-
I have two activities..When I swipe it will go to another activity..
So,I have :--
MainActivity.java
public class MainActivity extends Activity {

 private GestureDetectorCompat gestureDetectorCompat;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_getservice);

  gestureDetectorCompat = new GestureDetectorCompat(this, new MyGestureListener());
 }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
  this.gestureDetectorCompat.onTouchEvent(event);
        return super.onTouchEvent(event);
 }

 class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
  //handle 'swipe left' action only

        @Override
        public boolean onFling(MotionEvent event1, MotionEvent event2,
                float velocityX, float velocityY) {

         if(event2.getX() < event1.getX()){

          //switch another activity
             Intent intent = new Intent(
               MainActivity.this, Join_form.class);
             startActivity(intent);
             finish();
         }

            return true;
        }
    }
}

and Join_form.java
public class Join_form extends  Activity {

     private GestureDetectorCompat gestureDetectorCompat;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      gestureDetectorCompat = new GestureDetectorCompat(this, new MyGestureListener());
     }

     @Override
     public boolean onTouchEvent(MotionEvent event) {
      this.gestureDetectorCompat.onTouchEvent(event);
            return super.onTouchEvent(event);
     }

     class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
      //handle 'swipe left' action only

         @Override
            public boolean onFling(MotionEvent event1, MotionEvent event2,
                    float velocityX, float velocityY) {

                  if(event2.getX() > event1.getX()){

                   //switch another activity
                      Intent intent = new Intent(
                              Join_form.this, MainActivity.class);
                      startActivity(intent);
                      finish();
                  }

                return true;
            }
        }
    }

activity_getservice.xml is:--
        <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"   xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       >

<LinearLayout  android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#0b2607"
     >
<TextView android:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Form"
        android:layout_marginTop="30dp"
        android:padding="10dp"
        android:textSize="20dp"
        android:layout_gravity="center"/>

<View android:id="@+id/division1"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:layout_marginTop="5dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="#999999" />

   <LinearLayout android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal"
 android:layout_marginTop="5dp"
 android:layout_marginLeft="10dp"
 android:layout_marginRight="10dp">

        <TextView android:text="Name :"
    android:id="@+id/id"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:padding="10dip"
    android:gravity="left"
    android:layout_weight="1"
    />

      <EditText android:id="@+id/editText1"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:padding="10dip"
    android:hint="name"
    android:layout_weight="1" />

</LinearLayout>

<View android:id="@+id/division2"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:layout_marginTop="5dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="#999999" />

<LinearLayout android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal"
 android:layout_marginTop="5dp"
 android:layout_marginLeft="10dp"
 android:layout_marginRight="10dp">

        <TextView android:text="Address :"
    android:id="@+id/address"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:padding="10dip"
    android:gravity="left"
    android:layout_weight="1"
    />

      <EditText android:id="@+id/editText2"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:padding="10dip"
    android:hint="address"
    android:layout_weight="1" />

</LinearLayout>

<View
            android:id="@+id/division9"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:layout_marginTop="5dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
           android:background="#999999" />
<LinearLayout
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal"
  android:layout_marginTop="5dp"
 android:layout_marginLeft="10dp"
 android:layout_marginRight="10dp">

  <TextView
    android:text="You Are :"
    android:id="@+id/txt"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:padding="10dip"
   android:gravity="left"
    android:layout_weight="1" />

  <Spinner

    android:id="@+id/spinner2"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:padding="10dip"
    android:layout_weight="1" />

</LinearLayout>
<View
            android:id="@+id/division3"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:layout_marginTop="5dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
           android:background="#999999" />
<LinearLayout
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal"
  android:layout_marginTop="5dp"
 android:layout_marginLeft="10dp"
 android:layout_marginRight="10dp">

  <TextView
    android:text="hii"
    android:id="@+id/txt4"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:padding="10dip"
   android:gravity="left"
    android:layout_weight="1" />

  <Spinner

    android:id="@+id/spinner3"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:padding="10dip"
    android:layout_weight="1" />

</LinearLayout>
<View
            android:id="@+id/division10"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:layout_marginTop="5dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
           android:background="#999999" />

<LinearLayout
    android:id="@+id/check"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:layout_marginTop="5dp"
 android:layout_marginLeft="10dp"
 android:layout_marginRight="10dp">

     <TextView
    android:text="Select your reqirements:-"
    android:id="@+id/the"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="10dip"
    android:gravity="left"
    android:layout_weight="1"
    />

     <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         android:id="@+id/lay1">

        <CheckBox
            android:id="@+id/checkBox1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="apple"
            android:tag="apple"
              android:onClick="onCheckboxClicked" />

        <CheckBox
            android:id="@+id/checkBox2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="banana"
            android:tag="banana"
              android:onClick="onCheckboxClicked"/>

        <CheckBox
            android:id="@+id/checkBox3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="water_milon"
            android:tag="water_milon"
              android:onClick="onCheckboxClicked"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         android:id="@+id/lay2">

        <CheckBox
            android:id="@+id/checkBox4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="guava"
            android:tag="guava"
              android:onClick="onCheckboxClicked"/>

        <CheckBox
            android:id="@+id/checkBox5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="panir"
             android:tag="panir"
               android:onClick="onCheckboxClicked"/>

        <CheckBox
            android:id="@+id/checkBox6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="chatni"
             android:tag="chatni"
               android:onClick="onCheckboxClicked"/>

    </LinearLayout>

</LinearLayout>
<View
            android:id="@+id/division6"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
           android:background="#999999"
           android:layout_marginTop="5dp" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Write your message(optional) :"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="5dp" />

<EditText
    android:id="@+id/editText3"
     android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textMultiLine"
   android:padding="10dip"
   android:layout_marginTop="5dp"
   android:layout_marginLeft="30dp"
   android:layout_marginRight="30dp"
   android:background="@drawable/edit_text_stle"
   android:hint="write something ">
    <requestFocus />
</EditText>
<View
            android:id="@+id/division7"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
           android:background="#999999"
           android:layout_marginTop="5dp" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
         android:layout_marginTop="10dp">

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="send"
            />

    </LinearLayout>

 </LinearLayout>
 </ScrollView>

activity_main.xml is:--
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

</LinearLayout>

But I can not swipe the page. It is not going to the another page. Why it is happening?
Where is the problem?

A: Agree with @k3v1n4ud3. Let me just expand a bit since I can't really comment due to lack of karma.
With ViewPager (inside MainActivity.java) + MainFragment (Fragment)+ JoinForm (Fragment), you would be able to get away without having a listener for fling. It would just handle the swiping part automatically for you.
Just think about it like this: You have a brain (MainActivity w/ViewPager) and two arms (the first and second fragment you're implementing).

*

*Create a MainActivity that would contain your ViewPager.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

myViewPager = (ViewPager) findViewById(R.id.myViewPager);

//somehow fill the adapter
                    MyAdapter myAdapter = new MyAdapter(getSupportFragmentManager(), getApplicationContext()); //=== required as per the MyAdapter class

                    //set the adapter
                    myViewPager.setAdapter(myAdapter);

                    // display first fragment
                    myViewPager.setCurrentItem(0);

}

*Create an Adapter that extends FragmentPagerAdapter (or FragmentStatePagerAdapter). It looks like this:
class MyAdapter extends FragmentPagerAdapter {
private final int[] titles = {R.string.main_activity_title, R.string.join_activity_title};
private final String[] fragments = {
    MainFragment.class.getName(),
    JoinFragment.class.getName()
    };
private final Context ctx;

public MyAdapter(FragmentManager fm, Context ctx) {
    super(fm);
    this.ctx = ctx;
    }

@Override
public CharSequence getPageTitle(int position) {
    return ctx.getString(titles[position]);
    }

@Override
public Fragment getItem(int position) {
    return Fragment.instantiate(ctx, fragments[position]);
    }

@Override
public int getCount() {
    return titles.length;
    }
}

*(Optional) See those title thingys on top of each page, the ones you could click so you could fast forward to the other page? They're called tabhosts.
To use them, simply add a tabhost to your MainActivity layout and add this logic in MainActivity.java:
    myViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            // when user do a swipe the selected tab change
            myTabHost.setSelectedNavigationItem(position);
        }
    });

    //set titles
    for (int i = 0; i < myAdapter.getCount(); i++) {
        myTabHost.addTab(
                myTabHost.newTab()
                        .setText(myAdapter.getPageTitle(i))
                        .setTabListener(this)
        );
    }

4. (Optional) Animations on 'fling'
So to animate when you switch fragments, you simple have to call this:
    myViewPager.setPageTransformer(true, new DefaultTransformer());

And you can also customize it to your will.
I apologize if there are typos and other stuff. But this should cover majority of what you need.

A: You probably should change the architecture, transform your 2 activities into fragment and place them inside a viewPager. The viewPager will handle the sliding part for you.


text:
Q: How to use Extended File Attributes on NFS? I have an NFS_Server - NFS_Client system.
My client is mounted to an NFS_Server directory.
I want to change the attribute of NFS_Server directory's files via NFS_Client mounted directory by using Extended File Attributes (xattr).
When I tried to set an attribute from the client side, it gives the following answer:
root@ubuntu:/mnt/nfs/var/nfs# setfattr -n user.comment -v "some comment" test.txt
setfattr: nfs.txt: Permission denied
My question is:

*

*is it possible to use Extended File Attributes via NFS?

*if possible, how can I do this?
UPDATE:
Server side:
$ more  /etc/exports file has:
/var/nfs        192.168.56.123(rw,sync,no_subtree_check)

Client side:
$ root@ubuntu:/# mount -t nfs
192.168.56.130:/var/nfs on /mnt/nfs/var/nfs type nfs (rw,vers=4,addr=192.168.56.130,clientaddr=192.168.56.123)

thank you...

A: (This article is old, but I came across this article when looking for this functionality, and it doesn't represent the current state.)
As others have mentioned, there is no support for extended attributes in NFS.  However, there is significant interest in it, to the extent there is a proposed standard (RFC 8276).

A: All that is needed is Linux kernel version 5.9 or newer on both the server and client, then mount with NFS version 4.2 or newer. Support for extended attributes is enabled automatically when both server and client support nfs 4.2.
I have kernel version 5.15.16 on both my server and client with nfs-utils-2.5.4-r3, and it is working for me:
NFS Server /etc/exports
/  192.168.0.42(rw,subtree_check,no_root_squash)

NFS Client /etc/fstab
192.168.0.42:/  /mnt/slowpc  nfs  noatime,nodiratime,noauto,hard,rsize=1048576,wsize=1048576,timeo=60,retrans=60  0 0

NFS Client
# mount | grep /mnt/slowpc
192.168.0.42:/ on /mnt/slowpc type nfs4 (rw,noatime,nodiratime,vers=4.2,rsize=1048576,wsize=1048576,namlen=255,hard,proto=tcp,timeo=60,retrans=60,sec=sys,local_lock=none)
# cd /mnt/slowpc/tmp
# touch file
# printf bar | attr -s foo file
Attribute "foo" set to a 3 byte value for file:
bar
# attr -l file
Attribute "foo" has a 3 byte value for file

NFS Server
# attr -l /tmp/file
Attribute "foo" has a 3 byte value for /tmp/file

At https://lwn.net/Articles/799185/ it is mentioned that the new mount option user_xattr is required. However the current nfs utilities do not support that option. Fortunately user_xattr is enabled automatically when possible.
# mount -o user_xattr /mnt/test
mount.nfs: an incorrect mount option was specified
# tail -n 1 /var/log/messages
Jan 30 02:51:08 utl01 kernel: nfs: Unknown parameter 'user_xattr'

A: You can use fuse_xattrs (a fuse filesystem layer) to emulate extended attributes (xattrs) on NFS shares. Basically you have to do:

*

*mount the NFS share. e.g.: /mnt/shared_data

*mount the fuse xattr layer:

$ fuse_xattrs /mnt/shared_data /mnt/shared_data_with_xattrs

Now all the files on /mnt/shared_data can be accessed on /mnt/shared_data_with_xattrs with xattrs support. The extended attributes will be stored on sidecar files. The extended attributes are not going to be stored on the server filesystem as extended attributes, they are going to be stored in sidecar files.
Sadly this is only a work-around.
disclaimer: I'm the author of fuse_xattrs.

A: Extended attributes are not supported by nfs.There is no handler for user attributes in nfs kernel module.For more information read RFC for nfsv4.

A: The NFS code in Linux 5.9 has finally presented support for user extended attributes (user xattrs).
The NFS server updates for Linux 5.9 have support for user-extended attributes on NFS. This is the functionality outlined via IETF's RFC 8276 for handling of file-system extended attributes in NFSv4. "This feature allows extended attributes (hereinafter also referred to as xattrs) to be interrogated and manipulated using NFSv4 clients. Xattrs are provided by a file system to associate opaque metadata, not interpreted by the file system, with files and directories. Such support is present in many modern local file systems. New file attributes are provided to allow clients to query the server for xattr support, with that support consisting of new operations to get and set xattrs on file system objects."
Source: https://www.phoronix.com/scan.php?page=news_item&px=Linux-5.9-NFS-Server-User-Xattr


text:
Q: Determine if app is in foreground upon receiving a push notification iOS calls void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo) upon receiving a push notification regardless of whether the app is not running, in the background or in the foreground.
When it's in the foreground, I want the app to respond differently.
But how do I detect which state it is in?

A: Check the application state:
bool isInBackground =
    UIApplication.SharedApplication.ApplicationState == UIApplicationState.Background

A: You can detect when a push notification is tapped using a custom UNUserNotificationCenter  in the iOS project, and use the MessagingCenter to speak with the Xamarin.Form shared project.
The custom delegate:
create the file CustomUNUserNotificationCenterDelegate.cs in your Xamarin.iOS project:
using System;
using UserNotifications;
using Xamarin.Forms;

namespace MyApp.iOS
{
    public class CustomUNUserNotificationCenterDelegate : UNUserNotificationCenterDelegate
    {
        //This will be called when a user tap a notification and the app will be back in foreground
        public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
        {
            if (response.IsDefaultAction)
            {
                // User tapped on notification. Pass the notification body
               //(maybe its better to make some null check to prevent NRE. I'll skip it in this example
                var response = notification.Request.Content;
                MessagingCenter.Send("MyApp", "pushClicked", response.Body);
            }

            // Complete handling the notification.
            completionHandler();
        }
    }

    //This will be called when the notification is received when the app is in Foreground
    public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
    {
        //Notification received
        //(maybe its better to make some null check to prevent NRE. I'll skip it in this example
        var response = notification.Request.Content;
        MessagingCenter.Send("MyApp", "pushReceived", response.Body);

        //Complete handling the notification.
        completionHandler(UNNotificationPresentationOptions.None);
    }
}

Modify your AppDelegate.cs
Add to your AppDelegate.cs this to activate our custom delegate:
    //Custom delegate per gestire le push in foreground/cliccate da background
    if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
    {
        UNUserNotificationCenter.Current.Delegate = new CustomUNUserNotificationCenterDelegate();
    }

The Xamarin.Forms project
In your Xamarin.Forms project you can subscribe to your message and execute arbitrary code:
    //Subscribe to notification tapped when app is closed
    MessagingCenter.Subscribe<string, string> (this, "pushClicked", (sender, args) =>
    {
        //Do something when a push notification is clicked.
        //your notification body will be in the "args" variable
    });

    //Subscrive to notification received when app is in foreground
    MessagingCenter.Subscribe<string, string> (this, "pushReceived", (sender, args) =>
    {
        //Do something when a push notification is clicked.
        // your notification body will be in the "args" variable
    });

Dont forget to unsubscribe from the MessagingCenter when you dont need
  it anymore or the page/object container is disposed

A: You can monitor the Application lifecycle events:
public partial class App : Xamarin.Forms.Application
{
    public static bool IsInForeground { get; set; } = false;

    protected override void OnStart()
    {
        IsInForeground = true;
    }

    protected override void OnSleep()
    {
        IsInForeground = false;
    }

    protected override void OnResume()
    {
        IsInForeground = true;
    }
}

And then in any of your pages or services check for App.IsInForeground


text:
Q: Nuget packages.config and specific version I am trying to create a Nuget package from my project following this guide http://docs.nuget.org/docs/creating-packages/creating-and-publishing-a-package
I have successfully created a nuspec and nupkg. My project contains a dependency to Json.NET which I installed via Nuget. However, I want to specify a specific version of Json.NET to use, version 4.0.7. I added the below to my nuspec:
<dependencies>
  <dependency id="Newtonsoft.Json" version="[4.0.7]" />
</dependencies>

When I run nuget pack it seems to detect I have a packages.config
Using 'MyProject.nuspec' for metadata.
Found packages.config. Using packages listed as dependencies.

This seems to completely ignore my defined dependency in the nuspec as installing the Nuget package lists the dependencies as >= 4.0.7 which pulls in the latest version 4.0.8.
How can I stop this or preferably keep Nuget pulling in dependencies from the packages.config but allow me to overwrite specific dependencies?

A: The way you specified your version is correct; as shown in our versioning docs, [1.0] means 'version == 1.0'. The behavior you're describing would be a bug, but I couldn't reproduce the bug. What I did:

*

*Created a class library

*Added Json.NET via NuGet (it installed 4.0.8)

*Exec'd nuget spec

*Added <dependencies><dependency id="Newtonsoft.Json" version="[4.0.7]" /> to the .nuspec

*Exec'd nuget pack

*Opened the package in Package Explorer; it shows the dependency as '= 4.0.7'

*Installed my package in a new project; it shows the dependency as '= 4.0.7' and installs 4.0.7

Perhaps you aren't using the latest version of nuget.exe or the NuGet Visual Studio extension? When you say it "lists the dependency", where are you seeing that? When your package is installed, in Package Explorer, or somewhere else?

A: I hit the same issue. You need to define an exact version like this
<dependencies>
<dependency id="Newtonsoft.Json" version="[4.0.7,4.0.7]" />
</dependencies>

So that will ensure when the project pulls in the dependencies it will be = 4.0.7 not >= 4.0.7


text:
Q: Why don't specs2 + scalamock tests run in IntelliJ? Multiple suite traits detected I'm trying to run Specs2 tests from IDEA from both Windows and Mac versions of Intellij IDEA 14. I generated the idea project files using both gen-idea and the built in SBT plugin and get the same results...
When I try to run them, I get
Error running Specs2 in 'scala': Test class not found

I've added packages and switched "search for tests" to in single module but still no avail. I also get the message below on the run config.
Multiple suite traits detected: List(ScTrait: SpecificationStructure, ScTrait: SpecificationStructure,)

The similar post How to run all Specs2 tests under IntelliJ IDEA? doesn't help and it all runs fine from SBT, BTW. I can't run individual tests via the short-cut either :'(
I'm suspecting it's a combination of scalamock and specs2, as if I remove the following from my build.sbt, I can run them again.
"org.scalamock" %% "scalamock-specs2-support" % "3.2" % "test"

Here's the run config.

A: You should check if you have multiple specs2 jars dependencies in your module. If you just leave one jar dependency the configuration error should disappear.

A: To help other googlers, it could also be that you have one package depending on specs2-core, and scalamock-specs2-support which depends on specs2. The solution is to add an explicit dependency on specs2, and both dependencies should be evicted to the one you import. I was just able to fix this with the following dependency: "org.specs2" %% "specs2" % "3.7" % "test"


text:
Q: How to build a Flask-AppBuilder application from an existing simple flask application Hello I am new to python and I have built a simple dataViewer application using simple Flask and google chart. But now that I discovered Flask-AppBuilder and I would like to switch to Flask-AppBuilder then create a CRUD application from my existing application without loosing what I did before. Can someone help me how to did it?
Thank you


text:
Q: Efficient way in sending data from nodejs server to client using socketio I'm trying to create a simple chat app using nodejs, express, socketio and mysql. My question is, what is the most efficient way to send chat history data that I queried from mysql database in my nodejs server to the newly connected client application? Should I send the query results all at once and do the loop in client side or do the loop in nodejs server and send query results one by one to the client?

A: If by "efficient", you mean the least bandwidth to send the data, then it's nearly always more efficient to send one larger chunk of data then it is to send lots of smaller pieces of data (because there's overhead involved in each transmission).  You could just send a JSON-encoded array where each item in the array is a step in the history.  There are, of course, limits where you might want to break up really large pieces of data into more manageable pieces, so if your total data was hundreds of MBs, you probably don't want to send all of that at once.  But, if the total chat history is smaller than tens of MBs, probably best to just send it all at once (if your goal is to send it all).
Depending upon what you're sending, a plain JSON array of objects with lots of repeated property names is not always the most efficient format to send though it's always worth an experiment or two with compression turned on to see if it makes any difference or not.  We can't really comment further on that without seeing exactly what data you are sending.
In the future, you will get much more meaningful answers if you ask a specific question about your specific code and show both the code and the data you are sending.  Then, we can target our answer to your specific situation rather than having to make guesses about what your situation might be.  Theoretical questions pretty much never work as well here as specific questions about your actual code/data.  For some reason, there appears to be an instinct to ask a generic form of the question without your actual code/data, but that is usually exactly the wrong way to go and is a ton harder to offer a meaningful and specific answer to.


text:
Q: Backbone.js - Coordinating Layout (instantiation), State and History I am looking for a simple and extensible way of serializing the full state of my Backbone.js application.
Let's say I want to store the full state (some widget models + meta information such as the layout of the app etc.) in my "GlobalStateModel":
var GlobalStateModel = Backbone.Model.extend({
    defaults : {
        layout : undefined,
        widgetType1Collection : undefined, //Widget models
    },
});

I want to do this because then I can easily set corresponding history entries:
var HistoryController = Backbone.View.extend({
    model : globalStateModel,

    initialize: function () {
        _.bindAll(this, "render", "updateHistory");
        this.model.bind("change", this.updateHistory);
    },

    updateHistory : function () {
        var globalStateModel = this.model.toJSON()
        var state = jQuery.param.querystring("", state )
        appRouter.navigate('v1' + state, false);
    }
});

But here comes the tricky part ... I want to have a LayoutController or similar that instantiates widget modules that works together with the above:
var LayoutController = Backbone.View.extend({
    initialize: function () {
        _.bindAll(this, "render");
        this.model.bind("change:layout", this.render);
    },

    render : function () {
        var layout = this.model.get("layout");

        switch(layout){
            case "layout-1":
            this.renderLayout1();
            break;

            case "layout-2":
            this.renderLayout2();
            break;
        }
    },

    renderLayout1 : function () {

        var widgetModel1 = new WidgetModel()
        var widgetController1 = new WidgetController({model : widgetModel1})

        this.model.widgetType1Collection.add(widgetModel1);

        //fetch the right widget model attributes from the global state?
        widgetAttrs = { ..... }
        widgetModel1.set(widgetAttrs)

     },

});

Maybe this approach is completely flawed or maybe I'm just missing some plumbing to get this working?
How would you make the LayoutController instantiate 1 or several widgets and have their models be part of the globalState?
So that 1) when their models/collection changes, the globalState is serialized properly and 2) that globalState changes/hashchanges are reflected properly in the widgets?


text:
Q: Combine images using a nightshade Hi python and data visualization gurus,
I want to use the m.bluemarble() image as my "day" image, but then I want to use a different m.warpimage(...) as my "night" image.
Like this:
I am wondering if I can somehow use the m.nightshade(), but instead of just a black color, have it reveal the m.warpimage product instead?
import matplotlib.pyplot as plt
from datetime import datetime
from mpl_toolkits.basemap import Basemap
fig, axes = plt.subplots(1, figsize=(12,8))
m = Basemap(projection='cyl', resolution='l',
            area_thresh=None, ax=axes)
m.bluemarble()
m.warpimage('http://eoimages.gsfc.nasa.gov/images/imagerecords/55000/55167/earth_lights_lrg.jpg')
m.nightshade(datetime.utcnow(), alpha=0.5)
m.scatter([-75, 30, 40, 50, 60], [40, 20, 15, 10, -5], color='red', marker='o')
plt.show()

So, this almost does what I want, but it overwrites the original blue marble, which is not what I want to have happen. In the output image, where the image is darker (by the nightshade call), I want the warpimage to show through, but everywhere else, I want the original bluemarble.
Does anyone know a simple way to do this? Or, conversely, the hard way to do it, and still have a cool output image? For science.
Thanks in advance! Any advice is welcomed. I'm having a mental road-block...
Jake

A: I realise this is an old post, but as I was looking to do a similar thing I thought I'd post my possible solution. I'm a recent newcomer to Python so forgive the coding. I'm sure it can be tidied/rewritten more efficiently or using a more appropriate method!
From my Jupyter-Notebook:
import matplotlib.pyplot as plt
import datetime
from mpl_toolkits.basemap import Basemap
from matplotlib import path
import numpy as np
%matplotlib inline

def bluemarble_daynight(date,scale):

    # Define Bluemarble and Nightshade objects
    fig, axes = plt.subplots(1, figsize=(12,8))
    m  = Basemap(projection='cyl', resolution= None,
                 area_thresh=None, ax=axes)
    bm = m.bluemarble(scale=scale)
    ns = m.nightshade(date, alpha=0.5)

    bm_rgb = bm.get_array()
    bm_ext = bm.get_extent()

    axes.cla()

    # Get the x and y index spacing
    x = np.linspace(bm_ext[0], bm_ext[1], bm_rgb.shape[1])
    y = np.linspace(bm_ext[2], bm_ext[3], bm_rgb.shape[0])

    # Define coordinates of the Bluemarble image
    x3d,y3d = np.meshgrid(x,y)
    pts     = np.hstack((x3d.flatten()[:,np.newaxis],y3d.flatten()[:,np.newaxis]))

    # Find which coordinates fall in Nightshade
    # The following could be tidied up as there should only ever one polygon. Although
    # the length of ns.collections is 3? I'm sure there's a better way to do this.
    paths, polygons = [], []
    for i, polygons in enumerate(ns.collections):
        for j, paths in enumerate(polygons.get_paths()):
            #print j, i
            msk = paths.contains_points(pts)

    # Redefine mask
    msk        = np.reshape(msk,bm_rgb[:,:,0].shape)
    msk_s      = np.zeros(msk.shape)
    msk_s[~msk] = 1.

    # Smooth interface between Night and Day
    for s in range(bm_rgb.shape[1]/50): # Make smoothing between day and night a function of Bluemarble resolution
        msk_s = 0.25 * (  np.vstack( (msk_s[-1,:            ], msk_s[:-1, :            ]) )  \
                        + np.vstack( (msk_s[1:,:            ], msk_s[0  , :            ]) )  \
                        + np.hstack( (msk_s[: ,0, np.newaxis], msk_s[:  , :-1          ]) )  \
                        + np.hstack( (msk_s[: ,1:           ], msk_s[:  , -1,np.newaxis]) ) )

    # Define new RGBA array
    bm_rgba = np.dstack((bm_rgb, msk_s))

    # Plot up Bluemarble Nightshade
    m    = Basemap(projection='cyl', resolution= None,
                   area_thresh=None, ax=axes)
    bm_n = m.warpimage('http://eoimages.gsfc.nasa.gov/images/imagerecords/55000/55167/earth_lights_lrg.jpg',scale=scale)
    bm_d = m.imshow(bm_rgba)
    plt.title('Day/Night Map for %s (UTC)' % date.strftime("%d %b %Y %H:%M:%S"))
    plt.show()

date = datetime.datetime(2000,1,1,0,0,0)
bluemarble_daynight(date,0.25)


text:
Q: Is there a way to have static prototypes AND public ones in the same header file in C? The compiler will always whine when I have mixed public with static prototypes in a header file.
Say I have header main.h with a static prototype for function a and a normal prototype for function b. Then I want to #include the header in two .c files, namely main.c and other.c. In main.c I need an include as I call the function before any prototype.
main.h:
static int a(void);
int b(void);

main.c:
#include "main.h"
void main(){
  a();
}

static int a(void){
  /* do stuff */
}

int b(void){
  /* do stuff */
}

other.c:
#include "main.h"
b();

What's the best practice for this than the obvious solution of splitting the header file into a seperate header exclusively for static prototypes and one for public ones?

A: You don't put declarations of static functions in header files. Since they are local to the .c file that defines them, it doesn't make sense to export them from a header file.
There are two things you can do:

*

*Define the function before it is called in the c file (move definition of a() above main).

*Declare static function at the top of the C file (this is my personal choice). In your case, you move the declaration of a() to the top of main.c.

If the function is going to be used in multiple translation units, then you can define the static function in the header file. It could usefully be inline instead of static assuming you have a grown-up compiler that supports C99.

A: It makes no sense having static prototypes in a header, the reason for this is that static functions have file scope so no module outside can anyway access the functions.
Instead I would suggest you put static prototypes only in the .c file at the top of the file in the same file they are defined.

A: If you have the declaration of b() in main.h, why do you need it again in other.c that includes it? Other than that, it's all good, can't see any issue.
The important point to keep in mind about the "normal" functions is that all the forward declarations of the same function (b() in this case) must match, otherwise you'll have trouble (linking errors, compiler errors, what's not). In your case they don't match.
Unless of course b(); is an actual call to the function, but at least in the code you posted its out of any scope, thus is treated as a forward declaration.
Re the static forward declarations, they limit the visibility of the function to the compilation unit. So calling a() in other.c will not execute the a() implemented in main.c. That's the whole point of static in C.

A: IF the "static" function you want to define is short enough or cheap enough, you'll better define it as static inline and put its definition with its body (not only its declaration) in the *.h header file.


text:
Q: What is the difference between Relationship Metaparameters vs Chaining Arrows? The Puppet Language Relationships page has Relationship Metaparameters (before, require, notify, subscribe) and Chaining Arrows (->, ~>).
It seems that these could be used to the same effect. Using the examples they give, you could use before or require to dictate the order or it seems that you could also state Package['openssh-server'] -> File['/etc/ssh/sshd_config'].
What's the difference between these options?
What is considered "best practice" for ordering?
Also, when is it better to use before (or notify) vs require (or subscribe)? Does it matter or is it just a matter of preference?
same ordering relationship
package { 'openssh-server':
  ensure => present,
  before => File['/etc/ssh/sshd_config'],
}
file { '/etc/ssh/sshd_config':
  ensure  => file,
  mode    => 600,
  source  => 'puppet:///modules/sshd/sshd_config',
  require => Package['openssh-server'],
}

same notification relationship:
file { '/etc/ssh/sshd_config':
  ensure => file,
  mode   => 600,
  source => 'puppet:///modules/sshd/sshd_config',
  notify => Service['sshd'],
}
service { 'sshd':
  ensure    => running,
  enable    => true,
  subscribe => File['/etc/ssh/sshd_config'],
}

A: Yes, the relationship metaparameters and the chaining operators are different means to achieve the same ends.  The metaparameters have been in Puppet longer.
The chaining operators are distinguished by the fact that they can be used outside the scope of resource declarations without overriding resource parameters (overrides are not always possible).  They are especially useful in conjunction with resource collectors, so for example:
Group<||> -> User<||>

The metaparameters are distinguished by being parameters.  Among other things, that means their values can be drawn from resource defaults and / or from variables or class parameters.
There is no consensus best practice for whether to prefer chaining arrows or metaparameters for the many cases where both are viable.  I personally tend to prefer metaparameters when the relationship seems inherent in the nature of one or both resources, which is a lot of the time.
As to before/notify vs. require/subscribe, you will find that in many cases, it is more natural to define the relationship on one side than on the other.  This is especially true when one of the related resources is declared only conditionally: you then need to declare the relationship on the conditional side, lest the unconditional side sometimes have an unresolved relationship.  It can also be true when many resources must be related to one: even if you know all the resources involved, it is often easier to declare the relationship on the "many" side.
In many cases, however, yes, it is a matter of preference.


text:
Q: Django send_mail() in GAE I want a logged in user to be able to send a copy of the model object they created that has been saved in the database. Am using the get(pk=id) to recognize the particular one the user wants to send. The problem is, the send_mail() doesn't recognize the recipient email (to).
   @login_required
    def email_query(request, id):
        history = Carloan_form.objects.get(pk=id)
        subject = 'Nigerian Loan Calculator Query e-mail'
        from_email = 'xxxx@gmail.com'
        email = request.user.email
        to = "email"
        send_mail(subject,get_template('carloan/loancalc-query.txt').render(Context({'history':history})),\
                 from_email,[to], fail_silently=False)
        return HttpResponse('sent')

Update
@login_required
def email_query(request, id):
    history = Carloan_form.objects.get(pk=id)
    subject = 'Nigerian Loan Calculator Query e-mail'
    from_email = 'ajibike.ca@gmail.com'
    email = request.user.email
    send_mail(subject,get_template('carloan/loancalc-query.txt').render(Context({'history':history})),\
             from_email,[email,], fail_silently=False)
    return HttpResponse('/history_query_sent/')

Just decided to pass the email straight into the send_mail() and it worked. Thanks

A: Because you've set to to the string "email". I doubt that is what you wanted to do.
Why not pass the email variable directly into the send_mail call?


text:
Q: How to speed up backend of magento? my magento store backend is very slow, how can I speed up admin panel in magento?
I used items in below link but admin panel is still very slow:
https://suyati.com/blog/speed-up-magento-admin-backend/

A: 3 ways to speed up Magento backend:

*

*Sign up for better hosting plan. More CPU, More RAM.

*Audit your server. Make sure it is optimized. Upgrade OS. Upgrade web server (nginx or apache). Fine tune MySQL with the help of mysqltuner.

*3rd party plugins audit. Some custom extensions might slow your backend. Disable 3rd party plugins one by one and benchmark speed.

Taken from here.
Bonus point: enable Magento profiler and study its trace. See what function calls take most time. Try to understand why they take that much time and what you can do about. (In most cases it is some custom plugin, just delete it or find an alternative)


text:
Q: Installing scikit: ImportError: cannot import name MAXREPEAT I'm running elementary OS (a derivative of Ubuntu 12.04) on which I have installed:
Python 2.7.3 (default, Sep 26 2013, 20:08:41)
[GCC 4.6.3] on linux2
NumPy 1.8.0, SciPy 0.12.0, Matplotlib 1.2.1

I decided to install scikit following the simple instructions given here, which is basically the line:
sudo apt-get install python-sklearn

but it fails with the error:
...
  File "/usr/local/lib/python2.7/sre_parse.py", line 17, in <module>
    from sre_constants import *
  File "/usr/local/lib/python2.7/sre_constants.py", line 18, in <module>
    from _sre import MAXREPEAT
ImportError: cannot import name MAXREPEAT

Someone apparently had a similar issue here ImportError: cannot import name MAXREPEAT with cx_Freeze but I'm not sure the questions are equivalent and the answer given tells me very little about how to fix my install. Thoughts?

A: Whatever the issue was, running:
sudo pip install -U scikit-learn

installed it correctly.


text:
Q: Translate Pandas merge to Dask I am trying to perform a somewhat involved operation on a dataframe involving grouping and operations on numpy arrays. I can get the operation to work in Pandas, but the equivalent code in Dask gives me an error that I haven't figured out how to work around.
I have two kinds of items in my dataframe: shapes and colors. Each item is associated with a vector represented as a numpy array.
from pandas import DataFrame
from numpy import array
from scipy.spatial.distance import cosine
from numpy import mean as array_mean

p = DataFrame({
    "type": ["shape", "shape", "color", "color", "color"],
    "vector": [array([1.0, 1.1]),
                  array([0.8, 0.9]),
                  array([0.6, 0.8]),
                  array([1.1, 1.2]),
                  array([0.7, 0.9])
                 ]
})

    type    vector
0   shape   [1.0, 1.1]
1   shape   [0.8, 0.9]
2   color   [0.6, 0.8]
3   color   [1.1, 1.2]
4   color   [0.7, 0.9]

I want to do the following:

*

*Group the items by type.

*Take the mean vector for each group.

*For each item, calculate the cosine distance of its vector to its group's mean and sort within the group by this distance.

The following function accomplishes this with Pandas.
def pandas_ordering(f):
    means = f.groupby("type")["vector"].apply(array_mean).to_frame().rename(columns={"vector":"mean"})
    f = f.merge(means, left_on="type", right_index=True)
    f["cosine distance"] = f.apply(lambda row:cosine(row["vector"], row["mean"]), axis=1)
    return f.groupby("type", group_keys=False).apply(lambda x:x.sort_values("cosine distance"))

pandas_ordering(p)

    type    vector       mean                                       cosine distance
4   color   [0.7, 0.9]  [0.8000000000000002, 0.9666666666666667]    0.000459
2   color   [0.6, 0.8]  [0.8000000000000002, 0.9666666666666667]    0.001144
3   color   [1.1, 1.2]  [0.8000000000000002, 0.9666666666666667]    0.001280
0   shape   [1.0, 1.1]  [0.9, 1.0]                               0.000012
1   shape   [0.8, 0.9]  [0.9, 1.0]                               0.000019

I rewrote the function in Dask. The logic is identical, and the code is almost identical except for a couple of meta decorations.
import dask.dataframe as dd

f = dd.from_pandas(p, npartitions=1)

def dask_ordering(f):
    means = f.groupby("type")["vector"].apply(array_mean, meta="object").to_frame().rename(columns={0:"mean"})
    f = f.merge(means, left_on="type", right_index=True)
    f["cosine distance"] = f.apply(lambda row:cosine(row["vector"], row["mean"]), axis=1, meta="object")
    f.groupby("type", group_keys=False).apply(lambda x:x.sort_values("cosine distance"), meta="object")
    return f

However, the Dask version gives an error when it tries to merge the frame of means with the original frame of vectors.
dask_ordering(f).compute()

  ---------------------------------------------------------------------------
  ValueError                                Traceback (most recent call last)
  <ipython-input-120-46dd96a5db68> in <module>
  ----> 1 dask_ordering(f).compute()

  <ipython-input-119-49ddda5479b1> in dask_ordering(f)
        5 def dask_ordering(f):
        6     means = f.groupby("type")["vector"].apply(array_mean, meta="object").to_frame().rename(columns={0:"mean"})
  ----> 7     f = f.merge(means, left_on="type", right_index=True)
        8     f["cosine distance"] = f_1.apply(lambda row:cosine(row["vector"], row["mean"]), axis=1, meta="object")
        9     f.groupby("type", group_keys=False).apply(lambda x:x.sort_values("cosine distance"), meta="object")

  ~/Documents/notebooks/env/lib/python3.6/site-packages/dask/dataframe/core.py in merge(self, right, how, on, left_on, right_on, left_index, right_index, suffixes, indicator, npartitions, shuffle)
     3768             npartitions=npartitions,
     3769             indicator=indicator,
  -> 3770             shuffle=shuffle,
     3771         )
     3772

  ~/Documents/notebooks/env/lib/python3.6/site-packages/dask/dataframe/multi.py in merge(left, right, how, on, left_on, right_on, left_index, right_index, suffixes, indicator, npartitions, shuffle, max_branch)
      490             right_index=right_index,
      491             suffixes=suffixes,
  --> 492             indicator=indicator,
      493         )
      494

  ~/Documents/notebooks/env/lib/python3.6/site-packages/dask/dataframe/multi.py in single_partition_join(left, right, **kwargs)
      321     # new index will not necessarily correspond the current divisions
      322
  --> 323     meta = left._meta_nonempty.merge(right._meta_nonempty, **kwargs)
      324     kwargs["empty_index_dtype"] = meta.index.dtype
      325     name = "merge-" + tokenize(left, right, **kwargs)

  ~/Documents/notebooks/env/lib/python3.6/site-packages/pandas/core/frame.py in merge(self, right, how, on, left_on, right_on, left_index, right_index, sort, suffixes, copy, indicator, validate)
     7347             copy=copy,
     7348             indicator=indicator,
  -> 7349             validate=validate,
     7350         )
     7351

  ~/Documents/notebooks/env/lib/python3.6/site-packages/pandas/core/reshape/merge.py in merge(left, right, how, on, left_on, right_on, left_index, right_index, sort, suffixes, copy, indicator, validate)
       79         copy=copy,
       80         indicator=indicator,
  ---> 81         validate=validate,
       82     )
       83     return op.get_result()

  ~/Documents/notebooks/env/lib/python3.6/site-packages/pandas/core/reshape/merge.py in __init__(self, left, right, how, on, left_on, right_on, axis, left_index, right_index, sort, suffixes, copy, indicator, validate)
      628         # validate the merge keys dtypes. We may need to coerce
      629         # to avoid incompat dtypes
  --> 630         self._maybe_coerce_merge_keys()
      631
      632         # If argument passed to validate,

  ~/Documents/notebooks/env/lib/python3.6/site-packages/pandas/core/reshape/merge.py in _maybe_coerce_merge_keys(self)
     1136                     inferred_right in string_types and inferred_left not in string_types
     1137                 ):
  -> 1138                     raise ValueError(msg)
     1139
     1140             # datetimelikes must match exactly

  ValueError: You are trying to merge on object and int64 columns. If you wish to proceed you should use pd.concat

Presumably Dask is confused about the type of one of the columns, but I'm not sure which one. In particular I am not sure what the mention of a "int64" column in the error message is referring to.
The intermediary frame of mean vector values looks the same for both Pandas and Dask.
p.groupby("type")["vector"].apply(array_mean).to_frame().rename(columns={"vector":"mean"})

and
f.groupby("type")["vector"].apply(array_mean, meta="object").to_frame().rename(columns={0:"mean"}).compute()

both give
       mean
type
color  [0.8000000000000002, 0.9666666666666667]
shape  [0.9, 1.0]

Does anyone know how to make this work in Dask?

A: The problem is when you create the means dataframe - the index is an int and not an str (probably is a bug that is worth while to raise in github) (for some sort of reason - it may automatically be converted into a categorical type or something similar.)
In the mean time - below function is a work around.
def dask_ordering(f):
    means = f.groupby("type")["vector"].apply(array_mean, meta="object").to_frame(name="mean")
    means['idx'] = means.index
    means['idx'] = means['idx'].astype(str)
    f = f.merge(means, left_on="type", right_on="idx")
    f["cosine distance"] = f.apply(lambda row:cosine(row["vector"], row["mean"]), axis=1, meta="object")
    f.groupby("type", group_keys=False).apply(lambda x:x.sort_values("cosine distance"), meta="object")
    return f


text:
Q: Pass a returned value from a thread to another thread I'm learning posix thread programming and I'm struggling in the following program. So I've 2 threads with the ids: tid1 and tid2. I use the thread with tid1 to enter the values I want to sum each other into the second thread with tid2 but the result of the sum is not correct. So I've tried to display in tid2 the values I entered in tid1 but I realized that these are not correct too (didn't correspond to the entered values). Can you pleas tell me where I'm doing the error? The way I pass the pointer returned from a thread with tid1 to thread with tid2, is that correct?
Note: The values returned from tid1 are already correct because I checked it as you can also see in the main (line 56).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

void *entryValues(void *p)
{
   int nbVal = *(int*)p;
   int i = 0;
   int val = 0;
   int *tab;

   while(i < nbVal){
      printf("value %d: ", i);
      scanf("%d", &val);
      tab[i] = val;
      i++;
   }

   pthread_exit(tab);

}

void *sumValues(void *p)
{
    int *values;
    int sum = 0, i = 0;
    memcpy(values, (int*)p, sizeof((int*)p));
    printf("%d\n", values[0]);
    for (i = 0; i < sizeof(values); i++)
    {
    //printf("value %d: %d\n", i, values[i]);
    sum += values[i];
    }
    printf("The sum of the entered values is: %d\n", sum);
    return NULL;

}

int main(int argc, char **argv)
{
   pthread_t tid1;
   pthread_t tid2;
   int nbValues = 0;
   int *arr;

   printf("Please enter the number of values you want to sum each other: ");
   scanf("%d", &nbValues);
   if(pthread_create(&tid1, NULL, entryValues, &nbValues)!= 0)
   {
    fprintf(stderr, "creation of thread failed\n");
    return -1;
   }

   pthread_join(tid1, (void**)&arr);
   //printf("array: %d\n", arr[0]);

   if(pthread_create(&tid2, NULL, sumValues, arr) != 0)
   {
    fprintf(stderr, "creation of thread failed\n");
    return -1;
   }
   pthread_join(tid2, NULL);
   /* Waiting for the termination of tid */
   printf("End of main thread\n");
   return EXIT_SUCCESS;

}


text:
Q: How to use a system path to load xml file in XElement in windows phone I am working with a windows phone8 application. I have a file stored at a particular location in device and i want to open it with XElement. If i give path to that file it says uri should be relative and see webclient for more details. I know that it cant take xmlReader cause its not availabe in windows phone so that leaves me with two options to open a file with XElement which are String uri which windows phone libraries treat as a url and TextReader.
Can some one please give me an idea how to load my file in XElement directly for reading and writing purpose. Please help me out on this. or Any other way to handle my xml files.
Regards

A: The first approach I'd suggest is opening the path as a stream, and then use XDocument.Load(Stream). (There's a similar method for XElement, but I typically use XDocument when I'm loading a whole document, to make it clear that that's what I'm doing.)
That may cause issues if the document has relative DTD links or something similar, but in the vast majority of cases it will work.
Likewise you can save to a stream too.


text:
Q: Removing password_digest from API json? I'm using Sinatra to make a simple little API. I have not been able to figure out a way to remove the 'password_digest' field from the JSON I'm outputting. Well, I know of a long way that I can do it, but I have a feeling there is a much simpler way.
get "/users/all" do
content_type :json
@users = User.all

response = @users.map do |user|
  user = user.to_h
  user.delete("password_digest")
  user
end
response.to_json

end
All I'm trying to do is remove the password_digest field from the output. Is there a simple way to do this? I've tried searching with no luck.

A: get "/users/all" do
  content_type :json
  @users = User.all
  @users.to_json(except: [:password_digest])
end

You can also overide #as_json on the model to remove the attribute completely from serialization:
class User < ActiveRecord::Base
  def as_json(**options)
    # this coerces the option into an array and merges the passed
    # values with defaults
    excluding = [options[:exclude]].flatten
                                   .compact
                                   .union([:password_digest])
    super(options.merge(exclude: excluding))
  end
end

A: You should be able to do this:
  get "/users/all" do
    content_type :json
    @users = User.all

    response = @users.map do |user|
      user = user.to_h  # If your data is already a hash, you don't need this line.
      user.delete(:password_digest) # <-- If your keys are symbolized
      user.delete("password_digest") # <-- If your keys are strings
      user
    end
    response.to_json
  end


text:
Q: Stop a service so it can be uninstalled I am doing some automated uninstalls of Autodesk software, and Autodesk has once again screwed the pooch with their uninstalls. Their uninstall is supposed to do reference counting on certain shared components, like their Single Signor Service, Autodesk Genuine Service, Licensing service, etc. The problem is, when you are uninstalling that last ADSK product, the uninstaller is too stupid to stop the service, so their uninstaller fails with a 1603 fatal error. Last year you could stop the services before you started the uninstall, but this year I am getting this error
Stop-Service : Service 'Autodesk Access Service Host (Autodesk Access Service Host)' cannot be stopped due to the following error: Cannot open Autodesk Access Service Host service on computer '.'.

When using this code
Get-Service -Name "Autodesk Access Service Host" | Stop-Service -Force -NoWait

I have verified with
(Get-Service -Name "Autodesk Access Service Host").CanStop

that service can be stopped. At least according to the property.
I also tried
Start-Process "$env:WINDIR\system32\sc.exe" \\.,stop,"Autodesk Access Service Host" -NoNewWindow -Wait
while ((Get-Service -ComputerName '.' -Name "Autodesk Access Service Host" |
Select -ExpandProperty Status) -ne 'Stopped') {
    Write-Host "Waiting for service to stop..."
    Start-Sleep -Seconds 10
}

And that has run for 15 minutes with no results. Interestingly I CAN disable the service, but I really don't want that. I just want to stop it temporarily, so IF the Autodesk uninstall that is running is the last one with a dependency on this service will uninstall it correctly and returns the correct exit code of 0.
EDIT: I tried
sc stop "Autodesk Access Service Host"

from an elevated command prompt and that shows
STATE              : 3  STOP_PENDING
(NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)

so not really sure how to take STOP_PENDING along with NOT_STOPPABLE, nor why this would say NOT_STOPPABLE when the property above shows true.


text:
Q: javascript screen.width and screen.height not rendering as expected trying to make an element render the full size of the screen:
<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
</head>
<body>
    <canvas></canvas>
    <script>
        (function(){
            var canvas = document.getElementsByTagName("canvas")[0];
            canvas.style.background = "#0f0";
            canvas.style.width = screen.width + "px";
            canvas.style.height = screen.height + "px";

            console.log(
                "screen.width: " + screen.width +
                "\nscreen.height: " + screen.height +
                "\ncanvas.width: " + canvas.style.width +
                "\ncanvas.height: " + canvas.style.height
            );
        })()
    </script>
</body>
</html>

but the canvas element renders with approximately twice the width and twice the height of the screen in chrome v22 but it seems to be fine in FF.
I get console output:
screen.width: 1366
screen.height: 768
canvas.width: 1366px
canvas.height: 768px
if I manually set the width and height of the canvas in chrome I have to use:
canvas.style.width = 780 + "px";
canvas.style.height = 435 + "px";

to get it to the size of the screen in chrome but then checking in FF this renders as expected to be just over half the screen in both dimensions.
update:
I tried this:
<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
</head>
<body style="padding:0;margin:0;">
    <div>
        <canvas>
        </canvas>
    </div>
    <script>
        (function(){
            var div = document.getElementsByTagName("div")[0],
                canvas = document.getElementsByTagName("canvas")[0];

            div.style.background = "#f00";
            div.style.width = screen.width + "px";
            div.style.height = screen.height + "px";

            canvas.style.background = "#0f0";
            canvas.style.width = "100%";
            canvas.style.height = "100%";

            console.log(
                "screen.width: " + screen.width +
                "\nscreen.height: " + screen.height +
                "\ncanvas.width: " + canvas.style.width +
                "\ncanvas.height: " + canvas.style.height
            );
        })()
    </script>
</body>
</html>

but it has the same effect, works in FF but not in chrome.
I did this before on my test site www.0xor1.com but I used jQuery css({width:screen.width, height:screen.height}) to set it which is why it works but I don't understand why this way doesn't work in chrome.

A: Width and height of canvas element should be marked like:
<canvas id="myCanvas" width="200" height="200">

Css styles messes it up

A: Try to set
canvas.width = screen.width + "px";
canvas.height = screen.height + "px";

without the .style.

A: Maybe your window is much smaller then your screen. You can't cover more then the window, so maybe screen isn't what you want.
if changed it so this, so it covers the whole body
        var canvas = document.getElementsByTagName("canvas")[0];
        var body = document.getElementsByTagName("body")[0];
        canvas.style.background = "#0f0";
        canvas.style.width = body.offsetWidth + "px";
        canvas.style.height = body.offsetHeight + "px";


text:
Q: Handle missing reference to COM interface (MATLAB) nicely I have a VS2013 C# project which references the MATLAB COM interface. 90% of what the app does is in no way related to MATLAB and I would like to be able to compile and run in environments where MATLAB is not available. The desired behavior is:

*

*Build, regardless of presence of the reference (throwing a warning).

*If MATLAB is not available, print a message if the user tries to execute MATLAB specific functionality, but it should not be fatal.

My first instinct was to use a pre-processor directive with different build configurations, but I would like to avoid this because it gets messy when setting up continuous integration and tests etc.
So I tried some reflection:
try
{
  var matlab = Activator.CreateComInstanceFrom("appname.exe", "MLApp.MLApp").Unwrap();
}
catch
{
  //message
}

Which throws a MissingMethodException (i.e. it cannot find a constructor).  When MATLAB is present this works fine:
     var matlab = new MLApp.MLApp();

New ideas most welcome, thanks in advance!
Edit:
See below for a detailed answer, but for those looking for a quick bit of test code, here is what worked for me.
        var Matlab_t = Type.GetTypeFromProgID("Matlab.Autoserver");

        if (Matlab_t != null)
            matlab = Activator.CreateInstance(Matlab_t);
        else
            MessageBox.Show("Matlab installation not found.\n");

A: In my COM related Unit Tests / Detectors I simply do it in multiple steps:

*

*Find COM type

*Create COM object from type

*Call methods.

*Release COM objects, all of them.

In your case I would suggest writing mapper class hiding all of this COM ugliness under layer of abstraction. (I just needed those helpers to test COM library I wrote, so it was opposite)
Type.GetTypeFromProgID throws no exceptions when type is not found, instead it simply returns null.
    public static object GetComObject(string typeName)
    {
        Type ComType;

        ComType = Type.GetTypeFromProgID(typeName);
        if (ComType == null)
        {
            //COM type not found
        }
        // Create an instance of your COM Registered Object.
        return Activator.CreateInstance(ComType);
    }

When object is (or is not) created I follow up with dynamic or hand-written reflections (does same stuff as dynamic but with higher degree of control, and also works in older .NET versions).
    public static object CallFunction(string method, string typeName, params object[] args)
    {
        Type ComType;
        object ComObject;

        ComType = Type.GetTypeFromProgID(typeName);
        if (ComType == null)
        {
            //COM type not found
        }

        // Create an instance of your COM Registered Object.
        ComObject = Activator.CreateInstance(ComType);

        // Call the Method and cast return to whatever it should be.
        return ComType.InvokeMember(method, BindingFlags.InvokeMethod, null, ComObject, args);
    }

After work is finished you should release them, all of them. Including objects returned by (created by) methods in root COM object. (Releasing parent, but not its children causes, aside of memleaks, Unit Test engine to freeze, nasty)
    public static void DisposeCOM(dynamic obj)
    {
        if (obj != null)
        {
            Marshal.ReleaseComObject(obj);
        }
    }


text:
Q: compare column to values from procedure I have a list of values to evaluate. Example provided below
'16-%', '45-%','A1%','125%'

I then have 1 column that is the output of a stored procedure and 4 columns that get returned from aliased left outer joins
example :
Max(db_util.Efn_name_wid(tdl_tran.reason_code_id,
               remit_rmc.remit_code_id, remit_rmc.remit_code_name, 'Reason')
) AS DEN_REASON

, Max(RMC_1.remit_code_name)
       AS REMIT_CD1

,Max(RMC_2.remit_code_name)
       AS REMIT_CD2

,Max(RMC_3.remit_code_name)
       AS REMIT_CD3

,Max(RMC_4.remit_code_name)
       AS REMIT_CD4

The logic I am trying to build is this:
IF DEN_REASON like (any value in the list)
THEN evaluate column remit_cd1 against the same list, if it matches any value in the list, then continue to remit_cd2,remit_cd3, remit_cd4 until it finds the first remit code that doesn't match the value in the list.
Ultimately trying to return one value.

A: I think this CASE statement might be what you need:
SELECT CASE
    WHEN DEN_REASON LIKE (/* your set of values */)
         AND REMIT_CD1 LIKE (/* your set of values */)
         AND REMIT_CD2 LIKE (/* your set of values */)
         AND REMIT_CD3 LIKE (/* your set of values */)
         AND REMIT_CD4 NOT LIKE (/* your set of values */)
         THEN REMIT_CD4
    WHEN DEN_REASON LIKE (/* your set of values */)
         AND REMIT_CD1 LIKE (/* your set of values */)
         AND REMIT_CD2 LIKE (/* your set of values */)
         AND REMIT_CD3 NOT LIKE (/* your set of values */)
         THEN REMIT_CD3
    WHEN DEN_REASON LIKE (/* your set of values */)
         AND REMIT_CD1 LIKE (/* your set of values */)
         AND REMIT_CD2 NOT LIKE (/* your set of values */)
         THEN REMIT_CD2
    WHEN DEN_REASON LIKE (/* your set of values */)
         AND REMIT_CD1 NOT LIKE (/* your set of values */)
         THEN REMIT_CD1
    WHEN DEN_REASON NOT LIKE (/* your set of values */)
         THEN DEN_REASON
    END AS YourSingleResult

FROM --your query
(   SELECT
    Max(db_util.Efn_name_wid(tdl_tran.reason_code_id,
        remit_rmc.remit_code_id, remit_rmc.remit_code_name, 'Reason')
       ) AS DEN_REASON
    ,Max(RMC_1.remit_code_name) AS REMIT_CD1
    ,Max(RMC_2.remit_code_name) AS REMIT_CD2
    ,Max(RMC_3.remit_code_name) AS REMIT_CD3
    ,Max(RMC_4.remit_code_name) AS REMIT_CD4
    -- and the rest of your query, that you omitted from your example above
)

Then again, it might be shorter if you did your LIKE evals in your sub-query. Like this:
SELECT CASE
    WHEN MatchesDenReason = 1
         AND MatchesCD1 = 1
         AND MatchesCD2 = 1
         AND MatchesCD3 = 1
         AND MatchesCD4 = 0
         THEN REMIT_CD4
    WHEN MatchesDenReason = 1
         AND MatchesCD1 = 1
         AND MatchesCD2 = 1
         AND MatchesCD3 = 0
         THEN REMIT_CD3
    WHEN MatchesDenReason = 1
         AND MatchesCD1 = 1
         AND MatchesCD2 = 0
         THEN REMIT_CD2
    WHEN MatchesDenReason = 1
         AND MatchesCD1 = 0
         THEN REMIT_CD1
    WHEN MatchesDenReason = 0
         THEN DEN_REASON
    END AS YourSingleResult

FROM --your query
(   SELECT
    Max(db_util.Efn_name_wid(tdl_tran.reason_code_id,
        remit_rmc.remit_code_id, remit_rmc.remit_code_name, 'Reason')
       ) AS DEN_REASON
    ,CASE WHEN Max(db_util.Efn_name_wid(tdl_tran.reason_code_id,
        remit_rmc.remit_code_id, remit_rmc.remit_code_name, 'Reason')
       ) LIKE (/* your list */)
          THEN 1 ELSE 0 END AS MatchesDenReason
    ,Max(RMC_1.remit_code_name) AS REMIT_CD1
    ,CASE WHEN Max(RMC_1.remit_code_name) LIKE (/* your list */)
          THEN 1 ELSE 0 END AS MatchesCD1
    ,Max(RMC_2.remit_code_name) AS REMIT_CD2
    ,CASE WHEN Max(RMC_2.remit_code_name) LIKE (/* your list */)
          THEN 1 ELSE 0 END AS MatchesCD2
    ,Max(RMC_3.remit_code_name) AS REMIT_CD3
    ,CASE WHEN Max(RMC_3.remit_code_name) LIKE (/* your list */)
          THEN 1 ELSE 0 END AS MatchesCD3
    ,Max(RMC_4.remit_code_name) AS REMIT_CD4
    ,CASE WHEN Max(RMC_4.remit_code_name) LIKE (/* your list */)
          THEN 1 ELSE 0 END AS MatchesCD4
    -- and the rest of your query, that you omitted from your example above
)


text:
Q: filter() function in javasacript doesn't return values equal to 0 I'm trying to filter all the values from an array that are minor than 5, the problem is that the output doesn't contain the number 0, which is contained in the original array, how can I make to filter that value to?
Here's the code:
const numbers = [0,1,2,3,4,5,6,7,8,9,0];
const minor = (element) => {
  if(element < 5 || element === 0){
    return element;
  }
}
const minorVal = numbers.filter(minor);
console.log(...minorVal)

And this is what is printed in the console:
1
2
3
4

A: when you return element 0 filter function considers it false and does not return anything.
Try this
const minor = (element) => {
  if(element < 5 || element === 0){
    return true;
  }
}


text:
Q: Azure FunctionApp timers quit firing I have a few Functions within an Azure FunctionApp. All of the functions are set to trigger every 5 minutes, and have been working fine for the past 9 months. About 2 weeks ago they stopped firing. There has been 1 or 2 instances of each Function that have executed since then.
I can manually execute the function with inconsistent success. Sometimes it will execute, sometimes it won't. I am basing this execution rate on the data in the Monitoring tab. The function app is using the Consumption service plan.
I have not been able to find any errors in the logs or anything else of value. What can I do to troubleshoot this issue?

Thanks,
Phil