text:
Q: What is the Big-O complexity of the code? for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
            j=j*2;
      }
}

I am having trouble generalizing it.

A: If we count the number of multiplication the program does, the complexity will be n * log2(n)
You do n times the inner loop (i scales with n), and the inner loop repeats as long as j <= n. j increase exponentially
1, 3, 7, 15, 31, 63, 127, ... = (2^n) - 1

Which is 2^n scaling, so double the value of n makes the inner loop iterate once more.
log2(n * 2) = log2(n) + 1


text:
Q: JNI Crashes when I do anything at all :S Java code:
package library;

import java.nio.ByteBuffer;

public class Library
{
    static{System.loadLibrary("TestDLL");}

    native static void GetGLBuffer(ByteBuffer Buffer, int Width, int Height, int Size);

    public static void main(String[] args) {

        ByteBuffer B = ByteBuffer.allocateDirect(5);
        byte[] C = {'H', 'E', 'R', 'E', '\0'};
        B.put(C);
        GetGLBuffer(B, 0, 0, 4);
        System.out.println((char)B.get(0));
    }
}

C++ Code:
JNIEXPORT void JNICALL Java_library_Library_GetGLBuffer(JNIEnv *env, jclass cls, jobject buffer, jint Width, jint Height, jint Size)
{
    unsigned char* Buff = (unsigned char*)env->GetDirectBufferAddress(buffer);
    //*Buff = 'A'; Crashes it.
    //Buff[0] = 'A'; Crashes it.
    //std::cout<<Buff[0]; Prints fine but crashes when this function ends.
}

If I do nothing, it works perfectly fine. Also, if I declare variables within the function above, it crashes.
How do I fix it? Am I doing anything wrong?
It prints out this file: http://pastebin.com/Mz76Bk8G

A: I just want to say that I solved it. I had to go into my JNI folder, copy the JNI.h and the JNI_MD.h for JDK 7 to my C++ project folder, include it as a file and also use a .def file to export.
Without doing all of the above steps, it crashed the JVM. Now I'm not sure why but I'm just glad it works. I'm posting this to let others who have the same problem fix it.
Thanx for the views guys. Was quite difficult to figure out what was wrong. Hope this comment helps others.

A: The problem is that you're not passing an array of bytes into your C function, but rather a ByteBuffer object. To set values inside the buffer, you'll need to call the methods on the buffer object, which from C means querying the object for its class, querying the class for the proper method, then invoking the method.
For example, if you wanted to do the equivalent of calling the put(int index, byte b) method on the ByteBuffer object, you'd need to do something like this in your C code:
jclass cls = (*env)->GetObjectClass(env, objID);
jmethodId mid = (*env)->GetMethodID(env, cls, "put","(IB)V");
if(mid == 0) return;
(*env)->CallVoidMethod(env, objID, mid, 0, 'A');

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change each columns item font size in WPF I want to change each columns font size. I am using listview with Gridview. I want the result something like this:

Here is my XML Code:
<ListView x:Name="listView1" Margin="0,0,-5,-5" FontSize="20">
     <ListView.View>
          <GridView>
               <GridViewColumn Header="Column1" DisplayMemberBinding="{Binding c1}" />
               <GridViewColumn Header="Column2" DisplayMemberBinding="{Binding c2}" Width="780"/>
               <GridViewColumn Header="Column3" DisplayMemberBinding="{Binding c3}" Width="460"/>
           </GridView>
      </ListView.View>
</ListView>

C#:
this.listView1.Items.Add(new MyItem { c1= "This is Column 1 Row 1 Text", c2="This is Column 2 Row 1 Text", c3= "This is Column 3 Row 1 Text" });

class MyItem
{

    public string c1{ get; set; }

    public string c2{ get; set; }

    public string c3{ get; set; }
}

A: You can always use the CellTemplate instead of DisplayMemberBinding to have full customization options.

For the first column something like:
<GridViewColumn Header="Column1">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding c1}" FontSize="15px"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>


text:
Q: .NET: Is "foreach" command? I have just a terminology question. I have read that if, foreach etc. are statements but what does it mean in the terminology - are these commands?
It is maybe "lost in the translation" problem

A: From Statement (programming)

In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program is formed by a sequence of one or more statements. A statement will have internal components (e.g., expressions).
Many languages (e.g. C) make a distinction between statements and definitions, with a statement only containing executable code and a definition declaring an identifier. A distinction can also be made between simple and compound statements; the latter may contain statements as components.

In a nutshell it is one of many instructions in the language that makes the program to perform some very basic action. Through combining statements you define a complex activity that makes sense to you as an author. You define it by using little building blocks namely those statements.

A: A command and a statement is generally the same thing.
However, when talking about commands, it's usually something that a user enters directly rather than a statement in a program.
Also, while a command generally is an instruction to do something, a statement can also be instructions that doesn't actually perform anything, like for example declaring a constant value:
const int Answer = 42;

A: A statement is an expression that has no return value (or void or unspecified).


text:
Q: Bash: control a prompt program I've searched all over Google and the StackExchange sites, but all of the answers may work for the programs they used, but not for this (timecalc).
This program is similar of fsck, having a ">>>+" prompt when opened and, apparently, not supporting receiving programmatic usage/commands unless through a Bash trick.
How to send commands to timecalc as if using its prompt but from an external bash script? [OPTIONAL] Bonus: a solution that works also at fsck and most of other prompt/interaction-only programs.
./timecalc sample command to test: 15:00 - 5:00 (should return "10:00" to the bash script)

A: For example:
$ echo 15:00 - 5:00 | timecalc-linux | head -n1 | sed 's,^>>> ,,'
10:00


text:
Q: Why does this "df" output differ from what Finder reports? df -h shows:
Filesystem             Size   Used  Avail Capacity iused      ifree
%iused  Mounted on /dev/disk1            233Gi  150Gi   83Gi    65%
3350360 4291616919    0%   /

From Finder, Info on the HDD shows:
249.68 GB
101.57 GB (12.78 GB purgeable)
148,108,524,404 bytes (148.11 GB on disk)

Why are 83 GB available from df, but 101.57 GB available in the other view of the same HDD?

A: You're seeing two different values because macOS's Finder reports GB, while df reports GiB. Both numbers refer to the same actual number of Bytes.
You can use different bases to  specify a large number of Bytes:

*

*1 GB = 1 Gigabyte = 1000^3 Bytes ("Giga" is a so-called SI prefix)

*1 GiB = 1 Gibibyte = 1024^3 Bytes ("Gibi" is a so-called binary prefix)

The former has been primarily used by hard drive vendors, and Apple has chosen to report the disk size in Finder in the same way as you'd get when you buy a drive. This is technically correct, as drives are sold in "GB" and "TB".
The df shipped with macOS instead shows your drive with binary prefixes, thus with a total capacity of 233 GiB (which is roughly equivalent to 250 GB).
PS: The GNU df shipped with Linux will show binary prefixes when using df -h, but labeling them as G. If you want to use SI prefixes there, you have to use df -H.

A: The Finder does not report "purgable space", taken be the Timemachine local backups and system caches, because MacOS will free that space if necessary. df does not know about that and includes disk space taken for those purposes.
You can read more about that here: https://daisydiskapp.com/manual/4/en/Topics/PurgeableSpace.html


text:
Q: Spring Boot JPA get reference to EntityManagerFactory I have a Spring-Boot web application, and I have a 3rd party jar that has a data access layer.  In order to use it,  I have to send it a reference to an EntityManagerFactory.  I am able to do this like this:
    Map<String, String> stg = new HashMap<String, String>();
    stg.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/mydb");
    stg.put("hibernate.connection.username", "name");
    stg.put("hibernate.connection.password", "password");

    EntityManagerFactory fact = MultipleEntityManagerFactoryHolder.getEmf("stg", stg);

But how do I get the one that Spring (I assume)  has already built for me when I add this to the application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false
spring.datasource.username=user
spring.datasource.password=password

I have no access to the jar,  so I need the factory,  not the DataSource.  Anyone know how to get that?

A: You can simply autowire it in your bean:
@Autowired
private EntityManagerFactory emFactory;


text:
Q: How to Manually Generate Instance of Swagger ApiModel If I have the following class:
@ApiModel
public class SomeEvent {
    @ApiModelProperty(
        value = "The unique identifier of this event.",
        example = "MY_EVENT"
    )
    private final String eventType;

    @JsonCreator
    public SomeEvent(
           @JsonProperty(value = "eventType", required = true) String eventType) {
        this.eventType = eventType;
    }

    public String getEventType() {
        return eventType;
    }
}

I would like to use Swagger to generate an instance and serialize it to the following JSON:
{
    "eventType": "MY_EVENT"
}

By using this class as a @RequestBody in my Spring Boot controller, the expected serialized form is displayed perfectly on the Swagger UI.
However, I'd like to be able to generate an instance (where the instance's fields contain the values from the example in the @ApiModelProperty) using code. I've searched around and could not find a single example of how to do this, assuming it's possible to achieve.
Note: I do not want to just create an instance using new SomeEvent("MY_EVENT");, but rather use Swagger to grab the examples.


text:
Q: Last-child selector I'm a bit confused about the use of the :last-child selector. I have different buttons with the mark-up like this:

Post-Doctorate's

Staff

PhD Students

Now I want to give the last button a different margin-bottom so I tried to use this:
.people a:last-child .people-button {
    margin-bottom: 5px;
}

But it seems this is not the correct selector. Any help or explanation on how to do this?

A: Your code is right and works (see fiddle), but only in supported browsers.
ie: last-child won't work below IE9.
To see compatibility table see:
http://www.quirksmode.org/css/selectors/
https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child
Another, issue is that it could be overridden by another CSS rule with major precedence. Use Developer Tool (F12) in your browser OR context menu (right-click the anchor) for inspect the element.
Generally, the browser will show in the right pane for this element, the computed CSS styles & all styles that were applied (and overriden).

You could rewrite your code. Take off the divs inside a, and set a as display: block to break line and work padding:

    Post-Doctorate's

    Staff

    PhD Students

CSS:
.people-button {
    display: block;
}
.people a:last-child {
    padding-bottom: 50px;     /* if you want space inside anchor */
    background-color: #0aa;
}
.people {
    border: 1px solid #000;
    padding-bottom: 20px;     /* if you just want space at bottom of container */
}

http://jsfiddle.net/m7CNv/2/


text:
Q: Django Tastypie PATCH throws "'Bundle' object is not iterable" error I'm working on an API and for one of my endpoints I want to be able to make partial updates.
Here is the tastypie resource
class StoryResource(ModelResource):
    authors = fields.ToManyField(SimpleAuthorResource, 'authors', full=True)
    posts = fields.ToManyField(SimplePostResource, 'posts', full=True, blank=True)
    cover_photo = fields.ForeignKey(PhotoResource, 'cover_photo', full=True)
    class Meta:
        queryset = Story.objects.all()
        resource_name = 'story'
        validation = ModelFormValidation(form_class=StoryForm)
        authorization = Authorization()
        allowed_methods = ['get', 'post', 'patch', 'put']
        ordering = ['-created_ts']
    def determine_format(self, request):
        return "application/json"

And I'm using POSTMAN to make a PATCH request to update a field in the Story model.
It returns with this error:

{"error_message": "'Bundle' object is not iterable", "traceback": "Traceback (most recent call last):\n\n  File \"/usr/local/lib/python2.7/dist-packages/tastypie/resources.py\", line 192, in wrapper\n    response = callback(request, *args, **kwargs)\n\n  File \"/usr/local/lib/python2.7/dist-packages/tastypie/resources.py\", line 406, in dispatch_detail\n    return self.dispatch('detail', request, **kwargs)\n\n  File \"/usr/local/lib/python2.7/dist-packages/tastypie/resources.py\", line 427, in dispatch\n    response = method(request, **kwargs)\n\n  File \"/usr/local/lib/python2.7/dist-packages/tastypie/resources.py\", line 1332, in patch_detail\n    self.update_in_place(request, bundle, deserialized)\n\n  File \"/usr/local/lib/python2.7/dist-packages/tastypie/resources.py\", line 1345, in update_in_place\n    self.is_valid(original_bundle, request)\n\n  File \"/usr/local/lib/python2.7/dist-packages/tastypie/resources.py\", line 991, in is_valid\n    errors = self._meta.validation.is_valid(bundle, request)\n\n  File \"/var/www/novella-django/novella/novella/api/validation.py\", line 55, in is_valid\n    data[field] = self.uri_to_pk(data[field])\n\n  File \"/var/www/novella-django/novella/novella/api/validation.py\", line 29, in uri_to_pk\n    for one_uri in uris:\n\nTypeError: 'Bundle' object is not iterable\n"}

I'm not really sure whats wrong and I can't seem to find this bug anywhere else.

A: Sounds like your validation is trying to iterate through your foreign key bundles with this line:
for one_uri in uris:

That's where the "Bundle" object is not iterable is coming from. If you want to iterate over those fields as resource_uris, remove full=True from those FK fields.

If you want to keep them as full=True, you'll need to update your validation to either handle bundles for those fields or exclude them from the validation by using exclude in your form Meta class:
class ModelFormValidation:
    ...

    class Meta:
        exclude = (
            authors,
            posts,
            cover_photo
        )


text:
Q: How to manage Agile developers working with traditional (serial) business persons? Good afternoon,
My work environment has some problems. Our IT team is trying to be more agile, but we're not really getting buy-in from the business. They attend our daily stand-ups and sprint reviews, and they help with sprint planning, but then they turn around and do 4 months of requirements gathering for a project before moving forward with a (mostly) serial development style. The sprint goals are things like "get XX% closer to release".
For the IT team, they've turned the Sprints into a sort of death march. We end a Sprint one day and start a new Sprint the very next day. There's no reflection or changes done between sprints, only during.
Having never done any of the agile methodologies before, I haven't had a very pleasant introduction to them. So my questions are:
1) Should there be some time (perhaps a week or so) between sprints to do the reflection/introspection/changes/etc.? Or are back-to-back-to-back sprints the norm?
2) Is there any chance for survival for an agile team with no agile business counter-parts? If not, are there some transitional methodologies or even tips for moving the business towards an iterative if not necessarily agile mindset?
3) Should your entire team be on every sprint? We have almost 20 programmers on a single sprint but working on completely different projects (typically teams of 3-5, sometimes larger). Is it normal to have a single sprint or should we be trying to manage multiple independent sprints? Should we be trying to keep the multiple sprints in concurrent lockstep or should their timetables be allowed to overlap and be flexible?
Any thoughts or advice is appreciated. This is my first time coming over from SO for a question, so please let me know if there are better ways to phrase these kinds of questions (faq was rather helpful, but still not sure I'm following it perfectly). Thanks!

A: 1) Usually you can just review the last sprint in one meeting, plan the next and begin it. Particularly review how accurate task estimates were and feed this into estimates for the next sprint. You could delay the next sprint if you need to wait for customer feedback from the results of the previous one and you think that feedback will influence the tasks for the next sprint.
2) It won't make it easier, but the team can of course succeed. Your comment

The sprint goals are things like "get
  XX% closer to release"

is a bit worrying as ideally you want to be including demonstrable features/functionality as the goals in a sprint.
3) You say there are 3-5 completely different project. If they are unrelated i.e. for different products, there is no need to have them in sync, but they should each be treated as independent sprints. It sounds like your teams  for each sprint are probably a fine size.

A: 1) Should there be some time (perhaps a week or so) between sprints to do the reflection/introspection/changes/etc.?
No.  A week?  You must be crazy.  2 hours is the limit.

Or are back-to-back-to-back sprints the norm?

Absolutely.  Otherwise, you're spinning your wheels.

Is there any chance for survival for an agile team with no agile business counter-parts?

Business is never "Agile".  Agile is something you do.  Not them.  Indeed, never them.  They just ask for random stuff.  You manage it.

If not, are there some transitional methodologies or even tips for moving the business towards an iterative if not necessarily agile mindset?

None.  You decompose the requirements into sprints.  It's your discipline.  Not theirs.

Should your entire team be on every sprint?

Yes.

We have almost 20 programmers on a single sprint but working on completely different projects (typically teams of 3-5, sometimes larger).

What?  That's not a team.  That's a bunch of teams.  4 or maybe 5 separate teams.

Is it normal to have a single sprint or should we be trying to manage multiple independent sprints?

No idea what you're talking about.  But, since you seem to have 4 or 5 teams all mashed together, it's clear that you're going to have massive confusion.

Should we be trying to keep the multiple sprints in concurrent lockstep or should their timetables be allowed to overlap and be flexible?

Each team -- and the team's sprints -- are the team's problem.  No one else's.
Some folks things that big projects like this should be a "Scrum of Scrums".  Teams set their goals, build their things.  Representatives from each team get together periodically to coordinate the teams to get to mutually beneficial releases.

A: I'm sorry that you are in such an obviously dysfunctional organization.
If you wish to have any ability to measure progress, it is absolutely imperative that you plan in terms of 100% complete milestones.  If there is ever any room for honest disagreement about what a particular milestone is, the natural tendency is for the person doing the work to take the most optimistic possible interpretation on how much they have done, and the person hearing what they say to hear that in the most optimistic possible ways.  This means that the news gets better and better as you go up the chain, leading to a complete disconnect between reality and what the top hears.  http://www.davar.net/HUMOR/JOKES/SHIT.HTM is a humorous, and entirely realistic take on this phenomena.
How bad is this disconnect?  Consider this.  In the average project, the actual time taken to completion (if you ever get there) averages double the original estimates.  But no matter how much the project is delayed by, typically the people at the top don't get the first hints that the project is behind until about 2 weeks before the due date, as that is the point at which the disconnect between expectations and reality can no longer be hidden.
Therefore the XX% closer goals are not actual requirements.  Literally your team should refuse to accept those as actual requirements.  It is your job to educate them that you need concrete, actionable tasks, and in planning they will need to be broken down into specific tasks that can be estimated as taking at most a few hours.
Secondly, as others have said, you absolutely need to break down your team into smaller units, which probably will need to be on different schedules.  Research indicates that a single software team of 20 people working on one thing can accomplish about as much as a team of 5-8 people.  (I ran across this surprising fact in Steve McConnell's excellent book Software Estimation.)
Thirdly it is a really big red flag that it feels like a death march.  If it feels like a death march, it probably is a death march.  Software developers tend to be at peak performance when they are working 35-40 hours a week.  (I got that figure from Steve McConnell's Rapid Development.)  Working longer hours can get temporary performance increases, at the cost of long-term reduction in performance.  A large project is a marathon, you need to pace yourself.
Fourth there really needs to be a rhythm to a sprint.  When I worked in a team doing scrum, we found it very useful to divide each sprint into two sections that we called "long focus" and "short focus".  During "long focus" we did heads down software development on the tasks that had been agreed on for that sprint.  During "short focus" we did all of the necessary stuff we needed to that involves lots of interruptions and task switching.  So that was when we did QA, bug fixing, various meetings, estimating tasks for the next sprint, and finally agreed on what would and wouldn't be in the next sprint.  This worked very well for us because a lot of software development can only be done when you are in the "zone", which generally doesn't start until you have been doing one task for at least 15 minutes with no interruptions.
If you follow a rhythm like that then you get another win out of having different schedules between teams: your QA people can always work on whatever team is currently in QA, which keeps them with a constant level of work.
Good luck, and be aware that without support from the top you may be unable to fix the dysfunction.  If that is the case then your best realistic option may be to find a healthier organization to be part of rather than trying to make your organization into something that it is not going to become.

A: *

*My experience is that sprints are generally back to back with some loss of time to do retrospectives, demonstrate functionality, and plan the next sprint.  For example, the last day of a sprint would often be considered a write-off as there would be 3 meetings that spanned that day typically so a 2 week sprint equaled 9 working days.  The retrospective at the end of a sprint can bring changes to be tried in the next sprint that starts almost immediately in a sense.

*A chance yes but rather small as if you use Scrum there should be a product owner that is approved by management to direct prioritization of how urgently are some stories compared to others.  There has to be some understanding of what responsibility they have though another part is that the "XX% closer to release" is a rather poor metric to my mind as this tends to not include bugs and other last minute issues that are nearly impossible to properly estimate in my limited experience.  There is also something to be said for understanding when changes to priorities can be known to the team and used in planning a sprint.  Management buy-in is crucial as if they don't understand what you are doing it may be like trying to make deliveries while walking on a stationary tread mill.  While your legs are moving, you aren't getting any closer to dropping off anything.

*Not necessarily but sometimes that can be the case.  The key is to know how much is each developer allocated to the project and keeping this consistent so that when there is a velocity from the first few initial sprints, this is useful in predicting future velocities rather than being useless as the number of man hours on the projects bounces around too much to easier estimate how many points can be done in a sprint.  Each project should have its own set of sprints if the project is big enough to span into weeks of work.
Good luck on educating management in terms of what they have to do and how this works as that may be your big hurdle to overcome here.

A: If your project is utilizing Scrum, then you should have a Scrummaster whose job it is to educate all parties on how exactly the process is supposed to work.  If you are doing Scrum, sounds like the scrummaster is not doing his/her job, since having no buyoff from the business side of the project is a HUGE (and not uncommon) roadblock.

A: Tell the program people to screw it if they say get XX% closer to complete.  TELL them you will finish requirent X, Y and Z by such and such a date. If they want to contract the schedule ask them what they want to remove, if they balk tell them they either remove pieces or add time.  Saying get it done or else won't do a bit of good.  If they push assign your project manager code to complete that sprint.  Bear in mind Agile is a team effort.  If the project management people aren't working 12 hours days they better like hell be there fetching pizza and sodas for the people that are and any bonus for getting things done on or ahead of schedule better go to the people that did the work too.  Tell upper mgmt if you have too, they are probably the ones that pushed Agile on you while not training the project management people.
Track your progress, make adjustments then pick the next requirements to meet.  If the project isn't going to be delivered until the whole thing is done, don't worry about priority of features, worry about what features are important to you that they be done for future pieces.  You have to take ownership of this.  It should not be a death march either.  Scrum projects should be measuring the amount of work you can complete in the duration of a NORMAL sprint.  That 10 (or 9 as noted above) normal 8 hour working days.
One thing I heard at the Agile conference a few years ago was that your team is like a factory and it can product X amount of cars (or in your case features) per sprint.
Also your sprint teams should be 3 to 5 people not 20.  That could be part of the issue.  Each team should be picking their stories (requirements line items if you like) and working to those.  They should scrum separately, but meet large group on some basis to share ideas.
When managing these types of teams it may be better for the managers to scrum separately to determine what cross team tasks are needed and put the right people in touch.  A 20 person standup is monotonous and boring for those involved.


text:
Q: Failed to instantiate sessionFactory From org.springframework.orm.hibernate5.LocalSessionFactoryBean We are using spring and hibernate in our application i create LocalSessionFactoryBean object then @autowire SessionFactory in Repository As Follow : Create LocalSessionFactoryBean in AppConfig
 @EnableCaching
 @EnableAsync
 @EnableTransactionManagement
 @Configuration
 class AppCOnfig extends WebMvcConfigurerAdapter{
 @Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(restDataSource());
    sessionFactory.setPackagesToScan("com.xx.yyy");
    sessionFactory.setHibernateProperties(hibernateProperties());
    sessionFactory.setPhysicalNamingStrategy(new SnakeCaseNamingStrategy());
    sessionFactory.setImplicitNamingStrategy(new ImplicitNamingStrategyLegacyHbmImpl());
    return sessionFactory;
  }
}

In Repository We are Using @autowire annotation as
@Slf4j
@Repository
public class UserRepository {

    @Autowired
    private SessionFactory sessionFactory;

}

We are using hibernate and spring version as below  :
  4.3.4.RELEASE
  5.2.10.Final
But when i start application i got this error :
Error creating bean with name 'sessionFactory' defined in XXX.AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.ArrayStoreException: sun.reflect.annotation.EnumConstantNotPresentExceptionProxy
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1128)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1022)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)

I knew there is some issue when spring tried to got session factory from localeSessionFactoryBean But can not figure out how can we solve it.If anyone have some idea about it please help me out.

A: An EnumConstantNotPresentException is thrown when something tries to reference an enum constant by name when it doesn't exist. The Proxy variant of it is thrown, in my experience, when there's reflection involved. If you debug your app with a breaking point on the EnumConstantNotPresentExceptionProxy(Class<? extends Enum<?>>, String) constructor, you should be able to see the class of the enum and the name of the non-existent constant.


text:
Q: I need help with this error i keep getting when i try to install or do apt upgrade dpkg: error: parsing file '/var/lib/dpkg/status' near line 32239 package 'x11-common':

 end of file during value of field 'Conffiles' (missing final newline)

E: Sub-process /usr/bin/dpkg returned an error code (2)

I am quite new to linux and cant find anything on this issue. Thanks in advance for the help.

A: The text file /var/lib/dpkg/status is used as a database of installed packages. In this file, every line should be terminated by a newline character. The error indicates that it is not the case. This in turn tells us the file is damaged. Maybe Linux froze while an update was running, maybe the hard disk was 100% full (check with df -hl) and the file could not be written. There are probably other reason that could explain why the file is corrupted.
First try to understand what went wrong, in particular make sure you don't have a full disk.
Then, you need to recover from this situation. See this answer.


text:
Q: TClientDataset: Is there a way to make a StringField behave like an IntegerField when setting an index? I want to sort a ClientDataset by a StringField which contains Integers. These Integers are used as item numbers on invoices. When I sort the ClientDataset by that field using a simple index the result is this:
1
10
100
101
11
110
111
12
120
However I'd like them to be sorted like an IntegerField:
1
10
11
12
100
101
110
111
120
Is there a quick way to do this?

A: You don't need to change your existing field to a different type.  Instead, a way to do what you want is to define an ftInteger field on the CDS which is of FieldFind fkInternalCalc.  Then in the CDS's OnCalcFields event, set the field's value by converting the value of your string field to an integer.
The point of setting the calculated field's find tp fkInternalCalc is that the CDS can be indexed on, and hence sorted by, an fkInternalCalc field, unlike an fkCalculated field. So, by indexing your CDS on the added fkInternalCalc field, the records should be appear in their numeric order rather that the alphanumeric order of your string field.
Code:
procedure TForm1.CDS1CalcFields(DataSet: TDataSet);
begin
  if CDS1IntField.IsNull then
    CDS1IntField.AsInteger := StrToInt(CDS1StringField.AsString);
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  i : Integer;
begin
  CDS1.CreateDataSet;
  for i := 1 to 100 do
    CDS1.InsertRecord([IntToStr(i)]);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  CDS1.IndexFieldNames := 'IntField';
end;

A: If you want to sort as integers: by far the best approach is to: change the type to integer.
Yes, it's more work, but hear me out.

Currently you have 2 possibilities: either all your values are currently canonical1 integers, or they are not.
If they are, then you do have a little work to do. You need to change:

*

*The column in the database

*Any foreign key columns containing the same data

*The types of any persisted fields for those columns

*Any code that is expecting string item numbers

And you'll gain the following benefits:

*

*Better performance due to: single op comparisons, less data in memory, narrower keys for B-Tree indexes and reduced heap memory allocations in Delphi for the previous long string objects.

*Less concern about the nuances of strings and string comparison. E.g. unexpected padding.

*And a strong typing guarantee that you'll not unexpectedly have to deal with 'problematic strings'. You raised a concern whether you would "have any negative consequences" due to making the change. I'm not aware of any. However, not making the change does risk the consequence of unexpected non-integer item numbers.

However, if your item numbers are not canonical integers: then trying to sort as integers is already problematic. How would you sort the following item numbers as integers?
'03', '13', '3', 'B2', '  13 ', '3bad'

Martyn's answer would be the best way to go in this situation. Because you retain the original string value, you still have a safe and reliable key. (NB only use the internal calc field for sorting).
Note, you would have to tweak the: CDS1IntField.AsInteger := StrToInt(CDS1StringField.AsString); line to ensure you can set sensible sorting values. Any exceptions raised due to failure to convert some string would lead to nasty problems.
As a bonus, Martyn's answer is safe in the short term before you've investigated the knock-on effects of the larger change. But you may want to schedule time for the 'big job'.

1 The point about 'canonical' integers is subtle but important. Prefixing any number of zero's or spaces to an integer produces a non-canonical duplicate. Consider "3" and "03". As integers they are the same, but as strings they are different.


text:
Q: How to set Bundle Identifier correctly in Xcode 6.1.1 when I am using external charts in C-Objective? I have an iPad application made in Xcode 6.1.1 in which I am using external chart in C-Objective. Everything is working perfectly until I set up Bundle Identifier.
If I want to test it (without error) in simulator I need to have Bundle identifiers to all my parts set like:
Main part...com.Project
Other part...com.Project.SomePart
Chart....com.Project.Chart

Etc.
But in this case if I want to Archive it (for ITunes registering purposes) with this set up there is error:
*"The provisioning profile specified in your build settings ("PROFILE") has an AppID of "com.Project" which does not match your bundle identifier "com.Project.Chart".  Xcode can resolve this issue by downloading a new provisioning profile from the Member Center."*

This error disappear and I am free to archive when a set up my Bundle identifiers like this:
Main part...com.Project
Other part...com.Project.SomePart
**Chart....com.Project**

Etc.
But in this case I can't test it in simulator because of error error:
*An error was encountered while running (Domain = LaunchServicesError, Code = 0)*

Which I found out is because of prefixes.
How should I continue if I want to get my app online at iTunes? Is it key that I can't test it in that configuration which Archive(and validation and submitting) takes?

A: Correct setting of Bundle ID is the usual one with prefix of Bundle ID and with the sufix with dot
BundleID.sufix
The problem was that at my developer account I wrongly created Explicit App ID and it was suppose to be Wildcard App ID because of framework I used.


text:
Q: Calling $this inside Model in Phalcon I need reanimate an old site, that was made by another programmer a long time ago. The site is built on Phalcon and I don't know which versions of PHP are supported.
I'm seeing many errors like:

Using $this when not in object context

It is triggered because in Models many functions calls core functions of Phalcon like $this->session->get('auth'), but it looks like a new version of PHP doesn't allow it.
How can I fix it without a total rewrite of all models?
Is there any other way to call Phalcon's $this in Model?
Or is it not possible?

A: If you add variable $di (factory) to your application
you need to write this :
$this->di->session->get('auth');

A: You are calling a static method, therefore an object has not been created and there IS NO $this.
Static methods are BAD, try and avoid! They're essentially standalone functions hiding inside a class. They're also very annoying to test.


text:
Q: "To call" vs. "to ring" What is the difference between the verbs "call" and "ring" in the meaning of telephoning? For example:

*

*I will ring you back shortly.

*I will call you back shortly.

A: The two words are identical in meaning here. The usage of call is obvious, while the usage of ring simply originated from the noise a telephone makes when you call someone.
Ring is definitely a more informal word, so if in doubt, use call.

A: Ring is very common in Australia and New Zealand, and probably somewhat frequent in the U.K. and Ireland, but call is basically always used in the U.S.

A: I've heard "give * a ring" in the US, but never "ring *"

A: Ring is generally used in the UK, while call is used in the US.  There's no difference in meaning.


text:
Q: The expected-value of the square of Sample Variance. Suppose $X_1, \cdots, X_n$ are i.d.d. samples from population $X \sim N(\mu,\sigma^2)$, and the sample variance is denoted by
$T = \sum_{i = 1}^n \frac{(X_i - \overline{X})^2}{n}$.
I am curious about the expected-value of $T^2$, which is the square of $T$.
Apparently the key problem is what the distribution of $T^2$ is ?
According to my intuition, it may be some kind of F-distribution, but how to prove it ,especially to solve the cross term is the biggest problem that I have encountered.

A: You might now this forumla:
$$
\text{Var}[X] = E[X^2] - E[X]^2
$$
I.e.
$$
E[X^2] = \text{Var}[X] + E[X]^2
$$
The variance is the expected value of the squared variable, but centered at its expected value.
In this case, the random variable is the sample distribution, which has a Chi-squared distribution – see the link in the comment.

A: Working from a random sample $\mathbf X=\{X_1,\dots,X_n\}$ with mutually independent $X_i\sim\mathcal N(\mu,\sigma^2)$, the distribution of the unbiased sample variance
$$
S^2=\frac{1}{n-1}\sum_{i=1}^n(X_i-\bar X)^2
$$
is distributed according to the gamma distribution (shape-rate parameterization)
$$
S^2\sim\operatorname{Gamma}\left(\frac{n-1}{2},\frac{n-1}{2\sigma^2}\right).
$$
Since we are using the rate parameterization of the gamma distribution and $T=\frac{n-1}{n}S^2$ is follows that
$$
T\sim\operatorname{Gamma}\left(\underbrace{\frac{n-1}{2}}_{\alpha},\underbrace{\frac{n}{2\sigma^2}}_{\beta}\right).
$$
To find $\mathsf E(T^2)$ we then write
$$
\mathsf E(T^2)=\int_0^\infty t^2f_T(t)\,\mathrm dt=\frac{\beta^\alpha}{\Gamma(\alpha)}\int_0^\infty t^{\alpha+2-1}e^{-\beta t}\,\mathrm dt.
$$
Substituting $u=\beta t$ then gives
$$
\mathsf E(T^2)=\frac{\beta^\alpha}{\beta^{\alpha+2}\Gamma(\alpha)}\int_0^\infty u^{\alpha+2-1}e^{-u}\,\mathrm du=\frac{\Gamma(\alpha+2)}{\beta^2\Gamma(\alpha)}.
$$
Using the property $x\Gamma(x)=\Gamma(x+1)$ this result simplfies to
$$
\mathsf E(T^2)=\frac{(\alpha+1)\alpha}{\beta^2}=\frac{(n+1)(n-1)}{n^2}\sigma^4.
$$
Note for large $n$ this becomes
$$
\mathsf E(T^2)\sim\left(1-\frac{1}{n^2}+\mathcal O\left(\frac{1}{n^3}\right)\right)\sigma^4.
$$


text:
Q: Pg_dump error in php .postgress 9.1 I can not do the backup because windows throws error and I do not know how to solve it
I need to backup postgres using php and  windows. This is the command used.
**exec('pg_dump --dbname=postgresql://username:root@localhost:5432/sicanar > dbbackup.sql',$output);
print_r($output);**

But windows throws this error
The entry point for the icon_open procedure is not found in the C: \ WINDOWS \ System32 \ libintl.dll library
this error

A: I guess you copied the pg_dump.exe from an installation folder to some other location but did not copy all the dll's it needs. Now windows is trying to find them but find's a wrong version that is missing a function.
You will very likely need to copy the following dll's from the folder pg_dump was originally in
postgresql 9.4: intl.dll, libeay32.dll, libintl.dll, libpq.dll, ssleay32.dll and zlib1.dll.
postgresql 9.5 and 9.6: libeay32.dll, libiconv-2.dll, libintl-8.dll, libpq.dll, ssleay32.dll and zlib1.dll.


text:
Q: Ice cream, cones, and toppings. How many ways can I make the order? There are five orders of ice cream. Each ice cream order has a distinct cone, distinct ice cream flavor, and distinct topping. I have to put on a cone before I can put on ice cream, and I have to put on ice cream before I can put on the topping. I can arrange the orders multiple ways. For example, I can put out all three cones, then put on the ice cream then the toppings. Or I can just build each individual order up one by one. How many sequences can I fulfill the 5 orders? (I can only do 1 action at a time)
So my thoughts are: I have 5 options in the beginning (since there are 5 distinct cones) (So 5 choose 1), then when I choose a cone, I can put on that specific cone's ice cream, or put up another cone. So there are another 5 options. But I'm stuck on what to do from here.

A: So we can think your question like this: we can choose a incomplete order, then build the next item to be put on the order, then choose a incomplete order, then build the next item to be put on the order, etc.
So as there are $5$ orders, we can number them $1, 2, 3, 4, 5$. Then we have $3$ $1$'s, $3$ $2$'s $3$ $3$'s $3$ $4$'s and $3$ $5$'s. Then we have $\frac{(3\times5)!}{{3!}^5}=168168000$ ways. That is a lot!


text:
Q: avoid nested subscribe if there is a forkjoin inside Here is my code in angular
this.service.save(body).subscribe(
    resp => {
       this.dialog.confirmation({
          message: 'save object successfully!'
       })
       .subscribe((ok) => {
            if(ok) {
               this.pro.status = resp.status;
            this.loadingData(resp);
            const s1 = this.service.getSummary(this.id);
            const s2 = this.service.getCost(this.id);
            forkJoin([s1, s2]).subscribe([r1, r2]) => {
               this.view = r1;
               this.list = r2;
            }
          }
        });
     }
);

So there are many levels of subscribe. Not only it is ugly also the result is wrong and I can't not find it out by debugging. How can I rewrite it with rxjs operators?

A: You can simplify it using the RxJS operators, like the following:
// import { EMPTY, forkJoin } from 'rxjs';
// import { map, mergeMap } from 'rxjs/operators';

this.service
  .save(body)
  .pipe(
    mergeMap((result) =>
      // Merge the main observable with the dialog confirmation one..
      // and map it to an object that contains the result from both observables.
      this.dialog
        .confirmation({ message: 'save object successfully!' })
        .pipe(map((confirmed) => ({ result, confirmed })))
    ),
    mergeMap(({ result, confirmed }) => {
      if (confirmed) {
        this.pro.status = result.status;
        this.loadingData(result);
        const s1 = this.service.getSummary(this.id);
        const s2 = this.service.getCost(this.id);
        return forkJoin([s1, s2]);
      }
      // Don't emit any value, if the dialog is not confirmed:
      return EMPTY;
    })
  )
  .subscribe(([r1, r2]) => {
    this.view = r1;
    this.list = r2;
  });

Note: To handle the memory leaks, it's highly recommended to unsubscribe from the observable when you don't need it anymore, and this can be achieved based on your use cases, such as assigning the subscribe function result to a Subscription variable and calling unsubscribe in ngOnDestroy lifecycle hook, or using a Subject with takeUntil operator and calling next/complete functions in ngOnDestroy.
And here is how to use the unsubscribe method for example:
// import { Subscription } from 'rxjs';

@Component({...})
export class AppComponent implements OnInit, OnDestroy {
    subscription: Subscription
    ngOnInit(): void {
      this.subscription = this.service.save(body)
        // >>> pipe and other RxJS operators <<<
        .subscribe(([r1, r2]) => {
          this.view = r1;
          this.list = r2;
        });
    }
    ngOnDestroy() {
        this.subscription.unsubscribe()
    }
}

You can read more about that here: https://blog.bitsrc.io/6-ways-to-unsubscribe-from-observables-in-angular-ab912819a78f

A: This should be roughly equivalent:
this.service.save(body).pipe(

  mergeMap(resp =>
    this.dialog.confirmation({
      message: 'save object successfully!'
    }).pipe(
      // This filter acts like your `if(ok)` statement. There's no
      // else block, so if it's not okay, then nothing happens. The
      // view isn't updated etc.
      filter(ok => !!ok),
      mapTo(resp)
    )
  ),

  tap(resp => {
    this.pro.status = resp.status;
    // If the following line mutates service/global state,
    // it probably won't work as expected
    this.loadingData(resp);
  }),

  mergeMap(_ => forkJoin([
    this.service.getSummary(this.id),
    this.service.getCost(this.id)
  ]))

).subscribe([view, list]) => {
  this.view = view;
  this.list = list;
});


text:
Q: database unconfirmed deadlock t-sql 2005 For instance, there exists table A and table B, and i need to process an update in A and then B and I decide to table lock both them during use (as demanded by my architect). Simultaneously, another procedure is called which table locks B, then locks A.
Will this transaction complete? I have a feeling its a deadlock, quite sure of it as it's not releasing any resources...

A: Yes it is a possible deadlock.
The deadlock scenario is
Your task locks A
Other task locks B
then
Your task tries to lock B but it can't as you have the lock
and
other task tries to lock A but it can't as you have it.
So one of these tasks has to fail/rollback so the other can complete. Depending on RDBMS used the db will choose one of these to terminate.
Often the solution is for a guideline that you must lock resources in the same order in all processes usually this has to be manualy enforced.

A: Yes. This approach will end in a classic cyclic deadlock as mentioned here
Using TABLE level lock for an update is an Overkill. What is the rationale behind doing this ? If you have the correct indexes, locks will be acquired at the key level, which helps multiple processes concurrently access the tables in question.
Still it is a best practice to access the tables in the same order when possible.


text:
Q: looking for file catalog application (GUI) I'm looking for a Linux application to catalog the files on my many external HDs and search them. I'm using Ubuntu, so i prefer a normal deb in the repositories but i can't find one. After some research by Google, I find no proper application - does any GUI exist ?
See this old forum entry : "printable file catalog or index for (external) USB and flash drives" ( https://www.linuxquestions.org/questions/linux-software-2/printable-file-catalog-or-index-for-external-usb-and-flash-drives-829171/ ) -- here are some key texts of this page :

Question:
I'm very surprised that there is no [relatively] mature application to
address these issues ?! Like diskettes of years past, we now
accumulate external drives that are USB, Firewire, e-SATA, or flash.
Unlike diskettes, these new drives hold hundreds or thousands of
files. It is so easy (and inexpensive) to grab a drive a copy files
that it is trivial to accumulate duplicates or more instances of the
same files. All of this makes a catalog very valuable AND makes
duplicate identification all the more so.
Answer:
It is possible that this (making a catalogue with find
/media/Disk1 * > ~/Indices/Disk1_index ) and then searching for a
filename in those catalogues with grep filename ~/Indices/* is so
trivial from the command line, that no one has bothered to develop
anything more complicated than gwhere (which seems to work, though I
only used it the once). Duplicates are another matter altogether: Same
filenames does not necessarily mean that the contents of those files
are the same. Conversely, different filenames does not necessarily
mean that the contents of the files are different.
Remark:
There are several *nix utilities for dealing with this sort of
problem, fdupes comes to mind, but there are others. No application
could compete with the method "find for indexing, grep for search"

I tried "gwhere" but it's limited and slow and its last version is of 2007. Most file catalog utilities i find are for Windows ..
Must Linux users really learn to use command line functions like "find" and "grep" to do all kinds of queries ? Eg. in a search, we often want to exclude some file types or include only images, search by date / period, etc.
Someone must have created some nifty GUI which sets all proper find & grep parameters as our options ? Does anyne know of a good modern Linux GUI application to catalog and search files ? maybe using a DB, not some big CSV / XML file ?

A: Tracker

Description from Tracker's Homepage
Tracker is a search engine, search tool and metadata storage system.
It allows you to find the proverbial needle in your computer's haystack as well as providing a one stop solution to the organisation, storage and categorisation of your data. Some plugins allow you to use Tracker in GNOME applications, for example: Totem and Nautilus.
Installation
sudo apt install tracker-gui

Getting started
You can configure Tracker by running tracker-preferences and access the simple search GUI by running tracker-needle. To index files you need to start tracker daemon -s, I recommend adding this command to your Autostart Applications (System → Preferences → Startup Applications). For more information browse the website and read tracker --help. An alternative GUI for Tracker is catfish, see this answer.

A:  Catfish

Description from Catfish's homepage and launchpad page
Catfish is a GTK+ search utility written in Python. Its search is powered by locate and find behind the scenes, with search suggestions provided by zeitgeist. The advanced options allow filtering by date and file type. The interface is intentionally lightweight and simple, using only GTK+. Catfish can be used as a GUI for tracker and doodle as well.
Installation
sudo apt install catfish

A:  DocFetcher

Description from DocFetcher's homepage
DocFetcher is an Open Source desktop search application: It allows you to search the contents of files on your computer. — You can think of it as Google for your local files. The application runs in Java on Windows, Linux and OS X, and is made available under the Eclipse Public License. This way it's portable and can very well be stored externally.
For more information there's the homepage, the wiki and the forum.
Installation

*

*Install Java: How do I install Java?

*Download DocFetcher from sourceforge.net

*Unzip the archive using your archive manager or
unzip docfetcher-*-portable.zip

*Navigate inside the extracted directory and run the program with
./DocFetcher-GTK3.sh

or if DocFetcher doesn't start or the GUI behaves strangely:
./DocFetcher-GTK2.sh


text:
Q: vbulletin 4 Search doesn't work We recently upgraded to PHP 5.3 (from 5.2) and MySQL 5.1 (from 5.0) and did a database restore on vbulletin 4 forum. After these search stopped working at all.
No matter what you search, you end up on /forum/search.php?searchid=-2139739119 with no results. ?do=getnew, ?query=your+keyword, advanced search etc. none of these work. all loads that url with negative searchid and says "Sorry - no matches. Please try some different terms."
What we tried: rebuilded the search index via command line, disabled plugin system, cleared up post cache etc. none of these worked.
What may be the cause to this problem?
Thank you very much for any input.

A: 1.
Please check if Zend Guard is installed. Many times it causes problems with the vBulletin search. If it's installed, try to remove it. On your php.ini file, remark this extension as comment, just like that:
 ;[Zend]

 ;zend_extension="/usr/local/Zend/lib/Guard-5.5.0/php-5.3.x/ZendGuardLoader.so"

2.
If that didn't solved the problem, try to recompile the PHP.


text:
Q: No module error when module is installed I've been using Think Python to learn programming over the last few days. Today I got to chapter 4 when it starts talking about needing Swampy, a package (correct term?) used to teach, in this chapter, interface design.
So, getting to my issue, the first bit of code I'm told to enter is
from swampy.TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
wait_for_user()

When I run it, I get the following error
Traceback (most recent call last):
File "/Users/dylanevans/Documents/Code/Python/TurtleWorld.py", line 1, in <module>
from swampy.TurtleWorld import *
ImportError: No module named swampy.TurtleWorld

I have installed and uninstalled swampy using pip and distutils, swampy is in site-packages and when I ask the interpreter what modules are installed, swampy shows up. I just don't see why I'm getting the error.
Also, my PYTHONPATH has '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/swampy' at the end. Although it does have it twice, I don't know whether that's important.
Any help would be greatly appreciated.
Thanks

A: Open up a terminal and type env | grep ^PYTHONPATH hopefully you get something like this:
PYTHONPATH=/python/path/with/write/access:/another/python/path

Select one of the paths you have write access to and that will be OURPYPKGPATH=/python/path/with/write/access
If no such PYTHONPATH exists we will make our own in our home directory and ensure python can see it in future:
mkdir ~/.ourPyPkgPath
echo 'export PYTHONPATH=$PYTHONPATH:~/.ourPyPkgPath' >> ~/.profile

And in this case we will use OURPYPKGPATH=~/.ourPyPkgPath
Now to install swampy
easy_install -d $OURPYPKGPATH 'http://pypi.python.org/packages/source/s/swampy/swampy-2.1.1.tar.gz'

Now it should be just a case of either source ~/.profile or logging out and in again, in order to set the PYTHONPATH environmental variable.

A:
Also, my PYTHONPATH has
  '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/swampy'
  at the end. Although it does have it twice, I don't know whether
  that's important.

Did you add it there manually? You should modify PYTHONPATH if you install packages in non-standard locations - in other words, if you don't use pip or easy_install but want the package to be available to Python globally.
To eliminate such headaches, it is recommended to use a virtual python environment, which you can create using virtualenv. Once you have virtualenv installed:
burhan@lenux:~$ virtualenv --no-site-packages swampy
The --no-site-packages flag is deprecated; it is now the default behavior.
New python executable in swampy/bin/python
Installing distribute.............................................................................................................................................................................................done.
Installing pip...............done.
burhan@lenux:~$ source swampy/bin/activate
(swampy)burhan@lenux:~$ pip install swampy
Downloading/unpacking swampy
  Downloading swampy-2.1.1.tar.gz (46Kb): 46Kb downloaded
  Running setup.py egg_info for package swampy

Installing collected packages: swampy
  Running setup.py install for swampy

Successfully installed swampy
Cleaning up...
(swampy)burhan@lenux:~$ python
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from swampy.TurtleWorld import *
>>> quit()
(swampy)burhan@lenux:~$

A: Have you installed the swampy module? If not, follow these instructions.
To run a standalone script, you can put your code inside the following block:
if __name__ == '__main__':
    world = TurtleWorld()
    bob = Turtle()
    wait_for_user()

This tells python to execute the code if the script is being directly called. So if you instead had this in a function like swampFunction and you called it from a different script, the above block wouldn't run.


text:
Q: Oracle before delete trigger I have two tables
army

*

*name VARCHAR(50) PRIMARY KEY

*number_of_soliders INTEGER

soldier

*

*soldier_id INTEGER PRIMARY KEY

*army_name VARCHAR(50) REFERENCES army(name)

Now, I need to create trigger, which would work as ON DELETE CASCADE. The problem is, that I have already existing trigger for soldier, which automatically updates number_of_soldiers for his army and if i just put there ON DELETE CASCADE, it will result in a error, because when I delete the army, the trigger can't reference the number_of_soliders back.
So the task is to create trigger, which will delete all soldiers of the army before the army itself is deleted. I have tried:
CREATE OR REPLACE TRIGGER TRG_DELETE_SOLDIER
    BEFORE DELETE ON army
        FOR EACH ROW
BEGIN
    DELETE FROM soldier WHERE army_name = :old.name;
END;

Hovewer, this results in an error table is mutating, trigger may not see it on table operates, M:N table which references Soldier ID (ON DELETE CASCADE) and Weapon ID. However, the trigger does not touch this table, nor the second one for updating number_of_soldiers.
Any ideas what could be wrong?

A: May I suggest to use on delete cascade with your foreign keys on your tables instead of solving this with a trigger?
alter table soldier
add constraint fk_soldier
  foreign key (army_name)
  references army(name)
  on delete cascade
;

If you already use on delete cascade on this constraint, then maybe you forgot it on the weapon_id, which you also mention in your question.
NOTE 1: please consider using a numerical primary key for your army table and the foreign key. You are up to big trouble if you want to change the army name and need to update all child tables as well.
NOTE 2: you don't have to store the number of soldiers in your army table because you can let the database calculate that. Do you have a specific reason to store it redundantly?

A: Storing and maintaining number_of_soldiers in the parent table is awkward and can break if multiple sessions insert/delete soldiers for the same army at the same time. If you don't do that then you don't need soldier-level triggers to update the army table, and can go back to ON CASCADE DELETE without a trigger on the army table either. The number of soldiers for each army can be found by joining the tables:
select a.name, count(s.soldier_id) as number_of_soldiers
from army a
left join soldier s on s.army_name = a.name
group by a.name;

db<>fiddle demo. (That query can of course be stored as a view; which could be materialized if necessary.)
But for the sake argument, if you are stuck with the table column maintenance and need the trigger to clean up, an option is to selectively bypass the soldier-level trigger, using a when clause and an environment context value.
For example, you could add calls to dbms_application_info.set_client_info (or module, or action - whatever make most sense), with a value that makes sense for you to indicate why the soldier-level trigger should not fire; something like (with a not-very-helpful value):
CREATE OR REPLACE TRIGGER TRG_DELETE_SOLDIER
    BEFORE DELETE ON army
        FOR EACH ROW
BEGIN
    DBMS_APPLICATION_INFO.SET_CLIENT_INFO('CASCADING');
    DELETE FROM soldier WHERE army_name = :old.name;
    DBMS_APPLICATION_INFO.SET_CLIENT_INFO(null);
END;
/

Then in the soldier-level trigger test for that value:
CREATE OR REPLACE TRIGGER trg_decrement_army
BEFORE DELETE ON soldier
FOR EACH ROW
WHEN (sys_context('userenv', 'client_info') is null
   OR sys_context('userenv', 'client_info') != 'CASCADING')
BEGIN
  UPDATE army SET number_of_soliders = number_of_soliders - 1
  WHERE name = :old.army_name;
END;
/

If the context value has been set by the army-level trigger, then soldier-level trigger won't run because the when condition is not met. Otherwise it will still  run and decrement the soldier count.
db<>fiddle
But this is still not recommended...


text:
Q: Programmatically change a shape's colour from a range How would I programmatically change the colour of a shape I have drawn based on a colour range?  My shape can have a value between 0 and 1 which defines its colour: full red (0)  to full green (1), with white as the mid range.  Please see the image link for the colour transition style.
http://combinationstudios.com/static/colour-range.png
Thanks,
Ben

A: Well if you are working with input (like 1.2 or so) You could link that input to the RGB value of your color range. With a formula I think you should achieve that.
Also in what are you programming?
grtz Robin

A: You are looking for gradients. Here is Apple documentation on how to use them.
In your case, you will need to use three color components (red, white and green) and not only (red and green).


text:
Q: Ricci flow reference with pictures I'm going to talk about the singularities of the Ricci flow for a group of physics students on Monday!
To create a PowerPoint, I need a text or paper that contains photos and figures to raise the intuition of the subject, because they have studied physics and understanding of abstract concepts is a bit difficult for them!!
Can someone introduce me a reference that has these features?
Thanks a lot!

A: There are some really fine pictures of different aspects of singularities of Ricci flows in these lecture notes  of Peter Topping.
Good luck with your lecture!


text:
Q: JsonConvert.Serialize performance in F# I create a record type as follows:
type CombEmp =
    {
        empid:int
        empname:string
        email:string
    }

let defCombEmp:CombEmp =
    {
        empid = 0
        empname = ""
        email = ""
    }

I then create record instances:
let chrE1 = {defCombEmp with empid = 100; empname = "Wayne Rooney"; email = "wroo@mun.com"}
let chrE2 = {defCombEmp with empid = 100; empname = "Wayne R"; email = "war@mun.com"}
let chrE3 = {defCombEmp with empid = 100; empname = "Wayne R"; email = "rooney@mun.com"}

Then I create a list of 65-70 records using above instances as so:
let hrLst = [|chrE1;chrE2;chrE3;chrE1;chrE2;chrE3;chrE1; ...... |] |> Array.toList

I have now written code as given below.
The function GetByteCount gets the size of serialized data (using NewtonSoft here).
The function loop1 creates a long list of around 500k length using above hrLst.
The function loop2 reduces the input sequence by 1000 in every iteration and calls GetByteCount for the remaining list
let GetByteCount data = //can improve this algorithm?
    let stopWatch = System.Diagnostics.Stopwatch.StartNew()
    let x = data
            |> JsonConvert.SerializeObject
            |> Encoding.UTF8.GetByteCount
    stopWatch.Stop()
    Console.WriteLine("time reqd: " + stopWatch.Elapsed.TotalMilliseconds.ToString() + " milliseconds")
    x

let PerfTestLoop() =
    let rec loop1 ctr l =
        if ctr%100 = 0 then Console.WriteLine("" + ctr.ToString())
        match ctr with
        |500 -> l
        |_ ->
            let l2 = l @ hrLst
            loop1 (ctr+1) l2
    let l = loop1 1 hrLst
    let len = l.Length
    let s = l @ l |> List.toSeq
    Console.WriteLine("input length: " + (Seq.length s).ToString())
    Console.WriteLine("Start Measuring ..")
    let stopWatch = System.Diagnostics.Stopwatch.StartNew()

    let rec loop2 ctr s =
        match ctr with
        |100 -> s |> GetByteCount
        |_ ->
            let news = Seq.skip 2000 s
            let size = news |> GetByteCount
            loop2 (ctr+1) news
    let x = loop2 1 s

let res =  PerfTestLoop() // becomes slow gradually

Observation is that the time taken for execution of GetByteCount in each iteration of loop2 goes on increasing even though the size of the sequence is reducing! Why is this happening? In Task Manager, the CPU and Memory usage remains steady. Is there any other way to find the byte count of the data or to reduce the time required for executing GetByteCount somehow?
If in loop2 I remove the Seq.skip line and use the same sequence in each iteration then the time required is similar for each iteration and doesn't vary much.

A: There are many possible improvements to this code, but the main problem here is not understanding when to choose a list, array or seq based on their relative pros and cons in semantics and performance.
An F# list is an immutable singly linked list which is fast at quickly adding and removing items from the front. It's not fast at concatenation (the @ operator), or accessing items at a certain index.
An F# array is a .NET array: it's mutable, and has fast index access etc. However, most F# functions for working with arrays will avoid mutation and make copies.
A seq is a .NET IEnumerable<T>. It is a sequence that you can enumerate through from beginning. The values are calculated as they are needed by the sequence consumer and may be expensive to compute. Each value could depend on previous values depending on the implementation of the seq, which is why if you create a new sequence with skipped values and pass it somewhere else, the new call site still needs to re-evaluate the skipped values in order to get the ones that it will actually use. One way around this in F# is to use Seq.cache. This will turn a normal seq into one which caches each item as it's evaluated so that repeated access does not cause recalculation.ver, most F# functions for working with arrays will avoid mutation and make copies.

So why do you need to use a seq in the first place? You have a list to start with, which is not lazy and therefore you're holding all this data in memory. You do let s = l @ l |> List.toSeq. Changing this to List.toArray and using Array.skip later on will probably make this much faster.
It would probably also help to change all of your lists to arrays too, since you're not making use of the benefits of lists. If you keep hrLst as an array then you can remove loop1 entirely and just do this: Array.replicate 500 hrLst |> Array.concat

In general, I recommend that you become very familiar with the F# collections: list, array, seq, map and set. Browse the functions in these modules and their documentation as they will be useful in almost all F# code. The built in functions will usually remove the need to use recursion and result in simpler code. I suspect that loop2 could also be replaced with some use of Array.chunkBySize but it's not clear to me what your code is trying to do.


text:
Q: Custom Settings and Rounding in Formulas I have some formulas that use values stored in custom settings.   For example
If(X < custom setting-y && x >= custom setting , 'foo', 'bar') My formula seems to be fine and my custom setting values are correct but I am getting bar instead of foo.
    If(Email_Open_Rate__c >= $Setup.health_check_console__c.Email_Open_Rate_A_Value__c, 'A',
If(Email_Open_Rate__c < $Setup.health_check_console__c.Email_Open_Rate_A_Value__c && Email_Open_Rate__c >= $Setup.health_check_console__c.Email_Open_Rate_B_Value__c, 'B',
If(Email_Open_Rate__c < $Setup.health_check_console__c.Email_Open_Rate_B_Value__c && Email_Open_Rate__c >= $Setup.health_check_console__c.Email_Open_Rate_C_Value__c, 'C',
If(Email_Open_Rate__c < $Setup.health_check_console__c.Email_Open_Rate_C_Value__c && Email_Open_Rate__c >= $Setup.health_check_console__c.Email_Open_Rate_D_Value__c, 'D',
'F'))))

When I adjusted the value for C to .199 then my records with a grade of 20% were given a C.

A: The main feature of using nested if statements is that you don't need to recheck all of the previous conditions. Here's a revised version:
If(Email_Open_Rate__c >= $Setup.health_check_console__c.Email_Open_Rate_A_Value__c, 'A',
If(Email_Open_Rate__c >= $Setup.health_check_console__c.Email_Open_Rate_B_Value__c, 'B',
If(Email_Open_Rate__c >= $Setup.health_check_console__c.Email_Open_Rate_C_Value__c, 'C',
If(Email_Open_Rate__c >= $Setup.health_check_console__c.Email_Open_Rate_D_Value__c, 'D',
'F'))))

Your formula looks otherwise correct, as far as I can tell, but this version should avoid any rounding errors, which I suspect may be what caused the situation at hand.


text:
Q: Pkg-config 0.28 did not build on OSX 10.10.2 Recently I clean installed Yosemite 10.10.2
I also installed gcc using
brew install gcc

Now I'm trying to build and install python and openmpi from source because previously I've had problems with gfortran and clang.
So I did
brew install openmpi --build-from-source -verbose
brew install python --build-from-source -verbose

with variables and aliases:
export CC=gcc-4.9
export CXX=g++-4.9
export CPP=g++-4.9
export LD=gcc-4.9
export FC=gfortran-4.9
export HOMEBREW_CC=gcc-4.9
export HOMEBREW_LD=gcc-4.9
export HOMEBREW_CXX=g++-4.9
export HOMEBREW_CPP=g++-4.9
export HOMEBREW_FC=gfortran
alias cc=gcc-4.9
alias gcc=gcc-4.9
alias c++=c++-4.9
alias g++=g++-4.9

Still getting the following error:
In file included from /usr/include/dispatch/dispatch.h:51:0,
             from        /System/Library/Frameworks/CoreFoundation.framework/Headers/CFStream.h:15,
             from /System/Library/Frameworks/CoreFoundation.framework/Headers/CFPropertyList.h:13,
             from /System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h:55,
             from /System/Library/Frameworks/CoreServices.framework/Headers/CoreServices.h:19,
             from gunicollate.c:30:
/usr/include/dispatch/object.h:143:15: error: expected identifier or '(' before '^' token
typedef void (^dispatch_block_t)(void);

/usr/include/dispatch/object.h:362:3: error: unknown type name 'dispatch_block_t'
dispatch_block_t notification_block);

==> Formula
Path: /usr/local/Library/Formula/pkg-config.rb
==> Configuration
HOMEBREW_VERSION: 0.9.5
ORIGIN: https://github.com/Homebrew/homebrew
HEAD: 9bbd6637009256d70b57691c3ad1979ca2bb5916
Last commit: 9 hours ago
HOMEBREW_PREFIX: /usr/local
HOMEBREW_CELLAR: /usr/local/Cellar
CPU: dual-core 64-bit penryn
OS X: 10.10.2-x86_64
Xcode: 6.2
CLT: 6.2.0.0.1.1424975374
Clang: 6.0 build 600
X11: N/A
System Ruby: 2.0.0-p481
Perl: /usr/bin/perl
Python: /usr/bin/python
Ruby: /usr/bin/ruby
Java: 1.6.0_65
==> ENV
HOMEBREW_CC: gcc-4.9
HOMEBREW_CXX: g++-4.9
MAKEFLAGS: -j2
CMAKE_PREFIX_PATH: /usr/local
CMAKE_INCLUDE_PATH: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/libxml2:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/apache2:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/System/Library/Frameworks/OpenGL.framework/Versions/Current/Headers
CMAKE_LIBRARY_PATH: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/System/Library/Frameworks/OpenGL.framework/Versions/Current/Libraries
CMAKE_FRAMEWORK_PATH: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/System/Library/Frameworks
PKG_CONFIG_LIBDIR: /usr/lib/pkgconfig:/usr/local/Library/ENV/pkgconfig/10.10
HOMEBREW_SDKROOT: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk
PATH: /usr/local/Library/ENV/4.3:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/opt/gcc/bin

Error: pkg-config 0.28 did not build

My understanding is that there is a conflict between clang and gcc-4.9 configuration.
I could temporally solve it doing:
brew install pkg-config

So it doesn't build if from source and uses clang configuration.
I see that Xcode is still in the Include and Library path, and I think this prevents linking with gcc-4.9.
How can I install pkg-config using gcc-4.9 only?

A: Problem solved after following this instructions changing:
typedef void (^dispatch_block_t)(void); // this is for clang

To
typedef void* dispatch_block_t;  //this is for gcc-4.9


text:
Q: how to print an object in Golang template like if we could have done in JavaScript renderTemplate(w, "index", map[string]interface{}{
    "ActualQAll": req.URL.Query(),
})

and inside golanghtml
...{{.ActualQAll}}...

But it shows nothing.
how can I print the whole object out like if I could do in javascript by doing JSON.stringify(obj) an object?
Thanks

A: Use fmt.Sprintf function, maybe something like below:
renderTemplate(w, "index", fmt.Sprintf("%s", ActuallQAll))

I'm not sure what exactly the object looks like.


text:
Q: How to make a php array of a mysql_fetch_array while loop At the moment I have a large number of php files, each one with an array statement in the format:
$array1 = array ( array ( 'Husband' => 'bob',
                          'Wife' => 'ann' ),
                  array ( 'Husband' => 'fred',
                          'Wife' => 'donna' ),
                  array ( 'Husband' => 'john',
                          'Wife' => 'mary' ) );

This of course returns from print_r ($array1) the output (A):
    Array ( [0] => Array (
                  [Husband] => bob [Wife] => ann )
           [1] => Array (
                  [Husband] => fred [Wife] => donna )
           [2] => Array ( [Husband] => john [Wife] => mary ) )

In a separate class file, I access $array1 data, using statements like:
for ($col = 0; $col < sizeof($array1); $col++)
{
  echo $array[$col]['Wife']."
";
}

On the theory that a large number of anything is a database, I am wanting to migrate the data in the multiple php array files array into a MySQL database, and access the MySQL data from my class file.  So I set up the following in MySQL:
CREATE TABLE IF NOT EXISTS `arrays` (
  `id` int(5) NOT NULL auto_increment,
  `husband` varchar(255) collate utf8_unicode_ci NOT NULL,
  `wife` varchar(255) collate utf8_unicode_ci NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

INSERT INTO `arrays` (`id`, `husband`, `wife`) VALUES
(1, 'bob', 'ann'),
(2, 'fred', 'donna'),
(3, 'john', 'mary');

Then I access this MySQL database from PHP:
$sql = "SELECT * FROM `database`.`arrays`";
$link  = mysql_connect ('localhost', 'username', 'password' ) or die(mysql_error());
mysql_select_db ('database', $link) or die(mysql_error());
$result = mysql_query ($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
  $array2 = array ( 'Husband' => $row['husband'],
                    'Wife' => $row['wife'] );
  print_r ($array2);
}

This will produce output (B) like:
Array ( [Husband] => bob [Wife] => ann )
Array ( [Husband] => fred [Wife] => donna )
Array ( [Husband] => john [Wife] => mary )

My question is how do I make a php array of the mysql_fetch_array while loop, so that output B looks like output A.  I want to be able to continue to access the data in my class file in the manner $array[$col]['Wife'], but from the MySQL database.

A: All you need to do here is push the array returned by mysql_fetch_array() onto a larger array using []:
$MultiDimArray = array();

while($row = mysql_fetch_array($result))
{
  $MultiDimArray[] = array ( 'Husband' => $row['husband'], 'Wife' => $row['wife'] );
}

print_r($MultiDimArray);

Now, a few comments:

*

*Please don't write new code with the mysql_* extension, use PDO or MySQLi instead.

*Use mysqli_fetch_assoc() and mysqli_fetch_row()  instead of mysqli_fetch_array() unless you explicitly want numerically indexed keys as well as associative.

*If you name your columns (including capitalisation) the same way as you use the keys in your code, you can simply push the return value of mysqli_fetch_assoc() onto the array.

For example:
while ($MultiDimArray[] = mysql_fetch_assoc($result)) continue;

*

*Don't use or die(mysql_error()); constructs. You should never show the result of mysql_error() (or it's PDO/MySQLi equivalent) in a production environment, and if you must do it for debugging make sure you remove it from your code immediately afterwards.

*Don't use sizeof($array1) directly as a loop condition. It is very inefficient, the only time you should ever do it is if the size of your array may change during the loop. You should call sizeof() once before the loop, store the result in a variable, and compare $col against that variable.

For example:
for ($col = 0, $size = sizeof($array1); $col < $size; $col++)
{
  echo $array1[$col]['Wife']."
";
}

// Also, don't forget you could simply do this:
foreach ($array1 as $row)
{
  echo $row['Wife']."
";
}

A: try to change your code this way
$array2 = array();
$sql = "SELECT * FROM `database`.`arrays`";
$link  = mysql_connect ('localhost', 'username', 'password' ) or die(mysql_error());
mysql_select_db ('database', $link) or die(mysql_error());
$result = mysql_query ($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
  $array2[] = array ( 'Husband' => $row['husband'],
                    'Wife' => $row['wife'] );
}

print_r ($array2);

I believe that is the result you are looking for

A: Maybe try something like:
while($row = mysql_fetch_array($result))
{
  $temparray = array ( 'Husband' => $row['husband'],
                    'Wife' => $row['wife'] );
  array_push($array2, $temparray);
}

print_r ($array2);


text:
Q: Periodically import data from files on Heroku I need to periodically import some data into my rails app on Heroku.
The task to execute is split into the following parts:
 * download a big zip file (e.g. ~100mb) from a website
 * unzip the file (unzipped space is ~1.50gb)
 * run a rake script that reads those file and create or update records using my active record models
 * cleanup
How can I do this on heroku? Is it better to use some external storage (e.g. S3).
How would you approach such a thing?
Ideally this needs to run every night.

A: I have tried exact same thing couple of days back and the conclusion that I came up with was this can't be done because of memory limit restrictions that heroku imposes on each process. (I build a data structure with the files that I read from the internet and try to push to DB)
I was using a rake task that would pull and parse couple of big file and then populate the database.
As a work around I run this rake task in my local machine now and push the  database to S3 and issue a heroku command from my local machine to restore the heroku DB instance.
"heroku pgbackups:restore 'http://s3.amazonaws.com/#{yourfilepath}' --app  #{APP_NAME} --confirm #{APP_NAME}"

You could push to S3 using fog library
require 'rubygems'
require 'fog'
connection = Fog::Storage.new(
    :provider              => 'AWS',
    :aws_secret_access_key => "#{YOUR_SECRECT}",
    :aws_access_key_id     => "#{YOUR_ACCESS_KEY}"
)

directory = connection.directories.get("#{YOUR_BACKUP_DIRECTORY}")

# upload the file
file = directory.files.create(
    :key    => '#{REMOTE_FILE_NAME}',
    :body   => File.open("#{LOCAL_BACKUP_FILE_PATH}"),
    :public => true
)

The command that I use to make a pgbackup on my local machine is
system "PGPASSWORD=#{YOUR_DB_PASSWORD} pg_dump -Fc --no-acl --no-owner -h localhost -U #{YOUR_DB_USER_NAME} #{YOUR_DB_DATABSE_NAME} > #{LOCAL_BACKUP_FILE_PATH}"

I have put a rake task that automates all these steps.
After thing your might try is use worker(DelayedJob). I guess you can configure your workers to run every 24 hours. I think workers don't have the restriction of 30 seconds limit. But I am not sure about the memory usage.


text:
Q: ApplyWebConfigModifications to only one web application and not all the farm I want to apply web.config modifications only on the webapplication i am installing my feature on and not all the web.configs of the farm. i am using SPWebService.ApplyWebConfigModifications , how can i do that? Help pls

A: The feature you use to deploy the modifications should be web app scoped and should have a feature receiver, activating the feature on the desired web app only should do the trick.

A: public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    using (SPSite site = ((SPSite)properties.Feature.Parent))
    {
        SPWebApplication webApplication = site.WebApplication;
        // webApplication.WebConfigModifications.Clear();
        // do modifications, using the feature.GetType().FullName as the Owner

        webApplication.Update();
        webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
    }
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    using (SPSite site = ((SPSite)properties.Feature.Parent))
    {
        SPWebApplication webApplication = site.WebApplication;
        Collection<SPWebConfigModification> entries = webApplication.WebConfigModifications;

        for (int i = entries.Count - 1; i >= 0; i--)
        {
            SPWebConfigModification entry = entries[i];
            if (entry.Owner == this.GetType().FullName)
                entries.Remove(entry);

        }

        webApplication.Update();
        webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
    }
}

Edit
In order to manage your current modifications without going directly in the SQL Server, use this file and copy it inside the folder:
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\ADMIN and access it from http://centraladministration:PORT/_admin/webconfig.aspx
Original sources TheKid blog and Harmjan Greving's Blog


text:
Q: Can't set data in Httpcontext.Current.Session I'm a beginner in WebApi, trying to access a global container to hold and store data from a user, but can't figure out what and why the data can't store in session, please see my codes below:
public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
        protected void Application_PostAuthorizeRequest()
        {
            System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
        }
        private bool IsWebApiRequest()
        {
            var appRelative = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath != null;
            var urlPrefix = appRelative && HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);
            return urlPrefix;
        }
        void Application_AcquireRequestState(object sender, EventArgs e)
        {
            // Session is Available here
            if (HttpContext.Current.Session != null)
             {
                 if (HttpContext.Current.Session["con"] == null)
                 {
                     HttpContext.Current.Session["con"] = "Sample";
                 }
             }
        }
    }

Global.asax.cs
public class SampleController : ApiController
{
    [System.Web.Http.Route("setsession"),HttpGet]
    //api/v1/sample/setsession/
    public IHttpActionResult SetSession()
    {
        var con = (string)HttpContext.Current.Session["con"];
        HttpContext.Current.Session["con"]= "Hello World";
        con = (string)HttpContext.Current.Session["con"];
        return Ok();
    }

    [System.Web.Http.Route("getsession"), HttpGet]
    //api/v1/sample/getsession/
    public IHttpActionResult GetSession()
    {
        var data = (string)HttpContext.Current.Session["con"];
        return Ok();
    }
}

SampleController.cs
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();
        var constraintsResolver = new DefaultInlineConstraintResolver();
        constraintsResolver.ConstraintMap.Add("apiVersionConstraint", typeof(ApiVersionConstraint));
        config.MapHttpAttributeRoutes(constraintsResolver);
        config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));
        config.Formatters.RemoveAt(0);
        config.Formatters.Insert(0, new SecureJsonMediaTypeFormatter());

        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        // Ignoring circular reference globally
        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

        // Preserving circular reference globally
        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
        config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

        // Remove the JSON formatter
        //config.Formatters.Remove(config.Formatters.JsonFormatter);

        // Remove the XML formatter
        config.Formatters.Remove(config.Formatters.XmlFormatter);
    }
}

WebApiConfig.cs
As you can see, i set the HttpContext.Current.Session["con"] to its default value Sample, to let me know there is a value. the scenario is when i set a value from api/v1/sample/setsession to that Session["con"] the result is totally works fine, the "Hello World" passed to Session["con"]. but when i do "api/v1/sample/getsession", the condition in global.asax.cs success and  HttpContext.Current.Session["con"] = null or no value, don't know why this happen, i also set sessionState mode="InProc", which stores session state in memory on the Web server but still session turn to default and no data stored from it, please help, any comment will be appriciated, Thanks in advance.


text:
Q: how to use ASIHTTPRequest reachability I am using ASIHTTPRequest to send requests to my php scripts that are then searching my mysql server, however I have read in apple documentation we have to implement reachability when ever we try to send or receive data over TCP...
What I am wanting to know is ASIHTTPRequest taking care of Reachability for me, or do I have to implement some method calls into my code to make sure the checking is being done?
any help would be great... ASIHTTPRequest documentation is abit light with regards to reachability and I have not been able to find any notes on what to actually do with regards to this.

A: There is a Google Group that is better equipped to answer ASIHTTPRequest questions.
Since it's a reimplementation of iOS functionality, it's not particularly iOS relevant.


text:
Q: Powermock: Notifications are not supported when all test-instances are created first When I try to execute the below simplified JUnit test, it succeeds but i am getting an error message: Notifications are not supported when all test-instances are created first!
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(BlockJUnit4ClassRunner.class)
@PrepareForTest({ A.class })
public class TestA extends TestB {
    @Test
    public void test() throws Exception {
        assertEquals(true, true);
    }
}

public class TestB {}
public class A {}

When I remove the @PowerMockRunnerDelegate(BlockJUnit4ClassRunner.class), or the extends TestB or the @PrepareForTest({ A.class }), the message disappears. Even an emtpy @PrepareForTest({ }) makes the error message appear.
I found this post, but it is not the same problem, because I am not using an extended BlockJUnit4ClassRunner.
I am trying to understand why this error message appears.
I am using the latest version of Powermock (1.6.6) and JUnit 4.12 and running the test using java8.

A: PowerMock extends jUnit events message and fire some additional event during test life circle. PowerMockTestListener could be used to listen all jUnit and additional PowerMock events.
One of this event required that an instance per test is created. A jUnit runner usually creates an new instance of test class per each test method in class, but some of them could create only one instance of class for all tests. When @PowerMockRunnerDelegate is used then delegated runner responsible for creating test instance.
If event "test start" is fired without "test created" then PowerMock detects that all test instances are created before tests are started and cannot fire its internal events and this message is printed to system.err. So, you have the same issue as it has been described in post.
PowerMock has only one implementation PowerMockTestListener at current moment - AnnotationEnabler. This implementation is used for integration with EasyMock and Mockito and supporting annotation like @TestSubject, @Mock and so on. As result, then you see this message in console it means that these features could not work properly. But for Mockito case it could be easier fixed with using MockitoAnnotations.initMocks(this).
Very interesting that if you remove 'extends TestB' the message is disappeared. I'll check this case and investigate why it happen.


text:
Q: I want a to compare a variable with files in a directory and output the equals I am making a bash script where I want to find files that are equal to a variable. The equals will then be used.
I want to use "mogrify" to shrink a couple of image files that have the same name as the ones i gather from a list (similar to "dpkg -l"). It is not "dpkg -l" I am using but it is similar. My problem is that it prints all the files not just the equals. I am pretty sure this could be done with awk instead of a for-loop but I do not know how.
prog="`dpkg -l | awk '{print $1}'`"

for file in $dirone* $dirtwo*
do
     if [ "basename ${file}" = "${prog}" ]; then
         echo ${file} are equal
     else
         echo ${file} are not equal
     fi
done

Could you please help me get this working?

A: The condition "$file = $prog" is a single string. You should try "$file" = "$prog" instead.
The following transcript shows the fix:
pax> ls -1 qq*
qq
qq.c
qq.cpp

pax> export xx=qq.cpp

pax> for file in qq* ; do
         if [[ "${file} = ${xx}" ]] ; then
             echo .....${file} equal
         else
             echo .....${file} not equal
         fi
     done
.....qq equal
.....qq.c equal
.....qq.cpp equal

pax> for file in qq* ; do
         if [[ "${file}" = "${xx}" ]] ; then
             echo .....${file} equal
         else
             echo .....${file} not equal
         fi
     done
.....qq not equal
.....qq.c not equal
.....qq.cpp equal

You can see in the last bit of output that only qq.cpp is shown as equal since it's the only one that matches ${xx}.
The reason you're getting true is because that's what non-empty strings will give you:
pax> if [[ "" ]] ; then
         echo .....equal
     fi

pax> if [[ "x" ]] ; then
         echo .....equal
     fi
.....equal

That's because that form is the string length checking variation. From the bash manpage under CONDITIONAL EXPRESSIONS:

string
-n string
            True if the length of string is non-zero.

Update:
The new code in your question won't quite work as expected. You need:
if [[ "$(basename ${file})" = "${prog}" ]]; then

to actually execute basename and use its output as the first part of the equality check.

A: First, I think there's a small typo. if [ "basename ${file}" =... should have backticks inside the double quotes, just like the prog=... line at the top does.
Second, if $prog is a multi-line string (like dpkg -l) you can't really compare a filename to the entire list. Instead you have to compare one item at a time to the filename.
Here's an example using dpkg and /usr/bin
#!/bin/bash
progs="`dpkg -l | awk '{print $2}'`"

for file in /usr/bin/*
do
    base=`basename ${file}`

    for prog in ${progs}
    do
        if [ "${base}" = "${prog}" ]; then
            echo "${file}" matches "${prog}"
        fi
    done
done

A: you can use case/esac
case "$file" in
  "$prog" ) echo "same";;
esac


text:
Q: VScode extension # to id I have seen many people writing "#someword" as a shortcut for

and also ".someword" as a shortcut for

Do you know how to do that?
Thank you for your help!

A: The functionality is build in. You do not need any additional extension. As soon as you save your file as a *.html you can use the #someword syntax and the Emmet Abbreviation pops up automatically-

A: It should be Emmet, it is installed by default in vscode.
Take a look here https://code.visualstudio.com/docs/editor/emmet


text:
Q: Notepad++ regular expression: line does not contain certain pattern I have the following list of objects:
type="user" N="ag12345" status="active"
type="user" N="he98745" status="active"
type="user" N="user1" status="active"
type="user" N="84566" status="active"
type="user" N="iu78965" status="active"

I need to find the lines where the tag "N" does not match the pattern @@#####. In other words A valid user has to be created as two consecutive alphabetic characters and 5 numbers.
The regular expression I am looking for should show me the lines:
type="user" N="user1" status="active"
type="user" N="84566" status="active"

I've tried many many things but I can't seem to understand how to do this.
One of my attempts was:
Find what:
type=user" N="(?![\l]{2}[\d]{5})" status="active"

and also:
type=user" N="(?![\l]{2})(?![\d]{5})" status="active"

but it doesn't work :(

A: You're almost there. Use [a-z]  instead of [\l], \l won't match any lowercase letters. If you want to deal with both upper and lowercase then use [a-zA-Z] .
type="user" N="(?![a-z]{2}\d{5}")[^"]*" status="active"

[^"]*, negated character class which matches any character but not of ", zero or more times.
DEMO


text:
Q: Google Maps not loading when key restrictions are enabled: Android I know this has been asked several times before but I am not sure whether my fix is proper. I am using Google Maps in my app. The google map is not loading and I am getting error as,
E/Google Maps Android API﹕ Authorization failure
Ensure that the "Google Maps Android API v2" is enabled.

My manifest is having,
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

My gradle file is below,
dependencies {
  compile 'com.android.support:appcompat-v7:26.0.1'
  compile 'com.google.android.gms:play-services:8.4.0'
  compile 'com.google.android.gms:play-services-maps:8.4.0'
  compile 'com.google.android.gms:play-services-analytics:8.4.0'
}

EDIT:
My fragment,
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/map"
 android:name="com.google.android.gms.maps.SupportMapFragment"
 android:layout_width="match_parent"
 android:layout_height="100dp" />

This is my layout where I am using the fragment,
    <RelativeLayout
      android:id="@+id/map_area"
      android:layout_width="match_parent"
      android:layout_height="wrap_content" >

      <fragment
         android:id="@+id/map"
         android:name="com.google.android.gms.maps.SupportMapFragment"
         android:layout_width="match_parent"
         android:layout_height="100dp"
         android:layout_marginTop="0dp" />

     <Button
          android:id="@+id/map_button"
          android:layout_width="match_parent"
          android:layout_height="50dp"
          android:layout_below="@+id/map"
          android:layout_centerHorizontal="true"
          android:layout_marginTop="0dp"
          android:text="View Map and Directions"
          android:textColor="#ffffff"
          android:textStyle="bold" />
      </RelativeLayout>

I have gone through some of the below links but none of these seems to work,

*

*How to enable "Google Maps Android API v2" in developers console

*Google Maps Android API v2 Authorization failure

*Google Maps v2 Authorization failure. Different SHA1

*Google Maps Android API v2 Authorization failure
After going through several links, I managed to make my Google Maps work on removing the key restrictions from the google console. Is this the correct solution? Can anyone help me in fixing the issue with the Google Maps?
NOTE: I already have my Google Maps API Enable in Console.

A: You need to enable the google map api from google console
Below are the step to enable the google map api .

*

*Go to Google API console.

*Click on the dropdown and select 'create a project'.
Enter Project Name.

*now click on Navigation drawer and select API Manager.
Enable google places api.


text:
Q: how do i add a section inside a section in Laravel in a Laravel project I want to add a section inside another section I've tried with a @yield but didn't worked.
and now I have this code:
@section('form')
  <form>MY FORM</form>
@endsection

and I put it inside this:
@extends('layouts.app')
@section('content')
 <body class: my page
   @include('form')
 </body>
@endsection

but when it loads I only see what 'content' has but not the @include() part.

A: You don't need to put @section('form') on your form.blade.php . Here's a simple example:
//index.blade.php
@extends('layouts.app')
@section('content')
    <body class="my-page">
       @include('form')
    </body>
@endsection

On the Form element
    <form>MY FORM</form>

If you do this, here's what output will look like:
<body class="my-page">
   <form>MY FORM</form>
</body>

A: @extends('layouts.app')
@section('content')
 <body class: my page
  @yield('form')
 </body>
@endsection

In Form Blade
@extends('index')
@section('form')
 @parent
 <form>MY FORM</form>
@endsection

Try like this