text:
Q: Java : newSingleThreadScheduledExecutor is not giving expected result when used parallel to akka framework Using Akka framework for my use case where I created one SupervisorActor and two child actors now parallel to that I have token service which needs to update my cache before the expiry please find the code :
public class TokenCacheService {
    final Logger logger = LoggerFactory.getLogger(TokenCacheService.class);
    private static final String KEY = "USER_TOKEN";
    private LoadingCache<String, String> tokenCache;
    private final ScheduledExecutorService cacheScheduler;
    ThreadFactory threadFactory = new ThreadFactoryBuilder()
            .setNameFormat("MyCacheRefresher-pool-%d").setDaemon(true)
            .build();

    public UserTokenCacheService(CacheConfig cacheConfig) {
        cacheScheduler = Executors.newSingleThreadScheduledExecutor(threadFactory);
        buildCache(cacheConfig);
    }

    public String getToken() {
        String token = StringUtils.EMPTY;
        try {
            token = tokenCache.get(KEY);
        } catch (ExecutionException ex) {
            logger.debug("unable to process get token...");
        }
        return token;
    }

    private void buildCache(CacheConfig cacheConfig) {
        tokenCache = CacheBuilder.newBuilder()
                .refreshAfterWrite(4, "HOURS")
                .expireAfterWrite(5, "HOURS")
                .maximumSize(2)
                .build(new CacheLoader<String, String>() {
                    @Override
                    @ParametersAreNonnullByDefault
                    public String load(String queryKey) {
                        logger.debug("cache load()");
                        return <token method call which return token>
                    }

                    @Override
                    @ParametersAreNonnullByDefault
                    public ListenableFutureTask<String> reload(final String key, String prevToken) {
                        logger.debug("cache reload()");
                        ListenableFutureTask<String> task = ListenableFutureTask.create(() -> return <token method call which return token>);
                        cacheScheduler.execute(task);
                        return task;
                    }
                });
        cacheScheduler.scheduleWithFixedDelay(() -> tokenCache.refresh(KEY), 0,
                4, "HOURS");
    }
}

It is working fine with test class :
  public static void main(String[] args) throws InterruptedException {
        TokenCacheService userTokenCacheService = new TokenCacheService();
        while(true){
            System.out.println(tokenCacheService.getToken());
            Thread.sleep(180000);
        }
    }

above method printing correct logs as after 4 hours which is expected but when I run the above code with my actual application (with Akka-actors) I can only see the first log cache load() apart from this it isn't printing further log for reload the cache.
Please suggest what am doing wrong here.

A: I tweaked the code little bit by setting the priority to 1 and replaced scheduleWithFixedDelay with scheduleAtFixedRate
ThreadFactory threadFactory = new ThreadFactoryBuilder()
            .setNameFormat("MyCacheRefresher-pool-%d")
            .setPriority(1)
            .build();

    public UserTokenCacheService(CacheConfig cacheConfig) {
        idsTokenApplication = new IdsTokenApplication();
        cacheScheduler = Executors.newSingleThreadScheduledExecutor(threadFactory);
        buildCache(cacheConfig);
    }

cacheScheduler.scheduleAtFixedRate(() -> tokenCache.refresh(KEY), 0,
                cacheConfig.getReloadCache(), TimeUnit.valueOf(cacheConfig.getReloadCacheTimeUnit()));


text:
Q: Expected number of tosses to get first head How to solve the problem of expected number of tosses to get first head using markov chains?
I'm not able to figure out how to write the transition matrix for this case.
Edit:
$$Transition \space matrix = \begin{bmatrix}
1 & 0\\
1/2 & 1/2
\end{bmatrix}$$
Expected number of steps to reach absorption state:
starting from heads $t_h = 1$
starting from tails $t_t = 1/2*t_t + 1/2* t_h$
$t_t$ = 1
Total steps = $t_t + t_h = 2$

A: First identify your states.  Heads and tails.  Then, since you are waiting for your first head, start out with the vector $(0,1)$ for $100$% tails, so to speak.  Then find the probability of switching to heads, or staying tails, given that it is currently heads.
So the vector $(0,1)$ needs to turn into $(1/2, 1/2)$, making that the second column of the transition matrix.  Likewise the first column.
So iterating would give the overall probability of heads at any number of tosses, but would not guarantee that it was the first time heads came up.
I don't see how to get from there to expected value for the number, but hopefully that will get you started.
EDIT. Alternative description of the states: "got heads" vs. "never got heads."  So once you transition to "got heads" you can't transition back.  So the second column in this case would still be $(1/2,1/2)$ but the first column would have to be $(1,0)$.

A: In order to get the first head on the nth toss you must get a tail on each of the first n-1 tosses which has probability (1/2)^(n-1) and then get a head on the nth toss which has probability 1/2.  So the probability of getting the first head on the nth toss is (1/2)^n.  The expected value is 1(1/2)+ 2(1/2)^2+ 3(1/2)^3+ ...+ n(1/2)^n.
To get that, consider the general geometric sum:Y(r)= 1+ r+ r^2+ ...+ r^n= (1- r^(n+1))/(1- r).  Y'= 1+ 2r+ 3r^2+ ...+ nr^(n-1).
Multiply that by  r: rY'= r+ 2r^2+ 3r^3+ ...+ nr^n.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get wireless working on an HP-Mini 110-3500, I have only usb ports How can I get wireless working on an HP-Mini 110-3500, I have only usb ports

A: If you have the same 110-3500 that I just got, you do have an ethernet port, but it's hidden. It is located under a cover along the right side of the computer, at the rear - opposite where you plug in the power, and just behind the attachment point for a security lock cable.
I hope that helps. I'm in the process of installing ubuntu myself on one now.

A: Can you add some hardware information to your question?

*

*I have a hardware detection problem, what logs do I need to look into?
From my googling it looks like it could either be a broadcom card or an atheros card. Once we determine which wireless card it is we'll be able to help you better.
Do you have ethernet available? Usually plugging in via a wire and running Additional Drivers does the trick.


text:
Q: Error: 'is_same' is not a member of 'std' when build c++ project in ubuntu? I have a small project and i get an error 'is_same' is not a member of 'std' when building.
this is some code:
template <class T>
T* UcmExportFactory::Unwrap (T* ptr)
{
    Utils::IUcmWrapper* wrapper = dynamic_cast<Utils::IUcmWrapper*> (ptr);

    // If the requested Ucm inteface is derived from an another (such as IUcmV from IUcmUnionValue), specify that whether we want the base class pointer or not.
    bool interfaceForAbstractBase = (std::is_same<IUcmUnionValue, T>::value || std::is_same<IUcmDiagCodedType, T>::value);
    return (wrapper) ? boost::any_cast<T*> ( wrapper->GetWrappedObject (interfaceForAbstractBase) ) : ptr;
}

Anyone can help me. I included header #include <type_traits>. Thanks.

A: std::is_same is a C++11 feature. Ubuntu 12.04 has GCC 4.6.3, which has only incomplete C++0x (not yet C++11) support. You can try by specifying the standard:
g++ --std=c++0x ...

A: Just a reminder to anyone landing on this page, as the OP has stated he did this:
You'll also get this error if you do not include the type_traits header, so don't forget that:
#include <type_traits>


text:
Q: Problem Upgrading Rails I'm running Tiger and (stupidly) decided to upgrade Rails from 1.1.6 to 1.2.6.  I ran the command "sudo gem install rails --include-dependencies" and everything seemed to go OK.  However, after the install, when I ran the command "rails -v", I got the errors shown below.  Could it be that 1.2.6 is not compatible with Tiger?  I've been searching the Internet for compatibility info but haven't found anything.  By the way, in desperation, I tried to go back to 1.1.6 but I still get the same errors so now I'm hosed. Can anyone help?  Thanks.
/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:55: uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
    from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support.rb:56
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
    from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record.rb:25
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems.rb:229:in `activate'
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems.rb:228:in `each'
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems.rb:228:in `activate'
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems.rb:214:in `activate'
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems.rb:213:in `each'
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems.rb:213:in `activate'
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems.rb:66:in `active_gem_with_options'
    from /usr/local/lib/ruby/site

A: By what you did, it looks like you jumped right to rails 2.3.2.
What I'd advise you to do now is to first upgrade everything:
sudo gem update --system
sudo gem update

And then install the 1.2.6 version too. Now you'll have 1.1.6, 1.2.6 and 2.3.2
sudo gem install rails -v1.2.6

And, btw, what's your ruby version, and are you using the one supplied by Apple? Particularly, if you ran the two following commands you'd get the information you need. (which will certainly differ from mine)
$ ruby --version
ruby 1.8.7 (2009-04-08 patchlevel 160) [i686-darwin9]
$ which ruby
/opt/local/bin/ruby

And no, there's no incompatibility with Tiger.

A: I got this error when I was (blindly) following the OS X RoR install directions from HiveLogic.  You'd expect they'd be OK because Apple links to them.  HOWEVER, the binary paths includes in this document are out of date!!!
Specially, the RubyGems were 0.9 instead of 1.3.  Other binaries in the list were out of date with dead links.
To fix the problem, follow the current directions from Ruby on Rails.  You'll download and install the right version of RubyGems and be good to go!
If you followed the HiveLogic directions, you may want to check ALL your versions.

A: You specify your desired Gem version by setting the RAILS_GEM_VERSION constant at the top of config/environment.rb, e.g.
RAILS_GEM_VERSION = '2.3.2'

OR you can freeze Rails in vendor/rails. When Rails bootstraps itself from your app it will first look in vendor/rails, so you can freeze your desired version in there. But I prefer the RAILS_GEM_VERSION approach myself.


text:
Q: Use value from sibling with condition I've been trying to get this to work for quite some time and I know I still have to watch the 22hrs I have left on my Udemy xsl class but it's not an inspiring teacher..
I want to search for a value higher up in the xml tree and use that value 'x times'. I want the value of /SHPMNT05/IDOC/E1EDT20/E1EDK33/E1EDT44/ABLAD
where /SHPMNT05/IDOC/E1EDT20/E1EDK33/E1EDT01/VBELN = /SHPMNT05/IDOC/E1EDT20/E1EDL20/VBELN
and use that in an extra /SHPMNT05/IDOC/E1EDT20/E1EDL20/ABLAD element
1 - I have as input xml
<?xml version="1.0" encoding="UTF-8"?>
<SHPMNT05>
   <IDOC BEGIN="1">
      <EDI_DC40 SEGMENT="1">
         <TABNAM>EDI_DC40</TABNAM>
      </EDI_DC40>
      <E1EDT20 SEGMENT="1">
         <TKNUM>0000287203</TKNUM>
         <E1EDK33 SEGMENT="1">
            <TSNUM>0001</TSNUM>
            <E1EDT44 SEGMENT="1">
               <QUALI>001</QUALI>
            </E1EDT44>
            <E1EDT44 SEGMENT="1">
               <QUALI>002</QUALI>
               <ABLAD>1</ABLAD>
            </E1EDT44>
            <E1EDT01 SEGMENT="1">
               <VBELN>0081018667</VBELN>
            </E1EDT01>
         </E1EDK33>
         <E1EDK33 SEGMENT="1">
            <TSNUM>0002</TSNUM>
            <E1EDT44 SEGMENT="1">
               <QUALI>001</QUALI>
            </E1EDT44>
            <E1EDT44 SEGMENT="1">
               <QUALI>002</QUALI>
               <ABLAD>2</ABLAD>
            </E1EDT44>
            <E1EDT01 SEGMENT="1">
               <VBELN>0081018668</VBELN>
            </E1EDT01>
         </E1EDK33>
         <E1EDK33 SEGMENT="1">
            <TSNUM>0002</TSNUM>
            <E1EDT44 SEGMENT="1">
               <QUALI>001</QUALI>
            </E1EDT44>
            <E1EDT44 SEGMENT="1">
               <QUALI>002</QUALI>
               <ABLAD>3</ABLAD>
            </E1EDT44>
            <E1EDT01 SEGMENT="1">
               <VBELN>0081018666</VBELN>
            </E1EDT01>
         </E1EDK33>
         <E1EDL20 SEGMENT="1">
            <VBELN>0081018666</VBELN>
         </E1EDL20>
         <E1EDL20 SEGMENT="1">
            <VBELN>0081018667</VBELN>
         </E1EDL20>
         <E1EDL20 SEGMENT="1">
            <VBELN>0081018668</VBELN>
         </E1EDL20>
      </E1EDT20>
   </IDOC>
</SHPMNT05>

2 - I want
<?xml version="1.0" encoding="UTF-8"?>
<SHPMNT05>
   <IDOC BEGIN="1">
      <EDI_DC40 SEGMENT="1">
         <TABNAM>EDI_DC40</TABNAM>
      </EDI_DC40>
      <E1EDT20 SEGMENT="1">
         <TKNUM>0000287203</TKNUM>
         <E1EDK33 SEGMENT="1">
            <TSNUM>0001</TSNUM>
            <E1EDT44 SEGMENT="1">
               <QUALI>001</QUALI>
            </E1EDT44>
            <E1EDT44 SEGMENT="1">
               <QUALI>002</QUALI>
               <ABLAD>1</ABLAD>
            </E1EDT44>
            <E1EDT01 SEGMENT="1">
               <VBELN>0081018667</VBELN>
            </E1EDT01>
         </E1EDK33>
         <E1EDK33 SEGMENT="1">
            <TSNUM>0002</TSNUM>
            <E1EDT44 SEGMENT="1">
               <QUALI>001</QUALI>
            </E1EDT44>
            <E1EDT44 SEGMENT="1">
               <QUALI>002</QUALI>
               <ABLAD>2</ABLAD>
            </E1EDT44>
            <E1EDT01 SEGMENT="1">
               <VBELN>0081018668</VBELN>
            </E1EDT01>
         </E1EDK33>
         <E1EDK33 SEGMENT="1">
            <TSNUM>0002</TSNUM>
            <E1EDT44 SEGMENT="1">
               <QUALI>001</QUALI>
            </E1EDT44>
            <E1EDT44 SEGMENT="1">
               <QUALI>002</QUALI>
               <ABLAD>3</ABLAD>
            </E1EDT44>
            <E1EDT01 SEGMENT="1">
               <VBELN>0081018666</VBELN>
            </E1EDT01>
         </E1EDK33>
         <E1EDL20 SEGMENT="1">
            <VBELN>0081018666</VBELN>
            ***<ABLAD>3</ABLAD>***
         </E1EDL20>
         <E1EDL20 SEGMENT="1">
            <VBELN>0081018667</VBELN>
            ***<ABLAD>1</ABLAD>***
         </E1EDL20>
         <E1EDL20 SEGMENT="1">
            <VBELN>0081018668</VBELN>
            ***<ABLAD>2</ABLAD>***
         </E1EDL20>
      </E1EDT20>
   </IDOC>
</SHPMNT05>

3 - My xsl is
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

<!--    <xsl:template match="/SHPMNT05/IDOC/E1EDT20/E1EDK33/E1EDT01[(VBELN= following-sibling::E1EDT01/VBELN) or (VBELN= ../following-sibling::E1EDK33/E1EDT01/VBELN)]"/> -->

          <xsl:template match="/SHPMNT05/IDOC/E1EDT20/E1EDL20/VBELN">
           <xsl:copy-of select="."/>
        <xsl:variable name="stopno" select="/SHPMNT05/IDOC/E1EDT20/E1EDK33/E1EDT01[VBELN=VBELN]/parent::node()/E1EDT44/ABLAD"/>
        <ABLAD><xsl:value-of select="$stopno" /></ABLAD>
      </xsl:template>

   <xsl:template match="text()">
        <xsl:value-of select="normalize-space(.)"/>
     </xsl:template>

</xsl:stylesheet>

4 - I get
<SHPMNT05>
  <IDOC BEGIN="1">
    <EDI_DC40 SEGMENT="1">
      <TABNAM>EDI_DC40</TABNAM>
    </EDI_DC40>
    <E1EDT20 SEGMENT="1">
      <TKNUM>0000287203</TKNUM>
      <E1EDK33 SEGMENT="1">
        <TSNUM>0001</TSNUM>
        <E1EDT44 SEGMENT="1">
          <QUALI>001</QUALI>
        </E1EDT44>
        <E1EDT44 SEGMENT="1">
          <QUALI>002</QUALI>
          <ABLAD>1</ABLAD>
        </E1EDT44>
        <E1EDT01 SEGMENT="1">
          <VBELN>0081018667</VBELN>
        </E1EDT01>
      </E1EDK33>
      <E1EDK33 SEGMENT="1">
        <TSNUM>0002</TSNUM>
        <E1EDT44 SEGMENT="1">
          <QUALI>001</QUALI>
        </E1EDT44>
        <E1EDT44 SEGMENT="1">
          <QUALI>002</QUALI>
          <OBLAD>2</OBLAD>
        </E1EDT44>
        <E1EDT01 SEGMENT="1">
          <VBELN>0081018668</VBELN>
        </E1EDT01>
      </E1EDK33>
      <E1EDK33 SEGMENT="1">
        <TSNUM>0002</TSNUM>
        <E1EDT44 SEGMENT="1">
          <QUALI>001</QUALI>
        </E1EDT44>
        <E1EDT44 SEGMENT="1">
          <QUALI>002</QUALI>
          <OBLAD>3</OBLAD>
        </E1EDT44>
        <E1EDT01 SEGMENT="1">
          <VBELN>0081018666</VBELN>
        </E1EDT01>
      </E1EDK33>
      <E1EDL20 SEGMENT="1">
        <VBELN>0081018666</VBELN>
        <ABLAD>1</ABLAD>
      </E1EDL20>
      <E1EDL20 SEGMENT="1">
        <VBELN>0081018667</VBELN>
        <ABLAD>1</ABLAD>
      </E1EDL20>
      <E1EDL20 SEGMENT="1">
        <VBELN>0081018668</VBELN>
        <ABLAD>1</ABLAD>
      </E1EDL20>
    </E1EDT20>
  </IDOC>
</SHPMNT05>

Do I need to use a 'for each' or something?
Kind regards,
Mike

A: <xsl:variable name="stopno" select="/SHPMNT05/IDOC/E1EDT20
  /E1EDK33[E1EDT01/VBELN=current()]
  /E1EDT44/ABLAD"/>

Note two points:

*

*E1EDT01 is inside the square brackets, which saves the parent::node() step.

*The VBELN element that was matched by the current template can be accessed as current().


text:
Q: How to Auto-recharge an account using Paypal or Stripe Has anyone found a way to auto recharge a mobile user's account using Paypal, Stripe or a similar payment platform? Similar to Skype's auto-refill, we would like to automatically deduct payment from our user's credit card when their credit is running low.
Thanks!

A: Stripe and PayPal are only payment providers, and do not cover any business logic the payment is used for. If you opt to use those services, you'll need to maintain the user's balance on your end and issue a CHARGE request when it runs low.
There are many payment services out there such as BrainTree or BlueSnap that support scheduled payments (e.c. Monthly, Quarterly), and some more sophisticated plans, but still none will maintain a usage balance for your customer. That's simply because only you can tell when a credit was consumed.

A: Tal is correct that if you want to bill a customer for aggregated usage, you (not the payments provider) generally need to track that usage and decide when to request additional funds.
But in order to make a "top-up" payment for a user's account happen without requiring action from the user to separately authorize each top-up you also need a payment token of some sort from your payments provider that grants you the authority to bill the user. With some payments provider this token is the raw card number; with more sophisticated solutions you get a derived token so that you don't have to store the card number (with all the associated risks & responsibilities).
PayPal, Braintree, Stripe, and other providers all have products that will do this for you.


text:
Q: .htaccess if path (folder) doesn't exist request another path By adding the language to my website i'm facing a problem.
Becouse i don't want to change all my urls from all my templates but i want to keep the language into my url i need to modyfy the .htaccess .
Basicly the problem is as folows: - To keep the language in url i have to change the site url:
ex:
without language: http://www.mysite.com/some/other/vars   SITE_URL : http://www.mysite.com
with language: http://www.mysite.com/cn/some/other/vars  changed SITE_URL : http://www.mysite.com/cn
when i request for css file SITE_URL/my_style/style.css , obiously the css will not be found in 2'nd case becouse is not in the folder cn/
How i can modyfy the .htaccess to change the requested path if the path is :
http://www.mysite.com/cn
http://www.mysite.com/es
http://www.mysite.com/fr
Originaly htaccess content is:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Options All -Indexes
Options All -Indexes
Options All -Indexes

Thanks..it should be simple...but i can't do it since 2 hours.
EDIT:
All i want is:
If a request is made at: www.mysite.com/cn/any/thing/else/style.css (in this case css file will not exist), make the request at: www.mysite.com/any/thing/else/style.css
Was a long day with no progress ...haha. it happends.

A: I suggest to fix the issue by requesting correct url! That just would be right.
However this should work
RewriteRule ^(cn|es|fr)/my_style/(.+)$ /my_style/$2 [L]

A: Add this to the htaccess files that you have in your cn/es/fr folders, preferably before any rules that you may have there:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/$1 -d
RewriteRule ^(.*)$ /$1 [L]

This should make it so a request for /my_style/style.css from within the cn folder will serve the one from the document root.


text:
Q: Django Signals: The QuerySet value for an exact lookup must be limited to one result using slicing I hope my title is enough to determine what the error is.
I have this code in my models.py (post_save)
    class StudentsEnrolledSubject(models.Model):
        Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+',
                                                        on_delete=models.CASCADE, null=True)
        Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,
                                                    null=True,blank=True)

    @receiver(post_save, sender=StudentsEnrollmentRecord)
    def create(sender, instance, created, *args, **kwargs):
        teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section,Education_Levels=instance.Education_Levels,Courses=instance.Courses)
        for each in teachers:
            if created and teachers.exists():
                StudentsEnrolledSubject.objects.update_or_create(
                        pk=each.id,
                        Students_Enrollment_Records=instance,
                        Subject_Section_Teacher=teachers.all()

                    )

    class StudentsEnrollmentRecord(models.Model):
        Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True)

    class SubjectSectionTeacher(models.Model):
        Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True)
        Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
        Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True)
        Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True)
        Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True)

when I used the Subject_Section_Teacher=teachers.first() i received no error but that is not what i want result, then i decide to change it to this Subject_Section_Teacher=teachers.all()
I just want the result to become this

not this

this is where I get/filter data

A: Update the code like this:
@receiver(post_save, sender=StudentsEnrollmentRecord)
def create(sender, instance, created, *args, **kwargs):
    teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section,Education_Levels=instance.Education_Levels,Courses=instance.Courses)
    for each in teachers:
        StudentsEnrolledSubject.objects.update_or_create(
                    pk=each.id,
                    Students_Enrollment_Records=instance,
                    Subject_Section_Teacher=each

                )

A: Since you're iterating over the teachers already, you should use each to pass the current teacher in the loop instead of teachers.all() which is invalid or teachers.first() which is always just the first teacher:
    for each in teachers:
        if created and teachers.exists():
            StudentsEnrolledSubject.objects.update_or_create(
                    pk=each.id,
                    Students_Enrollment_Records=instance,
                    Subject_Section_Teacher=each,
                )


text:
Q: NIR.subtract is not a function I am trying to calculate Kernal NDVI (kNDVI) and the code keeps giving me this error.
The link to the code:
https://code.earthengine.google.com/24e8503ec2f264d0ffe0ba1bfe4c6353
/// adding shapefile to the map

Map.addLayer(Etosha);

/// Dates of Interest
var start = ee.Date('2021-03-01');
var finish = ee.Date('2021-03-31');

// creating Image Collection
var S2A = ee.ImageCollection('COPERNICUS/S2_SR')
.filterBounds(Etosha)
.filterDate(start,finish)
.filterMetadata('Cloud_Cover','Less_Than',30);

/// Selecting the Bands
var image = S2A.mean();
var RED = S2A.select ('B4');
var NIR = S2A.select ('B8');

var addKNDVI = function(image){

  // Compute D2 a rename it to d2
  var D2 = NIR.subtract(RED).pow(2)
  .select([0],['d2']);

  // Gamma, defined as 1/sigmaˆ2
  var gamma = ee.Number(4e6).multiply(-2.0);

  // Compute kernel (k) and KNDVI
  var k = D2.divide(gamma).exp();
  var kndvi = ee.Image.constant(1)
  .subtract(k).divide(ee.Image.constant(1).add(k))
  .select([0],['knd']);
  return image.addBands(kndvi);

}

var kndvi = addKNDVI(image).select('kndvi');

Map.addLayer(kndvi);

A: NIR and RED are collections, not images.  Do the select inside the function on each individual image instead of on the whole collection.


text:
Q: UITabBar Showing More Icons Instead of "More" Option I'm currently attempting to use the UITabBar for an iOS app that contains 7 tabBar Items.
When I use the storyboard, I am able to achieve all 7 tabBarItems.
When I programmatically add the tabBarItems, It forces a "More" Button to access the other tabBarItems.
Is there a way programmatically keep all the 7 tabBarItems as when I am manually create the UITabBar?

The Code that I'm using to build the uitabbar in my appdelegate.m
  self.tabBarController = [[UITabBarController alloc] init];
  FirstViewController *firstVC = [[FirstViewController alloc] init];
  SecondViewController *secondVC = [[SecondViewController alloc] init];
  ThirdViewController *thirdVC = [[ThirdViewController alloc] init];
  FourthViewController *fourthVC = [[FourthViewController alloc] init];
  FifthViewController *fifthVC = [[FifthViewController alloc] init];
  SixthViewController *sixthVC = [[SixthViewController alloc] init];
  SeventhViewController *seventhVC = [[SeventhViewController alloc] init];

  NSArray *controllers = @[firstVC, secondVC, thirdVC, fourthVC, fifthVC, sixthVC, seventhVC];

  self.tabBarController.viewControllers = controllers;
  self.window.rootViewController = self.tabBarController;
  [_window addSubview:_tabBarController.view];

A: By design you are limited to 5, from apple docs

If you add more than five items to the viewControllers property, the
  tab bar controller automatically inserts a special view controller
  (called the More view controller) to handle the display of the
  additional items. The More view controller provides a custom interface
  that lists the additional view controllers in a table, which can
  expand to accommodate any number of view controllers. The More view
  controller cannot be customized or selected and does not appear in any
  of the view controller lists managed by the tab bar controller. It
  appears automatically when it is needed and is separate from your
  custom content. You can get a reference to it though by accessing the
  moreNavigationController property of UITabBarController.

It just not recommended , but if you insist you will need to use a library or perhaps use a tool bar and add many UIBarButtonItems to it.


text:
Q: The program is arbitrarily coming out of the recursion See I am trying to print the different ways the number n can be printed with the maximum number in it to be 4.
My program subtracts the no here(4) in a loop and then prints 4 at end and sends the remaining number here(2) to the same function with max as 3 ,2 ,1.
when max is 1 it just prints all 1s.
When I enter n=6 it displays output

2
  1 1 4

where it should display

2 4
  1 1 4

I don't know why this behavior is coming , it is a simple recursion and I also have checked a lot for errors.
This is the code
#include<bits/stdc++.h>
using namespace std;
void comp(int n,int k)
{
if(n>=k&&k!=0&&k!=1&&n!=0)
{

    for(int i=1;i<=(n/k);i++)
    {
        for(int l=k-1;l>=1;l--)
        {
            comp(n-(i*k),l);

        }

        for(int j=0;j<i;j++)
        {
            cout<<k<<" ";
        }
        cout<<"\n";
    }
}
if(k==1)
{
    for(int i=0;i<n;i++)
    {
        cout<<"1 ";
    }

}

}
int main()
{
int n;
while(cin>>n)
{
    comp(n,4);
}

return 0;
}


text:
Q: React Native Maps ref issue I have a react-native-maps MapView which is utilized in a fitToCoordinates function. The function zooms the map to fit a start point (current user location) and an end point. Below is the MapView object:
<MapView
      ref={map => { this.map = map; }}
      region={{
        latitude: this.props.startLatitude,
        longitude: this.props.startLongitude,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421
      }}
      style={styles.mapContainer}
      showsCompass={false}
      showsUserLocation
    >

      <MapViewDirections
        origin={{ latitude: this.props.startLatitude, longitude: this.props.startLongitude }}
        destination={this.props.optimalDestination}
        apikey={GOOGLE_API_KEY}
        strokeWidth={2}
        strokeColor={COLORS.MAIN.hexCode}
      />

      {this.walkLine()}

      {this.optimalAddressFound()}

      {this.fitCoordinates()}

    </MapView>

The fitToCoordinates function referenced in the MapView object is as follows:
fitCoordinates() {
if (this.props.optimalAddressFound && this.props.destinationMapFit) {
  this.map.fitToCoordinates(
    [{ latitude: this.props.startLatitude,
      longitude: this.props.startLongitude },
    { latitude: this.props.optimalAddressLat,
    longitude: this.props.optimalAddressLng }],
    { edgePadding: { top: 30, right: 30, bottom: 30, left: 30 } }
  );
 }
}

Everything works fine, except when a user opens the React Navigation Drawer Menu, navigates to another page, and then returns to the Map page. If they do that, the ref to the MapView object becomes undefined and the fitToCoordinates function fails (TypeError: Cannot ready property 'fitToCoordinates' of undefined).
My question is, how can I maintain the map ref if my user navigates to other screens? I have tried creating a function to store the MapView object in my Redux store but it seems that the Redux store cannot accept an object in the Reducer.

A: if you use react-navigation, you would need to set a key for your Map-Screen to make sure the same screen is reused instead of creating a new one each time.
something like
navigation.navigate({key: 'map-screen', routeName: 'Map'});


text:
Q: Reducing execution time of PostgreSQL stored function So in Postgres I created a function that creates a table vehicletracks_tracks and fills in with information calculated from original table. Original table includes the following atributes: id bigint NOT NULL DEFAULT, session character varying(32), client_id character varying(32) NOT NULL, vehicle_type smallint NOT NULL, geolocation geography(Geometry,4326) NOT NULL and "timestamp" timestamp without time zone NOT NULL.
In the function I calculate tracks and borders between them by observing time and velocity between two consecutive rows in original table. A fter creating tracks I calculate distance and duration of every track.
The function takes around 6 minutes and 30 seconds and then the output table is created and filled with rows. The original table has around 5 million rows. When you look at the procedure is there any possibility to reduce its execution time?
This is my function:
CREATE OR REPLACE FUNCTION vehicletracks()
      RETURNS void AS
      $BODY$
          DECLARE
            vrstica1 RECORD;
            vrstica2 RECORD;
            track_number INT;
          BEGIN
        SET TIME ZONE 'UTC';

        DROP TABLE IF EXISTS vehicletracks_tracks;
        CREATE TABLE vehicletracks_tracks (
          session character varying(32),
          client_id character varying(32) NOT NULL,
          vehicle_type smallint NOT NULL,
          track_number SERIAL PRIMARY KEY,
          track_distance DOUBLE PRECISION,
          track_duration INTERVAL,
          track_start TIMESTAMP WITH TIME ZONE,
          track_stop TIMESTAMP WITH TIME ZONE
        );

        DROP VIEW IF EXISTS group_by_client_session_vehicle;
        CREATE VIEW group_by_client_session_vehicle AS
        SELECT DISTINCT client_id, session, vehicle_type
        FROM roaduserspositions
        GROUP BY client_id, session, vehicle_type
        ORDER BY session, client_id, vehicle_type;

        FOR vrstica1 IN (SELECT * FROM group_by_client_session_vehicle)
          LOOP
            DROP VIEW IF EXISTS velocity_difference_view;
                DROP TABLE IF EXISTS difference_table;
                CREATE TABLE difference_table AS
                SELECT id, session, client_id, vehicle_type, geolocation, timestamp, time_difference, distance_difference
                FROM (SELECT t.*, t.timestamp - LAG(t.timestamp) OVER (ORDER BY t.session, t.client_id, t.vehicle_type, t.timestamp ASC) AS time_difference,
              ST_Distance(geolocation, LAG(geolocation) OVER (ORDER BY t.session, t.client_id, t.vehicle_type, t.timestamp ASC)) AS distance_difference
                      FROM (SELECT *
                            FROM timonwww_roaduserspositions
                            WHERE client_id = vrstica1.client_id AND session = vrstica1.session AND vehicle_type = vrstica1.vehicle_type) AS t) AS tab
                ORDER BY session, client_id, vehicle_type, timestamp;

            CREATE VIEW velocity_difference_view AS (
            SELECT *, distance_difference / EXTRACT(EPOCH FROM time_difference) AS velocity
            FROM difference_table
            WHERE EXTRACT(EPOCH FROM time_difference) > 0
            UNION
            SELECT *, 0 AS velocity
            FROM difference_table
            WHERE EXTRACT(EPOCH FROM time_difference) = 0
            ORDER BY session, client_id, vehicle_type, timestamp);

            DROP TABLE IF EXISTS new_time_difference;
            CREATE TABLE new_time_difference (
                track_id INTEGER,
                LIKE velocity_difference_view INCLUDING ALL);

            track_number := 1;
            INSERT INTO new_time_difference(track_id, id, session, client_id, vehicle_type, geolocation, timestamp, time_difference)
                SELECT
                CASE
              WHEN EXTRACT(EPOCH FROM time_difference) < 300 AND velocity < 121 THEN track_number
              ELSE track_number + 1
            END AS track_id, id, session, client_id, vehicle_type, geolocation, timestamp, time_difference
            FROM velocity_difference_view OFFSET 1;

            track_number := 1;
                FOR vrstica2 IN (SELECT * FROM velocity_difference_view OFFSET 1)
              LOOP
                IF EXTRACT(EPOCH FROM vrstica2.time_difference) < 300 AND vrstica2.velocity < 121 THEN
                  INSERT INTO new_time_difference VALUES(track_number, vrstica2.id, vrstica2.session, vrstica2.client_id, vrstica2.vehicle_type, vrstica2.geolocation, vrstica2.timestamp, vrstica2.time_difference);
                ELSE
                  track_number := track_number + 1;
                END IF;
              END LOOP;

                DROP TABLE IF EXISTS geolocation_difference_table;
                CREATE TABLE geolocation_difference_table AS
                SELECT *
                FROM (SELECT *, ST_Distance(geolocation, LAG(geolocation) over (ORDER BY timestamp ASC)) as geolocation_difference
                      FROM new_time_difference
                      WHERE track_id IN (SELECT * FROM generate_series((SELECT MIN(new_time_difference.track_id) FROM new_time_difference), (SELECT MAX(track_id) FROM new_time_difference)) num)) AS tab;

            DROP TABLE IF EXISTS track_distance_table;
            CREATE TABLE track_distance_table AS
            SELECT track_id, SUM(geolocation_difference) AS track_distance, SUM(time_difference) AS track_duration, MIN(timestamp) AS track_start, MAX(timestamp) AS track_stop
            FROM geolocation_difference_table
            GROUP BY track_id
            ORDER BY track_id ASC;

            INSERT INTO vehicletracks_tracks(session, client_id, vehicle_type, track_distance, track_duration, track_start, track_stop)
            SELECT vrstica1.session, vrstica1.client_id, vrstica1.vehicle_type, track_distance, track_duration, track_start, track_stop
            FROM (SELECT * FROM track_distance_table WHERE track_distance > 0 AND track_distance IS NOT NULL) AS t;

          END LOOP;

          DROP TABLE IF EXISTS vehicletracks_binding;
          CREATE TABLE vehicletracks_binding AS
          SELECT id, track_id
          FROM geolocation_difference_table
          ORDER BY track_id ASC;

          DROP VIEW IF EXISTS group_by_client_session_vehicle;
          DROP VIEW IF EXISTS velocity_difference_view;
          DROP TABLE IF EXISTS difference_table;
          DROP TABLE IF EXISTS new_time_difference;
          DROP TABLE IF EXISTS geolocation_difference_table;
          DROP TABLE IF EXISTS track_distance_table;

          END;
      $BODY$
      LANGUAGE plpgsql VOLATILE
      COST 100;


text:
Q: Will I need to call this pcre2_code_free() function to free up memory for a c++ class object? This pcre2_code_free() needs to be called to free up memory used by a structure pcre2_code. I am delcaring the pcre2_code as a class variable like this:
class Pcre2Regex{
    private:
    std::string pat_str;
    std::string modifier;
    PCRE2_SPTR pattern;
    pcre2_code *code;
    ...

    public:

    Pcre2Regex(const std::string& re,const std::string& mod=""){compile(re,mod);}
    void compile(void){compile(pat_str,modifier);}
    void compile(const std::string& re,const std::string& mod="");
    pcre2_code* getPcreCode(){return code;}
    void free(void){pcre2_code_free(code);}

};

Then I am creating an object like this:
{
Pcre2Regex re=Pcre2Regex("sample pattern");

///and calling re.free() before going out of scope
}

Is it really necessary to call the re.free() method before the object goes out of scope. If I leave everything upto the default destructor will there be a memory leak?
I have tried to put that free() function inside a destructor, but trying to free the memory of code from destructor yields a segmentation fault.
Note:
The pcre2_code is a c structure which uses c memory management codes to allocate memory for its' members.  pcre2_code_free() frees the memory used by the structure (it's members) using pure c memory deallocation function.
This is how I am setting values to the code:
code = pcre2_compile(
    pattern,                    /* the pattern */
    PCRE2_ZERO_TERMINATED,  /* indicates pattern is zero-terminated */
    compile_opts,                      /* default options */
    &error_number,          /* for error number */
    &error_offset,          /* for error offset */
    NULL);                  /* use default compile context */

The above function is being called by the class member function compile() i.e it is being called as soon as the class object being created.
All the memory allocation tasks are handled by the pcre2 library function pcre2_compile(). (pcre2_compile() as well as other pcre2 related variables and functions are defined in a static library (pcre2-8.a).


text:
Q: Is GC guaranteed to free memory of unused activities I am trying to analyze the memory usage of the Android app. I do that using
adb shell dumpsys meminfo <package name>

My app has only one Activity and I repeat the following steps probably a dozen of times:

*

*open the app;

*exit using the back button

After doing that a dozen of times dumpsys shows that around 1-2 instances of my Activities are still in memory. After I hit adb dumpsys for a couple of times the Activity count goes down to zero. Is this normal? If it is a leak I don't expect the Activity count to go down to zero. Does that mean GC claims the memory of the Activity objects slowly?

A:
Does that mean GC claims the memory of the activity objects slowly?

Finishing an Activity by pressing the back button does not mean its instance will be immediately killed and the memory GC-ed. The Activity's onDestroy() method is not a "finalizer". One can meet the case when by the time of starting a new Activity instance the "old" one is still sitting in memory (as a reference).

If it is a leak I don't expect the activity count to go down to zero.

If you see the app's process running it's not a leak as "the activity count goes down to zero".

After I hit adb dumpsys for a couple of times the activity count goes down to zero. Is this normal?

Yes, by the reasons described above.


text:
Q: Confusion: Tensor norm between LCSs Recently I have read that one may define a "tensor norm" on the projective tensor product $X\otimes_{\pi} Y$ between two locally convex spaces.  If $X$ and $Y$ are not Banach spaces, how is this possible?  Do we take the quotient by the ideal
$$
\left\{
ker(p\otimes q): p,q \mbox{ seminorms on $X$ and $Y$ respectively}
\right\}?
$$


text:
Q: Does PirateBrowser hide my IP address? Does PirateBrowser hide my IP address?
It uses Tor so the IP should be changed, but when I looked on What is my IP, I saw the same address as before.
Is there anybody who can explain it to me?

A: Obviously, the Pirate Browser doesn't hide your IP address. Your IP address is going to be visible to your local ISP router and every router till you get to your first TOR node. This is the way that IP works. It has to have IP addresses in order to route traffic.
Once on the TOR network, the TOR routing system then practices a whole bunch of security by obscurity tricks and encryption till the traffic leaves the end node on the far side with the return address visible to the remote server hopefully being the one belonging to that TOR node.
So to answer your question, if the browser's TOR configuration is functioning properly and you're actually routing your request to whatismyip through TOR, whatismyip should be reporting the IP address of the last TOR node. Sounds like you need to hit the books and figure out if your Pirate Bay Browser is properly configured so it routes everything through TOR.
After all, the last kerfluffle concerting TOR was that the browser bundle that's supposed to make it easier to use had a security issue that allowed a kiddie porn torrorist to get caught.
Note: Per current interviews with the purveyors, Pirate Browser is not intended to provide anonymous or secure internet access. It's mostly there to browse websites with access restrictions that are easily evaded.


text:
Q: Search via object property I have a SidebarBox class which has a person as a property. I would like to get all SidebarBoxes based on the person.
For this I have created the following repositoy:
public interface SidebarRepository extends Neo4jRepository<SidebarBox, Long> {
    List<SidebarBox> findAllByPerson_Id(Long personId);
    List<SidebarBox> findAllByPerson(Person person);
}

If I search via findAllByPerson_Id I get no entry at all and if I do via findAllByPerson the program crashes with the following error message:
java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:807) ~[spring-boot-2.4.2.jar:2.4.2]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:788) ~[spring-boot-2.4.2.jar:2.4.2]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:333) ~[spring-boot-2.4.2.jar:2.4.2]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1311) ~[spring-boot-2.4.2.jar:2.4.2]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1300) ~[spring-boot-2.4.2.jar:2.4.2]
    at de.skillkiller.persondb.PersondbApplication.main(PersondbApplication.java:24) ~[classes/:na]
Caused by: org.springframework.data.mapping.MappingException: The property 'null' is not mapped to a Graph property!
    at org.springframework.data.neo4j.core.mapping.DefaultNeo4jPersistentProperty.getPropertyName(DefaultNeo4jPersistentProperty.java:247) ~[spring-data-neo4j-6.0.3.jar:6.0.3]
    at org.springframework.data.neo4j.repository.query.CypherQueryCreator.toCypherProperty(CypherQueryCreator.java:549) ~[spring-data-neo4j-6.0.3.jar:6.0.3]
    at org.springframework.data.neo4j.repository.query.CypherQueryCreator.createImpl(CypherQueryCreator.java:385) ~[spring-data-neo4j-6.0.3.jar:6.0.3]
    at org.springframework.data.neo4j.repository.query.CypherQueryCreator.create(CypherQueryCreator.java:240) ~[spring-data-neo4j-6.0.3.jar:6.0.3]
    at org.springframework.data.neo4j.repository.query.CypherQueryCreator.create(CypherQueryCreator.java:85) ~[spring-data-neo4j-6.0.3.jar:6.0.3]
    at org.springframework.data.repository.query.parser.AbstractQueryCreator.createCriteria(AbstractQueryCreator.java:119) ~[spring-data-commons-2.4.3.jar:2.4.3]
    at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:95) ~[spring-data-commons-2.4.3.jar:2.4.3]
    at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:81) ~[spring-data-commons-2.4.3.jar:2.4.3]
    at org.springframework.data.neo4j.repository.query.PartTreeNeo4jQuery.prepareQuery(PartTreeNeo4jQuery.java:69) ~[spring-data-neo4j-6.0.3.jar:6.0.3]
    at org.springframework.data.neo4j.repository.query.AbstractNeo4jQuery.execute(AbstractNeo4jQuery.java:82) ~[spring-data-neo4j-6.0.3.jar:6.0.3]
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.4.3.jar:2.4.3]
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.4.3.jar:2.4.3]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:152) ~[spring-data-commons-2.4.3.jar:2.4.3]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:131) ~[spring-data-commons-2.4.3.jar:2.4.3]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.3.jar:5.3.3]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) ~[spring-data-commons-2.4.3.jar:2.4.3]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.3.jar:5.3.3]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) ~[spring-tx-5.3.3.jar:5.3.3]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) ~[spring-tx-5.3.3.jar:5.3.3]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.3.jar:5.3.3]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.3.jar:5.3.3]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.3.jar:5.3.3]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.3.jar:5.3.3]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.3.jar:5.3.3]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.3.jar:5.3.3]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.3.jar:5.3.3]
    at com.sun.proxy.$Proxy93.findAllByPerson(Unknown Source) ~[na:na]
    at de.skillkiller.persondb.PersondbApplication.lambda$demo$0(PersondbApplication.java:50) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:804) ~[spring-boot-2.4.2.jar:2.4.2]
    ... 5 common frames omitted

2021-02-23 18:51:36.308  INFO 34603 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2021-02-23 18:51:36.311  INFO 34603 --- [           main] org.neo4j.driver.Driver                  : Closing driver instance 1555928242
2021-02-23 18:51:36.313  INFO 34603 --- [           main] org.neo4j.driver.ConnectionPool          : Closing connection pool towards localhost:7687
Disconnected from the target VM, address: '127.0.0.1:40261', transport: 'socket'

Process finished with exit code 1

CommandLineRunner (shorted):
            Person person = new Person();
            person.setFirstname("Dieter");
            person.setLastname("Zufall");

            personRepository.save(person);

            SidebarBox sidebarBox = new SidebarBox("Test", person, new ArrayList<>());
            sidebarBox.addInformation(new SidebarBoxEntry("Key", "Nein"));
            sidebarBox.addInformation(new SidebarBoxEntry("AKey", "Nein"));

            sidebarRepository.save(sidebarBox);
            List<SidebarBox> a = sidebarRepository.findAll();
            List<SidebarBox> b = sidebarRepository.findAllByPerson_Id(person.getId());
            List<SidebarBox> c = sidebarRepository.findAllByPerson(person);

Person:
@EqualsAndHashCode(callSuper = true)
@Node
@Data
@ToString(callSuper = true)
@NoArgsConstructor
@AllArgsConstructor
public class Person extends BasicNode {
    private String firstname;
    private String lastname;
    private String comment;
}

SidebarBox:
@EqualsAndHashCode(callSuper = true)
@Node
@Data
@ToString(callSuper = true)
@NoArgsConstructor
@AllArgsConstructor
public class SidebarBox extends BasicNode{
    private String title;
    private Person person;
    private List<SidebarBoxEntry> information = new ArrayList<>();

    public void addInformation(SidebarBoxEntry entry) {
        information.add(entry);
    }

    public void removeInformation(SidebarBoxEntry entry) {
        information.remove(entry);
    }
}

Basic Node:
@Data
@AllArgsConstructor
@NoArgsConstructor
public abstract class BasicNode {
    @Id
    @GeneratedValue
    private Long id;

    @DateLong
    @LastModifiedDate
    private Date changedAt = new Date();

    @DateLong
    @CreatedDate
    private Date enteredAt = new Date();
}

Unfortunately I don't understand how to fix this error.
Can you tell me how I can realize such a query?

A: Due to the inheritance with the BasicNode there was a bug in Spring Data Neo4j that took the wrong meta-information and in your case did not create the right type (SidebarBox).
An update will be available later this month. In the mean-time you could check the 6.0.6-SNAPSHOT version of SDN.
I created an example with your code https://github.com/meistermeier/neo4j-issues-examples/tree/master/relatedIdQuery
And using this very version, it works with List<SidebarBox> findAllByPerson_Id(Long personId)
For the upcoming 6.1 release we have planned to introduce a "find by object" to also give you more flexibility.


text:
Q: Animating imageview broken if it's started again before one cycle finishes I've got an ImageView that I rotate with animation by 180 degrees with OnClickListener. If it's triggered very fast (before one animation finishes) the animation bugs out and leaves the View at weird angle (for example rotated 47 degrees versus basic state).
How to prevent next animation before current one finishes or how to deal with it in another way?
bankExpandArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (totalText.getVisibility() == View.GONE) {
                    totalText.setVisibility(View.VISIBLE);;
                    bankExpandArrow.animate().rotationBy(180f).start();
                }
                else {
                    totalText.setVisibility(View.GONE);
                    bankExpandArrow.animate().rotationBy(180f).start();
                }
            }
        });

A: try using rotation instead of rotationBy


text:
Q: Expansion of fraction Is there an expansion for
$$ (x+y)^p \approx x^p + y^p + \cdots $$
for $1<p<2$?

A: Let $\alpha\in\mathbb{C}$. The series $$(x+y)^{\alpha}
=\sum_{k=0}^{\infty}\binom{\alpha}{k}x^{\alpha - k}y^{k},$$
where
$$\binom{\alpha}{k} = \frac{\alpha (\alpha - 1)(\alpha - 2) \dotsm (\alpha - k + 1)}{k!}.$$
converges for all $x,y\in \mathbb {R}$ with $x>0$ and $\left|{\tfrac {y}{x}}\right|<1$. In the special case $k=0$ we get an empty product, which is defined to be $1$.
Reference: https://en.wikipedia.org/wiki/Binomial_series


text:
Q: Valgrind Unrecognised instruction I have the following code:
#include <iostream>
#include <random>

int main() {
    std::mt19937_64 rng(std::random_device{}());
    std::cout << std::uniform_int_distribution<>(0, 100)(rng) << '\n';
}

I try to profile it using valgrind, but it says:
vex amd64->IR: unhandled instruction bytes: 0xF 0xC7 0xF0 0x89 0x6 0xF 0x42 0xC1
vex amd64->IR:   REX=0 REX.W=0 REX.R=0 REX.X=0 REX.B=0
vex amd64->IR:   VEX=0 VEX.L=0 VEX.nVVVV=0x0 ESC=0F
vex amd64->IR:   PFX.66=0 PFX.F2=0 PFX.F3=0
==2092== valgrind: Unrecognised instruction at address 0x4cdc1b5.
==2092== at 0x4CDC1B5:std::(anonymous namespace)::__x86_rdrand() (random.cc:69)
==2092== by 0x4CDC321: std::random_device::_M_getval() (random.cc:130)
==2092== by 0x4009D4: main (random.h:1619)

Preceded by multiple instances of:
--2092-- WARNING: Serious error when reading debug info
--2092-- When reading debug info from /lib/x86_64-linux-gnu/ld-2.22.so:
--2092-- Ignoring non-Dwarf2/3/4 block in .debug_info

I am on Debian using standard packages on an x86-64 platform compiling with gcc 5.3.1 using valgrind-3.11.0. The illegal instruction seems to be inside libstdc++6.
How do I get valgrind to profile my code?

A: In fact, Valgrind emulate your program with an intermediate language (VEX) to know if it discovers memory violation.
This VEX language capture all the instructions of several assemblers such as i386, amd64, arm, ... But, from time to time, it miss a few instructions (especially specialized ones like rdrand which is linked to the AES specific instructions set).
Well, this is exactly what happened with your program. Valgrind did probably stumbled on an unknown instruction and could not translate it into the VEX intermediate language.
But, you are not the only one to be in line waiting for a fix:

*

*Same issue on Launchpad.

*Same issue on KDE bugtracker.

*... and so on ...

Here is a patch that has been applied to Valgrind and that may solve the problem for you (depending on your CPU).
But, the only thing you can do is to install a newer version of Valgrind and hope that the instruction is supported in the newest version.


text:
Q: How do I create a directory so I can add multiple branches in it on GitHub? I don't use Git that often so bear with me, please. From my origin main branch repository in GitHub, I locally created a new branch (feature-typescript) using Git. I have staged and committed my files within the feature-typescript branch. I'm thinking there might be a lot of feature-[name] branches. So instead of having multiple branches with the same beginning name, I would like to put them in a directory to make my remote repository branch category more organized.
I have tried to create a branch directory named feature within my remote repository but I'm not able to figure out how. Is there a way I can create a new directory named feature to my GitHub repository using Git?
One last thing I want to add that I'm confused about. As I mentioned earlier, I have already staged and committed my feature-typescript branch. I tried to push it to my remote repository but I get this error:
fatal: The current branch feature/typescript has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin feature/typesccript

Can anyone explain the reason for this? Thank you in advance!


text:
Q: How to send "waiting" to user while bot is processing operation? I am migrating a bot from V3 to V4 and I need to send to user messages about processing status.
When user send "hello bot, what's amount of the sales on january 2019?"
While bot is processing and do not send response about this question to frontend project, I want to send 3 events from frontend project to bot with values bellow:

*

*First event will sent after 7 seconds: the name will be "waiting" and value will be 7;

*Second event will sent after 15 seconds: the name will be "wating" and value will be 15;

*Third event will be sent after 20 seconds: the name will be "wating" and value will be "20";
The bot will response those events as the code bellow:
if (activity.Type == ActivityTypes.Event)
{
   if (activity.Name == "waiting")
   {
      var entity = new Entity();
      entity.SetAs(new Mention()
      {
            Text = "waiting",
      });
      if (activity.Value.ToString() == "7")
      {
         var replyMessage = activity.CreateReply();
         replyMessage.Entities.Add(entity);
         await turnContext.SendActivityAsync(Helper.MessageToUser.WaitAMinute);
      }
      else if (activity.Value.ToString() == "15")
      {
         var replyMessage = activity.CreateReply();
         replyMessage.Entities.Add(entity);
         await turnContext.SendActivityAsync(Helper.MessageToUser.IAmHere);
      }
      else if (activity.Value.ToString() == "20")
      {
         var replyMessage = activity.CreateReply();
         await turnContext.SendActivityAsync(Helper.MessageToUser.IGotIt);
      }
   }
}

Is it a good idea?


text:
Q: PasteSpecial Link =True , for a Range There's this code i wrote that doesn't execute and sends a message error 1004 .
Dim I As Long
Dim K As Long
Dim Plage() As String
Dim Dummy As String
Dim Adresses() As String
Dim ObjetCible As Workbook
Dim AdresseCible As String
'The function Plagedetab gets ranges of tables in the workbook as strings
  Plage = Plagedetab("C:\Users\Oumayna EL JAHRANI\Desktop\Test\TABLEAUX_PILLIER_III_CONSO")
'The function adresses gets paths to Excel workbooks as strings (there's a workbook for each worksheet)
  Adresses = Adressescibles("C:\Users\Oumayna EL JAHRANI\Desktop\Test\TABLEAUX_PILLIER_III_CONSO")
Dim Fichiersource As Workbook
Set Fichiersource = Workbooks.Open("C:\Users\Oumayna EL JAHRANI\Desktop\Test\TABLEAUX_PILLIER_III_CONSO")
Debug.Print (Fichiersource.Name)
Dim ClasseurType As Workbook: Set ClasseurType = Workbooks.Open("C:\Users\Oumayna EL JAHRANI\Desktop\Test\Fichier Type.xlsx")
  For I = 1 To Fichiersource.Sheets.Count
    AdresseCible = Adresses(I)
    Debug.Print (AdresseCible)
    Set ObjetCible = Workbooks.Open(AdresseCible)
    Dummy = Plage(I)
    Debug.Print (Dummy)
    ClasseurType.Activate
      For K = 1 To ClasseurType.Sheets.Count - 1
        If K = 1 Or K = 2 Then
'Here i copy all the formatting from my original file to the workbooks i created
          Debug.Print (CStr(ClasseurType.Sheets.Count))
          Fichiersource.Activate
          Fichiersource.Worksheets(I).Select
          Range(Dummy).Select
          Selection.Copy
          ObjetCible.Activate
          ObjetCible.Worksheets(K).Select
          Range("C7").Select
          Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
          SkipBlanks:=False, Transpose:=False
          Application.CutCopyMode = False
        ElseIf K = 3 Then
        End If
      Next
'Here i need to copy links from the last worksheet to the 2 first ones( of each workbook )
    ObjetCible.Activate
    ObjetCible.Worksheets(4).Select
    Range(Dummy).Select
    Selection.Copy
    ObjetCible.Worksheets(2).Select
    Range("C7").Select
'The pastespecial beyond doesn't work i tried with paste Nothing seems to work and i get a message error 1004
    ActiveSheet.PasteSpecial (Link = True)
    ObjetCible.Worksheets(4).Select
    Range(Dummy).Select
    Selection.Copy
    ObjetCible.Worksheets(1).Select
    Range("C7").Select
    ActiveSheet.PasteSpecial (Link = True)
    ObjetCible.Close SaveChanges:=True
  Next
End Sub

The problem here is the paste special , i know it only works for worksheets so i'm thinking maybe it's the fact that i put Range("C7").Select before that blocks my code . But still i need to paste links to the table that's in that exact range .
Thank's in advance


text:
Q: How to relate xib to storyboard I build an app with storyboard I need 356 viewcontroller at storyboard that's a lot and it is not possible to work with so many screens I create tab bar and table cell at storyboard I create xib I want do relationship from xib to table cell at storyboard how do it?
Thanks!

A: You have too many view controllers but Ill humour the actual question:
UIStoryBoard *storyBoard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];

BrowserViewController *vc = (BrowserViewController*)[storyboard instantiateViewControllerWithIdentifier:@"BrowserViewController"];

//get whatever instance you want off the VCs properties a table view or whatever
// but usually youll just want to push it onto a nav controller

[[self navigationController] pushViewController:vc animated:YES];

A: You can wire from TableViewController to other view.

For example, at first, you can set TableViewCell as below:

When tap the cell, the view with the number of tapped cell.

To send the number of tapped cell to next ViewController, you can use performSegueWithIdentifier:sender: and prepareForSegue:sender as below.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"showDetail"
                              sender:[NSString stringWithFormat:@"%d", indexPath.row + 1]];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    DetailViewController *c = segue.destinationViewController;
    c.string = (NSString *)sender;
}

You can download this project and just run it.
https://github.com/weed/p120809_TableCellToView


text:
Q: why does the code runs successfully with 'let' keyword, but not with 'var'? Consider the below code :
<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>
<button id="btn-3">Button 4!</button>

<script type="text/javascript">
    var prizes = ['Watch','A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
    for (var btnNum = 0; btnNum < prizes.length-1; btnNum++) {
        // for each of our buttons, when the user clicks it...
        document.getElementById('btn-' + btnNum).onclick = function() {
            // tell her what she's won!
            alert(prizes[btnNum]);
        };
    }
</script>

Here, if I use 'var' for declaring variable btnNum in the 'for' loop, code doesn't work successfully. On clicking the buttons, each button alerts the same value which is the last element of 'prizes' array.
But if I use 'let' keyword in place of 'var', it works successfully. Now, each button on clicking shows different array element (which I want to happen). So, what's wrong with 'var' keyword here and how just replacing it with the 'let', makes everything fine?
<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>
<button id="btn-3">Button 4!</button>

<script type="text/javascript">
    var prizes = ['Watch','A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
    for (let btnNum = 0; btnNum < prizes.length-1; btnNum++) {
        // for each of our buttons, when the user clicks it...
        document.getElementById('btn-' + btnNum).onclick = function() {
            // tell her what she's won!
            alert(prizes[btnNum]);
        };
    }
</script>

A: var creates a function level variable. It is shared by each instance of the loop. Since the clicks come later, they get whatever value the variable has after the last passage through the loop.
let creates a block level variable. Each time you go around the loop you get a new variable that belongs only to that journey through the loop.


text:
Q: How to insert data into JTable? i write this code for showing strings in a table.
but it doesnt shown and has no effect.
what is problrem?
 public pamnel() {
            initComponents();
             String[] columnNames = {"First Name",
                            "Last Name",
                            "Sport",
                            "# of Years",
                            "Vegetarian"};

    Object[][] data = {
        {"Kathy", "Smith",
         "Snowboarding", new Integer(5), new Boolean(false)},
        {"John", "Doe",
         "Rowing", new Integer(3), new Boolean(true)},
        {"Sue", "Black",
         "Knitting", new Integer(2), new Boolean(false)},
        {"Jane", "White",
         "Speed reading", new Integer(20), new Boolean(true)},
        {"Joe", "Brown",
         "Pool", new Integer(10), new Boolean(false)}
    };

     jTable1 = new JTable(data, columnNames);

 }

Edit:
  I add Jtable on a panel.

in the main add panel to a jframe.
 JFrame frame = new JFrame();
    frame.add(new pamnel());
    frame.setVisible(true);
    frame.setSize(600, 600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

The table is shown but data isn't show.
the row and column of table is empty!

A: You have to add the JTable to its parent-component and setVisible().

A: Did you really write the code yourself? I remember this from an oracle swing tutorial. Anyway, you've not added the JTable to a component. Observe below source
package components;

/*
 * SimpleTableDemo.java requires no other files.
 */

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class SimpleTableDemo extends JPanel {
    private boolean DEBUG = false;

    public SimpleTableDemo() {
        super(new GridLayout(1,0));

        String[] columnNames = {"First Name",
                                "Last Name",
                                "Sport",
                                "# of Years",
                                "Vegetarian"};

        Object[][] data = {
        {"Kathy", "Smith",
         "Snowboarding", new Integer(5), new Boolean(false)},
        {"John", "Doe",
         "Rowing", new Integer(3), new Boolean(true)},
        {"Sue", "Black",
         "Knitting", new Integer(2), new Boolean(false)},
        {"Jane", "White",
         "Speed reading", new Integer(20), new Boolean(true)},
        {"Joe", "Brown",
         "Pool", new Integer(10), new Boolean(false)}
        };

        final JTable table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        if (DEBUG) {
            table.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    printDebugData(table);
                }
            });
        }

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this panel.
        add(scrollPane);
    }

    private void printDebugData(JTable table) {
        int numRows = table.getRowCount();
        int numCols = table.getColumnCount();
        javax.swing.table.TableModel model = table.getModel();

        System.out.println("Value of data: ");
        for (int i=0; i < numRows; i++) {
            System.out.print("    row " + i + ":");
            for (int j=0; j < numCols; j++) {
                System.out.print("  " + model.getValueAt(i, j));
            }
            System.out.println();
        }
        System.out.println("--------------------------");
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("SimpleTableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        SimpleTableDemo newContentPane = new SimpleTableDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

The JTable is added to the JPanel in the SimpleTableDemo constructor. Then the JPanel is set as the content pane in the for the main JFrame, which is made as frame.setVisible(true). This happens in the createAndShowGUI method. The reason your code doesn't display the JTable is because a JTable is an abstract widget. You need to add the abstract widget to a component, such as a JFrame (in the above case) for it to be displayed.

A: Try something like this, just to make it run. Notice you drop the voidin the pammel method and a main was added.
import javax.swing.*;

class TableDemo {
    JTable jTable1;
    public static void main( String ... args ) {

       TableDemo tableDemo = new TableDemo();
       tableDemo.pamnel();

       JFrame frame = new JFrame();
       frame.add(  new JScrollPane(tableDemo.jTable1) );
       frame.pack();
       frame.setVisible( true );
    }
    public void initComponents(){
    }
    public void pamnel() {
            initComponents();
             String[] columnNames = {"First Name",
                            "Last Name",
                            "Sport",
                            "# of Years",
                            "Vegetarian"};

        Object[][] data = {
            {"Kathy", "Smith",
             "Snowboarding", new Integer(5), new Boolean(false)},
            {"John", "Doe",
             "Rowing", new Integer(3), new Boolean(true)},
            {"Sue", "Black",
             "Knitting", new Integer(2), new Boolean(false)},
            {"Jane", "White",
             "Speed reading", new Integer(20), new Boolean(true)},
            {"Joe", "Brown",
             "Pool", new Integer(10), new Boolean(false)}
        };

        jTable1 = new JTable(data, columnNames);

     }
}

A: It seams like the new JTable is not being added to pamnel.
Probably another instance, not initialized with data, is being added in initComponents()
private JTable jTable1 = new JTable();    // empty table

public pamnel() {
    initComponents();

    String[] columnNames = ...
    Object[][] data = ...

    jTable1 = new JTable(data, columnNames);  // new instance created here
    // nothing happens with that new instance
}

private void initComponents() {
    ...
    add(jTable1);    // added empty table, not the one created above (constructor)
    ...
}

The add method does not add a reference to the variable to the component, it only adds the value of the variable. So, if the variable is changed, the component still contains the previous (old) value.
Change the order of create-add:
private JTable jTable1;

public pamnel() {
    initComponents();
}

private void initComponents() {
    ...
    createTable();
    add(jTable1);
    ...
}

private void createTable() {
    String[] columnNames = ...
    Object[][] data = ...

    jTable1 = new JTable(data, columnNames);
}


text:
Q: How to start a Python script in LXTerminal using crontab at boot-up I have a script called myscript.py (in /home/pi) that I want to run in the terminal every time the Pi boot up.
I want to activate this by using 'crontab'. However after searching and trying stuff out I'm still no closer then when I was at the start.


text:
Q: iterate list and compare it's values with dict I am dealing with 1. list of dictionaries and 2. list. I am trying to:
1. iterate through list (list1),
2. Match the list1's value with the ID of API response, if found- put entire dict in a new_dict
3. else skip
API response in Json format:
   list_of_dict=[{"id":1500,
      "f_name": "alex",
       "age": 25
      },

      {"id" :1501,
       "f_name":"Bob",
       "age": 30
      },
      {"id" :1600,
       "f_name":"Charlie",
       "age": 35
      }
      ...
     ]

And a list1:
list1=[1500,1501,1211.....]

According to this, 1500 & 1501 is present in list_of_dict so that entire dict will be added in new_dict.
My attempt:
new_dict=dict()
for i,val in enumerate(list1):
    #assuming val found in dict
    #so put it in new dict
    print i ,"=",val
    new_dict.update({"id": val,"name":name, "age":age})

What i see is this code taking only last item of the list and updates the dict.. but in my case, new_dict will contains two dictionaries with id 1500 and 1501. What i am missing?

A:     list_of_dict = [{"id":1500,
                     "f_name": "alex",
                     "age": 25
                     },

                     {"id" :1501,
                      "f_name":"Bob",
                      "age" 30
                     },
                     {"id" :1600,
                      "f_name":"Charlie",
                      "age" 35
                     }
                     ...
                  ]

dicts = {d['id']:d for d in list_of_dict}
list1=[1500,1501,1211.....]

answer = [dicts[k] for k in list1 if k in dicts]

A: list_of_dict = [{"id":1500,
                     "f_name": "alex",
                     "age": 25
                     },

                     {"id" :1501,
                      "f_name":"Bob",
                      "age": 30
                     },
                     {"id" :1600,
                      "f_name":"Charlie",
                      "age": 35
                     }
                  ]

list1=[1500,1501,1211]

ret = filter(lambda x: x['id'] in list1, list_of_dict)
print ret

Check out the useful and simple filter function built-in to python.  It iterates through an iterable (list) and returns only the items that return true for the provided function
In this case, our filtering function is:
lambda x: x['id'] in list1

A: You can do this with a simple list comprehension, filtering the dicts by whether their id is in the list:
result = [d for d in list_of_dict if d["id"] in list1]

If your list1 is larger, you might want to turn it into a set first, so the lookup is faster:
list1_as_set = set(list1)
result = [d for d in list_of_dict if d["id"] in list1_as_set]


text:
Q: Getting pretty URLs with a GET form I'm trying to make dynamic/pretty urls like domain.com/p/term
In my case /p is actually a PHP script, via an .htaccess entry.
<Files "p">
  ForceType application/x-httpd-php
</Files>

and term is a search term, used to fetch relevant data from a database
So, if the "/term" part is provided in the URL everything is good. The problem is, if the request is just "domain.com/p/" with no term, I need to show a form asking for a term, and since I want the term the viewer enters to be displayed in the URL, I thought I should use a GET form. Super basic.. or so it seems :/
<form action="/p/" method="GET">
<input type="text" name=pid>
<input type="submit">
</form>

When submitted, it results in the URL being domain.com/p/?pid=term
Now, I just need to find how to mod rewrite that to domain.com/p/term
I've tried numerous re-write rules and can't get the desired result...
My latest attempts...
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

#Rewrite GET search "/p?pid=term" => "/p/term"
RewriteRule ^p\?pid=(.*)$ /p/$1 [L]

#Rewrite GET search "/p/?pid=term" => "/p/term"
RewriteRule ^p/\?pid=(.*)$ /p/$1 [L]

Neither seem to be triggering the rewrite, I still get /p/?pid=term in the address bar.
I've looked over several related questions, but none seem to address this scenario. A tap with a clue stick would be greatly appreciated.

A: You can not match against QueryString (Url part after the ?) using a RewriteRule. You need to match against %{QUERY_STRING} variable
RewriteEngine on

RewriteCond %{QUERY_STRING} ^pid=(.+)$
RewriteRule ^p/?$ /p/%1? [L,R]

A: It should be as follows
RewriteRule ^p/([0-9a-z]+) p/?pid=$1


text:
Q: Delphi rewriting .dat file I'm using Delphi and am attempting to rewrite a .dat file which stores records of books. One of the variables is .BookAmountAvailable, when a book is taken out I want it to lower to .BookAmountAvailable of that record by 1, I've read the file into a typed array, then found the correct book and lowered the amount available by 1.
When I rewrite the file with the updated array it doesn't write it correctly (it only writes one of the records back correctly, and the rest of the records are left blank.
The code to read into the array is:
assignfile (BookFile,'BookFile.dat');
reset (BookFile);
BookCounter := FileSize(BookFile);
SetLength(BookArray, BookCounter);
for Count1 := 1 to BookCounter  do
  begin
    read(BookFile, SingleBook);
    BookArray[Count1] := SingleBook;
  end;
closefile (BookFile);

The code I've used to rewrite the file is:
  BookArray[Count].BookAmountAvailable := BookArray[Count].BookAmountAvailable -1;
  assignfile (BookFile, 'BookFile.dat');
  rewrite (BookFile);
  for Count1 := 1 to BookCounter do
    begin
      seek (BookFile, Count1);
      write(BookFile, BookArray[Count1]);
    end;
  closefile (BookFile);

What is it that is causing it to not rewrite the array properly?

A: There are two problems with your code.

*

*Dynamic Arrays are ZERO based, and your indexing them as 1 based arrays.

*Seek() call is not needed.


text:
Q: GIS Certification I have a question regarding GIS certification.
My main goal is to develop GIS web applications.  Currently I am a developer with over 20 years building software and for the past 10 building web application using mostly Java on the server and HTML/Javascript/CSS on the client.  I also have a lot of experience with data integration.
I am currently enrolled in the Penn State's Postbaccalaureate Graphical Information System program. I just completed the first course this week and there are an 4 additional classes after that.  The first course was very good and informative and I feel I learned a lot of background knowledge in the GIS field.   I am trying to decide if I should continue on with the additional classes and complete the program.
Two reasons why I am reluctant to continue:
1) Not sure if this is the best way for me to get into the GIS industry given I want to develop in the field
2) The classes are expensive

A: Personally think that for development work, there's not too much a programmer can get from a GIS course, unless the course is run specifically for Computer Science students (which is rare). My learning (coming from a similar background to yours with lesser experience at the time) after enrolling in a Master's course was applied physics, spatial/locational modelling and statistical theory used in Remote Sensing amd Urban planning. It was all very interesting then, but I haven't used it since. Most of the work in GIS I have done has been standard IT work with basic GIS data model concepts involved. However, one of the biggest benifits of doing a Master's for me was learning how to write and present better and more confidently, which is a transferrable skill.
Questions you might want to ask yourself :
Do you prefer open-source development or would you rather work with vendors such ESRI/Manifold/MapInfo etc.?

My personal choice for programming was
  open source tools and I picked up GIS
  specific Java tools such as
  JTS/GeoTools etc on my own and more
  recently GeoServer/gdal.

Do you prefer Desktop or web?

web development jobs are harder to
  find and the user base can be hard to
  please as they are used to highly
  interactive desktop apps

What field would you like to work in - government, military, environment?

By far the biggest advantages of a GIS
  career is opens up avenues into
  fields you might not have considered
  or had access to with just an IT background

Hope this helps
sfk

A: Is the Penn State Program teaching classes according to the test?
I have been working with ESRI's software in the industry for almost 3 years, and I really feel like this certification would help me toward my goal of being a high level GIS developer.
My personal rule of thumb is that you get your best education out in the field. However, it sounds like the Penn State program may have some information that would be very useful to you, plus you get the degree.  If it adds to your ability to get GIS certification, that is definitely a plus.
--Seth

A: Aim to meet the criteria for the Esri Certification for Web Developer Professional, and ull be very desirable.

A: Have you seen this question, Switching career from web application to GIS developer??
I believe that if you're a strong developer who learns fast, you're a very attractive proposition for GIS jobs as is.  I'd suggest that you're better off spending your money on going to a GIS developer conference or two than education, given your current objectives.

A: If all you want to do is produce Web-GIS applications then I'd recommend you take my GEOG585 course "Open Web Mapping" (https://www.e-education.psu.edu/geog585/). But I have to say that you may well benefit from the other courses in the certificate to help you get up to speed in why geography is harder than it looks. I see a lot of web development experts and expert programmers asking questions on this forum and other lists which show that they just don't get the geographic concepts they are trying to implement. I suspect that nearly all of us could point to web map apps that really would work better (at all?) if the developers had asked a geographer at some point.


text:
Q: How to solve "Unable to initialize SMTP properly." when using using git send-email? I was trying to send an patch using git .
When i try sending mail the following error output is generated

My .gitconfig file looks like this

A: Corporate firewalls may block the required ports
I noticed that this problem only happened at work and not at home, and then found out that my work firewall was blocking the required IMAP / SMTP ports.
If that is the case, you must talk to your network administrator.
The difference is that when you use a web interface like gmail's, all traffic goes through HTTP ports, which are allowed, but git send-email uses the email protocol ports directly.
A good way to test that without polluting public mailing lists is to try to send regular emails with mutt or some other local email client first.
You can also check if outgoing ports are getting blocked with answers for this question: https://superuser.com/questions/631087/how-to-easily-determine-which-outbound-ports-arent-blocked-by-firewall

A: I have a smiler issue and,After lots of research I got the answer ...
Please configure the .gitconfig file like this ...
[sendemail]
    from = yourEmail@gmail.com
    smtpserver = smtp.gmail.com
    smtpserverport = 587
    smtpencryption = tls
    smtpuser = yourEmail@gmail.com
    smtppass = password
    suppresscc = self
    chainreplyto = false

After that you must have to allow your mail account to login from less secure App ,like for gmail to do the same follow the link https://support.google.com/accounts/answer/6010255?hl=en

TO debug the actual error you can enable the following flag..
--smtp-debug=1

To help keep your account secure, from May 30, 2022, Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.

A: I had a similar issue till I realised that I had made the encryption ssl instead of tls. Changing this parameter in .gitconfig helped me.
This says that the git version may not be up to date. Try that maybe?

A: Try this link:
http://morefedora.blogspot.com/2009/02/configuring-git-send-email-to-use-gmail.html
In addition to that, you might have to have to change the setting in your gmail account to allow less secure apps setting (https://www.google.com/settings/security/lesssecureapps).

A: Are you able to Ping smtp server. if not use IP address of smtp server.


text:
Q: what is the correct way to check variable is present in http response? I've created this service to handle auth and it is working fine...
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { tap } from 'rxjs/operators';
import { Storage } from '@ionic/storage';
import { EnvService } from './env.service';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class AuthService {

  isLoggedIn = false;
  token:any;

  constructor(
    private storage:Storage,
    private http: HttpClient,
    private env: EnvService,
  ) { }

  login(email: String, password: String) {

    let formData = {
      usuario    : email,
      senha      : password,
      retsession : true
    }

    return this.http.post(this.env.API_URL+'/login', formData).pipe(
      tap(response => {
        var token = ('jwt' in response) ? response.jwt : null ;
        this.storage.set('token', token)
        .then(
          () => { console.log('Token Stored: ' + token); },
          error => console.error('Error storing item', error)
        );
        this.token = token;
        this.isLoggedIn = true;
        return token;
      }),
    );
  }

}

Even it is working, I'm getting a compile error
[ng] ERROR in src/app/services/auth.service.ts(36,52): error TS2339: Property 'jwt' does not exist on type 'never'.

This error is on the line when I check if my token is present in http response data...
What is the correct way to check this avoiding this error?

A: To check if the token is present you could do:
let token = response['jwt'] ? response['jwt'] : null ;
Kind regards

A: sagat's answer is correct. Here is an example of how to pass an interface into an http call:
// form-data.interface.ts
export interface FormData {
  usuario: string;
  senha: string;
  retsession: boolean;
}

// login-response.interface.ts
export interface LoginResponse {
  jwt: string;
  // other properties
}

// login.service.ts
login(formData: FormData): Obvservable<LoginResponse> {
  return this.http.post<LoginResponse>(`${this.env.API_URL}/login`, formData);
}

// call this from your component (login.component.ts) or your state management (login.state.ts)
// call it like so
this.login(formData).subscribe((response) => {
  // perform your logic with the response
}

Your http post will return an observable that you can subscribe to. Pipe and tap are not needed here but basically do the same thing.
Note:
Instead of an interface if you're not receiving values for properties you're expecting you can use a class like so:
// login.response.model.ts
export class LoginResponse {
  jwt: string
  // other properties

  constructor(data: LoginResponse) {
    this.jwt = (data && data.jwt) ? data.jwt : '';
  }
}

This method will make sure all properties exist on the model and are set and have initial values. You won't encounter any errors if pieces of data are missing.


text:
Q: webpack lektor bootstrap scss @import paths I am attempting to use bootstrap with lektor.
Following the instructions found here, everything worked as expected. I then used npm to install jquery and bootstrap.
"Requiring" jquery and bootstrap in webpack/js/main.js works without a hitch. However when I attempted to
@import "bootstrap";

in webpack/scss/main.scss I got the following:
ERROR in ./~/css-loader!./~/sass-loader!./scss/main.scss
    Module build failed:
    @import "bootstrap";
    ^
          File to import not found or unreadable: bootstrap.
    Parent style sheet: stdin
          in /home/lysdexia/Projects/thing/webpack/scss/main.scss (line 4, column 1)

This lead me to a bunch of not-very-helpful reading vis the node search path. I found that all three of the the following:
@import "/home/lysdexia/Projects/thing/webpack/node_modules/bootstrap/dist/css/bootsrap.css";
@import "/bootstrap/dist/css/boostrap.css";
@import "/bootstrap.css";

. . . all seem to import without errors. All the scss examples show a simple @import whatever; which I now suspect may be shorthand for something, or an assumption of a different configuration.
Unfortunately, upon attempting to @extend a class with a bootstrap class gives me a The selector ".row" was not found., which says to me that the import didn't actually work, and failed without an error.
I must admit some embarrassment and confusion here. Is there a way to examine node's search paths? It seems somewhat logical (if a bit wishy-washy) that "/" can mean "full path from root" or "my paths start in node_modules", but why /bootstrap.css would even appear to work is just bizarre.


text:
Q: Unique way to express a positive rational number In the book of G.H. Hardy, "A course of pure mathematics", I found this miscellaneous problem from chapter I, is the exercise 2:

Prove:

*Any positive rational number can be expressed in one and only one way in the form
  $$
a_{1} + \frac{a_{2}}{2!} + \frac{a_{3}}{3!} + \cdots + \frac{a_{k}}{k!}
$$
  where $a_{1},a_{2},a_{3},\cdots,a_{k}$ are integers, and
  $$
0 \leq a_{1},0 \leq a_{2} < 2,0 \leq a_{3} < 3, \cdots , 0 < a_{k} < k
$$

I have left this image for reference, which is from the exercise in the book:

I have some ideas how to prove this, maybe using the representation of $e^{x}$ as an infinite sum, but in general, I have no idea how to solve this problem.

A: Sketch: Let $\frac{p}{q}$ be the rational number that is being calculated.

*

*Since $a_i<i$ for $i>1$, we know that
$$
\sum_{i=k}^m\frac{a_i}{i!}\leq\sum_{i=k}^m\frac{i-1}{i!}=\sum_{i=k}^m\frac{1}{(i-1)!}-\sum_{i=k}^m\frac{1}{i!}=\sum_{i=k-1}^{m-1}\frac{1}{i!}-\sum_{i=k}^m\frac{1}{i!}=\frac{1}{(k-1)!}-\frac{1}{m!}<\frac{1}{(k-1)!}.
$$

*We define each $a_i$ iteratively.  In particular, we choose $a_k$ so that $0\leq\frac{p}{q}-\sum_{i=1}^k\frac{a_k}{k!}<\frac{1}{k!}$.  If $a_k$ is too small, then the remainder is too large and could never be the sum of the remaining terms and if $a_k$ is too large, then the sum is larger than $\frac{p}{q}$.  This shows uniqueness (but not existence - this procedure might never finish).

*To show existence, we could use induction.  We'll show that
$$
\frac{p}{q}=\sum_{i=1}^q\frac{a_i}{i!}.
$$
We write
$$
\frac{p}{q}=\frac{p(q-1)!}{q!}.
$$
Define $p_q=p(q-1)!$.  Define $a_q$ so that $p_q\equiv a_q\pmod q$.  Then,
$$
\frac{p}{q}-\frac{a_q}{q!}=\frac{p_q-a_q}{q!}=\frac{p_{q-1}}{(q-1)!}
$$
for some integer $p_{q-1}$.  We can continue in this way, where $a_i$ is defined so that $p_i\equiv a_i\pmod i$.  Since the denominator is always decreasing, eventually, the result is an integer, which is $a_1$.  This construction shows existence, but not uniqueness.


text:
Q: Why do some yeoman scaffolds take up so much space? How to optimize? I noticed some generators take up quite a bit of space. For instance, generator-angular, after a fresh scaffold, takes up about 312MB. If I have ten Angular projects, that's quite a bit of space wasted.
 12K    Gruntfile.js
4.0K    README.md
 88K    app
4.0K    bower.json
3.9M    bower_components
308M    node_modules
4.0K    package.json
 16K    test
312M    total

Is there some way to have all my Angular projects reference a common set of node modules, so I can have a single folder that's 300MB, rather than ten of them?

A: A solution to minimize the memory footprint of the application is to install the node dependencies globaly with npm install >dependency< --global
See https://docs.npmjs.com/cli/install

A: When running your npm install do this:
`npm install -g [the-module-name]`

Doing this should save the reference globally, meaning that all other project you create, won't have to put the module into its own folder, but simply reference to the folder where the module has been saved globally.
BEWARE: This could create another problem, since the module need a module, which need a module, and so on. This gave me problems when deleting a project, since the file path seems to be to long for a Windows machine.
There's an easy fix here though: http://blog.ardill.com/2013/06/path-too-long-when-trying-to-delete.html


text:
Q: Plotting function of 2D space + time using Plot3D in Mathematica Is there a simple way of plotting a function f(x,y,t) = Exp[t-x-y] by setting the time t? I've tried several variations of
Plot3D[Evaluate[f[t,x,y],t->0],{x,0,1},{y,0,1},PlotRange -> All]

But I can't get it to work. I want to be able to change t and see how the plot changes, but I'm also using the equation f for a differential equation so I'm taking partials and I need t to be symbolic for other parts of the notebook. Or is there a way to make a plot video that updates with time?

A: Expanding on the comments.
Interactively manipulate the plot
f[x_, y_, t_] := Sin[t x] Sin[t y]
Manipulate[Plot3D[f[x, y, t], {x, -Pi, 2 Pi}, {y, -Pi, Pi}], {t, 0, 3, 1/8}]

Generate a list of plots
plots = Table[Plot3D[f[x, y, t], {x, -Pi, 2 Pi}, {y, -Pi, Pi}], {t, 0, 3, 1/8}];

Export the plots to an animated GIF
Export["plots.gif", plots]


text:
Q: Is it okay to store dynamic data in mongodb? I am using mongoose with nodejs.
For example I have a schema like that.
new Schema({
  x: Number,
  y: Number
});

My application needs difference of this props in a multiple places. It will be better if I will get this value from db rather than calculating it each time. So I need something like
new Schema({
  x: Number,
  y: Number,
  diff: this.x - this.y
})

Is it okay to do so? If yes, how I can do that?

A: Yes, you can store derived data in the database. Especially if calculations are expensive there are many cases where this makes a lot of sense.

If yes, how I can do that?

Most frequently the derived data is calculated in the application.
MongoDB also provides views.


text:
Q: How can I edit a pointer to a list node from a function in a recursion? I have been writing a program that is quite complex compared to what I have dealt with until now. Anyways at some point I am supposed to write a function that will manipulate a struct list. I'm trying to make this question as simple as possible so I wrote down a pretty simple piece of code just for reference.
Here is the thing: at first I call testf from another function providing it with a valid current as well as an i with a value of 0. This means that testf will call itself about 100 times before it starts accessing the rest of the code. This is when all the generated instances of testf will start getting resolved.
 void testf(listnode *current, int *i) {
   wordwagon *current2;

   current2 = current;
   if (*i < 100) {
     *i = *i + 1;
     current2 = current2->next;
     testf(current2, i);
   }

   current = current->next;
   return;
 }

If, let's say, I have enough connected list nodes at my disposal, is current = current->next; the correct way for the "last" testf function to access and edit the caller's current2 value (which is this function's current), or am I horribly wrong?
If I am, what is the way to make changes to the caller function's variables from inside the called function and be sure they won't go away as soon as the called function returns? I find it kind of hard to get a good grasp on how pointers work.
It is very likely that I have left out important information or that I haven't asked my question clearly enough. Please inform me if that is the case so I can edit in whatever you need.
Thanks in advance.

A: You can pass pointer  to a pointer in your function, and derefrence it to get a listnode pointer back , here is how the code will look like after that ( not tested for compilation ) :
void testf(listnode **current, int *i) {  // accept pointer to listnode pointer
   wordwagon *current2;

   current2 = *current;   // retreive pointer value by dereferece
   if (*i < 100) {
     *i = *i + 1;
     current2 = current2->next;
     testf(&current2, i);  // recursively call by reference to the pointer
   }

   *current = (*current)->next; /* change the current pointer next pointer, CORRECTED as suggested by Azure */
   return;
 }

Here is a list of really good articles for learning pointers :
a) http://cslibrary.stanford.edu/102/PointersAndMemory.pdf
b) http://cslibrary.stanford.edu/103/LinkedListBasics.pdf