text:
Q: How to solve org.hibernate.exception.SQLGrammarException: could not execute query What I am trying to achieve is to find the available vehicles by comparing time stamps in the database.so When I execute the following query it gives the following runtime exception SQL GrammerException. But I can't identify any direct syntax issue in this query.Please help me to solve this issue thank you in advance.
Query
 @Query(value = "SELECT id From VEHICLE WHERE id NOT IN (SELECT id FROM VEHICLE_BOOKING  WHERE  (HIRE_DATE_TIME <= ?1 AND RETURN_DATE_TIME >= ?1) OR (RETURN_DATE_TIME < ?2 AND RETURN_DATE_TIME >= ?2 )  OR ( ?1 <= HIRE_DATE_TIME AND ?2 >= RETURN_DATE_TIME) )",nativeQuery = true)
    List<Vehicle> checkAvailability( Date hireDateTime,Date returnDateTime);

Exception
org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; SQL [SELECT id From VEHICLE WHERE id NOT IN (SELECT id FROM VEHICLE_BOOKING  WHERE  (HIRE_DATE_TIME <= ? AND RETURN_DATE_TIME >= ?) OR (RETURN_DATE_TIME < ? AND RETURN_DATE_TIME >= ? )  OR ( ? <= HIRE_DATE_TIME AND ? >= RETURN_DATE_TIME) )]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:281)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:149)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy98.checkAvailability(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:205)
    at com.sun.proxy.$Proxy67.checkAvailability(Unknown Source)
    at com.banger.rentalmanagementsystem.controller.CustomerController.showUserProfile(CustomerController.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.exception.SQLGrammarException: could not execute query
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
    at org.hibernate.loader.Loader.doList(Loader.java:2890)
    at org.hibernate.loader.Loader.doList(Loader.java:2869)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2701)
    at org.hibernate.loader.Loader.list(Loader.java:2696)
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:338)
    at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:2142)
    at org.hibernate.internal.AbstractSharedSessionContract.list(AbstractSharedSessionContract.java:1163)
    at org.hibernate.query.internal.NativeQueryImpl.doList(NativeQueryImpl.java:173)
    at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1533)
    at org.hibernate.query.Query.getResultList(Query.java:165)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:126)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:88)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:154)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:142)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor$QueryMethodInvoker.invoke(QueryExecutorMethodInterceptor.java:195)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:152)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    ... 65 more
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Column "ac" not found [42122-200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:453)
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
    at org.h2.message.DbException.get(DbException.java:205)
    at org.h2.message.DbException.get(DbException.java:181)
    at org.h2.jdbc.JdbcResultSet.getColumnIndex(JdbcResultSet.java:3195)
    at org.h2.jdbc.JdbcResultSet.get(JdbcResultSet.java:3268)
    at org.h2.jdbc.JdbcResultSet.getString(JdbcResultSet.java:316)
    at com.zaxxer.hikari.pool.HikariProxyResultSet.getString(HikariProxyResultSet.java)
    at org.hibernate.type.descriptor.sql.VarcharTypeDescriptor$2.doExtract(VarcharTypeDescriptor.java:62)
    at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:243)
    at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:329)
    at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:3088)
    at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1907)
    at org.hibernate.loader.Loader.hydrateEntityState(Loader.java:1835)
    at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1808)
    at org.hibernate.loader.Loader.getRow(Loader.java:1660)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:745)
    at org.hibernate.loader.Loader.getRowsFromResultSet(Loader.java:1044)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:995)
    at org.hibernate.loader.Loader.doQuery(Loader.java:964)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:350)
    at org.hibernate.loader.Loader.doList(Loader.java:2887)
    ... 88 more

A: You need to return list of objects not list of ids, so you query should be something like this
@Query(value = "SELECT v From VEHICLE AS v WHERE id NOT IN (SELECT id FROM VEHICLE_BOOKING  WHERE  (HIRE_DATE_TIME <= ?1 AND RETURN_DATE_TIME >= ?1) OR (RETURN_DATE_TIME < ?2 AND RETURN_DATE_TIME >= ?2 )  OR ( ?1 <= HIRE_DATE_TIME AND ?2 >= RETURN_DATE_TIME) )",nativeQuery = true)

A: Syntax bcuz you select the only id to map a List,
Btw, I recommend that avoid using nativeQuery which lost benefit of JPA


text:
Q: Connect to H2 database using Datagrip client Connecting to local h2 db from Datagrip Client is failing with the below error

A file path that is implicitly relative to the current working
  directory is not allowed in the database URL
  "jdbc:h2:file:localhost:8082/test". Use an absolute path, ~/name,
  ./name, or the baseDir setting instead.

A: Where are the Database Files Stored? section in http://www.h2database.com/html/faq.html helped me to configure and connect.
DB URL Ex: jdbc:h2:file:C:/db-workspace/h2/data/test

A: Change data source Connection type to Embedded and specify path to your database file.

For additional options read H2 database URL overview

redpajama_set_name: RedPajamaStackExchange


text:
Q: MVVM and SingleSelectionModel in ComboBoxes in JavaFX I'm having trouble doing wiring a ComboBox.selectionModelProperty to my ViewModel.
The problem resides that the property is of type SingleSelectionModel, which is an interface and not really easy to instantiate. My idea was to instantiate a ObjectProperty<SingleSelectionModel> in the ViewModel and then bind it to ComboBox.selectionModelProperty.
class ViewModel {
  val selectedService = new SimpleObjectProperty[SingleSelectionModel[ServiceId]]()
  ..

  // I want to set an initial value but now I have a problem..
  // there's no easy way of instantiating a SingleSelectionModel
  // without resorting to roll out my own implementation of a
  // SingleSelectionModel.
}

*

*I assume this must be a common issue to whoever is doing MVVM (or something similar, for that matter), or am I doing something wrong?

*My take is that it makes sense for the ViewModel to always create its properties / bindings and then have the View's code-behind to apply the bindings -- it should be "in control" of the life-cycle of its properties/bindings and that includes their creation. Am I correct?

*Another option would be to have in my ViewModel just a property with the value my selection would take (let's say, a Color) and then it would be up to the View to do the conversion to a SingleSelectionModel, but it seems to me that the APIs are not really geared towards that. Are they?

Thanks!


text:
Q: Angular model is not being updated on animate complete callback The following HTML is included in my ng-controller div

{{ card.programName }}

 limit && isNotLastPage" ng-click="getNextCards()">

When I click getNextCards I will execute a HTTP request to get more cards. On success callback I wanted to start an jQuery animation (code below) and only after being completed I wanted to updated my cards model. But this approach doesn't work, keeping the same cards. Do you have any workaround? Thanks
$( "#cards-slider" ).animate({
    left: "-=500",
}, 100, function() {
    $scope.cards        =   data.elements;
    $scope.cartsTotal   =   data.total;
});

A: It's because the jquery ajax and animate functions are outside angular's digest cycle. You'll need to force a digest manually. Try this:
$( "#cards-slider" ).animate({
    left: "-=500",
}, 100, function() {
    $scope.cards        =   data.elements;
    $scope.cartsTotal   =   data.total;
    if (!$scope.$$phase) { // if digest is not already running
        $scope.apply();
    }
});


text:
Q: Android button onClick to display an AlertDialog application crash I am trying to display an AlertDialog when I press the Submit button.
Button submit = (Button) findViewById(R.id.submitButton);
            submit.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Application1GoodExample.this);
                    builder.setMessage("Your form has been successfully submitted");
                    TextView textView = (TextView) findViewById(android.R.id.message);
                    textView.setTextSize(40);
                    builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
                          public void onClick(DialogInterface dialog, int which) {
                              dialog.cancel();
                        } });

                    builder.show();

                }

            });

I believe it has something to do with it trying to access findViewById(android.R.id.message)
I have defined the TextView in my XML file as follows:
 <TextView android:id="@+id/message"
        android:layout_width="285dp"
        android:layout_height="78dp"
        android:textColor="#000000"
        android:textSize="45sp"
        android:gravity="center"
        />

I just want to change the default AlertDialog message "Your form has been successfully submitted" font size, but my program crashes when I press the Submit button

A: You are trying to access android.R, just remove "android" and it should work (your resources are in com.yourproject.R, not android.R).
findViewById(android.R.id.message)

A: First,if you want to set text size for a TextView in XML,the layout in setContentView()in MainActivity must contain a reference to it.
Second, you should replace android.R.id.message by R.id.message.


text:
Q: Modal topmost WPF Window called by .ShowDialog is shown in background I have a WPF application in which I want to password protect a tabitem in my central tabcontrol.
So I am using the tabControl_SelectionChanged event in my MainWindow.xaml.cs in which I call a modal password dialog if the selected tabitem has a tag = "password".
private void tabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        TabItem selectedItem = (TabItem)e.AddedItems[0];

        if (selectedItem.Tag != null && selectedItem.Tag.Equals("Password"))
        {
            PasswordView pw = new PasswordView();
            pw.Owner = this;
            bool? result = pw.ShowDialog();

            if (result.HasValue && !result.Value)
            {
                tabControl.SelectedItem = tabControl.Items[0];
            }
        }
    }

Here the properties of the password dialog:
Topmost="True"
Title="PasswordView"
WindowStyle="None"
ResizeMode="NoResize"
WindowState="Maximized"
WindowStartupLocation="CenterScreen"
ShowInTaskbar="False"

Properties of MainWindow:
WindowState="Maximized"
WindowStyle="None"
ResizeMode="NoResize"

The view shows a textbox and a button. On button click I am checking the password in the viewmodel and send a MVVMLight message to the password view, so the view can set the DialogResult and closes it self. (I have done it also with the DialogCloser with databinding the DialogResult and I got the same result)
In the viewmodel:
if (password.Equals(Properties.Settings.Default.ServicePassword))
        {
            PasswordOk = true;
        }
        else
        {
            PasswordOk = false;
        }

        password = "";

        Messenger.Default.Send<NotificationMessage>(
            new NotificationMessage(this, "CloseWindowsBoundToMe")
        );

and the view:
Messenger.Default.Register<NotificationMessage>(this, (nm) => CloseWindow(nm));

    private void CloseWindow(NotificationMessage nm)
    {
        if (nm.Notification == "CloseWindowsBoundToMe")
        {
            if (nm.Sender == this.DataContext)
            {
                PasswordViewModel pvm = ((PasswordViewModel)DataContext);
                DialogResult = pvm.PasswordOk;
            }
        }
    }

Back in the MainWindow.xaml.cs I am checking the DialogResult. If true (password is ok) nothing is done and if false I set the SelectedItem of the tabcontrol to the main tab.
TabItem selectedItem = (TabItem)e.AddedItems[0];

        if (selectedItem.Tag != null && selectedItem.Tag.Equals("Password"))
        {
            PasswordView pw = new PasswordView();
            pw.Owner = this;
            bool? result = pw.ShowDialog();

            if (result.HasValue && !result.Value)
            {
                tabControl.SelectedItem = tabControl.Items[0];
            }
        }

Basically all is working fine, but if I want to change in the protected tabitem more than 3 times with entering a wrong password the modal password view did not show in foreground. Only Alt+Tab brings the dialog to foreground....
This result is reproducible -> trying 3 times is ok then the next try the password dialog is shown in background.
There is another password protected tab, if I click this tab after the password dialog gets stuck in background two password dialogs are shown...
So the question is: Why is the modal password dialog not working always the same?


text:
Q: Why is the ROW keyword needed when constructing a row with one element, but not two? In PostgreSQL 11, the following expression
UPDATE test_table SET ("column_a","column_b") = ('value-a','value-b') WHERE "column_a" = 'value-c'

is accepted and performs the update.
But for a single column / value, like
UPDATE test_table SET ("column_a") = ('value-a') WHERE "column_a" = 'value-c'

it gives an error. ROW must be supplied, like
UPDATE test_table SET ("column_a") = ROW ('value-a') WHERE "column_a" = 'value-c'

Is there an explanation why this behavior was chosen? Is there an ambiguity if ROW is missing?

A: As is often the case, the answer is to be found in documentation.
The UPDATE reference says, in particular:

According to the standard, the source value for a parenthesized sub-list of target column names can be any row-valued expression yielding the correct number of columns. PostgreSQL only allows the source value to be a row constructor or a sub-SELECT.

whereas "row constructor" is defined like so:

A row constructor is an expression that builds a row value (also called a composite value) using values for its member fields. A row constructor consists of the key word ROW, a left parenthesis, zero or more expressions (separated by commas) for the row field values, and finally a right parenthesis. [...] The key word ROW is optional when there is more than one expression in the list.

The last sentence kind of makes sense, because a single expression in parentheses is ambiguous by itself and can be confused with a simple parenthesised expression.
This syntax was introduced in version 10 -- HT to ypercube™.


text:
Q: HOMEBREW - Installing Pygame on Mac OS X Snow Leopard So, I am trying to get pygame installed on my mac 10.6 via Homebrew. I am getting multiple errors
This is how I am installing Homebrew:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

That runs successfully in terminal. When I try and run the "brew" command to install mercurial
brew install mercurialand I get this error-bash: brew: command not found
I have tried to reinstall Homebrew multiple times, and it did not work. When I checked the /usr/local/bin/ directory, there was no file with "brew" in the name. I have also tried to run the commandpip3 install https://bitbucket.org/pygame/pygame, and I get this error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

A: There is a full set of instructions here:
https://bitbucket.org/pygame/pygame/issues/82/homebrew-on-leopard-fails-to-install#comment-627494
brew install mercurial

brew install sdl sdl_image sdl_mixer sdl_ttf smpeg portmidi
pip install hg+http://bitbucket.org/pygame/pygame


text:
Q: Cookies in ruby on rails - Login in different browsers I am new to web development.
I am using rails 4.2.
If a user logs in from a browser (chrome for instance), its session is stored in cookie (with a remember_token variable).
If the same user logs in from a different browser (firefox), its remember_digest (a hash of remember_token variable using Bcrypt) in DB is overwritten and hence is invalid for the other browser.
How can I solve this problem?
Is it possible to keep the same remember_token and remember_digest for different browsers?
Thank you

A: That's kind of problematic. Here's why:

*

*Cookies are browser dependent, as you're already aware.

*Being able to recreate digests(by creating methods that do what you want) is insecure. It defeats the whole purpose of using remember digests.

I can't say I recommend the following but:
One simple way of doing it is having multiple remember digests in database. Imagine having remember_digest0 and remember_digest1. In this case, you could support 2 browsers at a time(before overriding). You can add as many as you want.
-You'll need to update your authentication methods to check each digest saved in database and do stuff if any match.
-You'll need to tweak the methods for saving digests. You'll need to check which one is null or oldest, then save your new digest into that null/oldest.
Due to the nature of cookies and their security implications, this is probably the only safe way to do it. Even then I don't think it's worth it.


text:
Q: The `g` suffix for some GnuWin32 utils For these commands there are both a g-suffix version and a plain version:
gdate.exe
gecho.exe
ginstall.exe
gln.exe
gmkdir.exe
grmdir.exe
gsort.exe

I can't find the difference.
Edit
Someone is interested to this: OS Win7 Pro, GnuWin32  coreutils 5.3.
To be clear, g is the marketing suffix accompanying software released under GNU licensing terms (like k for KDE desktop apps). Here I'd like to know why only these commands (in coreutils) are suffixed and what is the difference with the others in the same directory without the suffix.

A: The g prefix here means that the tool is from GnuWin32 as opposed to the native Windows command of the same name. For example, mkdir and echo are builtin commands in the cmd.exe shell, and find.exe is part of Windows and does a completely different thing from the coreutils find (it is actually more similar to grep). Therefore, the prefix is needed to allow accessing both native and GnuWin32 commands at the same time.


text:
Q: Use working sets by default in Eclipse RCP How can I set programmatically an RCP to use working sets as top level elements in the Project Explorer by default instead of projects?

A: The Packages View is org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart.
The value of the top level elements mode is saved in a IDialogSettings object in the state location for the org.eclipse.jdt.ui plugin (so this is a dialog_settings.xml file in the org.eclipse.jdt.ui folder in the workspace .metadata).
The entry key value is rootMode in the org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart section. A value of 2 sets working sets top level.
You would have to set this value before the packages view opens. Once the view is open there are no accessible APIs to change the value (everything is internal).
Note: all the above is defined in internal classes and is therefore not part of the Eclipse API and may be changed without notice.

A: For programmatic access, you can get the Project Explorer's ViewPart (which is of class org.eclipse.ui.navigator.resources.ProjectExplorer) and call the setRootMode method.
Alternatively, you can set it via the setting org.eclipse.ui.navigator.resources.workingSets.showTopLevelWorkingSets


text:
Q: Parser exception for /FadeInOut/AndroidManifest.xml: The markup in the document following the root element must be well-formed I hope this error is in manifest file ,here i am placing the manifest file.error is showing at last line.
thanks in advance
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.sri.fadeinout"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="15" />

        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".MainActivity"
                android:label="@string/title_activity_main" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>

A: You need to make sure that you pay attention to anything after the </manifest> tag. Although the top (and what you post on SO) may be fine, if you have other things below this tag, Eclpise will throw an error (and with good reason, your xml is now malformed).


text:
Q: How to shutdown and restart dirmngr? dirmngr is used by python-apt and is recommended by gnupg and gpgsm. I tried to shutdown dirmngr as shared in the manpage but got this -
└─[$] dirmngr -vv --shutdown

dirmngr[9494]: error opening '/home/shirish/.gnupg/dirmngr_ldapservers.conf': No such file or directory

Can somebody share how to shutdown it ? I tried --debug-level and other tricks but couldn't get it to shutdown. How do I shutdown dirmngr ?
Update -
[$] dpkg -l dirmngr

Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                           Version              Architecture         Description
+++-==============================-====================-====================-=================================================================
ii  dirmngr                        2.1.17-3             amd64                GNU privacy guard - network certificate management service

Think it is installed perfectly inspite of the errors -
[$] systemctl --user status dirmngr

● dirmngr.service - GnuPG network certificate management daemon
   Loaded: loaded (/usr/lib/systemd/user/dirmngr.service; static; vendor preset: enabled)
   Active: active (running) since Sun 2017-01-08 14:46:21 IST; 5h 47min ago
     Docs: man:dirmngr(8)
 Main PID: 1203 (dirmngr)
   CGroup: /user.slice/user-1000.slice/user@1000.service/dirmngr.service
           └─1203 /usr/bin/dirmngr --supervised

Jan 08 14:46:40 debian dirmngr[1203]: DBG: chan_5 <- KEYSERVER --clear hkp://pgp.mit.edu
Jan 08 14:46:40 debian dirmngr[1203]: DBG: chan_5 -> OK
Jan 08 14:46:40 debian dirmngr[1203]: DBG: chan_5 <- KS_GET -- 0xDAD95197
Jan 08 14:46:40 debian dirmngr[1203]: DBG: dns: libdns initialized
Jan 08 14:46:50 debian dirmngr[1203]: DBG: dns: getsrv(_hkp._tcp.pgp.mit.edu): Server indicated a failure
Jan 08 14:46:50 debian dirmngr[1203]: command 'KS_GET' failed: Server indicated a failure <Unspecified source>
Jan 08 14:46:50 debian dirmngr[1203]: DBG: chan_5 -> ERR 219 Server indicated a failure <Unspecified source>
Jan 08 14:46:50 debian dirmngr[1203]: DBG: chan_5 <- BYE
Jan 08 14:46:50 debian dirmngr[1203]: DBG: chan_5 -> OK closing connection
Jan 08 14:46:50 debian dirmngr[1203]: handler for fd 5 terminate

A: systemctl --user stop dirmngr.socket
systemctl --user restart dirmngr.socket

A: With the current version of GnuPG you can kill dirmngr with gpgconf, like this:
gpgconf --kill dirmngr


text:
Q: Mono For Android In app Billing Does anyone have a working example of setting up in app billing in mandroid I am using JNI to access java classes but I seem to have gotten stuck with declaring a transaction handler in one of my actvities

A: There is a repository on Github that claims to have what you need it was published along with theese comments on the mono mailing list:

this has been tested with real money for managed in-app products only. All the code is there for unmanaged products and subscriptions, it just needs to be tested.

Good luck :-)


text:
Q: What are the reasons for and against developing a game in Java/C#(XNA included)/Unity? I am thinking of creating a game just for fun. What are the advantages in programming in these languages?
I believe Unity and Java both have their own embeddable applet thing and C# has a software package (XNA Game Studio) ready for developing games for Windows Phone, XBOX 360 and PC.
Just some criteria:

*

*How platform compatible is the language (can it run on Mac, I want it to definitely be able to run on PC)

*Does it have libraries for game development (include these please)?

*How is the basic performance of the runtime? (Do crashes often occur?)

*Can it be run in a web browser?

*Does the user have to install a runtime?

*Any other things that make the language good...

I want to develop games for PC.

A: Allow me to put my support behind C# and particularly XNA.
With the use of Mono (including paid libraries like MonoTouch and MonoDroid), you can get C# running pretty much anywhere (eg). C# is certainly fast enough for game development. And the runtimes are very much stable. It can run in-browser via Silverlight.
In my opinion, C# is superior to Java as a language, especially for game development, and especially considering tool and library support - especially XNA.
XNA is a game development library (similar to DirectX in scope) and there are also plenty of libraries built for XNA. In addition is has by far the best library of sample code available.
XNA runs natively on Windows, Xbox 360, Windows Phone 7 and (an older version) on Zune.
On PC, C# and XNA each require runtimes. Microsoft's ClickOnce installer makes this very easy. It gives your user a bootstrap installer, which then downloads and installs the runtimes from Microsoft as necessary. The .NET 4.0 Client Profile is 41MB and XNA 4.0 is 7MB. This answer has more details.
In addition there are projects that port XNA (2D API only) to other platforms. I am currently funding a project called ExEn with the goal of bringing a high-quality 2D XNA implementation to the browser (Silverlight), iOS, Android and Mac.
If you can't wait for ExEn, you could try some of the libraries it is based on - SilverSprite (Silverlight) and XnaTouch (iOS). SilverSprite is quite buggy, XnaTouch is a bit better.
(At the moment, if you want to do a 3D game on these platforms, Unity is perhaps a better option.)

A: To be clear, Unity isn't a language (like C# and Java), it is an authoring tool and runtime.  You write your game's logic in C#, UnityScript (flavor of JavaScript) or Boo (flavor of Python).  The authoring tool is quite stable and powerful and gives small teams a fantastic pipeline for adding 3D models, textures, sounds, shaders, etc.
In my (fairly long) professional career as a game developer I've only used one authoring tool that was superior to Unity, and that was an in-house proprietary tool developed over many years by a team of top-notch engineers.
There's no equivalent to Unity in the Java world that I'm aware of. XNA will give you a head start if you're writing straight C#, but you'll still have to create/integrate a lot of fundamental stuff (physics, particle systems, collision detection) before you're even close to what you could accomplish day 1 with Unity.
Standalone Unity games can be built for Mac or Windows. The standalone build doesn't require the user to install Mono, and is very stable in my experience.  There is also a Unity Web Player that allows games to run in A-class browsers on Mac and Windows. The web player is only installed on about 35 million browsers (sounds like a lot, but consider Facebook has over 500 million users).
I know I sound like a shill, but Unity really is a great tool.

A: i dont think its about programming language anymore. its depend on your target platform.

*

*xbox + pc > xna, .net

*android > java

*html5 > javascript

A: For game development, C# is far better then Java or JavaScript.
If you use Unity3D, you can use C# over JavaScript & you should.
Unity3D
Pros:

*

*Unity3D runs on: Windows, Mac, XBOX, PS3, WII, iPhone, Android

*Unity has a built-in physics engine (If you want to use this in a 2D game, you need to programmatically loc an axis).

Cons:

*

*Costs money for any other platform besides PC or Mac.

XNA
Pros:

*

*XNA runs on:: Windows, XBOX, Phone7.

*XNA is free for all platforms.

Cons:

*

*Limited to Microsoft products. More coding required.

If you're just starting & you want to make a 3D game, I would look into Unity3D.
If you're wanting to do a 2D game XNA or Unity3D would be good.
Sadly neither run on Linux. :(

A: I have used Unity quite extensively and I would defiantly recommend it. It goes to all platforms (You do have to buy the licences) but it is a very good engine. Worth looking at! Plus the fact you can develop in C# as it uses mono is a massive plus.


text:
Q: how to set various row heights for a one JTable I have a JTable which contains a one column, cell render of each table cell is  dynamically generated JPanel therefore each table cell height should be different according to its JPanel, I have tried to change the row height at the place where the jpanel is rendered but it is not working. please tell me how to set different JTable row heights in a JTable,
this is how I tried to do this,
    private QCellPanel renderer = new QCellPanel();
    private QCellPanel editor = new QCellPanel();

    @Override
    public Object getCellEditorValue() {
        return editor.getQuestion();
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        renderer.setQuestion((Qusetion) value);

        table.setRowHeight(renderer.getPreferredSize().height);
        return renderer;
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        editor.setQuestion((Qusetion) value);
        table.setRowHeight(editor.getPreferredSize().height);
        return editor;
    }

A: You need to use the two-argument version setRowHeight(rowNumber, height).
If possible, you should also avoid changing the row height in the getXComponent methods, as setRowHeight forces the table to be redrawn, which will cause it to ask for a renderer component again, etc... The default implementation is probably smart enough to not trigger this as long as the height is stable, but if you end up with infinite loops this is were I'd look first :)


text:
Q: Express $C_n = \cosh(0) + \cosh(1) + \cosh (2) + \dots + \cosh(n)$ Could someone give me some hint of how to do this question please.

I've been stuck for more than $3$ hours on this question.

A: Replacing $x$ with $k$ in the given relations (and rearranging somewhat), we have
$$\begin{cases}
&\sinh{(1)}\cosh{(k)}+\left(\cosh{(1)}-1\right)\sinh{(k)}=\sinh{(k+1)}-\sinh{(k)},\\
&\left(\cosh{(1)}-1\right)\cosh{(k)}+\sinh{(1)}\sinh{(k)}=\cosh{(k+1)}-\cosh{(k)}.\\
\end{cases}$$
Summing both equations from $k=0$ to $k=n$, we find
$$\begin{cases}
&\sinh{(1)}C_{n}+\left(\cosh{(1)}-1\right)S_{n}=\sinh{(n+1)},\\
&\left(\cosh{(1)}-1\right)C_{n}+\sinh{(1)}S_{n}=\cosh{(n+1)}-1.\\
\end{cases}$$
This yields a system of two linear equations in two unknowns, $C_{n}$ and $S_{n}$, which can be solved by standard methods. The result is
$$\begin{cases}
&C_{n}=\frac{\sinh{(1)}\sinh{(n+1)}-\left(\cosh{(1)}-1\right)\left(\cosh{(n+1)}-1\right)}{\sinh^2{(1)}-\left(\cosh{(1)}-1\right)^2},\\
&S_{n}=\frac{\sinh{(1)}\left(\cosh{(n+1)}-1\right)-\left(\cosh{(1)}-1\right)\sinh{(n+1)}}{\sinh^2{(1)}-\left(\cosh{(1)}-1\right)^2}.\\
\end{cases}$$
Using the hyperbolic Pythagorean identity, $\sinh^2{(x)}-\cosh^2{(x)}=-1$, the denominators can be simplified as
$$\begin{align}
\sinh^2{(1)}-\left(\cosh{(1)}-1\right)^2
&=\sinh^2{(1)}-\left(\cosh^2{(1)}-2\cosh{(1)}+1\right)\\
&=\sinh^2{(1)}-\cosh^2{(1)}+2\cosh{(1)}-1\\
&=2\cosh{(1)}-2\\
&=2\left(\cosh{(1)}-1\right).\\
\end{align}$$
If one desires to eliminate $\sinh{(1)}$ from the numerator as well, one can simply replace it with $\sinh{(1)}=\sqrt{\cosh^2{(1)}-1}$, again using the Pythagorean relation.


text:
Q: Access members of derived class through base class pointer C++ Is there any way to have a general code access members of derived class through base class pointer? Or any other way around this?
Let's say I have a class Shape. I have classes Square and Triangle which inherit it. Both have their own private members which have nothing to do with each other so there is no point in having them in the base class. Now, what if I need to write a class into a file, but I don't know if the class is Square or Triangle until the moment I need to write it in the file?
I've been trying to figure out how to solve this problem. The worst case solution would be to write the data of both Square AND Triangle into a file, add an identifier (Triangle or Square) for both reading and writing and have a small parser put the class together when loading data. This would be inefficient and waste of time.
I was wondering if there is some trick or design pattern or anything that can help with the situation.

A: This serialization should be done using virtual functions. Define a function in the base class that shall serialize the object. The Triangle and the Square overrides this functions and write

*

*the identifier

*all data that should be serialized

You may implement the common part in the base class if appropriate.
When you want load the file you will need factory method that creates the class instance corresponding to the identifier. The new instance virtual deserialize method must be called to load the actual data.

A: You can have a pure virtual getter in your Base Class. and all your Derived classes will override that. like this
class Shape{
  public:
    virtual int data() const = 0;
};
class Square: public Shape{
  private:
     int _member;
  public:
    virtual int data() const{
     //do something with private members and return it
     return _member;
    };
};

A: I think there is no direct way to remove this overhead. Normally this is done by a two things. First of all, the object needs a serialization mechanism:
To serialize things, one need a location to serialize to. In this case, we will do this using a data container, but this can also be a file stream or a container class. Serialization can be made from within the object or from outside, most easy implementation is now from the inner side:
The simple serialization part:
class Shape{
public:
  virtual void serialize( Datacontainer &o ) const = 0;
};

class Triangle: public Shape{
  void serialize( Datacontainer &o ) const{
    o.add('T');
    o.add(corners);
  }
  std::vector<point> corners;
}

class Circle: public Shape{
  void serialize( Datacontainer &o ) const{
    o.add('C');
    o.add(center);
    o.add(radius);
  }
  point center;
  double radius;
}

During serialization, you can do this by using the basic class Shape:
Shape *tri = new Triangle;
tri->serialize( dataContainer or file );

Deserialization is not as easy, because you need to know the type. A good pattern for this is the Builder pattern. Despite this, we can implement a more C++ likely way to do this:
Add the following thing to all of your classes:
static Shape* createFrom( Datacontainer &o );

For eg. the Circle implementation:
Shape* Circle::createFrom( Datacontainer &o )
{
  Circle *c = new Circle()
  c->center = o.get();
  c->radius = o.get();
}

This enables us to create a concrete instance, but we have a common function footprint for the method. Now one can implement a very easy builder like this one:
class ShapeBuilder
{
public:
  static Shape* createShape( Datacontainer& o )
  {
    char id = o.get();
    swith(id){
    case 'T':
      return Triangle::createFrom(o);
    case 'C':
      return Circle::createFrom(o);
    }
  }
}

A: You need to declare virtual methods in your base class, and have derived classes define them. If you want to save them to a file though - you will need a way to identify what specific class instance is in the file, since they may have different memory layouts.

A: Probably the best way is to do something like this. The basic patten is that you can put common code, that is guaranteed always to be the same for every derived class, in the base. Things that need to differ, put in a virtual function that the derived classes each implement differently.
class Shape {
    virtual void writeSerialData(std::ostream &) const = 0;
  public:
    void writeToFile(const std::string &filename) const {
        std::ofstream outfile(filename); // filename.c_str() in C++03
        writeSerialData(outfile);
        if (!outfile.close()) {
            // report the error
        }
    }
    virtual ~Shape() {}
};

class Square : public Shape {
    double length;
    virtual void writeSerialData(std::ostream &out) const {
        out << "Square{" << length << '}';
    }
  public:
    Square(double l) : length(l) {}
};

Now you have the next problem -- how do you read an object back from a file, without knowing in advance which derived class it is? For that you need a way to see the text Square and either (a) call a static function of the class Square that knows how to interpret the data or (b) instantiate the class Square by giving it the data to interpret. It's worth looking into Boost Serialization, or other serialization libraries, before you go too far down that path.


text:
Q: Php, Spl, FilterIterator behaviour I am trying to understand the behaviour of FilterIterator at This Code,
I was trying to understand the action sequences, I didnt understand why if you try to print the current() value it wont work unless you will use next() or rewind() before for example:
// Please take a look at the link before
echo $cull->current(); // wont work
$cull->next(); or $cull->rewind(); then echo $cull->current(); // work

Now i dont know what i have to "Refresh" the "Pointer" to be able to print elements, if can some one explain to me please the action sequences mabye it will become clearer, Thank you all and have  a nice day.

A: imho if you don't call next() or rewind before accessing current() at first time, the internal iterator-pointer is not set to the first element...
common scenario is while($it->next()) AFAIK!

A: This is the same question I asked here, even though it sounds different:
Why must I rewind IteratorIterator
(Your CullingIterator is a FilterIterator which is an IteratorIterator).
Read the accepted answer and the comments, but the summary is that the way IteratorIterator is written in the php source code, functionally models something like this:
class IteratorIterator {
    private $cachedCurrentValue;
    private $innerIterator;
    ...
    public function current() { return $this->cachedCurrentValue; }
    public function next() {
        $this->innerIterator->next();
        $this->cachedCurrentValue = $this->innerIterator->current();
    }
    public function rewind() {
        $this->innerIterator->rewind();
        $this->cachedCurrentValue = $this->innerIterator->current();
    }
}

The important part being that the value is NOT retrieved from the inner iterator when you call current(), but instead, it's retrieved at other times(and the constructor isnt one of them).
Personally, I think this a borderline a bug, because it's unexpected and solvable without introducing unwanted behavior or performance issues, but oh well.


text:
Q: Fastest factorization process in java I am writing a program in java which works to calculate the sqrt of a given value up to 10^100
. For this, I know I have to use a BigInteger but the process I am dealing with is not so efficient as it takes a lot of time. What is the fastest process to factorize a number to deal with the program? What is the faster algorithm?
Thanks in advance.

A: First, I hope you realize that most input values won't have an exact integer answer for square root!  Are you sure you want to do this with BigInteger rather than BigDecimal?
You sure as heck don't want to iterate through each value up to n.  You need a way to improve your answers much more rapidly.  A simple way to do so is to make an initial guess for a value of the square root (I recommend n/2), and find its co-factor (n / guess).  If they're equal you're done, if they're not equal update your guess to be the average of the guess and its co-factor -- one of them will be greater than the actual square root, and the other will be smaller, so averaging will produce a value closer to the actual square root.  Lather, rinse, repeat.  If there isn't an exact square root, stop when the factor and the cofactor are within 1 of each other.
Addendum: Here it is in pseudo-code (actually Ruby, but that's pretty much the same thing):
def sqrt(n)
  guess = n / 2
  cofactor = 2
  loop do
    cofactor = n / guess
    break if (guess - cofactor).abs <= 1
    guess = (guess + cofactor) / 2
  end
  return [guess, cofactor].min
end

Translation to Java should be pretty straightforward.


text:
Q: Firebase Security Rules: Unknown variable $requestId2? When user1 --> user2 (user1 sends a request to user2). I am trying to perform certain checks using firebase rules, which are:

*

*Check if username2 exists

*Check if both users are not already friends

for that I've written the following rule:
{
  "rules":
  {
    "requests":
    {
      "$requestId":
      {
        ".read": "auth != null",
        ".write": "auth!=null &&
                   data.child('username2').val() == true &&
                   root.child('usernames-list').child( data.child('username2') ).exists() &&
                   !root.child('user-requests').child( auth.uId ).child('accepted-pending').child($requestId2).child( data.child('username2') ).exists()"
      }
    }
  }
}

But it returns the following errors at two areas:

*

*data.child('username2')   ----> Line 9: child() expects a string argument.

*data.child($requestId2)   ----> Line 9: Unknown variable $requestId2

Data Structure:
requests
---$requestId
    ---key: value

user-requests
---$userId
    ---pending
        ---$requestId
            ---key: value
    ---accepted
        ---$requestId
            ---key: value
    ---rejected
        ---$requestId
            ---key: value
    ---unfriend
        ---$requestId
            ---key: value
    ---accepted-pending
        ---$requestId
            ---key: value

Incoming json:
user1       --> authId of user1
username1   --> username of 1st user
username2   --> username of 2nd user
...

Note 1: I've tried using newData. instead of data. and still get the same errors. Also, newData('username2').isString() also returns the same error
Note 2: I could avoid the $requestId2 (error) by making a separate list only containing the usernames that user1 is friends with and compare it against that; but I'd still need to be able to use data.('username2') as a field withing the root.child()
Edit 1: The following rule publishes successfully, however I'm not sure if it still does what I've mentioned (need to check) :
".write": "auth!=null &&
           newData.child('username2').val() == true &&
           root.child('usernames-list').hasChild( newData.child('username2').val() ) &&
           !root.child('user-requests').child( auth.uId ).child('accepted-pending-usernames').hasChild( data.child('username2').val() )"

Ref:Firebase security - newData() as a parameter of hasChildren() expression

A: Edit 2: This should be the solution:

*

*.val() has been added within the brackets

*.exists() remains at the end

*I've created a separate list of usernames (/accepted-pending-usernames/) to overcome the wildcard error

*data has been replaced with newData
".write":  "auth!=null &&
            newData.child('username2').val() == true &&
            root.child('usernames-list').child( newData.child('username2').val() ).exists() &&
            !root.child('user-requests').child( auth.uId ).child('accepted-pending').child('accepted-pending-usernames').child( data.child('username2').val() ).exists()"

Note: Question may still remain unsolved as its unclear if firebase allows one to use multiple wildcards in the rules


text:
Q: I want to prove that $C_0(X)$ is Banach Let $X$ be locally compact Hausdorff space. I'm trying to prove that
$$
C_0(X)=\{ f:X\to \mathbb{C} \; | \; f \text{ is continuous and }\forall \epsilon>0 \; \exists K(\text{compact}) \subset X \text{ s.t. } |f|<\epsilon \text{ on } X\setminus K\}
$$
is complete space with $\sup$ norm.
I tried as follows:
Let $f_n$ be a Cauchy sequence in $C_0(X)$. Then for all $x\in X$,
$$
|f_n(x) - f_m(x)| \le \|f_n - f_m\|_\infty \to 0
$$
as $n,m\to \infty$. So $\{f_n\}$ is Cauchy in $\mathbb C$ and therefore the limit $f(x) := \lim_{n\to \infty} f_n(x)$ exsits. Now I'm trying to show that this $f(x)$ satisfies $f\in C_0(X)$ and $\|f - f_n\|_\infty \to 0$ as $n\to \infty$.
(1) Continuity:
Since $\forall \epsilon>0$, $\exists N$: $\forall n,m\ge N$, $\forall x \in X, $ $|f_n(x) - f_m(x)| \le \|f_n - f_m\|_\infty < \epsilon$,
taking $m\to \infty$, we have $|f_n(x) - f(x)| \le \epsilon$ so that $\{f_n\}$ converges uniformly to $f$ on $\mathbb C$, therefore $f$ is continuous.
(2) $\forall \epsilon>0 $ $\exists K(\text{compact}) \subset X \text{ s.t. } |f|<\epsilon \text{ on } X\setminus K$
Since $f_N \in C_0(X)$, $\exists K$(compact) $\subset X$ s.t. $|f_N|< \epsilon$ on $X\setminus K$. So $$
|f| \le |f-f_N| + |f_N| \le \epsilon + \epsilon = 2\epsilon.
$$
(3) From (1), we have $|f_n(x) - f(x)| \le \epsilon $ for $n \ge N$. So $\| f_n - f\|_\infty \le \epsilon$.
I'm wondering that my proof is correct or not. Would you please confirm my solution? In fact, I'm wondering that $2\epsilon$ argument works or not in (2). Also I think I did not use the property that $X$ is locally compact and Hausdorff in my solution.

A: You have the right ideas. To "fix" the $2\epsilon$ part you could just choose $N$ large enough so that $\|f-f_N\| < \epsilon/2$, and then derive a compact subset such that $\|f_N \| < \epsilon/2$ outside.
The "uniform limit of continuous functions functions is continuous" statement is true regardless of the topological properties of $X$. However when working with the space $C_0(X)$, the hypotheses that $X$ be locally compact and Hausdorff are usually included because then one can extend any function $f \in C_0(X)$ to the one-point compactification of $X$ by setting $f(\infty) := 0$, and this extension is continuous.


text:
Q: For every natural number n, prove that the vector $x = (n, n + 1, n (n + 1)) ∈ \Bbb R^3$ has as a norm a natural number, that is, $\|x\| \in \Bbb N$.
For every natural number $n$, prove that the vector $x = (n, n + 1, n (n + 1))$ ∈ $\mathbb{R}^3$ has as a norm a natural number, that is, $\|x\| \in \mathbb{N}$.

I made the internal product of the vector $x$ which gave $n^4 + 3n^3 + n^2$. Now I can't prove by induction. Does anyone have an idea?

A: Here's one way you can go about it.  You can assume that the expression inside the radial is a perfect square.  Then, $n^4+2n^3+3n^2+2n+1 = (n^2+an+b)(n^2+an+b)$.  Then, solve for $a$ and $b$.  If they are natural numbers, then that completes the proof.

A: \begin{align*}
\sqrt{n^2+(n+1)^2+n^2(n+1)^2}&=\sqrt{(n^2+1)(n+1)^2+n^2}\\
&=\sqrt{(n^2+1+2n)(n+1)^2+n^2-2n(n+1)^2}\\
&=\sqrt{(n+1)^4-2n(n+1)^2+n^2}\\
&=\sqrt{[(n+1)^2-n]^2}\\
&=(n+1)^2-n\\
&=n^2+n+1.
\end{align*}
This is obviously a natural number for $n\in\mathbb{N}$.


text:
Q: wp_nav_menu add something before closing container and after last list item I've been looking for a way to hard code a
 tag before the closing container tag of a particular menu:
$footer_nav = array(
    'menu'              => 'footer-menu',
    'menu_class'        => 'foobar',
    'container'         => 'ul',
    'theme_location'    => 'footer',
    'menu_id'           => 'footer_menu',
    'echo'              => true,
    'depth'             => 1,
);
wp_nav_menu( $footer_nav );

However when I try to add:
'after' => '
bar
',

it adds it after every list item.  When I researched for a solution I ran across I want remove last after wp_nav_menu and Wordpress Functions - How to use Replace String func. to add some code but when I try:
function foobar_the_menu($items,$args) {
    if ($args->theme_location == 'footer') {
        $footer_pattern     = '

';
        $footer_replacement = '

bar

';
        return substr_replace( $footer_pattern, $footer_replacement, $items, 1 );
    }
}
add_filter( 'wp_nav_menu', 'foobar_the_menu', 10, 2 );

It removes all the menus.  After referencing a few other questions I did see wp_nav_menu_items and preg_replace but I'm unsure what is the correct approach to target a particular menu to hard code a div since you cannot modify this in the menu array?

A: I think you can use:
'items_wrap' => '
%3$s
bar

',

as a wp_nav_menu() argument.
We're using this part of the wp_nav_menu() function:
$nav_menu .= sprintf(
    $args->items_wrap,
    esc_attr( $wrap_id ),
    esc_attr( $wrap_class ),
    $items
);

where the items_wrap argument contains the following sprintf specifiers:

*

*%1$s to match the wrap id

*%2$s to match the wrap class

*%3$s to match the generated HTML for the items.


text:
Q: Infinite total internal reflection Suppose that I have a block of some transparent material, glass, for instance, with a certain index of refraction.  Suppose that the transparent material is placed in air or in any other transparent medium with a smaller index of refraction (smaller index because we want to have total internal reflection, see second paragraph).
I shine a light ray into the block at some angle.  Depending on the angle, there might be one or more total internal reflections.
Question
My question is, is it possible to have a well-defined form/shape of block with a well-defined index of refraction, and have a special angle at which if we send a light ray into the block, the light ray will undergo total internal reflections forever inside the block?  (striking boundaries forever at angles larger than the critical angle; not just many times, but infinitely)
Approaches
Of course, there are trivial solutions such as a rectangular prism of infinite length (like an infinitely long wire) ...  But I am looking for nicer, more interesting cases such as blocks of finite volume.  Maybe it's simpler to start by thinking about 2D polygons.  Perhaps a combination of flat and curved boundaries in a 2D or 3D object could also work.
EDIT
I want to consider this question only on a theoretical, almost mathematical, basis.  (No attenuation, no scattering, etc.)
Ideas?
Thanks

A: A physicist's answer to this is that the second law of thermodynamics forbids such a construction. You are describing a perfect black body, and the indefinite input of light in the way you propose will inevitably heat any finite cavity with the properties you propose. If your input light comes through a perfect waveguide from a black body at some temperature $T$, then the second law forbids the device's rising to a temperature above that of the source. So some light has to eventually leave the device.
However, what of trapping a short pulse of light (where the heating effect would not be a problem)?
There are contrived mathematical solutions to similar problems. For a 2D example, consider a perfect circular mirror with an infinitely thin slit in it for a ray to pass through (here we strike another difficulty of applying ray optics to this problem: real light cannot pass through an infinitely thin slit and indeed diffracts strongly on the far side if (1) the slit is much less than a wavelength width and (2) the wall thickness is thin enough for transmission through the slit. So already we must begin to consider full EM theory rather than rays. But let's state the ray solution for completeness:

Theangle $\Delta\theta$ between the angular positions of successive bounces is constant. This angle is a continuous function of the incidence angle, and equal to $\pi$ when the incidence angle is nought. Clearly all values of $\Delta \theta$ in some neighborhood $(\pi-\epsilon,\,\pi+\epsilon)$ of nought are reachable by adjusting the incidence angle. So we choose a $\Delta\theta$ that is an irrational multiple of $2\pi$. The ray hits the slit again (and thus escapes) after $n$ circulations, where $n\,\Delta\theta=2\,\pi,\,m$, for integers $n$ and $m$. But this is impossible if $\Delta\theta$ is an irrational multiple of $2\,\pi$, whence the device "swallows" such a ray permanently.
Take heed how infinite precision is needed for this argument: a nonzero width slit in this device will always lead to an eventual escape. To understand that there must be an eventual escape of the ray in this case, either $\Delta\theta$ is a rational multiple of $2\,\pi$, in which case it hits the slit precisely after some finite number of bounces, or it is an irrational multiple of $2\,\pi$. If the latter case, it can be shown that the set of intersection points where the ray bounces from the mirror is dense in the circle, therefore, any nonzero angular interval (and thus nonzero width slit) contains at least one of these intersections, so the ray escapes in this case too.
We can make a more realistic ray solution escape proof. A strip of horizontal light rays will be trapped by a Cassegrain like structure with two arcs of parabolas with common focus and vertical directrices will do it:

See this MathOverflow Thread "Symmetric Black Hole Curves" for more information. But this solution also has the catch that the incoming ray must be perfectly horizontal for trapping to happen. Since diffraction is roughly tantamount to a nonzero angular spread of rays, this means that real light will eventually escape such a structure.

A: A counter-argument to all the naysayers :-) .
First of all, the evanescent wave has nothing to do with light escaping.  For example,  single-mode fiber optics are often designed such that there's a significant evanescent wave, but since there's no high-index material outside the core, no energy escapes (other than quantum probabilistic long-range tunneling).
Next, and this is the unobtanium part,  suppose you shoot a particle and its antiparticle into a, say,  octagonal right prism, such that the photons generated when they  destruct are emitted in the prism plane and at an angle equal to the face angle, which is also less than the critical angle for the prism material.  Those photons will bounce from face to face forever.

A: The answers here is beautiful. But, i'll give another simple example.
Just take a glass square. The critical angle of glass is 42 degree. So pass a light ray through a very small slit , such that it strikes the side of the square glass slab, at 45 degrees. It will reflect and will ALWAYS strike the faces of the slab at angles greater than 45 degrees. And you're in business!

A: In the language of wave optics, I think that your question boils down to the following:

Given that dissipation is negligible, can a dielectric medium of finite size
  support a mode that is propagating only within the medium and evanescent outside?

The answer to this question is certainly "No."
Regardless of the form of the electric field inside the medium, it should be matched to the field outside the medium satisfying the transverse wave equation:
\begin{equation}
\nabla\times(\nabla\times\textbf{E}) + \frac{1}{c^{2}}\frac{\partial^{2}\textbf{E}}{\partial t^{2}} = 0.
\end{equation}
For a propagating mode only within a finite-size medium, the field outside must be evanescent in all three dimensions. But the above equation does not have a solution with such a property. Therefore, any mode that appears to be localized should in fact be matched to a propagating solution outside the medium, making the mode leaky.


text:
Q: How to use EXT-X-DISCONTINUITY-SEQUENCE when creating an infinite HLS stream that loops over same fragments I am trying to create an infinite HLS stream. The idea is that the server sends the same fragments meaning that once the last fragment is sent the first one is sent again. As far as I know I have to use the EXT-X-DISCONTINUITY-SEQUENCE tag. Here is my initial manifest
#EXTM3U
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-ALLOW-CACHE:NO
#EXT-X-VERSION:2
#EXT-X-TARGETDURATION:8
#EXTINF:8,
fragment0.ts
#EXTINF:8,
fragment1.ts
#EXTINF:8,
fragment2.ts
#EXTINF:8,
fragment3.ts
#EXTINF:8,
fragment4.ts
#EXTINF:8,
fragment5.ts
#EXTINF:8,
fragment6.ts
#EXTINF:4,
fragment7.ts

This is what it looks like once the stream starts and fragment 0 gets pushed to the bottom.
#EXTM3U
#EXT-X-DISCONTINUITY-SEQUENCE:0
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-ALLOW-CACHE:NO
#EXT-X-VERSION:2
#EXT-X-TARGETDURATION:8
#EXTINF:8,
fragment1.ts
#EXTINF:8,
fragment2.ts
#EXTINF:8,
fragment3.ts
#EXTINF:8,
fragment4.ts
#EXTINF:8,
fragment5.ts
#EXTINF:8,
fragment6.ts
#EXTINF:4,
fragment7.ts
#EXT-X-DICONTINUITY
#EXTINF:8,
fragment0.ts

Once fragment 0 comes to the top I increment EXT-X-DISCONTINUITY-SEQUENCE. This does not seem to work tho, does anyone have an idea why ?

A: Every time a fragment gets removed from the top the EXT-X-MEDIA-SEQUENCE must be incremented by 1. So after fragment0.ts drops out at the top it must say #EXT-X-MEDIA-SEQUENCE:1 in the playlist.
Note, that the #EXT-X-DICONTINUITY will end up at the top of the playlist after some time and when it drops out the EXT-X-DISCONTINUITY-SEQUENCE must be incremented by 1 as well.


text:
Q: How can I get keyboard input outside of the Node.js process window? I'm making a tool that needs hotkeys to function. I'm currently using the keypress module to get input, however It's not receiving the input outside of the terminal window. Any easy solutions for this?

A: Forgot to post this before but I got everything working by simply using the iohook module. Thank you all! Here is a sample code for it: https://stackoverflow.com/a/41442293/13549031


text:
Q: Weighted Average in Stata's collapse command I couldn't find a Stata command on the following issue, so I solved it manually:
According to the official manual, Stata doesn't do weights with averages in the collapse command (p. 6 of the Collapse chapter):

It means that I am not able to get weighted average prices paid in my sales data set at a week/product level where the weight is the units sold. The data set is a collection of single transactions with # of purchases and prices per unit paid at week/store/product level:
clear
set more off
week,store,product,price,units
1,1,cheer,1,10
1,1,tide,2,6
1,2,cheer,2,7
1,2,tide,3,5
2,1,cheer,1,15
2,1,tide,1,20
2,1,mrclean,2,8
2,2,cheer,2,8
2,2,tide,4,5
2,2,mrclean,3,4

Clearly, taking simple averages when collapsing ignores number of units purchased, resulting in a wrong average price estimate.
So what I did is I manually calculated a new variable price x units in the original data set. Then, I collapsed the dataset by summing up the price x units and units variables:
collapse (sum) pricexunits units, by(week product)

And finally,  I created a new variable where I divided pricexunits by units. Do you think I could have done something differently?

A: You're misreading that documentation.
The point is whether normalization makes a difference to the results for different kinds of weights, not whether weights are allowed at all. In fact, weights are fairly generally allowed, as the help and manual entry explain.
Thus, the frequency-weighted sum or count differs from the analytically-weighted sum or count, and so forth.
Weights are allowed with collapse (mean). Try it, e.g.
collapse (mean) price [w=units] , by(week product)


text:
Q: How to pull the email address from a Facebook login? My app allows people to Login with their Facebook Account to write comment, rate, and share as that user. My problem I am currently having is after they login, it just leaves a blank/empty field in my SQL Database so i can't pull their user id unless it is filled. Now is this a problem with my PHP or it's in my LoginActivity?
So I tried to add the permissions to my code and get the same response.
This is on my onCreate section.

Session session = new Session(getApplicationContext());
        Session.setActiveSession(session);
        session.openForRead(new Session.OpenRequest(LoginActivity.this).setDefaultAudience(SessionDefaultAudience.ONLY_ME).setPermissions(Arrays.asList("public_profile", "user_friends", "email")).setCallback(statusCallback));
        Session.setActiveSession(session);

A: Have a look at

*

*https://developers.facebook.com/docs/facebook-login/login-flow-for-web/v2.2

*https://developers.facebook.com/docs/facebook-login/permissions/v2.2
Do you configure your permission scope correctly?


text:
Q: Insert something between elements generated with ng-repeat What would be the best way, to append an element in between elements generated using ng-repeat?
For example:

{{position+1}}

I would like to put a
 after every 4th element. My guess would be to create a directive with the link.post. Tell me if I'm on the good track.
Thank you
jsFiddle: http://jsfiddle.net/uPMZU/

A: I'm not entirely sure what you're trying to achieve with the
 but if your are trying to stack them in groups of four then you can do something using the $index variable from ng-repeat and a class change.
JSFiddle with this: http://jsfiddle.net/y44Cb/13/
HTML

{{position+1}}

CSS
div.red-block {
    display: inline-block;
    border: 1px solid red;
    width: 50px;
    height: 50px;
}
div.block {
    float: left;
}

A: You could use ng-repeat-start and ng-repeat-end and then check whether you want to render the break in a function.

{{position+1}}

with

or

A: You can use an ng-switch to do what you need

 0">
    {{position+1}}

jsfiddle: http://jsfiddle.net/7qrne/ if you inspect the "5" div you'll see it has the  same with the "9" div, but none of the others.


text:
Q: What is the behavior of EntryProcessor serialization? I noticed that the EntryProcessor interface implements Serializable. I have a value in the map that I want to update using executeOnKey method, but would rather use the DataSerializable interface on the EntryProcessor for obvious reasons. My question... What is the behavior? Does the executeOnKey ignore the DataSerializable interface? I can't find anything in the documentation.

A: Hazelcast send your EntryProcessor through Operation which implements the DataSerializable interface. The serialization of the instances of EntryProcessor are delegated to the SerializationService
So :

*

*You can implement DataSerializable : Hazelcast will use it

*You can register a custom Serializer for your implementation of EntryProcessor

*If you do nothing, the java serialization will be used


text:
Q: How to use caller ID instead of "s" in SIP refer method? I'm working on script for automated calls via SIP and ran into a problem with the Caller ID.
The script runs quite simple:

*

*Calls the customer by his phone (for example, +1234567890) via INVITE method

*When the customer answers the call, uses REFER method to transfer the call to his personal manager.

*Manager receives the incoming call with the dialog established with the customer.

At the step 2-3 manager always receives the call from the contact called s@1.2.3.4 (where 1.2.3.4 is the IP address of our SIP server). How can I set the customers phone instead of s@1.2.3.4 ?
The refer request I use looks like this:
REFER sip:+1234567890@1.2.3.4:5060 SIP/2.0
Via: SIP/2.0/UDP 192.168.1.1:5100;rport;branch=z9hG4bK160892
From: <sip:100@192.168.1.1>;tag=29899
To: <sip:+1234567890@1.2.3.4:5060>
Call-ID: 28990ec994a682147cf87eda75f97664@192.168.1.1
CSeq: 22 REFER
Contact: <sip:100@192.168.1.1:5100>
Max-Forwards: 70
Refer-to: sip:111@1.2.3.4
Referred-By: <sip:+1234567890@1.2.3.4:5060>
Content-Length: 0

Here 100 is SIP ID of the call robot, 192.168.1.1 is the IP of robot, 111 is SIP ID of manager.
I tried using Refer-To like these:
Refer-to: <sip:111@1.2.3.4?Call-ID=28990ec994a682147cf87eda75f97664@192.168.1.1&From=%3Csip%3A%2B1234567890%401.2.3.4%3A5060%3E&Contact=%3Csip%3A%2B1234567890%401.2.3.4%3A5060%3E>
Refer-to: <sip:111@1.2.3.4?Call-ID="69ca6b4e1874aa07569ee234cf746a3c@192.168.1.1"&From="<sip:+1234567890@1.2.3.4:5060>"&Contact="<sip:+1234567890@1.2.3.4:5060>">
Refer-to: <sip:111@1.2.3.4;method=INVITE?Call-ID="d71d3cc87f88eb1522859296889d39fb@192.168.1.1"&From="sip:+1234567890@1.2.3.4:5060"&Contact="<sip:+1234567890@1.2.3.4:5060>">

But nothing worked as I expected, caller ID of the incoming manager's call still was s@1.2.3.4. The correct caller ID is required for us to get call recordings.
SIP software used: Kerio Operator (based on Asterisk).
What Refer-To or other headers can I use to send the correct caller ID?

A: First some remarks regarding the REFER request:

*

*The Referred-By header should contain the referrer's SIP URI, not the referee's SIP URI.

*The REFER request should be sent within the existing dialog. It appears you send the REFER request outside of any dialog (no to-tag provided).

From your description I derive that you use a B2B SIP server. That means when the customer's phone (+1234567890@1.2.3.4) receives the REFER request, the resulting INVITE request will be sent to the SIP server (s@1.2.3.4). The SIP server will then create a new INVITE request and send this to the manager's phone (111@1.2.3.4).
The INVITE request from SIP server to manager's phone will contain the following values:

*

*to header --> 111@1.2.3.4

*from header --> +1234567890@1.2.3.4

*contact header --> s@1.2.3.4

The manager's phone then has to use the from header's value as caller ID, not the contact header's value.
You might want to check

*

*if the INVITE request contains the right header values

*if the manager's phone uses the right header to determine the caller ID.

I hope this helps.


text:
Q: Parallel GIS with `future` I noticed that when loading furrr after raster, I am warned that values is masked:
The following object is masked from 'package:raster':

    values

I'm not 100% convinced that is the issue, but I am struggling to run raster::extract on sf objects
library(raster)
library(sf)
p <- shapefile(system.file("external/lux.shp", package="raster"))
s <- as(p, "sf")
r <- raster(p, ncol=100, nrow=100)
values(r) <- 1:ncell(r)

I can extract just fine
raster::extract(r, s)

but when I parallelize (version 1) I get an error:
library(furrr)
plan(strategy = "multiprocess", workers =2)

future_map(1:2, function(extr){
  raster::extract(r,s)
})

one weird thing is that it seems to work ok with sp type objects (version 2)
u<-as(s, "Spatial")

future_map(1:2, function(extr){
  raster::extract(r,u)
})

Besides just switching between sf and SpatialPointsDataFrame, how can I get the "version 1" code working?

A: The workers aren't loading the sf package. Use .options = furrr_options(packages = "sf").
Reproducing the issue:
future_map(1:2, function(x){
  raster::extract(r,s)
})
#> Error in as(from, "Spatial"): no method or default for coercing "sf" to "Spatial"

Solution:
future_map(1:2, .options = furrr_options(packages = "sf"), function(x){
  raster::extract(r,s)
})


text:
Q: Swing JTable - Using key binding instead of KeyListener on Shift key I'm sorry if this has been answered before, I tried to look for the solution, but I couldn't find anything relevant. I'm new to this, so there's a chance I completely overlooked or ignored something that would have led me to an easy solution.
I've implemented a key listener for the shift key so that when the user presses shift, he enters the cell exactly one row before into the edit more (please take a look at the code below). Although, there's one problem; If the user is currently entering data into the cell, the shift key doesn't work and when debugging, we can see that the the program never even enters the key listener. I've been told to use key binding instead of key listeners to fix this problem. I've tried to follow some tutorial online and it looks like I've failed. Any help will be much appreciated, thanks a lot!
Two key listeners (Tab works fine, while Shift does not):
table.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            //KeyCode 9 is a key code for the Tab key
            if (e.getKeyCode() == 9) {
                if(table.isCellEditable(table.getSelectedRow(),table.getSelectedColumn())) {
                    table.editCellAt(table.getSelectedRow(), table.getSelectedColumn());
                } else {
                    table.editCellAt(table.getSelectedRow(), table.getSelectedColumn() + 1);
                }
            }
            //The problem occurs here
            //KeyCode 16 is a key code for the Shift key
            if (e.getKeyCode() == 16) {
                if(table.isCellEditable(table.getSelectedRow() + 1, table.getSelectedColumn())) {
                    table.editCellAt(table.getSelectedRow() + 1, table.getSelectedColumn());
                    table.setColumnSelectionInterval(table.getSelectedColumn(), table.getSelectedColumn());
                    table.setRowSelectionInterval(table.getSelectedRow() + 1, table.getSelectedRow() + 1);
                } else {
                    table.editCellAt(table.getSelectedRow() + 1, table.getSelectedColumn() + 1);
                    table.setColumnSelectionInterval(table.getSelectedColumn() + 1, table.getSelectedColumn() + 1);
                    table.setRowSelectionInterval(table.getSelectedRow() + 1, table.getSelectedRow() + 1);
                }

            }
        }
    });

Here's my attempted (and failed) solution:
 class ShiftAction extends AbstractAction{
        public void actionPerformed(ActionEvent ae){
            System.out.println("Shift");
            table.editCellAt(table.getSelectedRow() + 1, table.getSelectedColumn());
            table.setColumnSelectionInterval(table.getSelectedColumn(), table.getSelectedColumn());
            table.setRowSelectionInterval(table.getSelectedRow() + 1, table.getSelectedRow() + 1);
        }
    }
    shiftAction = new ShiftAction();
    table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT,KeyEvent.SHIFT_DOWN_MASK),"doShiftAction");
    table.getActionMap().put("doShiftAction",shiftAction);

Hopefully the question's not too stupid, and once again, thanks in advance.

A: e.getKeyCode() == 9

First of all, don't use magic numbers. People reading the code don't know what "9" means. Use the provided fields from the KeyEvent API:  KeyEvent.VK_???.

we can see that the the program never even enters the key listener.

Focus is on the JTextField being used as the editor for the cell so it receives the KeyEvent, not the table.

I've been told to use key binding instead of key listeners to fix this problem.

You need to use the appropriate InputMap. In this case it should be:
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT

Read the section from the Swing tutorial on How to Use Key Bindings for more information.


text:
Q: CSS styles not applied on dynamic elements in Internet Explorer 7 When we render dynamic elements with Javascript in IE7, the CSS styles are not applied.  When we use the Web Developer toolbar to view the page, the dynamic elements do not appear.  Pages render fine in Firefox, Chrome, and Safari.
Is IE7 unable to apply CSS styles to dynamically created elements?  IE8 renders the dynamic elements properly.
This question applies to IE8 since we use the meta tag to force IE8 to render in IE7 mode.
Thanks!

A: We found the problem: instead of using setAttribute('class', 'cssClass') on a new element, we needed to use setAttribute('className', 'cssClass'), where 'cssClass' is some user defined CSS class.
While FF handles the 'class' attribute, IE chokes because 'class' is a special keyword in Javascript.  Thus, you must use 'className' as the attribute name.
Thanks for everyone's responses!

A: I presume IE7 (ie IE8 loading as 7) is loading the CSS styles and only using those that apply to the document structure and load time. Maybe you can force reload of the stylesheet by including another tag in the dynamically loaded content.
Quick Q: Are you using the Strict DOCTYPE? They say something here about needing to use the Strict DOCTYPE with IE7 specifically. It's right under the Overview section.
Beware: If you didn't use Strict from the start, it's going to throw your layout out. But I would recommend using Strict anyway, as it makes your life easier in the long run. Just sort out your layout after switching and you're A for away.


text:
Q: Assign vector components to different variables in Julia I want to assign the result of an operation to a concatenation of variables in Julia. Something similar to this (although this doesn't work):
a = zeros(5)
b = zeros(5)
a, b .= rand(10)

Is it possible? Thank you.

A: You are looking for "vector view concatenation". The idea here is to use SubArrays to build an Array that is actually a view into two arrays. Julia does not support this out of the box. The Julia package ChainedVectors.jl was built for this, but it is heavily outdated and only works with Julia <= 0.4.
Not everything is lost. You have two alternatives:
Use CatViews.jl
As pointed out in the comments, CatViews.jl is like ChainedVectors.jl, but works with Julia 0.6 and 0.7:
Pkg.add("CatViews")
using CatViews

a = zeros(2)
b = zeros(2)
CatView(a, b) .= rand(4)

Build your own solution
With a little work, we can get as good as
a = zeros(2)
b = zeros(2)
MyView(a, b) .= rand(4)

Julia allows you to build your own view-concatenation type. The effort required to build it scales proportional to how general you want it to be. Here is a first attempt that works with vectors:
julia> # Create a type for a view into two vectors.

julia> type MyView{T} <: AbstractVector{T}
       a::Vector{T}
       b:: Vector{T}
       end

julia> import Base: size, getindex, setindex!

julia> # Define methods to make MyView behave properly.

julia> size(c::MyView) = size(c.a) .+ size(c.b)

julia> getindex(c::MyView, i::Int) = i <= length(c.a) ? getindex(a, i) : getindex(b, i-length(a))

julia> setindex!(c::MyView, val, i::CartesianIndex) = i[1] <= length(c.a) ? setindex!(c.a, val, i[1]) : setindex!(c.b, val, i[1]-length(a))

julia> setindex!(c::MyView, val, i::Int) = i <= length(c.a) ? setindex!(c.a, val, i) : setindex!(c.b, val, i-length(a))

julia> # Test MyView. Define two arrays and put them
julia> # into a single view.

julia> a = rand(2)
2-element Array{Float64,1}:
 0.701867
 0.543514

julia> b = rand(2)
2-element Array{Float64,1}:
 0.00355893
 0.405809

julia> MyView(a, b) .= rand(4)
4-element MyView{Float64}:
 0.922896
 0.969057
 0.586866
 0.457117

julia> # Hooray, it worked! As we see below,
julia> # the individual arrays were updated.

julia> a
2-element Array{Float64,1}:
 0.922896
 0.969057

julia> b
2-element Array{Float64,1}:
 0.586866
 0.457117

A: This?
a .= x[1:5]
b .= x[6:end]

You must tell Julia somehow where to split the vector.


text:
Q: Override default argument only when condition is fulfilled Given
case class Foo (
  x: Int = 1,
  y: String,
)

What is the best way to instantiate said class, overwriting default params only if a local condition is fulfilled (e.g. the local variable corresponding to the constructor parameter is not None)
object Test {
  /* Let's pretend I cannot know the state of x,y
   * because they come from the network, a file... */
  val x: Option[Int] = getX()
  val y: Option[String] = getY()

  Foo(
    x=???,   // how to get x=if(x.isDefined) x else "use default of Foo" here
    y=y.get,
  )
}

The straightforward solution of checking the condition and instantiating the case class differently does not scale (seven arguments with default values -> 128 different instantiations)
Solution 1) One solution I know is:
object Foo {
  val Defaults = Foo(y="")
}

object Test {
  val x: Option[Int] = getX()
  val y: Option[String] = getY()

  Foo(
    x=x.getOrElse(Foo.Defaults.x)
    y=y.get
  )
}

This works ok-ish. When y is None I get the NoSuchElementException, but that's OK because it is a mandatory constructor argument. However, this is clearly a hack and has the distinct drawback that it is possible to write:
  Foo(
    x=x.getOrElse(Foo.Defaults.x)
    y=y.getOrElse(Foo.Defaults.y)
  )

When y is None you get a non-sensical default value for y.
Solution 2) Another solution is something like:
sealed trait Field
case object X extends Field

object Foo {
  private val template = Foo(y="")
  val Defaults = {
    case X => template.x
  }
}

object Test {
  val x: Option[Int] = getX()
  val y: Option[String] = getY()

  Foo(
    x=x.getOrElse(Foo.Defaults(X))
    y=y.get
  )
}

This is a bit better type safety-wise, but now I have to create a type for each default parameter.
What would a correct and concise solution look like?

A: Not clear to me how you can do better than the following:
object Foo { def apply(optX: Option[Int], optY: Option[String]): Foo = Foo(optX.getOrElse(1), optY.get) }
case class Foo private(x: Int, y: String)

Foo(Some(5), None) // fails with NoSuchElementException
Foo(Some(5), Some("Hi")) // succeeds in creating Foo(5, "Hi")
Foo(None, Some("Hi")) // succeeds in creating Foo(1, "Hi"), note the default value of x

Whether a parameter is required or optional with a default is encoded via the invocation of get for the former and getOrElse for the latter.
Of course, you could wrap the Option's get method to provide a more meaningful message when required parameters are omitted.
I realize that is not far from your solution 1 and may not meet your needs.


text:
Q: Spring boot with security default login successful redirection issue I am working on spring boot with security, I want to have custom login page and after successful login ,i want to open dashboard page.
In my code I have used default login page after successful login , it is not redirected to dashboard page.
I have tried multiple ways,but no luck.
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .authorizeRequests()
        .antMatchers("/resources/**", "/register").permitAll()
        .anyRequest().authenticated()
        .and()
        .formLogin().defaultSuccessUrl("/dashboard", true)
//            .loginPage("/login")
        .permitAll()
        .and()
        .logout().logoutSuccessUrl("/login")
        .permitAll();
}
}

WebMvcConfigurer
@EnableWebMvc
@ComponentScan("com.hrmanagement")
public class WebMvcConfiguration implements WebMvcConfigurer {

@Override
public void addViewControllers(ViewControllerRegistry registry) {

//    registry.addViewController("/loginPage").setViewName("login");
      registry.addViewController("/dashboard").setViewName("login");
//    registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
}

  after successful login, it is redirected to http://localhost:8080/dashboard
I get
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Mar 10 17:14:47 IST 2019
There was an unexpected error (type=Not Found, status=404).
No message available.
I tried, adding login page in multiple locations(static,templates folders then added webapp-views) but no luck, can any one please suggest or help me in better understanding.


text:
Q: Is this a safe, inexpensive way to do auto-versioning on an ASP.NET web page? Or will it bite me? I've got an ASP.NET web page where I want to ensure users get the latest version of the javascript file each time they load the page, but I do not want them to download the file unless it's actually changed.  It is a continually evolving web app and the js files get modified frequently. I have a version number in the url that I update manually.  But I keep forgetting to update it when I change the js file.
<script type="text/javascript" src="js/Sched.js?v=1"></script>

So doing some searching for auto-versioning methods, I found one using re-writes and php, which made me think about my environment.  The only thing I came up with was to use the LastWriteTime of the js file for the version.  So I built a function:
    protected string GetFileTime(string file)
    {
        FileInfo fi = new FileInfo(Server.MapPath(file));
        if (fi.Exists)
        {
            Debug.WriteLine(fi.FullName);
            return fi.LastWriteTimeUtc.ToFileTime().ToString();
        }
        else
        {
            Debug.WriteLine("0");
            return "0";
        }
    }

And changed my script url in the page:
<script type="text/javascript" src="js/Sched.js?dev=<%= GetFileTime("js/Sched.js") %>"></script>

It seems to work great on my dev server. The browser sees this:
<script type="text/javascript" src="js/Sched.js?dev=131969009464369343"></script>

I've tested it with many page loads and the number remains the same until I make a change to the file.
So it seems like a great solution. I've looked at FileInfo and it reads the file meta data from the disk and does not open or lock the file.  But when I put it live on the production server with about 1000 users, is there a possibility of performance or other issues?


text:
Q: Memory leaks in iphone application Hi, guys! i'm newbie in iphone development. I have problems with the memory leak. I have such code.
do {

    int s = sqlite3_step(statement);
    switch (s) {
        case SQLITE_ROW:{

            Article *a = [[[Article alloc] init] autorelease];
            for (int i = 0; i < columnCount; i++) {
                const char *columnName = sqlite3_column_name(statement, i);
                if(strncmp(columnName, "title", strlen("title")) == 0){
                    const char* colStr = (char*)sqlite3_column_text(statement, i);
                    if(colStr != NULL)
                        a.title = [[[NSString alloc] initWithCString: colStr encoding:NSUTF8StringEncoding] autorelease];
                    continue;
                }
                if(strncmp(columnName, "author", strlen("author")) == 0){
                    const char* colStr = (char*)sqlite3_column_text(statement, i);
                    if(colStr != NULL)
                        a.author = [[[NSString alloc] initWithCString:colStr encoding:NSUTF8StringEncoding] autorelease];
                    continue;
                }
                if(strncmp(columnName, "description", strlen("description")) == 0){
                    const char* colStr = (char*)sqlite3_column_text(statement, i);
                    if(colStr != NULL)
                        a.description = [[[NSString alloc] initWithCString:colStr encoding:NSUTF8StringEncoding] autorelease];
                    continue;
                }
                if(strncmp(columnName, "link", strlen("link")) == 0){
                    const char* colStr = (char*)sqlite3_column_text(statement, i);
                    if (colStr)
                        a.link = [[[NSString alloc] initWithCString:colStr encoding:NSUTF8StringEncoding] autorelease];
                    continue;
                }
                if(strncmp(columnName, "imageUrl", strlen("imageUrl")) == 0){
                    const char* colStr = (char*)sqlite3_column_text(statement, i);
                    if (colStr)
                        a.imageUrl = [[[NSString alloc] initWithCString:colStr encoding:NSUTF8StringEncoding] autorelease];
                    continue;
                }
                if(strncmp(columnName, "pubDate", strlen("pubDate")) == 0){
                    const char* colStr = (char*)sqlite3_column_text(statement, i);
                    if(colStr)
                        a.pubDate = [[[NSString alloc] initWithCString:colStr encoding:NSUTF8StringEncoding] autorelease];
                    continue;
                }
            }
            [array insertObject:a atIndex:0];
        }
        break;
        case SQLITE_DONE:
            sqlite3_finalize(statement);
            dataForReadingAvailable = NO;
            break;
        default:{
            NSLog(@"getArticlesForFeed:sqlite3_step failed.Error:%s",sqlErrMsg);
            return nil;
        }
        break;
    }
}while(dataForReadingAvailable);

Tools from Xcode shows that i have leak memory when i a'm allocated object and when i initialized it properties. But why it's happens. All objects is autorealeased, so i think that will not to be such situation.
Thanks.

A: I think perhaps you overwrite the allocated memory with the new pointer somewhere.
I would replace
Article *a = [[[Article alloc] init] autorelease];

with
Article *a = [[Article alloc] init];
//some code
[a release]; //when you don't need it anymore

This is not a good practice to use autorelease much. It can even slow down your app btw in case of many objects.
And the strings like
 a.title = [[[NSString alloc] initWithCString: colStr encoding:NSUTF8StringEncoding] autorelease];

I would replace with
 a.title = [NSString stringWithCString:colStr encoding:NSUTF8StringEncoding];

In this case you also rely on autorelease pool, but it's much simpler.
EDIT:
Indeed, your 'Article' allocation is in the do-while loop.
In string [array insertObject:a atIndex:0]; your aray retains object and you don't need it anymore, but you rely on autorelease. Analyzer (or what tool you're using) sees, that you placed allocation in the cycle's body without releasing it after each iteration. This way, on the second iteration of the loop, you overwrite your "a" object, loosing the old pointer and leaking memory this way (pool won't find this pointer, since "a" overwritten). Even if you pass your loop only once, the analyzer does not care and gives you a warning.


text:
Q: Change aria-valuenow Kendo UI input So I have an imput to capture weight. When I click on edith I want the input to show me the information. It does shows it. But only when I click on it.
When the page loads the input stays with its aria-valuenow = 0.
<input type="text" class="k-formatted-value k-input" title="0.00 kg"
tabindex="0" role="spinbutton" aria-valuenow="0" aria-disabled="false"
style="font-size: 18px;">

I've tried to change it with Jquery and the attribute arr but it does not work.
$("#weight").attr('aria-valuenow', cow.weight);

Anyone who can help me out with this? Please.

A: So I totally forgot that I asked this. I solved it searching a little bit more in the web.
        $('#weight').data("kendoNumericTextBox").value(goat.weight);
        $('#weight').data("kendoNumericTextBox").trigger("change");

If there is anyone needing this.


text:
Q: Why isn't the StringBuilder class inherited from Stream? I'm just curious about this.  It strikes me that the behavior of a StringBuilder is functionally (if not technically) the same as a Stream -- it's a bin of data to which other data can be added.
Again, just curious.

A: A stream normally refers to an external input/output source (file, network). StringBuilder has no such characteristic.

A: Because it's not really a stream.  It's more of a buffer that grows.

A: StringBuilder has more than just Append functions.  It also has insert functions which is unnatural for a stream.  Use the StringWriter class if you want a stream that wraps a StringBuilder.

A: Stream is an input and output of binary data.
StringBuilder is means of building up text data.
Beyond that, there's the issue of state - a StringBuilder just has the current value, with no idea of "position". It allows you to access and mutate data anywhere within it. A stream, on the other hand, is logically a potentially infinite stream of data, with a cursor somewhere in the middle to say where you've got to. You generally just read/write forwards, with Seek/Position to skip to a specific part of the data stream.
Try to imagine implementing the Stream API with StringBuilder... it just doesn't fit. You could sort of do it, but you'd end up with StringReader and StringWriter, basically.

A: While both can have data added to them, the functionality as a whole is different.
A Stream is for inputting or outputting data from/to some source, not for building something.  StringBuilder does not need functionality that Stream provides, like Buffering, etc to build a resource.

A: On the other hand you will find the classes StringReader/Writer in System.IO. The StringWriter e.g. implements TextWriter against an underlying StringBuilder.
Personally I've never used it but if you have a text file writing routine you could make it work against a TextWriter. Then in your test, instead of instantiating a StreamWriter you instantiate a StringWriter and you could then check what was written by looking at the underlying StringBuilder.
Now I'm dizzy...


text:
Q: R Merge By adding rows I have 2 data sets, 1 with information about travels, and the other one containing the cost per travel depending on where I'm leaving from. I need to get the total cost of the travel and it's easy to do with a merge by where I'm leaving from, but when I do this it adds 1,500 rows to my 100,000 row dataset..
Anyone knows why is this happening? The biggest dataset is 100,000 rows, the other one is about 10,000
EDITThis is a subset of df1
x Poste       Locat  V3
1 905916      Mixco 0.3
2 905818      Mixco 0.6
3 905818      Mixco 0.6
4 905338 Castellana 0.5
5 904876      Mixco 0.3

This is a subset of df2
x  Vehiculo  Poste
1  Camion    340592
2  Camion    262776
3  Camion    340622
4  Camion    243254
5  Camion    258505

I need to merge both datasets using "Poste", as I will get the cost based on both "Locat"(location) and "Vehiculo"(vehicle) from another dataset.

sol <- merge(sol, df[,c(5,16)], by="Poste")