text:
Q: Storing custom user information in an authentication ticket instead of in Membership provider I've been looking at implementing a custom SQL Server-based membership provider and one of my problems is that the membershipUserObject is keyed on a GUID. Since I'm using an existing ID as a key to roles and user data, this presents an interesting problem.
I'd like your opinion on which option -- or whether there's another option I haven't considered -- to use if I want to persist my own ID in a web session without round-tripping to the database constantly. I know that, by default, the login control creates a Forms Authentication cookie with the username of the membership object. So -- I could:

*

*Implement the Logging_In method of the login control to add my field to the authentication cookie manually

if (Membership.ValidateUser(Login1.UserName, Login1.Password))
     {
     FormsAuthenticationTicket ticket = new
     FormsAuthenticationTicket(
     1,
     Login1.UserName,
     DateTime.Now,
     DateTime.Now.AddMinutes(30),
     Login1.RememberMeSet,
"some custom data want to store in ticket....", // User-data,
     in this case the roles
     FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
     HttpCookie cookie = new HttpCookie(
     FormsAuthentication.FormsCookieName,
     hash);
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);

*Create a custom MembershipUser Object that inherits from MembershipUser and provides my extra property. I'll still have to persist it somehow (in Session? eww..)

*Create a custom Profile Provider that contains the extra field and cache that in session. This seems a bit like overkill, though, for the few fields I would actually cache.
What's the best practice here? I've read countless articles and the extra data in the forms ticket seems like the best so far.

A: The MembershipUser.ProviderUserKey is of type object, using the default provider we cast this to a Guid in order to use it.
Since you are using a custom membership provider, when you retrieve a user from the database couldn't you populate MembershipUser.ProviderUserKey with an int (or whatever type your id is)? Of course, you would have to cast MembershipUser.ProviderUserKey to an int every time you wanted to use it.


text:
Q: Kendo UI Grid settings This is my grid settings:
 $scope.documentSources = new kendo.data.DataSource({
        transport: {
            read: {
                fun: console.log("Read"),
                url: serviceBase + "Documents/GetListDocuments",
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                beforeSend: function (req) {
                    req.setRequestHeader('Authorization', authGlobalService.getAuthorizationData().token);
                }
            },
            update: {
                fun: console.log("Update"),
                url: serviceBase + "Documents/GetListDocuments",
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                beforeSend: function (req) {
                    req.setRequestHeader('Authorization', authGlobalService.getAuthorizationData().token);
                }
            },
            save: {
                fun: console.log("Create"),
                url: serviceBase + "Documents/SetDocument",
                type: "POST",
                dataType: "json",
                data: 'hello hello',
                contentType: 'application/json',
                beforeSend: function (req) {
                    req.setRequestHeader('Authorization', authGlobalService.getAuthorizationData().token);
                }
            },
            parameterMap: function (options) {
                if (options.filter) {
                    options.filter = options.filter.filters;
                }

                return JSON.stringify(options);
            }
        },
        sort: {
            field: "dateAdded",
            dir: "desc"
        },
        schema: {
            data: "data",
            total: "total"
        },
        pageSize: 10,
        serverPaging: true,
        serverSorting: true,
        serverFiltering: true
});

$scope.msg = false;

$scope.documentListGridOptions = {
    dataSource: $scope.documentSources,
    selectable: 'row',
    scrollable: false,
    sortable: true,
    resizable: true,
    filterable: {
        extra: false
    },
    pageable: true,
    change: function (idSelectedVote) {
        $scope.$apply(function () {
            $scope.setSelected(idSelectedVote.sender.dataItem(idSelectedVote.sender.select()));
        });
    },
    dataValueField: "id",
    columns: [{
        title: "Id dokumentu",
        field: "documentid",
        hidden: true
    }, {
        title: "Nazwa dokumentu",
        field: "nameDocument",
    }, {
        title: "Opis",
        field: "descriptionDocument",
    }, {
        title: "Data dodania",
        field: "dateAdded",
        template: "#= kendo.toString(kendo.parseDate(dateAdded, ''), 'MM/dd/yyyy HH:mm') #"

    }, {
        title: "Nazwa Pliku",
        field: "fileName"
    }]
};

And I have a problem because counting rows doesn't work and neither the page  because I have always one row. Like on my ss below.
http://i.stack.imgur.com/56M7j.png
Can you help me with this? It's probably something wrong with my grid settings.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I display what's in my array on my  when sliding? I'm trying to figure out why Match and History aren't showing up whenever I slide my <Drawer/>.  The list[] array is what holds those two.
I'm following a tutorial.  I'm guessing <List dataArray={list} renderRow={(item) is the problem in SideMenu.js file.
Here's SideMenu.js file:
import React, {Component} from 'react';
import { Text, View} from 'react-native';
import {List, ListItem, Header} from 'react-native-elements';
import Container from "native-base/src/theme/components/Container";

export default class SideMenu extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        let list = [{
            title: "Match",
            onPress: () => {
                this.props.navigator.replace("Match")
            }
        }, { // 2nd menu item below
            title: "History",
            onPress: () => {
                this.props.navigator.replace("History")
            }
        }];

        return(
            <Container theme={this.props.theme}>
                <Header/>
                <View>
                    <List dataArray={list} renderRow={(item) =>
                        <ListItem button onPress={item.onPress.bind(this)}>
                            <Text>{item.title}</Text>
                        </ListItem>
                    }/>
                </View>
            </Container>
        );
    }
}

Here's AppContainer.js file:
import React, {Component} from 'react';
import {Navigator} from 'react-native-deprecated-custom-components';
import Drawer from "react-native-drawer-menu";
import SideMenu from './components/sideMenu';

export default class AppContainer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            toggled: false,
            store: {}, // holds data stores
            theme: null
        }
    }

    toggleDrawer() {
        this.state.toggled ? this._drawer.close() : this._drawer.open();
    }

    openDrawer() {
        this.setState({toggled: true});
    }

    closeDrawer() {
        this.setState({toggled: false});
    }

    renderScene(route, navigator) { // current route you want to change to, instance of the navigator
        switch(route) {
            default: {
                return null;
            }
        }
    }

    // handles how our scenes are brought into view
    configureScene(route, routeStack) {
        return Navigator.SceneConfigs.PushFromLeft; // pushes new scene from RHS
    }

    render() {
        return(
            <Drawer
                ref = {(ref) => this._drawer = ref}
                type = 'default' // controls how menu appears on screen, pushes content to the side
                content = {<SideMenu navigator={this._navigator} theme={this.state.theme}
                />}
                onClose={this.closeDrawer.bind(this)}
                onOpen={this.openDrawer.bind(this)}
                openDrawerOffset={0.9}
            >

            <Navigator
                ref={(ref) => this._navigator = ref}
                configureScene={this.configureScene.bind(this)}
                renderScene={this.renderScene.bind(this)}
            />

            </Drawer>
        );
    }
}


text:
Q: How to determine the best case and worst case of an program(algorithm)? Suppose I have this program, I want to compare 2 input lists. Assume array A and array B. How do I determine the best case and worst case of the function?
Here is my code in [php]:
foreach($array_1 as $k){
    if(!in_array($k, $array_2)){
        array_push($array_2, $k);
    }
}

What is the best case and worst case of the for loop? Please include some explaination, thank you :)
EDITED:
Since my goal is to compare 2 lists that have at lists 1 element in common. I think my above code is wrong. Here is the updated of my code
foreach($array_1 as $k){
    if(in_array($k, $array_2)){
        array_push($array_3, $k);
    }
}

And I guess it would be:
Best case: O(n)
Worst case: O(N*M)

A: Let's do a quick analysis then:
foreach($array_1 as $k)

means that the operation within will be repeated for each element of the array. Let denote the size of the array by N.
The operation within:
if (!in_array($k, $array_2)) {
  array_push($array_2, $k);
}

There are 2 operations here:

*

*in_array

*array_push
array_push is likely to be constant, thus O(1), while in_array is more likely a linear search in array_2 which will take either 1 operation (found as the first element) up to the length of array_2 operations.
Note that in_array represent the only variable here:

*

*best case: in_array returns at the first comparison --> all elements of array_1 are the same, and either array_2 was empty or they are equal to its first element. Complexity is O(N) since we have N elements in array_1

*worst case: each time we examine each element of array_2 --> all elements of array_1 are distinct and they are distinct from the previous elements of array_2. If M is the length of array_2 when it is inputed, then the complexity is along the line of O(N * (N+M) ), (N+M)/2 being the mean time for searching in array_2 as it's growing from M to M+N elements and the constant 2 being discarded in the O notation

Hope this helps.

A: Big O notation is all about approximations.  It makes it easy to compare algorithms.
If you imagine your array of elements, a search might be order N (you must look at each item to find the item you want), it might be order Log(N) if you have an ordered collection or it could even be order 1 depending on your collection type.
The important thing here is to look at your algorithm and determine what the key operations are that are repeated.
Foreach is clearly an order N operation, by definition you must operate on each element in your list.  O(N)
Next is your if InArray 2.  This sounds like a search over an array, which would most likely be unordered so it would be order N (linear search).  So your complexity would now be O(N * M). (for each n elements in array 1, perform a search of order N complexity over array 2).
Finally you have an array push.  I don't know your environment but this could be order 1 or order N if the array needs to be reallocated and copied in order to grow.  Lets assume order 1 to keep it simple.  Therefore your complexity in Big O is O(N*M).
So now best case is for each element to find it's counterpart on the first try and perform the array push, which would be O(N * 1 * 1) = O(N).
Worst case is that the each element cannot be found in the second list forcing the full search of all elements in array 2.  Therefore complexity is O(N * M).
Your teachers want to understand your thinking so show them your assumptions made.  I highly recommend that you read the exact question and information you have been given before relying on the assumptions given here, you may have been told the language/platform which would tell you the exact penalty and algorithms used in each case. Hope that helps :)

A: Generally with such a problem I just look at the algorithm as Dr. Evil and ask, "How can I make this take the most time possible?"


text:
Q: MVC 5 - SingleOrDefault method not working in ViewModel I have a Test controller with a simple method:
private ApplicationEntities _db = new ApplicationEntities();

public String GetSomeString()
{
    return _db.someStoredProcedure(8).SingleOrDefault();
}

This works fine in a controller and say the method returns "Hello"
The problem comes when it's in a ViewModel.
I have simplified it to this:
public class TestView
{
   private ApplicationEntities _db = new ApplicationEntities();

   private string smth;

   public String Something
   {
     get {
        //This line does not work here.
       Error    5   'System.Data.Entity.Core.Objects.ObjectResult<string>' does not contain a definition for 'SingleOrDefault' and no extension method 'SingleOrDefault' accepting a first argument of type 'System.Data.Entity.Core.Objects.ObjectResult<string>' could be found (are you missing a using directive or an assembly reference?)

        var d = _db.someStoredProcedure(8).SingleOrDefault();

         //This works, since the result is always only 1 row
        var a = _db.someStoredProcedure(8).GetEnumerator();
        var b = a.MoveNext();
        var c = a.Current;
           return a.Current;
        }
        set { smth= value; }
     }

    public async static void getString()
    {
       var a = new TestView().Something;
    }

}

Question is why SingleOrDefault() is not working here? (There is no assembly reference that can be easily added) And how this ViewModel and getString method can be solved better?


text:
Q: Regular expression in javascript to remove anything that is not: a-z 0-9 and hyphen Thanks in advance.
I would like a regular expression that removes anything that is NOT alpha numeric and a hyphen. So allowed are A-Z 0-9 and -.
Also, how could I apply that to a string in Javascript?
Thanks again.

A: var str = 'a23a-asd!@#$';
str.replace(/[^-a-z0-9]/ig,'');

A: Try this:
str = str.replace(/[a-zA-Z\d-]/g, "");

A: var output = input.replace(/[^A-Za-z0-9-]/g, "");

A: string.replace(/[^a-zA-Z0-9-]/g, "");

A: $(document).ready(function (e) {
        $('#Box, #Window').keyup(function(){
            var $th = $(this);
            $th.val($th.val().replace(/[^a-zA-Z0-9]/g, function(str){return '';}));
        });

    });

This can be used to validate Alphanumeric values.


text:
Q: How do I request injection in Android Fragments and Services? I'm following this tutorial to add Dagger 2 to my Android project.
After doing setup and creating the modules and components I can add the dependencies in an Activity like this:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_account);
    ButterKnife.bind(this);
    ((AppController) getApplication()).getNetComponent().inject(this);
}

I am struggling in how to inject dependencies in a Fragment and IntentService?
public class FragmentBrandList extends ListFragment {
}

In this class which @Override method should I request injection in and what will be the code for this?

A: Step 1: Create your ApplicationModule
@Module
public class ApplicationModule {

    private final DIApplication application;

    public ApplicationModule(DIApplication application) {
        this.application = application;
    }

    @Provides @Singleton
    public DIApplication provideApplication() {
        return application;
    }

    @Provides @Singleton
    public DogModel provideDogModel() {
        return new DogModelImpl("Scooby-doo");
    }

}

Step 2: Create your ApplicationComponent:
@Singleton
@Component(modules = {ApplicationModule.class})
public interface ApplicationComponent {
    void inject(DIApplication application);

    void inject(BaseActivity activity);
    void inject(BaseFragment fragment);

    void inject(DogSyncService service);
}

Step 3: Create a DI Class:
public class DependencyInjector {

    private static ApplicationComponent applicationComponent;

    public static void initialize(DIApplication diApplication) {
        applicationComponent = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(diApplication))
                .build();
    }

    public static ApplicationComponent applicationComponent() {
        return applicationComponent;
    }

    private DependencyInjector(){}
}

Final Step: Inject anywhere using:
DependencyInjector.applicationComponent()

Your question inspired me to create a Demo project that shows Activity, Fragment and Service injection using Dagger2. Here is the git: https://github.com/write2sv/AndroidDIDagger2/tree/master/app/src/main/java/work/shaggy/didemo

A:
In this class which @Override method i should use and what will be the code to add dependency in fragment?

The correct place to call injection inside a Fragment is onAttach(Context context). This is stated in the where to inject section of the Dagger 2 user guide here
@Override
public void onAttach(Context context) {
    ((AppController) context.getApplicationContext()).getNetComponent().inject(this);
    super.onAttach(context);
}

The correct place to call injection inside a Service is onCreate()
@Override
public void onCreate() {
    ((AppController) getApplication()).getNetComponent().inject(this);
    super.onCreate();

}

Note that in both cases the request for injection comes before the call to super.onCreate(). The Dagger user guide explains it like this:

It is crucial to call AndroidInjection.inject() before super.onCreate() in an Activity, since the call to super attaches Fragments from the previous activity instance during configuration change, which in turn injects the Fragments. In order for the Fragment injection to succeed, the Activity must already be injected. For users of ErrorProne, it is a compiler error to call AndroidInjection.inject() after super.onCreate().

In other words:

*

*The Activity super.onCreate() call re-attaches Fragments from a previous instance

*This super call in  cause Fragments to be re-injected (since Fragments are injected in onAttach)

*Fragments should be injected after their Activity is injected, therefore request injection in your Activity before calling super.onCreate().

You can always check where to inject by looking at the relevant source code for the com.google.dagger:dagger-android classes like DaggerFragment and DaggerService. See the GitHub repo here
For your specific example, please make sure you have added the new injection sites to the NetComponent:
void inject(FragmentBrandList frag);

void inject(BrandListService service);

A: I did it using
((AppController) getActivity().getApplication()).getNetComponent().inject(this);
in Fragment.onCreate() method.

A: ((MyApp) context.getApplicationContext()).getApplicationComponent().inject(MyFragment.this);

I added this in onAttach(Context context) method of the fragment.

A: You really just need to include the injector method for whatever you want to inject.
@Singleton
@Component
public interface AppComponent {
    void inject(MainActivity activity);
    void inject(FragmentBrandList fragmentBrandList);
}

A: You can use autodagger2 to avoid having to write all that boilerplate. I use this architecture quite often:
build.gradle
apt 'com.github.lukaspili.autodagger2:autodagger2-compiler:1.1'
compile 'com.github.lukaspili.autodagger2:autodagger2:1.1'

YourApp.java
@AutoComponent( modules = YourApp.YourAppModule.class )
public class YourApp extends Application {

    private static YourApp instance;
    private YourAppComponent component;

    public YourAppComponent getComponent() {
        return this.component;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        setupComponent();
    }

    private void setupComponent() {
        component = DaggerYourAppComponent.builder()
                .yourAppModule(new YourAppModule(instance))
                .build();
    }

    @dagger.Module
    public static class YourAppModule {
        private YourApp app;

        YourAppModule(YourAppApp application) {
            this.app = application;
        }

        @Provides @AutoExpose(YourApp.class)
        Application provideApplication() {
            return app;
        }

        @Provides @AutoExpose(PoswalaApp.class)
        Context provideContext() {
            return app;
        }

        @Provides @AutoExpose(YourApp.class)
        Retrofit provideApiAdapter() {
            return ApiService.getServiceInstance();
        }
    }
}

YourActivity.java
@AutoComponent(
    dependencies = YourApp.class,
    modules = YourActivity.YourActivityModule.class
)

public class YourActivity extends BaseActivity implements YourActivityView {

    private YourActivityComponent component;
    @Inject MyPresenter presenter

    // This is an abstract method from BaseActivity
    @Override
    protected void setupComponent(YourAppComponent appComponent) {
        component = DaggerYourActivityComponent.builder()
                .yourAppComponent(((YourApp) getApplication()).getComponent())
                .yourActivityModule(new YourctivityModule(this))
                .build();
    }

    @Override
    protected MyPresenter getPresenter() {
        return presenter;
    }

    @dagger.Module
    public static class YourActivityModule {

        private YourActivityView view;

        YourActivityModule(YourActivityView view) {
            this.view = view;
        }

        @Provides @AutoExpose(YourActivity.class)
        YourActivityView provideView() {
            return view;
        }

        // Your other dependencies
    }
}

Quick explanation:
Your app's module will have to a "universal" dependency, but this way you can achieve using several modules for a class. You just need to customize the
@AutoComponent(
    dependencies = YourApp.class,
    modules = { YourActivity.YourActivityModule.class, YourFragment.YourFragmentModule.class }
)

block. You can add as many modules as you like using that syntax.
Hope this helps you


text:
Q: countif excel with value in column A or column B I want to use COUNTIF in Excel, but I want to count rows where column V = yes OR column U = yes, with all the other criteria the same.
It is easy to use or with values in 1 column, such as P4:P999 = "apple" or "orange", but how to use or over multiple columns?
Below is an Excel code sample written to be readable. The only solution I found was to use addition and rewrite the entire code, but I hate this solution because it is too long.
SUM(COUNTIFS(
     P4:P9999,  {"apple", "orange"},
     B4:B9999, "potato",
     AF4:AF9999, "",
     V4:V9999,  "Yes"
    )
) +
SUM(COUNTIFS(
     P4:P9999,  {"apple", "orange"},
     B4:B9999, "potato",
     AF4:AF9999,  "",
     U4:U9999,  "Yes"
   )
)

A: Switch to SUMPRODUCT:
=SUMPRODUCT(((P4:P9999 = "apple")+(P4:P9999 = "orange"))*(B4:B999="potato")*(LEN(AF4:AF999)=0)*((V4:V9999="Yes)+(U4:U9999="Yes")>0))


text:
Q: How to click on a link that gets hidden when I click outside a textbox input? I have a text box input in a form;
when I click it, a link appears next to it. When I click outside the text input box, the link gets hidden.
I have this code that changes style of the text box input field and hides the link:
$('#txtbox').blur(function(){
$('#txtbox').removeClass('active');
$('#txtbox').addClass('passive');
$('#link').hide();
});

I'd like to be able to click on the link, but when I click wherever outsite the text box, the link gets hidden.
How can the link remain visible when I click on it, but also to get hidden when I click outsite the textbox and when I don't click on the link?

A: There are two solutions to your problem
1:) use fadeout/slow hide
$('#link').fadeOut();

or
$('#link').hide('slow');

2:) use setTimeout()
setTimeout( function() { $('#link').hide('slow'); }, 1000 );

A: Try this.
$(function(){
   $(document).click(function(){
      $('#link').hide();
   });
   $('#link').click(function(e){
      e.stopPropagation();
      //Do other stuff on click of link here
   });
   $('#txtbox').blur(function(){
       $('#txtbox').removeClass('active').addClass('passive');
   }).focus(function(e){
       $('#txtbox').addClass('active').removeClass('passive');
       $('#link').show();
   }).click(function(e){
        e.stopPropagation();
   });
});

Demo

A: I would think you could include an onChange function. http://forum.jquery.com/topic/jquery-change-trigger-and-onchange-event-in-input-box Besides here, a search for OnChange will give you many ideas.


text:
Q: Installing Ruby on Rails on Mac To install RoR on my Mac (v10.9.2), I decided to follow the instructions for Ruby 1.9.2 here: https://stackoverflow.com/a/8464619/2278546
"rvm install 1.9.2" was taking too long, so based on suggestions on SO, I used "rvm requirements" to install each of the requirements individually with macports.  I then executed "rvm install 1.9.2" and it ran much faster.
When I tried to execute "gem install rail", I got an error message saying

activesupport requires Ruby version >= 1.9.3

As a result, I went back and tried again with 1.9.3:
rvm install 1.9.3
rvm --default 1.9.3
gem update
gem install rails

This time, during the rails install command, the process got stuck installing the documentation for rails.  I decided to interrupt and run this instead:
gem install --no-ri --no-rdoc rails

This worked!  I ran the following:
rails new pong; cd pong; rails generate controller welcome index

The last command in that string gave me the following error:

/Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/sid.rb:17:in
  fiddle_func': uninitialized constant Spring::SID::DL (NameError)
    from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/sid.rb:30:in
  sid'     from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/sid.rb:39:in
  pgid'    from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/server.rb:78:in
  set_pgid'    from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/server.rb:34:in
  boot'    from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/server.rb:14:in
  boot'    from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/client/run.rb:36:in
  block in boot_server'    from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/client/run.rb:34:in
  fork'    from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/client/run.rb:34:in
  boot_server'     from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/client/run.rb:18:in
  call'    from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/client/command.rb:7:in
  call'    from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/client/rails.rb:23:in
  call'    from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/client/command.rb:7:in
  call'    from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/client.rb:26:in
  run'     from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/bin/spring:48:in
  <top (required)>'    from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/binstub.rb:11:in
  load'    from
  /Users/me/.rvm/gems/ruby-1.9.3-p545/gems/spring-1.1.2/lib/spring/binstub.rb:11:in
  <top (required)>'    from /Users/me/Coding/pong/bin/spring:16:in
  require'     from /Users/me/Coding/pong/bin/spring:16:in <top
  (required)>'  from bin/rails:3:inload'  from bin/rails:3:in `'

Based on suggestions read here and here and elsewhere, I decided to try with a different compiler:
port install gcc46
CC=`which gcc-mp-4.6`
rvm reinstall 1.9.3
gem install
rvm reinstall 1.9.3

Same problem with this installation as well.

A: I suspect interrupting those builds might have left things in a bad state. First off, uninstall 1.9.2. 1.9.3-p545 is the oldest supported version, as of now at least.
Next, uninstall the gem 'spring-commands-rspec' and run a gem pristine -all. Then do another bundle install. FWIW, I am able to run spring on my 10.9.2 macbook. You may have to reinstall the xcode command line tools if your gcc is giving you issues.
Beyond all that, you don't need spring to run a rails app. It's primarily a helper during development and testing. Once you get things cleaned up, I would just remove the thing from your Gemfile until you actually need it.

A: I was able to get things running by mixing @Andrew's advice with some common sense...
I first cleaned up the mess I had made:
sudo rvm remove 1.9.2
sudo rvm remove 1.9.3
sudo rvm remove 1.9.3-p545
sudo gem uninstall spring-commands-rspec
sudo gem pristine -a
sudo port uninstall rvm

I then reinstalled rvm
sudo port install rvm

and reinstalled Ruby 1.9.3 with rails:
sudo rvm install 1.9.3
sudo gem update
sudo gem install --no-ri --no-rdoc rails

The problem as described above still occurred.
I then remembered that I had received the following message when installing Ruby (confirming Andrew's comment):

WARNING: Please be aware that you just installed a ruby that is no
  longer maintained (2014-02-23), for a list of maintained rubies visit:
http://bugs.ruby-lang.org/projects/ruby/wiki/ReleaseEngineering

Please consider upgrading to ruby-2.1.1 which will have all of the
  latest security patches.

So, I cleaned up again:
sudo rvm remove 1.9.3
sudo rvm remove 1.9.3-p545
sudo gem uninstall spring-commands-rspec
sudo gem pristine -a

Then, I tried installing Ruby 2.1.1 and Rails:
sudo rvm install 2.1.1
sudo gem update
sudo gem install --no-ri --no-rdoc rails

This time, I got no errors when I tried to run
rails new pong; cd pong; rails generate controller welcome index

This is not an ideal answer because I still couldn't get 1.9.3 to work, but it fits my purposes (I think).  Anyone have any theories explaining why 1.9.3 doesn't work?
Thanks,
Grasswistle


text:
Q: SQL, trying to compare 2 int and getting error "Cant compare char and int" I'm getting this error:

"java.sql.SQLSyntaxErrorException: No están soportadas las
  comparaciones entre 'INTEGER' y 'CHAR (UCS_BASIC)'. Los tipos deben
  ser comparables. Además, los tipos de cadena también deben tener una
  intercalación coincidente. Si la intercalación no coincide, una
  posible solución es convertir los operandos para forzarlos a la
  intercalación por defecto (por ejemplo: SELECT tablename FROM
  sys.systables WHERE CAST(tablename AS VARCHAR(128)) = 'T1')"

My database table has 11 positions, everything is a varchar but the first one, thats a int.
And iI' getting data from the jtable, everything but the col 0, wich is a int, rest is strings.
And here is my code:
int colActual = jTableNombre.getSelectedRow();

private void jButtonGuardarNombreActionPerformed(java.awt.event.ActionEvent evt) {

    String nombre = (String) jTableNombre.getModel().getValueAt(colActual,1);
    String director=(String) jTableNombre.getModel().getValueAt(colActual,2);
    String año = (String) jTableNombre.getModel().getValueAt(colActual,3);
    String generos = (String) jTableNombre.getModel().getValueAt(colActual,4);
    String actores = (String) jTableNombre.getModel().getValueAt(colActual,5);
    String pais = (String) jTableNombre.getModel().getValueAt(colActual,6);
    String idioma = (String) jTableNombre.getModel().getValueAt(colActual,7);
    String doblaje = (String) jTableNombre.getModel().getValueAt(colActual,8);
    String subtitulos = (String) jTableNombre.getModel().getValueAt(colActual,9);
    String ubicacion = (String) jTableNombre.getModel().getValueAt(colActual,10);
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        stmt = conn.createStatement();
        String sql= "UPDATE MOVIES " +
            "SET NOMBRE = '"+nombre+"', "+
            "DIRECTOR = '"+director+"', "+
            "AÑO = '"+año+"', "+
            "GENEROS = '"+generos+"', "+
            "ACTORES = '"+actores+"', "+
            "PAIS = '"+pais+"', "+
            "IDIOMA = '"+idioma+"', "+
            "DOBLAJE = '"+doblaje+"', "+
            "SUBTITULOS = '"+subtitulos+"', "+
            "UBICACION = '"+ubicacion+"' "+
            "WHERE ID = '"+id+"'";
        stmt.executeUpdate(sql);
        int i= stmt.executeUpdate(sql);
        System.out.print(i);
        if (i>0) {
            JOptionPane.showMessageDialog(null, "Movie Updated");
        }
        else {
            JOptionPane.showMessageDialog(null, "Movie dindt update");
        }

    }
    catch(Exception e) {
        System.out.println(e);
    }

}

A: You are missing the id in this snippet of code:
    "WHERE ID = '"+id+"'";

Try to add it.

A: Try changing this line of code:
        "WHERE ID = '"+id+"'";

To:
        "WHERE ID = "+id;

Should work.
Welcome to Java, also I suggest u taking a look on the jdbc docs: https://docs.oracle.com/javase/tutorial/jdbc/basics/ and also as a suggestion I have to u is, if u are getting and SQLXXX Error, always go on debug, print your SQL command and try execute it on any SQL client, could be helpful to find syntax bugs.
C ya.


text:
Q: How to initialize unique variables in base class (Inheritance) If I am declaring several variables in the base class, they will be defined in every derived class, right? I just want to have the variables in the base class once for all derived class. Example:
class Base{
public:
 virtual ~Base();

protected:
 Base();
 int fileIndex;
};

class DerivedA : public Base{
public:
 DerivedA();
 virtual ~DerivedA();
 void DoSth(); //using fileIndex
};

class DerivedB : public Base{
public:
 DerivedB();
 virtual ~DerivedB();
 void DoSthDifferent(); //using the same fileIndex
};

How can I do that?

A: Just make  fileIndex a static variable:
static int fileIndex;

Then all instances from all derived classes will share the same value

A: I'm assuming this isn't a file index in some global log that you need to keep tidy. A static will do for that.
Use composition instead of (misusing) inheritance.
class FileAccessor
{
  int fileIndex;
  // Your stuff
};

Class A
{
  std::shared_ptr<FileAccessor> mFileAccessor;
public:
  A(std::shared_ptr<FileAccessor> fAccesor ) : mFileAccessor(fAccesor ) {}

  void DoSth () { /* use mFileAccessor*/ }
};

Class B
{
  std::shared_ptr<FileAccessor> mFileAccessor;
public:
  B(std::shared_ptr<FileAccessor> fAccesor ) : mFileAccessor(fAccesor ) {}

  void DoSth () { /* use mFileAccessor*/ }
};

int main()
{
  auto fAccesor = std::make_shared<FileAccessor>();
  A a{fAccesor};
  B b{fAccesor};
}

That way, if you need to synchronize access, the logic stays in FileReader.
If you need to have objects share state, than make it explicit by factoring the state into another object.


text:
Q: Pretty URL using mod_rewrite path issue I am using MOD_REWRITE to channel all URLs through a single file. The aim is to allow pretty urls like:
http://mysite.com/shop/electrical/hoover
or
http://mysite.com/shop/checkout
etc etc
I achieve this using the following .htaccess file:
# Turn on the RewriteEngine
RewriteEngine On
#
#  Rules
#
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . urlbug.htm

This is the stripped down HTML file that does all the work:
<!doctype html>

<meta charset="utf-8">
<title>My web page</title>
<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.20.custom.css" media="all"    rel="stylesheet"/>

Home

Clear Counters

Maintan Tables

Stock

Categories

Designers

User Database

This works if you visit a URL like:
http://www.facebookanswers.co.uk/code/foobar/works
However, if you try a URL like:
http://www.facebookanswers.co.uk/code/foobar/no/longer/works
Then the URL will load, however, none of the CSS or JS files will load.
This is because I am using relative URLs.
If I instead use absolute URLs, then all works fine. I have set up a different folder to demonstrate this:
http://www.facebookanswers.co.uk/code/foobar2/works
and
http://www.facebookanswers.co.uk/code/foobar2/works/as/well
This is the code with the absolute URLs:
<!doctype html>

<meta charset="utf-8">
<title>My web page</title>
<link type="text/css" href="http://www.facebookanswers.co.uk/code/foobar2/css/ui-lightness/jquery-ui-1.8.20.custom.css" media="all" rel="stylesheet"/>

Home

Clear Counters

Maintan Tables

Stock

Categories

Designers

User Database

Somewhere along the line, the path is getting confused. What is the best way around this? I would like to keep relative URLs if possible, as the code I am developing will be used on a number of sites. Its not the end of the world if I have to use absolute URLs, and I know that there are performance benefits in absolute URLs, but it seems odd that the browser will happily load the URL, but then think that it is stored somewhere else!

A: Use root relative URLs.
The problem is that the browser sees a URL like http://www.facebookanswers.co.uk/code/foobar/no/longer/works so a relative link would resolve as http://www.facebookanswers.co.uk/code/foobar/no/longer/works/code/foobar2/css... and so on.
Instead use this...
<link type="text/css" href="/code/foobar2/css/ui-lightness/jquery-ui-1.8.20.custom.css" media="all" rel="stylesheet"/>

By starting with a / you're forcing it to be relative to the root of the website, but by not specifying the domain, it'll work just fine if you deploy on another site. This is really just an HTML issue rather than a mod-rewrite one.
Take a look at your server access logs and you'll see what pages are being requested, and you'll see they're not what you were expecting.
Site-wide resources are always best referred to with root-relative URLs - it means you don't need to adjust them based on where you are in the site, and it makes them portable between sites (which is handy if, like me you have your development site on a local machine with a different domain name - I use www.example.com.dev when working locally on www.example.com)


text:
Q: SwiftUI Custom Navigation Bar VStack doesn't work I'm trying to make a custom navigation bar with back button, image, VStack (2 labels) but it didn't work. The whole view will stick to the center and not following the alignment I set. Thank you!
struct WeatherNavigation: View {
    var body: some View {
        HStack {
            WeatherNavigation()
        }
        .
        .
        .
    }
}

//
struct WeatherNavigation: View {
    var body: some View {
                Button(action: {
                    //action
                }, label: {
                    HStack {
                        Image("Back")
                            .foregroundColor(.black)
                        Image("Weather")
                            .resizable()
                            .frame(width: 40, height: 40)
                   }
                })
                .frame(width: 100, height: 50, alignment: .leading)
            VStack {
                Text(weather.description)
                    .font(.appFont(size: 18))
                    .foregroundColor(Color(uiColor: .black))
                Text(weather.location)
                    .font(.appFont(size: 12))
                    .foregroundColor(Color(uiColor: .blue))
            }
            .frame(width: .infinity, height: 50, alignment: .leading)
        }
}

A: First of all, you shouldn't set frame of the whole view like that. For you problem, it can divide into: make a HStack to store all the container view and make a space between those two of them. Because using HStack you don't need to add leading.
Code will be like this
struct WeatherNavigation: View {
    var body: some View {
        // make a HStack to store all the attribute
        HStack(alignment: .top) {
            Button(action: {
                //action
            }, label: {
                HStack {
                    Image("Back")
                        .foregroundColor(.black)
                    Image("Weather")
                        .resizable()
                        .frame(width: 40, height: 40)
               }
            })
            .frame(width: 100, height: 50)
            VStack {
                Text("Tokyo")
                    .foregroundColor(Color(uiColor: .black))
                Text("Japan")
                    .foregroundColor(Color(uiColor: .blue))
            }
            // make a space at the end
            Spacer()
        }
    }
}

And the usage like this
struct ContentView: View {
    var body: some View {
        VStack {
            HStack {
                WeatherNavigation()
            }
            Spacer()
        }

    }
}

More over: adding Spacer() means that make space between view. That will solved your problem if you want to keep like your way.


text:
Q: Deleting and Redrawing Matplotlib Animation There are a few parts to this problem, so let me summarize. I'm trying to be able to create an animation in a PySide window, and then later destroy and reanimate it based on new information.  I've created a sample script to demonstrate this, but it's a bit long, so here's an outline:

*

*Create a QtGui main window using PySide

*Create a widget in the window for drawing the animation

*Animate the widget using FuncAnimation

*On a button press:

*

*Delete the widget and animation

*Recreate the widget using different parameters for plotting

*Reanimate

Everything works until the button press, and I get the following stack trace:

Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_qt4.py", line 366, in idle_draw
    self.draw()
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_qt4agg.py", line 149, in draw
    self.update()
RuntimeError: Internal C++ object (MplWidget) already deleted.

How can I get rid of the current animation so that I can redraw a separate one?  Here's the code.
from matplotlib import pyplot as p
from mpl_toolkits.mplot3d import Axes3D    # @UnusedImport
from PySide import QtGui, QtCore

import matplotlib
import matplotlib.animation as animation
import sys
# specify the use of PySide
matplotlib.rcParams['backend.qt4'] = "PySide"

# import the figure canvas for interfacing with the backend
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg \
                                                            as FigureCanvas
from matplotlib.figure import Figure

import numpy as np
from math import pi, cos, sin

class Ui_MainWindow(object):
    def setupUi(self, MainWindow, direction, maxRadius):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 500)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                                       QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
                            self.pushButton.sizePolicy().hasHeightForWidth())
        self.pushButton.setSizePolicy(sizePolicy)
        self.pushButton.setMaximumSize(QtCore.QSize(150, 16777215))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.setText("Change Direction")
        self.horizontalLayout.addWidget(self.pushButton)
        self.frame = QtGui.QFrame(self.centralwidget)
        self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtGui.QFrame.Raised)
        self.frame.setObjectName("frame")
        self.gridLayout = QtGui.QGridLayout(self.frame)
        self.gridLayout.setObjectName("gridLayout")
        self.horizontalLayout.addWidget(self.frame)
        # ------
        self.mplWidget = MplWidget(self.frame, direction, maxRadius)
        # ------
        MainWindow.setCentralWidget(self.centralwidget)

        QtCore.QMetaObject.connectSlotsByName(MainWindow)

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.direction = 'up'
        self.maxRadius = 0.3
        self.ui.setupUi(self, self.direction, self.maxRadius)
        self.ui.pushButton.clicked.connect(self.changeStuff)
        self.animation = self.ui.mplWidget.animate()

    def changeStuff(self):
        del self.animation
        self.ui.mplWidget.deleteLater()
        dirs = {'up' :'down', 'down':'up'}
        rads = {0.3:1, 1:0.3}
        self.direction = dirs[self.direction]
        self.maxRadius = rads[self.maxRadius]
        self.ui.mplWidget = MplWidget(self.ui.frame, self.direction,
                                      self.maxRadius)
        self.animation = self.ui.mplWidget.animate()

class MplWidget(FigureCanvas):
    def __init__(self, parent=None, direction='up', maxRadius=0.3):
        self.figure = Figure()
        super(MplWidget, self).__init__(self.figure)
        self.setParent(parent)
        self.axes = self.figure.add_subplot(111, projection='3d')
        self.axes.set_xlabel("x label")
        self.axes.set_ylabel("y label")
        self.axes.set_zlabel("z label")
        self.axes.set_xlim3d([-1, 1])
        self.axes.set_ylim3d([-1, 1])
        self.axes.set_zlim3d([-1, 1])
        self.axes.set_aspect('equal')
        if   direction == 'up':
            self.c = 1
        elif direction == 'down':
            self.c = -1
        else:
            self.c = 1
        self.maxRadius = maxRadius
        self.frames = 50
        self.plot_handle = self.func_plot(self.frames)

    def func_plot(self, z):
        z /= float(self.frames) * self.c
        theta = np.arange(0, 2 * pi + pi / 50, pi / 50)
        xdata = self.maxRadius * z * np.array([cos(q) for q in theta])
        ydata = self.maxRadius * z * np.array([sin(q) for q in theta])
        zdata = z * np.ones(np.shape(xdata))
        if not hasattr(self, 'plot_handle'):
            plot_handle = self.axes.plot(xdata, ydata, zdata)[0]
        else:
            plot_handle = self.plot_handle
        plot_handle.set_data(xdata, ydata)
        plot_handle.set_3d_properties(zdata)
        return plot_handle

    def animate(self):
        return animation.FuncAnimation(
                    fig=self.figure, func=self.func_plot, frames=self.frames,
                    interval=1000.0 / self.frames, blit=False)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec_())

Version information:
matplotlib - 1.2.1
PySide - 1.1.2
Python - 2.7.4
Edit:
I followed the matplotlib Installation Instructions to do a source build from git.  I now have version 1.4.x installed.  However, the original problem persists.

A: This is related to a bug in matplotlib qtbackend that tears things down in the wrong order (see here).  Adding
self.ui.mplWidget.close_event()

in ChangeStuff takes care of the exception you have, but the newly created canvas isn't shown.
On the other hand, I don't understand why any canvas is shown at all as the widget is never added to a layout.  If you tweak the set up a bit and explicitly add/remove the widget to the gridLayout it does what you want:
from mpl_toolkits.mplot3d import Axes3D    # @UnusedImport
from PySide import QtGui, QtCore

import matplotlib
import matplotlib.animation as animation
import sys
# specify the use of PySide
matplotlib.rcParams['backend.qt4'] = "PySide"

# import the figure canvas for interfacing with the backend
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg \
                                                            as FigureCanvas
from matplotlib.figure import Figure

import numpy as np
from math import pi, cos, sin

class Ui_MainWindow(object):
    def setupUi(self, MainWindow, direction, maxRadius):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 500)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                                       QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
                            self.pushButton.sizePolicy().hasHeightForWidth())
        self.pushButton.setSizePolicy(sizePolicy)
        self.pushButton.setMaximumSize(QtCore.QSize(150, 16777215))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.setText("Change Direction")
        self.horizontalLayout.addWidget(self.pushButton)
        self.frame = QtGui.QFrame(self.centralwidget)
        self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtGui.QFrame.Raised)
        self.frame.setObjectName("frame")
        self.gridLayout = QtGui.QGridLayout(self.frame)
        self.gridLayout.setObjectName("gridLayout")
        self.horizontalLayout.addWidget(self.frame)
        # ------
        self.mplWidget = MplWidget(None, direction, maxRadius)
        self.gridLayout.addWidget(self.mplWidget)
        # ------
        MainWindow.setCentralWidget(self.centralwidget)

        QtCore.QMetaObject.connectSlotsByName(MainWindow)

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.direction = 'up'
        self.maxRadius = 0.3
        self.ui.setupUi(self, self.direction, self.maxRadius)
        self.ui.pushButton.clicked.connect(self.changeStuff)
        self.animation = self.ui.mplWidget.animate()

    def changeStuff(self):
        self.ui.mplWidget.close_event()  # mpl clean up
        self.ui.mplWidget.deleteLater()  # QT cleanup
        self.ui.gridLayout.removeWidget(self.ui.mplWidget)

        dirs = {'up': 'down', 'down': 'up'}
        rads = {0.3: 1, 1: 0.3}
        self.direction = dirs[self.direction]
        self.maxRadius = rads[self.maxRadius]
        self.ui.mplWidget = MplWidget(self.ui.frame, self.direction,
                                      self.maxRadius)
        self.ui.gridLayout.addWidget(self.ui.mplWidget)
        self.animation = self.ui.mplWidget.animate()
        print self.ui.frame.children()
        print 'finished change stuff'

class MplWidget(FigureCanvas):
    def __init__(self, parent=None, direction='up', maxRadius=0.3):
        self.figure = Figure()
        super(MplWidget, self).__init__(self.figure)
        self.setParent(parent)
        self.axes = self.figure.add_subplot(111, projection='3d')
        self.axes.set_xlabel("x label")
        self.axes.set_ylabel("y label")
        self.axes.set_zlabel("z label")
        self.axes.set_xlim3d([-1, 1])
        self.axes.set_ylim3d([-1, 1])
        self.axes.set_zlim3d([-1, 1])
        self.axes.set_aspect('equal')
        if direction == 'up':
            self.c = 1
        elif direction == 'down':
            self.c = -1
        else:
            self.c = 1
        self.maxRadius = maxRadius
        self.frames = 50
        self.plot_handle = self.func_plot(self.frames)

    def func_plot(self, z):
        z /= float(self.frames) * self.c
        theta = np.arange(0, 2 * pi + pi / 50, pi / 50)
        xdata = self.maxRadius * z * np.array([cos(q) for q in theta])
        ydata = self.maxRadius * z * np.array([sin(q) for q in theta])
        zdata = z * np.ones(np.shape(xdata))
        if not hasattr(self, 'plot_handle'):
            plot_handle = self.axes.plot(xdata, ydata, zdata)[0]
        else:
            plot_handle = self.plot_handle
        plot_handle.set_data(xdata, ydata)
        plot_handle.set_3d_properties(zdata)
        return plot_handle

    def animate(self):
        return animation.FuncAnimation(
                    fig=self.figure, func=self.func_plot, frames=self.frames,
                    interval=1000.0 / self.frames, blit=False)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec_())


text:
Q: Installing Using Terminal Brings Up Long List of Auto Removable 'Options' So I'm using the terminal to install a few programs, little minor things like visual boy advance and such. Every time I do, it makes a rather gigantic list of things that can be removed with autoremove and I have no idea if it's even safe to consider doing it or not. A lot of it sounds like very important things.
List as follows:
The following packages were automatically installed and are no longer required:
  alien app-install-data apt-xapian-index apturl-common at debugedit
  gir1.2-gmenu-3.0 guile-2.0-libs laptop-detect lib32z1 libc6-i386
  libcaca0:i386 libcdio-cdda1 libcdio-paranoia1 libcurl3:i386
  libdevmapper1.02.1:i386 libevent-2.0-5 libgail-common libgail18 libgc1c2
  libgsoap4 libidn11:i386 libjpeg62 libnatpmp1 libpod-plainer-perl
  libpython2.7:i386 libpython2.7-minimal:i386 libpython2.7-stdlib:i386
  libreadline6:i386 libreoffice-gtk librpmbuild3 librpmsign1 librtmp0:i386
  libsdl1.2debian:i386 libsigsegv2 libxmu6:i386 lsb-security m4 ncurses-term
  oneconf oneconf-common pax python-debtagshw python-lxml python-oneconf
  python-piston-mini-client python3-oneconf python3-piston-mini-client
  python3-xdg rpm software-center-aptdaemon-plugins transmission-common
  ubuntu-extras-keyring

Can someone tell me if this is normal and a viable thing to do, or if it's abnormal and to not use autoremove?

A: Personally, I've never had any problems autoremoving, however, other users have reported the uninstallation of all kinds of stuff they didn't want to uninstall so there is the very real possibility of unforeseen consequences.
If you are the kind of person that would rather not have to fix things, you should probably leave it alone.


text:
Q: ElasticSearch : special characters while searching I have an elastic search index where I am searching on a field whose analyzer is 'english'. I had a problem with queries with special characters, and I found this :
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#_reserved_characters
Is there a clean way to create an escaped version of the query in java ? Lucenes query parser does not cover all the characters which ES needs to escape.


text:
Q: A python script that automatically input some text in a website and get its source code I am doing biomedical named extraction using Python.
Now I have to cross check the results from inputting the text to http://text0.mib.man.ac.uk/software/geniatagger/ and parse the source code of the HTML text that I get after submitting text into it.
I want that the same thing to be done in my GUI itself i.e. it input from GUI that I have made and submit the text into this website and get the source code so that for cross checking I don't have to visit each time from the browser.
Thanks in advance

A: Actually, this is a great question!
First thing you have to do is to explore a source code of the website a little bit.
If you look at the source code of the website you see this block of code
<form method="POST" action="a.cgi">

Please enter a text that you want to analyze.

<textarea name="paragraph" rows="15" cols="80" wrap="soft">
... some text here ...
### This is a sample. Replace this with your own text.

</textarea>

<input type="submit" value="Submit Text" />
<input type="reset" />

</form>

What you see is that request is send to a.cgi address, since we are already on address
http://text0.mib.man.ac.uk/software/geniatagger/

The data we want to send will be send to address concatenated with this one
http://text0.mib.man.ac.uk/software/geniatagger/a.cgi

But what are we going to send there?
We need a data, data are send as "paragraph" POST parameter, you see that since form has attribute method with value POST, and name of textarea is "paragraph"
We open this using this python code
import urllib
import urllib2

text =  """
        Further, while specific constitutive binding to the peri-kappa B site is seen in monocytes, stimulation with phorbol esters induces additional, specific binding. Understanding the monocyte-specific function of the peri-kappa B factor may ultimately provide insight into the different role monocytes and T-cells play in HIV pathogenesis.

### This is a sample. Replace this with your own text.
        """
data = {
        "paragraph" : text
       }

encoded_data = urllib.urlencode(data)
content = urllib2.urlopen("http://text0.mib.man.ac.uk/software/geniatagger/a.cgi",
        encoded_data)
print content.readlines()

And what do we get so far? We got an "engine" for your GUI program.
What you can do is parse this content variable with python's HTMLParser (optional)
And you mentioned that you want to display this in GUI?
You can do this using GTK or Qt and map this functionality to a single button, you must read a tutorial , it's really easy for this purpose. If you have problems just comment this post and I can extend this answer with GUI


text:
Q: The diversity of Riemannian metrics adapted to a given foliation، A Krein Millman view point(2) Inspired by this answer to the linked   question we add a  more bounded conditions to this post. This question is asked seperately because the previous one had a complete answer so we did not revise it.
Let $X$ be a Kronecker vector field on the two dimensional torus $\mathbb{T}^2$. The torus is equiped  with the standard metric and the corresponding Hodge operator is denoted by $*$.
Let $K$  be the space of  all 1- forms $\alpha$ of class $C^1$ on $\mathbb{T}^2$ which satisfy $d\alpha=0,\;\alpha(X)=1$  and $|*\alpha(X)|\leq 1$. The later norm is the usual supnorm of the space of functions.
Then $K$ is  a  convex $C^1$- closed subset of  all  $C^1$  1-forms on $\mathbb{T}^2$.

Is $K$ a compact  subset of the space of 1-forms with respect to $C^1$ topology? If  the  answer is affirmative. according to the Krein Millman theorem, what is a presise description of its  extreme points of  $K$?

Does the topological structure of $K$ depends on chosing the vector field $X$ tangent to our initial Kronecker foliation of torus? Does the topological structure of $K$ depend on the slope of our Kronecker foliation?

Motivation:
A motivation for this  question is the following:
In this post and  some  other related linked posts we try to  find  a Riemannian metric compatible to orbits of  a  non vanishing vector  fields. Choosing various metrics enable us to have different  curvatuare functions. Possessing  an appropriate curvature function is very essential for appllying the Gauss Bonnet theorem to the problem of limit cycles of  vctor fields.(For counting them as closed geodesics). So this situation leads us to think about the diversity of closed differential 1-forms $\alpha$  with $\alpha(X)=1$. Under these conditions, in particular the propery of  closed convexity of this set $K$.  one is tempt  to be  curious  about the presice description of   possible extrem points of $K$.


text:
Q: A Wallis-like formula for $\pi$: $(\frac21)^2(\frac23)^2(\frac43)^2(\frac45)(\frac65)^2(\frac67)^2(\frac87)(\frac89)^2\cdots$ I don't quite understand this and would appreciate a clear explanation, if possible.
If we begin with the Wallis product for $\frac{\pi}{2}$,
$$\prod_{n=1}^\infty \left( \frac{2n}{2n-1} \cdot \frac{2n}{2n+1} \right) = \Big(\frac{2}{1} \cdot \frac{2}{3}\Big) \cdot \Big(\frac{4}{3} \cdot \frac{4}{5}\Big) \cdot \Big(\frac{6}{5} \cdot \frac{6}{7}\Big) \cdot \Big(\frac{8}{7} \cdot \frac{8}{9}\Big) \cdot \; \cdots \\ = \Big(\frac{2}{1}\Big) \cdot \Big( \frac{2}{3}\Big) \cdot \Big(\frac{4}{3}\Big) \cdot \Big(\frac{4}{5}\Big) \cdot \Big(\frac{6}{5}\Big) \cdot \Big(\frac{6}{7}\Big) \cdot \Big(\frac{8}{7}\Big) \cdot \Big(\frac{8}{9}\Big) \cdot \; \cdots \\ = \frac{\pi}{2}$$
By squaring only factors whose numerator and denominator sum to primes, we obtain
$$\Big(\frac{2}{1}\Big)^2 \cdot \Big( \frac{2}{3}\Big)^2 \cdot \Big(\frac{4}{3}\Big)^2 \cdot \Big(\frac{4}{5}\Big) \cdot \Big(\frac{6}{5}\Big)^2 \cdot \Big(\frac{6}{7}\Big)^2 \cdot \Big(\frac{8}{7}\Big) \cdot \Big(\frac{8}{9}\Big)^2 \cdot \; \cdots  = \pi\\$$
Why?

A: We have to show that the product of those factors is (convergent and) equal to $2$.
The factors are precisely $\frac{p-\chi(p)}{p+\chi(p)}$, where $p$ runs through odd primes, and $$\chi(n)=\begin{cases}(-1)^{(n-1)/2},&n\text{ is odd}\\\hfill 0,\hfill&n\text{ is even}\end{cases}$$ is known as the non-trivial Dirichlet character modulo $4$, and we know that $$\prod_p\big(1-\chi(p)p^{-s}\big)^{-1}=\sum_{n>0}\chi(n)n^{-s}=\sum_{n=0}^\infty\frac{(-1)^n}{(2n+1)^s}\qquad(\Re s>1)$$ since $\chi$ is completely multiplicative. The (harder!) fact that the equality holds at $s=1$ is a particular case of the result discussed here; you may also want to follow the links out there. The sum at $s=1$ is well-known to be $\pi/4$, thus $\prod_p\big(1-\chi(p)/p\big)=4/\pi$. As $$\frac{1-\chi(p)/p}{1+\chi(p)/p}=\frac{\big(1-\chi(p)/p\big)^2}{1-\big(\chi(p)/p\big)^2}=\frac{\big(1-\chi(p)/p\big)^2}{1-1/p^2},$$ and $\prod_p(1-1/p^2)^{-1}=(1-1/4)$$\zeta(2)$$=\pi^2/8$ since the product is over odd primes, we find $$\prod_p\frac{p-\chi(p)}{p+\chi(p)}=\left(\frac{4}{\pi}\right)^2\frac{\pi^2}{8}=2$$ as expected.


text:
Q: Css Grid media query element pushed outside I am trying to learn CSS grid but some strange issue keeps acquiring. So I am building a simple grid with 5 areas Header, Main Footer left sidebar, and right sidebar. It works fine and here is the code but when resizing for some strange reason right sidebar appears beneath the grid on the right here is also my codepen https://codepen.io/yuri-gaiduk/pen/xxOOOda. Just to clarify after the media query is applied I only want to see Header, Midlle, and Footer

On left

Heade

On right

Main

Footer

and here is the css
.container{
           display:grid;
           grid-template-columns:auto;
           grid-template-rows:auto;
           grid-template-areas:
                              "leftbar header header header rightbar"
                              "leftbar midle midle midle rightbar"
                              "leftbar midle midle midle rightbar"
                              "leftbar midle midle midle rightbar"
                              "leftbar midle midle midle rightbar"
                              "leftbar midle midle midle rightbar"
                              "footer footer footer footer footer";
           height:400px;
       }

      .box{
          border:1px solid black;
          width:100%;
          height:100%;
          text-align:center;
      }

     .rigth-bar{
          grid-area:rightbar;
     }

     .left-bar{
          grid-area:leftbar;
     }

    .header{
          grid-area:header;
    }

    .main{
          grid-area:midle;
    }

    .bottom{
          grid-area:footer;
    }

    .red_box{
          background-color:red;
    }

    .orange_box{
          background-color:orange;
    }

   .blue_box{
         background-color:blue;
    }

   .green_box{
         background-color:green;
   }

   .coral_box{
         border:1px solid black;
         background-color:coral;
         width:100%;
         height:100%;
         text-align:center;
   }

  @media (max-width:1000px){
      .container{
          grid-template-areas:
                             "header header header"
                             "midle midle midle"
                             "midle midle midle"
                             "midle midle midle"
                             "midle midle midle"
                             "midle midle midle"
                             "footer footer footer";
       }

  }

A: Leaving leftbar and rightbar out of your grid-template-areas won't remove those elements from the DOM, it will just take them out of the grid. Your left-bar is actually directly behind your right-bar when your media query is active (which is why you can't see it).
You'll also want to set display: none on them:
.left-bar, .rigth-bar{
  display: none;
}

Here's an example snippet from your code pen:

.container {
  display: grid;
  grid-template-columns: auto;
  grid-template-rows: auto;
  grid-template-areas: "leftbar header header header rightbar" "leftbar midle midle midle rightbar" "leftbar midle midle midle rightbar" "leftbar midle midle midle rightbar" "leftbar midle midle midle rightbar" "leftbar midle midle midle rightbar" "footer footer footer footer footer";
  height: 400px;
}

.box {
  border: 1px solid black;
  width: 100%;
  height: 100%;
  text-align: center;
}

.rigth-bar {
  grid-area: rightbar;
}

.left-bar {
  grid-area: leftbar;
}

.header {
  grid-area: header;
}

.main {
  grid-area: midle;
}

.bottom {
  grid-area: footer;
}

.red_box {
  background-color: red;
}

.orange_box {
  background-color: orange;
}

.blue_box {
  background-color: blue;
}

.green_box {
  background-color: green;
}

.coral_box {
  border: 1px solid black;
  background-color: coral;
  width: 100%;
  height: 100%;
  text-align: center;
}

@media (max-width:1000px) {
  .container {
    grid-template-areas: "header header header" "midle midle midle" "midle midle midle" "midle midle midle" "midle midle midle" "midle midle midle" "footer footer footer";
  }
  .left-bar,
  .rigth-bar {
    display: none;
  }
}

On left

Heade

On right

Main

Footer


text:
Q: docker networking in Multi host in same network I have two ubuntu os in my system . I install docker in both ubuntu and create a containers in both the dockers and i need to communicate with the networks ...

A: Run your container using option --net=host. This way, both containers will have an IP address in your local network.
An example for a container called ubuntu:
docker run -d --name ubuntu --net=host ubuntu


text:
Q: Why is my Windows 7 using so much memory? Ok so I open the task manager, select show all processes from all users and about 20-30 processes come up totalling around 500mb usage max od memory, when I then click the Performance tab, it shows as 1.4GB being used! Where is it eating up all this extra memory? Is this a built in feature to reserve memory or something?
Also anyone know why the Hard Disk gets hammered so much too when its idle? Not badly hammered just constantly flashing..

A: For the RAM, caching. Your HDD is about 40 times slower than your RAM, so programs preloaded into RAM load significantly faster. For the HDD, indexing, which lends the search it's speed and flexibility.

A: All this behavior is part of technologies introduced in Windows Vista such as SuperFetch and File Indexing. Your account of your available RAM and disk activity is normal and expected. I share with you similar numbers.


text:
Q: Efficient use of Python list comprehensions I have a Python list of objects that could be pretty long. At particular times, I'm interested in all of the elements in the list that have a certain attribute, say flag, that evaluates to False. To do so, I've been using a list comprehension, like this:
objList = list()
# ... populate list
[x for x in objList if not x.flag]

Which seems to work well. After forming the sublist, I have a few different operations that I might need to do:

*

*Subscript the sublist to get the element at index ind.

*Calculate the length of the sublist (i.e. the number of elements that have flag == False).

*Search the sublist for the first instance of a particular object (i.e. using the list's .index() method).

I've implemented these using the naive approach of just forming the sublist and then using its methods to get at the data I want. I'm wondering if there are more efficient ways to go about these. #1 and #3 at least seem like they could be optimized, because in #1 I only need the first ind + 1 matching elements of the sublist, not necessarily the entire result set, and in #3 I only need to search through the sublist until I find a matching element.
Is there a good Pythonic way to do this? I'm guessing I might be able to use the () syntax in some way to get a generator instead of creating the entire list, but I haven't happened upon the right way yet. I obviously could write loops manually, but I'm looking for something as elegant as the comprehension-based method.

A: If you need to do any of these operations a couple of times, the overhead of other methods will be higher, the list is the best way. It's also probably the clearest, so if memory isn't a problem, then I'd recommend just going with it.
If memory/speed is a problem, then there are alternatives - note that speed-wise, these might actually be slower, depending on the common case for your software.
For your scenarios:
#value = sublist[n]
value = nth(x for x in objList if not x.flag, n)

#value = len(sublist)
value = sum(not x.flag for x in objList)

#value = sublist.index(target)
value = next(dropwhile(lambda x: x != target, (x for x in objList if not x.flag)))

Using itertools.dropwhile() and the nth() recipe from the itertools docs.

A: I'm going to assume you might do any of these three things, and you might do them more than once.
In that case, what you want is basically to write a lazily evaluated list class. It would keep two pieces of data, a real list cache of evaluated items, and a generator of the rest. You could then do ll[10] and it would evaluate up to the 10th item, ll.index('spam') and it would evaluate until it finds 'spam', and then len(ll) and it would evaluate the rest of the list, all the while caching in the real list what it sees so nothing is done more than once.
Constructing it would look like this:
LazyList(x for x in obj_list if not x.flag)

But nothing would actually be computed until you actually start using it as above.

A: Since you commented that your objList can change, if you don't also need to index or search objList itself, then you might be better off just storing two different lists, one with .flag = True and one with .flag = False. Then you can use the second list directly instead of constructing it with a list comprehension each time.
If this works in your situation, it is likely the most efficient way to do it.


text:
Q: $exception {"unexpected token 'creator'"} Microsoft.Scripting.SyntaxErrorException I have a C# application through which I want to run a python script. What python script does is it takes a doc files and create other 3 doc files.
I'm getting an error from this code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Project_new
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {

            InitializeComponent();
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Button Welcome = new Button();
            Welcome.Click += new RoutedEventHandler(Welcome_Click);
            ComboBoxItem cbi = (ComboBoxItem)(sender as ComboBox).SelectedItem;
        }

        private void Welcome_Click(object sender, RoutedEventArgs e)
        {

            var ComboItem = new1.SelectedValue;// Item;// (ComboBoxItem)cmbDeviceDefinitionId.SelectedItem;
             string s = ((System.Windows.FrameworkElement)ComboItem).Name;
            //string name = ComboItem. Name;
            if (new1.SelectedValue == cbi1)
                {
                Window1 win1 = new Window1();
                win1.Show();
                this.Close();

                // python script to be loaded
                    var ipy = Python.CreateRuntime();
                    string importScript = "import sys" + Environment.NewLine + "sys.path.append(r\"{0}\")" + Environment.NewLine + "from {1} import *";
                    string fullPath = @"C:\Users\gpathak\Documents\new scripts\Automation Scripts (Packet Range)\Document_creator\document creator track to train.py";
                    var engine = Python.CreateEngine();
                    ScriptScope scope = engine.CreateScope();

                // import the module//
                      string scrpitStr = string.Format(importScript,
        System.IO.Path.GetDirectoryName(fullPath),
                        System.IO.Path.GetFileNameWithoutExtension(fullPath));
                    var importSrc = engine.CreateScriptSourceFromString(scrpitStr, Microsoft.Scripting.SourceCodeKind.File);
                    importSrc.Execute(scope);
                    string expr = "functionOfMyModule()";
                    var result = engine.Execute(expr, scope);
            }
            else if (new1.SelectedValue == cbi2)
            {
                Window2 win2 = new Window2();
                win2.Show();
                this.Close();

            }
            else
            {
                Window3 win3 = new Window3();
                win3.Show();
                this.Close();

            }

        }
    }
}

I'm getting this error:
Microsoft.Scripting.SyntaxErrorException occurred
  HResult=0x80131500
  Message=unexpected token 'creator'
  Source=<Cannot evaluate the exception source>
  StackTrace:`enter code here
   at Microsoft.Scripting.ErrorSink.Add(SourceUnit source, String message, SourceSpan span, Int32 errorCode, Severity severity)
   at IronPython.Compiler.Parser.ReportSyntaxError(Token t, SourceSpan span, Int32 errorCode, Boolean allowIncomplete)
   at IronPython.Compiler.Parser.ParseFromImportStmt()
   at IronPython.Compiler.Parser.ParseSmallStmt()
   at IronPython.Compiler.Parser.ParseSimpleStmt()
   at IronPython.Compiler.Parser.ParseStmt()
   at IronPython.Compiler.Parser.ParseFileWorker(Boolean makeModule, Boolean returnValue)
   at IronPython.Compiler.Parser.ParseFile(Boolean makeModule, Boolean returnValue)
   at IronPython.Runtime.PythonContext.ParseAndBindAst(CompilerContext context)
   at IronPython.Runtime.PythonContext.CompilePythonCode(Nullable`1 compilationMode, SourceUnit sourceUnit, CompilerOptions options, ErrorSink errorSink)
   at IronPython.Runtime.PythonContext.CompileSourceCode(SourceUnit sourceUnit, CompilerOptions options, ErrorSink errorSink)
   at Microsoft.Scripting.SourceUnit.Compile(CompilerOptions options, ErrorSink errorSink)
   at Microsoft.Scripting.SourceUnit.Execute(Scope scope, ErrorSink errorSink)
   at Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
   at Project_new.MainWindow.Welcome_Click(Object sender, RoutedEventArgs e) in C:\Users\gpathak\Documents\Visual Studio 2017\Projects\Project new\Project new\MainWindow.xaml.cs:line 65
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
   at System.Windows.Controls.Primitives.ButtonBase.OnClick()
   at System.Windows.Controls.Button.OnClick()
   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
   at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
   at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
   at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
   at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at System.Windows.Application.Run()
   at Project_new.App.Main()

This is the error I'm getting. I want to know why this error is coming. I don't have any problem with python script. Its running fine if I run it on python IDE but when I try run through C# this error is coming.

A: Your file name has space change it to underscore, Space is not allowed in import file name.
Your python code is changed to as follows
import sys
sys.path.append(r"C:\Users\gpathak\Documents\new scripts\Automation Scripts (Packet Range)\Document_creator")
from document creator track to train import *

change your document creator track to train.py file name to document_creator_track_to_train.py and use the same name in your code which will solve the problem.


text:
Q: Downloading a zip file from a given path in express api + react So I'm completely lost at this point. I have had a mixture of success and failure but I can't for the life of me get this working. So I'm building up a zip file and storing it in a folder structure that's based on uploadRequestIds and that all works fine. I'm fairly new to the node but all I want is to take the file that was built up which is completely valid and works if you open it once it's been constructed in the backend and then send that on to the client.
const prepareRequestForDownload = (dirToStoreRequestData, requestId) => {
  const output = fs.createWriteStream(dirToStoreRequestData + `/Content-${requestId}.zip`);
  const zip = archiver('zip', { zlib: { level: 9 } });

  output.on('close', () => { console.log('archiver has been finalized.'); });
  zip.on('error', (err) => { throw err; });

  zip.pipe(output);
  zip.directory(dirToStoreRequestData, false);
  zip.finalize();
}

This is My function that builds up a zip file from all the files in a given directory and then stores it in said directory.
all I thought I would need to do is set some headers to have an attachment disposition type and create a read stream of the zip file into the res.send function and then react would be able to save the content. but that just doesn't seem to be the case. How should this be handled on both the API side from reading the zip and sending to the react side of receiving the response and the file auto-downloading/requesting a user saves the file.
This is what the temp structure looks like

A: There is some strategies to resolve it, all browser when you redirect to URL where extension ending with .zip, normally start downloading. What you can do is to return to your client the path for download something like that.
http://api.site.com.br/my-file.zip
and then you can use:

window.open('URL here','_blank')


text:
Q: Visual Studio 2010 Windows Forms Designer Problems Isn't that a crazy error?
I get this when trying to open a form containing some UserControls from another assebly and using Entity Framework and SQL CE on visual studio designer.
Object of type Namespace.T[] cannot be converted to type Namespace.T[]!!!
Call Stack:
at System.RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast) at System.RuntimeType.CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr) at System.Reflection.RtFieldInfo.InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, Boolean doVisibilityCheck, Boolean doCheckConsistency) at System.Runtime.Serialization.FormatterServices.SerializationSetValue(MemberInfo fi, Object target, Object value) at System.Runtime.Serialization.ObjectManager.CompleteObject(ObjectHolder holder, Boolean bObjectFullyComplete) at System.Runtime.Serialization.ObjectManager.DoNewlyRegisteredObjectFixups(ObjectHolder holder) at System.Runtime.Serialization.ObjectManager.RegisterObject(Object obj, Int64 objectID, SerializationInfo info, Int64 idOfContainingObj, MemberInfo member, Int32[] arrayIndex) at System.Runtime.Serialization.Formatters.Binary.ObjectReader.RegisterObject(Object obj, ParseRecord pr, ParseRecord objectPr, Boolean bIsString) at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ParseObjectEnd(ParseRecord pr) at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Parse(ParseRecord pr) at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run() at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream) at System.Resources.ResXDataNode.GenerateObjectFromDataNodeInfo(DataNodeInfo dataNodeInfo, ITypeResolutionService typeResolver) at System.Resources.ResXDataNode.GetValue(ITypeResolutionService typeResolver) at System.Resources.ResXResourceReader.ParseDataNode(XmlTextReader reader, Boolean isMetaData) at System.Resources.ResXResourceReader.ParseXml(XmlTextReader reader)
But its the same name type exactly!
The project builds successfully and runs ok!!!
OK i deleted the .resx file of the form and now i get 2 other errors i thought i have passed.
1st is "The specified named connection, not intended to be used with the EntityClient provider, or not valid"
Call Stack:
at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString) at System.Data.EntityClient.EntityConnection..ctor(String connectionString) at System.Data.Objects.ObjectContext.CreateEntityConnection(String connectionString) at System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName) at DJPro.Settings.Model.SettingsEntities..ctor() in D:\Visual Studio Projects\DJProAutomation\DJPro.Settings.Model\SettingsSelfTrackModel.Context.cs:line 33 at DJPro.Data.Access.SettingsDataOperations.GetConfiguration() in D:\Visual Studio Projects\DJProAutomation\DJPro.Data.Access\SettingsDataOperations.cs:line 33 at DJPro.Studio.Controls.DeckControl..ctor() in D:\Visual Studio Projects\DJProAutomation\DJPro.Deck.Controls\DeckControl.cs:line 51
2nd is about a control i have on a library saying.
"The variable deckControl1 is either undeclared or was never assigned"
Call Stack:
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.Error(IDesignerSerializationManager manager, String exceptionText, String helpLink) at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression) at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression) at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)
Then restored from a backup the resx file and im going back to the first problem.
So strange errors, everything seems fine in the Entity Data Model libraries and the app.config has all the necessary connection strings. As for the deckControl1 UserControl it seems fine to the library i have created it and opens ok.
I think this gets me crazy enough and stops the development.
Any idea?

A: It looks like you have a version conflict between the assembly used to generate the ResX and the currently referenced assembly.
Try removing the reference, re-adding it as a project reference, and regenerating the ResX.

A: Found the problem, if you use in UserControl constructor code that initializes entity framework context provides problems....even problem can occur while trying to initialize context for data operations in the Load event handler.
Tricky!


text:
Q: How to add sqlite command line tool to Docker aspnet:5.0-alpine image? I have docker image based on aspnet:5.0-alpine that I would like to add the sqlite3 command line tool so I can open a shell prompt and examine database files. I have tried adding these commands to my Dockerfile
RUN apk update && apk upgrade
RUN apk add --no-cache sqlite-dev

but the image only contains the sqlite libraries, not the sqlite3 command line tool.
Is there a way to add the sqlite3 command tool to the image?

A: The command line tool is in the sqlite package.
RUN apk update && apk upgrade
RUN apk add --no-cache sqlite

Should add it.


text:
Q: How to restore default sharing extension under Yosemite OS X Yosemite introduce few extensions like sharing extensions. With some defaults one like share with Apple Mail, iMessage, ... but today thoses extensions are missing for me. Is there's any knowed way, even with CLI to restaure them ?

A: run /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -kill -seed


text:
Q: Query Jetpack Wordpress Stats List I want to show the most viewed post from the week in a widget.
<?php

function filter_where($where = '') {
    //posts in the last 30 days
    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
    return $where;
}
add_filter('posts_where', 'filter_where');

query_posts('post_type=post&posts_per_page=4&orderby=rand&order=DESC');

while (have_posts()): the_post(); ?>

<a href="<?php the_permalink(); ?>" title="<?php printf(esc_attr('Permalink to %s'), the_title_attribute('echo=0')); ?>" rel="bookmark"><?php the_title(); ?>

<?php
endwhile;
wp_reset_query();
?>

I'm using this one, because Jetpack doesn't allow me to query the most viewed post.

A: You can try this method:
<?php
// creating the post views DB table
add_action('wp_head', 'create_post_views_table');
function create_post_views_table() {
    global $wpdb;
    // our table name
    $table_name = $wpdb->prefix . "post_views";
    // SQL for creating the table
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            meta_id int(11) NOT NULL AUTO_INCREMENT,
            post_id int(11) NOT NULL,
            date_viewed datetime NOT NULL,
            PRIMARY KEY (meta_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";
    // we're using functions from the WP admin
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    // executing the SQL
    dbDelta($sql);
}
?>

<?php
// Add this function when user sees the post / most likely in single.php or loop-single etc.

// recording each post view
function update_post_views($postID) {
    global $wpdb;
    // our table name
    $table_name = $wpdb->prefix . "post_views";
    // the current time
    $date = date('Y-m-d H:i:s');
    // the SQL for inserting the view
    $sql = "INSERT INTO $table_name (post_id,date_viewed) VALUES ($postID, '$date')";
    // executing the SQL
    $wpdb->query($sql);
}
?>

<?php
// get the most popular posts for the last X days
function get_most_popular_posts($count = 30, $interval = '') {
    global $wpdb;
    $where = '';
    // adding WHERE clause to specify the date interval
    if ($interval) {
        $where = "
        WHERE date_viewed > ( NOW() - INTERVAL $interval DAY)
        ";
    }
    // building SQL
    $sql = "SELECT post_id, COUNT(post_id) as count
            FROM {$wpdb->prefix}post_views
            {$where}
            GROUP BY post_id
            ORDER BY count DESC
            LIMIT $count
            ";
    // fetching the posts
    $results = $wpdb->get_results($sql);
    return $results;
}
?>


text:
Q: Cloud SQL database failed to connect from mysql client I'm unable to connect to Google Cloud SQL from my desktop mysql client. I am also unable to set the sql instance password in google console. It says "instance is busy". I was able to connect to the sql instance using this same command line few weeks ago. Now it's unclear why it is not allowing the same. I see a similar question being asked before but it does not have any resolution.
c:\mysql --host=xxx.xxx.253.xx --user=root --password
ERROR 1045 (28000): Access denied for user 'root'@'xxx.xxx.214.xxx' (using password: NO)
The reason I'm trying to connect from the command line is that my access to the same DB from GAE is also failing with the same error as below.
com.xxx store: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
This is the first time I'm trying to access the database from a GAE app. Any idea why the mysql client is not connecting and where I should look to troubleshoot?
Edit:
mysql client connection issue is resolved by upgrading to a newer mysql version (5.6.19). The GAE connection issue persists.
The jdbc url I use is
"jdbc:google:mysql://projid:sqlinstance/dbname?user=root&password=root"

A: The GAE connection issue was resolved by removing the password from the URL. The new jdbc
url is "jdbc:google:mysql://projid:sqlinstance/dbname?user=root".


text:
Q: Google js API to create pie chart with JSON data I am using Google jsapi to create pie chart using JSON data from getData.php. But my code is not working as expected.
getData.php
<?php  header('Content-Type: application/json');

$mysqli = new mysqli("localhost", "root", "", "test");

if ($mysqli->connect_errno)
{
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$query01="SELECT a.ratings,
                 a.name
            FROM programming_languages a";
$res01=mysqli_query($mysqli,$query01);

$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(

    // Labels for your chart, these represent the column titles
    // Note that one column is in "string" format and another one is in "number" format as pie chart only
    // required "numbers" for calculating percentage and string will be used for column title
    array('label' => 'name', 'type' => 'string'),
    array('label' => 'ratings', 'type' => 'number')
);

$rows = array();
while($r = $res01->fetch_array(MYSQLI_ASSOC)) {
    $temp = array();
    // the following line will be used to slice the Pie chart
    $temp[] = array('v' => (string) $r['name']);

    // Values of each slice
    $temp[] = array('v' => (int) $r['ratings']);
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>

Here is jQuery script:
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);

function drawChart() {
      var jsonData = $.ajax({
          url: "getData.php",
          dataType: "json",
          async: false
          }).responseText;

      var data = new google.visualization.DataTable(jsonData);

      var chart = new google.visualization.PieChart(document.getElementById('chart_div2'));
      chart.draw(data, {width: 500, height: 400});
    }

Here is my php array:
 [
    {
        "name": "C",
        "ratings": "17"
    },
    {
        "name": "Java",
        "ratings": "16"
    },
    {
        "name": "C++",
        "ratings": "9"
    },
    {
        "name": "Objective-C",
        "ratings": "2"
    }
 ]


text:
Q: Let $G$ be a group and let $H_1,H_2\unlhd G$ such that $H_1\cap H_2 = \{1\}$ and $H_1H_2=G.$ Prove $G\simeq H_1\times H_2$ I'm having some struggles with the following exercise:

Let $G$ be a group and let $H_1,H_2\unlhd G$ such that $H_1\cap H_2 = \{1\}$ and $H_1H_2=G.$
Prove that $G\simeq H_1\times H_2$

Because $H_1H_2=G$ we can write any element $g$ of $G$ as:
$$g=h_1h_2$$
with $h_1\in H_1$ and $h_2 \in H_2$ and then I proved that this way representing elements of $G$ is unique. Then I considered the following  function:
$$f:G\longrightarrow H_1\times H_1 $$
$$g(=h_1h_2)\mapsto(h_1,h_2)$$
I already showed that $f$ is bijective but I'm having some struggle proving that $f$ is a homomorphism. How can this be proved?

A: The idea is to show that if $x\in H_1$ and $y\in H_2$, then $xy=yx$.
This is equivalent to showing that $xy(yx)^{-1}=1$, so to
$$
xyx^{-1}y^{-1}=1
$$
Now note that $xyx^{-1}\in H_2$, so $xyx^{-1}y^{-1}\in H_2$ as well. Also $yx^{-1}y^{-1}\in H_1$, so $xyx^{-1}y^{-1}\in H_1$. Both statements follows from the subgroups being normal.
Since $H_1\cap H_2=\{1\}$ we have the proof.
The rest follows easily: the map $H_1\times H_2\to G$ defined by $(h_1,h_2)\mapsto h_1h_2$ is quite obviously a homomorphism, due to the above property. Prove it is an isomorphism.


text:
Q: Square transactions Api - retrieving request results Please help me understand what I need to do next. I am using square transactions API to accept payments on an ecommerce website. I got the nonce from the form generated and I want I get the following response below. I now need to retrieve values from this response and store them in variables so that I can move on to create a purchase order for the order to be fulfilled.
SquareConnect\Model\ChargeResponse Object
(
    [errors:protected] =>
    [transaction:protected] => SquareConnect\Model\Transaction Object
        (
            [id:protected] => ...
            [location_id:protected] => ...
            [created_at:protected] => 2018-08-05T15:45:48Z
            [tenders:protected] => Array
                (
                    [0] => SquareConnect\Model\Tender Object
                        (
                            [id:protected] => ...
                            [location_id:protected] => ..
                            [transaction_id:protected] => ...
                            [created_at:protected] => 2018-08-05T15:45:48Z
                            [note:protected] => Online Transaction
                            [amount_money:protected] => SquareConnect\Model\Money Object
                                (
                                    [amount:protected] => 20448
                                    [currency:protected] => USD
                                )

                            [tip_money:protected] =>
                            [processing_fee_money:protected] =>
                            [customer_id:protected] =>
                            [type:protected] => CARD
                            [card_details:protected] => SquareConnect\Model\TenderCardDetails Object
                                (
                                    [status:protected] => CAPTURED
                                    [card:protected] => SquareConnect\Model\Card Object
                                        (
                                            [id:protected] =>
                                            [card_brand:protected] => VISA
                                            [last_4:protected] => 1111
                                            [exp_month:protected] =>
                                            [exp_year:protected] =>
                                            [cardholder_name:protected] =>
                                            [billing_address:protected] =>
                                            [fingerprint:protected] =>...
                                        )

                                    [entry_method:protected] => KEYED
                                )

                            [cash_details:protected] =>
                            [additional_recipients:protected] =>
                        )

                )

            [refunds:protected] =>
            [reference_id:protected] =>
            [product:protected] => EXTERNAL_API
            [client_id:protected] =>
            [shipping_address:protected] =>
            [order_id:protected] =>
        )
)

I just need the result of the transaction confirming that the card is charged

A: You'll need to use Getter methods to access the private attributes. For example: https://github.com/square/connect-php-sdk/blob/master/docs/Model/ChargeResponse.md