text:
Q: Structuring an OU to properly model an Organizational Hierarchy I'm experimenting with using OUs in my network's Active Directory and group policy.  However, I'm having a little trouble figuring out the right way to structure my OUs so that I can have individual departments, but also have a higher level management users gain all rights of the departments lower on the organization's hierarchy.
Let's say I have 4 organizational units

*

*Sales

*Marketing

*Accounting

*Executive

Each department has their own drive mapping, which I set up through individual group policies within the department OUs.  However, the one exception to this structure is the Executive department.  These are the leaders of the company, so I would like users in this OU to get access to ALL of the drive mappings, not just a single drive.  However, since an OU can only have one parent, I don't know how I could set this up so that the Executive OU can inherit the drive mapping policies from all departments.
One thought would be have individual policies for each drive mapping, and then simply link the drive mapping policies to each department I wanted to have access.  In this case, the Executive OU would have 4 links, one for each drive mapping.  While this makes sense to a certain extent, it doesn't sound like the most maintainable solution.  Everytime a department was added, or if additional policies were granted to an existing department, I would need to duplicate this link in the Executive OU as well.
The other thought I had would be to simply use Security Groups as the objects in each OU, and assign departmental users to the security group instead of the OU (e.g DOMAIN\Marketing).  However, this does not appear to work the way I expect.  Group policies only seem to be applied to a user once they have been added to the appropriate OU, and it does not matter what Security Group they are in.
The only other solution I can think of is to simply move the department policies out of OUs and instead rely on Security Filtering to apply the policies to different Groups.  However, this does not seem to be the way that most examples and tutorials handle managing their policy objects, instead favoring these departmental OUs like I've listed above.
What is the proper way for me to structure my Group Policy objects to accomplish what I am after?

A: The proper way of handling this is using a single group policy for drive maps across your organization, with the usage of Group Policy Preferences.
You can then set up targeting rules on each drive map according to your own security scheme. I'd probably avoid using OU's as the targeting rule, since you would need security groups no matter what.


text:
Q: What is the easiest way to save an ArrayList in Android? I'm building an app that has a favourites list, but when I exit the app, the favourites list is reset to nothing because the list is not being saved (since lists can't be saved in SharedPrefs). How can I save an ArrayList OR String[] in Android? If you recommend Serialization or a Local Database, could you please explain what these are and mean? I've heard the terms and followed tutorials but do not understand.
Maybe another approach to the same question is how would you normally build a favourites list?

A: There's a question that explains it in a very nice way:
Save ArrayList to SharedPreferences
From its answer (I've already tested it), after API 11 you can do something like this:
//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);

//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();

I summarized his answer, but you should check the complete answer. It's really helpful!

A: Option1: easiest. Iterate over arraylist and save each element into sharedPreferences
option2: convert arraylist into a string. Then save into shared pref.
option3: save your data into a database. Google how to use sqllite with android

A: You can use Sugar ORM library for Android. It will create for you the database you need by simply making the object class of your ArrayList to extend SugarRecord.
For example, if your List type is ArrayList you have to make your Books class extend SugarRecord, and then in your Activity iterate in a loop through the items and set item.save() and it is saved to the database.
I have a sample project here.
If you have any question send me a PM.
Hope it helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loading my Greasemonkey script after another GM Script Loads I have two greasemonkey scripts loading on a particular url.  How do I make sure my second GM script doesn't load until the first GM script completes building it's page elements.  Also how do I control the order in which the GM scripts load/run?

A: Select you script Name in GreaseMonkey "Manage User Scripts" UI, and hold down the Alt key and press Down key until it goes last.
There is a hint message in that UI actually

Drag-and-Drop with the mouse or press
  Alt-Up/Alt-Down to reorder scripts in
  this list

A: S.Mark described how to manage the order of execution in the Greasemonkey script management interface, which is part of it. But it can't be guaranteed that Script 1 will finish effecting all its operations on the DOM before Script 2 begins.
If Script 2 is dependent on the actions of Script 1, that has to be handled.
One approach: Have Script 2 check the DOM for some state changed by Script 1 (which signals Script 1 effects have completed). In Script 2 stay in a recursive loop with window.setTimeout() and routinely check for the signalling state, then break out and begin the main work of Script 2 once the condition has been met.
Another approach altogether: combine the two scripts into one, and order the blocks of code appropriately.


text:
Q: ui:repeat - adding / removing elements from list does not work properly I have following code in my  .xhtml file
<h:form id="registration3Form">
<h:panelGroup id="terms_outer_panel">
   <h:commandLink styleClass="item-7"
                    action="#{registerBusinessWizardController.addCourse}"
                    value="#{msgBundle['registerThirdPage.panel.addSchedule']}">
   </h:commandLink>
   <ui:repeat value="#{registerBusinessWizardController.courses}" var="course">
                    <h:panelGroup id="terms_inner_panel">

                            <h:inputText id="price" styleClass="item-2" value="#{course.price}" />

                            <h:inputText  id="dateFrom" styleClass="date" value="#{course.date}" >
                                <f:convertDateTime  pattern="yy-MM-dd" type="date" dateStyle="long"/>
                            </h:inputText>

                            <h:inputTextarea value="#{course.additionalInfo}"/>

                                <h:commandLink
                                    value="#{msgBundle['registerThirdPage.panel.deleteSchedule']}"
                                    actionListener="#{registerBusinessWizardController.removeCourse}">
                                    <f:ajax render=":registration3Form:terms_outer_panel" execute="terms_inner_panel"/>
                                </h:commandLink>

                    </h:panelGroup>
        </ui:repeat>
    //some other stuff
</h:panelGroup>
</h:form>

And when page is rendered. And user clicks addSchedule link I expect that ui repeat will add new  div class="term"
with empty values bind to inputs, because:
public void addCourse(){
    Course course = new Course();
    courses.add(course);
}

I am adding new Course object with null price additionalInfo and date to the list used by ui:repeat.
Instead I get new

part with values copied from previous entry.
When I remove element from list (In managedBean proper object from list is removed) I see data from object which was just removed :/
Did someone encounter this kind of problem?
Do you have any advice?

A: This seems to be another <ui:repeat> bug. Mojarra's <ui:repeat> has (had) too many problems. First step is to exclude the component from being suspect by replacing it by a fullworthy UIData component, such as <h:dataTable>. If it works, then it's most definitely a bug in <ui:repeat>, otherwise it's just a bug in your own code (based on the code given as far I don't see any, I however assume that your bean is @ViewScoped).
If it's indeed caused by <ui:repeat> itself, then the first step is usually to upgrade to latest Mojarra version. This is currently 2.0.6 for Servlet 2.5 containers and 2.1.4 for Servlet 3.0 containers. If that doesn't solve the problem, then you should look at replacing Mojarra by MyFaces which has a different and better <ui:repeat> implementation. If that isn't an option for some reason, then you should consider looking at a 3rd party component library which has an UIData based component which doesn't render any markup, such as Tomahawk's <t:dataList>.


text:
Q: Blowfish CBC encryption not decrypting I have difficulties decrypting a blowfish encrypted string in a .net environment, that was encrypted by the mcrypt php library.
Here is the script I use to encrypt some data
<?php

function encrypt_blowfish($data, $key) {
    $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $crypttext = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC,    $iv);
    echo 'IV:   ' . bin2hex($iv) . "\n";
    echo 'DATA: ' . bin2hex($crypttext) ."\n" ;
}

$secretKey = 'somekey';
$data = 'Hello World this is an encryptiontest!';

encrypt_blowfish($data, $secretKey);

I decided to use the bouncingcastle library since it seemed to be the default choice for encryption and they had a PCL version (which I need). For testing purpose I just copy/pasted the echo'd values into my C# code.
var ivString = "34c33fed0386dda1";
var iv = Hex.Decode (ivString);

var dataString = "ced4ed218d7a1fd228f8c43ca6b83f097648811661d5510678a26953729ceccdf6d78a7695cbfe43";
var data = Hex.Decode (dataString);

var keyString = "somekey";
var key = System.Text.Encoding.UTF8.GetBytes (keyString);

var engine = new BlowfishEngine();
var cipher =new PaddedBufferedBlockCipher(new CbcBlockCipher(engine));

var keyParam = new KeyParameter(key);
cipher.Init (false, keyParam);

var outBytes = new byte[data.Length];
var len = cipher.ProcessBytes (data, 0, data.Length, outBytes, 0);

cipher.DoFinal(outBytes, len);

Console.WriteLine(System.Text.Encoding.UTF8.GetString(outBytes));

When I run this code DoFinal explodes with a "Corrupt padding block" exception. So I read about pcks7 padding which essentially fills the bytes of the original string. I calculated that for my input string and the blowfish cbc algorithm block size of 8, I would need two bytes of padding so I added "22" at the end of the string. This however yielded the same result.
Also, I don't see any point where I can insert the IV into the blowfish decryption. It feels like I am completely lacking/not understanding a vital point here. Any1 any ideas on what goes wrong here? Also if possible I would like to skip on the padding part in my php and simply decrypt with iv/passphrase in c#, is that even possible?
Cheers and thanks
Tom

A: I ended up using a simpler library which supperts cbc mode in a very simple fashion.
http://jaryl-lan.blogspot.de/2014/07/openfire-blowfish-encryptiondecryption.html

A: @Tom, your decryption problem was probably due to the '\0' padding that the PHP mcrypt library uses when it needs to make a block of text congruent to its fixed block length (64 bits, or 8 bytes). I hear .Net uses something different? Moreover, does mcrypt_create_iv() produce a  binary data? Out of curisoity, why would you use bin2hex() on the IV.
The way to send the IV with with the cipher text is simply $cipherText = $iv . $cipherText. Then, they say, you can use substr() (possibly, mb_substr()) to recover the IV and the true cipher text from the composite. Use the recovered IV and your key to decrypt the cipher text.
The last step is to remove any padding that may have been added to the plain text by mcrypt.
I created a Blowfish diagnostic page here. I am on PHP 5.6.20, and I cannot get mcrypt to decrypt my data because I have a strange IV problem. The same technique I described to you does not seem to work. I posted the text of the diagnostic script on this question:
Blowfish IV Recovery Problem
Here is a working on-line version on my domain:
Blowfish Diganositc Webpage
I guess it is a good thing you tried something else. Ecryption with Blowfish seems to work fine, but even when using native PHP, there appears to be an issue with the decryption process. But, it could just be me! ;-)


text:
Q: $f^{(2k)}(a)=0$. Does the Taylor series converge? If $f^{(2k)}(a)=0$ for all $k \in [0, \infty), k \in \mathbb{N}$. Then does the Taylor Series for f centered at $x=a$ converge for any value of x?
I picked an example where $f(x)=x, a=0$. Then Even-Power derivatives will always be 0. However, this function does not converge for all values of x. Does this constitute as a proper counterexample to the statement above?


text:
Q: Entity Framework Code First - Table Per Hierarchy - should the Discriminator field be indexed? Quite simply, when using Code First and creating a table per hierarchy table my gut feeling is that the Discriminator field should be indexed as it'll be used to filter the data with pretty much every query.
Why doesn't EF add an Index to the Discriminator field?

A: Not always. You can find some people talking about this here: https://github.com/aspnet/EntityFramework/issues/4030.
Now, if you judge that will be better to create an index, you can use the convention delivery in the nuget Package EntityFramework.DiscriminatorIndex as described here: https://bytenosso.blogspot.com.br/2016/10/entity-framework-discriminator-index.html

A: i dont know i got your question right or not but its the default behaviour of ef. In the TPH mapping scenario,all types in an inheritance hierarchy are mapped to a single table.  A discriminator column is used to identify the type of each row. When creating your model with Code First, TPH is the default strategy for the types that participate in the inheritance hierarchy.
and you modify this behaviour using Fluent Api
modelBuilder.Entity<Course>()
.Map<Course>(m => m.Requires("Type").HasValue("Course"))
.Map<OnsiteCourse>(m => m.Requires("Type").HasValue("OnsiteCourse"));


text:
Q: Another word for "understated sexuality"? I am trying to find a proper word for describing a visual concept.
At the moment the closest description is "understated sexuality", but maybe there is another word to describe a woman that is beautiful, attractive, sexy, confident and at the same time modest?
"Majestic or glorious" (Eilia 2015) "are too lavish, I need something different." (maxlaks 2015)

A: You can't throw a bunch of adjectives together and expect English to cough up some magic word. It might happen, but then again, it might not.
If you want to focus on her beauty, use

beautiful, attractive, appealing, charming

If you want to focus on her appearance, you could try

classy, elegant, sophisticated... or even resplendent (depending on the case)

For confidence, try

poised, self-assured

Modesty, in some senses, goes against confidence, but you can use

self-effacing, unpretentious

For understated sexuality in particular, I'm partial to
elegant

(of people or their behaviour) attractive and showing a good sense of style

or, in extreme cases
sensuous

Attractive or gratifying physically, especially sexually:

[Oxford]

PS - In my humble opinion as a reader, I like writers to describe girls with as many specific adjectives as possible, rather than be too laconic about it. Even your description in the post would mean more to a girl than any single word could.

A: I like chic:

adjective (chicer, chicest)
Elegantly and stylishly fashionable:

The connotation of stylish welcomes a deeper appreciation than most people offer to the elegant woman the OP describes:

1856, as a noun, "style, artistic skill,"
  from French chic, 19c. in
  "stylishness" sense, originally "subtlety" (16c.), which is of unknown
  origin, perhaps [Klein] related to German Schick "tact, skill,"
  from
  Middle Low German schikken "arrange appropriately," or
  Middle High
  German schicken "to arrange, set in order;"...
Etymonline.com

A: Winsome is a good old English word for that:
adjective
1.
sweetly or innocently charming; winning; engaging:
a winsome smile.
an elegant demure and a winsome smile describes many a lass in English books.

A: How about winsome:

adj.
Attractive or appealing in a fresh, innocent way

A: Someone fitting exactly that description (yeah, she's currently reading over my shoulder) seems to find a way to fascinate me every day, so it might just be that all those qualities add up to make her "fascinating."

A: I'd say the person has a wholesome beauty.

A: Ravishing
1.) Extremely beautiful or attractive; enchanting; entrancing.


text:
Q: Is there a more efficient way to remove localization from a NIB or Storyboard? I've picked up an iOS project that was previously localized for 20 languages, but not yet translated. While reviewing before submitting for translation, I discovered that most of the NIBs and storyboards that are localized have generated strings for a lot of placeholder text that is not used runtime. Since many of the files are only placeholder text strings, the localization just needs to be removed. I'm aware that this can be done by removing the individual language localizations, deleting the reference to the file in the project, moving the file up a directory from Base.lproj, and re-adding it. However, since there are 20 languages and 40+ resource files, removing the localization in this manner is relatively tedious and time-consuming.
Obviously I can just fix it as mentioned above, but I would love to avoid the tedium in the future. Does anyone know of a better way to un-localize a resource file? If not in Xcode, a command line solution would be equally appreciated; anything that doesn't require thousands of repetitive mouse clicks.


text:
Q: Run program as root without using sudo Can someone help me to run a ".run" on Ubuntu 12.04 LTS.
My problem is I want to execute this program as super-user, but I don't want to use sudo to run it.
I just want to run with "./NvidiaTvOut.run", but the system says: "Operation not permitted".
It can appear easy, but I have searched a lot and I don't know what to do.
Best regards,

A: Yes it is possible. However, the error "operation not permitted" is indicative of the file itself not having executable privileges.
It appears you are already in the directory with the file, if not cd into the directory first and then run the following before you try to run the file again.
sudo chmod +x NvidiaTvOut.run

You may now use
./NvidiaTvOut.run

to execute the file.
If you need root privileges, You will see "permission denied" instead of "operation not permitted".
The output of ls -l will show the file permissions for the files in the current directory and an x at the end of the permissions indicates the file is executable.
Please post any errors.

A: I think that NvidiaTvOut.run file have not execution permission.
You can change it's permission as it's executable.
$ sudo chown $USER ./NvidiaTvOut.run

$ chmod +x ./NvidiaTvOut.run

$ ./NvidiaTvOut.run

or
$ sudo chmod 755 NvidiaTvOut.run

$ ./NvidiaTvOut.run

or
$ sudo chmod +x NvidiaTvOut.run

$ ./NvidiaTvOut.run

or If it is a shell script file, as following.
$ sh NvidiaTvOut.run


text:
Q: python- why the list doesn't modified? >>> c=[1,100,3]
>>>def nullity (lst):
   lst=[]
>>>nullity (c)
>>>c
[1,100,3]

Why c doesn't return []? Isn't nullity(c) mean c=lst so thy both point now at []?

A: Python has pass-by-value semantics, meaning that when you pass a parameter to a function, it receives a copy to the object's reference, but not the object itself. So, if you reassign a function parameter to something else (as you did), the assignment is local to the function, the original object "outside" the function remains unchanged. A completely different situation happens if you change something inside the object:
def test(a):
    a[0] = 0

lst = [1, 2, 3]
test(lst)
lst
=> [0, 2, 3]

In the above snippet the list's elements were changed, that's because both lst and a are pointing to the exact same object. Now back to the original question - notice that in Python 3.2 and below there isn't a clear() method (it was added in Python 3.3), here is a related discussion. But you can do this for the same effect, and it'll work in Python 2.x and 3.x:
def nullity(lst):
    del lst[:]

A: You're reassigning local variable lst to a new empty list. To empty an existing list, you need to delete all its members:
del lst[:]

A: Python does not allow you to replace parameters. You are only changing what "lst" refers to within the function, but it does not affect the calling code.
Instead change the list itself by clearing it:
def nullity (lst):
    lst.clear()  # With Python >= 3.3

A: Lets use the id() function
In [14]: c=[1,2,3]

In [15]: def nullity (lst):
    ...:     print id(lst)
    ...:     lst=[]
    ...:     print id(lst)
    ...:

In [16]: id(c)
Out[16]: 33590520

In [17]: nullity(c)
33590520
33591024

When doing the reassignment a new local object is created which is not the same as the one used when calling the function.


text:
Q: RegEx for Spanish alphabets in ColdFusion 8 I know that I can use [a-z] to check for any alphabets from a to z in CF 8.  However, are there any regex to detect spanish alphabets like á, í, ó, é, ñ, etc.?
Thanks in advance,
Monte

A: ColdFusion doesn't nicely deal with Unicode regex.
You can use things like #Chr(375)# to get the characters into a regex string, but it's a bit messy having to do that.
However, Java does work with Unicode, and since CF can utilise Java easily, you can use Java regexes to do unicode matching.

This will match a single Unicode letter in Java regex:
\p{L}

With more details on regex Unicode here: http://www.regular-expressions.info/unicode.html

And as for using Java regex in CF, well simple replacing is just this:
<cfset NewString = OldString.replaceAll('\p{L}','ReplaceWith') />

So if all you need is to replace strings, you can do that.
However, if you want matching (equivalent to rematch), or more complex functionality, then simplest solution is to use a component that wraps the Java regex functionality into a easy to use CFC with regular CFML functions you can call. Like jre-utils.cfc
This allows you to do:
<cfset jre = createObject('component','jre-utils').init() />

<cfset Matches = jre.match( '\p{L}++' , String ) />

Which will return an array of the (Unicode) words in the string.

A: There was recently a discussion here about international RegExes which I cannot find right now. I believe the current situation is that regular expressions are commonly possible with only default latin alphabet.

A: Try if the special "word character class" \w works for you. Caution: This will also match numbers. Perhaps you could clarify with an example what you want to accomplish exactly?
\w should match a, ä or á (but also 0).
\w(?<!\d) will match a, ä or á (but not 0).
\w+ will match börk but also l33t.
\b(?:\w(?<!\d))+\b will match börk but not l33t.


text:
Q: how i can measure width of text entity in Eyeshot Vb.net? I want to measure text width in Vb.net. Just like i have a text entity, i can get or set the text height but unable to get the text width.Just like the text in the code, i want its width , i have set its height to be 0.25 in the constructor.
Dim a As Text
a.TextString = "Ahmad"
a.Height = 0.25
a.Plane = Plane.ZX
a.InsertionPoint = New Point3D(xMinGlobal - 2.5, 0, 1.5)

A: You can check the BoxSize property of the entity.
If it's Nothing, try calling the Regen() method or adding the text entity to the scene.


text:
Q: Massive ropes and tension Consider the diagram bellow, a massive string hanging in equilibrium

My question is this: Can we take any 2 random point on the rope, say A and B and then use $\sum F=0$ on the rope between them: i.e. say that $$T_0 \sin(\theta)+ T_0 \sin(\theta)=mg.$$ Where $\theta$ is the angle the two forces $T_0$ make with the horizontal and m is the total mass of the rope between these two points.
If this is the case would is work with the points in green so that in resolving horizontally would get us say $$T_1 \cos(\theta_1) = T_2 \cos(\theta_2)$$ where $\theta_1$ and $\theta_2$ are the angles they make with the horizontal.
If you need any more information please just ask, thanks.

A: You can only do the balance of forces between spatially separate points only if you know the slope of the rope at each point, and the weight of the rope between the points only.
To get there you use a small section to derive the differential equations and then integrate over the range of $x$ values you want.
Given a small section of rope spanning the horizontal distance ${\rm d}x$ then the tangential distance is ${\rm d}s = \sqrt{ {\rm d}x^2 + {\rm d}y^2 }$ which leads to the expression ${\rm d} s = \sqrt{1+y'^2}\, {\rm d}x$ where $y'=\tan \theta$ is the slope.
The total weight of the rope in this section is thus ${\rm d}w = \mu g\, {\rm d} s$ where $\mu$ is the linear density of the rope $\mu = \rho A = \frac{m}{\ell}$ with $\rho$ mass density, $A$ the cross sectional area, $m$ the total hanging mass and $\ell$ the total hanging length.
At each point if we split the tangential tension $T$ into horizontal part $H$ and vertical part $V$ such that $\tan \theta = \frac{V}{H}$ and $T=\sqrt{H^2+V^2}$
This leads to the following equations
$$ \begin{align} \frac{{\rm d}H}{{\rm d}x} &= 0 \\ H \frac{{\rm d}^2 y}{{\rm d}x^2} &= \mu g \frac{{\rm d}s}{{\rm d}x} = \mu g \sqrt{1+\left(\frac{{\rm d}y}{{\rm d}x}\right)^2} \end{align} $$
In the end you get an equation for the shape of the rope $y(x)$ called a catenary. To get the balance of forces between points (1) and (2) above you have
$$ \begin{align} -T_1 \cos \theta_1 + T_2 \cos \theta_2 &= 0 \\
-T_1 \sin \theta_1 + T_2 \sin \theta_2 &= \mu g \int_{x_1}^{x_2} \sqrt{1+\left(\frac{{\rm d}y}{{\rm d}x}\right)^2} {\rm d}x \\
\tan \theta_1 &= \frac{{\rm d}y}{{\rm d}x} \vert_{x=x_1} \\
\tan \theta_2 &= \frac{{\rm d}y}{{\rm d}x} \vert_{x=x_2} \\
T_1 &= H \sqrt{1+\left(\frac{{\rm d}y}{{\rm d}x}\right)^2} \vert{x=x_1} \\
T_2 &= H \sqrt{1+\left(\frac{{\rm d}y}{{\rm d}x}\right)^2} \vert{x=x_2}
\end{align}$$
PS. I know all this works because I used the above to create a catenary solver:


text:
Q: Devise after sign up path with an additional reddirect After user registration, user lands on after_sign_up_path_for(resource) in RegistrationsController.
This path leads user to screen that needs to be shown. If invited in a group, the user will after registration land on a group, if user is invited in community it will land on the community, etc.
The redirect path is built via the store_location_for method.
My question is, how can I make an additional redirect before that?
My goal is to have a Wellcome screen and then at the button continue to redirect to lading screen that can be group or community.

A: All you need to do is override after_signup_path_for method:
def store_location_for
  session[:location] = ...your location
end

def after_signup_path_for(resource_or_scope)
  session[:location].present? ? redirect_to session[:location] : super
end


text:
Q: Error while running allure command line generate command I just got my allure framework done .. but while generating HTML report with command line I get following error
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlElement at com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector.<init>(JaxbAnnotationIntrospector.java:139) at com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector.<init>(JaxbAnnotationIntrospector.java:126) at io.qameta.allure.context.JacksonContext.<init>(JacksonContext.java:24) at io.qameta.allure.ConfigurationBuilder.useDefault(ConfigurationBuilder.java:50) at io.qameta.allure.Commands.createReportConfiguration(Commands.java:158) at io.qameta.allure.Commands.generate(Commands.java:63) at io.qameta.allure.CommandLine.run(CommandLine.java:129) at java.base/java.util.Optional.orElseGet(Optional.java:348) at io.qameta.allure.CommandLine.main(CommandLine.java:72) Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlElement at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:533) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:186) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:476) ... 9 more

Command i used -
allure generate --report-dir directory-with-results --clean
java --version
java 9-ea
Java(TM) SE Runtime Environment (build 9-ea+162)
Java HotSpot(TM) 64-Bit Server VM (build 9-ea+162, mixed mode)
allure --version
2.0.0
rspec -v
RSpec 3.6

A: There's no need to downgrade java, there's an easier solution, at least on Linux.
So in my case I have java 8 and java 9. By default java 9 is used.
If allure requires java 8, I just run it like that:
$ JAVA_HOME=/usr/lib/jvm/java-8-oracle allure generate

This temporarily switches the java version from 9 to 8 just for this command.

A: So there is no solution as such but as per @Nicolai I downgraded to JAVA 8 and it has fixed the issue.
On how I downgraded follow these simple steps mentioned here

A: there are very simple way to genrated reports via allure.
first install allure.
allure-pytest 2.6.0
allure-python-commons 2.6.0
then if you unable to genrated the reports then follow below steps..
step -1 (using pytest)
pytest test_parameterDemo.py --alluredir=path where you want to save reports.
step -2
allure serve report_path
if still it is showing allure is not command (blah -blah)
then install allure using npm plugin with below command
npm install -g allure-commandline --save-dev
then again follow step-2 then one server will start and you can able to see allure reports.


text:
Q: Is the analytification functor part of a geometric morphism of topoi? Let $Sh(\mathsf{\mathbb{C}-fAlg}^{op})$ be the topos of zariski sheaves on finitely genertaed $\mathbb{C}$-algebras.
A complex analytic space for our purpose is a locally ringed space locally isomorphic to an analytic subset of $\mathbb{C}^{n}$ (with the sheaf of holomorphic functions). Denote the category of these by $\mathsf{An}$ (for analytic). There's a grothendiek topology on the category given by jointly sujective open immersions (where open immersion are topological embeddings with locally isomorphic structure sheaves). Let $Sh(An)$ be the topos of analytic sheaves on analytic spaces. We have an affine analytification functor:
$$f: \mathsf{\mathbb{C}-fAlg}^{op} \to \mathsf{An}$$
Which associates to an affine $\mathbb{C}$ scheme the corresponding analytic subspace of $\mathbb{C}^n$. This morphism induces a pushforward for presheaves:
$$f_*: Psh(\mathsf{An}) \to Psh(\mathsf{\mathbb{C}-fAlg}^{op})$$
I'm afraid to say anything about sheaves at this point since I'm not so comfortable with toposes yet really. What I'd like to be able say is the following:

(Extremely conjectural!) The pushforward $f_*$ extends to a morphism of topoi:
$$F_*: Sh(\mathsf{An}) \to Sh(\mathsf{\mathbb{C}-fAlg}^{op})$$
This morphism is geometric with left adjoint the analytification
  functor:
$$F^*:  Sh(\mathsf{\mathbb{C}-fAlg}^{op}) \to Sh(\mathsf{An})$$
In partuicular this functor sends schemes in
  $Sh(\mathsf{\mathbb{C}-fAlg}^{op})$ to analytic spaces.

Is there a way to make this precise?
I'm trying to see the analytification functor come out of general nonsense because it seems like the existence of it should be natural.
I'm obviously not talking about any powerful statements about properties of this functor like GAGA etc. I'm only looking for a natural way to define this functor.

A: I am not very familiar with the analytic side of the pictures or with the analytification functor but here is what I can claim, it seems from your comment that this answer your question:
If you have two subcanonical site $C$ and $D$ (it means that representable presheaves are sheaves, so it is the case with your example).
If $C$ has all finite limits.
If you have a functor $f :C \rightarrow D$ that preserves finite limits and send covering family in $C$ to covering family in $D$ then:
the precompostion with $f : Prsh(D) \rightarrow Prsh(C)$ send sheaves over $D$ to sheaves over $C$ and the restriction of this functor to sheaves defines the $f_*$ part of a geometric morphism:
$f_*: sh(D) \rightarrow sh(C)$
Moreover (easy to check from the universal property) $f^*$ send representable sheaves in $sh(C)$ to representable sheaves in $sh(D)$ in a way that extend $f: C \rightarrow D$.
You have more general claim of this sort on the nLab page morphism of sites
Or in more standard litterature, have a look to MacLane&Moerdijk "sheaves in geometry and logic" chapter VII, more specifically setion 9 and 10.


text:
Q: Fitting data to a differential system I have a three equation ODE system. I have two parameters $\beta$ and $\gamma$ for which I try to find numerical values such that the model fits the data.
Here is the code I use
pop = 65800000;
sol = ParametricNDSolveValue[{s'[t] == -β x[t] s[t] , s[0] == pop, x'[t] == β x[t] s[t] -γ  x[t], x[0] == 1, r'[t] == γ  x[t], r[0] == 0}, {s, x, r}, {t, 0, 61}, {β, γ}];

The data I have
infe = {7, 7, 6, 4, 4, 4, 4, 1, 1, 0, 2, 5, 25, 44, 86, 116, 176, 196,269, 404, 632, 921, 1178, 1370, 1739, 2221, 2803, 3570, 4396, 5284, 6473, 6953, 8268, 9328, 10575, 12310, 13144, 16796, 17923, 20002, 22511, 25269, 29561, 30366, 33599, 39161, 42022, 41290, 61650, 66955, 68578, 71849, 79404, 80827, 82333, 86740, 89431, 91012, 94094, 98769, 99741};

reco = {4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 602, 1290, 1590, 1590, 2200, 2200, 3280, 3900, 4950, 5700, 5700, 7200, 7930, 9440, 10900, 12400, 14000, 15400, 16200, 17300, 19300, 21300, 23200, 24900, 26400, 27200, 27700, 28800, 31000};

popu = {pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop, pop};

(I know the last one seems creepy.)
susce = popu - Total[{infe, reco}];
data1 = {susce, infe, reco};

and
ω = 61;
transformedData1 = {ConstantArray[Range[3], ω] // Transpose, ConstantArray[Range[ω], 3], data1}~Flatten~{{2, 3}, {1}};

I write
model[β_, γ_][i_, t_] := Through[sol[β, γ][t], List][[i]] /; And @@ NumericQ /@ {β, γ, i, t}

and
fit = NonlinearModelFit[transformedData1, model[β, γ][i, t], {β, γ}, {i, t}]

This yields
FittedModel[model[-2.85412.x 10^6,0.0196833]]

Since it is the well known SIR model, the parameter $\beta$ should be positive but I do not know why it gives a negative number.
How can I fit the data to the ODE system and check if the differential system fits the data?


text:
Q: Exposing C# enums as views in database Say if I have a column in database which can accept any one value of the enum that is defined in my C# code.
There is a usual way to make it be available to the database to store it in a database table and refer it from there.
But sometimes you don't want to store the enum in the database but just want to maintain it in the code, for these cases I have come up with the solution in my project to have a view which will return the values of enums so that we do not have to hard code it in the database, so having something like this in the database
CREATE VIEW ENUM.ValidationFailReasonTypes
AS
SELECT 1 AS [FormLevel], 2 AS [GridLevel]

For enum
public enum ValidationFailReasonTypes
{
    FormLevel = 1,
    GridLevel = 2
}

So just wanted to ask is it a good idea to do like this or is there some better way to handle this case when we don't want to store enum in the database?

A: It all depends.
Old school database folk like me want you to build validity checks into your data model. See this question for how you would do that. You end up with a nice, self-documenting schema, which guarantees that your application can only contain valid entries for ValidationFailReasonTypes.
An alternative view is that the database is just the storage mechanism, and it's perfectly OK for the application to be the guarantor of data validity, especially if it has lots of unit tests. In this case, you use an ENUM in you C#, write unit tests to validate that the entries match your expectations, and accept the fact your database table has an integer column which could contain lots of values, but the application limits it to (1, 2).
I think it's important to pick one approach and stick to it. Your solution - if I understand it correctly - is a bit of both.
In general, I'd use an enum for values that are not going to change without a new release of your application, usually because you're enabling some new functionality.
I'd expect to use a database entry for something that can change in the business domain independently of your application's release. "Grid level" and "form level" feel like features in your application, so I think an enum is okay.

A: The entire reason for an enum is consistency, clarity, and ease of use when coding. I would think you would want that sort of clarity and consistency on the database side as well. If you persist an enum value to the database, you absolutely should have referential integrity on the column and a corresponding definition table. The view saves you nothing in my opinion.
Create a table and add referential integrity to the field even if it only has two rows for all eternity.


text: Q: Can KVMs for 3 monitors & USB keyboard/mouse be used in a mixed Mac/PC environment? Is it possible to use three Thunderbolt displays on multiple computers (mixed environment of PCs and Macs)?  I've used KVMs in other PC-only environments, but I am trying to find out if both PCs and Macs can use three Thunderbolt displays at once, with the ability to switch between the machines.


text:
Q: Is there any case that the atomicity of std::atomic is not guaranteed, when is_lock_free() == false? Even if is_lock_free() == false , typically maybe, the atomicity of std::atomic can be  guaranteed. Is that right?
I wander that there are computer environments or cases where the atomicity is not guaranteed, when is_lock_free() == false.

A: Non-lock-free atomics aren't address-free, so shared memory between two processes would mean they don't respect each other's lock.  (Same for two virtual mappings of a page holding the same atomic object in the same process, unless the hash table of locks is only indexed on the low bits of the address, the offset-within-page, but that would probably be a bad design.)
ISO C++ doesn't define memory-mapping functions or processes, so the standard itself doesn't go into much detail other than saying lock-free atomics should be address-free (which makes them work in shared memory).  That is the case on real-world implementations.
Otherwise it's always atomic.  The usual implementation mechanism is simple: use the address to index a table of spinlocks or mutexes.
Of course, this assumes a program free of undefined behaviour, but so does everything else in C++.  Any UB anywhere during the execution of a C++ program means all guarantees of anything before or after that point are out the window.
In practice there aren't a lot of ways you could break atomicity of a non-lock-free std::atomic, other than really obvious stuff like using memcpy or a plain-uint64_t* to access the object representation, instead of going through the std::atomic<uint64_t> class.
Lock-free std::atomic is actually easier to break with UB, e.g. by dereferencing an atomic<T>* that's not aligned to alignof(std::atomic<T>).  On many ISAs that support unaligned loads/stores, that will run but not actually be atomic, because the C++ implementation was relying on hardware guarantees for atomicity of aligned loads and stores.


text:
Q: How can I get a list from state and modify it in qore? I am using the ServiceApi::saveStateData({"my-key": some_list}); method to save a list to my qorus IE state.
What I wanted to ask is how can I get the list from the state and add/remove elements from the list and put it back in the state?
Also I want to know how can I join lists? Like for example I want to join two lists under some_list and put it under state?
Thanks a bunch for the help in advance,
Cristi

A: Lists are always passed by reference, and even though there is a "pseudo-class" for lists (as with other basic types in Qore), all the methods are read-only.
To make changes to a list, use the +=, +, push, splice, extract operator, unshift, and pop operators.
Q: How can I add/remove elements from the list?
Option 1: Use the extract operator to remove elements:
prompt$: qore -ne 'list<auto> l = (1, 2, 3, 4); printf("removed: %y\n", (extract l, 1, 2)); printf("l: %y\n", l);'
removed: [2, 3]
l: [1, 4]

Option 2: Use the remove operator with a range to remove a slice of a list:
prompt$ qore -ne 'list<auto> l = (1, 2, 3, 4); printf("removed: %y\n", remove l[1..2]); printf("l: %y\n", l);'
removed: [2, 3]
l: [1, 4]

Q: How can I join lists?
Use the +=, + to concatenate lists:
prompt$ qore -ne 'list<auto> l1 = (1, 2); list<auto> l2 = (3, 4); printf("new list: %y\n", l1 + l2);'
new list: [1, 2, 3, 4]
prompt$  qore -ne 'list<auto> l1 = (1, 2); list<auto> l2 = (3, 4); l1 += l2; printf("new list: %y\n", l1);'
new list: [1, 2, 3, 4]

Note that to add a list as a single element to another list, it's best to use the push operator:
qore -ne 'list<auto> l1 += (1, 2); list<auto> l2 = (3, 4); push l1, l2; printf("new list: %y\n", l1);'
new list: [1, 2, [3, 4]]

Note that I used += for the original assignment above to ensure that l1 has type list<auto> - as a simple assignment would have resulted in list<int> which would cause the push expression to throw an exception.
Also note that as lists are basic types in Qore, they are always passed by value (technically they are passed by reference using copy-on-write semantics), and the "pseudo-class" for lists (as with all pseudo-classes in Qore) implements only read-only methods; updating lvalues in Qore is only done with operators.  This is because updating lvalues in Qore is complex due to Qore's multithreaded nature.  All Qore operators are thread-atomic, and lvalues can only be changed with operators that guarantee consistency and atomicity even in complex expressions.
The exception to the above is in objects, which are always passed by reference (actually technically with a copy of a reference, similar to Java); all other value types are passed by value.


text:
Q: How can I exclude a character when capturing regex group in Python? The current code is:
"...GO-Results-?T?o?p?-Price-TXT-Regular">(?P<cena>.*?) €</div>'

Now, this group (?P<cena>.*?) captures a price of some items. But the price is given as, for example, 5.400 €. So, this group captures 5.400 . I want it to capture 5400. I have been looking all over the internet on how to do that, but I can't find anything useful. Does anyone know how to do that?
I need that because I am using this data in Jupyter. But, it then changes 5.400 to 5.4. In my case, 5.400 means five thousand four hundred and not five point four, so this is unacceptable. If it is possible to change this in Jupyter (Pandas), I am also interested in this kind of a solution.

A: If you want the group to arrive as a coherent unit, you can post-process it:
match.group('cena').replace('.', '')

More complicated version with multiple characters:
match.group('cena').translate(str.maketrans(dict.fromkeys('., ', '')))

Or you can just use regex again:
re.sub(r'\D', '', match.group('cena'))


text:
Q: Line bundles and Cyclic Covers of Curves Let $X \to Y$ be a cyclic etale cover of smooth projective geometrically connected curves over some field $k$. Then the map is classified by an element of the cohomology group $H^1_{et}(Y_{k_s}, \mu_n)$; in other words the data of the covering is equivalent to giving a line bundle on $Y$ together with a trivialization of its $n$-th power. It follows that the induced map on Picard schemes given by pullback is not injective. My question is: what can be said about the kernel? I am especially interested in the special case of a degree $2$ cover; i.e are there are any other elements in the kernel besides the trivial bundle and the bundle classified by the covering. This one is given explicitly by pushing forward the structure sheaf on $X$ and modding out by the structure sheaf on $Y$.
I tried asking this on MSE but got no answer.

A: Let me give an answer when $\mathrm{char} \, k=0$.
In this situation the double cover $f \colon X \to Y$ is defined by a line bundle $\mathcal{L}$ such that $\mathcal{L}^{\otimes 2} = \mathcal{O}_Y$ and the trace map provides a splitting
$$f _* \mathcal{O}_X = \mathcal{O}_Y \oplus \mathcal{L}^{-1}.$$
Assume now that $\mathcal{M}$ belongs to the kernel of $$f^* \colon  \mathrm{Pic} \, Y \to \mathrm{Pic} \, X.$$
Then $f^* \mathcal{M} = \mathcal{O}_X$ so, by applying the functor $f_*$ and the projection formula, we obtain $$f_* \mathcal{O}_X = f_* f^* \mathcal{M} = \mathcal{M} \otimes f_* \mathcal{O}_X = \mathcal{M} \oplus (\mathcal{M} \otimes \mathcal{L}^{-1}).$$
By the Krull-Schmidt theorem the decomposition of  a vector bundle in a direct sum of indecomposable ones is unique up to permutation of the summands, so we get either $\mathcal{M} = \mathcal{O}_Y$ or $\mathcal{M}=\mathcal{L}$.
Summing up, $\ker \, f^*$ is the subgroup of order $2$ generated by $\mathcal{L}$.
Exactly the same argument shows that if the étale cover is cyclic of degree $n$, then $\ker f^*$ is cyclic of the same order.

A:

Theorem. Let $X \to Y$ be an étale Galois cover with group $G$ of proper geometrically integral schemes over any field $k$. Then we have an exact sequence
    $$0 \to \operatorname{Hom}(G,k^\times) \to \operatorname{Pic}(Y) \to \operatorname{Pic}(X)^G.$$
    In particular, the kernel has size at most $n = |G^{\operatorname{ab}}|$, with equality if and only if $n$ is invertible in $k$ and $\mu_r \subseteq k$, where $r$ is the exponent of $G^{\operatorname{ab}}$.

Proof. An étale Galois cover with group $G$ is the same thing as a $G$-torsor, and we have a Hochschild–Serre spectral sequence (see e.g. Milne's Étale cohomology notes, Thm 14.9)
$$E_2^{pq} = H^p(G,H^q(X,\mathbb G_m)) \Rightarrow H^{p+q}(Y,\mathbb G_m).$$
The exact sequence of low degree terms is
$$0 \to H^1(G,\mathbb G_m(X)) \to H^1(Y,\mathbb G_m) \to H^1(X,\mathbb G_m)^G \to H^2(G,\mathbb G_m(X)) \to \ldots .$$
Since $X$ is proper and geometrically integral, the global sections of $\mathcal O_X$ are just the constants $k$, hence the global sections of $\mathbb G_m$ are just $k^\times$. This clearly has the trivial $G$-action, so
$$H^1(G,\mathbb G_m(X)) = \operatorname{Hom}(G,k^\times).$$
This proves the first statement. The second statement follows since
$$\operatorname{Hom}(G,k^\times) = \operatorname{Hom}(G^{\operatorname{ab}},k^\times),$$
and for any finite abelian group $G$ there is a noncanonical isomorphism $G^{(p')} \cong \operatorname{Hom}(G,\bar k^\times)$, where $(-)^{(p')}$ denotes the prime to $p$-part if $\operatorname{char} k = p > 0$ (and the entire group if $\operatorname{char} k = 0$).
Since the group generated by the images of homomorphisms $G \to \bar k^\times$ is the subgroup $\mu_r$ for $r$ the exponent of $G$, we conclude that they are all realised over $k$ if and only if $\mu_r \subseteq k$. $\square$


text:
Q: CSRF Token extend token expiry on Runtime I have an existing Flask application that uses ajax request extensively to make changes to data & page. There are many actions that make an ajax request to the server to modifiy & make changes to data.
The application uses flask-wtf CSRF for Protection against Cross Site Requst Forgery. The expiry time for my CSRF token is 60 Mins.
Now, if a user has had a page open in a tab for more than an hour, and submits the form the CSRF validation fails and an error is thrown.
I want to know if there is a way to extend the expiry time of the CSRF tokens when i make an ajax request.
My current hack:
For now i was thinking of having a csrf_fail_handler function which can generate a new CSRF token when the previous one has failed & send it in the response with some unique status code.
My ajax response handler funtion can then check for the status code in response and update the _csrf_token field.
Somethign like this:
Python Code
@csrf.error_handler
def csrf_error(reason):
    return render_template('csrf_error.html', reason=reason), 701 # my unique resposne code

csrf_error.html
{"_csrf" : {{csrf_token() }} }

JQuery ajax global handler for ajaxError:
$( document ).ajaxError(function( x, response) {
  if ( x.status == 701 ) {
    $( "#csrf_token" ).val( response._csrf);
    $('#notifiy').text("Please Retry").show();
  }
});

This will give me the new CSRF token in response when the previous one has failed. and then in my ajax handler.
I wnat to know what is the best approach to this ? Does this affect the security ?
Note:
I know that the best solution is simply increasing the CSRF expiry time in the config file. However the client thinks that it may be a security breach if having expiry time longer than an hour.


text:
Q: 'New Project' Failure: Android Studio 0.3.4 I'm a newb so perhaps I am missing something obvious, but I haven't been able to find anything on it and I am out of ideas...
java version "1.7.0_07"
Java(TM) SE Runtime Environment (build 1.7.0_07-b10)
Java HotSpot(TM) Server VM (build 23.3-b01, mixed mode)
Android Studio Version: 0.3.4 Build 132.908450
Ubuntu 12.04
I get the following error message when completing the 'New Project' Wizard using all defaults:
"org.gradle.internal.service.DefaultServiceRegistry.add(Ljava/lang/Class;Ljava/lang/Object;)V
Consult IDE log for more details (Help | Show Log)"
Additionally, the project files are created in the home folder despite the IDE not launching.
I haven't been successful in locating the log, so any direction on that could possibly help the cause.
I installed gradle hoping that would fix it; no luck.
Any help is much appreciated!

A: It happened to me when I upgraded Android Studio while using system Gradle 1.8 (not Gradle wrapper). The solution is to go to android-studio/plugins/gradle/lib folder and delete all Gradle 1.8 libraries (keep 1.9-rc-3 ones).


text:
Q: Swift-Deletion in Core Data with multiple selection In Core Data application, we can swipe to delete a row, but I want to delete multiple rows by selecting them.
self.tableView.allowsMultipleSelectionDuringEditing = true

I have done the above and I have also implemented the usual deletion method. I also tried something like this.
     func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
    return UITableViewCellEditingStyle.Delete
}

     func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    let entry: DiaryEntry = self.fetchedResultsController.objectAtIndexPath(indexPath) as! DiaryEntry
    let coreDataStack: CoreDataStack = CoreDataStack.defaultStack
    coreDataStack.managedObjectContext.deleteObject(entry)
    coreDataStack.saveContext()
}
  func controllerWillChangeContent(controller: NSFetchedResultsController) {
    self.tableView.beginUpdates()
}

    var multipleSelection = false

    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
    switch type {

    case .Insert :
        if indexPath != newIndexPath {
            tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
        }

    case .Delete :
        if (multipleSelection == true) {
            let selectedRows = self.tableView.indexPathsForSelectedRows
            for selectionIndex in selectedRows! {
                let indicesOfItemsToDelete = NSMutableIndexSet()

                indicesOfItemsToDelete.addIndex(selectionIndex.row)

                let entry: DiaryEntry = self.fetchedResultsController.objectAtIndexPath(selectionIndex) as! DiaryEntry
                let coreDataStack: CoreDataStack = CoreDataStack.defaultStack
                coreDataStack.managedObjectContext.deleteObject(entry)
                coreDataStack.saveContext()
            }
            self.tableView.deleteRowsAtIndexPaths(selectedRows!, withRowAnimation: .Automatic)
        } else {
            self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
        }

    case .Update :
        self.tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)

    case .Move :
        self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
        if indexPath != newIndexPath {
            tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
        }

    }
}

   func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
    switch type {

    case .Insert :
        self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic)

    case .Delete :
        self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic)

    case .Update :

        //let range: NSRange = NSMakeRange(0, (self.fetchedResultsController.sections?.count)!)
        self.tableView.reloadSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic)

    default:
        break
    }

}

When I press the edit method, I set the tableView's editing to true and after selection, when I press delete button, following is the code.
 let selectedRows = self.tableView.indexPathsForSelectedRows
 multipleSelection = true
 for selectionIndex in selectedRows! {
                tableView(tableView, commitEditingStyle: .Delete, forRowAtIndexPath: selectionIndex)
            }
 self.tableView.deleteRowsAtIndexPaths(selectedRows!, withRowAnimation: .Automatic)
    self.tableView.reloadRowsAtIndexPaths(selectedRows!, withRowAnimation: .Automatic)

But, I am getting an error: CoreData: error: Serious application error.  Exception was caught during Core Data change processing.  This is usually a bug within an observer of .....
Can, someone please tell me the solution?

A: Don't delete by asking the table view to delete (commit editing type). Get the list of managed objects to delete and delete them from the context yourself, then tell the table view they're gone (which you already do). Also, don't reload the rows after you tell the table they're gone.


text:
Q: How can I create an automated GPS tracker using A9G AI Thinker module? I have an AI Thinker A9G module connected to an ESP8266 D1 mini. I have the following script to send and receive AT commands to/from the module. The idea is to get a SMS with the Google maps GPS location of the module onto my mobile phone.
// GPS tracker with AI Thinker A9G module and AZ Delivery D1 Mini ESP8266 module
#include <SoftwareSerial.h>

#define rxPin D7
#define txPin D8
SoftwareSerial A9modem(rxPin, txPin);  // Pins D7 Rx and D8 Tx are used as used as software serial pins

String incomingData;  // For storing incoming serial data
String gpsData;       // For storing location data
char msg;
char call;

void setup()
{
  Serial.begin(115200);  // Baud rate for serial monitor
  A9modem.begin(115200);  // Baud rate for GSM shield

  Serial.println("GPS/GSM A9G BEGIN");
  Serial.println("Enter character for control option: ");
  Serial.println("h : to disconnect a call");
  Serial.println("s : to send a message");
  Serial.println("r : to receive a message");
  Serial.println("c : to make a call");
  Serial.println("l : to read location");
  Serial.println("d : to disconnect gps");
  Serial.println();
  delay(100);

  // Set SMS mode to text mode
  A9modem.print("AT+CMGF=1\r");
  delay(100);

  // Set GSM module to TP show the output on serial out
  A9modem.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);
}

void loop()
{
  ReceiveMessage();
  gpsData = incomingData.substring(33, 52);
  Serial.print("Location: ");
  Serial.println(gpsData);
  delay(2000);

if (Serial.available() > 0)
   switch(Serial.read())
  {
    case 's':
      SendMessage();
      break;
    case 'r':
      ReceiveMessage();
      break;
    case 'c':
      MakeCall();
      break;
    case 'h':
      HangupCall();
      break;
    case 'l':
      ReadLocation();
      break;
    case 'd':
      DisconnectGps();
      break;
  }
}

void ReceiveMessage()
{
  if (A9modem.available() > 0)
  {
    incomingData = A9modem.readString();  // Get the data from the serial port
    Serial.print(incomingData);
    delay(100);
  }
}

void SendMessage()
{
  A9modem.println("AT+CMGF=1");       // Sets the GSM Module into text mode
  delay(1000);                        // Delay of one second
  A9modem.println("AT+CMGS=\"xxxxxxxxxxxxx\"\r");  // Replace your mobile number here
  delay(1000);
  String sms = "http://maps.google.com/maps?q=" + gpsData;  // Create the SMS location string
  A9modem.println(sms);
  delay(100);
  A9modem.println((char)26);          // ASCII code of CTRL+Z
  delay(1000);
}

void MakeCall()
{
  A9modem.println("ATD+xxxxxxxxxxxxx;");   // Replace your mobile number here
  Serial.println("Calling  ");            // Print response over serial port
  delay(1000);
}

void HangupCall()
{
  A9modem.println("ATH");
  Serial.println("Hangup Call");
  delay(1000);
}

void DisconnectGps()
{
  A9modem.println("AT+GPS=0");
  Serial.println("Disconnect GPS");
  delay(1000);
}

void ReadLocation()
{
  A9modem.println("AT+GPS=1");
  delay(1000);
  A9modem.println("AT+LOCATION=2");   // Check location every two seconds
  delay(2000);
}

So if I use the commands "l" and "s" in Arduino IDE serial monitor everything is working well but I don't know how to change the code in a way that I get a fully automated GPS tracker. The idea is the following: Power on starts the tracker. When gpsData string is not empty the first SMS will be send to my mobile phone. The next SMS follows 20 minutes later and so on until power is switched off. Could you help please?
Thanks in advance!

A: Finally I came up with this solution but I'm not very happy with it (it is working but I have to restart the module from time to time because there are no GPS data). There are 3 reasons for this: There is no error handling for the GPS function, I set the delays in a more ore less random way to get everything working but I don't know if the values make sense and I don't know if the substring() function is the best way to get the location from the serial response.
// GPS tracker with AI Thinker A9G module and AZ Delivery D1 Mini
   ESP8266 module
#include <SoftwareSerial.h>

#define rxPin D7
#define txPin D8

SoftwareSerial A9modem(rxPin, txPin);  // Pins D7 Rx and D8 Tx are used as used as software serial pins

String incomingData;  // For storing incoming serial data
String gpsData;       // For storing location data

int runGps = 1;
int sendSms = 0;

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);  // Use builtin LED for correct GPS status

  Serial.begin(115200);   // Baud rate for serial monitor
  A9modem.begin(115200);  // Baud rate for GSM shield

  // Set SMS mode to text mode
  A9modem.print("AT+CMGF=1\r");
  delay(300);

  // Set GSM module to TP show the output on serial out
  A9modem.print("AT+CNMI=2,2,0,0,0\r");
  delay(1000);

  Serial.end();
  delay(500);
}

void loop()
{
  Serial.begin(115200);

  ReceiveMessage();  // Start a new serial stream
  gpsData = incomingData.substring(33, 52);  // Strip all unnessesary data from the stream
  Serial.print("Location: ");  // Check if the location data are correct
  Serial.println(gpsData);
  delay(1000);

  if(runGps == 1) {   // Start GPS
    ReadLocation();
    delay(20000);  // Wait for GPS to be ready
  }

  if(gpsData.length() == 19 && sendSms == 0) {  // If the location string is correct send SMS
    if (isdigit(gpsData.charAt(0))) {           // Check if the stream starts with a number
      SendMessage();
      digitalWrite(LED_BUILTIN, HIGH);
      delay(300);
      digitalWrite(LED_BUILTIN, LOW);
      delay(300);
      digitalWrite(LED_BUILTIN, HIGH);
      delay(300);
      digitalWrite(LED_BUILTIN, LOW);
      delay(300);
      digitalWrite(LED_BUILTIN, HIGH);
    }
  }

  if(runGps == 0 && sendSms == 1) {
    runGps = 1;
    sendSms = 0;

    delay(6000);  // Make sure that all SMS serial communication is over

    while (A9modem.available()) {
      A9modem.read();  // Delete all data from serial buffer
    }

    delay(300000);  // If SMS was sent wait 5 minutes before running the main loop again

    Serial.end();
    delay(500);
  }
}

void ReceiveMessage()
{
  if (A9modem.available() > 0)
  {
    incomingData = A9modem.readString();  // Get the data from the serial port
    Serial.print(incomingData);
    delay(500);
  }
}

void SendMessage()
{
  sendSms = 1;                        // Stop starting the SendMessage function
  A9modem.println("AT+CMGF=1");       // Sets the GSM Module into text mode
  delay(1000);
  A9modem.println("AT+CMGS=\"xxxxxxxxxx\"\r");  // Replace your mobile number here
  delay(1000);
  String sms = "http://maps.google.com/maps?q=" + gpsData;  // Create the SMS string
  A9modem.println(sms);
  delay(500);
  A9modem.println((char)26);          // ASCII code of CTRL+Z
  delay(500);
}

void ReadLocation()
{
  runGps = 0;                         // Stop starting the ReadLocation function
  A9modem.println("AT+GPS=1");
  delay(1000);
  A9modem.println("AT+LOCATION=2");   // Check location every two seconds
  delay(2000);
}

A: Try turning ON the NMEA stream from the A9G. Say you want to get the NMEA data every t seconds, you can add and then call the following function once in the void setup()
void TurnOnNMEA(int t)
{
    if(t > 3600)
        t = 3600; // Because the max time is 3600s
    A9modem.print("AT+GPSRD=");
    A9modem.println(t);
    while(!A9modem.available()); // wait till the A9G sends a response
    char c;
    while(A9modem.available())
    {
        c = A9modem.read();
        Serial.print(c);
        delay(2); // Time needed for the next character
    }
}

This will start the NMEA data stream every t seconds which you can print using the following function,
void ReadNMEA()
{
    char c; // Read each character from the stream as it comes
    if(A9modem.available())
    {
        c = A9modem.read();
        Serial.print(c);
        delay(2); // Time needed for the next character
    }
}

Parsing and decoding the NMEA is a bit tricky thing to do. There is a lot of information inside it and the decoding depends on what you want to do with it. If you just want the location, you can parse the $GNGGA line.
When parsing the data, DO NOT USE Arduino String() class. It is a very bad idea when handling this kind of stream. Instead, use char array.


text:
Q: Xlviewer not able to render excel sheet Team,
I have an unusual problem of XLviewer.aspx not able to render the excel sheet by itself but takes the help of defualt client application to render....meaning it takes the help of installed office excel application 2010 and renders it.
To give you some background, i am trying to export the excel out of datagrid view.I observed that the datagridview export to excel code saves the generated excel file as excel 97-2007 by default. This cannot be opened by xlviewer. However, when i save in the format of "Excel worksheet" , the file gets opened by xlviewer.
Any idea, how do i save the excel in the format of Excel worksheet when i export? or are there any other ideas you can share?


text:
Q: ¿ Cómo probar proyectos de manera independiente a otros? Tengo dos paquetes en el mismo proyecto con numerosas clases dentro de cada uno. Todas las clases son públicas. Hay un paquete que presenta fallos en una de las clases. El otro paquete está sin fallos.
Quiero probar una clase ejecutable del segundo paquete, pero no me deja porque primeramente ejecuta el primer paquete, encuentra el fallo de la mencionada clase y se detiene la ejecución por el error del primer paquete.
Me gustaría saber si hay alguna manera de ejecutar el segundo paquete sin ejecutar el primero. Gracias.

A: puedes utilizar JUnit de java para realizar pruebas unitarias para cada uno de los metodos de cada clase.
Lo que JUnit hace es poder hacer pruebas pequeñas de segmentos de codigo.


text:
Q: Copy and paste through specific criteria on filter I'm new to VBA and I'm facing some problems with the code below:
It just need to find all the cells with "Add" on column DE and paste the names which is on the left column DD to the last blank cell on column A. The macro runs ok until the paste line. I don't know if there is another way around it.
ActiveSheet.Range("$DD$16:$DE$200").AutoFilter Field:=109,         Criteria1:="Add"
Range("DD16").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

'unfilter Macro
ActiveSheet.Range("$A$13:$DE$133").AutoFilter Field:=109

'Paste names marked as "Add"
Range("A14").Select
ActiveCell.End(xlDown).Offset(1, 0).Select
ActiveSheet.Paste


text:
Q: Implementing onActivityResult() in a Service I have the following code, which should record the device screen, using a service.
The problem is that to use it I need to use a call like: startActivityForResult/onActivityResult, for the permission thing to be able to record the screen.
But on Android Service there is no such call.
I have to start something like this:
startActivityForResult (mProjectionManager.createScreenCaptureIntent (), CAST_PERMISSION_CODE);

code:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != CAST_PERMISSION_CODE) {
            Log.w("class:", "Unknown request code: " + requestCode);
            return;
        }
        Log.w("class:", "onActivityResult:resultCode");
        if (resultCode != RESULT_OK) {
            startRec = false;
            Toast.makeText(this, "Screen Cast Permission Denied :(", Toast.LENGTH_SHORT).show();
            return;
        }
        prepareRecording("start");
        mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);

        Log.w("class:", "onActivityResult:mMediaProjection");

        // TODO Register a callback that will listen onStop and release & prepare the recorder for next WidgetProvider
        // mMediaProjection.registerCallback(callback, null);
        mVirtualDisplay = getVirtualDisplay();
        mMediaRecorder.start();
    }

How can I make any suggestions?
full code:
package com.unkinstagram;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Environment;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import static android.app.Activity.RESULT_OK;

class Constants {
    public interface ACTION {
        public static String MAIN_ACTION = "com.unkinstagram.action.main";
        public static String STARTFOREGROUND_ACTION = "com.unkinstagram.action.startforeground";
        public static String STOPFOREGROUND_ACTION = "com.unkinstagram.action.stopforeground";
        public static String REC_ACTION = "com.unkinstagram.action.rec";
        public static String STOP_ACTION = "com.unkinstagram.action.stop";
    }

    public interface NOTIFICATION_ID {
        public static int FOREGROUND_SERVICE = 101;
    }
}

public class ForegroundService extends Service {
    private static final String LOG_TAG = "class:";

    private static final int CAST_PERMISSION_CODE = 22;
    private DisplayMetrics mDisplayMetrics;
    private MediaProjection mMediaProjection;
    private VirtualDisplay mVirtualDisplay;
    private MediaRecorder mMediaRecorder;
    private MediaProjectionManager mProjectionManager;

    private boolean startRec = false;

    @Override
    public void onCreate() {
        super.onCreate();
        mDisplayMetrics = new DisplayMetrics();
        mMediaRecorder = new MediaRecorder();
        mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        WindowManager window = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        window.getDefaultDisplay().getMetrics(mDisplayMetrics);
        Log.v(LOG_TAG,"create");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
            Log.i(LOG_TAG, "Received Start Foreground Intent ");
            Intent notificationIntent = new Intent(this, MainActivity2.class);
            notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            Intent recIntent = new Intent(this, ForegroundService.class);
            recIntent.setAction(Constants.ACTION.REC_ACTION);
            PendingIntent pRecIntent = PendingIntent.getService(this, 0, recIntent, 0);

            Intent stopIntent = new Intent(this, ForegroundService.class);
            stopIntent.setAction(Constants.ACTION.STOP_ACTION);
            PendingIntent pStopIntent = PendingIntent.getService(this, 0, stopIntent, 0);

            Notification notification = new NotificationCompat.Builder(this)
                    .setContentTitle("Stai per registrare lo schermo del device.")
                    .setSmallIcon(R.drawable.ic_videocam_off)
                    .setContentIntent(pendingIntent)
                    .setOngoing(true)
                    .addAction(0, "Rec", pRecIntent)
                    .addAction(0, "Stop", pStopIntent)
                    .build();
            startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, notification);

        } else if (intent.getAction().equals(Constants.ACTION.REC_ACTION)) {
            Log.i(LOG_TAG, "Clicked Rec");
            startRecording();
        } else if (intent.getAction().equals(Constants.ACTION.STOP_ACTION)) {
            Log.i(LOG_TAG, "Clicked Stop");
            stopRecording();
            stopForeground(true);
            stopSelf();
        } else if (intent.getAction().equals(Constants.ACTION.STOPFOREGROUND_ACTION)) {
            Log.i(LOG_TAG, "Received Stop Foreground Intent");
            stopForeground(true);
            stopSelf();
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(LOG_TAG, "In onDestroy");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void startRecording() {
        startRec = true;
        // If mMediaProjection is null that means we didn't get a context, lets ask the user
        Log.w("class:", "startRecording:start");
        if (mMediaProjection == null) {
            // This asks for user permissions to capture the screen
            Log.w("class:", "startRecording:startResult");
            startActivityForResult(mProjectionManager.createScreenCaptureIntent(), CAST_PERMISSION_CODE);
            Log.w("class:", "startRecording:endResult");
            return;
        }
        Log.w("class:", "startRecording:end");
        mVirtualDisplay = getVirtualDisplay();
        mMediaRecorder.start();
    }

    private void stopRecording() {
        startRec = false;
        Log.w("class:", "stopRecording:start");
        if (mMediaRecorder != null) {
            mMediaRecorder.stop();
            mMediaRecorder.reset();
            //mMediaRecorder = null;
        }
        if (mVirtualDisplay != null) {
            mVirtualDisplay.release();
            //mVirtualDisplay = null;
        }
        if (mMediaProjection != null) {
            mMediaProjection.stop();
            //mMediaProjection = null;
        }
        Log.w("class:", "stopRecording:end");
    }

    public String getCurSysDate() {
        return new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
    }

    private void prepareRecording(String name) {
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            Toast.makeText(this, "Failed to get External Storage", Toast.LENGTH_SHORT).show();
            return;
        }
        final String directory = Environment.getExternalStorageDirectory() + File.separator + "Recordings";
        final File folder = new File(directory);
        boolean success = true;
        if (!folder.exists()) {
            success = folder.mkdir();
        }
        if (!success) {
            Toast.makeText(this, "Failed to create Recordings directory", Toast.LENGTH_SHORT).show();
            return;
        }

        String videoName = (name + "_" + getCurSysDate() + ".mp4");
        String filePath = directory + File.separator + videoName;

        int width = mDisplayMetrics.widthPixels;
        int height = mDisplayMetrics.heightPixels;

        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mMediaRecorder.setVideoEncodingBitRate(8000 * 1000);
        mMediaRecorder.setVideoFrameRate(24);
        mMediaRecorder.setVideoSize(width, height);
        mMediaRecorder.setOutputFile(filePath);

        try {
            mMediaRecorder.prepare();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

    }

    private VirtualDisplay getVirtualDisplay() {
        int screenDensity = mDisplayMetrics.densityDpi;
        int width = mDisplayMetrics.widthPixels;
        int height = mDisplayMetrics.heightPixels;
        return mMediaProjection.createVirtualDisplay(this.getClass().getSimpleName(),
                width, height, screenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mMediaRecorder.getSurface(), null, null);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != CAST_PERMISSION_CODE) {
            Log.w("class:", "Unknown request code: " + requestCode);
            return;
        }
        Log.w("class:", "onActivityResult:resultCode");
        if (resultCode != RESULT_OK) {
            startRec = false;
            Toast.makeText(this, "Screen Cast Permission Denied :(", Toast.LENGTH_SHORT).show();
            return;
        }
        prepareRecording("start");
        mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);

        Log.w("class:", "onActivityResult:mMediaProjection");

        // TODO Register a callback that will listen onStop and release & prepare the recorder for next WidgetProvider
        // mMediaProjection.registerCallback(callback, null);
        mVirtualDisplay = getVirtualDisplay();
        mMediaRecorder.start();
    }
}

A: So you want to use MediaProjection in a Service. To use MediaProjection, you need user to grant permission and then use the Intent returned in the onActivityResult to create a MediaProjection. However, you're in a service and no onActivityResult is available.
Here is an useful github issue: https://github.com/mtsahakis/MediaProjectionDemo/issues/7. There're also some gists you can use.
The basic idea is using an Activity to ask for permission and then start your service with an Intent wrapping the result Intent(Intent is also a parceable so it can be put into another Intent).

A: While a service can be involved in the screen recording, asking permission has to be done from an activity. So, ask for permission before you start your service.
For example, in this sample app, while the RecorderService is what actually starts and stops the screen recording, the MainActivity is what requests permission, before starting that service. That activity uses Theme.Translucent.NoTitleBar, so it has no UI of its own, other than the system permission dialog.


text:
Q: How to tell GCC link the library into the exe? I am new to C and GCC. I am following Tensorflow in C and I have build it successfully.
For reference, below is my GCC command
gcc.exe -Iinclude -Llib test.c -ltensorflow -o test.exe

However, when I run the exe, I am getting an error saying
tensorflow.dll is missing

and if I copy the tensorflow.dll on the same location as the test.exe it works. Is it possible to make this exe independent of the library? In other words, I want to share only the exe with others and not the library.


text:
Q: How to detect if a device is an iPad? Is it possible to detect whether a browser is running on iOS (I want to know if the device is an iPad) by using feature detect with Modernizr. Like it adds lt-ie8 class for IE8. I want to know what it sticks to <html> class if the device is an iPad.
I just want to add css classes exclusively for iPad.

A: You can use Modernizer to declare a class on the body or html tag when a person is viewing a certain browser.
From there you can declare those classes within your stylesheet.
https://modernizr.com/docs#using-modernizr-with-css

A: via the user-agent header.
Copied from google search, I searched for user-agent ipad.
User-Agent String   Apple Product   iOS Version Build
Apple-iPad1C1/807.4 iPad    4.3.1   8G4 Mar 25, 2011
Apple-iPad1C1/808.7 iPad    4.3.2   8H7 Apr 14, 2011
Apple-iPad1C1/810.3 iPad    4.3.3   8J3 May 4, 2011
Apple-iPad1C1/811.2 iPad    4.3.4   8K2 Jul 15, 2011

Basically you should search for Apple-Ipad* in the user-agent header.


text:
Q: Arrowheads in VectorStyle and StreamStyle doesn't work properly in VectorPlot and StreamPlot, respectively. A bug? I'm using Mathematica 10.0.2 for Mac.
Arrowheads given in VectorStyle for VectorPlot doesn't work for some combinations of directives.
Beginning with the following plot:
VectorPlot[{1, 1}, {x, 0, 8}, {y, 0, 8}]

Working combinations
Example 1
VectorPlot[{1, 1}, {x, 0, 8}, {y, 0, 8}, VectorStyle -> Arrowheads[0]]
VectorPlot[{1, 1}, {x, 0, 8}, {y, 0, 8}, VectorStyle -> {Arrowheads[0]}]

Example 2
VectorPlot[{1, 1}, {x, 0, 8}, {y, 0, 8}, VectorStyle -> {{Black, Arrowheads[0]}}]

Example 3
VectorPlot[{1, 1}, {x, 0, 8}, {y, 0, 8}, VectorStyle -> {{Thick, Arrowheads[0]}}

Malfunctioning combinations
The follow codes should work in removing the arrow heads but they don't.
Directive is forbidden:
VectorPlot[{1, 1}, {x, 0, 8}, {y, 0, 8}, VectorStyle -> Directive[Arrowheads[0]]]

No, you can't pretend there are multiple sets of fields (cf Example 1):
VectorPlot[{1, 1}, {x, 0, 8}, {y, 0, 8}, VectorStyle -> {{Arrowheads[0]}}]

No, Arrowheads[0] can't be the first directive (cf Example 2):
VectorPlot[{1, 1}, {x, 0, 8}, {y, 0, 8}, VectorStyle -> {{Arrowheads[0], Black}}]

No, you can't customise both colour and thickness simultaneously, irrespective of where Arrowheads is:
VectorPlot[{1, 1}, {x, 0, 8}, {y, 0, 8}, VectorStyle -> {{Red, Thick, Arrowheads[0]}}]
VectorPlot[{1, 1}, {x, 0, 8}, {y, 0, 8}, VectorStyle -> {{Arrowheads[0], Red, Thick}}]

The same is true for StreamPlot and StreamStyle. Is all this a bug?

On Wolfram Cloud, which I guess is equivalent to 10.1, every combination described above works fine except
VectorPlot[{1, 1}, {x, 0, 8}, {y, 0, 8}, VectorStyle -> Directive[Arrowheads[0]]]
StreamPlot[{1, 1}, {x, 0, 8}, {y, 0, 8}, StreamStyle -> Directive[Arrowheads[0]]]

Arrowheads is a directive supported by Graphics (ref.), and any directives supported by Graphics should be able to appear inside Directive (ref.).

A: It is probably a bug in V10.02.
In V10.1:
Directive does not work on each individual element of the Graphics. If you want to use it then you can do it like this:
VectorPlot[{1, 1}, {x, 0, 8}, {y, 0, 8},
 VectorStyle -> {Arrowheads[0], Directive[Red, Thick]}]

For the rest examples, they all work fine.
Update:
Arrowhead is a Directive as you said and it do appear in the Graphics Directive of the graphics.
VectorPlot[{1, 1}, {x, 0, 8}, {y, 0, 8},
  VectorStyle -> Directive[Arrowheads[0]]] // FullForm

But it does not work unless Arrowhead is grouped in list with each Arrow:
VectorPlot[{1, 1}, {x, 0, 8}, {y, 0, 8},
  VectorStyle -> Arrowheads[0]] // FullForm


text:
Q: Searching for tweets by keywords and location on Rails I'm new to Rails and developing in general and am trying to use the Twitter gem to search for tweets by location and keywords in my Rails app. Following the documentation at http://www.rubydoc.info/gems/twitter I have been able to figure out how to search for tweets by keyword (in my case #restaurant) but not filter this by my user's location.
I am currently trying the following:
In my controller

@search = client.search("#restaurant", result_type "recent", geocode: "#{@lat}, #{@lon}, #{@radius}mi")

In my view:

<% @search.take(3).each do |tweet| %>
   <% tweet.text %>
   <% end %>

If the geocode parameter is taken out I get 3 tweets with "#restaurant", but with the geocode nothing is returned. Is there a problem with my code?
As I am so new to programming, I could be approaching this problem completely wrong and I'm also open to any alternative approaches.

A: This might sound a little dump but your Geocode is in the middle of Peru as far as I can tell and 100miles might be too small of a radius. How about increase the miles (10000 miles) and try again.
I took that advice from this post: Twitter Gem with multiple search options


text:
Q: Convert object to url query parameters What is the equivalent of $httpParamSerializer(params) from angular 1 in angular 2?

A: I don't know about an exact equivalent, but with URLSearchParams it will handle the encoding for you. Sucks it doesn't allow you to just pass an object, so you need to do something like
import { URLSearchParams } from '@angular/http';

let params = new URLSearchParams();
for (let key in someObj) {
  if (somObj.hasOwnProperty(key)) {
    params.set(key, someObj[key])
  }
}

If all you need is the string for some odd reason, just call params.toString(). Otherwise if you want to pass it to the Http request, just do
let options = new RequestOptions({ search: params });
http.get(url, options);

The query string will get appended to the URL in a GET request, and in a POST request, you can set it as the body
http.post(url, params);


text:
Q: Deleting objects from Core Data that doesn't exist in an array I have a Core Data object like the following.
DummyObject
{
  objectID:<objectID>
  objectName:<objectName>
}

And I have 1000 of these DummyObjects saved. I have also an array objectArray which contains 100 of these DummyObjects.
I want to run a query that would delete all the DummyObjects which are not in this array.

A: From my comment
You could just try a predicate like the following for your fetch request
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (self IN %@)", yourArray];

Using it together with a NSFetchRequest allows you to retrieve the objects that are not in the array.
Obviously, yourArray contains objects of type DummyObject.
To delete,
// fetch request with predicate...
NSArray* results = // execute the fetch request

for(NSManagedObject* dummy in results) {
   [context deleteObject:dummy];
}

// save here...

where results is the array of objects retrieved by your fetch request.


text:
Q: Not iframe but i can't find any element on the webpage (selenium python) I'm trying to automate the game play for a site but I can't find any element on the page relating to the game and it doesn't appear to be in an iframe like other answers on this platform suggested for other related questions. Being unable to find any element i opted to Clicking at coordinates without identifying element and i found this
actions.move_to_element_with_offset(driver.find_element_by_tag_name('body'), 0,0)
actions.move_by_offset(X coordinates, Y coordinates).click().perform()

but i still need to be able to interact with the elements on the site so as to be able to input values and also get values from the site.


text:
Q: When calling super().save() in overriden save method, model is not updating ManyToManyField If I have a model with a field that is a ManyToManyField, calling super().save() inside of the overidden save method, the model object is not getting updated if referenced inside of the save method.
models.py
class AddOn(models.Model):
    name = models.CharField(max_length=100)

class Invoice(models.Model):
    additional_options = models.ManyToManyField(AddOn)

    def save(self, *args, **kwargs):
        super().save()
        # this prints the objects that were selected prior to the save.
        # this isn't helpful if the selected objects have changed.
        print(self.additional_options.all())


text:
Q: Force redraw of img element My Elm app lets the user rotate pictures: when a picture on the screen is clicked, elm makes an API call to rotate the picture file on the server. Following that I'd like the rotated image to show in the browser.
But the virtual DOM hasn't changed at all since the img node has the same src URL. Is there a way I can force the img to be recreated anyway?
Sure, I could use a Keyed node or modify some attribute on my img to force the redraw, but that would mean adding something to my model that is modified on rotate. It's possible but not very elegant.

A: You want something to be modified on rotate: namely, the image. So you're going to have a change in your model at the point when you want the rotation to occur. I'd have the response from the API increment a counter in the model (or use the current time via Time.now), and then update the image URL with a cache busting query parameter based on that value. More details on cache busting query parameters are here: Cache busting via params


text:
Q: Actualizar el estado de tu proyecto en github mediante git No tengo claro si estoy entendiendo el manejo de git (combinado con un repositorio como puede ser github).
Supongamos que ya he creado mi proyecto y he hecho los pasos iniciales de git y ya está todo en mi repositorio de github. Yo sigo trabajando y modifico mi archivo main.py (inicialmente estaba vacío y ahora ya he empezado a codificar) y por hoy ya he terminado.
En este punto entiendo es interesante actualizar el estado de mi proyecto, entonces según he entendido ahora debería hacer un git commit -m "Comentarios", esto lo que hace es actualizar mi repositorio local y a continuación un git push -u origin main.
¿Es esto correcto?
Siguiendo mis pasos, hago un commit y me aparece el siguiente mensaje

Debo hacer un add, si la respuesta es que sí, alguien puede ayudarme a entenderlo? Yo entendía que el add era para añadir nuevos elementos, pero si se trata de actualizar los que ya se tenían no hace falta.
Muchas gracias.

A: Si, tienes que hacer un add. En corto, git hace el commit de todo lo que encuentre en el staging area. Entonces, antes de hacer un commit, tienes que decirle pasar tus archivos a ese staging area. Esto lo haces con un add. Si usas el comando git add ., incluyes todos los archivos que has cambiado. También puedes elegirlos usando git add *direccion del archivo*.


text:
Q: How do I create my own group on facebook by android app? I have read this page(https://developers.facebook.com/docs/graph-api/reference/user/groups) and I can get all my groups, but it can create new group according the webpage. How can I create my group ( not app group ) like official website and app?

A: You can only create "normal" groups via the facebook website, and not via the Graph API.
See

*

*https://developers.facebook.com/docs/graph-api/reference/v2.3/group#publish

You can't publish on this endpoint.


text:
Q: when I export dataframe to excel I got just part of columns I have nested dictionary which I try to export to excel
I have code which generate correct dataframe, the idea is to generate it in excel, but I get in excel only part of the columns, what I am doing wrong
user_ids = []
frames = []

for user_id, d in res_duplicate.items():
    for item in d:
        user_ids.append(user_id)
        frames.append(pd.DataFrame.from_dict(item, orient='index'))

df = pd.concat(frames, keys=user_ids)
print (df)
df.to_excel('C:/Users/user/Desktop/dict1.xlsx', index = False, header=False)

when I print dataframe I got

but in excel I have just columns time and docs

A: First 2 columns are MultiIndex, so if use index=False is not written to excel. Possible solution is remove it:
df = pd.concat(frames, keys=user_ids)
df.to_excel('C:/Users/user/Desktop/dict1.xlsx', header=False)

Or convert MultiIndex to columns, then default RangeIndex is by index=False omitted:
df = pd.concat(frames, keys=user_ids).reset_index()
df.to_excel('C:/Users/user/Desktop/dict1.xlsx',index = False,  header=False)


text:
Q: Window not responding while using sockets SFML I am doing some simple SFML game, and I want to have network communication using udp Sockets. But the problem is that window is blocked and not responding if I try to update position of circle using coordinates that socket receives. Here is the code below. Does anyone know what the problem is?
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include <iostream>
#include <string>
#include <iostream>

int posX=100,posY=220,x=5;
sf::UdpSocket receiver;
sf::SocketSelector selector;

void changePosition ();
void defineWindow(sf::RenderWindow &window);
void drawCircle(sf::CircleShape &circle, sf::RenderWindow &window);

int main ()
{
  receiver.bind(15000);
  selector.add(receiver);

  sf::RenderWindow window (sf::VideoMode(800,600), "Krugovi");

  defineWindow (window);

  return 0;
}

void changePosition ()
{
  if (x>0 && posX+x>685) {
    posX=685;
    x=-x;
  }
  else if (x<0 && posX+x<15) {
    posX=15;
    x=-x;
  }
  else
    posX=posX+x;
}

void defineWindow(sf::RenderWindow &window)
{
  sf::CircleShape circle(50);
  sf::Event event;
  sf::Clock clock;

  while (window.isOpen()) {
    while(window.pollEvent(event)) {
      if (event.type == sf::Event::KeyPressed) {
        if (event.key.code == sf::Keyboard::Escape)
          window.close();
      }
      if (event.type==sf::Event::Closed)
        window.close();
    }

    window.clear(sf::Color::White);

    char msg[5];
    size_t received;
    sf::IpAddress ip;
    unsigned short port;

    std::string string;

    if (selector.wait()) {
       if(receiver.receive(msg,sizeof(msg),received,ip,port)==sf::UdpSocket::Done) {
        posX=atoi(msg);
      }
    }

    drawCircle(circle,window);

    window.display();
  }
}

void drawCircle(sf::CircleShape &circle, sf::RenderWindow &window)
{
  circle.setFillColor(sf::Color::Yellow);
  circle.setOutlineThickness(15);
  circle.setOutlineColor(sf::Color::Red);
  circle.setPosition(posX,posY);
  window.draw(circle);
}

A: sf::SocketSelector::wait() without any parameters will wait forever until something is received on one of it's sockets, so you won't be responding to events in your window.
If you pass it a time to wait, for example sf::milliseconds(5) then you can continue to poll for events
Relevent docs here


text:
Q: SqlDataReader Convert SQL Signed to .NET Unsigned Integers Often use SQL Identity as the ID of .NET objects.
Start the ID at 0 or 1 as don't want the objects to have negative IDs.
The ID is presented to users so it needs to be logical to humans.
Also often use something like ((Int32)key1 << 32) + key2; for hash
If unsigned can so with faster (UInt32)key1 << 32 | key2;
Since SQL does not have unsigned data type half the range is lost.
What is a good practice for converting from SQL signed to unsigned in .NET?
Where the convert goes from 0 to max.
A straight cast does not not work as (UInt16)Int16.Min = Int16.Max +1.
Need to convert Int16.Min to 0 and Int16.Max to UInt16.Max.
In SQL will set the Identity seed to minimum (or minimum +1) for the data type.
Currently have a situation where going to blow through Int32 max but doubt it will ever get past UInt32 max.   If it does get past UInt32 max the app and database will need a full review.
Tried extensions to SqlDataReader and it seems to work.
Will post as an answer.
Not yet gone into production so checking SO for something better or warnings about the approach.
Don't need DataTable compatibility as this app uses zero and never will.
We don't use Entity Framework nor SQL LINQ.  Grunge TSQL and SP.
public static class MyExtensions
{
    public static UInt16 GetUInt16(this SqlDataReader rdr, int i)
    {
        //return (UInt16)rdr.GetInt16(i);  // wrong answer
        Int16 int16 = rdr.GetInt16(i);
        UInt16 uint16 = (UInt16)(int16 + 32768);
        return uint16;
    }
    public static UInt32 GetUInt32(this SqlDataReader rdr, int i)
    {
        Int32 int32 = rdr.GetInt32(i);
        UInt32 uint32 = (UInt32)(int32 + 2147483648);
        return uint32;
    }
}

A: You can store your UInt32 as an Int32 in SQL Server.  Cast your unsigned integer to a signed one when saving to SQL.
Your UInt32 values that are larger than Int32.MaxValue will be represented in SQL as negative numbers, but you can cast them back to UInt32 after reading from the database.
If using ADO.Net
uint hash;

When reading data
while (reader.Read())
{
    uint hash = (uint)reader.GetInt32(myIndex);
}

When writing data
cmd.Parameters.AddWithValue("MyParamName", (int)hash);

If using EF Code First
Expose a property of type Int32 that just wraps your hash value, and mark the actual hash property as NotMapped.
private uint hash;

[NotMapped]
public uint Hash
{
    get { return hash; }
    set { hash = value; }
}

public int HashAsLong
{
    get { return hash; }
    set { hash = value; }
}

A: In the end what I did way make the object responsible for the translation.
A read only signed property of sqlID.
For updates back to the database decided that should not mess with that value.
The objects also expose an unsigned ID that is used by other objects, hash, and UI.


text:
Q: javascript - arguments.callee.toString() and arguments.callee.name does not return function name I'm trying to get the name of the currently running function. From what I've read, this should be possible using:
(arguments.callee.toString()).match(/function\s+(\[^\s\(]+)/)

However, when I run this in Firefox and Safari (latest versions on Mac) the name is not returned.
console.log( arguments.callee ) returns the source of the function, but not the assigned name. arguments.callee.name returns an empty string.
My sample code is as follows:
var testobj = {
    testfunc: function(){
        console.log( (arguments.callee.toString()).match(/function\s+(\[^\s\(]+)/) );
    }
}
testobj.testfunc();

A: The typical arguments.callee hacks don't work here because what you've done is assigned an anonymous function as the value for the object's 'testfunc' key.  In this case the hacking even gets worse, but it can be done, as follows:
var testobj = {
    testfunc: function(){
      for (var attr in testobj) {
              if (testobj[attr] == arguments.callee.toString()) {
                  alert(attr);
                  break;
                }
            }
    }
}
testobj.testfunc();

A: On firefox 3.5, Safari 5, and Chrome 6.0 you can use:
function myFunctionName() {
 alert("Name is " + arguments.callee.name );
}

myFunctionName();

You can also get the function that called the current one using arguments.callee.caller.

A: /function\s+(\[^\s\(]+)/

What's with the backslash before [? I don't think you want a literal square bracket here. Without that it should work.
Although I'd strongly recommend against anything to do with sniffing function name or especially sniffing caller function. Almost anything you might do using these hideous hacks will be better done using some combination of closures and lookups.

A: I think there's a much cleaner and elegant solution to all this. Assuming the function is a member of some higher-level object—and that's always going to be the case, even if the function's owner is "window" or some other global object, we can access the global object via the this keyword, we can access the function itself via arguments.callee and we can access all the parent's object (function) names via for (var o in this), so you should be able to get the desired information fairly easily as...
returnMyName = function() {
  for (var o in this) {
    if (arguments.callee===this[o]) return o;
  }
};

That should be robust and avoid any weird IE browser behaviors accessing named functions, etc.

A: Function.prototype.getName = function(fn) {
    if(Function.name || Function.prototype.name) return this.name;
    return this.toString().match(/^function\s+(\w+)\s*\(/)[1];
};

A: You declared an anonymous function with
function(){

You should declare it as
function testfunc(){

to get the name printed.

A: First of all, the function doesn't have a name. The function name is what you put in-between function and the arguments list (...). Here's how to get a function's name (don't use the name property, as it can be changed):
var fName = arguments.callee.toString(0).match(
  /^function\s*(?:\s+([\w\$]*))?\s*\(/
);
fName = (fName ? fName[1] : "");

A: I found that if you simply log the function object, like so:
console.log(arguments.callee)

or
console.debug(arguments.callee)

that you simply get the function name in the console log with some options.