text:
Q: How do I extract timestamp and keywords from logs? I have wifi logs that I need to clean and parse. I want to take the timestamp and specific keywords, then save them to a new file. I am currently using this to clean the output file, then save the specific logs that contain Assoc Success to the output.txt file.
open("output.txt", "w").close()
with open("SampleLogs.txt", "r") as in_file, open("output.txt", "w") as out_file:
    for line in in_file.readlines():
        if "Assoc success" in line:
            out_file.write(line)

The logs now look like this:

Sep 16 23:59:58 RU3109-2-A7240-2 stm[7119]: <501119> <7119>    Assoc success @ 23:59:58.982251: 04:8d:6d:ec:77:23: AP 10.47.89.24-47:3a:e8:b5:e1:c1-EXT-St130A-AP365-1

What is the best way to extract only the timestamp (Sep 16 23:59:58) and the keyword (RU3109)?

A: Hope this way can help you.
split_list = line.split()
timestamp = " ".join(split_list[:3])
keyword = split_list[3].split("-")[0]


text:
Q: Seg Fault Using a Struct in Shared Memory I apologize in advance for my ignorance, this is giving me a lot more trouble than it should, but I've been banging my head into my desk for hours trying to come up with what I'm doing wrong.  I want to write an application that has shared memory storing a struct.  For some reason, I can't get off the ground to start, I keep getting a seg fault from accessing the members of my struct.
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>

#define MAX_SEQUENCE 10

struct shared_data
{
    long sequence[10];
    int sequence_size;
};
typedef struct shared_data shared_data;

int main(int argc, char * argv[])
{
    int segment_id;

    shared_data * shared_memory;

    segment_id = shmget(IPC_PRIVATE, sizeof(shared_data), S_IRUSR | S_IWUSR);

    shared_memory = (shared_data *) shmat(segment_id, NULL, 0);

    shared_memory->sequence_size = atoi(argv[1]);

    printf("\n\nSequence Size: %d\n\n",shared_memory->sequence_size);

    shmdt(shared_memory);
}

UPDATE:  Thanks everyone, my system administrator was running diagnostics and somehow disabled shared memory.

A: Your code doesn't look to bad to me. The only obvious thing missing is some kind of check for the number of arguments passed like:
if (argc != 2)
  return 1;

Is it possible you just missed to call your program with an argument. In this case it would be
atoi (argv[1])

that leads to your segfault.
BTW: additionally checking return values of shmget and shmat might be a good idea too.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I find in SQL for a match of 15 characters out of 17? I have a table where a field is varchar(17) and contains 17 char long phrases. They are alphanumeric. I need to add another row this table, but before I do, I need to check for possible duplicates. The logic for duplicates needs to be if any 15 characters of the new phrase matches with any 15 characters to a record in the table.
Samples:
5 Table rows:

1N6BF0KM2HN802620
1N6BF0KMXHN801974
1N6BF0LYXHN811101
1N9BF0KM6HN800482
1N12F0LY4HN809375

New phrase to add: 1N6BF0KAXHN802974
Found in table row 2: 1N6BF0KMXHN801974
Duplicate: Does not match 2 charaters only

New phrase to add: 109BF0KM6HN800492
Found in table row 4: 1N9BF0KM6HN800482
Duplicate: Does not match 2 charaters only

New phrase to add: 1N12F0LY4HN709375
Found in table row 5: 1N12F0LY4HN809375
Not Duplicate: Does not match 1 charaters

New phrase to add: 1N6AF0BYXHN911101
Found in table row 3: 1N6BF0LYXHN811101
Not Duplicate: Does not match more than 2 charaters

I try searching for regular expression or any algorism.

A: Here is a solution using

*

*a function which compares a pair of string character by character and returns the number of matches

*which uses the function to compare a string with all the values already in the table before entering it.

I don't think that regex is appropriate because we would need to count the number of matches with different regex pattern fir each existing entry. Regex is good for matching to a pattern which doesn't change.

create table sample (Samples char(17));
insert into sample values
('1N6BF0KM2HN802620'),
('1N6BF0KMXHN801974'),
('1N6BF0LYXHN811101'),
('1N9BF0KM6HN800482'),
('1N12F0LY4HN809375');

CREATE FUNCTION dbo.countMatches
(
@string1 CHAR(17) ,
@string2 CHAR(17)
)
returns int
AS
BEGIN
     DECLARE @IsMatching int =0 ;
     DECLARE @loopCount INT = 0;
     SET @IsMatching = 0;
     WHILE @loopCount < 17
        BEGIN
             IF(
                SUBSTRING(@string1,@loopCount+1,1)
                = SUBSTRING(@string2,@loopCount+1,1)
                )
              BEGIN
                SET @IsMatching = @IsMatching + 1;
              END;
            SET @loopCount = @loopCount + 1;
        END
RETURN @IsMatching
END

create procedure insertSample (@newSample char(17))
as
begin
DECLARE @sample char(17);
declare @IsMatching int;
declare @thisMatching int = 0;
DECLARE sample_Cursor CURSOR
   FOR SELECT samples FROM sample
OPEN sample_Cursor

FETCH NEXT FROM sample_Cursor INTO @sample

WHILE @@FETCH_STATUS = 0
BEGIN
    set @IsMatching=dbo.countMatches(
        @sample, @newSample);
    FETCH NEXT FROM sample_Cursor INTO @sample
    if (@IsMatching > @thisMatching)
    begin
      set @thisMatching = @IsMatching;
    end
END
CLOSE sample_Cursor
DEALLOCATE sample_Cursor
  if (@thisMatching >  14)
    RAISERROR (
       'too many matching characters',16, 1)
    else
    begin
      insert into sample values(@newSample);
      select 'ok accepted' result,
         @thisMatching numMatches;
     end
  RETURN;
end

EXEC insertSample '1N6BF0KAXHN802974'
GO

Msg 50000 Level 16 State 1 Line 26

too many matching characters

EXEC insertSample '109BF0KM6HN800492'
GO

Msg 50000 Level 16 State 1 Line 26

too many matching characters

EXEC insertSample '1N12F0LY4HN709375'
GO

Msg 50000 Level 16 State 1 Line 26

too many matching characters

EXEC insertSample '1N6AF0BYXHN911101'
GO

result      | numMatches
:---------- | ---------:
ok accepted |         14

select * from sample;
GO

| Samples           |
| :---------------- |
| 1N6BF0KM2HN802620 |
| 1N6BF0KMXHN801974 |
| 1N6BF0LYXHN811101 |
| 1N9BF0KM6HN800482 |
| 1N12F0LY4HN809375 |
| 1N6AF0BYXHN911101 |

SELECT dbo.countMatches(
          '1N12F0LY4HN709375',
          '1N12F0LY4HN709366');

| (No column name) |
| ---------------: |
|               15 |

db<>fiddle here


text:
Q: GL_SAMPLE_ALPHA_TO_COVERAGE on android I'am using OpenGL ES 2.0 on android and trying to enable alpha to coverage.
glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);

But it doesn't give any effect as I expect. The same code works well on windows and linux desktops.
Is the alpha to coverage supported on android devices? May be I need to enable some additional options?


text:
Q: ToggleButton isChecked vs isActivated - Android I'm trying to see what method of the ToggleButton widget is used to check if it is switched to "on" or "off", and I couldn't make out of the reference if it's isChecked() or isActivated()
What are the differences between the two?

A: View.setActivated() says in the JavaDoc that the activated state has nothing to do with CheckBox or ToggleButton, but with some kind of selection state that a generic View can be in when in a ListView.
The developers even apologize for the confusion:

Um, yeah, we are deeply sorry about the terminology here

isActivated() is also only available on API levels > 11.
isChecked() is from CompoundView, which ToggleButton and CheckBox both extend from. This is the state that you want to be checking for. It is available on all API levels.

A: use isChecked() for ON and OFF
if (isChecked()) {
        // The toggle is enabled  ON state
    } else {
        // The toggle is disabled  OFF state
    }

As i know there is no isActivated() method for toggle button, it is for a view either it is active or not.

A: The difference become clear from the documentation:
public boolean isActivated ()

is View method and responsible for providing basic View state. Here is clear description of what activation is in Android terms.
From the other hand,
public boolean isChecked ()

is more 'high level' property of another entity - CompoundButton and provides it's state - is it ON or OFF.


text:
Q: Formula for the derivative of finite power series in reversed order of terms. I wanted to solve the polar part in Schrödinger's wave equation for the H-atom by direct substitution of functions of form:-
$$
\Theta_{lm}(\theta) = a_{lm} \sin^{|m|}\theta \sum_{r≥0}^{r≤(l-|m|)/2}(-1)^rb_r \cos^{l-|m|-2r}\theta
$$
The $a$'s are normalisation constants, no problem there. However, the problem of determining the $b$'s ultimately drops down to finding the first and second derivatives of the polynomial in $z=\cos \theta$:
$$
P(z)=\sum_{r≥0}^{r≤(l-|m|)/2} (-1)^rb_r z^{l-|m|-2r}
$$
Which is a finite power series written in decreasing order of powers. I couldn't find a formula for so (well sometimes I get that dumb), but I think it does exist, maybe some reference book or website. I emphasize that what I'm doing is right the reverse of Frobenius-method. Thanks.


text:
Q: CompletableFuture, thenCompose method I have some misunderstanding about the contract of thenCompose(Function<? super T,? extends CompletionStage<U>> fn). Here is what's said there:

Returns a new CompletionStage that, when this stage completes
  normally, is executed with this stage as the argument to the supplied
  function.

It seems the function accepts the result of this CompletionStage, not the CompletionStage itself. So what do they mean  by that?
And what about the task represented by the returned CompletableFuture?
Runnable r;
ExecutorService es;
Function<Void, CompletableFuture<Void>>f;
//...
CompletableFuture.runAsync(r, es)
.thenCompose(f);

Does it mean, a task, represent by CompletableFuture returned by thenCompose will be executed in the same ThreadPool as the Runnable r?

A: This appears to be a mistake in the JavaDoc. Other methods such as thenApply use the following formulation:

Returns a new CompletionStage that, when this stage completes
  normally, is executed with this stage's result as the argument to the
  supplied function. […]

(emphasis is my own)
Also, in Java 9, the formulation is now:

Returns a new CompletionStage that is completed with the same value as
  the CompletionStage returned by the given function.
When this stage completes normally, the given function is invoked with
  this stage's result as the argument, returning another
  CompletionStage. When that stage completes normally, the
  CompletionStage returned by this method is completed with the same
  value. […]

As to which thread/thread pool will execute the function, this will actually depend on the implementation.
For CompletableFuture, this is indicated at the top of the documentation:

Actions supplied for dependent completions of non-async methods may be performed by the thread that completes the current CompletableFuture, or by any other caller of a completion method.

In practice, there seem to be 2 possible cases:

*

*If this stage is already completed, then the function is applied immediately on the thread calling thenCompose();

*If this stage is not completed yet, the function will be applied on the thread that completes this stage (correct me if wrong).

Note that there is no "task" inside a CompletableFuture. The only "task" that the returned CompletableFuture does is binding the result of the one returned by the passed function with itself. You are in charge of executing the task that will complete the CompletableFuture your function returns.


text:
Q: Titanium Studio Error: No Android SDK found I am new to the Titanium or any other cross platform SDK. I am facing issues with the setup of Titanium Studio. I followed steps as below:
Installed NodeJS
Installed JDK 1.7 update 55 32-bit
Installed Titanium Studio 3.2.3
After first launch of Titanium Studio it installed the Titanium SDK, Alloy, Titanium CLI and other updates. In the preferences,
Titanium SDK Path
C:\Users\<UserName>\AppData\Roaming\Titanium\
ANDOIRD SDK Path
E:\adt-bundle-windows-x86_64-20131030\sdk
Environment Variables are set as follows:
ANDROID_SDK
E:\android-sdk-windows
ANDROID_SDK_HOME
c:\users\<UserName>
JAVA_HOME
C:\Progra~2\Java\jdk1.7.0_55
Path
C:\Program Files\TortoiseSVN\bin;c:\Progra~2\Java\jdk1.7.0_55\bin;C:\Program Files\nodejs\;C:\Program Files (x86)\Git\git-cheetah\..\bin;E:\android-sdk_r22.3-windows\android-sdk-home\tools;E:\android-sdk_r22.3-windows\android-sdk-home\platform-tools;C:\Program Files (x86)\Git\bin;C:\Program Files\nodejs
There are two problems here:
Alloy is not available in the new project template and
Android SDK is not available in the project template

A: On Windows Min JDK Version  supported is 6 (aka 1.6) rev 10 and Max JDK Version supported is 6 latest revision.
The 32-bit version of the JDK is required regardless of whether Titanium is running on a 32-bit or 64-bit Windows system.
On Windows, Studio contains its own JRE, meaning you do not need to install the JDK before installing or launching Studio but will need it to use the Titanium SDK.
Titanium Studio prompts you to install the JDK when installing the Android SDK from the Dashboard on Windows.
For more details please check this link.


text:
Q: Translucent System Bars on KitKat with Phonegap Build I'd like to give my Phonegap Build app a modern and fresh look by using the translucent system bars on phones running KitKat but as far as I know it's currently impossible to use custom Android style items. It is possible to select a theme with the gap:config-file tag but there isn't a default Android theme with translucent system bars.
Would a proper conclusion be that it's absolutely impossible to use translucent system bars? Or is there some kind of workaround/hack?
If it isn't possible at the moment, could I ever expect this feature in Phonegap Build? Or does the KitKat Webview not allow translucent bars at all?


text:
Q: Alert using the select object I have tried using the select object with JavaScript but it dosent seem to be going.  do anyone know what am talking about
this is what I have tried
var x = document.getElementById("mySelect").selectedIndex;

var u = document.getElementsByTagName("option")[x].value;

        document.getElementById("demo").innerHTML=u;

A: var sel = document.getElementById("mySelect");  //reference the select
var index = sel.selectedIndex;  //find the index that was picked
var option = sel.options[index];  //select the option that was picked
document.getElementById("demo").innerHTML = option.value;  //read the value

if you want the text and not the value use .text
document.getElementById("demo").innerHTML = option.text;  //read the value

What this sample code does not do is deal if nothing is selected. That would be a selectedIndex equal to -1.


text:
Q: spring @Transactional JDBC Template MySQL DB not rolling back I am trying to implement the Spring @transactional with jdbc templates from the service layer calling
2 insert methods in a DAOImpl and using simplejdbctemplate to the insert and i see in the logs that spring creates a new transaction on my service method and my first insert suceeds and the second insert fails and even though it says it is rolling back on the same connection the first insert never get rolled back from my Mysql DB.(i am using innodb engine).
Here is my service method.
@Service
@TransactionConfiguration(transactionManager="txManager")
public class NewWizardService{
    ApplicationContext ctx = new ClassPathXmlApplicationContext("dataSourcesConfig.xml");
    UserDAO userDAO = (UserDAO)ctx.getBean("userDAO");
    @Transactional(rollbackFor=Throwable.class,  readOnly=false)
    public void createNewFirm()
    {

    userDAO.insert1();
    userDAO.insert2();

    }

}
Here is my datasource and transaction manager spring configuration.
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

<bean id="dbcpDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName"><value>${jdbc.driverClassName}</value></property>
    <property name="url"><value>${jdbc.url}</value></property>
    <property name="username"><value>${jdbc.username}</value></property>
    <property name="password"><value>${jdbc.password}</value></property>
</bean>

<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>

Here is my log trace.
2012-03-28 16:56:31,460 DEBUG [org.springframework.jdbc.datasource.DataSourceTransactionManager] - Creating new transaction with name [com.CAIS.wizardService.NewWizardServiceImpl.createNewFirm]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; '',-java.lang.RuntimeException
2012-03-28 16:56:31,654 DEBUG [org.springframework.jdbc.datasource.DataSourceTransactionManager] - Acquired Connection [org.apache.commons.dbcp.PoolableConnection@7d627b8b] for JDBC transaction
2012-03-28 16:56:31,660 DEBUG [org.springframework.jdbc.datasource.DataSourceTransactionManager] - Switching JDBC Connection [org.apache.commons.dbcp.PoolableConnection@7d627b8b] to manual commit
2012-03-28 16:56:31,663 DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Executing prepared SQL update
2012-03-28 16:56:31,663 DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Executing prepared SQL statement [insert into client (fullName, createDate, createUser) values (?, ?, ?)]
2012-03-28 16:56:31,663 DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - Fetching JDBC Connection from DataSource
2012-03-28 16:56:31,664 DEBUG [org.springframework.jdbc.datasource.DriverManagerDataSource] - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/cais]
2012-03-28 16:56:31,816 DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - Registering transaction synchronization for JDBC Connection
2012-03-28 16:56:31,833 DEBUG [org.springframework.jdbc.core.JdbcTemplate] - SQL update affected 1 rows
2012-03-28 16:56:31,840 DEBUG [org.springframework.jdbc.core.JdbcTemplate] - SQLWarning ignored: SQL state '01000', error code '1265', message [Data truncated for column 'createDate' at row 1]
2012-03-28 16:56:31,842 DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Executing prepared SQL update
2012-03-28 16:56:31,842 DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Executing prepared SQL statement [insert into client (fullName, createDate, createUser) values (?, ?, ?)]
2012-03-28 16:56:31,918 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Finished creating instance of bean 'Sybase'
2012-03-28 16:56:31,918 INFO [org.springframework.jdbc.support.SQLErrorCodesFactory] - SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase]
2012-03-28 16:56:31,918 DEBUG [org.springframework.jdbc.support.SQLErrorCodesFactory] - Looking up default SQLErrorCodes for DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@6cf84b0a]
2012-03-28 16:56:31,920 DEBUG [org.springframework.jdbc.support.SQLErrorCodesFactory] - Database product name cached for DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@6cf84b0a]: name is 'MySQL'
2012-03-28 16:56:31,920 DEBUG [org.springframework.jdbc.support.SQLErrorCodesFactory] - SQL error codes for 'MySQL' found
2012-03-28 16:56:31,920 DEBUG [org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator] - Unable to translate SQLException with Error code '1406', will now try the fallback translator
2012-03-28 16:56:31,920 DEBUG [org.springframework.jdbc.support.SQLStateSQLExceptionTranslator] - Extracted SQL state class '22' from value '22001'
2012-03-28 16:56:31,921 DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - Returning JDBC Connection to DataSource
2012-03-28 16:56:31,923 DEBUG [org.springframework.jdbc.datasource.DataSourceTransactionManager] - Initiating transaction rollback
2012-03-28 16:56:31,923 DEBUG [org.springframework.jdbc.datasource.DataSourceTransactionManager] - Rolling back JDBC transaction on Connection [org.apache.commons.dbcp.PoolableConnection@7d627b8b]
2012-03-28 16:56:31,934 DEBUG [org.springframework.jdbc.datasource.DataSourceTransactionManager] - Releasing JDBC Connection [org.apache.commons.dbcp.PoolableConnection@7d627b8b] after transaction
2012-03-28 16:56:31,934 DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - Returning JDBC Connection to DataSource

Thanks in advance.

A: use @Transactional instead of @TransactionConfiguration because it is for transactional tests.
@Transactional is fine for a single txManager, but if you have more than one, you can change your tx anno. like @Transactional("productTxManager") or @Transactional("orderTxManager").

A: Your <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/> needs to be defined in your webapp-serlet.xml.
You will find an explaination here : Spring @Transactional annotations ignored


text:
Q: Taking a list of integers in groups of three and outputting them in groups of 8 i am working on a few exercises to do with parallel using the groovy plugin in java however i have hit a wall. The system takes data objects that contain three integers but has to output the data in objects that contain integers.
What iv got so far:
import org.jcsp.lang.*

class GenerateSetsOfThree implements CSProcess {

    def ChannelOutput outChannel

    void run(){
        def threeList = [
                         [1, 2, 3],
                         [4, 5, 6],
                         [7, 8, 9],
                         [10, 11, 12],
                         [13, 14, 15],
                         [16, 17, 18],
                         [19, 20, 21],
                         [22, 23, 24] ]
        for ( i in 0 ..< threeList.size)outChannel.write(threeList[i])
        //write the terminating List as per exercise definition
        outChannel.write ([-1, -1, -1])

this all works fine.
Then:
import org.jcsp.lang.*

class ListToStream implements CSProcess{

    def ChannelInput inChannel
    def ChannelOutput outChannel

    void run (){
        def inList = inChannel.read()
        while (inList[0] != -1) {
            // hint: output list elements as single integers
        outChannel.write (inList[0, 1, 2, 3, 4, 5, 6, 7])

        }
        outChannel.write(-1)
    }
}

This is where the issue arises, i have no idea how to take the integers and group them into eights
finally:
import org.jcsp.lang.*

class CreateSetsOfEight implements CSProcess{

    def ChannelInput inChannel

    void run(){
        def outList = []
        def v = inChannel.read()
        while (v != -1){
            for ( i in 0 .. 7 ) {
                // put v into outList and read next input
                outList = [(v)]
                v = inChannel.read()
            }
            println " Eight Object is ${outList}"
        }
        println "Finished"
    }
}

this all seems fine.
Any advice would be appreciated.
Thanks.

A: you are not supposed to convert them in ListToStream to octuples already.  first they get converted to single values there.  the convertion to octuples is done in the last step CreateSetsOfEight.  to pass down single values, you emit each value on its own.
e.g.
while (inList[0] != -1) {
    // hint: output list elements as single integers
    inList.each{ outChannel.write it }
    inList = inChannel.read()
}

Yet all the anwers are online too: https://github.com/GPars/GPars/tree/master/docs/JonKerridgeBook


text:
Q: Oracle SQL Date Format I have been trying to convert the following varchar into date format with no luck:
12/99
01/04

I have tried to_char(mydate, 'mm/yy') which gives me errors.  Is there any way to convert this to date format even though I am missing the day?

A: You can use RR format for year:
select to_date('12/99','mm/rr') from dual --01/12/1999
select to_date('01/04','mm/rr') from dual --01/01/2004

This format get years between 1950 to 2049.


text:
Q: Can I make an assignment operator on a base class that returns sub-class type Sorry for the bad title... I have a base class like:
template<class T>
class GPtr
{
public:
    typedef T BaseType;

    GPtr& operator=(const BaseType& rhs)
    {
        ...
    }
};

I often want to make subclassed specializations like:
class GraphicPtr : public GPtr<Graphic>
{
...
};

However my base-class assignment operator still returns GPtr<Graphic> not GraphicPtr and it's annoying to have to copy-paste code in case the core assignment operator functionality should change later.
Is there a neat way to define the base-class assignment operator so it returns the type of the actual class in use?

A: In C++, the base class has no idea of it's children. You may add a template parameter that will be the derived class and use it.
template<class T, class Derived>
class GPtr
{
public:
    typedef T BaseType;

    Derived& operator=(const BaseType& rhs)
    {
        ...
    }
};

A: Maybe you can use the CRTP instead?
#include <iostream>

template<class Derived>
class GPtr
{
public:
    typedef Derived DerivedType;

    GPtr& operator=(const GPtr& rhs)
    {
        std::cout << "GPtr::operator=" << std::endl;

        return *this;
    }
};

class GraphicDerived : public GPtr<GraphicDerived>
{
    public:

        GraphicDerived& operator=(const GraphicDerived& rhs)
        {
            std::cout << "GraphicDerived::operator=" << std::endl;
            // Inheiriting shadows the name of the base operator= which
            // needs to be explicitly called.
            GPtr<GraphicDerived>::operator=(rhs);
            return *this;
        };
};

class Graphic {};

using namespace std;

int main()
{

    GraphicDerived one;
    GraphicDerived two;

    cout << "derived assignment: " << endl;
    one = two;

    GPtr<Graphic> ptrOne;
    GPtr<Graphic> ptrTwo;

    cout << "GPtr assignment stnadalone : " << endl;

    ptrOne = ptrTwo;
};

Results with:
derived assignment:
GraphicDerived::operator=
GPtr::operator=
GPtr assignment stnadalone :
GPtr::operator=

A: What you are asking for does not really make sense. When the base object is being assigned, it cannot possibly know which of the potentially infinite number of derived types it is being called from, and thus cannot return a different type in each case. Furthermore, even if that was possible, it would not be possible to use that in real code.
C++ resolves everything but polymorphic calls at runtime, and even for polymorphic calls it only delays finding the exact override, but not the signature (i.e. even with covariant return types, the return type of the base override will be used.
Technically it can be done, with or without templates, but all of them exhibit the same core issue: The base class can only be a base class for a single type, the type returned by the assignment operator, limiting the usability as a base class.
What is the real problem that you want to solve?
The approach that you are taking does not seem appropriate. It would be much better if you explained what you are trying to achieve so that people can suggest other approaches.


text:
Q: What is the meaning of this []? I can't understand the reason of using [0] in front of dish.id and dish.featured in the following code:
import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish';
import { DISHES } from '../shared/dishes';

@Injectable()
export class DishService {

  constructor() { }

  getDishes(): Dish[] {
    return DISHES;
  }

  getDish(id: number): Dish {
    return DISHES.filter((dish) => (dish.id === id))[0];
  }

  getFeaturedDish(): Dish {
    return DISHES.filter((dish) => dish.featured)[0];
  }
}

This is the  Dish class:
import { Comment } from './comment';

export class Dish {
    id: number;
    name: string;
    image: string;
    category: string;
    label: string;
    price: string;
    featured: boolean;
    description: string;
    comments: Comment[];
}

A: Read this .filter(). The reason why the dish.id and dish.featured has [0] in the end because filter always returns the result in an array.

var words = ['a','spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length == 1);

console.log(result);

A: Filter returns an array so when you use [0] It means take the first selection.
You can read more here: Filter


text:
Q: How to implement opacity compatible in both IE5 and IE11 I am trying to render a form with opacity = 0.5 & disable the actions of elements on a button click , it works well in IE11 but fails in IE 5 .
<script>
function opaqueForm(){
var form = document.getElementById('myFormName'),s,opacity;
s = form.style;
s.filter = 'alpha(opacity=50)';
s.opacity = 50/100
for(var i=0;i<form.length;i++) form[i].disabled=true;
}
</script>

When I tried to check the DOM explorer to see how it is rendered , I see in IE 5 the filter is applied to the form and opacity is not applied . The form is not rendered opaque in IE5.
Can anyone suggest how to style the form to render it opaque in both IE5 and IE11
Thanks in advance for any suggestions & solutions.

A: You would probably be safe not expending effort supporting a browser that reached end of life two decades ago.
But, for historical curiosity, it turns out (to my surprise) that what you want is actually possible! Versions of Internet Explorer from v5.5 through v8 used a proprietary -ms-filter property instead of standards (as is true of many IE features; this was during the "Embrace and Extend" era.)
The syntax for opacity looked something like this:
{ filter:progid:DXImageTransform.Microsoft.Alpha(opacity = 100 ... ) ... }


text:
Q: Landing page keeps returning static files in express I am trying to use static files in my project, but when the user makes a get request to my "/" landing page. I want to send non-static things like a json. But for some reason it just automatically sends my index.html in my static file.
const express = require("express");
const app = express();

app.use(express.static("public"));

app.get("/", (req, res) => {   //This sends the user to the index.html even tho i want to send 123
  res.send("123");
});

app.listen("3000");

A: As your code is written, the express.static() middleware looks at the / request, finds an index.html file in the public directory and serves that as the response for the / request.  This is a feature of express.static() that is causing a conflict for you with your custom route for "/".
You have at least four choices for a solution here:

*

*You can specify an option for express.static() to disable the index.html feature so it will avoid the "/" route and pass control on to your subsequent route handlers.

*You can move the express.static() middleware AFTER your app.get("/", ...) route so that your custom route gets first dibs at the request.

*You can remove the index.html file from your public directory so express.static() won't find it.  Using a template system for all your HTML files that locates all HTML template files in some other directory that express.static() can't see (such as a views directory) would cause this to happen too or just moving it to some private directory and using it from your code from the private directory would work too.

*Give ALL your static resources a common path prefix so there is never a URL conflict between static resources and custom route handlers.

The first option (disable index.html feature in express.static()) would look like this:
const express = require("express");
const app = express();

// disable index.html feature
app.use(express.static("public"), {index: false});

app.get("/", (req, res) => {
  res.send("123");
});

app.listen("3000");

The second option (change the order of route definitions/middleware) would look like this:
const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.send("123");
});

// put this after custom route definitions so they take precendence
app.use(express.static("public"));

app.listen("3000");

The fourth option (give all static resources a common path prefix) would look like this:
const express = require("express");
const app = express();

app.use(express.static("/static", "public"));

app.get("/", (req, res) => {
  res.send("123");
});

app.listen("3000");

With this fourth option, you'd then have to prefix all your static URLs with the static prefix (which you can make anything you want) and thus "/" would never be a match for express.static().

A: Is there any particular reason that you have an index.html file inside your public directory and are serving something else? The convention is serve static assets such as CSS, JS, images etc. from your public folder, and HTML / templates in folder which would be a sibling of public such as views.
The browser will always default to rendering an index.html file if it is found in the root of the public directory. Move the HTML file to a separate folder and the route should work

A: app.use is a middleware, so whenever you're running a app, it always first go through the middleware, Try the below code
const express = require("express");
const app = express();

app.get("/", (req, res) => {   //This sends the user to the index.html even tho i want to send 123
  res.send("123");
});

app.use(express.static("public"));

app.listen("3000");


text:
Q: How can I retrieve a numerical value for the wifi strength on Mac OSX? I'm looking for a numerical value that represents the wifi signal strength on my Mac. Is there an easy command line tool that can continuously report wifi signal and/or dropped packet statistics?

A: So I made a function in z shell to easily find the wifi strength with a numerical value thanks to the help from someone at MoonPoint.com[1] who knows far more about the utility than I do.
To use it, just append this code to the bottom of ~/.zshrc. Next time you open the shell, just type in wifi to run the command once or wifi -l or wifi --loop to run it continuously.
path+="/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/"
wifi(){
    if [[ -n $1 && (($1 == -l || --loop)) ]]; then
        clear
        while true; do
            airport -I;
            echo "Press Ctr+c to exit.";
            sleep 1;
            clear;
        done
    else
        airport -I;
        echo "\nPass -l or --loop for continous measurement"
    fi
}

The output will look like this.
wifi
     agrCtlRSSI: -76
     agrExtRSSI: 0
    agrCtlNoise: -94
    agrExtNoise: 0
          state: running
        op mode: station
     lastTxRate: 130
        maxRate: 217
lastAssocStatus: 0
    802.11 auth: open
      link auth: wpa2-psk
          BSSID:
           SSID: ATTUYrDBxi
            MCS: 1
  guardInterval: 800
            NSS: 2
        channel: 60,80

Pass -l or --loop for continous measurement

agrCtlRSSI represents the signal strength and can be a value from -100 to 0. The closer it is to 0, the better. I still need to figure out what NIC IC is being used so I understand what power (dB) it translates to, but it's at least better than three little wifi bars when troubleshooting connection speed.


text:
Q: Change Django Form Attribute on view I'm using a Django Form with a DatePicker widget. I have to define the Min and Max date of the DatePicker on a class level. I would like to have these two values change when I run my view, otherwise, it keeps the Min and Max date values from the time that I start my Django server.
from django import forms
from bootstrap_datepicker_plus import DatePickerInput
import pandas as pd
import datetime as dt

MIN_DATE = dt.datetime.today().strftime('%m-%d-%Y')
MAX_DATE = (dt.datetime.today() + dt.timedelta(days=92)).strftime('%m-%d-%Y')

class TableEdit(forms.Form):
    Account = forms.CharField(label='Account', max_length=10)
    Hedge = forms.CharField(label='Hedge', max_length=10)
    Date = forms.DateField(widget=DatePickerInput(
        options={
            'format': 'MM/DD/YYYY',
            'minDate': MIN_DATE,
            'maxDate': MAX_DATE
        }))

How can I modify my MIN_DATE and MAX_DATE form attributes every time that I call my form from a view?

A: You can achieve this in the form's __init__ method, like so:
class TableEdit(forms.Form):
    Account = forms.CharField(label='Account', max_length=10)
    Hedge = forms.CharField(label='Hedge', max_length=10)
    Date = forms.DateField()

def __init__(self, *args, **kwargs):
    super(TableEdit, self).__init__(*args, **kwargs)
    min_date = dt.datetime.today().strftime('%m-%d-%Y')
    max_date = (dt.datetime.today() + dt.timedelta(days=92)).strftime('%m-%d-%Y')
    self.fields['Date'].widget = DatePickerInput(
        options={
            'format': 'MM/DD/YYYY',
            'minDate': min_date,
            'maxDate': max_date
        })


text:
Q: Space complexity O(1) storing string I am a bit confused on space complexity.  Is this O(1) space complexity or O(N) complexity?
Since I am creating a string of size n, my guess is the space complexity is O(N) is that correct?
## this function takes in a string and returns the string

def test(stringval):
stringval2 = ""
for x in stringval:
   stringval2 = stringval2 + x
return stringval2

test("hello")}

A: Yes, that's correct. The space complexity of storing a new string of length n is Θ(n) because each individual character must be stored somewhere. In principle you could reduce the space usage by noticing that stringval2 ends up being a copy of stringval1 and potentially using copy-on-write or other optimizations, but in this case there's no reason to suspect that this is the case.
Hope this helps!


text:
Q: clerification of definition topology I have read that [0,1] with respect to the metric topology is a topological space. Where the metric topology is that a subset of X=[0,1] is open (and in the topology) if and only if it is a union of balls.
In the definiton of a topology it says that X needs to be in the topology, i.e X needs to be open in X. But [0,1] can not be written as a union of balls. Therefore i am wondering wether you can take any set X and put a topology on it, and define X as open, even thoug it is not open w.r.t the "topology rule", or if i am missunderstanding something, and [0,1] actually can be written as an union if balls?

A: In the interval $[0,1]$, the open ball with center at $\frac12$ and radius $1$ is actually $[0,1]$. By definition, this open ball consists of all points $x\in X$ with $|x-\frac12|<1$, and this is clearly true for all elements of $X$.
From the fact that $X\subseteq \Bbb R$, one might intuitively expect that ball to be $(-\frac12, \frac32)$. This is not true. Open balls in a metric space are always subsets of the metric space themselves, so open balls of $X$ cannot go outside $X$.
If you want open balls in some metric space which lies naturally inside some bigger metric space, you have to be very clear on whether those balls are considered balls in the larger space or in the smaller space, because that does affect what the balls look like once they get close to the boundary of the smaller space (basically, is the smaller space thought of as a space on its own, or is it just a subset of the larger space). In this case, we're forgetting $\Bbb R$ and focusing on $X$, so that's where the open balls lie.


text:
Q: Order Link List I have a base class called linkList and two derived class. One order link list class and unorder link list class. My order link list class is not working and i have no idea why.When i insert 3 numbers into the list it work but when i insert more than 4 values it messes up. It will also say the length of the list is larger than what it actually is. [enter image description here][1]
void insert(const T& newItem){
    nodeType<T> *current;
    nodeType<T> *trailCurrent=nullptr;
    nodeType<T> *newNode;

    bool found;

    newNode = new nodeType<T>;
    newNode->info = newItem;
    newNode->next = nullptr;

    //if the list is empty add to empty list
    if (this->first == nullptr){
        this->first = newNode;
        this->last = newNode;
        this->count++;
    }
    else {

        current = this->first;
        found = false;

        while (current != nullptr && !found){
            if (current->info >= newItem)
                found = true;
            else{
                trailCurrent = current;
                current = current->next;
            }

            //if current value is first item into the list insert into the front
            if (current == this->first){
                newNode->next = this->first;
                this->first=newNode;
                this->count++;

            }
            else{

                trailCurrent->next = newNode;
                newNode->next=current;

                if (current == nullptr)
                    this->last = newNode;

                this->count++;

            }
        }

    }

}


text:
Q: How can I create thousands of associated products? My configurable product has four attributes - each attribute has up to 36 options resulting in thousands of options for the customer to choose from.
How can I create all the associated products without doing it one by one?
Or is there a better way to make all the choices available?

A: Try using this
private function _attachProductToConfigurable( $_childProduct, $_configurableProduct ) {
   $loader = Mage::getResourceModel( 'catalog/product_type_configurable' )->load( $_configurableProduct, $_configurableProduct->getId() );

   $ids = $_configurableProduct->getTypeInstance()->getUsedProductIds();
   $newids = array();
   foreach ( $ids as $id ) {
      $newids[$id] = 1;
   }

   $newids[$_childProduct->getId()] = 1;

   //$loader->saveProducts( $_configurableProduct->getid(), array_keys( $newids ) );
   $loader->saveProducts( $_configurableProduct, array_keys( $newids ) );
}


text:
Q: Json request returning data in browser, but not in App I have an ASIHTTPREQUEST querying a server which returns a JSON object. When I access the Url(http://xxxxxxxxxxx.xxx/xxxxx.json) via a browser, the JSON object is fine. However, when I request it in the app with
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:address]];

the JSON object structure is returned, but the values are all "can't be blank".
Anyone have any ideas as to why this is happening?

A: I sorted this by changing it to ASIHTTPRequest.


text:
Q: Script started throwing "Reference error SpreadsheetApp is undefined " I made an script for a Google Sheets. It's been a month since people used it and worked perfectly.
Basically the script looks in a spreadsheet, makes some formulas with the data and returns a value.
At the beginning of the script I call for "SpreadsheetApp.getActiveSpreadsheet()" function that returns me the actual spreadsheet. The problem is that sometimes the script returns an error that says "Reference error: SpreadsheetApp is undefined".
The weird thing is that if I close the Spreadsheet and open it again after 5 minutes (random time) the script works well! I can't find the error pattern. I don't know if it's something I made, or something from Google.
Can anyone help me?

A: Try open spreadsheet by ID
SpreadsheetApp.openById("0sdfksdlfkjsdlkfj_example_fdslkfjlsjkf");


text:
Q: How to deserialize a json array with multiple data types? I now need to deserialize a JSON that looks like this:
{
    "arguments": {
        "game": [
            "--username",
            "--version",
            "--assetsDir",
            {
                "rules": [
                    {
                        "action": "allow",
                        "features": {
                            "is_demo_user": true
                        }
                    }
                ],
                "value": "--demo"
            },
            {
                "rules": [
                    {
                        "action": "allow",
                        "features": {
                            "has_custom_resolution": true
                        }
                    }
                ],
                "value": [
                    "--width",
                    "--height"
                ]
            }
        ]
    }
}

As you can see, the array named "game" has both "value" and "object" in it. (But the fact is WORSE than this example, the number of elements is NOT certain)
And the data type of arguments.game[*].value is NOT certain, too.
I used to use classes to describe it, but deserialization failed.
Can't seem to describe an array with multiple element types with a class?
I am using Json.NET. Is there any way to deserialize this "game" array.
Thanks.

A: Is it a requirement to deserialize to an instance of a class? You could use an ExpandoObject:
using System.Dynamic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

Console.WriteLine("Hello, World!");
string json = @"{
""arguments"": {
    ""game"": [
        ""--username"",
        ""--version"",
        ""--assetsDir"",
        {
            ""rules"": [
                {
                    ""action"": ""allow"",
                    ""features"": {
                        ""is_demo_user"": true
                    }
                }
            ],
            ""value"": ""--demo""
        },
        {
            ""rules"": [
                {
                    ""action"": ""allow"",
                    ""features"": {
                        ""has_custom_resolution"": true
                    }
                }
            ],
            ""value"": [
                ""--width"",
                ""--height""
            ]
        }
    ]
}
}";

var expConverter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, expConverter);

The obj variable will contain the result of the JSON conversion, then you can traverse the dynamic object in code.
For example, to get a list of strings under 'game':
IList<object> list = new List<object>(obj.arguments.game);
foreach (object str in list)
{
    if (str as string != null)
    {
        Console.WriteLine(str as string);
    }
}


text:
Q: How can I tell the user is logged into Facebook on iOS? I'm using the Accounts Framework on iOS 6 to get access to Facebook. As long as the user has logged into Facebook in Settings, it works great. However, when they are not logged in to Facebook, my call to -requestAccessToAccountsWithType:options:completion: sends a generic system error to the completion block:
Error Domain=com.apple.accounts Code=6 "The operation couldn't be completed. (com.apple.accounts error 6.)"

Seems pretty useless. Is there some other way I'm supposed to know that the user is not logged in?
(Incidentally, this is not an issue when the user is logged in toFacebook but has disabled access to my app in Settings: that returns an unambiguous error code.)

A: I think +isAvailableForServiceType: in SLComposeViewController is what I need. I hadn't thought to look there, because I'm not using SLComposeViewController. But I don't see why I can't call this class method and not try to request access if it returns false.

A: I'm trying to solve the same issue. I've just notice that the error code is 6 when the use has not connect the phone with facebook. It's 7 when the user is connected and press the "don't allow" button.
The documentation is available in the ACError.h file.


text:
Q: Google Chrome Extension POST to AWS DynamoDB? I'm trying to set up a simple Google Chrome Extension that will pop up a form.
The form will collect first name, last name, career title, and other informations when the user uses the extension on a particular page.
Upon submit of the pop up form, the form will reach API Gateway that trigger Lambda to write data to DynamoDB.
I can't seem to find any documentations/guides/tutorials around how to connect Chrome Extensions to AWS services.
I was wondering if I setup a React Chrome Extension, and then install AWS Amplify. Upon build by Chrome, will the AWS Amplify work..?

A:
I can't seem to find any documentations/guides/tutorials around how to connect
  Chrome Extensions to AWS services.

From AWS perspective Chrome Extension is the same as real user, web site or any other client. Depending on a technical stack of you extension, you can use AWS API or SDK inside your extension to work with AWS.


text:
Q: Use same usestate hook for multiple icons I have a two buttons in my react project (material ui icons) which are lowerarrow(both) and i made a use state and function to change upper arrow to lower arrow when it is clicked but i dont know how to use the same state for my another icon too, maybe using some id or something  i dont know , right now i put {iconstate} in both the icons so both the icons are changing together i am trying to figure out how to change them individually without making new state and function here is my code :-
JSX:-
import React , {useState} from 'react';
import Weather_leftpanecss from './Weather_leftpane.module.css'
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';

export default function Weather_leftpane() {

  const [iconstate, seticonstate] = useState(<KeyboardArrowDownIcon/>)
  const [valuestate, setvaluestate] = useState(true)

  const togglearrow = ()=>{
    if(valuestate==true){
      seticonstate(<KeyboardArrowUpIcon/>)
      setvaluestate(false)

    }
    else{
      seticonstate(<KeyboardArrowDownIcon/>)
      setvaluestate(true)
    }
  }

  return

Weather

          <input type="text" placeholder='Search for city..' />

            Cities

            {iconstate}

            Settings

            {iconstate}

;
}

css:-
.App {
  font-family: sans-serif;
  text-align: center;
}

(not the real css ,just added it because i have included it everywhere in my code with module)

A: Here you need to save the selected Id in the state.
import React , {useState} from 'react';
import Weather_leftpanecss from './Weather_leftpane.module.css'
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';

export default function Weather_leftpane() {

  const [valuestate, setvaluestate] = useState(true)
  const [id, setId] = useState(null);

  const togglearrow = (val)=>{
    if(valuestate==true){
      setvaluestate(false)
    }else{
      setvaluestate(true)
    }
    setId(val);
  }

  return

Weather

          <input type="text" placeholder='Search for city..' />

            Cities

 togglearrow('item_3_2')} >
            {valuestate && id == 'item_3_2' ? KeyboardArrowUpIcon : KeyboardArrowDownIcon }

            Settings

 togglearrow('item_4_1')}>
          {valuestate && id == 'item_4_1' ? KeyboardArrowUpIcon : KeyboardArrowDownIcon }

;
}

A: Here you can use one state to achieve that, saving in one state the status of both buttons, which one is clicked or not and render the icon based on that status.
the toggleArrow function gets the itemId and uses it to set the updated value of the button. We use !prevState[itemId] since if it is false it will become true and vise versa.
I took the liberty of giving the state a more informative name than a generic name.
import React, { useState } from "react";
import Weather_leftpanecss from "./Weather_leftpane.module.css";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";

export default function Weather_leftpane() {
  const [clickedButtons, setClickedButtons] = useState({
    item_3_2: false,
    item_4_2: false
  });

  const toggleArrow = (itemId) => {
    setClickedButtons((prevState) => ({
      ...prevState,
      [itemId]: !prevState[itemId]
    }));
  };

  return (

Weather

          <input type="text" placeholder="Search for city.." />

            Cities

 toggleArrow("item_3_2")}
          >
            {clickedButtons["item_3_2"] ? (
              <KeyboardArrowUpIcon />
            ) : (
              <KeyboardArrowDownIcon />
            )}

            Settings

 toggleArrow("item_4_2")}
          >
            {clickedButtons["item_4_2"] ? (
              <KeyboardArrowUpIcon />
            ) : (
              <KeyboardArrowDownIcon />
            )}

  );
}


text:
Q: Why isn't this new comment environment working ? "Illegal parameter number", "can't use macro parameter # in horizontal mode" I wanted to create a new comment environment with special format of comments to a text.
Here is the MWE:
\documentclass[french, 11pt, a4paper, titlepage]{report}
\usepackage[T1]{fontenc}
\usepackage[utf8x]{inputenc}
\usepackage{fontawesome}

\newenvironment{commentaire}[1]
{
\paragraph{\faCommentsO}
}
{
~(#1)
}

\begin{document}
    text above
    \begin{commentaire}{author}
        comment
    \end{commentaire}
    text bellow
\end{document}

Got those two errors

*

*Illegal parameter number in definition of \endcommentaire line 12

*You can't use 'macro parameter character #' in horizontal mode. line 18

I don't understand, especially because my new environment seems to feature the recquirements
Thank you !


text:
Q: Hibernate One to One, not generating Foreign key I have 4 tables here: Register, User, User roles and User Profile Image
Register and User are mapped my a One to One relationship and a reference of Register is generated in Users table...... This is fine..
Now talking about One to Many Relation between User and the Roles table, it also works perfectly by generating a User table reference in the roles table..
But problem is when working with One to One between User and the Profile Image. Profile Image is not generating reference of User....Why the user reference is not generated in Profile Image table
Register
@Entity
@Getter
@Setter
public class Register {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @OneToOne(cascade = CascadeType.ALL,orphanRemoval = true,mappedBy = "register")
    private User user;

}

User
@Entity
@Getter
@Setter
public class User {

    @Id
    @Column(name = "User_Id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @OneToOne(cascade = CascadeType.ALL,fetch=FetchType.EAGER)
    @JoinColumn(name = "user_id")
    private UserProfileImage userProfileImage;

    @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinColumn(name = "user_id")
    private List<UserRoles> userRoles;

}

User Profile Image
@Entity
@Getter
@Setter
public class UserProfileImage {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(name = "name")
    private String name;
    @Column(name = "type")
    private String type;
    @Column(name = "picByte", length = 100000)
    private byte[] picByte;

    public UserProfileImage() {
        super();
    }

    public UserProfileImage(String name, String type, byte[] picByte) {
        this.name = name;
        this.type = type;
        this.picByte = picByte;
    }
}

A: Profile mapping in User class is not correct and in your profile class there is no user field and hence it's not generating the user reference in the profile class.
Also, User to Roles mapping is also not correct, your user class will not populate roles with your mappings.
Try this:
public class User {

    ...
    @OneToOne(cascade = CascadeType.ALL,fetch=FetchType.EAGER)
    @JoinColumn(name = "PROFILE_IMAGE_ID")   // foreign key column in User table
    private UserProfileImage userProfileImage;

    @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER,mappedBy="user")
    private List<UserRoles> userRoles;

}

public class UserProfileImage {
    ...

    @OneToOne(mappedBy="userProfileImage")
    private User user;

    ...
}

public class UserRole {
    ...

    @ManyToOne
    @JoinColumn(name="USER_ID")  // foreign key column in User Role table
    private User user;

    ...
}


text:
Q: VPN with overlapping subnets? We have a number of site to site VPN tunnels which each have a their own consecutive subnet, for example:
Branch 1 - 192.168.1.0/24
Branch 2 - 192.168.2.0/24
Branch 3 - 192.168.3.0/24
Branch 4 - 192.168.4.0/24
Branch 5 - 192.168.5.0/24
Branch 6 - 192.168.6.0/24

We also have a number of users whom need to create PPTP tunnels while they are roaming. Occasionally those roaming users hit the expected problem that their local network matches that of Branch 1.
Note: All VPN tunnels terminate at Branch 1 and are given an IP in the 192.168.1.0/24 range.
The network design is the result of a legacy management system of which the network was a product of. I am now working towards adding additional subnets to Branch 1 to terminate the VPN tunnels. So, for example, Branch 1 would have the following subnets:
192.168.1.0/24
10.0.1.0/24
10.0.2.0/24
10.0.3.0/24

What I am trying to get my head around is where the conflict is causing problems. Essentially, the question is; if the VPN tunnels terminate to a subnet that does not match that of the roaming users' local network - will the conflict remain due to the 192.168.1.0/24 subnet existing on the terminating device, even though it's not the actual subnet the roaming client is connecting on?
Company VPN on same subnet as home network

A: The problem is that when a users is on a network with a matching subnet (192.168.{0,1,2}.0/24 are the most dangerous ones) the remote address it is trying to hit is a link-local address now, so the routing table is never consulted and the packet is just sent on the wire. Thus, the packet ment to go down the VPN doesn't since the machine thinks that the address it is trying to reach is link-local.


text:
Q: ThisDocument object reference How ThisDocument object refers to the docm file contents, which containing the code?
I had insert a module under the *.docm project which contains this code:
Sub test()
   Debug.Print ThisDocument.Name
End Sub

Returns Normal.dotm as result.
But it is expected returning the current docm file's name.
How can set 'Thisdocument' Object subroutines refers to the current docm file?
Any help would be greatly appreciated.

A: Get the name of the Excel file which contains the code you are running:
ThisWorkbook.Name

Get the name of the Excel file that your code is currently referencing:
ActiveWorkbook.Name

If you are running code from a Word doc that is referencing an Excel file, you would use ActiveWorkbook.Name.
This post goes into more detail on ActiveWorkbook vs ThisWorkbook.
Difference between Thisworkbook.name and Activeworkbook.name in VBA

A: As commented by  Cindy Meister, From the tagging and the question it's not clear exactly what you have (or have in your mind). However assuming that you are aiming something highly tricky and unconventional with both Excel & Word applications involved. In normal condition ThisDocument will never refer to Normal.dotm(from a module under the *.xlsm project) but since you made it happen and also aim to "set Thisdocument Object refers to the current xlsm file", I would have try it like this from a module in xlsm file.
Global ThisDocument As Object
Sub calltest()
Dim wd As Word.Application
Set wd = CreateObject("Word.Application")
wd.Visible = True                 'for demo only
Set ThisDocument = wd.Templates(1)   'This will result Normal.dotm (as you are experiencing - may be similar code is already in the calling routine)
test
Set ThisDocument = ThisWorkbook     'This will result workbook Containing the module with code
test
End Sub
Sub test()
Debug.Print ThisDocument.Name
End Sub

Obviously it is assumed Reference to Microsoft Word XX Object Library had aleady been taken.


text:
Q: Are "Shopify's Liquid" and "Siteleaf Liquid" the same? I see two sites for the Liquid lang, seems it is one lang:

*

*Shopify: https://shopify.github.io/liquid/

*Siteleaf: https://www.siteleaf.com/blog/tags/liquid/
Are they the same language? If not, what is most popular? Seems Shopify's because it's used in the Jekyll tool.

A: Yes, I think they are the same.
On the homepage the paragraph:
"Benefit from a large open source community. Use any
 existing Jekyll theme, or write your own using Liquid,
 Sass, and CoffeeScript. Develop locally and even offline."

The word "liquid" links to https://shopify.github.io/liquid/ suggesting they are using Shopify's liquid.


text:
Q: Is there a shorter way of writing function signatures that take and return closures? Is there a shorter way of writing these function signatures?
fn hof_five(a: i32, func: impl Fn(i32) -> i32) -> impl Fn(i32) -> i32 {
    move |v| func(a + v)
}

fn hof_six(a: i32, func: Box<dyn Fn(i32) -> i32>) -> Box<dyn Fn(i32) -> i32> {
    Box::new(move |v| func(a + v))
}

Something like using F: impl Fn(i32) -> i32 or F: Box<dyn Fn(i32) -> i32>
So that the signature becomes something like:
fn hof_five<F>(a: i32, func: F) -> F {
    move |v| func(a + v)
}

A: The two examples you gave are quite different.
fn hof_five(a: i32, func: impl Fn(i32) -> i32) -> impl Fn(i32) -> i32 {
    move |v| func(a + v)
}

This function accepts a closure of a type implementing Fn(i32) -> i32, and returns a closure of a type implementing this trait, but the argument and return types are different types. The argument type is inferred by the compiler based on the closure you pass in, and the return type is inferred based on the closure you return. Each closure has its own individual type.
Since argument type and return type are different types, there is no way to refer to them by the same name. The only thing you could do is define a trait that requires Fn(i32) -> i32 as a prerequisite:
trait MyFn: Fn(i32) -> i32 {}

impl<T> MyFn for T
where
    T: Fn(i32) -> i32,
{}

With this trait definition, you can rewrite hof_five as
fn hof_five(a: i32, func: impl MyFn) -> impl MyFn {
    move |v| func(a + v)
}

The blanket implementation of MyFn makes sure that all closures implementing Fn(i32) -> i32 automatically also implement MyFn.
fn hof_six(a: i32, func: Box<dyn Fn(i32) -> i32>) -> Box<dyn Fn(i32) -> i32> {
    Box::new(move |v| func(a + v))
}

This function accepts a pointer pointing to a closure implementing Fn(i32) -> i32, but the concrete type of that closure is not known at compile time. If you actually call the closure, the concrete type of the closure is determined at runtime, and the generated code dynamically dispatches to the right function. In this case, argument type and return type are the same type, so you can use a type alias if you want to:
type MyBoxedFn = Box<dyn Fn(i32) -> i32>;

fn hof_six(a: i32, func: MyBoxedFn) -> MyBoxedFn {
    Box::new(move |v| func(a + v))
}

This is completely equivalent to the original version.

A: Not usefully, no, there is not.
To make something shorter, you generally have to reduce redundancy or remove characters.

*

*There's no semantic redundancy because the argument and return type mean different things.

*impl and fn and i32 are already abbreviated, so they can't have characters removed.

All that's left is textual similarities. You can use a macro to do that, but I don't think it's a good idea:
macro_rules! F {
    () => (impl Fn(i32) -> i32);
}

fn hof_five(a: i32, func: F!()) -> F!() {
    move |v| func(a + v)
}

See also:

*

*What makes `impl Trait` as an argument "universal" and as a return value "existential"?

You might also be interested in using where clauses to spread out the complexity:
fn hof_five<F>(a: i32, func: F) -> impl Fn(i32) -> i32
where
    F: Fn(i32) -> i32,
{
    move |v| func(a + v)
}


text:
Q: Not all USB devices automatically mounted when hot-plugged Ubuntu 17.10 I'm running Ubuntu 17.10 and my iPhone and Kobo tablet (neither PTP nor MTP) won't be automatically mounted and shown in Nautilus when I plug them in. I can only mount and open these manually. All other devices, including usb sticks, a GoPro and a external hard drive do mount and open with Nautilus automatically when hot-plugged.
In Setting -> Devices -> Removable Media all settings are set. And also when I go to /org/gnome/desktop/media-handling with Dconf-editor all settings should be fine.
The story is, I updated from Ubuntu 16.04 to 17.10 and connected my iPhone to transfer some pictures, that's all I usually did. It still did work, but it didn't show all the pictures any more (this turned out to be an iPhone setting). But before I realised that, I started messing around with the libimobiledevice. Ended up deleting it, to attempt to reinstall, but automatically got a lot more deleted and couldn't get in the Ubuntu desktop environment anymore. Ended up reinstalling ubuntu-desktop, first nothing worked with both iPhone/ Kobo, but now it only works manually.

*

*iPhone 4s with iOS 9.3.5

*Kobo tablet with Android 4.2.2

*Laptop is an Acer Aspire V3-571


text:
Q: Group By and Fill With tidyr and dyplr Does Not Execute I have a dataframe:
Store <- c('A','A','A', 'B','C','C')
Main_or_branch <- c('main', 'Branch','Branch','main','main', 'Branch')
flavor <- c('chocolate', 'N/A','N/A', 'vanilla', 'strawberry','N/A')

df <- data.frame(Store, Main_or_branch, flavor)

and it looks like this:
 Store Main_or_branch flavor
 <fct> <fct>          <fct>
1 A     main           chocolate
2 A     Branch         N/A
3 A     Branch         N/A
4 B     main           vanilla
5 C     main           strawberry
6 C     Branch         N/A

I'm trying to use group by and fill :
df %>% group_by(Store) %>% fill(flavor)

but my output still looks like this
  Store Main_or_branch flavor
  <fct> <fct>          <fct>
1 A     main           chocolate
2 A     Branch         N/A
3 A     Branch         N/A
4 B     main           vanilla
5 C     main           strawberry
6 C     Branch         N/A

Does anyone know what the issue could be? running version tidyr 1.1.4
Thanks!

A: Using na.locf
library(zoo)
library(dplyr)
df %>%
   group_by(Store) %>%
   mutate(flavor = na.locf(na_if(flavor, "N/A"))) %>%
   ungroup
# A tibble: 6 × 3
  Store Main_or_branch flavor
  <chr> <chr>          <chr>
1 A     main           chocolate
2 A     Branch         chocolate
3 A     Branch         chocolate
4 B     main           vanilla
5 C     main           strawberry
6 C     Branch         strawberry

A: "N/A" is not the same as NA. Here you go:
df[df == "N/A"] <- NA  # Substitute all instances of "N/A" with NA

df %>% group_by(Store) %>% fill(flavor)

# A tibble: 6 x 3
# Groups:   Store [3]
  Store Main_or_branch flavor
  <chr> <chr>          <chr>
1 A     main           chocolate
2 A     Branch         chocolate
3 A     Branch         chocolate
4 B     main           vanilla
5 C     main           strawberry
6 C     Branch         strawberry

A: Just need to convert the string NAs to actual NA.
df %>%
  mutate(
    flavor = na_if(flavor, 'N/A')
  ) %>%
  group_by(Store) %>%
  tidyr::fill(flavor)


text:
Q: Any harm in binding directly to service properties? Is there any harm in the approach of creating a service which holds some state of my angular application, injecting that service into the components that are conditioning on the state and then in their templates binding directly to the respective properties of that service?
I saw that frequently Subjects are used to trigger state updates across components and was wondering if there are any scenarios where the approach described above wouldn't work and one has to use Subjects instead.

A: I often find that devs are not taking advantage of the binding and change detection available in Angular and basically circumventing it by using Subjects when they don't really need to.
For example, I have a complete Subject/Behavior subject example here: https://github.com/DeborahK/MovieHunter-communication in the MH-Take3 folder.
I then have the exact same functionality using simple properties in the MH-Take4 folder with no Subject/BehaviorSubject and quite a bit less code.
The one thing I would recommend, however, is to wrap your service property into a component property so that your template does not need to know about your service. This is not required, but provides good encapsulation.
For example:
get showImage(): boolean {
    return this.movieParameterService.displayPosters;
}
set showImage(value: boolean) {
    this.movieParameterService.displayPosters = value;
}

I have a "parameter" service that retains the parameters for one of my views. In this case, it is retaining whether the user has turned the display of images on or off. I expose the service parameter using a getter and setter in the component. That way the template binds to the component and does not need to know about the service.
In addition to the basic benefits of encapsulation, this also makes it easier to use editor features such as "Find all references" as it will find the components that use the service. It won't find any if the only reference is in strings in the template.


text:
Q: Starting text at newline after title of subsection I am typing my document in amsart class.
I created a subsection with small title, and then wrote the paragraph of the subsection:
 \subsection*{Examples}
 Consider a group of order 8.....

In the output, it shows title of subsection, and immediately after that, the paragraph starts. Then I inserted \vskip1mm:
\subsection*{Examples}
\vskip1mm
Consider a group of order 8.....

But there was no effect of the command \vskip1mm.
Question: How can we leave the space between title of section and next paragraph?

A: It's a precise choice of the class (which I agree with, by the way).
You can change one of the parameters in the definition of \subsection:
\documentclass{amsart}
\usepackage{lipsum} % just for the example

\makeatletter
\def\subsection{\@startsection{subsection}{2}%
  \z@{.5\linespacing\@plus.7\linespacing}{.3\linespacing}%
  {\normalfont\bfseries}}
\makeatother

\begin{document}

\section{A section title}

\lipsum[2]

\subsection{A subsection title}

\lipsum[3]

\end{document}

A: You could also do this I think.
\documentclass{amsart}
\begin{document}
\subsection*{Examples}~\par
\vskip1mm
Consider a group of order 8.....
\end{document}


text:
Q: javascript Instagram login Access-Control-Allow-Origin Error I follow the step for client login on Instagram, I configured my app on instagram client manager
My webapp follows this steps:

*

*I change url in https://api.instagram.com/oauth/authorize/?client_id=<MY_CLIEND_ID>&redirect_uri=http://localhost:8080/&response_type=code

*I authorize my webapp

*The url become http://localhost:8080/?code=<INSTAGRAM_ACCESS_TOKEN>

*I call ( Ajax GET request ) https://api.instagram.com/v1/tags/nofilter/media/recent?access_token=<INSTAGRAM_ACCESS_TOKEN>

But i get this error:
Failed to load https://api.instagram.com/v1/tags/nofilter/media/recent?access_token=INSTAGRAM_ACCESS_TOKEN : Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

A: Try calling the same Ajax using CORSA API, prefix "https://cors-anywhere.herokuapp.com/" + URL, adding CORSA should bypass CORS easily. :)


text:
Q: Apollo Server Azure Functions - Change Sandbox Endpoint I'm using Apollo Server with Azure Functions and as of a v3.8.0 there is a new embed option for the landing page plugin which allows the sandbox to be embedded into the server endpoint.
This is what my current config looks like
const server = new ApolloServer({
  schema,
  context: ({ context }) => context,
  plugins: [ApolloServerPluginLandingPageLocalDefault({
    embed: true
  })],
});

export default server.createHandler({
  cors: {
    origin: '*'
  },
});

I'd like to lock down the Function App in Azure by using Azure Active Directory and having any unauthenticated requests get rejected with 401: Unauthorized. The problem, however, is that would also deny access to the sandbox when trying to access it when deployed in Azure.
Is there a way to specify a separate sandbox endpoint that could allow unauthenticated requests? Then from the sandbox we could send in a Authorization: Bearer ... header to the actual graphql endpoint.


text:
Q: Hendrix missing admin django template I'm starting my first demo app with Hendrix, my firsts steps come from here (Django / Twisted (or hendrix) help to start).
Right now I create the project and only do this
1- Add sitetree extension
2- run migrate to create database
3- create super user
When I run "hx start" and enter to admin app, every thing works perfect, but when start the project using this script
from hendrix.deploy.base import HendrixDeploy
deploy = HendrixDeploy (options={'wsgi':'portal.wsgi.application'})

deploy.run()

The project start without error but the template for Admin app is missing, probably I forgot something, but I don't know what.
Thank you in advance for any help.
Best Regards


text:
Q: R DBI Sparklyr DBWritetable running with no result Coming from an MS-SQL environment into a HIVE environment that also has spark access. Right trying to use RStudio and R (and sometimes python using rPython) to replace some things I used to use T-SQL for as well as a whole host of things I never could do before.
In order for this to work I will need to be able to read and write back to the HIVE DB.
I have connected using spark and the R package sparklyr and can connect to our HIVE cluster using the R package DBI with the spark connection and pull data into R dataframes just fine:
sc <- spark_connect(master = "yarn-client", spark_home="/usr/hdp/current/spark-client", config = config)
result3 <- dbGetQuery(sc, "select * from sampledb.sampletable limit 100")

The above code works everytime. I can also create tables within the DB in the context of a quoted sql statement using dbGetQuery without problems so its not a write permissions issue.
However, when I try to write data from an R frame back to the HIVE cluster like so:
dbWriteTable(conn = sc, name = "sampledb.rsparktest3", value = result3)

It runs without error but the table does not show up and I cannot query it.
If I try to write the table again I get this error:
> dbWriteTable(conn = sc, name = "sampledb.rsparktest3", value = result3)
Error in .local(conn, name, value, ...) :
Table sampledb.rsparktest3 already exists

Any ideas what could be happening? Is there a better way I should be doing this besides DBI?
Thanks in advance for any help!
Below is the entire RStudio console log from when I run these statements:
> result3 <- dbGetQuery(sc, "select * from sampledb.sampletable limit 100")
> dbWriteTable(conn = sc, name = "sampledb.rsparktest3", value = result3)
> result3y <- dbGetQuery(sc, "select * from sampledb.rsparktest3 limit 2")
Error: org.apache.spark.sql.AnalysisException: Table not found: sampledb.rsparktest3; line 1 pos 35
at org.apache.spark.sql.catalyst.analysis.package$AnalysisErrorAt.failAnalysis(package.scala:42)
at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1.apply(CheckAnalysis.scala:54)
at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1.apply(CheckAnalysis.scala:50)
at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:121)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:120)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:120)
at scala.collection.immutable.List.foreach(List.scala:318)
at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:120)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:120)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:120)
at scala.collection.immutable.List.foreach(List.scala:318)
at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:120)
at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$class.checkAnalysis(CheckAnalysis.scala:50)
at org.apache.spark.sql.catalyst.analysis.Analyzer.checkAnalysis(Analyzer.scala:44)
at org.apache.spark.sql.execution.QueryExecution.assertAnalyzed(QueryExecution.scala:34)
at org.apache.spark.sql.DataFrame.<init>(DataFrame.scala:133)
at org.apache.spark.sql.DataFrame$.apply(DataFrame.scala:52)
at org.apache.spark.sql.SQLContext.sql(SQLContext.scala:817)
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:497)
at sparklyr.Invoke$.invoke(invoke.scala:102)
at sparklyr.StreamHandler$.handleMethodCall(stream.scala:97)
at sparklyr.StreamHandler$.read(stream.scala:62)
at sparklyr.BackendHandler.channelRead0(handler.scala:52)
at sparklyr.BackendHandler.channelRead0(handler.scala:14)
at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:244)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:846)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:111)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137)
at java.lang.Thread.run(Thread.java:745)
> dbWriteTable(conn = sc, name = "sampledb.rsparktest3", value = result3)
Error in .local(conn, name, value, ...) :
Table sampledb.rsparktest3 already exists

A: with a sparklyr connection use the  spark_write_table instead of dbWriteTable to write back to Hive

A: Writing Spark table to hive using Sparklyr:
Loading local dataframe to spark:
iris_spark_table <- copy_to(sc, iris, overwrite = TRUE)
sdf_copy_to(sc, iris_spark_table)

Creating a table in hive (append database name if necessary):
DBI::dbGetQuery(sc, "create table iris_hive as SELECT * FROM iris_spark_table")


text:
Q: Making log file from last directory name I have two directory paths source and destin.  Would like to construct a file name logfl with its path being that at destination destin, and its name being tho name of the last directory name.

*

*Example input data
source="/home/hagbard/01cuneus"
destin="/media/hc1"

*Desired result for logfl would be:
/media/hc1/01cuneus.log

Made the following attempt, but the filename is not being constructed properly:
# set log file from name of last directory of SOURCE
log="${source%/}"       # remove `/` if it occurs as last character
log="${source##*/}"     # gets last directory name from SOURCE
log="${destin%/}/$log"  # not absolutely necessary


text:
Q: Linkediting error when having a static unique_ptr Because I want my unique_ptr to be the same in all my objects, I decided to make it a static field.
After that an error has appeared:
https://pastebin.com/PPe6z0Ub
I don't really know how to fix it, I've tried searching for it online but I couldn't find anything really useful.
Code:
DBFeed.h
#pragma once
#include <vector>
#include <string>
#include <memory>

class DBFeed
{
public:
    void CalculatePosts();
    std::vector<std::string> GetPost();
    void ClearFeed();
private:
    static std::unique_ptr<std::vector<std::vector<std::string>>> m_postari;
    static int m_index;
};

DBFeed.cpp
#include "DBFeed.h"
#include "DBLink.h"

int DBFeed::m_index = 0;

void DBFeed::CalculatePosts()
{
    DBFeed::m_postari = std::make_unique<std::vector<std::vector<std::string>>>();
    pqxx::work worker(*DBLink::GetInstance());
    try
    {
        worker.conn().prepare("CountPostsFeed", "SELECT COUNT(id) FROM posts");
        worker.conn().prepare("ReadAllPostsFeed",
            "SELECT message FROM followers RIGHT JOIN posts ON followers.followed = posts.user_id WHERE followers.follower = 51 LIMIT 5 OFFSET" + std::to_string(m_index+=5)
        );
        pqxx::row countPostsResult = worker.exec_prepared1("CountPostsFeed");
        std::string number = countPostsResult.at("count").c_str();
        pqxx::result readAllPostsResult = worker.exec_prepared_n(std::stoi(number), "ReadAllPostsFeed");
        for (const auto& currentPost : readAllPostsResult)
        {
            std::string postID = currentPost.at("id").c_str();
            std::string message = currentPost.at("message").c_str();
            std::string dateCreated = currentPost.at("date_created").c_str();
            DBFeed::m_postari->push_back(std::vector<std::string>{postID, message, dateCreated});
        }
        worker.commit();
    }
    catch (const pqxx::unexpected_rows&)
    {
        throw std::runtime_error("Reading all of an users posts for feed failed");
    }
}

std::vector<std::string> DBFeed::GetPost()
{
    if (m_postari->empty())
    {
        CalculatePosts();
    }
    std::vector<std::string> deReturnat = m_postari->at(0);
    m_postari->erase(m_postari->begin());
    return deReturnat;
}

void DBFeed::ClearFeed()
{
    m_index = 0;
    m_postari.reset();
}

Why is this error happening and how can I fix it?
//Edit:
Fixed it by adding this by changing DBFeed.cpp's first lines as follows:
#include "DBFeed.h"
#include "DBLink.h"

int DBFeed::m_index = 0;
std::unique_ptr<std::vector<std::vector<std::string>>>
DBFeed::m_postari = std::make_unique<std::vector<std::vector<std::string>>>();

void DBFeed::CalculatePosts()
{
    pqxx::work worker(*DBLink::GetInstance());
....

But I'd still like to get an explanation on why it was happening and why is it fixed now.


text:
Q: Rails , cant view register user page I keep getting this error when I try and view my register user page

Firefox has detected that the server
  is redirecting the request for this
  address in a way that will never
  complete.

def register
    #User registration form
    @user = User.new(params[:user])
    if @user.save
      flash[:notice] = "Account Created Successfully"
      redirect_to(:action=>'menu')
    else
      flash[:notice] = "Please fill in all fields"
      redirect_to(:action=>'register')
    end
  end

Create User

  <%= form_for(:user, :url => {:action => 'register'}) do |f| %>

        First Name
        <%= f.text_field(:first_name) %>

        Last Name
        <%= f.text_field(:last_name) %>

        UserName
        <%= f.text_field(:user_name) %>

        Password
        <%= f.text_field(:password) %>

        Email
        <%= f.text_field(:email) %>

        Telephone
        <%= f.text_field(:telephone) %>

      <%= submit_tag("Register") %>

  <% end %>

A: Aren't you putting a redirect in your view method?
redirect_to(:action=>'register')

Are you distinguishing between the view method and the method that is actually fired when the user submits the form? Ex. for RestfulAuthentication the view is called "new", and the actual method that creates a user after the form is submitted is called "create".

A: You're redirecting you the same register action in the else.  Try render :action => '<action that contains the form>'

A: I think that FireFox message means that you have some kind of server redirect loop going on. For example, if you have a before filter in your application controller that says if the user in not logged in then send them to the register user page. But then on redirect to the register page, that user is still not logged in. Then Rails will try to redirect them again to that page. Thus forming a loop.


text:
Q: Перемещение указателя в потоке или неработающий seekg Имеется файл следующего содержания:

1 2 3 4 5

Мне необходимо относительно текущей позиции указателя переместиться на n-ое кол-во символов вперед.
Пробую сделать так:
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char* argv[])
{
   ifstream file("f1");
   int c;
   int n = 2;
   file.seekg(n,file.cur);
   c = file.get();
   cout << c << endl; // "49" - 1
   return 0;
}

На выходе должно получится значение "50" (т.е. код символа "2"), а выходит "49" (т.е. "1") - т.е. указатель не смещается. В чем косяк?
И что удивительно, то вот таким образом выходит "50" (т.е. двойка):
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char* argv[])
{
   ifstream file("f1");
   int c;
   int n = 2;
   file.seekg(n);
   c = file.get();
   cout << c << endl; // "50" - 2
   return 0;
}

A: #include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char* argv[])
{
   ifstream file("f1", file.binary); // бинарный режим решил проблему
   int c;
   int n = 2;
   file.seekg(n,file.cur);
   c = file.get();
   cout << c << endl;
   return 0;
}


text:
Q: Truouble implementing two smooth scrolling effects I am making a webpage that is continuous scrolling. However I am unable to make it scroll smoothly
My html code is:

        MAPPLAS

Inicio

Portfolio

Equipo

Blog

Contacto

My function is as follows:
((function() {
        $('ul.nav a').bind('click',function(event){
            var $anchor = $(this);

            $('html, body').stop().animate({
                scrollTop: $($anchor.attr('href')).offset().top
            }, 1500);
            event.preventDefault();
        });
    });
})();

I think there is a problem because I have another function which creates a buttom back-to-top, that function is as follows:
 ((function() {

        $('').appendTo($('body'));

        $(window).scroll(function() {

            if($(this).scrollTop() != 0) {
                $('#back-to-top').fadeIn();
            } else {
                $('#back-to-top').fadeOut();
            }

        });

        $('#back-to-top').click(function() {
            $('body,html').animate({scrollTop:0},600);
        });

})();

The thing is that one is working smoothly ( the back to top ) but the other is not. I am not an expert on js and I have tried including completely separated js scripts but nothing solves the problem.
Anyone has an idea why is not working??Thank u!

A: <!DOCTYPE HTML>

    <meta charset="UTF-8">
    <title>Smooth Scrolling</title>

    HTML
    JavaScript
    jQuery
    PHP
    CSS

HTML

            put your text about html here

JavaScript

            put your javascript details here.

jQuery

            Put your details about javascript here

PHP

            put your details about php here

CSS

put your details


text:
Q: Simulating random walkers which can not collide into each other in Matlab I have written a code to simulate the motion of circular particles in a 2d box. Whenever they move out of the box, I put them inside the box and near the wall. I want to add the diameter (2R) of particles in the code, which means when the distance between the center of two circles become less than 2R, they separate along the line connecting their centers so that the distance between the centers of the circles becomes equal to 2R.
Could anyone suggest a code to perevent the overlapping of particles?
This is my code in which overlap is not considered:
clear all
close all
l = 224; nn = 800; %number of particles
time = 1000; dd = 1;
x= l*rand(1,nn);
y= l*rand(1,nn);

for t = 1:time;
x= x + rand(1,nn)-0.5* ones(1,nn);
y=y+rand(1,nn)-0.5* ones (1,nn);
index = (x < 0); x(index) = abs(normrnd(0,1,1,nnz(index)));
index = (y < 0); y(index) = abs(normrnd(0,1,1,nnz(index)));
index = (x > l); x(index) = l-abs(normrnd(0,1,1,nnz(index)));
index = (y > l); y(index) = l-abs(normrnd(0,1,1,nnz(index)));
end

A: Here is some commented code which does what you want. Notably:

*

*psize is some defined particle size for interaction.

*point-to-point distances found using pdist2.

*points that are too close are moved away from each other by some amount (dp times their current distances, if dp=1/2 then their x and y distances double) until there are no clashes.

See comments for details.
clear; close all;
l = 224; nn = 800; % number of particles
time = 100;
x = l*rand(1,nn); y = l*rand(1,nn);
psize = 2;         % Particle size for interaction
dp = 0.1;

figure; hold on; axis([0 l 0 l]);
for t = 1:time;
    % Random movement
    movement = 2*rand(2,nn)-1;
    x = x + movement(1,:);
    y = y + movement(2,:);
    index = (x < 0); x(index) = abs(normrnd(0,1,1,nnz(index)));
    index = (y < 0); y(index) = abs(normrnd(0,1,1,nnz(index)));
    index = (x > l); x(index) = l-abs(normrnd(0,1,1,nnz(index)));
    index = (y > l); y(index) = l-abs(normrnd(0,1,1,nnz(index)));

    % Particle interaction. Loop until there are no clashes. For
    % robustness, some max iteration counter should be added!
    numclash = 1;
    while numclash > 0
        dists = pdist2([x;y]', [x;y]');   % Distances between all particles
        dists(dists < psize) = NaN;       % Those too close are assigned NaN
        tooclose = isnan(tril(dists,-1)); % All NaNs identified by logical
        [clash1,clash2] = find(tooclose); % Get particles which are clashing
        numclash = numel(clash1);         % Get number of clashes
        % All points where there was a clash, move away from each other
        x(clash1) = x(clash1) + (x(clash1)-x(clash2))*dp;
        x(clash2) = x(clash2) - (x(clash1)-x(clash2))*dp;
        y(clash1) = y(clash1) + (y(clash1)-y(clash2))*dp;
        y(clash2) = y(clash2) - (y(clash1)-y(clash2))*dp;
    end

    % Plot to visualise results. Colour fade from dark to bright green over time
    scatter(x,y,'.','markeredgecolor',[0.1,t/time,0.4]);
    drawnow;
end
hold off

Result:

Edit:
For a clearer diagram, you could initialise some colour matrix C = rand(nn,3); and plot using
scatter(x,y,[],C*(t/time),'.'); % the (t/time) factor makes it fade from dark to light

This would give each particle a different colour, which also fade from dark to light, rather than just fading from dark to light as before. The result would be something like this:


text:
Q: An Odd Tag Organization Script So!
I am working in PHP and have a huge list of taxonomy/tags, say around 100,000.
A similar list of tags can be can be found in the wealth of tags listed under products at Zazzle.com.
I am attempting to programmatically organize this list into a tiered menu of sorts based on the relationship between words, similar strings, and specificity.
I have toyed around with the levenshtein function, similar_text, searching for sub_str(ings), using the Princeton WordNet database, etc. and just can't crack this nut.  Essentially, I am trying to build an Ontology out of this database that goes from very general to very specific in tiers.  It doesn't have to be perfect, but I have run out of simple keyphrases to search for and ideas of how to go about doing this in a programmatic way and yet still having some semblance of order.
For instance:
If I use sub_str, I might end up with Dog->Dogma,Dogra, etc.
If I use levenshtein or similar text, I might end up Bog, Log, Cog, and Dog all very closely related.
This database, or taxonomy - if you will, is also conistently changing and thus atleast part of the analysis has to be done on the fly.  The good news is only one level of the result needs to be available.  For instance, the near results of a query such as Dog might be small dog, large dog, red dog, blue dog, canine, etc.
I know this is a terrible question, but does anyone have a ray-of-light of at least what steps i should take, any useful functions I could use, queries to research, methodologies, etc?
Thank you for your time.

So far, I have two suggestions for programmetically organizing tags into an ontology.

*

*Find co-occurences of tags to organize them into groups.  I believe the idea being that if tags occur together they are probably related.

*Use algorithmic stemming to reduce multiple forms/derivations/roots of words to a stem.  This should reduce the quantity of tags the script needs to sift through.... in addition to possibly identifying similar tags based on the root stem.

A: If you have whole sentences or at least more than just single words available, you might want to have a look into Latent semantic analysis
Don't be scared by the math, once you got the basic idea behind it, it's fairly simple:

*

*create a (high-dimensional) term-document matrix of your data

*essential step: transform your huge sparse matrix into a lower dimension (Singular value decomposition)

*every [collection of tags/terms] can then be specified by an vector in your lower dimension model

*the (cosine) similarity between those two vectors is a good measurement for the similiarity of your tags, even they might not be the same stem (you may find dog and barking related)

*a good input for the term-document matrix is vital

An excellent read on this [and other IR topics] (Free eBook): Introduction to Information Retrieval
Have a look at the book, it's very well written and helped me a lot with my IR thesis.


text:
Q: Visual studio ignores AdditionalLibraryDirectories in props file I'm trying to build the application that uses libzip.
I build the libzip library first and got zip.lib and zip.dll.
Now on the linking stage I get an error

Error LNK1104 cannot open file 'zip.lib'

It seems that AdditionalLibraryDirectories is ignores whereas AdditionalIncludeDirectories works well (all zip-related headers are found)
settings.props:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ImportGroup Label="PropertySheets" />
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup />
  <ItemDefinitionGroup>
    <ClCompile>
      <AdditionalIncludeDirectories>$(SolutionDir)\libzip\lib;$(SolutionDir)\libzip\build;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
    </ClCompile>
    <Link>
      <AdditionalLibraryDirectories>$(SolutionDir)\libzip\build\lib\Debug</AdditionalLibraryDirectories>
      <AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;zip.lib;%(AdditionalDependencies)</AdditionalDependencies>
    </Link>
  </ItemDefinitionGroup>
  <ItemGroup />
</Project>

If I add "$(SolutionDir)\libzip\build\lib\Debug\" to Additional library directories of the project, everything works! So the zip library is not corrupted.


text:
Q: Find a compund Poisson variable with characterist function as centered compound Poisson I know that if $(X_j , j \geq 1)$ is a sequence of i.i.d. process with $\sigma$ being the probability distribution of $X_j's$ and $N \sim \text{Poisson}(\lambda)$ independent of the $X_j's$, then the compund Poisson random variable
$$Z = \sum_j^N X_j \sim CP(\lambda, \sigma)$$
is such that its characteristic function is given by:
$$\varphi_X(t)= e^{\lambda(\,\phi_X(t)- 1 \,)}, \varphi_X(t) = \int_{\mathbb{R}}e^{itx}d\sigma(x)$$
Moreover, for the centered compound Poisson variable $\tilde{Z} = Z - \mathbb{E}Z = Z - \lambda \mathbb{E}X$, its ch. f. is given by
\begin{equation}\label{eq1}
\varphi_{\tilde{Z}}(t)= e^{\lambda\phi(t)},\quad \phi(t)= \int_{\mathbb{R}}\Big(e^itx - 1 - itx\Big)d \sigma(x)\tag{1}
\end{equation}
But I would like to know if there is any $\bar{X}_j$ so that the characteristic function of
$$\bar{Z}= \sum_{j=1}^N \bar{X}_j$$
is given, directly (without centering), by equation (\ref{eq1}). I tried putting $\bar{X}_j = X_j - \mathbb{E}X_j$, but it didn't work.
some help!


text:
Q: How to write or append to text file using sql? i need to call sqlcmd from stored procedure to export table to text file?

A: by the following way you can do this
exec master..xp_cmdshell 'echo pranay test application > d:\file.txt'

more about this : http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/how-to-copy-data-append-data-into-files-


text:
Q: Javascript calculate date week by week Hy guys,
i have write this javascript code for calculate date for any day of week progressively.
But i ahve error when the code must be calculate the end of month: example after 31/07/2'15 the code generate 32/07/2015 instead 01/08/2015.
This is my code:
var application = this;
        var currentDate = new Date();
        var stringDate1 = currentDate.getUTCDate() + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
        var stringDate2 = (currentDate.getUTCDate()+1) + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
        var stringDate3 = (currentDate.getUTCDate() + 2) + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
        var stringDate4 = (currentDate.getUTCDate() + 3) + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
        var stringDate5 = (currentDate.getUTCDate() + 4) + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
        var stringDate6 = (currentDate.getUTCDate() + 5) + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
        var stringDate7 = (currentDate.getUTCDate() + 6) + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();

where my code is wrong?
Any help please?
BR

A: Just add the hours*minutes*seconds*milliseconds to today's date, and you get tomorrow's date, and so on.
var tomorrowsDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);

A: To calculate the date for one day ahead you can use Date.prototype.setDate()
So to calculate all dates from today and week ahead, you can do something like this:
var currentDate = new Date();
var stringDate = [];

for (var i = 0; i < 7; ++i) {
    currentDate.setDate(currentDate.getDate() + 1);
    stringDate[i] = currentDate.getUTCDate() + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
}

console.log(stringDate);

// 0: "28/7/2015"
// 1: "29/7/2015"
// 2: "30/7/2015"
// 3: "31/7/2015"
// 4: "1/8/2015"
// 5: "2/8/2015"
// 6: "3/8/2015"