Auto layout VFL: align all trailing in an horizontal constraint

Question: I have four labels stacked one below the previous one but alighning its baseline with the top of its content view, not with a vertical spacing with each other.
I do it by code this way
[contentView addConstraint:[NSLayoutConstraint constraintWithItem:topFirstLabel_
                                                        attribute:NSLayoutAttributeBaseline
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:contentView
                                                        attribute:NSLayoutAttributeTop
                                                       multiplier:1.0f
                                                         constant:20.0f]];

[contentView addConstraint:[NSLayoutConstraint constraintWithItem:topSecondLabel_
                                                        attribute:NSLayoutAttributeBaseline
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:contentView
                                                        attribute:NSLayoutAttributeTop
                                                       multiplier:1.0f
                                                         constant:47.0f]];

[contentView addConstraint:[NSLayoutConstraint constraintWithItem:topThirdLabel_
                                                        attribute:NSLayoutAttributeBaseline
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:contentView
                                                        attribute:NSLayoutAttributeTop
                                                       multiplier:1.0f
                                                         constant:70.0f]];

[contentView addConstraint:[NSLayoutConstraint constraintWithItem:topFourthLabel_
                                                        attribute:NSLayoutAttributeBaseline
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:contentView
                                                        attribute:NSLayoutAttributeTop
                                                       multiplier:1.0f
                                                         constant:87.0f]];

Now, I want all labels to be aligned by the trailing space with its superview.
Can I do that with an unique VFL string? Something like this, although this example will crash the app:
NSDictionary *views = NSDictionaryOfVariableBindings(contentView, topFirstLabel_, topSecondLabel_, topThirdLabel_, topFourthLabel_);
NSDictionary *metrics = @{ @"bigMargin" : @12 };

[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[topFirstLabel_][topSecondLabel_][topThirdLabel_][topFourthLabel_]-bigMargin-|"
                                                                    options:NSLayoutFormatAlignAllTrailing
                                                                    metrics:metrics
                                                                      views:views]];

Comment: I don't think you'll be able to do that -- You have to have all the labels in the format string to align them, but you can't set other spacings, since you've already done that with the other methods. Why not have the labels be spaced vertically with respect to each other (instead of wrt to the contentView), then you can use VFL to do that spacing as well as the align all trailing edges?
Comment: @rdelmar I can't do that, I have to align each cell a fixed space from its superview top edge to the baseline. Nothing to do there :P Thanks for your response.
Answer: This library might help you. It uses a vertical linear layout concept and you can add paddings as needed.
Answer: I don't think you can do this in a single call.
You can probably do something like this:
for ( NSString* viewName in views.allKeys )
{
    [contentView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: [NSString stringWithFormat: @"H:[%@]-bigMargin-|", viewName], options:NSLayoutFormatAlignAllTrailing metrics:metrics views:views];
}


Metalic sound on cello G string

Question: I am new to the cello and have been experiencing a sound on the G string that I can't quite pinpoint the cause of. Everywhere I have looked online appears to be specific to wolf tones or rattles, and I don't believe it is either.
The best I can describe the sound is like a metallic tone on top of the normal G frequency. I only get the sound when I play open G and it is not every time, sometimes it takes some effort to replicate. Here are a few other observations I have made:

No other strings are contributing. I can dampen all other strings and
it still makes the sound.
It seems to get worse with more rosin.
There
doesn't appear to be anything else on the cello vibrating.

If I can't figure it out, I plan to take it to the shop where I bought it to see if they can troubleshoot, but I thought I would ask here first just in case it is a possible easy fix.
The cello is an Avalor Studio 2008 - Guy Cole with Thomastik Infield Spirocore G and C strings.
Edit----
Audio clip is here: https://voca.ro/bLownwgbPX0
The second bow stroke has the sound in question.
Thanks in advance!
Comment: @TimBurnett-Bassist Audio is upload!
Comment: Any chance you can post a recording of the noise?
Comment: One thing you could consider is trying out different strings.  Sometimes it takes a bit of trial and error to match the best strings with your instrument.  I know strings can be pricey, but it might make a lot of difference.  Maybe ask your teacher if they have any old/discarded strings you could try out first.
Comment: @TimBurnett-Bassist I will post the sound as soon as I can get to the instrument and record it. Good suggestion!
Comment: Not a full answer as this is an inexpert opinion, but I had a similar issue on an old double bass I used to play. The issue, as far as I could tell, was a slight kink in the string that liked to cause a high overtone. Changing the string fixed it. I also think that this problem isn't very major (it's pretty slight in the recording) and part of getting good at the instrument is learning how to tame wild sounds like this with your bowing technique.
Answer: Since you mention you're new to the cello,  I suspect this is largely a case of inexperience with bowing.  I bet you will not hear it if you pluck the G-string.
I have played several different cellos of different quality, and while a topnotch instrument is less likely to show this problem, the G-string is more prone to this sort of "shatter" behavior until you learn just the right amount of pressure and acceleration curve as you start the bow stroke.
For starters, try starting a bow on A (fingered on the Gstring) and without changing anything in the bow speed or angle, release the string and see if the G pitch is reasonably clean.   In addition, make sure you are not too close to the bridge, as that makes starting a clean open-string tone more difficult as well.
Comment: Thank you for the feedback! I had recently played for several months on a beginners cello and switched to a higher quality one recently. I had never had a problem on the other cello but I will be sure to try your strategy and see how it works.
Comment: I was able to meet with someone more way experienced than me and it turns out you are correct that it has to do with the amount of pressure on the string. By dropping my elbow a bit more and letting gravity do more work I am able to avoid the sound more consistently. Thank you for steering me in the right direction and I hope this helps more fellow beginners down the road!
Answer: As Matt Putnam suggests, this could be an issue with the string itself. Either damage or a quality control mishap. So check over the string visually and by running your (clean) fingers over it. Detune the string so you can inspect it at the points of contact at the nut and saddle.
Another problem that can cause rattling on an open string of a stringed instrument is if the nut or saddle is too flat and parallel to the string direction. This makes the string sit farther back from the sounding portion and it strikes the material of the nut or saddle with each vibration, causing a Sitar-like buzz. To check this, detune the string and pull it out of the nut slot. Take a straight edge and make sure that the nut slot has a slight back angle so that the vibrating portion of the string makes contact at the edge on the fingerboard side and not somewhere in the middle. The saddle should have an edge and not be too flat.
Comment: I believe I have some old strings on a practice cello that I can try switching out to see if it improves. Thank you for the information, I had no idea small deformations in strings could cause such problems.

Metalic sound on cello G string


Is it possible to use the result of a subquery in a case statement of the same outer query?

Question: I am writing a search routine with a ranking algorithm and would like to get this in one pass.
My Ideal query would be something like this....
select *, (select top 1 wordposition
           from wordpositions
           where recordid=items.pk_itemid and wordid=79588 and nextwordid=64502
          ) as WordPos,
      case when WordPos<11 then 1 else case WordPos<50 then 2 else case WordPos<100 then 3 else 4 end end end end as rank
from items

Is it possible to use WordPos in a case right there? It's generating an error on me , Invalid column name 'WordPos'.
I know I can redo the subquery for each case but I think it would actually re-run the case wouldn't it?
For example:
select *, case when (select top 1 wordposition from wordpositions where recordid=items.pk_itemid and wordid=79588 and nextwordid=64502)<11 then 1 else case (select top 1 wordposition from wordpositions where recordid=items.pk_itemid and wordid=79588 and nextwordid=64502)<50 then 2 else case (select top 1 wordposition from wordpositions where recordid=items.pk_itemid and wordid=79588 and nextwordid=64502)<100 then 3 else 4 end end end end as rank from items

That works....but is it really re-running the identical query each time?
It's hard to tell from the tests as the first time it runs it's slow but subsequent runs are quick....it's caching...so would that mean that the first time it ran it for the first row, the subsequent three times it would get the result from cache?
Just curious what the best way to do this would be...
Thank you!
Ryan
Comment: Yes sorry T-SQL not MySQL...fixed the tag...
Answer: You can do this using a subquery.  I will stick with your SQL Server syntax, even though the question is tagged mysql:
select i.*,
       (case when WordPos < 11 then 1
             when WordPos < 50 then 2
             when WordPos < 100 then 3
        else 4
        end) as rank
from (select i.*,
             (select top 1 wpwordposition
              from wordpositions wp
              where recordid=i.pk_itemid and wordid=79588 and nextwordid=64502
             ) as WordPos
      from items i
     ) i;

This also simplifies the case statement.  You do not need nested case statements to handle multiple conditions, just multiple where clauses.
Comment: That worked thanks!  Both answers are right...I choose this one because the example was directly usable in my project. Also thanks for the tip on simplifying the case!
Answer: No. Identifiers introduced in the output clause (the fact that it comes from a sub-query is irrelevant) cannot be used within the same SELECT statement.
Here are some solutions:

Rewrite the query using a JOIN1, This will eliminate the issue entirely and fits well with RA.
Wrap the entire SELECT with the sub-query within another SELECT with the case. The outer select can access identifiers introduced by the inner SELECT's output clause.
Use a CTE (if SQL Server). This is similar to #2 in that it allows an identifier to be introduced.

While "re-writing" the sub-query for each case is very messy it should still result in an equivalent plan - but view the query profile! - as the results of the query are non-volatile. As such the equivalent sub-queries can be safely moved by the query planner which should move the sub-query/sub-queries to a JOIN to avoid any "re-running" in the first place.

1 Here is a conversion to use a JOIN, which is my preferred method. (I find that if a query can't be written in terms of a JOIN "easily" then it might be asking for the wrong thing or otherwise be showing issues with schema design.)
select
   wp.wordposition as WordPos,
   case wp.wordposition .. as Rank
from items i
left join wordpositions wp
  on wp.recordid = i.pk_itemid
where wp.wordid = 79588
  and wp.nextwordid = 64502

I've made assumptions about the multiplicity here (i.e. that wordid is unique) which should be verified. If this multiplicity is not valid and not correctable otherwise (and you're indeed using SQL Server), then I'd recommend using ROW_NUMBER() and a CTE.


how to add list of widgets in flutter?

Question: I have used the package flutter_form_builder to create list of widget form.
I created a page that enables the user to add as many widget as he wants with the function named _addwidget()

 var _myWidgets = <Widget>[];
 int _index = 0;
 var evaluationOptions = ['1', '2', '3', '4', '5', '6', '7', '8'];

 bool autoValidate = true;
 final _formKey = GlobalKey<FormBuilderState>();

 final Map<int, String> nomModulevalues = Map();
 final Map<int, String> evaluationvalues = Map();

 final List<TextEditingController> _nomModuleControllers = [];
 final List<TextEditingController> _evaluationnumber = [];

  void _addwidget() {
   int keyValue = _index;
   _myWidgets = List.from(_myWidgets)
     ..add(Column(
       key: Key("$keyValue"),
       children: <Widget>[
         SizedBox(height: 10),
         Container(

           child: Column(
             children: <Widget>[
                  .......
                   Column(
                     children: <Widget>[
                       SizedBox(
                         height: 20,
                       ),
                       _buildnommodule(keyValue),
                       _buildevaluation,
                      ],
                   ),
                 ],
               )
             ],
           ),
         )
       ],
     ));

   setState(() => ++_index);
 }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
  .....
     floatingActionButton: FloatingActionButton(
       onPressed: () {
         _addwidget();
   ....
     body: SizedBox(
       height: double.infinity,
       width: double.infinity,
       child: Form(
           autovalidateMode: AutovalidateMode.disabled,
           key: _formKey,
           child: Stack(
        ....
                   Expanded(
                     child: SizedBox(
                       child: ListView(
                         padding: const EdgeInsets.all(10.0),
                         children: _myWidgets,
                     ),
                   ),
                   )],
               )

 Widget _buildnommodule(int keyValue) {
   TextEditingController controller = TextEditingController();
   _nomModuleControllers.add(controller);
   return Container(
     child: FormBuilderTextField(
       name: 'nom',
       controller: controller,
     ),
   );
 }

 Widget _buildevaluation(int keyValue) {
   TextEditingController controller = TextEditingController();
   _evaluationnumber.add(controller);
   return FormBuilder(
     autovalidateMode: AutovalidateMode.disabled,
     child: DropdownButtonHideUnderline(
         child: FormBuilderDropdown(
       name: 'evaluation',
       validator: FormBuilderValidators.compose(
           [FormBuilderValidators.required(context)]),
       items: evaluationOptions
           .map((evaluation) => DropdownMenuItem(
                 value: evaluation,
                 child: Text(
                   evaluation,
                   style: const TextStyle(color: Colors.black),
                   textAlign: TextAlign.center,
                 ),
               ))
           .toList(),
     )),
   );
 }
}

The code works well and is generated as the user wants, but when you start filling out this questionnaire, you notice that the information disappears when moving from one widget to another
For example, we create four widgets by pressing four times in the FloatingActionButton,after when filling the first three parts and moving to the fourth, we notice that the information entered in the first and second barriers has disappeared (empty widget)
Note: when I changed the FormBuilderDropdown to FormBuilderTextField it work correctly
Comment: I am not sure but give it a try to add a different, unique `name` for each input field, instead of `nom` and `evaluation`. Maybe the package relies on that field names are unique within a form.
Comment: thank you , but not working.
Comment: It may also be a visual error that the product that is growing the list of widgets because the other contents are not displayed correctly
Comment: I have added a note to my question
Answer: As i understood the content of your FormFields is disappearing as soon you scroll right?
That's probably a behaviour of the ListView. The ListView automatically disposes the state of the Widgets out of View.
You can try to add this to your ListView:
ListView(
  addAutomaticKeepAlives: true,
),

Comment: I have added a note to my question
Comment: sorry but not working

how to add list of widgets in flutter?


HTML + javascript saved viewing position after re-loading html

Question: I have this code where I can save the position of my html file like a bookmark and the box jumps to the position of the last save. Both work well.
When I re-open the document again it goes to the position as planned, but the box is not there anymore. (the box jumps back to the start)
How can I keep the box at the saved point after re-loading the html?
Here is my JSFiddle
Thank you very much in advance!
HTML:

CSS:
#takeMeToSave {
  background-color: lightblue;
  position: fixed;
  top: 0;
  cursor:pointer;
  border-radius:4px;
  padding:3px;
}

#box {
  position: absolute;
  background-color: black;
  opacity: 0.5;
  height: 2.5em;
  width: 100%;
  left: 0;
  top: 0px;
  transition: 0.3s top;
  pointer-events:none;
}

JS:
  var test = "test";
  try {
      localStorage.setItem(test, test);
      localStorage.removeItem(test);
      return true;
  } catch(e) {
      return false;
  }
}

function getTotalHeight() {
  return document.body.clientHeight;
}

function getSavedPercent() {
  var percent = storageSupported ? loadFromStorage() : loadFromCookie();
  return (percent == null || percent == "") ? 0 : percent;
}

/******* Save *******/

function saveInStorage() {
  localStorage.setItem("scrollPercent", (document.documentElement.scrollTop / getTotalHeight()));

}

function saveCookie() {
  var expDate = new Date();
  expDate.setDate(expDate.getDate() + 7); // start over if it's been more than ___ days
  document.cookie = "scrollPercent=" + (document.documentElement.scrollTop / getTotalHeight())
              + "; " + expDate;
}

/******* Load *******/

function loadFromStorage() {
  return localStorage.getItem("scrollPercent");
}

function loadFromCookie() {
  return document.cookie.replace(/(?:(?:^|.*;\s*)scrollPercent\s*\=\s*([^;]*).*$)|^.*$/, "$1");
}

/******* Handler *******/

var saveButton = document.getElementById("saveButton");
var saved = document.getElementById("saved");
var takeMeToSave = document.getElementById("takeMeToSave");
var cordinateCont = "";
var cordinateBtn = ""
var boxMove = document.getElementById("box");

takeMeToSave.style.display = "none"
saveButton.onclick = function(e) {
  storageSupported ? saveInStorage() : saveCookie();
  saved.style.visibility = "visible";
  setTimeout(function() {
    saved.style.visibility = "hidden";
  }, 1500);
  cordinateCont = e.pageY; //where is the click according to content including scroll content
  cordinateBtn = e.clientY; //cordinateBtn is where it is clicked inside btn
  takeMeToSave.style.display = "block";
  boxMove.style.top = cordinateCont +60 - cordinateBtn + 'px';
};

takeMeToSave.onclick = function() {
  storageSupported ? saveInStorage() : saveCookie();
  window.scrollTo({
    top: cordinateCont + 60 - cordinateBtn,
    left: 0,
    behavior: 'smooth'
  });
  //1 is borderWidth of btn and 50, cordinateBtn, 1 is subtracted from position to remove wherever it is clicked on btn and only change with respect to top of window screen of content
};

/******* Logic *******/

var storageSupported = checkStorageSupport(),
  percent = getSavedPercent();

if (percent > 0) {
  if (confirm("Would you like to continue reading where you left off?")) {
      document.documentElement.scrollTop = percent * getTotalHeight();
  };
}

Comment: Use cookies or use local storage - https://blog.logrocket.com/localstorage-javascript-complete-guide/
Answer: I see you have already used LocalStorage very well.
You could save the button position as you've done with the scroll position and re-apply it on page load (as you've done with scroll).
It will be something like this :

const boxLocalStorageId = "boxTop";

function saveButtonPosition(boxTop) {
  localStorage.setItem(boxLocalStorageId, boxTop);
}

function loadButtonPosition() {
  if(localStorage.hasOwnProperty(boxLocalStorageId)) {
    // We have found button position in local storage
    return localStorage[boxLocalStorageId];
  } else {
    // We didn't found the data -> we return a default value
    return 0;
  }
}

You'll then need to call saveButtonPosition on save button click
And for the loadButtonPosition, you could add after your confirm boxMove.style.top = loadButtonPosition() + "px";
Here's a working jsFiddle with the solution.
But keep in mind that I've only implemented LocalStorage support. If you really need cookie support, I could help you through adding it to the solution but from CanIUse, the support for localStorage is good enough to use it.
Comment: @Wickeda I've updated the answer with a js fiddle ! :)
Comment: Glad to have helped :) !
Comment: Thank you for your answer, but I'm feeling really dumb as I'm playing around in my fiddle with your code but I can't get it to work. I feel I am missing some knowledge :( May I ask you to write it into JSFiddle. Sorry for the inconvenience and thank you in advance
Comment: It works like a charm! THANK YOU A MILLION TIMES! (I see now that I was falling short with the boxTop const)
Comment: I marked the answer as solution. You really made my day :-)
Answer: You should add an event on the scroll of the body element and in the handler function record document.scrollingElement.scrollTop value in the cookie or local storage.
On loading page handler you can load data from you storage location and use document.scrollingElement.scrollTo({top: value}) to scroll page to last position.


JPA Hibernate Stream Performance Issue

Question: I'm using hibernate and JPA for fetching 50k data with stream from MySQL database, it scheduled around 5-15 minutes periodically.
this is my config of datasource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.idle-timeout=120000
spring.datasource.hikari.connection-timeout: 300000
spring.datasource.hikari.leak-detection-threshold: 300000
spring.datasource.connection-test-query=SELECT 1
spring.datasource.test-while-idle=true
spring.datasource.test-on-borrow=true

here is the service class
@Service
public class BalanceReminderStream {

    @PersistenceContext(unitName = "myServiceReminderEntityManager")
    EntityManager entityManager;

    @Autowired
    Constant constant;

    @Transactional(readOnly = true)
    public boolean executeReminder(){

       //if another scheduling thread still running
       if(constant.activeReminder.containsKey(Context.BALANCE_REMINDER)){
           config.generalLogger.warn("Scheduling still running on another thread at "+constant.activeReminder.get(Context.BALANCE_REMINDER)+", skipping reminder");
           return false;
      }
      constant.activeReminder.put(Context.BALANCE_REMINDER, LocalDateTime.now());

      constant.streamBalanceReminder = userServiceReminderRepository.findAllActiveBalanceReminder();

      //do get data
      constant.streamBalanceReminder.forEach(userServiceReminder -> {

            constant.fetchSizeBalanceReminder.getAndIncrement();

            //process each records, add to thread pool
            threadPoolManager.addBalanceReminderQueue(userServiceReminder);

            //detach the entity so garbage collector can reclaim the memory
            entityManager.detach(userServiceReminder);
        });
     }
     return true;
}

here is jpa
@Repository
public interface UserServiceReminderRepository extends JpaRepository<UserServiceReminder, Long>{
    @QueryHints(value = {
            @QueryHint(name = HINT_FETCH_SIZE, value = "" + Integer.MIN_VALUE),
            @QueryHint(name = HINT_CACHEABLE, value = "false"),
            @QueryHint(name = READ_ONLY, value = "true")
    })
    @Query("FROM #{#entityName} WHERE status = 'ACTIVE' AND status_reminder = 'BALANCE'")
    Stream<UserServiceReminder> findAllActiveBalanceReminder();
    }
}

and I call the component from scheduler class like this
@Component
@EnableScheduling
@EnableAsync
public class BalanceReminderScheduler {
    @Autowired
    BalanceReminderStream balanceReminderStream;

    @Autowired
    Config config;

    @Autowired
    Constant constant;

@Async
@Scheduled(fixedRate = 1000L * 60 * 15)
void execute(){
    long start = System.currentTimeMillis();
    boolean isReminderExecuted = false;
        try {
            isReminderExecuted = balanceReminderStream.executeReminder();
        }catch (TransactionSystemException e){
            String stacktrace = ExceptionUtils.getStackTrace(e);
            config.generalLogger.error(stacktrace);
            //close stream
            if(constant.streamBalanceReminder!=null){
                constant.streamBalanceReminder.close();
            }
        }catch (Exception e){
            String stacktrace = ExceptionUtils.getStackTrace(e);
            config.generalLogger.error(stacktrace);
        }finally{
            if(isReminderExecuted) {
                config.generalLogger.info("Fetch size: " + constant.fetchSizeBalanceReminder.get()
                    + " (" + (System.currentTimeMillis() - start) + " ms)");
                 constant.activeReminder.remove(Context.BALANCE_REMINDER);
                 constant.fetchSizeBalanceReminder.set(0);
                 //close stream
                 if(constant.streamBalanceReminder!=null){
                     constant.streamBalanceReminder.close();
                 }
             }
        }
    }
}

for first time run, it doesn't get any exception, and the fetch time still about 10 seconds, but after 3 hours, the fetch time getting slowed down drastically and then got an exception

org.springframework.transaction.TransactionSystemException: Could not roll back JPA transaction; nested exception is org.hibernate.TransactionException: Unable to rollback against JDBC Connection
    at org.springframework.orm.jpa.JpaTransactionManager.doRollback(JpaTransactionManager.java:593)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:835)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:809)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.completeTransactionAfterThrowing(TransactionAspectSupport.java:672)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:392)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
    at com.sample.myapp.service.reminder.BalanceReminderStream$$EnhancerBySpringCGLIB$$ee49a3b6.executeReminder(<generated>)
    at com.sample.myapp.scheduler.BalanceReminderScheduler.execute(BalanceReminderScheduler.java:58)
    at sun.reflect.GeneratedMethodAccessor90.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:774)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
    at org.springframework.aop.interceptor.AsyncExecutionInterceptor.lambda$invoke$0(AsyncExecutionInterceptor.java:115)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.TransactionException: Unable to rollback against JDBC Connection
    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.rollback(AbstractLogicalConnectionImplementor.java:127)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.rollback(JdbcResourceLocalTransactionCoordinatorImpl.java:304)
    at org.hibernate.engine.transaction.internal.TransactionImpl.rollback(TransactionImpl.java:142)
    at org.springframework.orm.jpa.JpaTransactionManager.doRollback(JpaTransactionManager.java:589)
    ... 23 more
Caused by: java.sql.SQLException: Streaming result set com.mysql.cj.protocol.a.result.ResultsetRowsStreaming@76fa3328 is still active. No statements may be issued when any streaming result sets are open and in use on a given connection. Ensure that you have called .close() on any active streaming result sets before attempting more queries.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ConnectionImpl.rollbackNoChecks(ConnectionImpl.java:1951)
    at com.mysql.cj.jdbc.ConnectionImpl.rollback(ConnectionImpl.java:1845)
    at com.zaxxer.hikari.pool.ProxyConnection.rollback(ProxyConnection.java:396)
    at com.zaxxer.hikari.pool.HikariProxyConnection.rollback(HikariProxyConnection.java)
    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.rollback(AbstractLogicalConnectionImplementor.java:121)
    ... 26 more

after that, it will always get an exception until I restart the java, is there any I missed here?
Comment: Hard to say what is going on without seeing the full code. It seems that you have some sort of connection/resource leak though. Not sure what Spring Data does when you request a `Stream` to be returned from a repository. Try to time `findAllActiveBalanceReminder` and `addBalanceReminderQueue` separately as well to see if the time to execute these tasks increases as well.
Answer: Are you sure that every query is done with processing before another query starts?
Maybe it is stacking data, and that's why you are getting longer processing times.
Just an idea.
Also, you can try to run it with a CPU profiler to check what is taking the most of the time.
Comment: I'm pretty sure on it, actually I already add the code to check is the thread of fetching data still running (I've edited on my code), sometimes I got log that the thread still active

JPA Hibernate Stream Performance Issue


Fourier Transform of $\cos(\pi t)+2\sin(3\pi t)+\cos(5\pi t)\cos(7\pi t)$

Question: I think I understand this question up until the last term. So far I have:
$$F(\omega)=\pi(\delta(\omega+\pi) + \delta(\omega-\pi))+2\pi(\delta(\omega+3\pi) + \delta(\omega-3\pi))+\frac{1}{2}(\delta(\omega+5\pi) + \delta(\omega-5\pi)*\delta(\omega+7\pi) + \delta(\omega-7\pi))$$
I don't understand how to convolve the delta functions. Let me know if I am on the right track with this.
Thank you!
Answer: There's no need to convolve the delta functions, because
$$\cos{5 \pi t} \cos{7 \pi t} = \frac12 (\cos{2 \pi t} + \cos{12 \pi t})$$
Comment: @user1971854: cosine addition theorem: $$\cos{(a+b)} = \cos{a} \cos{b} - \sin{a} \sin{b}$$
Comment: would you car to explain which property you used to find this?
Comment: I'm sorry, but I am still missing the connection. Where does the sine term go, where does $cos(2\pi t)$ come from and why is it scaled by 1/2?
Comment: @user1971854: If you are talking about convolutions and delta functions, then you should be able to consider $\cos{(a-b)}$ and add them together to figure this out.
Comment: Aha, I see it now. Thank you for your help!


Alterar imagem de fundo de um Adapter Recycler View após click

Question: É o seguinte, eu criei um Adapter que altera um RecyclerView em uma Activity que eu chamo através desta função (dentro da activity):
 private void gerarDatasView(CalendarJur calendario){

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
        listDatas.setLayoutManager(linearLayoutManager);

        ListDatasAdapter adapter = new ListDatasAdapter();
        adapter.setDateJur(calendario.getDatas());

        listDatas.setAdapter(adapter);

    }

O listDatas é o RecyclerView.
E funciona perfeitamente conforme a imagem:

Cada item desta lista foi criado através do onBindViewHolder no meu Adapter assim:
public void onBindViewHolder(@NonNull final ViewListDatas holder, int position) {
        DateJur data = datas.get(position);
        holder.diaMes.setText(data.getDiaMes());
        holder.diaSemana.setText(data.getDiaSemana());

        if(holder.getAdapterPosition() == posNow){
            holder.btn.setImageResource(R.drawable.background_date_layout_selected);
            posNow = holder.getAdapterPosition();
        }
        holder.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                holder.btn.setImageResource(R.drawable.background_date_layout_selected);
                // muda a cor de fundo conforme o click
            }
        });
    }

Quando eu clico em uma outra data a cor do fundo se altera da forma como eu quero, porém a data antiga teria que ficar com o background padrão (branco), mas ambos ficam com o background selecionado (azul) veja:

Minha pergunta:
Como eu faço para o adaptador saber que tem que alterar o outro item para a cor padrão após um click?
Tem como controlar isso dentro do Adapter ou eu teria que fazer de outra forma?
Como eu não queria deixar a pergunta muito extensa, coloquei os códigos que eu acho que são necessários, mas se precisar de outras informações é só pedir.
Answer: Uma abordagem seria guardar numa variável a posição do item do adapter que foi clicado, assim sempre que o click fosse feito bastava alterar o fundo do item que está guardado na variável para o "normal" e por fim mudar o fundo do item clicado para o "novo".
Algo deste género:
RecyclerView recyclerView;
int posUltimoClick = -1;

public void onBindViewHolder(@NonNull final ViewListDatas holder, int position) {
        DateJur data = datas.get(position);
        holder.diaMes.setText(data.getDiaMes());
        holder.diaSemana.setText(data.getDiaSemana());

        if(holder.getAdapterPosition() == posNow){
            holder.btn.setImageResource(R.drawable.background_date_layout_selected);
            posNow = holder.getAdapterPosition();
        }
        holder.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(posUltimoClick != -1){

                    // Vai aceder ao layout anteriormente clicado e mudar o fundo para o "normal"
                    Button btnAnt = recyclerView.getLayoutManager().findViewByPosition(posUltimoClick).findViewById(R.id."item que quer alterar o fundo");
                    btnAnt.setImageResource(R.drawable.background_date_layout_normal);
                    notifyItemChanged(posUltimoClick);
                    posUltimoClick = position;

                    // muda a cor de fundo do item clicado atualmente
                    holder.btn.setImageResource(R.drawable.background_date_layout_selected);
                }else{
                    posUltimoClick = position;
                    // muda a cor de fundo do item clicado atualmente
                    holder.btn.setImageResource(R.drawable.background_date_layout_selected);
                }
            }
        });
    }

Nota: para aceder ao recyclerview tem que o passar como parâmetro do construtor do adapter
Espero ter ajudado.
Comment: Boa ideia! Eu consegui de outra forma... Vou postar também depois. Não irei marcar como certa ainda pois quero testar e ver se aparecem outras respostas. Mas.. muito obrigado!
Answer: A forma que eu fiz (não sei se é a melhor) foi utilizando LinearLayoutManager junto com uma interface interna no Adapter:
Adapter
public class ListDatasAdapter extends RecyclerView.Adapter<ListDatasAdapter.ViewListDatas> {

    public ClickResponseDataItem clickItemResponse;

    public interface ClickResponseDataItem {
        void response(int position);
    }

    @NonNull
    @Override
    public ViewListDatas onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
       ... código sem importância ...
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewListDatas holder, int position) {
        final DateJur data = datas.get(position);

       // botao de click
        holder.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if( posNow != holder.getAdapterPosition()){
                    holder.btn.setImageResource(R.drawable.background_date_layout_selected);
                    holder.diaSemana.setTextColor(ContextCompat.getColor(context, R.color.colorWhite));
                    holder.diaMes.setTextColor(ContextCompat.getColor(context, R.color.colorWhite));
                    posNow = holder.getAdapterPosition();
                    clickItemResponse.response(holder.getAdapterPosition()); // interface
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    class ViewListDatas extends RecyclerView.ViewHolder {
       ... código sem importância ...
    }
}

Na activity eu implemento a interface do adapter:
public class JuridicoCalendarActivity extends AppCompatActivity implements ListDatasAdapter.ClickResponseDataItem {

    private LinearLayoutManager linearLayoutManager;
    private int posIni = 0;
    private RecyclerView listDatas;

E insiro a função dentro dela:
 public void response(int position) {

        View v = linearLayoutManager.findViewByPosition(posIni);
        ImageButton btn = v.findViewById(R.id.btnDataJur);
        TextView text1 = v.findViewById(R.id.diaMesDataJur);
        TextView text2 = v.findViewById(R.id.diaSemanaDataJur);

        text1.setTextColor(ContextCompat.getColor(getBaseContext(), R.color.colorText));
        text2.setTextColor(ContextCompat.getColor(getBaseContext(), R.color.colorText));

        btn.setImageResource(R.drawable.background_date_layout_unselect);
        posIni = position;

    }

Ainda na activity instancio o meu adaptador da seguinte forma:
// configuro o LinearLayoutManager
linearLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
listDatas.setLayoutManager(linearLayoutManager); // seto no RecyclerView

adapter = new ListDatasAdapter(); // crio o adaptador
adapter.clickItemResponse = this; // seto a interface
listDatas.setAdapter(adapter); // seto o adapta

Desta forma, com o linearLayoutManager eu consigo gerenciar cada item do adapter na função response() da activity.
    // pega a view
    View v = linearLayoutManager.findViewByPosition(posIni);
    // altera os valores
    ImageButton btn = v.findViewById(R.id.btnDataJur);
    TextView text1 = v.findViewById(R.id.diaMesDataJur);
    TextView text2 = v.findViewById(R.id.diaSemanaDataJur);


Does just intonation work for any given key, or is it impractical even for a work in a single key?

Question: According to my understanding any non-chorded instrument, like a string instrument or horn, can use a just intonation, so the problem only arises with chorded instruments like pianos. So, for example, in a symphony that does not have a piano I suppose using just intonation is possible.
On the other hand, let's imagine a piano concerto. As long as the concerto is in a single key, then is it possible to use a just intonation tuning, or will there still be problems?
Comment: The requirement to fix a temperament arises when the notes are fixed in pitch.  It does not depend on whether an instrument can play chords or not; it's just easier to bend pitches if you're playing only one at a time.  For example, a guitar player can bend individual notes in a chord to approach just intonation.  Any instrument where it's not possible to bend the pitches must choose a temperament; this includes for example the hammered dulcimer, which is not primarily a chord-playing instrument.
Answer: Impractical for any key.

C = 1/1
D = 9/8
E = 5/4
F = 4/3
G = 3/2
A = 5/3
B =15/8
C = 2/1

Now check chords; the major chords:

C-E-G    1 : 5/4 : 3/2  or  4:5:6 ratio (multiplying by the LCM)
G-B-D  3/2 :15/8 :18:8  or  4:5:6 ratio
F-A-C  4/3 : 5/3 : 6/3  or  4:5:6 ratio

The minor chords:

D-F-A  9/8 : 4/3 : 5/3  or  27:32:40 ratio  <-- !
E-G-B  5/4 : 3/2 :15/8  or  10:12:15 ratio
A-C-E  5/3 : 2/1 :10/4  or  10:12:15 ratio

So the ii chord is already different.
Comment: Yes, but not using Just Intonation. One of the meantone or other recirculant tunings was used.
Comment: So it's possible to tune a keyboard in just intervals if you avoid certain chords.  For example, in the key of C you can have a just F major chord if you avoid D minor (and D major as V/V).  If you tune for the just D minor (and a just V/V), you lose either the just major third between F and A. (Actually, you can also lower the D to preserve the just F-to-A third, but then you lose the just perfect fifth between D and G.  Since G major is the dominant of C major, you won't want to do that.)  Note that you run into the problem before you get to chromatic chords.
Comment: @CarlWitthoft furthermore, I doubt it would have been common to retune harpsichords for each piece.  It takes some minutes to tune a harpsichord.  You could shift one or two notes between pieces, and I've been to concerts where that has been done, but if it's not done at intermission someone has to talk to the audience for a bit while the instrument is retuned.  Earlier in the baroque period, pieces were almost all written in closely related keys that would not have required retuning.  Erratum: strike "either" from the previous comment.
Comment: It's unclear what your point is.  Consider the fact that, prior to Well-Tempered Clavier,  keyboards (harpsichord in particular) were retuned to the key of each piece (just intonation).
Comment: ahhh, thank you for the correction.  Always glad to learn stuff.
Comment: @CarlWitthoft any keyboard must be tempered; that is why we speak of just *intonation* but equal *temperament.* Pure just intonation requires moving notes to different frequencies to fit the context. I recently found a video of Pachelbel's famous canon in three temperaments, one claiming to be just intonation. A commenter noticed that the tuning was rather poor toward the end; this is where the violins have some ii 6/5 chords (including E) over the bass G (most of the piece has IV chords there). The fourth between the B and the E is indeed horribly out of tune, though it is fleeting.
Comment: So you're saying that in the early days, even a harpsichord playing on its own tuned to one key will still sound out of tune in that one key - with no modulations? I was under the (probably wrong) impression that 12tet came about so an instrument so tuned could be played in any key, to overcome the restrictions brought about by an instrument tuned 'justly'.
Comment: I thought the whole point of the "Well-Tempered Clavier" was that it was a celebration of being able to write for a keyboard in any key?
Comment: Many of the mean-tone  or recirculant temperaments can be played in different keys; there keys do sound slightly different. However, a V-I still sounds like a V-I so temperament isn't as big an effect as it might seem (else equal-temperament wouldn't work.)
Comment: @Tim no, I'm saying that early harpsichords and other keyboard instruments used tempered tunings.  These, being unequal temperaments, sounded better in some keys than others.  Equal temperament is an improvement over other temperaments (in some respects; in others it is worse, as with any compromise).  Nobody ever tuned keyboards using only just thirds and fifths because it is mathematically impossible.
Comment: @Duston it certainly is.  The myth here is that non-well-tempered keyboards were somehow tuned in "just intonation." That is impossible. You can do it using only just fifths, but then the major thirds are even wider than in equal temperament.
Comment: @Duston also, the so-called "well" temperaments allow you to play in every key, but, being unequal, the different keys sound different, and in some keys there may still be unusable "wolf" intervals that Bach will have avoided in certain compositions.  So it was probably not possible to transpose every WTC movement into each of the 11 other possible keys.  By contrast, with a modern keyboard in equal temperament, it is possible.
Answer: I think it comes down to taste at that point for keyboards. Equal temperament is most common though. A few folk guitar players tune there guitars to just intonnation cause it can give a more pure sound. Coming from a wind band experience and also chior we always try for just intonation as it sounds more in tune and overtones sound nicer, but most of the time the musicians just use their ear and it natrually occurs. Practically and to keep things simpler for piano and mallet players sacrificing being slighty out of tune in every key makes their life simpler and allows you to shift from key to key with out nasty sounding intervals. Hope this helps :)
Comment: What does it mean to tune a guitar to just intonation?  Do they tune the b string a just third (5:4 ratio) above the g string?  If they do that, and tune all the fourths to a 4:3 ratio, then the top e string will be vibrating 3.95 times the frequency of the bottom e string instead of 4 times.  Or are you talking about guitars with frets that aren't straight across the neck?
Comment: Also, there are lots of pieces that sink in pitch when you sing them in perfect just intonation.  To keep from going flat you have to modify the intonation slightly.


Nginx: multiple domains not working

Question: I'm trying to have multiple sites on the same server. I have a DigitalOcean VPS with Debian and Nginx. Whatever I go to site1.com, site2.com or site3.com, the site shows the site1.com content. Also, when I type www.site.com, www.site2.com or www.site3.com Chrome shows "This webpage is not available"
On .../sites-available/ and .../sites-enabled/ I have the site1.com, site2.com and site3.com files with the following content. This is from site1.com:
server {
listen 80;
server_name site1.com  www.site1.com;
access_log /opt/www/site1.com/access.log;

root /opt/www/site1.com; }

This is from site2.com:
server {
listen 80;
server_name site2.com  www.site2.com;
access_log /opt/www/site2.com/access.log;

root /opt/www/site2.com; }

And from site3.com:
server {
listen 80;
server_name site3.com  www.site3.com;
access_log /opt/www/site3.com/access.log;

root /opt/www/site3.com; }

What am I doing wrong? As you may predict, yes, this is my first time setting up a Nginx server.
Thanks for your help!
Comment: Did you restart nginx? Did you check your DNS? Those aren't your real domain names...
Comment: Yes, I restarted Nginx and checked my DNS but still doesn't work. I used those names for example :)
Comment: do all the 3 sites DNS name point to the IP addresses configured on DO VPS ?
Answer: You need to tell Nginx which documents to serve from the root domain directories if the directory is requested by the client.
Try adding:
    index index.html index.htm;

below the root declaration. This will tell nginx what file types to serve from the directory
You have to reload/restart nginx after any configuration changes.
For reference:
http://nginx.org/en/docs/http/ngx_http_index_module.html
Comment: I added that line below the root declaration and now it works! Thank you very much! Problem solved.
Comment: Dont forget to accept the answer if it helped you solve your problem.
Comment: `You have to restart nginx after any configuration changes.`. Just to clear things out - you may reload nginx as well.
Comment: @Glueon Yes thanks Glueon I have updated the answer with clarification.

Nginx: multiple domains not working


Como salvar os parâmetros de uma função numa variável?

Question: Eu quero executar esta função coord(343,5,6,2,86528,875433, longitude, latitude, 'COORDENADAS');
Mas eu queria salvar os parâmetros para executar a função depois. Como salvar?
Tentei var x = 343,5,6,2,86528,875433, longitude, latitude, 'COORDENADAS'
mas dá erro.
Comment: Como assim você quer chama-la de novo? Você quer executa-la de novo usando os mesmos parâmetros?
Comment: @KaduAmaral Sim, atualizando um ou dois parametros mas usando a mesma base.
Answer: Você pode acessar o objeto arguments da função:

var args; // Variável no escopo global para salvar os parâmetros
function MinhaFuncao(x, y, z, w, k, j){
    args = arguments; // Salva os parâmetros passado
    console.log(arguments);
    document.getElementById('log').innerHTML = arguments[1];
}
//; Executa função primeira vez
MinhaFuncao(1, 'arroz', 3.14, 'macarrão', true, 'joão', 'picolé', 'maracujá');

// Alterando o terceiro argumento
args[2] = 'Feijão';

// Pode chama-la novamente usando o apply:
if (args != undefined)
   MinhaFuncao.apply(this, args);
   // Primeiro parâmentro é o contexto,
   // o segundo é o array de argumentos

Retorno do objeto arguments:
Arguments[8] {
  0: 1
  1: "arroz"
  2: 3.14
  3: "macarrão"
  4: true
  5: "joão"
  6: "picolé"
  7: "maracujá"
}

Comment: Interessante, contrapondo que não foi necessário salvar separadamente e é possível salvar e editar, obrigado!
Comment: Como `arguments` é um tipo especial, eu recomendaria salvar como array: `args = Array.prototype.slice.call(arguments, 0);`
Comment: Tem algum motivo em especial ou situação que apenas atribuí-lo diretamente seria um problema @bfavaretto?
Comment: É que geralmente não se espera encontrar um objeto tipo Arguments fora de uma função.
Answer: Seria assim:
var p1 = 343, p2 = 5, p3 = 6, p4 = 2, p5 = 86528, p6 = 875433,
    p7 = longitude, p8 = latitude, p9 = 'COORDENADAS';

Coloquei no GitHub para referência futura.
Note que você tem 9 parâmetros aí, precisa salvar em 9 variáveis. Poderia usar o array também, mas acho que é até melhor neste caso que sejam 9 variáveis. A única coisa que deveria mudar em relação ao que eu fiz é dar nomes mais significativos para as variáveis, indicando o que é cada parâmetro.
Você pode achar que não é uma boa solução, mas não vejo uma melhor, apesar de existirem outras criativas. Na verdade não sei porque precisa disto, talvez você nem tenha esta necessidade. Não faz muito sentido fazer isto. É possível que todo o design da aplicação esteja errado.
Comment: Sim, acertou, até lhe entendo. Mas é uma requisição que vai pro servidor e foi rejeitada, ou seja eu preciso reenvia-la com os mesmos parametros mas atualizando alguns para que ela nao seja novamente rejeitada, não vejo um problema de design, se tiver solução melhor.. Mesmo assim obrigado!


Mixed-effect logistic regression in R - questions

Question: I am new to R, and don't see these questions answered anywhere in documentation (though I could be wrong).

I am using the following nomenclature to run my mixed-effects logistic regression, based on instructions from another site:
output <- glmer(DV ~ IV1 + IV2 + (1 | RE), family = binomial, nAGQ = 10)
RE is a factor with several levels.
This works. But I'm wondering why it's necessary to use the (1 | RE) syntax instead of just DV~IV1+IV2 | RE.
I am running two mixed effects logistic regressions. On one of them I can view the random effects intercepts using ranef(). But I get all 0s when I run ranef on the output of the other one. Both regressions/data are ostensibly the same. What do all 0s for the random effects intercepts mean?
Answer:
(1|RE) specifies that you want the intercept to vary randomly across levels of RE. You could also specify (1+IV1|RE) for example if you wanted the intercept and the slope for IV1 to vary randomly.
Perhaps there is no considerable variation in the intercept across RE that can be picked up in the second data set. Does the basic fit output (summary(fitObject)) suggest no variation on that intercept in the second model?

That's about all that can be said without more information.
Comment: This was enormously helpful. In regards to question 2, I just looked at the `summary()` output for the model, and indeed the variance is 0 and SD 0 for the random effects variable. I'm surprised by this; I think I need to go back and make sure the data in my data matrix is lined up correctly.


How to prove that if $\sum a_{n}^2$ converges, $\sum |a_{n}|$ also converges?

Question: I can prove the converse, but not this one. Actually, it's a prove or disprove question. Any hints?
Comment: This is obviously false. A counterexample is $a_n=1/n$.
Answer: The assertion is false ! Here is a well-known counterexample: $a_n = \frac{1}{n}$. $\sum_n a_n$ diverges and $\sum_n a_n^2$ converges.


I cant import the Zxing library

Question: I am working with Unity to make app interfaces and I need to make a QR code reader in my app and the tutorial that I've watched used a library called ZXing, but when I try to import it with using ZXing; it gives an error saying that this library doesn't exist, how can I import it?
Comment: https://learn.microsoft.com/en-us/nuget/quickstart/install-and-use-a-package-in-visual-studio
Answer: Havr you installed ZXing via the NuGet paket manager? There is a C# implementation called ZXing.Net. The easiest way to install is directly via Visual Studio.

I cant import the Zxing library


How to break styled text into pages in Android?

Question: I have a long text which I want to break into multiple pages. Also I need a way to style this text.
Answer: UPDATE: I created sample application, that shows how to use PageSplitter.
How it works? Example application (Russian) - Cleverum. You need only PageSplitter class. Other code shows you how to use this class.
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.style.StyleSpan;

import java.util.ArrayList;
import java.util.List;

public class PageSplitter {
    private final int pageWidth;
    private final int pageHeight;
    private final float lineSpacingMultiplier;
    private final int lineSpacingExtra;
    private final List<CharSequence> pages = new ArrayList<CharSequence>();
    private SpannableStringBuilder currentLine = new SpannableStringBuilder();
    private SpannableStringBuilder currentPage = new SpannableStringBuilder();
    private int currentLineHeight;
    private int pageContentHeight;
    private int currentLineWidth;
    private int textLineHeight;

    public PageSplitter(int pageWidth, int pageHeight, float lineSpacingMultiplier, int lineSpacingExtra) {
        this.pageWidth = pageWidth;
        this.pageHeight = pageHeight;
        this.lineSpacingMultiplier = lineSpacingMultiplier;
        this.lineSpacingExtra = lineSpacingExtra;
    }

    public void append(String text, TextPaint textPaint) {
        textLineHeight = (int) Math.ceil(textPaint.getFontMetrics(null) * lineSpacingMultiplier + lineSpacingExtra);
        String[] paragraphs = text.split("\n", -1);
        int i;
        for (i = 0; i < paragraphs.length - 1; i++) {
            appendText(paragraphs[i], textPaint);
            appendNewLine();
        }
        appendText(paragraphs[i], textPaint);
    }

    private void appendText(String text, TextPaint textPaint) {
        String[] words = text.split(" ", -1);
        int i;
        for (i = 0; i < words.length - 1; i++) {
            appendWord(words[i] + " ", textPaint);
        }
        appendWord(words[i], textPaint);
    }

    private void appendNewLine() {
        currentLine.append("\n");
        checkForPageEnd();
        appendLineToPage(textLineHeight);
    }

    private void checkForPageEnd() {
        if (pageContentHeight + currentLineHeight > pageHeight) {
            pages.add(currentPage);
            currentPage = new SpannableStringBuilder();
            pageContentHeight = 0;
        }
    }

    private void appendWord(String appendedText, TextPaint textPaint) {
        int textWidth = (int) Math.ceil(textPaint.measureText(appendedText));
        if (currentLineWidth + textWidth >= pageWidth) {
            checkForPageEnd();
            appendLineToPage(textLineHeight);
        }
        appendTextToLine(appendedText, textPaint, textWidth);
    }

    private void appendLineToPage(int textLineHeight) {
        currentPage.append(currentLine);
        pageContentHeight += currentLineHeight;

        currentLine = new SpannableStringBuilder();
        currentLineHeight = textLineHeight;
        currentLineWidth = 0;
    }

    private void appendTextToLine(String appendedText, TextPaint textPaint, int textWidth) {
        currentLineHeight = Math.max(currentLineHeight, textLineHeight);
        currentLine.append(renderToSpannable(appendedText, textPaint));
        currentLineWidth += textWidth;
    }

    public List<CharSequence> getPages() {
        List<CharSequence> copyPages = new ArrayList<CharSequence>(pages);
        SpannableStringBuilder lastPage = new SpannableStringBuilder(currentPage);
        if (pageContentHeight + currentLineHeight > pageHeight) {
            copyPages.add(lastPage);
            lastPage = new SpannableStringBuilder();
        }
        lastPage.append(currentLine);
        copyPages.add(lastPage);
        return copyPages;
    }

    private SpannableString renderToSpannable(String text, TextPaint textPaint) {
        SpannableString spannable = new SpannableString(text);

        if (textPaint.isFakeBoldText()) {
            spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, spannable.length(), 0);
        }
        return spannable;
    }
}

First, you have to create PageSplitter object with pageWidth and pageHeight (in pixels) which you can get from View.getWidth() and View.getHeight():
ViewPager pagesView = (ViewPager) findViewById(R.id.pages);
PageSplitter pageSplitter = new PageSplitter(pagesView.getWidth(), pagesView.getHeight(), 1, 0);

lineSpacingMultiplier and lineSpacingExtra must have same values as lineSpacingMultiplier and lineSpacingExtra attributes of TextViews which will keep page texts.
Using PageSplitter.append() method you can append text which will be measured with textPaint:
TextPaint textPaint = new TextPaint();
textPaint.setTextSize(getResources().getDimension(R.dimen.text_size));
for (int i = 0; i < 1000; i++) {
    pageSplitter.append("Hello, ", textPaint);
    textPaint.setFakeBoldText(true);
    pageSplitter.append("world", textPaint);
    textPaint.setFakeBoldText(false);
    pageSplitter.append("! ", textPaint);
    if ((i + 1) % 200 == 0) {
        pageSplitter.append("\n", textPaint);
    }
}

Then by using PageSplitter.getPages() method you can get original text splitted to pages and put each of them into TextView:
pagesView.setAdapter(new TextPagerAdapter(getSupportFragmentManager(), pageSplitter.getPages()));

TextPagerAdapter:
public class TextPagerAdapter extends FragmentPagerAdapter {
    private final List<CharSequence> pageTexts;

    public TextPagerAdapter(FragmentManager fm, List<CharSequence> pageTexts) {
        super(fm);
        this.pageTexts = pageTexts;
    }

    @Override
    public Fragment getItem(int i) {
        return PageFragment.newInstance(pageTexts.get(i));
    }

    @Override
    public int getCount() {
        return pageTexts.size();
    }
}

PageFragment:
public class PageFragment extends Fragment {
    private final static String PAGE_TEXT = "PAGE_TEXT";

    public static PageFragment newInstance(CharSequence pageText) {
        PageFragment frag = new PageFragment();
        Bundle args = new Bundle();
        args.putCharSequence(PAGE_TEXT, pageText);
        frag.setArguments(args);
        return frag;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        CharSequence text = getArguments().getCharSequence(PAGE_TEXT);
        TextView pageView = (TextView) inflater.inflate(R.layout.page, container, false);
        pageView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_size));
        pageView.setText(text);
        return pageView;
    }
}

where R.layout.page is
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:textSize="@dimen/text_size"
          android:lineSpacingMultiplier="1"
          android:lineSpacingExtra="0sp">
</TextView>

PageSplitter.renderToSpannable() method wraps text to SpannableString according to textPaint settings. In current method implementation I consider only TextPaint.isFakeBoldText() property, but you can also apply other properties. For example, you can apply TextPaint.getTextSize() property with AbsoluteSizeSpan.
Comment: @hugocarlmartin You can use Html.fromHtml() method to get Spanned string from html markup. Then you can write your own PageSplitter that has  append(Spanned) method instead of append(String, TextPaint). But it's not trivial task.
Comment: will this ensure that the pages are an exact fit on any display screen? I am trying something similar using textpaint but my issue is in fitting the text exactly in the screen so as  no vertical scroll is needed and also that word wrapping happens so as no word is split between pages. You can see my solution in the thread http://stackoverflow.com/questions/20830160/string-processing-very-slow-in-new-android-version4-3
Comment: I fixed few bugs and updated source code to latest version.
This code works perfectly in application https://play.google.com/store/apps/details?id=com.codeoverdrive.cleverum.philosophy
Comment: have you try with big html file (1.4mb), how long it take??
Comment: @dreamfighter No, I think it would take significant time. What you can do is to split big file to pages with PageSplitter and save them in application folder when you open your application at first time. And next time you open application use these pages.
Comment: Would it be possible to get this as a project so that I can see all the parts?
Comment: @hugocarlmartin Yes, will be soon.
Comment: While waiting for the project I was trying to implement the code above. I got "The method getObjectStorage() is undefined for the type PageFragment". What am I doing wrong?
Comment: @hugocarlmartin See update. I created GitHub repo. And forget about getObjectStorage() - that was a newbie crap.
Comment: Thx, I look into it straight away.
Comment: Do you know if its possible to use this with html? A Spanned text or something?
Comment: @hugocarlmartin I think that it is possible but you need to adapt my solution to your case. I will try to do this when I will have a time.
Comment: I've tried but as soon as I use  tags it gets crazy.
Comment: I have downloaded the sample application, compiled it without any problems, however it crashes when running it. Can anybody help me? Here is a screenshot https://www.dropbox.com/s/17ps8ih35bkkk47/pagesplitter.jpg?dl=0
Comment: I had to create a new android project and add all the files manually to solve this problem as I don't understand what happened on the screenshot and how to resolve it.
Comment: @Ivan I've updated project to use latest Gradle Android plugin and Android SDK. Try to open it in Android Studio. It should compile and run without any issues.
Comment: I dont have studio cause I use eclipse. Also I managed to run the sample already. Do you have updated PageSplitter to handle Html? Would be so helpful to find such code...
Comment: @Ivan No, but you are free to contribute. I'll be waiting for your pull request :-)
Comment: Good solution! I have a [similar one](http://stackoverflow.com/questions/31837840/paginating-text-in-android/32096884#32096884), just a bit "shorter")
Comment: @mixel Great sample, thanks a lot, but unfortunately it don't break the last line to another page if it's shorter than TextView width(


Problems adding new domain to httpd.conf file

Question: So, I just bought a brand new domain. I set up my dns records with the host (godaddy) but something strange happens on my server.
I've added this to the httpd.conf file:
<VirtualHost *:80>
ServerName www.newdomainname.tld
DocumentRoot /usr/share/roundcube/
</VirtualHost>

But somehow I'm redirected to the root of my server.
Then I tried adding this under the entry for the new domain name:
<VirtualHost *:80>
ServerName shop.olddomainname.tld
DocumentRoot /usr/share/roundcube/
</VirtualHost>

And it worked without any problems.
What's going on? Am I forgetting anything?
Answer: Assuming this is your first additional domain, do you have a NameVirtualHost outside of the VirtualHosts section?
NameVirtualHost *:80

The setup for multi VirtualHosts is documented nicely at http://httpd.apache.org/docs/2.2/vhosts/examples.html
A good way to figure out what you have configured is to run
/usr/local/apache2/bin/httpd -S

Which will return all directives currently configured.
Comment: I had that in the ports.conf file, but not in the httpd.conf file. I also have a few files in sites-enabled/, but don't really know what files get loaded at what time...
Comment: Okay, you can figure out what the VirtualHost setting are by running httpd -S (added to original answer).
Answer: On Ubuntu you should define your virtual hosts in /etc/apache2/sites-available.  These get linked to the /etc/apache2/sites-enabled by the a2ensite command.
You may want to examine the existing default site and possibly disable it with the a2dissite command.  The first defined site will be treated as the default site by apache.
As your definitions are the same, you may just want one site with a serveralias defined.


Como criar algoritmo de árvore de natal em PHP

Question: Estou fazendo o seguinte código, porém o PHP não soma e atribui zero:
<?php
$linha = "*";
for($i = 0; $i < 6; $i++){
    echo($linha)."
";
    $linha += "*"; //aqui o php nao soma
}
?>

A saída desse código era pra ser:
*
**
***
****

Porém sai assim:
0
0
0
0
0
0

Alguém pode me ajudar?
Comment: Obrigado Marcelo Bonifazio por editar
Comment: += como assim???
Answer: Você esta querendo concatenar strings, para isso você usa o . não o + em php.
Basta alterar a seguinte linha $linha += "*"; para $linha .= "*";:
$linha = "*";
for($i = 0; $i < 6; $i++){
    echo($linha)."
";
    $linha .= "*";
}

Uma breve explicação:
O operador .= em PHP é utilizado para concatenação de variáveis, exp: $a .= $b pode ser reescrito como: $a = $a . $b. E é esperado que se tenha o seguinte: string .= string.
O operador += em PHP é utilizado para a operação aritmética de soma de variáveis, exp: $a += $b pode ser reescrito como: $a = $a + $b. E é esperado que se tenha o seguinte: integer += integer.
Desse modo, com o operador aritmético +=, por mais que o valor esteja em parentes, dando a entender que é uma string e não um valor numérico, é feita a conversão de string para integer. Como pode ser visto com o seguinte teste:
echo "Teste com .=

";
$linha = "Isso é";
echo "Valor antigo: ". $linha."
Tipo antigo: ".gettype($linha)."

";
$linha .= " um teste";
echo "Novo valor: ". $linha."
Tipo novo: ".gettype($linha)."

";
echo "Teste com +=

";
$linha = "Isso é";
echo "Valor antigo: ". $linha."
Tipo antigo: ".gettype($linha)."

";
$linha += " um teste";
echo "Novo valor: ". $linha."
Tipo novo: ".gettype($linha)."

";
echo "Outro teste com +=

";
$linha = "4";
echo "Valor antigo: ". $linha."
Tipo antigo: ".gettype($linha)."

";
$linha += "10";
echo "Novo valor: ". $linha."
Tipo novo: ".gettype($linha)."
";

Isso deve imprimir:

Teste com .=
Valor antigo: Isso é  Tipo antigo: string
Novo valor: Isso é um teste  Tipo novo: string
Teste com +=
Valor antigo: Isso é  Tipo antigo: string
Novo valor: 0  Tipo novo: integer
Outro teste com +=
Valor antigo: 4  Tipo antigo: string
Novo valor: 14  Tipo novo: integer
Comment: @EversonSouzadeAraujo se a resposta resolveu inteiramente sua pergunta, lembre-se de votar positivo e marcar a pergunta como aceita, clicando no sinal verde abaixo do mecanismo de votação.
Comment: era isso mesmo  @gustavox deu certo, obg
Comment: Obrigado Marcelo Bonifazio
Comment: quando clico diz que não tenho permissão
Comment: @EversonSouzadeAraujo Pra votar você já tem, acho que pra aceitar a resposta tem um tempo mínimo que tem que esperar. Essa foi bem rápida né. :)


How to get Docker desktop on Ubuntu?

Question: I am new to Docker/Kubernetes and trying to see if there is a way to get 'Docker Desktop' like functionality on Ubuntu, which is my primary development machine. All I know from my search is that the 'Docker Desktop' is only from Windows and Mac.
It contains many useful tools bundled together as below which is great for someone like me who is new to the ecosystem :

Docker Desktop includes Docker Engine, Docker CLI client, Docker
Compose, Notary, Kubernetes, and Credential Helper.

Is there a way to get docker desktop for Linux or is there anything similar?
Comment: "Is there a way to get docker desktop for Linux" -- no there is not.  "Docker Desktop" is a Windows/Mac thing as more in needed on those platforms.  They essentially shield an entire virtual machine installation.  None of that is needed on Linux.
Comment: Unless I am mistaken, `docker.io` is the main package on Ubuntu:  https://packages.ubuntu.com/source/focal/docker.io
Comment: @DirkEddelbuettel That may have been the case in 2020, but I think this has chaged now: https://docs.docker.com/desktop/install/ubuntu/
Comment: `apt-get install docker-compose` gets you "Docker Engine", Docker CLI and Docker Compose.
Comment: Things to indeed change over time, such is the path of mankind.  I glanced at the desktop offering, and (very personally speaking) decided it's insane that it insist on shimming a VM between the kernel and itself .... to "compatible with the experience on other OSs". Thanks but not thanks.  But good to have choice, I am sure some people may enjoy having it.
Comment: As mentioned by @AndrewS in the comment, Docker Desktop for Linux has been released and no longer a `tech preview`. Link to the announcement: https://www.docker.com/blog/the-magic-of-docker-desktop-is-now-available-on-linux/
Comment: @DhavalD Good point. I have updated [my 2022 February answer](https://stackoverflow.com/a/70967611/6309) below.
Answer: Currently, docker desktop supported Mac, Windows only.
For ubuntu, you can use Docker Engine with Portainer (Web-based).
Other options:

LazyDocker

2022 Update:
Docker Desktop for Linux (Tech Preview)
Get more info about it at this issuse
It is currently only available as a .deb for Ubuntu 21.04, 21.10 and Debian distributions.
Comment: It's also part of Ubuntu itself:  https://packages.ubuntu.com/source/focal/docker.io  So just do `sudo apt install docker.io`.
Comment: Thank you for your responses. I was looking for a complete package which has docker and Kubernetes and all other essentials like 'Docker desktop' has, but I think that kind of an option doesn't exist for Linux. I ended up installing each ( Docker and Kubernetes ) separately using `sudo wget -qO- https://get.docker.com | sh` for Docker and [Minikube](https://minikube.sigs.k8s.io/docs/start/) for Kubernetes.
Comment: `DockStation` and `Kitematic` are deprecated.
Answer: Docker announced in a blog post (16-Sep-2021):

Docker Desktop for Linux will be available to all developers through
the free Docker Personal and paid Docker Pro, Team, and Business
subscriptions. If you're interested in early access please sign-up for
our developer preview program.

That's good news! While the Desktop features are not really "required" on Linux, I've grown to like the user interface and not needing to behave differently on the Linux platform is very welcome!
Answer: Feb. 2022: there is now an official documentation (for what is still a Tech Preview)
Oct. 2022: Docker Desktop 4.12 has been released, and the Linux distribution is no longer a tech preview.

Docker Desktop for Linux

<code>curl https://desktop-stage.docker.com/linux/main/amd64/74134/docker-desktop.deb --output docker-desktop.deb
sudo apt install ./docker-desktop.deb

systemctl --user start docker-desktop
systemctl --user enable docker-desktop

journalctl --user --unit=docker-desktop
</code>
Answer: In fact, there is a Docker Desktop for Linux, but not for all distros. Please visit the official documentation for more detailed explanation and for further changes. Since it is an experimental version, you should read the known issues before installing.
If you are interested, you can also visit their public roadmap
The short tale is this:

Docker Desktop for Linux (Tech Preview)
(...) This Tech Preview is
aimed at early adopters who would like to try an experimental build of Docker Desktop for Linux and provide feedback.(...) Download and install
Docker Desktop for Linux is currently available on Ubuntu 21.04, 21.10 and Debian distributions.

This version runs a Virtual Machine.
I strongly recommend to read the provided article
Comment: Yes, see my [February answer](https://stackoverflow.com/a/70967611/6309) for installation.

How to get Docker desktop on Ubuntu?


Does a solution to this functional equation exist and if so can we construct it?

Question: For $x\geq 0 $ we have $f(x) +xf(1/x) = x/(1+x)$ as well as the conditions $\lim_{x\rightarrow 0} f(x) = 0$ and $\lim_{x\rightarrow \infty} f(x) = 0$. Clearly $f(1) = \frac{1}{4}$. What is the solution, if it exists at all? I have no clue how to tackle this problem. Or are the information not enough to uniquely determine a solution? Thanks.
Answer: The solution does exist.
$$
f(x)=\frac{x}{\left(1+x\right)^2}
$$
satisfies the equation:
$$
f(x)+x\,f\left(\frac{1}{x}\right)=
\frac{x}{\left(x+1\right)^2}+\frac{1}{\left(1+\frac{1}{x}\right)^2}=
\frac{x+x^2}{\left(x+1\right)^2}=
\frac{x(x+1)}{\left(x+1\right)^2}=\frac{x}{x+1}
$$
as required. Unfortunetely, I came up with it by pure guessing, based on the asymptotic behaviour of $f$ near $0$ and $\infty$. I'll try to come up with some more systematic approach.
Comment: Thank you! That solution works. I am curious to see a systematic way. Is that solution unique? mercio's answer suggests that there are many solutions.
Comment: I very much doubt if this is unique. I don't have time right now to think about it more, but I'd like to think about it more later.
Answer: For any $x > 0$, we have two statements involving $f(x)$ and $f(1/x)$ by applying the equation at $x$ and at $1/x$, and we should make sure that it says the same thing :
At $x$ we get $f(x) + xf(1/x) = x/(1+x)$.
At $1/x$ we get $f(1/x) + (1/x)f(x) = (1/x)/(1+1/x) = 1/(x+1)$, which is equivalent to $xf(1/x) + f(x) = x/(x+1)$ because $ x \neq 0$.
So the two statements are equivalent.
Since your functional equation relates values at $x$ with values at $1/x$, you can pick values of $f$ arbitrarily on $(0;1]$ and this will determine $f$ on $[1;\infty)$ by applying the functional equation.
With your conditions, you need $\lim_{x \to 0} f(0)=0,f(1)=1/4$, and
$\lim_{x \to \infty} f(x) = 0$.
This means $0 = \lim_{x \to \infty} f(x) = \lim_{x \to 0} f(1/x) = \lim_{x \to 0} 1/(1+x) - f(x)/x = 1 - \lim_{x \to 0} f(x)/x$. So this says that $f'(0)$ exists and is $1$.
Therefore, if you pick any function $f : [0;1] \to \Bbb R$ with $f(0)=0,f'(0)=1,f(1)=1/4$ and extend $f$ on $[1;\infty)$ with $f(x) = x/(1+x)-xf(1/x)$, you obtain a solution to the functional equation.
Comment: Minor mistake: $f'(0)=1$, not $-1$.
Comment: Thank you @mercio. That shows that this does not uniquely determine a function but rather gives one freedom to choose the function in the bulk, that is away from 0 and 1.
Answer: I played with some intuitive substitutions simplifying the problem stepwise, first define
$$f(x)=(1+x)g(x)$$
which leads to
$$g(x)+g(1/x)=\frac{x}{(1+x)^2}$$
Second, substitute
$$g(x)=\frac{1}{2}\frac{x}{(1+x)^2}+h(x)$$ and you get
$$h(x)+h(1/x)=0.\qquad(1)$$
The solution of this is $h(x)=c(x)\ln x$ where $c(x)$ is an arbitrary function which satisfies
$$c(x)-c(1/x)=0.\qquad (2)$$
This leads to
$$f(x)=\frac{x}{2(1+x)}+(1+x)c(x)\ln x.$$
Now let's come back to $c(x)$. (2) is ensured when choosing
$$c(x)=d(x)+d(1/x)$$ with an arbitrary function $d(x)$.
Your side conditions now lead to the following remaining question:
Find $g(x)$ such that
$$\lim_{x\to 0} (1+x)\left(d(x)+d(1/x)\right)\ln x =0$$
$$\lim_{x\to \infty} (1+x)\left(d(x)+d(1/x)\right)\ln x =-\frac{1}{2}$$
With your side-codition $f(0)=0$ leads to $c=0$, but the second can't be satisfied.
Comment: That does not satisfy $lim_{x\to\infty}f(x)=0$
Comment: Yeah, thanks, I was already correcting this.
Comment: If we replace $d(x) + d(1/x)$ in the last two equations by $c(x)$. Why can't we have a function that has this properties as well as $c(x) -c(1/x) = 0$?


dynamically placing a value in django query

Question: I have following code:
hotels = models.Hotel.objects.filter(
            wed=True,
            county=hotel_main.county.id,
            subscriptions__end_date__gte=datetime.date.today(),
            subscriptions__enquiry_count__lte=F('subscriptions__tier__enquiry_limit'),
        ).filter(Q(x=TRUE|Q(y=True)).distinct()

And i have a list test = ['x','y','z','w']
The values of filter changes dynamically, so I use something like:
filter(Q(test[0]=TRUE|Q(test[3]=True))

which changes dynamically, but when I did that I got the following error:
Keyword can't be an expression

I know i can't use it there but let me know how to achieve this... Thank you!
Edit
I did as Chris suggested:
test[1] = {x: True}

and in my filter, I did as follows
filter(Q(test[1])).

it gave me below error:
need more than 1 value to unpack

Answer: Use a dictionary to set the keys and then expand it into kwargs with **, i.e.:
Q(**{test[0]: True})

Comment: can you make it bit more cleat


$4x^2-5xy+4y^2=19$ with $Z=x^2+y^2$, find $\dfrac1{Z_{\max}}+\dfrac1{Z_{\min}}$

Question: I have no idea how to approach this question at all. I've tried to find the maximum and minimum of the quadratic but i am too confused on what to do afterwards.
Comment: Which calculus course is this for? Have you learned about the method of Lagrange multipliers?
Comment: I am learning this on my own, we haven't been taught calculus yet at school and no I haven't learned about Lagrange multipliers. Could you expand please.
Comment: They are a technique for optimizing of a function such as $Z=x^2+y^2$, subject to a constraint like $4x^2-5xy+4y^2=19$. The idea is that your constraint forms a curve, and $Z$ is only optimized on that curve if its direction of greatest increase is perpendicular to the curve at that point (since otherwise you could move along the curve to increase or decrease $Z$). My personal favourite introduction to Lagrange multipliers is in Paul's online math notes: http://tutorial.math.lamar.edu/Classes/CalcIII/LagrangeMultipliers.aspx
Answer:
From the given equation $\,xy = \cfrac{4(x^2+y^2) - 19}{5} = \cfrac{4 Z - 19}{5}\,$. But for $\forall x,y \in \mathbb{R}$ the inequality holds $\,xy \le \cfrac{1}{2}(x^2+y^2)\,$ so $\,\cfrac{4 Z - 19}{5} \le \cfrac{Z}{2} \iff \boxed{Z \le \cfrac{38}{3}}\,$
$0 \le (x+y)^2 = x^2+y^2+2xy = Z + 2 \cfrac{4 Z - 19}{5}=\cfrac{13 Z - 38}{5} \implies \boxed{Z \ge \cfrac{38}{13}}$

$Z_{min}=\cfrac{38}{13}$ is attained for $x=-y=\sqrt{\cfrac{19}{13}}$ and $Z_{max}=\cfrac{38}{3}$ is attained for $x=y=\sqrt{\cfrac{19}{3}}\,$.
Answer: Without Lagrange multipliers (but with trigonometry). Use polar coordinates:
$x=\sqrt Z\cos\theta$
$y=\sqrt Z\sin\theta$
$xy=Z\sin\theta\cos\theta=\frac{Z}{2}\sin(2\theta)$
From your equation you get $\frac{1}{z}=\frac{4}{19}-\frac{5\sin(2\theta)}{38}$
As $\sin$ takes values between $-1$ and $1$:
So $\frac{1}{z_{min}}+\frac{1}{z_{max}}=2\cdot\frac{4}{19}=\frac{8}{19}$
Answer: Let $x=\sqrt{z}\cos B, y=\sqrt{z}\sin B$, hence we get
$$4z-\frac{5z}{2}\sin\left (2B  \right )=19$$
for $-1\leq \sin\left ( 2B \right )\leq 1$ and $\displaystyle z=\frac{19}{4-\dfrac{5}{2}\sin\left ( 2B \right )}$.
Now the answer will follow.
Comment: How would you follow on from this, sorry i'm not very good at calculus.
Comment: @Julian Lopez  using $-1\leq \sin\left ( 2B \right )\leq 1$ and you will get the maximum and minimum of $z$.
Answer: $$4x^2-5xy+4y^2-19=0$$
By quadratic formula we have,
$$x=\frac{1}{8} (5 y\pm \sqrt{304-39y^2})$$
So,
$$z=y^2+\frac{1}{64} (5 y\pm \sqrt{304-39y^2})^2$$
Now take derivative, set it to zero, and examine sign changes.


How to add the header in autogenerated bindings code by qdbusxml2cpp?

Question: $qdbusxml2cpp -v -c CustomIf -p customif.h:customif.cpp org.item.custom.xml
org.item.custom.xml
<node>
<interface name="org.pace.custom">
<method name="Send_Custom_Msg">
<arg name="msg" type="a(ii)" direction="in"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="Message"/>
</method>
<signal name="LateEvent">
<arg name="eventkind" type="s" direction="out"/>
</signal>
</interface>
</node>

How to add the header - message.h in the generated adaptor customif.h? I don't want to add manually into it as #include "message.h", but actually want the qdbusxml2cpp to add the inclusion.
Comment: $ qdbusxml2cpp -c  CustomIfAdaptor -a -i  customifadaptor.h:customifadaptor.cpp org.pace.custom.xml In this command, where to add message.h
Answer: Use the following option:
-i <filename> Add #include to the output

So, this would be the corresponding command:
qdbusxml2cpp -v -i message.h -c CustomIf -p customif.h:customif.cpp org.item.custom.xml


Comparing a database date field with date

Question: Compare database date with a date
I want to check the database date field is less than 5 days or not
I tried with Carbon class which output values in integer and MySQL database returns value in string or object
$ticket = Tickets::select('created_at')->where('id','=',$id)->get();

I want to check if this result of date is less than 5 days or not
for i.e.  if the current result date is 01-05-2019 then message should be "ticket is older than 5 days"
Comment: What's column is date type to compare?
Comment: the type is timestamp
Comment: well actually i want to check the ticket date is older than 5 days or not
Comment: Just to make sure I understand your question, you still want to get the Ticket whether it's older than 5 days or not? Can you show how you're wanting to displaying the message e.g. pass it to a blade file or return just that string from the controller?
Comment: yes return string from controller
Answer: I think you can just change the current date to 5 days less and compare it
  $date = new DateTime;
  $date->modify('-5 days');
  $formatted_date = $date->format('Y-m-d H:i:s');

  $ticket = Tickets::where('created_at', $formatted_date)->where('id','=',$id)->first();

if you want to ignore the timestamp and compare date only you may need to do
 $formatted_date = $date->format('Y-m-d');
 $ticket = Tickets::where(Date('created_at'), $formatted_date)->where('id','=',$id)->first();

I have not tested it, but it seems these code should work fine for you.
Answer: I have created the model scope
More about scopes:

https://laravel.com/docs/5.8/eloquent#query-scopes
https://medium.com/@janaksan_/using-scope-with-laravel-7c80dd6a2c3d

So add this scope method to your model that is Ticket
   /**
     * Scope a query to only include the last n days records
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeWhereDateOccurs($query, $fieldName, $upToDate,$noOfDays = 5)
    {
        $startFrom = \Illuminate\Support\Carbon::parse($upToDate)->toDateTimeString();
        $endUpTo =  \Illuminate\Support\Carbon::createFromDate( $startFrom)->subDays( $noOfDays)->toDateTimeString();

        return $query->whereDate($fieldName, '>=', $startFrom)->whereDate($fieldName, '<=', $endUpTo);
    }

So now we are done with the method
Now in your controller
$ticket = Tickets::where('id','=',$id)
                  ->WhereDateOccurs( 'created_at', '01-05-2019',5)
                  ->get();

and here is the query log generated
SELECT *
FROM   `tickets`
WHERE  Date(`created_at`) >= ?
       AND Date(`created_at`) <= ?
       AND `id` = ?
       AND `tickets`.`deleted_at` IS NULL

and I am using softdeletes so the  deleted_at IS NULL is added to all the query builder.
Comment: It looks like you have posted four answers (including this one) by copying and pasting. I normally flag as duplicates, but you appear to have tailored these a bit, so some of them will escape in terms of uniqueness. In general, please do not go looking for opportunity to re-paste your answers - it copies+pastes errors too, and the answers will start to diverge over time.
Comment: The questions are [one](https://stackoverflow.com/a/56037803), [two](https://stackoverflow.com/a/55861536), [three](https://stackoverflow.com/a/55585749), [four](https://stackoverflow.com/a/55683607).
Answer: This should work for you. This will return the date difference from today.
$ticket = Tickets::selectRaw('abs(datediff(created_at,"'.\Carbon\Carbon::now().'")) as day')->where('id','=',$id)->first();


Algebraic manipulation of binomial coefficients near the middle of their line in Pascal's triangle

Question: Prove, by algebraic manipulation, that:
\[ {{2n} \choose {n}} + {{2n} \choose {n+1}}={1\over2} {{2n+2} \choose {n+1}} \]
Comment: This just looks like a special case of pascals identity, Jillian you should slow down on the question posting and try to research some of these yourself, you could have found an algebraic proof on wikipedia, which I found after several searchs
Comment: I don't really like the notation used, and its not typed using math tex, if you could refine your question perhaps with binomial coeifficents, typed correctly, I could help you
Comment: If you're going to go on a Math forum just to bring people down, perhaps rethink why you're here.
Comment: There's a button called "Edit" @Ethan
Answer: $$\binom{2n}{n}+\binom{2n}{n+1}=\frac{(2n)!}{(n!)^2}+\frac{(2n)!}{(n+1)!(n-1)!}=\frac{(2n)!}{((n-1)!)^2}\left(\frac{1}{n^2}+\frac{1}{n(n+1)}\right)=$$
$$=\frac{(2n)!}{((n-1)!)^2}\frac{2n+1}{n^2(n+1)}=\frac{(2n+1)!}{n!(n+1)!}$$
Try to complete the few steps left now...
Answer: $$\binom m r+\binom m{r+1}=\frac{m!}{(m-r)! r!}+\frac{m!}{(m-r-1)! (r+1)!}=\frac{r+1}{m+1}\frac{(m+1)!}{\{(m+1)-(r+1)\}! (r+1)!}+\frac{m-r}{m+1}\frac{(m+1)!}{\{m-(r+1)\}! (r+1)!}$$
$$=\binom{m+1}{r+1}\cdot\left(\frac{r+1}{m+1}+\frac{m-r}{m+1}\right)=\binom{m+1}{r+1}$$
Putting $m=2n,r=n,$
$$\binom {2n} n+\binom {2n}{n+1}=\binom{2n+1}{n+1}=\frac{(2n+1)!}{n!(n+1)!}=\frac1 2 \frac{(2n+2)\cdot (2n+1)!}{(n+1)\cdot n!(n+1)!}=\frac1 2\frac{(2n+2)!}{(n+1)!(n+1)!}=\frac1 2\binom{2n+2}{n+1}$$
Answer: A general method for such identities, similar to what DonAntonio wrote but requiring less thought, is to write the binomial coefficients as fractions of factorials and clear all the denominators.  (In the case at hand you'll multiply by $2((n+1)!)^2$.)  Then cancel the biggest common factors you can find. What's left should be fairly easy to compute.
For this particular problem, though, a nicer-looking (but perhaps harder to find) alternative is essentially what Ethan suggested in a comment.  Multiply both sides of the proposed equation by 2.  (If you get the impression that I really don't like fractions, you're right.) On the left, use the fact that $C(2n,n+1)=C(2n,n-1)$ to replace one of the two $C(2n,n+1)$'s.  That will set you up for three applications of Pascal's identity, which convert the left side to the right.
Answer: $2n \choose n$ and $2n \choose n+1$ are consecutive terms in the same row of Pascal's triangle. Because each entry in Pascal's triangle is the sum of the two entries above it, this implies that* $${2n\choose n} + {2n\choose n+1}={2n+1\choose n+1}$$
Now we must show that $\frac{1}{2}{2n+2\choose n+1}={2n+1\choose n+1}$
$$\frac{1}{2} {2n+2\choose n+1}=\frac{(2n+2)!}{2(n+1)!(n+1)!}=\frac{(n+1)(2n+1)!}{(n+1)!(n+1)!}=\frac{(2n+1)!}{n!(n+1)!}={2n+1\choose n+1}$$
*DonAntonio derived this step using algebraic manipulation.


How to embed cylinder into affine space

Question: View cylinder as the Riemannian surface $\mathbb{C}/ \mathbb{Z}$, how does one embed it into affine space holomorphically?
It is well known by the maximum principle that there is no holomorphic embedding of compact complex into the affine space $\mathbb C^n$. I'am trying to find some noncompact complex manifold that also can not embed into the affine space.
Comment: This question would benefit from added context, and will likely be closed otherwise. For example, simply telling us where you got the problem from or explaining what you tried would be a big step forward! (For further feedback/help with asking questions, you can ask [here](https://chat.stackexchange.com/rooms/43593/constructive-feedback).)
Comment: @user1729 sorry,actually it looks likes a homework,I just want to consider some example about embedding the riemannian surface into the affine space.
Comment: @user1729 after I post the question,I realize that f(z)=e^z give the embedding and I answer the question by myself. But my answer disappear,I quite confuse about what happening now.
Comment: Its not about homework, but really about *why* you want to do this, and what kind of things you know. For example, is it part of a larger problem, or were you thinking about something else and this question cropped up naturally?
Comment: (For your deleted answer: you need to explain *why* it is an embedding. Saying "I think $f(x)=e^z$ should be an embedding" isn't a useful answer. So you should try and add in some reasoning. On the other hand, if you are unsure how to prove this then you could add it to your question, which would be a decent improvement to it.)
Comment: @user1729 I got it,thank you!
Answer: the function $f(z)=e^z$ give the embedding.More presicely, we can assume the cylinder is just a region in complex plane with $Im(z)$ belong to$[0,2\pi)$,since f is periodic and its period is actually $2\pi$ in the imaginary part.it is easy to find that $logz$ give the inverse of f.
A famous theorem claim that every noncompact riemannian surface is stein, which means that every noncompact riemannian surface can be embed into the affine space.So if the manifold exists,it's complex dimension must be bigger than 1.
Comment: Certainly the cylinder does not embed (even continuously) in $\Bbb C$. I presume you meant $e^{2\pi i z}$, but this still isn't going to work.
Comment: @TedShifrin sorry,I think, for injective $e^z=1$ implys z=$2ikπ$ .And $e^z$ is continuous and open map since it is holomorphic. Why this material do not obtain the embedding?
Comment: The Stein manifolds are supposed to embed as *closed* submanifolds, are they not? Your map is certainly not proper, as the origin is a limit point of the image.
Comment: @TedShifrin I think if we view the cylinder $S_1×(0,1)$ as a cone with its summit be cut off. It's quiet easy to embed it into $\mathbb{C}$ by projection.
Comment: @TedShifrin  Oh,here the embedding is not need to be closed embedding . Maybe my example of stein manifold mislead you,sorry.
Comment: @TedShifrin Actually there are no close embedding from cylinder to $C$ by the invariant of domain.

How to embed cylinder into affine space


Inverting a sum of identity and a singular matrix

Question: I wish to invert $\mathbf{A}=(\mathbf{I} - \mathbf{X})$, where $\mathbf{I}$ is the an identity $N\times N$ matrix and $\mathbf{X}$ is an $N \times N$ non-invertible matrix. One way to do it is by using the Newman series expansion, but in my application, it is not converging to the exact solution even when the order of the approximation is very high. I have also tried to do eigen-decomposition, i.e. letting $\mathbf{A}=\mathbf{I} -
 \mathbf{Q}\mathbf{D}\mathbf{Q}^{-1}=\mathbf{Q}(\mathbf{I} - \mathbf{D})\mathbf{Q}^{-1}$, then after all $\mathbf{X}$ is singular.  Is there any way to invert $\mathbf{A}$ exactly without having to invert the whole $(\mathbf{I} - \mathbf{X})$ or $\mathbf{X}$?
Thanks,
_L
Comment: $A$ *is* $(I - X)$, so no, you cannot invert $A$ exactly without inverting $I - X$. To invert one is to invert the other.
Comment: Why are you wanting to invert this matrix? Most things that could be solved with inversion can be solved by other easier methods.
Comment: Easier in terms of complexity? If so, How much gain do these easier methods offer, compared with the well known matrix inversion complexity that is of the order of $N^3$?
Comment: @L.Smash It depends on what you're trying to do... As I asked, why do you need to invert this matrix?
Answer: I can give you a few methods of calculating the inverse without directly calculating the inverse of $A$, but I can't really speak to their efficacy.
Singular Value or Eigenvalue Decomposition:
SVD tells us that $A=USV^T$ where $U,V$ are orthogonal and $S$ is diagonal. It follows that $A^{-1}=VS^{-1}U^T$. Note that the elements of $S^{-1}$ are simply the reciprocal of the elements of $S$. Eigenvalue decomposition is similar but requires a full set of eigenvalues.
Series Expansion
If we treat $I-X$ as a matrix function, we can expand it's inverse into a taylor series. Note that this requires that $|\lambda|<1$ for all eigenvalues of $I-X$ for convergence:
$$(I-X)^{-1}=I+X+X^2+X^3+...$$
This is an approximation however, and has a pretty strict requirement on the eigenvalues.
Don't Invert it
Many applications that require matrix inversion can be solved by other means such as LU or SVD decomposition. It really depends on why you need to invert this matrix.