问:
Custom SQL query in JPA repositories
For the following query:

```<code>@Query("SELECT fd FROM DPPFile fd WHERE fd.ID= ':ID'")
List<DPPFile> findByID(@Param("ID")String ID/);
</code>```

I'm getting the following weird exception:

```<code>Caused by: java.lang.IllegalArgumentException: Parameter with that position [1] did not exist
    at org.hibernate.jpa.spi.BaseQueryImpl.findParameterRegistration(BaseQueryImpl.java:502)
    at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:692)
    at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:181)
    at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:32)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:140)
    at org.springframework.data.jpa.repository.query.StringQueryParameterBinder.bind(StringQueryParameterBinder.java:61)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:100)
    at org.springframework.data.jpa.repository.query.SpelExpressionStringQueryParameterBinder.bind(SpelExpressionStringQueryParameterBinder.java:69)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:160)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:151)
    at org.springframework.data.jpa.repository.query.AbstractStringBasedJpaQuery.doCreateQuery(AbstractStringBasedJpaQuery.java:81)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:190)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:121)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
</code>```

I'd expect this exception if I was using ?1 instead of the named parameter approach. Using the ?1 fails as well so I'm not sure what's going wrong here.
The DPPFile class has a member called ID as well as getter/setter.

(The reason I'm not using the default "findByID" with no query on top of it function is because I want to extend the query with additional parameters)

答:
As an alternative solution, you can skip the whole @Query annotation by using spring-data findOne assuming ID is your unique identifier in the entity. Otherwise, you can rely on spring-data to generate the query from the name of the method. Use something like this:

```<code>@Entity
public class DPPFile {

  @Id
  private Integer identifier;

  private Integer ID;
}

public interface DPPFileRepository extends Repository< DPPFile, Integer> {

   List<DPPFile> findByID(String ID);
}
</code>```

see https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation

Title: Custom SQL query in JPA repositories

Body:
For the following query:

@Query("SELECT fd FROM DPPFile fd WHERE fd.ID= ':ID'")
List<DPPFile> findByID(@Param("ID")String ID/);

I'm getting the following weird exception:

Caused by: java.lang.IllegalArgumentException: Parameter with that position [1] did not exist
    at org.hibernate.jpa.spi.BaseQueryImpl.findParameterRegistration(BaseQueryImpl.java:502)
    at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:692)
    at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:181)
    at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:32)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:140)
    at org.springframework.data.jpa.repository.query.StringQueryParameterBinder.bind(StringQueryParameterBinder.java:61)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:100)
    at org.springframework.data.jpa.repository.query.SpelExpressionStringQueryParameterBinder.bind(SpelExpressionStringQueryParameterBinder.java:69)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:160)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:151)
    at org.springframework.data.jpa.repository.query.AbstractStringBasedJpaQuery.doCreateQuery(AbstractStringBasedJpaQuery.java:81)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:190)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:121)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)

I'd expect this exception if I was using ?1 instead of the named parameter approach. Using the ?1 fails as well so I'm not sure what's going wrong here.
The DPPFile class has a member called ID as well as getter/setter.

(The reason I'm not using the default "findByID" with no query on top of it function is because I want to extend the query with additional parameters)

Body:
As an alternative solution, you can skip the whole @Query annotation by using spring-data findOne assuming ID is your unique identifier in the entity. Otherwise, you can rely on spring-data to generate the query from the name of the method. Use something like this:

@Entity
public class DPPFile {

  @Id
  private Integer identifier;

  private Integer ID;
}

public interface DPPFileRepository extends Repository< DPPFile, Integer> {

   List<DPPFile> findByID(String ID);
}

see https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation


来源: stackexchange

问:
what is the best way to synchronize container access between multiple threads in real-time application
I have std::list<Info> infoList in my application that is shared between two threads. These 2 threads are accessing this list as follows:

Thread 1: uses push_back(), pop_front() or clear() on the list (Depending on the situation)
Thread 2: uses an iterator to iterate through the items in the list and do some actions.

Thread 2 is iterating the list like the following:

```<code>for(std::list<Info>::iterator i = infoList.begin(); i != infoList.end(); ++i)
{
  DoAction(i);
}
</code>```

The code is compiled using GCC 4.4.2.

Sometimes ++i causes a segfault and crashes the application. The error is caused in std_list.h line 143 at the following line:

```<code>_M_node = _M_node->_M_next;
</code>```

I guess this is a racing condition. The list might have changed or even cleared by thread 1 while thread 2 was iterating it.

I used Mutex to synchronize access to this list and all went ok during my initial test. But the system just freezes under stress test making this solution totally unacceptable. This application is a real-time application and i need to find a solution so both threads can run as fast as possible without hurting the total applications throughput.

My question is this:
Thread 1 and Thread 2 need to execute as fast as possible since this is a real-time application. what can i do to prevent this problem and still maintain the application performance? Are there any lock-free algorithms available for such a problem?

Its ok if i miss some newly added Info objects in thread 2's iteration but what can i do to prevent the iterator from becoming a dangling pointer?

Thanks

答:
If you're using C++0x you could internally synchronize list iteration this way:

Assuming the class has a templated list named objects_, and a boost::mutex named mutex_

The toAll method is a member method of the list wrapper

```<code> void toAll(std::function<void (T*)> lambda)
 {
 boost::mutex::scoped_lock(this->mutex_);
 for(auto it = this->objects_.begin(); it != this->objects_.end(); it++)
 {
      T* object = it->second;
      if(object != nullptr)
      {
                lambda(object);
           }
      }
 }
</code>```

Calling:

```<code>synchronizedList1->toAll(
      [&](T* object)->void // Or the class that your list holds
      {
           for(auto it = this->knownEntities->begin(); it != this->knownEntities->end(); it++)
           {
                // Do something
           }
      }
 );
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have std::list<Info> infoList in my application that is shared between two threads. These 2 threads are accessing this list as follows:

Thread 1: uses push_back(), pop_front() or clear() on the list (Depending on the situation)
Thread 2: uses an iterator to iterate through the items in the list and do some actions.

Thread 2 is iterating the list like the following:

for(std::list<Info>::iterator i = infoList.begin(); i != infoList.end(); ++i)
{
  DoAction(i);
}

The code is compiled using GCC 4.4.2.

Sometimes ++i causes a segfault and crashes the application. The error is caused in std_list.h line 143 at the following line:

_M_node = _M_node->_M_next;

I guess this is a racing condition. The list might have changed or even cleared by thread 1 while thread 2 was iterating it.

I used Mutex to synchronize access to this list and all went ok during my initial test. But the system just freezes under stress test making this solution totally unacceptable. This application is a real-time application and i need to find a solution so both threads can run as fast as possible without hurting the total applications throughput.

My question is this:
Thread 1 and Thread 2 need to execute as fast as possible since this is a real-time application. what can i do to prevent this problem and still maintain the application performance? Are there any lock-free algorithms available for such a problem?

Its ok if i miss some newly added Info objects in thread 2's iteration but what can i do to prevent the iterator from becoming a dangling pointer?

Thanks

Body:
If you're using C++0x you could internally synchronize list iteration this way:

Assuming the class has a templated list named objects_, and a boost::mutex named mutex_

The toAll method is a member method of the list wrapper

 void toAll(std::function<void (T*)> lambda)
 {
 boost::mutex::scoped_lock(this->mutex_);
 for(auto it = this->objects_.begin(); it != this->objects_.end(); it++)
 {
      T* object = it->second;
      if(object != nullptr)
      {
                lambda(object);
           }
      }
 }

Calling:

synchronizedList1->toAll(
      [&](T* object)->void // Or the class that your list holds
      {
           for(auto it = this->knownEntities->begin(); it != this->knownEntities->end(); it++)
           {
                // Do something
           }
      }
 );


问:
sql error when adding joins options and conditions
I made this query in cakePhp to get count with conditions and inner joins but I found error like this :

SQL Error: 1064: Syntax Error near 'inscriptions_reducs registered INNER WHERE Registration.seance_id = 5402 AND` Insc' in line 1

this is my query:

$countInscri = ClassRegistry::init('Inscription')->find('count',array(
'joins'=>array(
            'table'=>'inscriptions_reducs',
            'alias'=>'insc',
            'type'=>'INNER',
            'conditions'=>array('insc.inscription_id = Inscription.id')
            ),

'conditions'=>array('Inscription.seance_id'=>$value['Seance']['seance_id'],
                    'Inscription.is_confirmed is not null',
                    'Inscription.canceled is null',

                    'NOT'=>array('insc.reduction_id'=>array(1,2,22))
                    )
));
```

答:
Join param needs to be an array of arrays:</p>

```<code>'joins' => array(
    array(
        'table'=>'inscriptions_reducs',
        'alias'=>'insc',
        'type'=>'INNER',
        'conditions'=>array('insc.inscription_id = Inscription.id')
        ),
    )
)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Join param needs to be an array of arrays:

'joins' => array(
    array(
        'table'=>'inscriptions_reducs',
        'alias'=>'insc',
        'type'=>'INNER',
        'conditions'=>array('insc.inscription_id = Inscription.id')
        ),
    )
)


问:
SQL Procedure - use aggregate in subquery
I have:

Distributors in Disributor table. (DisributorID = PK)

Regions in Region Table. (DisributorID = FK)

I want to store a procedure that accepts a number from user as a @scale which is number of Regions each distributor has. procedure should go and check which Distributors has reached that @scale number and add 10 dollars to their salary!

I have this code, but it feels weird/Stupid/not working! I think the way i look at the problem is wrong.

```<code>    create procedure RewardDistributors (@scale int = null)
    as
    if @scale is null
    begin
    raiserror ('Please provide A value!', 16, 1)
    end
else
    begin
    if not exists
    (select COUNT(RegionID) from Region having COUNT(RegionID) >= @scale)
    begin
    raiserror ('No one reached this number yet', 16, 1)
    end

    else
    begin
        update Distributor
        set wage = (wage + 10)
        where DistributorID =
        (select DistributorID, COUNT(*) from Region group by DistributorID having COUNT(*) >= @scale)
    end
end
</code>```

return

答:
A simplification of your proc:

```<code>CREATE PROCEDURE RewardDistributors
    @Scale INT
AS

UPDATE Distributor
SET wage = wage + 10
WHERE DistributorID IN (
    SELECT DistributorID
    FROM Region
    GROUP BY DistributorID
    HAVING COUNT(*) >= @Scale
)

PRINT CAST(@@ROWCOUNT AS VARCHAR) + ' rows updated.'
</code>```

Don't allow the parameter to be NULL if you're just going to check if its NULL. You also don't need to perform any tests - just do the update and then print how many rows were updated. You can modify that if you really want distinct output messages.

Body:
I have:

Distributors in Disributor table. (DisributorID = PK)

Regions in Region Table. (DisributorID = FK)

I want to store a procedure that accepts a number from user as a @scale which is number of Regions each distributor has. procedure should go and check which Distributors has reached that @scale number and add 10 dollars to their salary!

I have this code, but it feels weird/Stupid/not working! I think the way i look at the problem is wrong.

    create procedure RewardDistributors (@scale int = null)
    as
    if @scale is null
    begin
    raiserror ('Please provide A value!', 16, 1)
    end
else
    begin
    if not exists
    (select COUNT(RegionID) from Region having COUNT(RegionID) >= @scale)
    begin
    raiserror ('No one reached this number yet', 16, 1)
    end

    else
    begin
        update Distributor
        set wage = (wage + 10)
        where DistributorID =
        (select DistributorID, COUNT(*) from Region group by DistributorID having COUNT(*) >= @scale)
    end
end

return

Body:
A simplification of your proc:

CREATE PROCEDURE RewardDistributors
    @Scale INT
AS

UPDATE Distributor
SET wage = wage + 10
WHERE DistributorID IN (
    SELECT DistributorID
    FROM Region
    GROUP BY DistributorID
    HAVING COUNT(*) >= @Scale
)

PRINT CAST(@@ROWCOUNT AS VARCHAR) + ' rows updated.'

Don't allow the parameter to be NULL if you're just going to check if its NULL. You also don't need to perform any tests - just do the update and then print how many rows were updated. You can modify that if you really want distinct output messages.


问:
Main class instance for all subclasses
I got three classes: Bank, account and Coin. I want the class Bank to have a default coin variable , which I pass on to its constructor. So I extended account to Bank, this would mean that I can access the default coin variable through the method getmainCoin() via the account class. For some reason I'm getting this error when trying that:

Error:(12, 32) java: constructor bank in class com.company.bank cannot be applied to given types;
    required: com.company.Coin
    found: no arguments
    reason: actual and formal argument lists differ in length

```<code>// Instantiations
Coin dollars = new Coin("Dollar", "$");;
bank SomeBank = new bank(dollars);
Person john = new Person("John Doe", 20, dollars, new account(9058));
System.out.println(john.checkbalance());

public class bank {
  public String name;
  private int coinsheld;
  private Coin maincoin;

  public bank(Coin maincoin){
      this.maincoin = maincoin;
  }

  public Coin getmainCoin(){
      return this.maincoin;
  }

}

public class account extends bank {
  private int balance;
  private static int accounts;
  private int accnumber;
  private Coin coin;

  public account(int balance){
      this.balance = balance;
      this.accounts += 1;
      this.accnumber = accounts;
      this.coin = getmainCoin();
  }
}

public class Coin {
  public static int total;
  private String name;
  private String sign;
  private int id;

  public Coin(String name, String sign){
      this.name = name;
      this.sign = sign;
      this.id = total + 1;
  }

  public int getID(){
      return this.id;
  }
}
</code>```

答:
Whenever you extend a class, the sub-class automatically calls super(), in its constructor. super() basically calls the super-class' constructor. Now, your super-class bank doesn't have a argument-less constructor, because you overrode the default one. To fix, do add a constructor like this:-

```<code>public bank() {

}
</code>```

Or you could explicitly call super with a Coin object.

```<code>public account(int balance){
  super(someCoinReference);
  ..//rest of code
}
</code>```

However, this is probably not what you want.

Title: Main class instance for all subclasses

Body:
I got three classes: Bank, account and Coin. I want the class Bank to have a default coin variable , which I pass on to its constructor. So I extended account to Bank, this would mean that I can access the default coin variable through the method getmainCoin() via the account class. For some reason I'm getting this error when trying that:

Error:(12, 32) java: constructor bank in class com.company.bank cannot be applied to given types;
    required: com.company.Coin
    found: no arguments
    reason: actual and formal argument lists differ in length

// Instantiations
Coin dollars = new Coin("Dollar", "$");;
bank SomeBank = new bank(dollars);
Person john = new Person("John Doe", 20, dollars, new account(9058));
System.out.println(john.checkbalance());

public class bank {
  public String name;
  private int coinsheld;
  private Coin maincoin;

  public bank(Coin maincoin){
      this.maincoin = maincoin;
  }

  public Coin getmainCoin(){
      return this.maincoin;
  }

}

public class account extends bank {
  private int balance;
  private static int accounts;
  private int accnumber;
  private Coin coin;

  public account(int balance){
      this.balance = balance;
      this.accounts += 1;
      this.accnumber = accounts;
      this.coin = getmainCoin();
  }
}

public class Coin {
  public static int total;
  private String name;
  private String sign;
  private int id;

  public Coin(String name, String sign){
      this.name = name;
      this.sign = sign;
      this.id = total + 1;
  }

  public int getID(){
      return this.id;
  }
}

Body:
Whenever you extend a class, the sub-class automatically calls super(), in its constructor. super() basically calls the super-class' constructor. Now, your super-class bank doesn't have a argument-less constructor, because you overrode the default one. To fix, do add a constructor like this:-

public bank() {

}

Or you could explicitly call super with a Coin object.

public account(int balance){
  super(someCoinReference);
  ..//rest of code
}

However, this is probably not what you want.


问:
Android - Changing button height it is stretched
I have a button with an image. The height of the image should be the 20% of the height of the device. So I set the height of the image programmatically.

The problem is that, if i do it, the image becomes stretched. I put the settings that it has to be scaled centerinside and I have tried also with other elements, as imagebutton or imageview, but I had always the same problem.

How can I do?

UPDATE
This is my xml code:

```<code> <LinearLayout
    android:id="@+id/letterLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"
    android:layout_marginBottom="10dp"
    android:scaleType="centerCrop"
    android:gravity="center"
    android:layout_gravity="center"
    android:onClick="onClick">
    <Button
        android:id="@+id/letterButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:fontFamily="sans-serif"
        android:textStyle="bold"
        android:padding="30dp"
        android:textColor="#000000"
        android:background="#00000000"
        android:clickable="false"/>
</LinearLayout>
</code>```

And my Java code where i set the height:

```<code>        letterLayout.getLayoutParams().height = (int) (hQdr);
        letterTest.getLayoutParams().height = (int) (hQdr);
        //letterTest.getLayoutParams().width = (int) (wQdr);
</code>```

答: Did you tried with the parameter android:scaleType="centerCrop"? This Crops your Image to enter in the layout

ContentLicense: CC BY-SA 4.0

Body:
I have a button with an image. The height of the image should be the 20% of the height of the device. So I set the height of the image programmatically.

The problem is that, if i do it, the image becomes stretched. I put the settings that it has to be scaled centerinside and I have tried also with other elements, as imagebutton or imageview, but I had always the same problem.

How can I do?

UPDATE
This is my xml code:

 <LinearLayout
    android:id="@+id/letterLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"
    android:layout_marginBottom="10dp"
    android:scaleType="centerCrop"
    android:gravity="center"
    android:layout_gravity="center"
    android:onClick="onClick">
    <Button
        android:id="@+id/letterButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:fontFamily="sans-serif"
        android:textStyle="bold"
        android:padding="30dp"
        android:textColor="#000000"
        android:background="#00000000"
        android:clickable="false"/>
</LinearLayout>

And my Java code where i set the height:

        letterLayout.getLayoutParams().height = (int) (hQdr);
        letterTest.getLayoutParams().height = (int) (hQdr);
        //letterTest.getLayoutParams().width = (int) (wQdr);


问:
SVN checking out new files from repo that others have added
If I have checked out a SVN repo and work on it locally all is fine.  If my colleague also checks out the repo and they can also work on it fine.

When my colleague creates a new file, adds it to the repo and commits it.  Running update does not automatically download the additional file.

Deleting the local repo and checking it out a second gets the additional file.

What command do I need to execute to ensure that when running update it does get any additional files?

I am using the Tortoise shell and subversion SVN.   The end application is an electronics cad package, Altium, so we normally only use checkout, commit and update commands.

答: That sounds like some setting going horribly wrong on your SVN server, update should most definitely add / delete files in your local copy based on what's committed to the server!</p>


问:
convert numbers to 26base with only letters
I need to convert number in "Alphabetic" Counting System, similar to excel spreadsheets:

convert(1) == "A";

  convert(2) == "B";

  ...

  convert(26) == "Z";

  convert(27) == "AA";

  ...

  convert(52) == "AZ";

  convert(53) == "BA";

  ...

  convert(702 ) == "ZZ";

  convert(703 ) == "AAA";

this is my code:

```<code>function convert($n){
    if ($n> 26) {
        $tmp = floor($n / 26);
        $n= $n % 26;
        $result = chr(($tmp - 1) + 65) . chr(($n - 1) + 65);
    } else {
        $result = chr(($n- 1) + 65);
    }
    return $result;
}
</code>```

but the output is a bit off:

@, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,

  AA, AB, AC, AD, AE, AF, AG, AH, AI, AJ, AK, AL, AM, AN, AO, AP, AQ, AR, AS, AT, AU, AV, AW, AX, AY,

  B@, BA

I tried to tweak the numbers but I can not make it right, any suggestion for a better algorithm ?

答:
Taking advantage of PHP's ability to increment strings as well as numbers:

```<code>function convert($number) {
    $result = 'A';
    for($i = 1; $i < $number; ++$i) {
        ++$result;
    }
    return $result;
}
</code>```

Demo

Body:
I need to convert number in "Alphabetic" Counting System, similar to excel spreadsheets:

convert(1) == "A";

  convert(2) == "B";

  ...

  convert(26) == "Z";

  convert(27) == "AA";

  ...

  convert(52) == "AZ";

  convert(53) == "BA";

  ...

  convert(702 ) == "ZZ";

  convert(703 ) == "AAA";

this is my code:

function convert($n){
    if ($n> 26) {
        $tmp = floor($n / 26);
        $n= $n % 26;
        $result = chr(($tmp - 1) + 65) . chr(($n - 1) + 65);
    } else {
        $result = chr(($n- 1) + 65);
    }
    return $result;
}

but the output is a bit off:

@, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,

  AA, AB, AC, AD, AE, AF, AG, AH, AI, AJ, AK, AL, AM, AN, AO, AP, AQ, AR, AS, AT, AU, AV, AW, AX, AY,

  B@, BA

I tried to tweak the numbers but I can not make it right, any suggestion for a better algorithm ?

Body:
Taking advantage of PHP's ability to increment strings as well as numbers:

function convert($number) {
    $result = 'A';
    for($i = 1; $i < $number; ++$i) {
        ++$result;
    }
    return $result;
}

Demo


问:
Element positioned higher because of flexbox
I have two identical divs and one of them is nested inside an extra
. In display, both of the squares sit besides to their peer paragraph, but the first square is higher compared to the second one to their respective paragraph. What effect of flexbox creates the difference?

p {
  margin-top: 1rem;
  line-height: 1.85rem;
}

.flexbox {
  display: flex;
}

.square {
  float: left;
  margin-top: 1rem;
  background-color: #cfc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flexbox">
  <div>
    <div id="first" class="square">A square</div>
    <p>A paragraph sits aside to the square.</p>
  </div>
</div>

<div>
  <div id="second" class="square">A square</div>
  <p>A paragraph sits aside to the square.</p>
</div></code>```

Without the line-height and margin-top, the square inside the flexbox is still higher, and I'd like to demolish that side-effect of flexbox.

答:
This appears to be an issue of margin collapsing.

From MDN:

Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing.

source: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

In your non-flexbox example the margin-top of the child div and the margin-top of the container div are collapsed into one margin. This is consistent with margin collapse behavior between parent and child in a block formatting context.

Note that div elements normally have a margin-top by default which is applied by the browser. Look for it in dev tools in user agent styles.

You can override the margin collapse behavior by adding a border or padding on the container:

.flexbox {
  display: flex;
}

#border {
  border: 1px dashed red;
}

#padding {
  padding: 5px;
}

.square {
  float: left;
  margin-top: 1rem;
  background-color: #cfc;
  border: 1px solid black;
}

p {
  margin-top: 1rem;
  line-height: 1.85rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flexbox">
  <div>
    <div id="first" class="square">A square</div>
    <p>A paragraph sits aside to the square.</p>
  </div>
</div>

<div id="border">
  <div id="second" class="square">A square</div>
  <p>A paragraph sits aside to the square.</p>
</div>

<div id="padding">
  <div id="second" class="square">A square</div>
  <p>A paragraph sits aside to the square.</p>
</div></code>```

In a flex formatting context...

...the flex container’s margins do not collapse with the margins of its contents.

source: https://www.w3.org/TR/css-flexbox-1/#flex-containers

Hence, there is no margin collapsing in flexbox.

Body:
I have two identical divs and one of them is nested inside an extra
. In display, both of the squares sit besides to their peer paragraph, but the first square is higher compared to the second one to their respective paragraph. What effect of flexbox creates the difference?

p {
  margin-top: 1rem;
  line-height: 1.85rem;
}

.flexbox {
  display: flex;
}

.square {
  float: left;
  margin-top: 1rem;
  background-color: #cfc;
}

A square

A paragraph sits aside to the square.

A square

A paragraph sits aside to the square.

Without the line-height and margin-top, the square inside the flexbox is still higher, and I'd like to demolish that side-effect of flexbox.

Body:
This appears to be an issue of margin collapsing.

From MDN:

Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing.

source: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

In your non-flexbox example the margin-top of the child div and the margin-top of the container div are collapsed into one margin. This is consistent with margin collapse behavior between parent and child in a block formatting context.

Note that div elements normally have a margin-top by default which is applied by the browser. Look for it in dev tools in user agent styles.

You can override the margin collapse behavior by adding a border or padding on the container:

.flexbox {
  display: flex;
}

#border {
  border: 1px dashed red;
}

#padding {
  padding: 5px;
}

.square {
  float: left;
  margin-top: 1rem;
  background-color: #cfc;
  border: 1px solid black;
}

p {
  margin-top: 1rem;
  line-height: 1.85rem;
}

<div class="flexbox">
  <div>
    <div id="first" class="square">A square</div>
    <p>A paragraph sits aside to the square.</p>
  </div>
</div>

<div id="border">
  <div id="second" class="square">A square</div>
  <p>A paragraph sits aside to the square.</p>
</div>

<div id="padding">
  <div id="second" class="square">A square</div>
  <p>A paragraph sits aside to the square.</p>
</div>

In a flex formatting context...

...the flex container’s margins do not collapse with the margins of its contents.

source: https://www.w3.org/TR/css-flexbox-1/#flex-containers

Hence, there is no margin collapsing in flexbox.


问:
Destination array is not long enough to copy all the items in the collection. Check array index and length
I have this code. It gives me an error :

Destination array is not long enough to copy all the items in the
  collection. Check array index and length.

I thought that it was because of using a dictionary, so I switched it to ConcurrentDictionary, but the error is still here.

```<code>private void SaverCallback()
{
    AddThread("Main Thread");
    const string path = "milestone";
    while (!stop)
    {
        ConcurrentDictionary<string, object> milestone = new ConcurrentDictionary<string, object>();
        milestone.TryAdd("Jobs", JobQueue.Queue.MainQueue);
        milestone.TryAdd("Locked Jobs", JobQueue.Queue.LockedQueue);

    again: try {
            using (FileStream writingStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
            {
                BinaryFormatter formater = new BinaryFormatter();
                formater.Serialize(writingStream, milestone);
                writingStream.Flush();
                Logger.Debug("Status saved");
            }
        }
        catch(Exception e)
        {
            Logger.Error($"Milestone exception: {e.Message}");
            goto again;
        }
        this.WaitTime(60000);
    }
    RemoveThread();
}
</code>```

UPD:

Destination array is not long enough to copy all the items in the
  collection. Check array index and length. and    at
  System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
  at System.Collections.Generic.Dictionary2.CopyTo(KeyValuePair2[]
  array, Int32 index)    at
  System.Collections.Generic.Dictionary`2.GetObjectData(SerializationInfo
  info, StreamingContext context)    at
  System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object
  obj, ISurrogateSelector surrogateSelector, StreamingContext context,
  SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter,
  ObjectWriter objectWriter, SerializationBinder binder)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo
  objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteArrayMember(WriteObjectInfo
  objectInfo, NameInfo arrayElemTypeNameInfo, Object data)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteArray(WriteObjectInfo
  objectInfo, NameInfo memberNameInfo, WriteObjectInfo memberObjectInfo)
  at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo
  objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object
  graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)

  at
  System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream
  serializationStream, Object graph, Header[] headers, Boolean fCheck)

  at AggregateRunner.Enteties.Saver.SaverCallback()

答:
As far as I can see, you're taking a snapshot for your queues once an hour, but the main problem with your code is that you're trying to serialize your queue (which is a ConcurrentQueue<T>, I guess) itself without any cloning or synchronization logic. Another problem with your code is a goto usage, which is not necessary at all here.

The exception you're facing is a ArgumentException and is a third possible exception of CopyTo method of the ConcurrentQueue<T>. It's happening during the serialization because of some thread added some messages to queue and now it doesn't fit in array serializer decided to use.

So, what you can do in such situation is either introduce some locking during access to the original queues (which you're decided to do), or create a clone for your queues and serialize that in a safe manner without blocking other threads.

You can do this with CopyTo method of ConcurrentQueue<T> by yourself, with creating array with length more than number of messages in queue, but the locking in general is more convenient way to clone the data. So your code should be like this:

```<code>private void SaverCallback()
{
    AddThread("Main Thread");
    const string path = "milestone";
    while (!stop)
    {
        try
        {
            lock (JobQueue.Queue.MainQueue)
            lock (JobQueue.Queue.LockedQueue)
            {
                using (var writingStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                {
                    var milestone = new ConcurrentDictionary<string, object>();
                    milestone.TryAdd("Jobs", JobQueue.Queue.MainQueue);
                    milestone.TryAdd("Locked Jobs", JobQueue.Queue.LockedQueue);

                    var formater = new BinaryFormatter();
                    formater.Serialize(writingStream, milestone);
                    writingStream.Flush();
                    Logger.Debug("Status saved");
                }
            }
            // this line cloud be in finally case too,
            // if you don't need to save a queue in case of some errors
            this.WaitTime(60000);
        }
        catch(Exception e)
        {
            // note that logger accepts whole exception information
            // instead of only it's message
            Logger.Error($"Milestone exception: {e}");
            continue;
        }
    }
    RemoveThread();
}
</code>```

Body:
I have this code. It gives me an error :

Destination array is not long enough to copy all the items in the
  collection. Check array index and length.

I thought that it was because of using a dictionary, so I switched it to ConcurrentDictionary, but the error is still here.

private void SaverCallback()
{
    AddThread("Main Thread");
    const string path = "milestone";
    while (!stop)
    {
        ConcurrentDictionary<string, object> milestone = new ConcurrentDictionary<string, object>();
        milestone.TryAdd("Jobs", JobQueue.Queue.MainQueue);
        milestone.TryAdd("Locked Jobs", JobQueue.Queue.LockedQueue);

    again: try {
            using (FileStream writingStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
            {
                BinaryFormatter formater = new BinaryFormatter();
                formater.Serialize(writingStream, milestone);
                writingStream.Flush();
                Logger.Debug("Status saved");
            }
        }
        catch(Exception e)
        {
            Logger.Error($"Milestone exception: {e.Message}");
            goto again;
        }
        this.WaitTime(60000);
    }
    RemoveThread();
}

UPD:

Destination array is not long enough to copy all the items in the
  collection. Check array index and length. and    at
  System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
  at System.Collections.Generic.Dictionary2.CopyTo(KeyValuePair2[]
  array, Int32 index)    at
  System.Collections.Generic.Dictionary`2.GetObjectData(SerializationInfo
  info, StreamingContext context)    at
  System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object
  obj, ISurrogateSelector surrogateSelector, StreamingContext context,
  SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter,
  ObjectWriter objectWriter, SerializationBinder binder)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo
  objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteArrayMember(WriteObjectInfo
  objectInfo, NameInfo arrayElemTypeNameInfo, Object data)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteArray(WriteObjectInfo
  objectInfo, NameInfo memberNameInfo, WriteObjectInfo memberObjectInfo)
  at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo
  objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)    at
  System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object
  graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)

  at
  System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream
  serializationStream, Object graph, Header[] headers, Boolean fCheck)

  at AggregateRunner.Enteties.Saver.SaverCallback()

Body:
As far as I can see, you're taking a snapshot for your queues once an hour, but the main problem with your code is that you're trying to serialize your queue (which is a ConcurrentQueue<T>, I guess) itself without any cloning or synchronization logic. Another problem with your code is a goto usage, which is not necessary at all here.

The exception you're facing is a ArgumentException and is a third possible exception of CopyTo method of the ConcurrentQueue<T>. It's happening during the serialization because of some thread added some messages to queue and now it doesn't fit in array serializer decided to use.

So, what you can do in such situation is either introduce some locking during access to the original queues (which you're decided to do), or create a clone for your queues and serialize that in a safe manner without blocking other threads.

You can do this with CopyTo method of ConcurrentQueue<T> by yourself, with creating array with length more than number of messages in queue, but the locking in general is more convenient way to clone the data. So your code should be like this:

private void SaverCallback()
{
    AddThread("Main Thread");
    const string path = "milestone";
    while (!stop)
    {
        try
        {
            lock (JobQueue.Queue.MainQueue)
            lock (JobQueue.Queue.LockedQueue)
            {
                using (var writingStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                {
                    var milestone = new ConcurrentDictionary<string, object>();
                    milestone.TryAdd("Jobs", JobQueue.Queue.MainQueue);
                    milestone.TryAdd("Locked Jobs", JobQueue.Queue.LockedQueue);

                    var formater = new BinaryFormatter();
                    formater.Serialize(writingStream, milestone);
                    writingStream.Flush();
                    Logger.Debug("Status saved");
                }
            }
            // this line cloud be in finally case too,
            // if you don't need to save a queue in case of some errors
            this.WaitTime(60000);
        }
        catch(Exception e)
        {
            // note that logger accepts whole exception information
            // instead of only it's message
            Logger.Error($"Milestone exception: {e}");
            continue;
        }
    }
    RemoveThread();
}


问:
How to quickly snap a view in storyboard back into its constraints after accidentally moving it
Everything I have found, every one says this cant be done.

I studied in fullsail university and they taught me how to do this so I know without a doubt it can be done. No one just knows how and assumes it can't.

Basically, when in XCode-story board, I would add constraints to a view and everything is all blue and perfect. From there, if you click, hold a drag, the view to another position then all of the constraints will turn orange. (Not RED because the constraints are still good it just simply needs to snap back into place..)

When in school my teacher taught me a quick key short cut that you press and everything snaps back into place and its all blue again. It has been a while since I have coded and i am just now getting back into it again and i just cant remember what that shortcut was.

I hope someone out there knows how to do this. Maybe any fullsail graduates?

Your responses are greatly appreciated.

答:
What you're looking to do is referred to as "Update(ing) Frames."

The quick command is indeed option-command-equals

The command can also be reached from the bottom menu of a storyboard.

This link may change in the future but check out the Auto Layout Guide. Specifically reference the "Resolve Auto Layout Issues Tool" section.


问:
Scrollview not scrolling
I'm using a scroll view which is having only one child linearlayout.
Linearlayout contains listview and some other items also, but only listview is scrolling. what should i do ?
Here is my layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/beco_white"
android:orientation="vertical">

<include layout="@layout/toolbar" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ViewSwitcher
            android:id="@+id/view_switcher"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/button_sign_in"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="@dimen/dp20"
                    android:background="@drawable/dark_blue_round_corner"
                    android:fontFamily="sans-serif-normal"
                    android:text="Login to beCo"
                    android:textAllCaps="false"
                    android:textColor="@android:color/white"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_sign_up"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="@dimen/dp20"
                    android:background="@drawable/customborder"
                    android:fontFamily="sans-serif-normal"
                    android:text="Create New Account"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent"
                    android:textSize="14sp" />

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white">

                <com.facebook.drawee.view.SimpleDraweeView
                    android:id="@+id/image_profile"
                    android:layout_width="@dimen/dp88"
                    android:layout_height="@dimen/dp88"
                    android:layout_gravity="left"
                    android:layout_marginBottom="@dimen/dp10"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_marginTop="@dimen/dp10"
                    fresco:actualImageScaleType="centerCrop"
                    fresco:placeholderImage="@drawable/no_profile_pic"
                    fresco:roundAsCircle="true"
                    fresco:roundingBorderColor="@color/white"
                    fresco:roundingBorderWidth="@dimen/dp2" />

                <TextView
                    android:id="@+id/user_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="John Doe"
                    android:textColor="@android:color/black"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/user_name"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toEndOf="@+id/image_profile"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="johndoe@mail.com"
                    android:textColor="@android:color/black"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_edit"
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignTop="@+id/image_profile"
                    android:background="@drawable/customborder"
                    android:text="Edit Profile"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent" />

            </RelativeLayout>

        </ViewSwitcher>

        <View
            android:layout_width="wrap_content"
            android:layout_height="1dp"
            android:background="@color/grey_200" />

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>
</ScrollView>
</LinearLayout>
</code>```

Any one please help me?

答:
Try this layout:

changes:

Make your inner linearlayout wrap into Scrollview

Apply android:layout_height="wrap_content" for scrollview

End the scrollview before Listview as both can not be applied together

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><include layout="@layout/toolbar" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="false">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ViewSwitcher
            android:id="@+id/view_switcher"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/button_sign_in"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="@dimen/dp20"
                    android:background="@drawable/dark_blue_round_corner"
                    android:fontFamily="sans-serif-normal"
                    android:text="Login to beCo"
                    android:textAllCaps="false"
                    android:textColor="@android:color/white"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_sign_up"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="@dimen/dp20"
                    android:background="@drawable/customborder"
                    android:fontFamily="sans-serif-normal"
                    android:text="Create New Account"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent"
                    android:textSize="14sp" />

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white">

                <com.facebook.drawee.view.SimpleDraweeView
                    android:id="@+id/image_profile"
                    android:layout_width="@dimen/dp88"
                    android:layout_height="@dimen/dp88"
                    android:layout_gravity="left"
                    android:layout_marginBottom="@dimen/dp10"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_marginTop="@dimen/dp10"
                    fresco:actualImageScaleType="centerCrop"
                    fresco:placeholderImage="@drawable/no_profile_pic"
                    fresco:roundAsCircle="true"
                    fresco:roundingBorderColor="@color/white"
                    fresco:roundingBorderWidth="@dimen/dp2" />

                <TextView
                    android:id="@+id/user_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="John Doe"
                    android:textColor="@android:color/black"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/user_name"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toEndOf="@+id/image_profile"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="johndoe@mail.com"
                    android:textColor="@android:color/black"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_edit"
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignTop="@+id/image_profile"
                    android:background="@drawable/customborder"
                    android:text="Edit Profile"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent" />

            </RelativeLayout>

        </ViewSwitcher>
    </LinearLayout>
</ScrollView>

<View
    android:layout_width="wrap_content"
    android:layout_height="1dp"
    android:background="@color/grey_200" />

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

Title: Scrollview not scrolling

Body:
I'm using a scroll view which is having only one child linearlayout.
Linearlayout contains listview and some other items also, but only listview is scrolling. what should i do ?
Here is my layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/beco_white"
android:orientation="vertical">

<include layout="@layout/toolbar" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ViewSwitcher
            android:id="@+id/view_switcher"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/button_sign_in"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="@dimen/dp20"
                    android:background="@drawable/dark_blue_round_corner"
                    android:fontFamily="sans-serif-normal"
                    android:text="Login to beCo"
                    android:textAllCaps="false"
                    android:textColor="@android:color/white"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_sign_up"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="@dimen/dp20"
                    android:background="@drawable/customborder"
                    android:fontFamily="sans-serif-normal"
                    android:text="Create New Account"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent"
                    android:textSize="14sp" />

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white">

                <com.facebook.drawee.view.SimpleDraweeView
                    android:id="@+id/image_profile"
                    android:layout_width="@dimen/dp88"
                    android:layout_height="@dimen/dp88"
                    android:layout_gravity="left"
                    android:layout_marginBottom="@dimen/dp10"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_marginTop="@dimen/dp10"
                    fresco:actualImageScaleType="centerCrop"
                    fresco:placeholderImage="@drawable/no_profile_pic"
                    fresco:roundAsCircle="true"
                    fresco:roundingBorderColor="@color/white"
                    fresco:roundingBorderWidth="@dimen/dp2" />

                <TextView
                    android:id="@+id/user_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="John Doe"
                    android:textColor="@android:color/black"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/user_name"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toEndOf="@+id/image_profile"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="johndoe@mail.com"
                    android:textColor="@android:color/black"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_edit"
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignTop="@+id/image_profile"
                    android:background="@drawable/customborder"
                    android:text="Edit Profile"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent" />

            </RelativeLayout>

        </ViewSwitcher>

        <View
            android:layout_width="wrap_content"
            android:layout_height="1dp"
            android:background="@color/grey_200" />

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>
</ScrollView>
</LinearLayout>

Any one please help me?

Body:
Try this layout:

changes:

Make your inner linearlayout wrap into Scrollview

Apply android:layout_height="wrap_content" for scrollview

End the scrollview before Listview as both can not be applied together

<?xml version="1.0" encoding="utf-8"?>

<include layout="@layout/toolbar" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="false">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ViewSwitcher
            android:id="@+id/view_switcher"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/button_sign_in"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="@dimen/dp20"
                    android:background="@drawable/dark_blue_round_corner"
                    android:fontFamily="sans-serif-normal"
                    android:text="Login to beCo"
                    android:textAllCaps="false"
                    android:textColor="@android:color/white"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_sign_up"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="@dimen/dp20"
                    android:background="@drawable/customborder"
                    android:fontFamily="sans-serif-normal"
                    android:text="Create New Account"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent"
                    android:textSize="14sp" />

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white">

                <com.facebook.drawee.view.SimpleDraweeView
                    android:id="@+id/image_profile"
                    android:layout_width="@dimen/dp88"
                    android:layout_height="@dimen/dp88"
                    android:layout_gravity="left"
                    android:layout_marginBottom="@dimen/dp10"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_marginTop="@dimen/dp10"
                    fresco:actualImageScaleType="centerCrop"
                    fresco:placeholderImage="@drawable/no_profile_pic"
                    fresco:roundAsCircle="true"
                    fresco:roundingBorderColor="@color/white"
                    fresco:roundingBorderWidth="@dimen/dp2" />

                <TextView
                    android:id="@+id/user_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="John Doe"
                    android:textColor="@android:color/black"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/user_name"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toEndOf="@+id/image_profile"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="johndoe@mail.com"
                    android:textColor="@android:color/black"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_edit"
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignTop="@+id/image_profile"
                    android:background="@drawable/customborder"
                    android:text="Edit Profile"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent" />

            </RelativeLayout>

        </ViewSwitcher>
    </LinearLayout>
</ScrollView>

<View
    android:layout_width="wrap_content"
    android:layout_height="1dp"
    android:background="@color/grey_200" />

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />


问:
Can Java RegEx Parse These Type Strings?
I am trying to use Java's Pattern & Matcher classes to parse out either a phone # or email from a string:

```<code>        Pattern pattern = Pattern.compile(  "(.*):(\\s*)(.*)(\\s.*)$");
    Matcher matcher = pattern.matcher(parties);
    if (matcher.find())
    {
        return matcher.group(3);
        //group(2) matches friendly name in Parties string
    }
</code>```

It's close to working but not quite matching in all cases. Here are some samples of what I need to parse:

Ex. 1 "From:  +19255551212  MARY- SUE" needs to return "+19255551212"

Ex. 2 "From:  someone@gmail.com " needs to return "someone@gmail.com"

Ex. 3 "To:  +1 (415) 233-1212 Sally" needs to return "+1 (415) 233-1212"

Currently, the above code seems close but not quite right. It returns:

Ex. 1: +19255551212  MARY-

Ex. 2: someone@gmail.com

Ex. 3: +1 (415) 233-1212

Any help would be appreciated.

Thanks!

答:
For your given examples this regex should work:

```<code>^(?:From|To):\s+(\+?[()\d\s-]*\d+|[^\s@]+@\S+)\b
</code>```

RegEx Demo

Though keep in mind that phone numbers and email addresses can vary a lot and this regex may need to be tweaked further depending on your inputs.

Body:
I am trying to use Java's Pattern & Matcher classes to parse out either a phone # or email from a string:

        Pattern pattern = Pattern.compile(  "(.*):(\\s*)(.*)(\\s.*)$");
    Matcher matcher = pattern.matcher(parties);
    if (matcher.find())
    {
        return matcher.group(3);
        //group(2) matches friendly name in Parties string
    }

It's close to working but not quite matching in all cases. Here are some samples of what I need to parse:

Ex. 1 "From:  +19255551212  MARY- SUE" needs to return "+19255551212"

Ex. 2 "From:  someone@gmail.com " needs to return "someone@gmail.com"

Ex. 3 "To:  +1 (415) 233-1212 Sally" needs to return "+1 (415) 233-1212"

Currently, the above code seems close but not quite right. It returns:

Ex. 1: +19255551212  MARY-

Ex. 2: someone@gmail.com

Ex. 3: +1 (415) 233-1212

Any help would be appreciated.

Thanks!

Body:
For your given examples this regex should work:

^(?:From|To):\s+(\+?[()\d\s-]*\d+|[^\s@]+@\S+)\b

RegEx Demo

Though keep in mind that phone numbers and email addresses can vary a lot and this regex may need to be tweaked further depending on your inputs.


问:
How to implement the strategy pattern in Clojure?
I have three similar functions, they filter a collection of maps matching a key (column) against its value, case-insensitively.

Here is the original code I want to DRY up:

```<code>;; gets a collection filtered by a column, exact match
(defn get-collection-by-equals [collection-name column-name column-value]
 (filter #(= (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, with partial match, case-insensitive
(defn get-collection-by-like [collection-name column-name column-value]
 (filter #(string/includes? (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, which starts with given value, case-insensitive
(defn get-collection-by-starts-with [collection-name column-name column-value]
 (filter #(string/starts-with? (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))
</code>```

You can see how similar the code is, I'm just using a different matching strategy in each case, =, includes? and starts-with?.

My first attempt was as follows:

```<code>;; returns a function which does a case-insensitive match between given column and value for the given map
(defn matching-fn [match-fn column-name column-value]
  (fn [map] (match-fn (string/lower-case (column-name map)) (string/lower-case column-value))))

;; gets a collection filtered by a column, exact match
(defn get-collection-by-equals [collection-name column-name column-value]
 (filter #((matching-fn = column-name column-value) %) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, with partial match, case-insensitive
(defn get-collection-by-like [collection-name column-name column-value]
 (filter #((matching-fn string/includes? column-name column-value) %) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, which starts with given value, case-insensitive
(defn get-collection-by-starts-with [collection-name column-name column-value]
 (filter #((matching-fn string/starts-with? column-name column-value) %) (cached-get-collection collection-name)))
</code>```

I didn't like the readability of this solution and it occurred to me that I could just pass the matching function, instead of having a function which returns a function, I came up with this:

```<code>;; gets a collection filtered by a column, using the given function, case-insensitive
(defn get-collection-by-filter [collection-name filter-fn column-name column-value]
 (filter #(filter-fn (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, exact match, case-insensitive
(defn get-collection-by-equals [collection-name column-name column-value]
  (get-collection-by collection-name = column-name column-value))

;; gets a collection filtered by a column, with partial match, case-insensitive
(defn get-collection-by-like [collection-name column-name column-value]
 (get-collection-by collection-name string/includes? column-name column-value))

;; gets a collection filtered by a column, which starts with given value, case-insensitive
(defn get-collection-by-starts-with [collection-name column-name column-value]
 (get-collection-by collection-name string/starts-with? column-name column-value))
</code>```

Is this idiomatic Clojure, are there other (better) solutions?

Using a macro seems overkill.

答:
Like a number of OO patterns, in a functional language the entire pattern boils down to "use a function with an argument". Extract everything but the small part that changes into a new function, with the part that changes as an argument to that function.</p>

```<code>(defn collection-comparator [cmp]
  (fn [collection-name column-name column-value]
    (let [lower-value (string/lower-case column-value)]
      (filter #(cmp (string/lower-case (column-name %))
                    lower-value)
              (cached-get-collection collection-name)))))

(def get-collection-by-equals (collection-comparator =))
(def get-collection-by-like (collection-comparator string/includes?))
(def get-collection-by-starts-with (collection-comparator string/starts-with?))
</code>```

Body:
I have three similar functions, they filter a collection of maps matching a key (column) against its value, case-insensitively.

Here is the original code I want to DRY up:

;; gets a collection filtered by a column, exact match
(defn get-collection-by-equals [collection-name column-name column-value]
 (filter #(= (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, with partial match, case-insensitive
(defn get-collection-by-like [collection-name column-name column-value]
 (filter #(string/includes? (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, which starts with given value, case-insensitive
(defn get-collection-by-starts-with [collection-name column-name column-value]
 (filter #(string/starts-with? (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))

You can see how similar the code is, I'm just using a different matching strategy in each case, =, includes? and starts-with?.

My first attempt was as follows:

;; returns a function which does a case-insensitive match between given column and value for the given map
(defn matching-fn [match-fn column-name column-value]
  (fn [map] (match-fn (string/lower-case (column-name map)) (string/lower-case column-value))))

;; gets a collection filtered by a column, exact match
(defn get-collection-by-equals [collection-name column-name column-value]
 (filter #((matching-fn = column-name column-value) %) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, with partial match, case-insensitive
(defn get-collection-by-like [collection-name column-name column-value]
 (filter #((matching-fn string/includes? column-name column-value) %) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, which starts with given value, case-insensitive
(defn get-collection-by-starts-with [collection-name column-name column-value]
 (filter #((matching-fn string/starts-with? column-name column-value) %) (cached-get-collection collection-name)))

I didn't like the readability of this solution and it occurred to me that I could just pass the matching function, instead of having a function which returns a function, I came up with this:

;; gets a collection filtered by a column, using the given function, case-insensitive
(defn get-collection-by-filter [collection-name filter-fn column-name column-value]
 (filter #(filter-fn (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, exact match, case-insensitive
(defn get-collection-by-equals [collection-name column-name column-value]
  (get-collection-by collection-name = column-name column-value))

;; gets a collection filtered by a column, with partial match, case-insensitive
(defn get-collection-by-like [collection-name column-name column-value]
 (get-collection-by collection-name string/includes? column-name column-value))

;; gets a collection filtered by a column, which starts with given value, case-insensitive
(defn get-collection-by-starts-with [collection-name column-name column-value]
 (get-collection-by collection-name string/starts-with? column-name column-value))

Is this idiomatic Clojure, are there other (better) solutions?

Using a macro seems overkill.

Body:
Like a number of OO patterns, in a functional language the entire pattern boils down to "use a function with an argument". Extract everything but the small part that changes into a new function, with the part that changes as an argument to that function.

(defn collection-comparator [cmp]
  (fn [collection-name column-name column-value]
    (let [lower-value (string/lower-case column-value)]
      (filter #(cmp (string/lower-case (column-name %))
                    lower-value)
              (cached-get-collection collection-name)))))

(def get-collection-by-equals (collection-comparator =))
(def get-collection-by-like (collection-comparator string/includes?))
(def get-collection-by-starts-with (collection-comparator string/starts-with?))


问:
MATLAB Convert a matrix of unknown size to a system of equations?
I have a square matrix of coefficients f, and would like to be able to solve these algebraically as a system of simultaneous equations (all the equations f[i,1] + f[i,2]x + ... + f[i, n]z = T for the same T)- the problem is that I don't know how large the matrix is, or what the value of T is going to be.

Is there a way that I can generate a set of equations from a matrix of coefficients, if I don't know in advance how many variables I will need, so that I can use the solve function?

答:
this is what you want as I understand it:</p>

```<code>% random number of coefficients (="unknown size")
n = randi([2,10],1);
% equation system matrix Ax = T
A = rand(n);
T = rand * ones(size(A,1),1);
% solve equations system
x = A\T;
</code>```

Body:
this is what you want as I understand it:

% random number of coefficients (="unknown size")
n = randi([2,10],1);
% equation system matrix Ax = T
A = rand(n);
T = rand * ones(size(A,1),1);
% solve equations system
x = A\T;


问:
I have cloned a ruby project from gitlab and trying to run but gem is not installing
I have cloned the project and also resolved so many issues related to gems installation and other configuration but now i am stuck on this issue

```<code>RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/bundler-1.14.6/lib/bundler/spec_set.rb:87:in `block in materialize': Could not find mini_portile2-2.0.0 in any of the sources (Bundler::GemNotFound)
</code>```

I have tried a lot to install this gem but no avail.
when i try to install this gem this message shows

```<code>$ gem install miniportile --version "2-2.0.0"
ERROR:  Could not find a valid gem 'miniportile' (= 2.pre.2.0.0) in any repository
</code>```

答:
Try changing the line in your gemfile to:

```<code>gem 'mini_portile2', '~> 2.0.0'
</code>```

Or from the command line:

```<code>gem install mini_portile2 --version '2.0.0'
</code>```

Body:
I have cloned the project and also resolved so many issues related to gems installation and other configuration but now i am stuck on this issue

RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/bundler-1.14.6/lib/bundler/spec_set.rb:87:in `block in materialize': Could not find mini_portile2-2.0.0 in any of the sources (Bundler::GemNotFound)

I have tried a lot to install this gem but no avail.
when i try to install this gem this message shows

$ gem install miniportile --version "2-2.0.0"
ERROR:  Could not find a valid gem 'miniportile' (= 2.pre.2.0.0) in any repository

Body:
Try changing the line in your gemfile to:

gem 'mini_portile2', '~> 2.0.0'

Or from the command line:

gem install mini_portile2 --version '2.0.0'


问:
Python find first occurrence of character after index
I am trying to get the index of the first occurrence of a character that occurs in a string after a specified index. For example:

```<code>string = 'This + is + a + string'

# The 'i' in 'is' is at the 7th index, find the next occurrence of '+'
string.find_after_index(7, '+')

# Return 10, the index of the next '+' character
>>> 10
</code>```

答:
Python is so predicable:

```<code>>>> string = 'This + is + a + string'
>>> string.find('+',7)
10
</code>```

Checkout help(str.find):

```<code>find(...)
    S.find(sub[, start[, end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.
</code>```

Also works with str.index except that this will raise ValueError instead of -1 when the substring is not found.

Body:
I am trying to get the index of the first occurrence of a character that occurs in a string after a specified index. For example:

string = 'This + is + a + string'

# The 'i' in 'is' is at the 7th index, find the next occurrence of '+'
string.find_after_index(7, '+')

# Return 10, the index of the next '+' character
>>> 10

Body:
Python is so predicable:

>>> string = 'This + is + a + string'
>>> string.find('+',7)
10

Checkout help(str.find):

find(...)
    S.find(sub[, start[, end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.

Also works with str.index except that this will raise ValueError instead of -1 when the substring is not found.


问:
JSF XHTML automatic static code review and quality measurement
Does anyone of you know any code reviewing tool designed for JSF like PMD/Checkstyle and other for Java? I am searching for a way to check some good practices on facelet pages.</p>

答:
Unfortunately, I didn't found such a tool yet.

The best I found for the moment is a web plugin for the Sonar tool, but it does not provide a lot of (useful) information. However, I think it's a good idea to keep an eye on it!


问:
How to take a "num/den" type input in Java?
I want to take in input like this:

Enter a fraction(num/den):

I thought this would work,

```<code>Scanner input = new Scanner(System.in);
System.out.print("Enter a fraction(num/den):");
numerator = input.nextInt();
input.next();
denominator = input.nextInt();
</code>```

and divide symbol will be disregarded.

答:
You can retrieve input data as below.

```<code>String input = scanner.nextLine();
</code>```

You can can apply rules to format/use depending on your requirements afterwards

One way of doing it, use / as delimiter to split the text then convert into two int to divide. Then you'll end up having fraction.

```<code>String parts[] = input.split(your_chosen_delimiter);
</code>```

Body:
I want to take in input like this:

Enter a fraction(num/den):

I thought this would work,

Scanner input = new Scanner(System.in);
System.out.print("Enter a fraction(num/den):");
numerator = input.nextInt();
input.next();
denominator = input.nextInt();

and divide symbol will be disregarded.

Body:
You can retrieve input data as below.

String input = scanner.nextLine();

You can can apply rules to format/use depending on your requirements afterwards

One way of doing it, use / as delimiter to split the text then convert into two int to divide. Then you'll end up having fraction.

String parts[] = input.split(your_chosen_delimiter);


答:
You can use:</p>

```<code>start_index = 7
next_index = string.index('+', start_index)
</code>```

Title: Python find first occurrence of character after index

Body:
You can use:

start_index = 7
next_index = string.index('+', start_index)


答:
```<code>string.find('+', 7)
</code>```

Read the documentation.

Body:
string.find('+', 7)

Read the documentation.


答:
```<code>In [1]: str.index?
Docstring:
S.index(sub[, start[, end]]) -> int

Like S.find() but raise ValueError when the substring is not found.
Type:      method_descriptor

In [2]: string = 'This + is + a + string'

In [3]: string.index('+', 7)
Out[3]: 10
</code>```


问:
Error sending email via SMTP in C#, Does this still work in 2017?
Having researched the issue extensively especially applying recommendations from similar issues on stackoverflow, the below code still returns error ""System.Net.Mail.SmtpException: Syntax error, command unrecognized. The server response was: connection rejected at....""

```<code>        try
        {
            var mail = new MailMessage();
            mail.From = new MailAddress("demo77377@gmail.com");
            mail.To.Add(new MailAddress("xxxxxxx@gmail.com"));
            mail.Subject = "TEST";
            mail.Body = "This is a test mail from C# program";

            using (var smtp = new SmtpClient())
            {
                smtp.Credentials = new System.Net.NetworkCredential("demo77377@gmail.com", "AABBCCDDEE1!","gmail.com");
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.UseDefaultCredentials = false;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Timeout = 10000;
                //
                smtp.Send(mail);
                Console.WriteLine("Message sent successfully");
                Console.ReadLine();
            }

        }
        catch (Exception e)
</code>```

I have done everything possible

On Client> I have alternated smtp properties (permutation) etc

On Server> I have made gmail account less secure, I have disabled captcha etc

I observed that similar issues on stackoverflow were mostly dated over 3years ago and thus, is it possible that gmail no longer supports this SMTP method via C#, likewise has it been deprecated in favor of gmail API

Also, please find provided in code, original password supplied for the gmail account, in order to confirm if this issue is general or isolated to this gmail account

Thanks

答:
This code is verified to work fine:

```<code>var fromAddress = new MailAddress("YOUREMAIL@gmail.com", "YOUREMAIL@gmail.com");
var toAddress = new MailAddress("YOUREMAIL@gmail.com", "YOUREMAIL@gmail.com");
const string fromPassword = "YOURPASSWORD";
const string subject = "YOUREMAIL@gmail.com";
const string body = "YOUREMAIL@gmail.com";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
    Timeout = 20000
};

using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}
</code>```

I'm not comfortable including your personal details even though you have so I have removed them. Obviously replace the email and password with the correct details.

Body:
Having researched the issue extensively especially applying recommendations from similar issues on stackoverflow, the below code still returns error ""System.Net.Mail.SmtpException: Syntax error, command unrecognized. The server response was: connection rejected at....""

        try
        {
            var mail = new MailMessage();
            mail.From = new MailAddress("demo77377@gmail.com");
            mail.To.Add(new MailAddress("xxxxxxx@gmail.com"));
            mail.Subject = "TEST";
            mail.Body = "This is a test mail from C# program";

            using (var smtp = new SmtpClient())
            {
                smtp.Credentials = new System.Net.NetworkCredential("demo77377@gmail.com", "AABBCCDDEE1!","gmail.com");
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.UseDefaultCredentials = false;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Timeout = 10000;
                //
                smtp.Send(mail);
                Console.WriteLine("Message sent successfully");
                Console.ReadLine();
            }

        }
        catch (Exception e)

I have done everything possible

On Client> I have alternated smtp properties (permutation) etc

On Server> I have made gmail account less secure, I have disabled captcha etc

I observed that similar issues on stackoverflow were mostly dated over 3years ago and thus, is it possible that gmail no longer supports this SMTP method via C#, likewise has it been deprecated in favor of gmail API

Also, please find provided in code, original password supplied for the gmail account, in order to confirm if this issue is general or isolated to this gmail account

Thanks

Body:
This code is verified to work fine:

var fromAddress = new MailAddress("YOUREMAIL@gmail.com", "YOUREMAIL@gmail.com");
var toAddress = new MailAddress("YOUREMAIL@gmail.com", "YOUREMAIL@gmail.com");
const string fromPassword = "YOURPASSWORD";
const string subject = "YOUREMAIL@gmail.com";
const string body = "YOUREMAIL@gmail.com";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
    Timeout = 20000
};

using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

I'm not comfortable including your personal details even though you have so I have removed them. Obviously replace the email and password with the correct details.


问:
Get all the dates of current week
Say I consider Sunday - Saturday as a week, how do I get all the dates of the current week in c#?

For example, current date is 30th March 2017, the output I need is,

```<code>26-March-2017,
27-March-2017,
28-March-2017,
29-March-2017,
30-March-2017,
31-March-2017,
01-April-2017
</code>```

答:
Assuming  that Sunday will be the start day of the week, as it is mentioned in the question I suggest following solution.</p>

```<code>var today = DateTime.Now.Date; // This can be any date.

Console.WriteLine(today.DayOfWeek);

var day = (int)today.DayOfWeek; //Number of the day in week. (0 - Sunday, 1 - Monday... and so On)

Console.WriteLine(day);

const int totalDaysOfWeek = 7; // Number of days in a week stays constant.

for (var i = -day; i < -day + totalDaysOfWeek; i++)
{
     Console.WriteLine(today.AddDays(i).Date);
}
</code>```

Title: Get all the dates of current week

Body:
Say I consider Sunday - Saturday as a week, how do I get all the dates of the current week in c#?

For example, current date is 30th March 2017, the output I need is,

26-March-2017,
27-March-2017,
28-March-2017,
29-March-2017,
30-March-2017,
31-March-2017,
01-April-2017

Body:
Assuming  that Sunday will be the start day of the week, as it is mentioned in the question I suggest following solution.

var today = DateTime.Now.Date; // This can be any date.

Console.WriteLine(today.DayOfWeek);

var day = (int)today.DayOfWeek; //Number of the day in week. (0 - Sunday, 1 - Monday... and so On)

Console.WriteLine(day);

const int totalDaysOfWeek = 7; // Number of days in a week stays constant.

for (var i = -day; i < -day + totalDaysOfWeek; i++)
{
     Console.WriteLine(today.AddDays(i).Date);
}


问:
Link changed - where can I find a list of Outlook office REST API scopes?
I am currently using the old Outlook office REST API v2 to access outlook.com mail of users via oauth (as opposed to microsoft graph, due to a lack of certain desired features)

For authentication scopes, it needs values like

https://outlook.office.com/mail.readwrite

https://outlook.office.com/mail.readwrite.shared

vs microsoft graph's

Mail.ReadWrite

Mail.ReadWrite.Shared

Unfortunately, the documentation that supposedly provides a comprehensive list of supported scopes https://dev.outlook.com/restapi/getstarted has had its links changed to point to microsoft graph's documentation (which doesnt really help at all)

THE FOLLOWING IS FROM THE ABOVE LINK, AND REDIRECTS TO THE BELOW LINK
  scope: a space-delimited list of access scopes that your app requires. For a full list of Outlook scopes, see Authenticate Office APIs using the "v2.0" endpoints [https://developer.microsoft.com/en-us/graph/docs/authorization/auth_overview]

答: I'm not aware of a global list of Outlook scopes but they should be documented along side each REST method under the Minimum Requires Scopes.</p>