text:
Q: How to return a string in a method in an ionic typescript file and assign to a variable? Cannot return a string to another method in ionic typescript file.
We want to eventually return the JSON.stringify(res) and assign this to the stringset. When this didn't work we tried testing by simply returning a string "hi". This simple return does not work.
We have tried returning any or string types, the ide does not like the string type.
Please help in determining how to return a string from the postCall method so it is retained by the stringset variable.
 navNextQuestion() {
  let stringset = this.postCall("A004");
  this.navCtrl.push('QuestionPage', {
      firstPassed: stringset,
      secondPassed: "it did pass"
  });
 }

 //Below passes variable to PHP file#
 public postCall(id:string): string {
 let data=JSON.stringify({answer_id:id, type:"answer"});
 this.http.post('http://localhost/retrieve-data.php',data)
 .map(res => res.json())
 .subscribe(res => {
 alert("success "+JSON.stringify(res));

 //parses JSON response into array (uncomment below when ready)
 //this.response = JSON.stringify(res);

 return "hi";

A: You need to return your post and eventually your map to that funktion to use the JSON Data you recieve in your post.
You can only access the response data inside of the subscribe and the map funktion.
Update
navNextQuestion() {
let stringset = this.postCall("A004").subscribe(stringset => {
this.navCtrl.push('QuestionPage', {
  firstPassed: stringset,
  secondPassed: "it did pass"
   });
 });
}

 //Below passes variable to PHP file#
 public postCall(id:string){
 let data=JSON.stringify({answer_id:id, type:"answer"});
 return this.http.post('http://localhost/retrieve-data.php',data)
   .map(res => res.json());
}

I edited the code to exactly replace yours.


text:
Q: git-svn dcommit fails on directory with umlauts My Setup
I'm working on Windows XP 32bit (german). I installed
$ git --version
git version 1.7.4.msysgit.0

and created a git-svn repository where I successfully commited a bunch of files and directories from a previous SCM.
The Problem
But on the 2nd git-svn dcommit I got this error:
$ git svn dcommit
Committing to http://mysvnserver/repos/myrepo/trunk ...
RA layer request failed: PROPFIND request failed on '/repos/myrepo/trunk/path/with/weird/%DC%20f%FC%20umlauts': \
 PROPFIND of '/repos/myrepo/trunk/path/with/weird/%DC%20f%FC%20umlauts': 207 Multi-Status (http://mysvnserver) at C:\Programme\Git/libexec/git-core/git-svn line 4529

The directory has german umlauts in its name and I think the problem is a wrong conversion between msysgit, svn and windows. I can not delete the directory directly in the svn repository browser of TortoiseSVN nor can I check out the directory on cygwin because the directory is missing at all there.
I'm now stuck with a broken directory in SVN and can not git-svn dcommit the deletion of the directory because I then get the RA layer request failed error.
My Question
Any tips? Do I have to clone the whole repository from SVN again?

A: The quick solution
I was able to remove the parent folder with the repository browser of TortoiseSVN. That fixed it for me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: incorrect synatax near '>' select (round(
   (isnull(sum(OD1.AfterDiscount),0)
    + isnull((select sum(td.freight) from K_FS_GenerateDcno TD where TD.Name =32),0)
    - isnull((select sum(recamount) from   K_FS_AmountReceived AR where  AR.Name=32),0)
   )>500000,0))
from  K_FS_OrderDetails OD
left outer join K_FS_OrderDetails1 OD1 on OD1.ID=OD.sno
left outer  join K_FS_DistributorDetails DD on DD.sno = OD.customername
where OD.confirmation='True' and OD.customername=32

I am getting an error at > 500000 condition...
please help me

A: Try this instead:
        Select    a.*
        From (
             select round(
             (
                 isnull(sum(OD1.AfterDiscount),0)+
                  isnull((select sum(td.freight) from K_FS_GenerateDcno TD where TD.Name =32),0)  -
                  isnull((select sum(recamount) from   K_FS_AmountReceived AR where AR.Name=32),0)
            ),0)   as RoundedAmount
            from  K_FS_OrderDetails OD
            left outer join K_FS_OrderDetails1 OD1 on OD1.ID=OD.sno
            left outer  join K_FS_DistributorDetails DD on DD.sno = OD.customername
            where OD.confirmation='True' and OD.customername=32
        )   as a
        Where RoundedAmount > 500000

This will evaluate RoundedAmount after the calculations..

A: some parentheses are wrong but there is no information what you want to do with the query.
the simplified structure of your select part is:
(round( (isnull()+isnull()-isnull()) > 50000,0))

so you are rounding a boolean value ?!


text:
Q: How to check output from a method in the child class has correct size Is there a pythonic way of checking the outputs of a method in a child class from the parent class.
For example if you have this structure, I want to perform a check (in the parent class) on the output from the method 'generate' in the child class (e.g. if it has the correct shape).
class parent_class(object):

    def generate(self):
        raise NotImplementedError

class child_class(parent_class):

    def generate(self, array_size):
        return np.random.uniform(size = [10,10])

The following achieves the correct effect, but requires calling the method check_class in the init method of the child class. Is there any way of achieving this check without having to remember to put the call to the 'check_class' method in every child class?
class parent_class(object):

    def generate(self, size):
        raise NotImplementedError

    def check_class(self):
        assert self.generate([5,5]).shape == (5,5), 'Output of generate has the wrong shape'

class child_class(parent_class):

    def __init__(self):
        self.check_class()

    def generate(self, size):
        return np.random.uniform(size = [10,10])

If you call generate, this will now check the size of the output is correct, as required:
a = child_class()

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call    last)
<ipython-input-58-389a5f325aca> in <module>()
----> 1 a = child_class()

<ipython-input-56-99054bf26f0e> in __init__(self)
 10
 11     def __init__(self):
---> 12         self.check_class()
 13
 14     def generate(self, size):

<ipython-input-56-99054bf26f0e> in check_class(self)
  5
  6     def check_class(self):
----> 7         assert self.generate([5,5]).shape == (5,5), 'Output of generate has the wrong shape'
  8
  9 class child_class(parent_class):

AssertionError: Output of generate has the wrong shape

A: You can set the check at instance creation level (__new__()) so that it always executes, e.g.:
class Parent(object):

    def __new__(cls, *args, **kwargs):
        instance = super(Parent, cls).__new__(cls)  # create our instance
        instance.check()  # immediately call check on it
        return instance  # return it to the requestor

    def check(self):
        assert self.generate() == 10, "generate() must return 10"

    def generate(self):
        raise NotImplementedError

class Child(Parent):

    def generate(self):
        return 10

class BadChild(Parent):

    def generate(self):
        return 20

child = Child()
# everything's fine...

parent = Parent()
# NotImplementedError

bad_child = BadChild()
# AssertionError: generate() must return 10

You can also use metaclasses, but don't go there if you don't need it.
As a side note, I hope you're not doing this thing as a sort of an API for your module, tho. Don't write Javaesque Python - treat the users of your module as adults and make it clear what your module expects.


text:
Q: Alter assembly permission set to Safe Is there a way to alter the permission set for all the assemblies under a database at once?
I am seeing the error Assembly 'Logger' cannot be loaded because this edition of SQL Server only supports SAFE assemblies. So I want to change the permission from Unsafe to Safe for all the assemblies under a particular database.
Help appreciated!!


text:
Q: Why does Perl complain about "Unsuccessful stat on filename containing newline"? I am getting an error I do not understand. I am using File:Find to recurse a fylesystem on Windows using Activestate Perl 5.8.8 and trying to stat $File::Find::name; so I am not stat-ing a filename got from a text file scanning requiring chomp-ing or newline removing. I was unable to get file modification time, the mtime in:
my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat($File::Find::name);

so trying a
-s $File::Find::name

gives me the error:

Unsuccessful stat on filename containing newline

A typical file name found is F01-01-10 Num 0-00000.pdf but I get the same error even renaming in E02.pdf

A: According to perldiag if any file operation fails and the filename happens to contain a newline character, the warning "Unsuccessful  on filename containing newline" will be emitted.
The assumption is that, as you say, the filename has come from standard input or similar, and the user has forgotten to chomp the newline away. You might want to pass the string through chomp anyway, just to see if it works.
There is some evidence that &CORE::stat mtime might be broken with some combinations of OS patchlevel and ActiveState Perl versions - a suggested workaround is to use the File::stat module like so:
my $sb = stat($File::Find::name);
my $mtime = scalar localtime $sb->mtime;

...you might find File::stat's object representation to be more convenient than the list returned by CORE::stat.

A: Even i got the same error while trying to delete a folder. i used chomp before using rmtree command. That solved my problem.

A: Ran into this same problem in my script and found my mistake to be when i created the file i tagged a date stamp to the end and forgot to chomp my $DATE variable before adding it to the file name.

A: Yep, just ran into this myself with a hand built scalar. Scratched my head a bit until I realized I had included a time/date stamp in the filename. Chomp the date command and voila, problem resolved.


text:
Q: Limit devices that app can run I have found this great answer with this list
Do I need to add armv6 support when limiting apps to iOS 4.0+?
ARMv8 / ARM64 = iPhone 5s, iPad Air, Retina iPad Mini
ARMv7s = iPhone 5, iPhone 5c, iPad 4
ARMv7  = iPhone 3GS, iPhone 4, iPhone 4S, iPod 3G/4G/5G, iPad, iPad 2, iPad 3, iPad Mini
ARMv6  = iPhone, iPhone 3G, iPod 1G/2G

So if I want limit my app to be run on iPhone 5 and higher, can I just remove armv7 architecture from Xcode, or Apple reject this kind of limitation?
Just to be clear I don't want to limit with iOS version, I just want to support iPhone 5 and higher with latest iOS version. Is it possible?


text:
Q: How to point to a geom_label with a geom_segment? Let's start with this toy example:
library(ggplot2)

nodes=data.frame(x = c(30, 50, 72, 35, 48, 70),
                 y = c(90, 65, 93, 15, 37, 10),
                 label = c("box1", "box2", "box3", "box4", "box5","box6"))
links=data.frame(x = c(50, 72, 48, 70, 48),
                 y = c(65, 93, 37, 10, 37),
                 xend = c(30, 50, 35, 48, 50),
                 yend = c(90, 65, 15, 37, 65),
                 startname = c("box2", "box3", "box5", "box6", "box5"),
                 endname = c("box1", "box2", "box4", "box5", "box2"))

gg<-ggplot(nodes, aes(x=x, y=y)) +
  geom_segment(data=links, aes(x=x, y=y, xend=xend, yend=yend)) +
  geom_label(aes(label=label)) + xlim(0, 100) + ylim(0,100) +
  theme_void()+ theme(legend.position = "none")
gg

In this case I'm already making sure to have the segments come before the labels so that the labels will be on top of the segments giving the appearance that the line is going to the label.  That's fine here, but what I really want to do is point to one of the boxes so I need the points that make up the exterior of the label box.  I've seen similar questions which use the ggrepel package but that solves the problem 'how to keep the label from interfering with data points?' but I want to make the label the center of attraction.
I tried converting gg into grob.  I looked at str(ggplotGrob(gg)$grobs[[5]]$children[[4]]$children[[1]]) which was promising as it starts with:
List of 13
$ label        : chr "box1"
$ x            : 'simpleUnit' num 0.318native
..- attr(*, "unit")= int 4
$ y            : 'simpleUnit' num 0.864native
..- attr(*, "unit")= int 4

where that (.318, .864) is close to the first point of (30,90) if divided by 100.  From there though it's not clear where to go.
I did grid::grobCoords(ggplotGrob(gg)$grobs[[5]]$children[[4]]$children[[1]], TRUE) but the coordinates make even less sense to me...
gTree GRID.labelgrob.13779
grob box
shape 1
x: -0.1781439 0.1847727 0.1835647 ... [51 values]
y: 7.597254 7.597254 7.597278 ... [51 values]
grob text
shape 1
x: -0.1581439 -0.1581439 0.1647727 ... [4 values]
y: 7.647254 7.772254 7.772254 ... [4 values]

That's just the route I tried to find a way to point to the label.  If there's another way that doesn't involve grobs then that's fine too.  I thought about just creating geom_rects and and putting geom_text on top of them since it's defined by the boundary rather than center point so then I automatically know the boundary location of the rect.  The problem with that approach is I don't know how big to make the geom_rect to fit the text.

A: It sounds as though you are trying to get the co-ordinates of the label box outlines expressed as user co-ordinates. The problem here is that if you shrink or expand your plotting window, the labels stay the same size. This has the effect of changing their co-ordinates. Even trying to do this via grob-hacking runs into the same problem.
Since you are using theme_void, you could make your plot fill the whole window by setting expand = c(0, 0) on both your x and y scales, which along with your axis limits, makes it straightforward to convert plotting space into user space.
gg <- ggplot(nodes, aes(x = x, y = y)) +
  geom_segment(data=links, aes(xend = xend, yend = yend)) +
  geom_label(aes(label = label)) +
  scale_x_continuous(limits = c(0, 100), expand = c(0, 0)) +
  scale_y_continuous(limits = c(0, 100), expand = c(0, 0)) +
  theme_void() +
  theme(legend.position = "none")

gg

Now we measure device size in millimetres:
dev_size <- dev.size(units = "cm") * 10

We can now measure the height from the centre of the label to its top / bottom edge. This relies on the calculation that the font size is 11, that 1 pt = 0.352778mm, that from top to bottom of the plot is 100 in user space (our y axis), that the spacing around the box is 0.25 of a line width:
label_height <- 100 * (11 * 0.352778 * 0.75) / dev_size[2]

This allows us to plot segments that touch the upper edge of our labels (we prove that here by drawing arrows on them)
gg + geom_segment(aes(xend = x, y = y + 5, yend = y + label_height),
                  color = "red", arrow = arrow(length = unit(2, "mm")))

We can do the same for the lateral edges of the boxes, but we would need to use the strwidth function to measure the size of each string then perform a similar calculation.
Note also, that if you resize your plot after it is drawn, the arrows will not line up, and their position will need to be recalculated.


text:
Q: how to develop mail storage in jsp? Where can I get information about mail storage? For ex. creating new folder in your Yahoo account and saving some important emails in that folder. I want to develop email server in JSP. I dont know JSP, I have to learn & develop it. Please give me information regarding this.

A: First of all learn the JavaMail API, so you will be able to communicate with POP3, IMAP and SMTP servers. There are either APIs such as commons-net and commons-email.
Second, learn JSP, a good place to start is the Java EE tutorial
Third, understand the JSP model 2 architechture which emphasizes on the MVC pattern for the web. In short, it means you write most of your logic as Java objects, and let the JSP to handle the UI only. A good place to start is by using the Spring Framework MVC application step-by-step tutorial which is based in the spring framework which I found to be really helpful when building web applications in Java.

A: JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and enables interaction with backend Java code with help of taglibs (like JSTL) and Expression Language (EL, those ${} things). I don't see how and why you would create a mail storage in JSP. Keep in mind that writing raw Java code in JSP using scriptlets (those <% %> things) is considered a bad practice. Use a real Java class for that. So is there the HttpServlet class which you can extend to write code logic to control, preprocess and/or postprocess requests from/to JSP files.
Now the mail storage part, firstly you need a mail server. It's required to be able to send/receive emails. Without a mail server you can't do anything with any of the Mail API's (from which I by the way highly recommend to choose the JavaMail API, because it provides both POP3 and SMTP support to retrieve and send mails respectively, the Apache Commons Email is restricted to sending mails only). You can make use of the mail server of your ISP to read and send your own mails, you can make use of the mail server of public mailboxes like Yahoo/Gmail/etc, but you're only restricted to your own account. If you want to have full control over the mail server and be able to create individual mailboxes/addresses/folders and so on, you'll need to install your own mail server, for example Apache James.
Now the business logic, just write normal Java classes which does all the mail reading/sending work with help of the JavaMail API (just create a Javabean class representing an email and read emails into a collection of those Javabeans and send mails with the data gathered from those Javabeans).
Once you got it all to work, next step would be to create Servlet(s) which calls the business logic you've developed based on specific request parameters. Finally create JSP files with forms which submits to those Servlet(s) and/or with tables which displays the data collected by those Servlet(s).
That should be it. To learn JSP/Servlet, I can recommend the Sun Java EE tutorial part II chapters 4-9 and/or Marty Hall's Coreservlets.com tutorials.
Good luck.


text:
Q: Types of lists in sharepoint 2010 I think there are two types of lists in Sharepoint. Internal lists and external lists.
External lists means when we create any list by any of the templates like announcements, calender,Custom list etc.
Then what are the internal lists in sharepont.
Correct me if I am wrong.

A: External list refers to Lists that have an external data source.
http://msdn.microsoft.com/en-us/library/ee558778
And the internal list is a normal list in SharePoint.


text:
Q: How to unit test quartz in camel I am having problem in figuring out how to test my route which use quartz in its from
My spring file
<spring:route id="metricExtractionTimer" startupOrder="1">
    <spring:from uri="quartz://metricExtractionTimer?fireNow=true"/>
    <transform>
        <simple>........... Object Added to DB ...........</simple>
    </transform>
    <to uri="stream:out"/>
    <to uri="mock:result"/>
</spring:route>

My Test File
@RunWith(CamelSpringJUnit4ClassRunner.class)
@BootstrapWith(CamelTestContextBootstrapper.class)
@ContextConfiguration(locations = "/beans-test.xml")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class MetricExtractionTest{

    @EndpointInject(uri = "mock:result")
    protected MockEndpoint resultEndpoint;

    @Produce(uri = "quartz://metricExtractionTimer?fireNow=true")
    protected ProducerTemplate producerTemplate;

    @Test
    public void testQuartzCron() throws Exception {
        producerTemplate.sendBody(null);
    }
}

Exception:
Caused by: org.apache.camel.FailedToStartRouteException: Failed to start route metricExtractionTimer because of startupOrder clash. Route quartz already has startupOrder 1 configured which this route have as well. Please correct startupOrder to be unique among all your routes.
    at org.apache.camel.impl.DefaultCamelContext.doCheckStartupOrderClash(DefaultCamelContext.java:3414)
    at org.apache.camel.impl.DefaultCamelContext.safelyStartRouteServices(DefaultCamelContext.java:3364)
    at org.apache.camel.impl.DefaultCamelContext.doStartOrResumeRoutes(DefaultCamelContext.java:3147)
    at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:3003)
    at org.apache.camel.impl.DefaultCamelContext.access$000(DefaultCamelContext.java:172)
    at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:2799)
    at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:2795)
    at org.apache.camel.impl.DefaultCamelContext.doWithDefinedClassLoader(DefaultCamelContext.java:2818)
    at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:2795)
    at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61)
    at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:2764)
    at org.apache.camel.test.spring.CamelSpringTestContextLoader$7.execute(CamelSpringTestContextLoader.java:515)
    at org.apache.camel.test.spring.CamelSpringTestHelper.doToSpringCamelContexts(CamelSpringTestHelper.java:92)
    at org.apache.camel.test.spring.CamelSpringTestContextLoader.handleCamelContextStartup(CamelSpringTestContextLoader.java:509)
    at org.apache.camel.test.spring.CamelSpringTestContextLoader.loadContext(CamelSpringTestContextLoader.java:164)
    at org.apache.camel.test.spring.CamelSpringTestContextLoader.loadContext(CamelSpringTestContextLoader.java:87)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 28 more

A: Looks like Camel makes trouble manually triggering a self-triggering route, which is kind of understandable. Also, you don't really want to test the Camel Quartz module, since this already well tested open-source code.
I suggest you make the quartz route call a sub-route with a direct:yourRouteName consumer. That one can then be called smoothly from your unit test.

A:
Also, you don't really want to test the Camel Quartz module, since this already well tested open-source code.

Don't agree with this statement. By that reasoning we shouldn't test our interactions with other frameworks as well, e.g. Spring, Hibernate, Camel, etc.
@Bilal: Your best bet is to look at how the camel-quartz2 project tests itself [1].
Specifically, you can look at [2] and [3].
[1] https://github.com/apache/camel/tree/master/components/camel-quartz2/src/test
[2] https://github.com/apache/camel/blob/master/components/camel-quartz2/src/test/java/org/apache/camel/component/quartz2/SpringQuartzCronRouteTest.java
[3] https://github.com/apache/camel/blob/master/components/camel-quartz2/src/test/resources/org/apache/camel/component/quartz2/SpringQuartzCronRouteTest.xml
As an example:
@Component
public class MyRoute extends RouteBuilder {

  @Override
  public void configure() throws Exception {
    from("quartz2://myGroup/myTimerName?cron=0/2+*+*+*+*+?")
        .to("mock:result");
  }
}

@RunWith(CamelSpringBootRunner.class)
@SpringBootTest
public class MyRouteTest {

  @Autowired
  private CamelContext camelContext;

  @EndpointInject(uri = "mock:result")
  private MockEndpoint resultEndpoint;

  @Test
  public void testRoute() throws Exception {
    resultEndpoint.expectedMinimumMessageCount(3);

    MockEndpoint.assertIsSatisfied(camelContext);
  }
}


text:
Q: Does calling the constructor of an empty class actually use any memory? Suppose I have a class like
class Empty{
    Empty(int a){ cout << a; }
}

And then I invoke it using
int main(){
    Empty(2);
    return 0;
}

Will this cause any memory to be allocated on the stack for the creation of an "Empty" object? Obviously, the arguments need to be pushed onto the stack, but I don't want to incur any extra overhead. Basically I am using the constructor as a static member.
The reason I want to do this is because of templates. The actual code looks like
template <int which>
class FuncName{
    template <class T>
    FuncName(const T &value){
        if(which == 1){
            // specific behavior
        }else if(which == 2){
            // other specific behavior
        }
    }
};

which allows me to write something like
int main(){
    int a = 1;
    FuncName<1>(a);
}

so that I get to specialize one template parameter, while not having to specify the type of T. Also, I am hoping the compiler will optimize the other branches away inside the constructor. If anyone knows if this is true or how to check, that would be greatly appreciated. I assumed also that throwing templates into the situation does not change the "empty class" problem from above, is that right?

A: It might, it might, not, depending on circumstances. If you say:
Empty e;
Empty * ep = & e;

then obviously things have to be allocated.

A: Try it and see. Many compilers will eliminate such temporary objects when asked to optimise their output.
If the disassembly is too complex, then create two functions with different numbers of such objects and see if there is any difference in the stack locations of objects surrounding them, something like:
void empty1 ( int x )
{
    using namespace std;

    int a;
    Empty e1 ( x );
    int b;

    cout << endl;
    cout << "empty1" << endl;
    cout << hex << int ( &x ) << " " << dec << ( &x - &a ) << endl;
    cout << hex << int ( &a ) << " " << dec << ( &a - &b ) << endl;
}

and then try running that compared with an empty8 function with eight Empties created. With g++ on x86, if you do take the address of any of the empties you get a location between x and a on the stack, hence including x in the output. You can't assume that the storage for objects will end up in the same order as they are declared in the source code.

A: Quoting Stroustrup:
Why is the size of an empty class not zero?
To ensure that the addresses of two different objects will be different. For the same reason, "new" always returns pointers to distinct objects. Consider:
class Empty { };

void f()
{
    Empty a, b;
    if (&a == &b) cout << "impossible: report error to compiler supplier";

    Empty* p1 = new Empty;
    Empty* p2 = new Empty;
    if (p1 == p2) cout << "impossible: report error to compiler supplier";
}

There is an interesting rule that says that an empty base class need not be represented by a separate byte:
struct X : Empty {
    int a;
    // ...
};

void f(X* p)
{
    void* p1 = p;
    void* p2 = &p->a;
    if (p1 == p2) cout << "nice: good optimizer";
}

This optimization is safe and can be most useful. It allows a programmer to use empty classes to represent very simple concepts without overhead. Some current compilers provide this "empty base class optimization".


text:
Q: Is there an existing parser for iCalendar files for PHP? I've been searching for an iCalendar parser for PHP, but have been unable to find a complete one. qCal doesn't seem complete. Bennu seems even less so. I've seen a lot of people wanting one, but not much else.

A: After an endless search I finally found a good one, with great documentation:
http://www.kigkonsult.se/iCalcreator/

A: sabre-vobject is another (disclaimer: mine). It's been tested in a lot of environments, and provides a natural 'SimpleXML'-like interface to iCalendars and vCards.
http://sabre.io/vobject/

A: You may also check out SG iCalendar. It's very simple to use and seems to be well commented.

A: There are others ..

*

*http://sourceforge.net/projects/phpicalendar/

*http://www.macupdate.com/info.php/id/9224

*http://php-ical.nuclearscripts.com/


text:
Q: Malalanobis distance between two multivariate Gaussian distributions Let $\mathbf{x}\in\Bbb{R}^n$ be an $n$-dimensional real vector distributed normally with mean vector $\mu\in\Bbb{R}^n$ and covariance matrix $\Sigma$; i.e. $\mathbf{x}\sim\mathcal{N}(\mu,\Sigma)$.
The Mahalanobis distance of $\mathbf{x}$ is defined as
$$
D_M(\mathbf{x}) = \sqrt{ (\mathbf{x}-\mu)^\top\Sigma^{-1}(\mathbf{x}-\mu) }.
$$
I am interested in defining a distance between two $n$-dimensional random vectors $\mathbf{x}\sim\mathcal{N}(\mu_x,\Sigma_x)$ and $\mathbf{y}\sim\mathcal{N}(\mu_y,\Sigma_y)$ in a similar way as above.
The Bhattacharyya distance between two multivariate distributions $\mathcal{N}(\mu_x,\Sigma_x)$ and $\mathcal{N}(\mu_y,\Sigma_y)$ includes the following "Mahalanobis term" (as Wikipedia suggests):
$$
d(\mathbf{x},\mathbf{y})=\sqrt{(\mathbf{x}-\mathbf{y})^\top \Bigg(\frac{\Sigma_x+\Sigma_y}{2}\Bigg)^{-1}(\mathbf{x}-\mathbf{y})}.
$$
Would that be a good candidate?

A: Yes, that is a fine candidate, because in the first case you are basically computing the distance to the mean, but for two distributions you have two actual sample vectors you can compute the distance between, so there's really no reason to include the means in the distance calculation.  But if you're interested in variants, the basic issue is how to define the matrix in the middle. If $x$ and $y$ were sampled from distributions with different covariances $\Sigma_x$ and $\Sigma_y$, then one natural thing to do is to take the average of the two covariances, as you have found. At the very least, this is consistent in the sense that you get $\Sigma_x^{-1}$ as the inverse matrix if $\Sigma_x = \Sigma_y$. However there are possibly variants which may, for example, take the average of the inverses rather than the inverse of the average. This also has the consistency property when $\Sigma_x = \Sigma_y$. I would have to read more to explain perhaps why they chose the average of the covariances (before taking inverse) over all other choices


text:
Q: AppEngine JDO with multiple server instances loses transaction updates on entities fetched by key I have a simple JDO test cases that consistently reproduces the problem:
1. two app engine tasks modify the same entity at about the same time
2. the tasks use a JDO transaction and use getObjectById to load the entity
3. have task A modify attribute A on the entity (assume A runs first)
4. have task B modify attribute B on the entity
The problem arises when each of the two tasks executes on two different app engine instances. In which case, I can see log messages that say task A has properly set attribute A to a non-null value and the transaction committed successfully. Then when task B runs on a separate instance it prints out that it does not see the changes that were made to attribute A by task A. Then task B logs that it has set attribute B to a non-null value and that its transaction completes successfully.
Then, when I look in the datastore, attribute A is still null even though I can see log output that says it was set to non-null and the transaction was successful. I would have expected one of two things: 1) when task B loads the entity the value of attribute A reflects that it has been set to a non-null value, or 2) task B loads stale data, but the commit fails with a "too much contention" error. Either of those would be fine. (Note that occasionally I do see contention errors)
What am I missing? It seems like there's some weird caching going on each instance. I was pretty sure that loading an entity by its key within a transaction should reflect changes made to that entity even when those changes are made on a separate app engine instance. When writing a test case to reproduce this I created completely new entity classes and tasks to ensure no other code was somehow mucking things up and I reproduced it in production (the devserver gives slightly different behavior).
Any help is greatly appreciated!

A: Seems like you are having a version issue. Use @version this will automatically handle concurrent modification and will throw an optimistic lock exception.


text:
Q: Grouping column by the first two characters into two groups I have this type of DF
DF
N   ID
1   0230
2   5902
3   2359
4   0530

DF
N   ID     GR
1   0230   1
2   5902   2
3   2359   1
4   3030   2

I would like to group column ID by the first two characters into two groups.
If first two characters are number lower than 30 is group 1 and higher than 30 and lower than 59 is group 2.
I would prefer dplyr solution.
I have tried this:
DF%>%
mutate(GR = ifelse(str(ID[2] >= 0 & DRG[2] < 31, 1, ifelse(str(ID[2] >= 31 & DRG[2] < 60, 0, "-" )))))

A: Here is a math based solution,
(df$ID /(10^(nchar(df$ID)-2)) > 30 ) + 1
#[1] 1 2 1 2

DATA:
 dput(df)
structure(list(N = 1:4, ID = c(230L, 5902L, 2359L, 530L)), class = "data.frame", row.names = c(NA,
-4L))

A: Here's a base Rsolution:
Data:
df <- data.frame(
  N = 1:4, ID = c("0230", "5902", "2359", "0530"))

Solution:
df$GR <- ifelse(as.numeric(sub("(\\d{2})(\\d{2})", "\\1", df$ID)) < 30 , 1, 2)

Here, we first define two regex capturing groups (\\d{2})and refer back to the first such group with \\1 to extract it with sub, then we convert the result of  the extraction to type numeric, and finally we instruct ifelse to assign 1 and respectively 2 depending on the size of the extracted values:
Result:
df
  N   ID GR
1 1 0230  1
2 2 5902  2
3 3 2359  1
4 4 0530  1

A: Here's a dplyr solution
library(dplyr)
DF %>%
  mutate(GR = case_when(
   as.numeric(ID) <= 3000 ~ 1,
   TRUE ~ 2)
  )

# A tibble: 4 x 3
      N ID       GR
  <dbl> <chr> <dbl>
1     1 0230      1
2     2 5902      2
3     3 2359      1
4     4 0530      1


text:
Q: How do I prevent assign errors when using union types in typescript? Imagine I have these interfaces:
   interface FirstElement {
      id: string;
      coordinates: Coordinates;
      type: FirstElementTypes;
      options: FirstElementOptions;
    }

   interface SecondElement {
      id: string;
      coordinates: Coordinates;
      type: SecondElementTypes;
      options: SecondElementOptions;
    }

    interface FirstElementDTO {
      id: string;
      type: FirstElemenTypes;
      options: FirstElementOptions;
    }

    interface SecondElementDTO {
      id: string;
      type: SecondElementTypes;
      options: SecondElementOptions;
    }

Now I want to create a DTO object, mapping these interfaces to their corresponding DTO interface. Because they share the same properties, with only the options being different, I'd like to use a single converter function. But when using typescripts union typing like this...
  private static convertElementToDTO(element: FirstElement | SecondElement): FirstElementDTO | SecondElementDTO {
    return {
      id: element.id,
      options: element.options,
      type: element.type
    };
  }

...I (obviously) get an error message telling me that the options are not compatible. Would it be possible in typescript to "tell" a function that if FirstElement is the input type, FirstElementDTO is the output type and vice versa for SecondElement - without writing the same code multiple times and using several if-statements? Thanks for your help!

A: It's possible a generic function might work here.  First, some dummy type definitions to make the code here a self-contained example:
type FirstElementTypes = { FirstElementTypes: true };
type FirstElementOptions = { FirstElementOptions: true };
type SecondElementTypes = { SecondElementTypes: true };
type SecondElementOptions = { SecondElementOptions: true };

Then we can represent your types this way, to reduce code duplication:
// your types
interface FirstElementDTO {
  id: string;
  type: FirstElementTypes;
  options: FirstElementOptions;
}

interface SecondElementDTO {
  id: string;
  type: SecondElementTypes;
  options: SecondElementOptions;
}

// define elements as extension of DTOs to reduce code duplication
interface FirstElement extends FirstElementDTO {
    coordinates: Coordinates;
}

interface SecondElement extends SecondElementDTO {
    coordinates: Coordinates;
}

And finally here's the generic function:
// generic Pick function
function convertElementToDTO<E extends FirstElement | SecondElement>(
  element: E
): Pick<E, "id" | "options" | "type"> {
  return {
    id: element.id,
    options: element.options,
    type: element.type
  };
}

And it works without error:
declare const f: FirstElementTypes;
declare const o: FirstElementOptions;
declare const c: Coordinates;
const first: FirstElementDTO = convertElementToDTO({
  id: "firstEl",
  type: f,
  coordinates: c,
  options: o
}); // okay

Playground link
Hope that helps; good luck!


text:
Q: system clock keep changing I'm using Windows 7 and the system clock is almost stuck within two hours.
When I change it to the right time, the clock will stick to the right time + 2 hours (after reaching the right time + 2 hours it will go back 2 hours).
The time zone is right, so it's definitely a virus or malware; but I scanned the system using avira and kaspersky with negative results.
Is there anyway to fix it without formatting?

A: You could have a bad/rouge time server defined, which dynamically updates your system time. Please open a command prompt in administrator mode, and input this command:
w32tm /query /status

Please paste the "source" line.
It may also be possible that the time defined in your BIOS is not being set properly. When your PC powers on press DEL or F2 to enter the setup utility, and in general CMOS settings, ensure the time is set correctly there.

A: Have you changed something in the Windows Services ? Have you disabled the Service Software Licensing?
You must do this through safe mode.

*

*Remove all floppy disks, CDs, and DVDs from your computer, and then restart your computer.

*Click the Start button, click the arrow next to the Lock button, and then click Restart.

*Do one of the following:

*

*If your computer has a single operating system installed, press and
hold the F8 key as your computer restarts. You need to press F8
before the Windows logo appears. If the Windows logo appears, you
will need to try again by waiting until the Windows logon prompt
appears, and then shutting down and restarting your computer.

*If your computer has more than one operating system, use the arrow
keys to highlight the operating system you want to start in safe
mode, and then press F8.

*On the Advanced Boot Options screen, use the arrow keys to highlight
Safe Mode with command prompt, press Enter

*Log on to your computer with a user account that has administrator rights.

*Type services.msc in Windows Run Command
(Win+R)

*Then in the list of services locate Software Licensing. Right-click
it, select Properties

*Change "Startup type:" to Automatic, then click OK. Restart you
computer

Report back to us, did it solve the problem ?

A: I have seen exactly this issue before. It was a very old installation of Windows, with (presumably) some sort of corrupted system file. Using the right time zone would cause the wrong time to be displayed. What worked for me was simply reinstalling Windows (which, incidentally fixed all the other system problems with that old installation of Windows in the process). I rarely advise jumping straight in and doing a reinstall, but having seen this myself, I think you should be open to the idea. If you do a reinstall (or repair install) you could have it fixed today- otherwise it will just drag on for a while. By the way I don't like it when people say "...blah blah blah, so it's DEFINITELY a virus or malware!". The one thing I can guarantee is that it's NOT malware. Malware is too often the scapegoat for things people can't explain IMO.

A: It almost sounds like its in your BIOS.  I once had an issue like this and basically reflashed my BIOS.  That fixed my issue.  Mine wasn't quite like yours however it smells like its in your BIOS.  Have you tried installing other versions of Windows and seeing what happens to the clock?  Just something to think about.  By the way if you do end up reflashing your BIOS, there's a point where you do not want to turn off your computer.  I'm sure the upgrade software will make you aware of that though.


text:
Q: Método Focus() asp net Tenho uma página com vários controles, quando eu disparo um evento de um botão quero que o foco vá a um textBox que fica lá em baixo da página, porém isto não está ocorrendo simplesmente colocando o método focus() no textBox. Será que algum outro controle como um listBox está interferindo? Porque neste evento que tento colocar o foco num textBox também estou passando um índice a fim de que fique selecionado um item da listBox: listBox.SelectedIndex = 0. Poderia ser também um problema de escopo? Por exemplo, esse textBox que deve receber o foco fica em outro panel. Eu quero que esse textBox receba o foco e que a página desça (a barra horizontal) até ele, entende?

A: Fiz em JavaScript:
document.getElementById("textBox").focus();

Aí deu certo.


text:
Q: Algorithm for graph post dominance? What algorithm can be used to calculate post dominators in a control flow graph?
Currently I calculate the dominators by using the iterative bit vector algorithm:
#include <iostream>
#include <list>
#include <stack>
#include <vector>
#include <memory>
#include <map>

class BasicBlock
{
public:
    BasicBlock(std::string name) : mName(name) { }

    void AllocateDominatorsAndSetToTrue(const size_t nBlocks)
    {
        mDominators.resize(nBlocks);
        for (size_t i = 0; i < nBlocks; i++)
        {
            mDominators[i] = true;
        }
    }

    void SetAllDominatorsTo(bool value)
    {
        for (size_t i = 0; i < mDominators.size(); i++)
        {
            mDominators[i] = value;
        }
    }

    std::string mName;

    int mId = 0;

    // Links to blocks before this one
    std::vector<BasicBlock*> mPredecessors;

    // Links to blocks after this one
    std::vector<BasicBlock*> mSucessors;

    std::vector<bool> mDominators;
    std::vector<BasicBlock*> mImmediateDominator;
};

class ControlFlowGraph
{
public:
    void AddBasicBlock(std::string name)
    {
        mBasicBlocks.emplace_back(std::make_unique<BasicBlock>(name));
    }

    void AddSucessor(std::string block, std::string target)
    {
        FindBlock(block)->mSucessors.emplace_back(FindBlock(target));
    }

    void AddPredecessor(std::string block, std::string target)
    {
        FindBlock(block)->mPredecessors.emplace_back(FindBlock(target));
    }

    BasicBlock* FindBlock(std::string name)
    {
        for (const auto& block : mBasicBlocks)
        {
            if (block->mName == name)
            {
                return block.get();
            }
        }
        return nullptr;
    }

    void CalculateDominators()
    {
        const size_t nBlocks = mBasicBlocks.size();
        int i = 0;
        for (std::unique_ptr<BasicBlock>& block : mBasicBlocks)
        {
            block->mId = i++;
            block->AllocateDominatorsAndSetToTrue(nBlocks);
        }

        BasicBlock* block = mBasicBlocks[0].get();
        block->SetAllDominatorsTo(false);
        block->mDominators[block->mId] = true; // block always dominates itself

        bool changed = false;
        do
        {
            changed = false;
            for (std::unique_ptr<BasicBlock>& b : mBasicBlocks)
            {
                if (b == mBasicBlocks[0]) // Is it the entry node?
                {
                    continue;
                }
                for (BasicBlock* pred : b->mPredecessors)
                {
                    auto T = b->mDominators;
                    for (size_t i = 0; i < nBlocks; i++)
                    {
                        if (b->mDominators[i] && pred->mDominators[i])
                        {
                            b->mDominators[i] = true;
                        }
                        else
                        {
                            b->mDominators[i] = false;
                        }
                    }
                    b->mDominators[b->mId] = true; // block always dominates itself
                    if (b->mDominators != T)
                    {
                        changed = true;
                    }
                }
            }
        }
        while (changed);
    }

    void CalculateImmediateDominators()
    {
        // ??
    }

    std::vector<std::unique_ptr<BasicBlock>> mBasicBlocks;
};

int main()
{
    ControlFlowGraph graph;

    graph.AddBasicBlock("1");
    graph.AddBasicBlock("2");
    graph.AddBasicBlock("3");
    graph.AddBasicBlock("4");
    graph.AddBasicBlock("5");
    graph.AddBasicBlock("6");

    graph.AddSucessor("1", "2");
    graph.AddSucessor("2", "3");
    graph.AddSucessor("2", "4");
    graph.AddSucessor("3", "2");
    graph.AddSucessor("4", "5");
    graph.AddSucessor("4", "6");
    graph.AddSucessor("5", "4");
    graph.AddSucessor("6", "2");

    graph.AddPredecessor("2", "1");
    graph.AddPredecessor("3", "2");
    graph.AddPredecessor("4", "2");
    graph.AddPredecessor("5", "4");
    graph.AddPredecessor("6", "4");

    graph.CalculateDominators();
    graph.CalculateImmediateDominators();

    return 0;
}


text:
Q: Android: Changing fragments with ViewPager I'm using PagerSlidingTabStrip library for ViewPager https://github.com/astuetz/PagerSlidingTabStrip. I want to change the fragments while scrolling. I achieved that with the below code.
MainActivity.java
public class MainActivity extends SherlockFragmentActivity {

private MyPagerAdapter adapter;
ViewPager pager;
private PagerSlidingTabStrip tabs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
    pager = (ViewPager) findViewById(R.id.pager);
    adapter = new MyPagerAdapter(getSupportFragmentManager());

    pager.setAdapter(adapter);

    final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
            .getDisplayMetrics());
    pager.setPageMargin(pageMargin);

    tabs.setViewPager(pager);

}

public class MyPagerAdapter extends FragmentPagerAdapter {
    private final String[] TITLES = {"First","Second","Third"};
    private SherlockFragment[] fragments = new SherlockFragment[] { new FirstFragment(), new SecondFragment(), new ThirdFragment()};

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return TITLES[position];
    }

    @Override
    public int getCount() {
        return TITLES.length;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments[position];
    }

}
}

FirstFragment.java
public class FirstFragment extends SherlockFragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View v = inflater.inflate(R.layout.fragment_main, container, false);
    Toast.makeText(getSherlockActivity(), "This is from first", Toast.LENGTH_SHORT).show();
    return v;
}
}

SecondFragment.java
public class SecondFragment extends SherlockFragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View v = inflater.inflate(R.layout.fragment_main, container, false);
    Toast.makeText(getSherlockActivity(), "SecondFragment", Toast.LENGTH_SHORT).show();
    return v;
}
}

ThirdFragment.java
public class ThirdFragment extends SherlockFragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View v = inflater.inflate(R.layout.fragment_main, container, false);
    Toast.makeText(getSherlockActivity(), "ThirdFragment", Toast.LENGTH_SHORT).show();
    return v;
}
}

I got the three fragments and I'm testing them with Toasts.
When the application opens with the MainActivity, FirstFragment is attached to the Activity , but it shows two toasts, one from Firstragment and other from SecondFragment , and when I scroll to second tab, it shows the toast of ThirdFragment.
So, I figured its going like this. If I scroll from left to right , the fragment right to the current fragment is displayed and if I scroll from right to left, the fragment left to the current fragment is displayed. Please help.
Thanks.

A: It's because of fragments caching. When you visit some fragments, sibling fragments to it also being created (onCreate() called).


text:
Q: Excel formula to concatenate Average with Text In excel I have a range on which I need to calculate average and show the result in a new cell  in this format:
38.2% (Avg)

I tried to use this formula
=CONCATENATE(AVERAGE(Y7:Y14), " (Avg)")

But this formula shows the result this way:
.38264782356378563576 (Avg)

How can I restrict the number to 2 decimal places and put the % symbol?

A: You can actually use custom formatting which serves the purpose of displaying and keeping the value as a number (on which you can perform further calculations with ease):

The formatting is:
00.0% "(Avg)"

Or if you don't want to get keep it as number, you can always do:
=TEXT(AVERAGE(Y7:Y14),"00.0% ""(Avg)""")

A: Multiply the number with 100, then use ROUND() on this number to round up to the amount of digits you require (1) and change your string (Avg) to % (Avg).
=CONCATENATE(ROUND(100*AVERAGE(Y7:Y14), 1), "% (Avg)")


text:
Q: How to display/render User's name stored in an external model without refreshing the page? I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page.
For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number".
I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered.
models.py
class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model):
    employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False)
    work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False)
    station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True,  blank=True)

    def __str__(self):
        return self.employee_number

This is the model where the name is stored
alldata/models.py
class Salesman(models.Model):
    slsmn_name = models.CharField(max_length=25)
    id = models.IntegerField(db_column='number', primary_key=True)

I was reading I can add to the "attrs" in the widget an 'onchange' part, but I am not too familiar with how to approach this and tying it to the ajax request from forms and not the html.
forms.py
class WarehouseForm(AppsModelForm):
    class Meta:
        model = EmployeeWorkAreaLog
        widgets = {
            'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}),
        }
        fields = ('employee_number', 'work_area', 'station_number')

views.py
class EnterExitArea(CreateView):
    model = EmployeeWorkAreaLog
    template_name = "operations/enter_exit_area.html"
    form_class = WarehouseForm

    def form_valid(self, form):
        # do submission stuff..

def get_employee_name(request):
    employee_number = request.GET.get('employee_number')
    employee = Salesman.objects.get(employee_number=employee_number)
    employee_name = employee.slsmn_name
    return employee_name

urls.py
urlpatterns = [
    url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'),

    path('get-employee-name/<int:id>/', views.get_employee_name, name='employee_name'),
]

The ajax request I tried to create is at the end of this html. I modified a similar request I found, but it does not actually display anything on the screen, not sure if I'm missing an area where the request is actually never being called, as I am not too familiar with how these types of requests work.
enter_exit_area.html
{% extends "base.html" %}

{% block main %}
    <form id="warehouseForm" action="" method="POST" novalidate >
        {% csrf_token %}

                {{ form.employee_number.help_text }}
                {{ form.employee_number }}

                {{ form.work_area.help_text }}
                {{ form.work_area }}

                <button type="submit" name="enter_area" value="Enter">Enter Area</button>

    </form>

{% endblock main %}

A: You should change the type:'get' from the post. You can always check the network tab in your browsers developer tool (press F12) to check what happens exactly when you change the id. (check weather AJAX calls or not.)


text:
Q: Conditional variable check using Ansible with failed_when module? I have an Ansible task in which I am using variables - window and total_files. And I am passing these two variable values from the command line:
 - name: Check all files
   find: paths=/var/lib/goldy/jobs/processdata/workspace/files
         file_type=file
         age=-{{ window }}m
         age_stamp=mtime
   register: files
   failed_when: files.matched < total_files

Here is how I am running:
ansible-playbook -e 'host_key_checking=False' -e 'total_files=6' -e 'window=10' abc.yml

But somehow my total_files variable is not working at all with failed_when module. I tried all the combinations I can think of but if I use "{{ total_files }}" like this then I am getting warning so that's why I started using total_files like this but still it doesn't work. Any thoughts on what I am doing wrong?
[WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: files.matched < "{{ total_files }}"

A:
And I am passing these two variable value from the command line

So you are passing strings, hence you compare files.matched to a string value.
Change to:
failed_when: files.matched < total_files | int

The warning you posted is irrelevant to the root problem.


text:
Q: Users post to twitter from wordpress I've a property website where user can add property after twitter logged in.
Now I want to post update on twitter about property on his/her twitter page. How its posible?
I've setuped twitter aap. My site in wordpress so I can not trace users password. What is solution for this can you help?

A: Have you tried this plugin?


text:
Q: Find the eccentricity of the conic $4(2y-x-3)^2 -9(2x+y-1)^2=80$ Find the eccentricity of the conic $4(2y-x-3)^2 -9(2x+y-1)^2=80$
Solution :
$4(2y-x-3)^2 = 4x^2-16xy+24x+16y^2-48y+36$
and $9(2x+y-1)^2 = 36x^2+36xy-36x+9y^2-18y+9$
$\therefore 4(2y-x-3)^2 -9(2x+y-1)^2 = 7y^2+60x -52xy-32x^2-30y+27 =80$
Can we have other option available so that we will be able to find the solution more quicker way,
Since this is a conic then the  given lines let $L_1 =2y-x-3=0 $ and $L_2 = 2x+y-1=0$ are perpendicular to each other .. Can we use this somehow please suggest... thanks..

A: As the Rotation of the axes does not change the eccentricity of a curve
set $2y-x-3=X,2x+y−1 =Y$ so that the given equation becomes  $$4X^2-9Y^2=80\iff \frac{X^2}{\frac{80}4}-\frac{Y^2}{\frac{80}9}=1$$
Now we know, $$b^2=a^2(e^2-1)$$ where $a,b\le a$ are the semi-major & semi-minor axes and $e$ is the eccentricity of the hyperbola

A: With a translation of the origin in the center of the conic (which is the point of intersection of the two lines, you get the equation in the form
$$
4(-X+2Y)^2-9(2X+Y)^2=80
$$
Now the lines are indeed orthogonal: since $1^2+2^2=5$, you can write the equation as
$$
4\cdot5\left(-\frac{1}{\sqrt{5}}X+\frac{2}{\sqrt{5}}Y\right)^2
-9\cdot5\left(\frac{2}{\sqrt{5}}X+\frac{1}{\sqrt{5}}Y\right)^2=80
$$
The transformation
\begin{cases}
\xi=-\frac{1}{\sqrt{5}}X+\frac{2}{\sqrt{5}}Y\\
\eta=\frac{2}{\sqrt{5}}X+\frac{1}{\sqrt{5}}Y
\end{cases}
is a rotation, so you get the canonical form
$$
4\xi^2-9\eta^2=16
$$
or
$$
\frac{\xi^2}{4}-\frac{\eta^2}{16/9}=1
$$
Thus you have
$$a^2=4,\quad b^2=\frac{16}{9}$$

A: However,
With rotation letting Q = 7y^2 -52xy -32x^2 using a rotation matrix have that:
x = cx' + sy'
y = -sx' + cy'
x^2 = c^2x'^2 +s^2y'^2 + 2csx'y'
y^2 = s^2x'^2 +c^2y'^2 - 2csx'y'
xy = -csx'^2 + csy'^2 + (c^2 - s^2)(x'y')
Subbing in these and extracting all x'y' components to equate to zero gives:
-14csx'y' -64csx'y' -52(c^2 - s^2)(x'y') = 0
x'y'(52s^2 - 78cs - 52c^2) = 0
2s^2 - 3cs -2c^2 = 0
using quadratic formula for s
s = 3/4c +or- 5/4c = -1/2c or 2c   (dividing both by c) gives:
t = -1/2 or 2 hence
theta = 26.57 or 63.43
Subbing either into Q since both render xy component zero (subbing 26.57) gives:
Q' = 20y'^2 - 45x'^2
Completing the square and re-arranging gives
5((root2y' - 3(root2)/2)^2)/39 - 5((root3x' - 2(root3)/3)^2)/26 = 1
Which is a hyperbola with a^2 = 39/5 and b^2 = 26/5
We know e^2 = 1 - (b^2)/(a^2) = 1/3
Hence I find e = root(1/3)
To lab Bhatt: Barring a mistake on my part it seems that our eccentricities differ where in your assumption of X and Y e = root(65/81). What have I done wrong? Is it the perpendicular bit that allows for X and Y assumption. Please shed some light if you will. I would suggest that maybe rotation doesn't make a difference to eccentricity as you suggest but the assumption does?


text:
Q: Convolution of two 3D numpy arrays in python I need to convolve a (128,128,128) numpy array m with a (35,35,35) kernel k.
I am looking for something like Matlab's convn function
convn(m,k,'same')

The most similar function I found in python is
ndimage.convolve()

but is not the same.
Can anyone suggest a method of doing this as easy as calling that function in Matlab?


text:
Q: How to work with ColumnDataSource and LegendItem together in bokeh? I would like to create a categorial scatter plot with these functions using bokeh:

*

*Hover Tooltips

*Legend outside the plot area with click policy = "hide"
After numerous searches, I can implement the function #1 and #2 separately.
But I don't know how to make these 2 functions work at the same time.
Tooltips only needs one glyph object, but legend outside plot area needs a for-loop to create a list of glyph objects which is used to generate legend_items.
Thanks.
Code Example:

*

*Hover Tooltips can be achieved by using ColumnDataSources
(https://docs.bokeh.org/en/latest/docs/user_guide/categorical.html#heat-maps)

import pandas as pd
from bokeh.sampledata.stocks import AAPL
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, output_file, show

df = pd.DataFrame(AAPL)
output_file("test.html")
p = figure(tools="hover")
source = ColumnDataSource(df)

p.scatter("high", "low", source=source)

p.hover.tooltips = [("Date","@date")]

show(p)

*Legend outside the plot
(Position the legend outside the plot area with Bokeh)

import pandas as pd

from bokeh.models import Legend, LegendItem
from bokeh.palettes import Spectral4
from bokeh.plotting import figure, output_file, show
from bokeh.sampledata.stocks import AAPL, GOOG, IBM, MSFT

output_file("test2.html")
p = figure(x_axis_type="datetime")
p_list = []

for data, name, color in zip([AAPL, IBM, MSFT, GOOG], ["AAPL", "IBM", "MSFT", "GOOG"], Spectral4):
    df = pd.DataFrame(data)
    df['date'] = pd.to_datetime(df['date'])
    p_list.append(p.line(df['date'], df['close'], line_width=2, color=color, alpha=0.8))

legend_items = [LegendItem(label=x, renderers=[p_list[i]]) for i, x in enumerate(["AAPL", "IBM", "MSFT", "GOOG"])]
legend_ = Legend(items=legend_items, click_policy="hide", location="center", label_text_font_size="12px")
p.add_layout(legend_, "right")

show(p)

A: import pandas as pd

from bokeh.models import Legend, LegendItem, ColumnDataSource
from bokeh.palettes import Spectral4
from bokeh.plotting import figure, show
from bokeh.sampledata.stocks import AAPL, GOOG, IBM, MSFT

p = figure(x_axis_type="datetime", tools='hover')
p.hover.tooltips = [("Date", "@date{%F}"),
                    ("Open", "@open"),
                    ("Close", "@close")]
p.hover.formatters = {'@date': 'datetime'}

legend_items = []
for data, name, color in zip([AAPL, IBM, MSFT, GOOG],
                             ["AAPL", "IBM", "MSFT", "GOOG"],
                             Spectral4):
    data['date'] = pd.to_datetime(data['date']).values
    ds = ColumnDataSource(data)
    renderer = p.line('date', 'close', source=ds,
                      line_width=2, color=color, alpha=0.8)
    legend_items.append(LegendItem(label=name, renderers=[renderer]))

legend = Legend(items=legend_items, click_policy="hide",
                location="center", label_text_font_size="12px")
p.add_layout(legend, "right")

show(p)

If you want to have different tooltips for different stocks, you can create one hover tool per each stock and specify them in the tools argument. The downside - there will be multiple hover tool buttons on the toolbar.


text:
Q: How to remove a single tick label on a plot, leaving the tick itself I'd like to remove all but the first and last tick labels, but keep their ticks on a plot.
However, using the below code, all labels get removed
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 1)
ax.plot(np.arange(10))

locs = ax.get_xticks()
labels = ax.get_xticklabels()
labels[1].set_text('')  # Should only remove the 2nd label
ax.set_xticks(locs)
ax.set_xticklabels(labels)

results in:

Where are all my labels are removed, rather than just the 2. How can I remove just that single number?
I'd expect the following plot to show up (rendered by BigBen using the code above in a comment, using matplotlib 3.6.0 and Python 3.9.7):

Preferably in a method capable of removing all but the first and last label. For that I tried:
for label_idx in range(1, len(labels)-1):
    labels[label_idx].set_text('')

which also removed all labels. I want all ticks but only the labels 0 and 8 to show up, i.e. remove the labels 2, 4 and 6.
I'm using Python 3.9.12 with matplotlib 3.5.2 on a Spyder 5.3.2 IDE. After upgrading to Python 3.9.15 and matplotlib 3.5.3 the issue remains.
The code in Bhargav's answer generates the same issue on my system: it removes all labels for me. I'm going to presume this is a bug in Python, matplotlib or Spyder.

A: In
Python  - 3.9.10
matplotlib: 3.5.1

Uisng Tick_formatter
plt.xticks(np.arange(min(locs), max(locs)+1, 2))
ax.xaxis.get_major_ticks()[1].draw = lambda *args:None

Gives #

if you want to keep ticks
plt.xticks(np.arange(min(locs), max(locs)+1, 2))
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[1] = ''
ax.set_xticklabels(labels)

Gives #


text:
Q: Unable to grab dates into a column While using quantmod and scraping GOOGLE stock prices I want the dates and it is showing the dates but unable to subset the dates.
library(quantmod)
start <- as.Date("2017-01-01")
end <- as.Date("2017-11-01")
getSymbols("GOOGL", src = "yahoo", from = start, to = end)

Snapshot:
What should I do?

A: The xts class (a superset of the zoo class which stores the time data as rownames rather than in numeric columns) has a method for "[" that can be used. It parses dates as characters and uses "/" to separate the ends of intervals:
G.subset <- GOOGL["2017-01-01/2017-11-01"]

Read more at:
?`[.xts`
?xts

The time values are accessible with the index function.


text:
Q: How to convert date in this format 'Dec-07-2013 09:32:05 CST' in GWT In GWT Whats the correct format to convert date something like
Dec-07-2013 09:32:05 CST
Im using "mmm-dd-yyyy HH:mm:ss zzz" but getting UTC -5 timezone.

A: Is UTC -5 not equal to CST (during Dayligh tSaving Time)?
http://www.worldtimebuddy.com/?pl=1&lid=6,100&h=6


text:
Q: Check if subgroup is normal based on generators Let's say we have a group $G=\langle g_1,g_2,g_3\rangle$ for some generators $g_i$. Further, suppose I have some subgroup $\langle h_1,h_2\rangle =H\subset G$ for some generators $h_i$. For $H$ to be normal in $G$ we must have $gHg^{-1}=H$ for all $g\in G$. Is there an easy way to check this computationally? What I mean is, can I do something like check $g_jh_ig_j^{-1}\in H$ for each $i,j$? Or is this not sufficient? If it is sufficient, is there something even easier we can do, like check if each $g_jh_ig_j^{-1}$ is one of the generators $h_k$?

A:
Theorem. Let $G$ be a group, and $N\leq G$ a subgroup. Let $X\subseteq N$ and $Y\subseteq G$ be subsets such that $N=\langle X\rangle$ and $G=\langle Y\rangle$. The following are equivalent:

*

*$N\triangleleft G$.

*For all $g\in G$, $gNg^{-1}=N$.

*For all $g\in G$, $gNg^{-1}\subseteq N$.

*For all $g\in G$ and $n\in N$, $gng^{-1}\in N$.

*For all $g\in G$ and all $x\in X$, $gxg^{-1}\in N$.

*For all $y\in Y$, $yNy^{-1}=N$.

*For all $y\in Y$, $yNy^{-1}\subseteq N$ and $y^{-1}Ny\subseteq N$.

*For all $y\in Y$ and $x\in X$, $yxy^{-1}\in N$ and $y^{-1}xy\in N$.

Proof. (1)$\iff$(2) is the usual definition.
Clearly (2)$\implies$(3); to get (3)$\implies$(2), note that for $g\in G$, we have $gNg^{-1}\subseteq N$ from (3), and applying $3$ to $g^{-1}$ we have $g^{-1}Ng\subseteq N$. Left multiplying by $g$ and right multiplying by $g^{-1}$ we get $N\subseteq gNg^{-1}$, giving $gNg^{-1}=N$, thus proving (2).
It is easy to see that (3)$\iff$(4).
(4)$\implies$(5) is immediate. To get (5)$\implies$(4), first note that for all $x\in X$ and $g\in G$, since $gxg^{-1}\in N$ and $N$ is a subgroup, then $gx^{-1}g^{-1}=(gxg^{-1})^{-1}\in N$. Now let $n\in N$. Since $N=\langle X\rangle$, we can write $n = x_1^{\epsilon_1}\cdots x_n^{\epsilon_n}$, where $x_i\in X$ are not necessarily distinct, and $\epsilon_i\in\{1,-1\}$ for all $i$. Then
$$\begin{align*}
gng^{-1} &= g(x_1^{\epsilon_1}\cdots x_n^{\epsilon_n})g^{-1}\\
&= (gx_1^{\epsilon_1}g^{-1})(gx_2^{\epsilon_2}g^{-1})\cdots(gx_n^{\epsilon_n}g^{-1}).
\end{align*}$$
Each $gx_i^{\epsilon_i}g^{-1}\in N$, so this is a product of elements of $N$, and hence lies in $N$. Thus, $gng^{-1}\in N$, proving (4).
(2)$\implies$(6) is immediate. To prove that (6)$\implies$(2), note that from $yNy^{-1}=N$ we get, left multiplying by $y^{-1}$ and right multiplying by $y$, that $N=y^{-1}Ny$. Let $g\in G$; using $G=\langle Y\rangle$, we know that we can write $g=y_1^{\epsilon_1}\cdots y_n^{\epsilon_n}$, with $y_i\in Y$ and $\epsilon_i\in \{1,-1\}$ for all $i$. We also know that $y_j^{\epsilon_j}Ny_j^{-\epsilon_j}=N$. From this, we get
$$\begin{align*}
gNg^{-1} &= (y_1^{\epsilon_1}\cdots y_n^{\epsilon_n})N(y_1^{\epsilon_1}\cdots y_n^{\epsilon_n})^{-1}\\
&= y_1^{\epsilon_1}\cdots y_{n-1}^{\epsilon_{n-1}}(y_n^{\epsilon_n }Ny_n^{-\epsilon_1})y_{n-1}^{-\epsilon_{n-1}}\cdots y_1^{-\epsilon_1}\\
&= y_1^{\epsilon_1}\cdots y_{n-1}^{\epsilon_{n-1}}Ny_{n-1}^{-\epsilon_{n-1}}\cdots y_1^{-\epsilon_1}
\end{align*}$$
and inductively we get $gNg^{-1}=N$, proving 2.
(6)$\iff$(7), since $y^{-1}Ny\subseteq N$ is equivalent, multiplying by $y$ on the left and $y^{-1}$ on the right, to $N\subseteq yNy^{-1}$.
(7)$\implies$(8) is clear. For (8)$\implies$(7), using the same argument to show that (5)$\implies$(4) we see that (8) implies that $yny^{-1}\in N$ and $y^{-1}ny\in N$ for all $n\in N$, giving (7). $\Box$
However, in (7) and (8) it is not, in general, enough to require $yNy^{-1}\subseteq N$ (respectively $yxy^{-1}\in N$). A counterexample can be found in this post.


text:
Q: Multiple expandable list views not scrollable I have a Problem by my App.
In a loop I dynamically create an ExpandableListView. Now I want to make my screen scrollable.
But when i put a Scrollview over my Layout, the screen will not able to scroll and the expandable list views are very tiny. How can I fix this?

No i have to scroll the Screen with the ExpandableListViews.
When i have more Customers or i turn the Phone, the Screen will be to small and so i have to Scroll, but it will not works.
Thanks Mark
My screen looks like:
+-------------------------------------+
|                                     |
|  Customer 1:                        |
|  +-------------------------------+  |
|  |                               +  |
|  |    ExpandableListView 1       +  |
|  |                               +  |
|  +-------------------------------+  |
|                                     |
|                                     |
|  Customer 2:                        |
|  +-------------------------------+  |
|  |                               +  |
|  |    ExpandableListView 2       +  |
|  |                               +  |
|  +-------------------------------+  |
|                                     |
|                                     |
|  Customer 3:                        |
|  +-------------------------------+  |
|  |                               +  |
|  |    ExpandableListView 3       +  |
|  |                               +  |
|  +-------------------------------+  |
|                                     |
|                                     |
|                                     |
+-------------------------------------+

A: I can't say without seeing the code, but it sounds like your list item view are small enough to not need to bee scrolled through. FWIW you don't need a scroll view for a ListView or ExpandableListView as they both scroll on their own.


text:
Q: Noda Time: Period.Between returning incorrect value I have a trouble with NodaTime lib. My goal: compute Year/Month/Date between two dates. So, here is my test example:
    private static void Main()
    {
        var list = new List<Tuple<DateTime, DateTime>>
        {
            new Tuple<DateTime, DateTime>(new DateTime(1980, 1, 1), new DateTime(1983, 12, 31)),
            new Tuple<DateTime, DateTime>(new DateTime(2009, 1, 1), new DateTime(2015, 01, 23))
        };
        var totalPeriod = Period.Zero;
        foreach (var tuple in list)
        {
            var dateFrom = tuple.Item1;
            var dateTo = tuple.Item2;
            var ld1 = new LocalDate(dateFrom.Year, dateFrom.Month, dateFrom.Day);
            var ld2 = new LocalDate(dateTo.Year, dateTo.Month, dateTo.Day);
            var period = Period.Between(ld1, ld2, PeriodUnits.YearMonthDay);
            totalPeriod += period;
        }
        Console.WriteLine("Years: {0}, Months: {1}, Days: {2}",
            totalPeriod.Years,
            totalPeriod.Months,
            totalPeriod.Days);
        Console.Read();
    }

The output is:
Years: 9, Months: 11, Days: 52
It's wrong for me. I want to get, for example, the next output (Of course, the output depends on number of days in month, assuming that there are 31 days in our month):
Years: 10, Months: 0, Days: 21
So, I want that days was rounded to years and month. How I can get this?
The answer:
Using Matt's answer I created the next solution:
 foreach (var tuple in list)
        {
            var dateFrom = tuple.Item1;
            var dateTo = tuple.Item2;
            var period = Period.Between(LocalDateTime.FromDateTime(dateFrom).Date, LocalDateTime.FromDateTime(dateTo).Date, PeriodUnits.YearMonthDay);
            totalPeriod += period;
        }
        // trying clarify the period
        while(totalPeriod.Days >= 30)
        {
            totalPeriod = totalPeriod - Period.FromDays(30);
            totalPeriod = totalPeriod + Period.FromMonths(1);
            while (totalPeriod.Months >= 12)
            {
                totalPeriod = totalPeriod - Period.FromMonths(12);
                totalPeriod = totalPeriod + Period.FromYears(1);
            }
        }

A: Richard was right in his comment on the OP.  The problem is that the months and years aren't distinct quantities unto themselves.  One must have a frame of reference to "count" them.  You have that reference when you do the Period.Between operation, but it's lost by the time you try to add the periods together.
If you check the periods that are being added, it makes sense:
First:  Years: 3, Months: 11, Days: 30
Second: Years: 6, Months: 0,  Days: 22
Total:  Years: 9, Months: 11, Days: 52

In order to round as you would like, the 22 days being added to the 30 days would somehow have to know which month was being referenced.  Even if you retained the original information - which one would you use?  You could well have a 28-day month on one side, and a 31-day month on the other.
The best you could do would be to artificially round the results yourself afterwards, and choose a flat value (such as 30 days) to represent all months.
Oh, one minor thing (unrelated to your question) - To go from a DateTime to a LocalDate, try LocalDateTime.FromDateTime(dt).Date.  :)


text:
Q: Will a 3 phase induction generator fight its own rotation? So in a 3 phase induction generator with coils for the stator and magnets for on the rotor, I am wondering if the the current induced in the coils would create a magnetic field that would oppose the rotation of the magnets on the rotor?

A: All generators work such that the output current produces a force that opposes the rotation.  Think about it.  This comes from basic physics without having to know anything about how a generator works.  If there were no back force, there would be no power going into the generator from turning its shaft, which means no power could be coming out.

A: Yes, any generator will be subject to this effect.
You can't get something for nothing, so the more current drawn from the coils, the larger the (opposing) magnetic field (counter mmf) and the harder the rotor will be to turn.
If this didn't happen then the amount of energy required to turn the rotor would not change according to the load on the output, which would break the laws of physics.

A: if you follow Lenz's law.... effect opposes its cause.... in induction generator, the cause of current in coil is relative movement of magnetic field produced by rotor magnets. now by lenz's law, the current in stator will produce the magnetic field which opposes the cause "THE MOVEMENT", so it will try to stop the rotor... and the till the rotor is rotating, the current will flow in stator. also, the force is dependent on load also... greater the load, greater the current is drawn from stator, the greater will be the field created by stator, but to feed the greater load, the greater energy input from rotor side is also required to maintain the system at rated operation. thats how it works!!!


text:
Q: Linq deferred operations I mostly understand deferred execution, but I have a question about a particular case:
Given a code fragment such as
                        var resultsOfInterest = from r in ...
                                                select r;
                        foreach (var x in resultsOfInterest)
                        {
                            //do something with x
                        }

how many times is the query resultsOfInterest  executed? Once when setting up the foreach loop, or once for every element 'x'? Would it be more efficient with
                        foreach (var x in resultsOfInterest.ToArray())
                        {
                            //do something with x
                        }

?
TIA

A: It will be executed once, jut before loop, when GetEnumerator() method will be executed over query variable. Here is how foreach loop looks like:
var enumerator = resultsOfInterest.GetEnumerator(); // query executed here

while(enumerator.MoveNext()) // iterating over results of query execution
{
   var x = enumerator.Current;
   // do something with x
}

Second sample will not be more efficient, it simply stores results of query execution in array, and then calls array iterator:
var enumerator = resultsOfInterest.ToArray().GetEnumerator();
// loop stays same

A: In both cases, it only runs once.
In the first example, (if this is a Linq-to-Objects query), it runs just long enough to get the next x on each iteration. In the second example, it has to evaluates the entire result set at once and stores it to an array.
So, suppose this is an expensive query and it takes 1 second to get each item, and there are 20 items in the list, both queries will take about 20 seconds to process all items. However, the first one will be blocked for 1 second on each iteration while it gets the next item, but the second will be blocked for 20 seconds before the start of the loop, then loops through all the items in the array fairly quickly.
Neither is more efficient in when it comes to actually evaluating the query. In general, however, you should be avoid unnecessary calls to ToArray or ToList, since in addition to evaluating the query, it must allocate an array for the results (List<T> stores its items in an internal array). For a list of 20 items, this doesn't mean much, but when you have several thousand items, this can cause some noticeable slow-down. Of course, this doesn't mean that ToArray is always bad. If you had 5 foreach-loops in the previous example, storing the results in an array and looping through the array rather than re-evaluating the query each time would actually speed up the code by about 80 seconds

A: In both cases, the query is only executed once, but in the second case there are two enumerations.
Assuming 1000 items:
Case 1:

*

*Execute the select clause, assign result to x.

*Goto 1, repeat 1000 times.

Case 2:

*

*Create array.

*Execute the select clause, assign result to the array.

*Goto 2, repeat 1000 times.

*Access an element from the array, assign it to x.

*Goto 4, repeat 1000 times.

So generally creating an array is not desirable at all. But if you need to enumerate the same items multiple times yourself, and array access is faster than your select, then of course it would be more efficient to create the array.


text:
Q: What is the best way to manage pages content? My current template has the "onepage" style, but for SEO questions I've decided to change all theme by using pages separately in order to optimize each page and enjoy the best of Yoast plugin.
In my "onepage" template, I use get_template_part to include every section into the homepage. Every section is a category and each content is a post. Every "template part" contains a custom WP_Query I use to get the content.
Now I'm going to use multiple pages, I'm a little bit lost about managing the content. Should I insert all html of each section into the WP editor or it's better to create a custom template (e.g. page-about.php) and put html there? I mean, is it a good pratice using posts to manage content for pages or it's not a recommended way?

A: I would recommend you to use WP default editor functionality to display HTML on front end until and unless you don't have any specific requirement for a specific page. This will be easy for you to manage easily.


text:
Q: Angular directive does not work inside the `contenteditable` element Angular directive does not work inside the contenteditable element. How could I fix it?
Here is my sample use case.
I have a directive:
import { Directive, ElementRef } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Directive({
  // tslint:disable-next-line: directive-selector
  selector: '.customDownload',
})
export class ImgHandlingDirective {
  constructor(
    private el: ElementRef<HTMLImageElement>,
    private http: HttpClient,
  ) {

    alert("code reached");
  }

}

When I add an element with the customDownload class outside of the contenteditable I am getting the alert message as expected:
import { Component, ViewChild, Output } from '@angular/core';
import { DialogComponent } from './dialog.component';
import { EditorComponent } from '@progress/kendo-angular-editor';

@Component({
    selector: 'my-app',
    template: `
    <kendo-editor #editor style="height: 400px;" [iframe]="false">
        <kendo-toolbar>
            <kendo-toolbar-buttongroup>
                <kendo-toolbar-button kendoEditorBoldButton></kendo-toolbar-button>
                <kendo-toolbar-button kendoEditorItalicButton></kendo-toolbar-button>
                <kendo-toolbar-button kendoEditorUnderlineButton></kendo-toolbar-button>
                <kendo-toolbar-button kendoEditorStrikethroughButton></kendo-toolbar-button>
            </kendo-toolbar-buttongroup>
            <kendo-toolbar-button text="Upload Image" (click)="open()"></kendo-toolbar-button>
        </kendo-toolbar>
    </kendo-editor>

    <img class="customDownload" />

    <my-dialog #upload [editor]="editor"></my-dialog>
  `
})
export class AppComponent {
    @ViewChild('upload') public dialog: DialogComponent;
    @Output() @ViewChild('editor') public editor: EditorComponent;

    public open() {
        this.dialog.open();
    }
}

Now I change my code to the following:
import { Component, ViewChild, Output } from '@angular/core';
import { DialogComponent } from './dialog.component';
import { EditorComponent } from '@progress/kendo-angular-editor';

@Component({
    selector: 'my-app',
    template: `
    <kendo-editor #editor style="height: 400px;" [iframe]="false">
        <kendo-toolbar>
            <kendo-toolbar-buttongroup>
                <kendo-toolbar-button kendoEditorBoldButton></kendo-toolbar-button>
                <kendo-toolbar-button kendoEditorItalicButton></kendo-toolbar-button>
                <kendo-toolbar-button kendoEditorUnderlineButton></kendo-toolbar-button>
                <kendo-toolbar-button kendoEditorStrikethroughButton></kendo-toolbar-button>
            </kendo-toolbar-buttongroup>
            <kendo-toolbar-button text="Upload Image" (click)="open()"></kendo-toolbar-button>
        </kendo-toolbar>
    </kendo-editor>

    <my-dialog #upload [editor]="editor"></my-dialog>
  `
})
export class AppComponent {
    @ViewChild('upload') public dialog: DialogComponent;
    @Output() @ViewChild('editor') public editor: EditorComponent;

    public open() {
        this.dialog.open();
    }
}

Go to Upload Image:

Upload an image:

Check that the image was uploaded with the necessary class:

And now I see that the element was added to DOM, but Angular has just ignored it and no directive constructor run.
Here is the working example from the stackblitz.
I need the directive to be run (i.e. the alert message to be displayed) for the dynamically added element (i.e. an image with class customDownload). How could I achieve this?


text:
Q: UITableView's didSelectRow method not working I'm not receiving the touches. It shows the selection on the iPhone's screen, but it doesn't performs the method didSelectRow.
    usersTV.register(UserCell.self, forCellReuseIdentifier: "userCell")
    usersTV.dataSource = self
    usersTV.delegate = self
    usersTV.backgroundColor = .clear
    usersTV.separatorColor = .white
    usersTV.translatesAutoresizingMaskIntoConstraints = false
    usersTV.isHidden = true
    usersTV.tableFooterView = UIView()
    usersTV.isUserInteractionEnabled = true
    usersTV.isEditing = false
    usersTV.allowsSelection = true
    usersTV.allowsSelectionDuringEditing = false
    usersTV.allowsMultipleSelection = false
    usersTV.allowsMultipleSelectionDuringEditing = false
    usersTV.delaysContentTouches = false

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

Everything is programatically written.
The cells are custom with 3 labels and added constraints.
What could be the problem ?
UPDATE:
class UserCell : UITableViewCell{
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        let viewsDict = ["userName":userName,"field1":field1,"field2":field2]

    contentView.superview?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-8-[userName(120)]-8-[field1]-8-[field2(120)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict))
    contentView.superview?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[userName]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict))
    contentView.superview?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[field1]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict))
    contentView.superview?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[field2]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict))

UPDATE:
The didSelectRow method works only if you tap with 2 fingers...

A: TableViewCell is not clickable with one finger tap, but it is with two fingers
The answer of this question helped me. I've set GestureRecognizer on the main view. When I remove it the problem fixes.

A: I think this code will help you.If not,There may be a  issue with the label constraints.
@IBOutlet weak var UserTV: UITableView!
override func viewDidLoad() {
    super.viewDidLoad()
    UserTV.register(UserCell.self, forCellReuseIdentifier: "userCell")
    UserTV.dataSource = self
    UserTV.delegate = self

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let vc :UserCell = self.UserTV.dequeueReusableCell(withIdentifier: "userCell") as! UserCell
    vc.textLabel?.text = "Index: \(indexPath.row)"
    vc.backgroundColor = UIColor.red
    return vc
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("Slected \(indexPath.row)")
}

A: First of all, here is my comment on your code:

*

*No need to go much complex for this easy task.

*Don't forgot to set delegate and datasource properly.

*No need to use Visual Format way to set constraints, use Anchors.

My suggestion for you:

*

*Always try to use UICollectionView instead of UITableView.

class SampleTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: - Variables
lazy private var listTableView: UITableView = {
    let tableView = UITableView()
    tableView.translatesAutoresizingMaskIntoConstraints = false
    tableView.delegate = self
    tableView.dataSource = self
    return tableView
}()

// MARK: - View LifeCycle
override func viewDidLoad() {
    super.viewDidLoad()
    initialSetup()
}

// MARK: - Private Methods
private func initialSetup() {
    view.backgroundColor = .white

    view.addSubview(listTableView)
    listTableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    listTableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    listTableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    listTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    listTableView.register(UITableViewCell.self, forCellReuseIdentifier: "listCell")
}

// MARK: - TableView Methods
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 20
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 50
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "listCell", for: indexPath)
    cell.textLabel?.text = "Table Row - \(indexPath.row)"
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print(#function)
}


text:
Q: Defer, Async and the PageSpeed Insights I try to optimize the page speed load using the recommendations of PageSpeed Insights about, particularly, the deferring JavaScripts, in order do not block the page content to render.
So, it appears that HTML5 introduced a preatty cool feature, the async attribute, that permits to load scripts asynchronously in the "chaotic" mode. There is another attribute, the defer one, that loads them also asynchronously, but in the "ordered" mode (as I understood from that article).
So, I concluded that

*

*Always use (for every <script src='my.js'>) the defer attribute.

*In case if the script is not "load critical" (like jQuery, or jQuery-ui) the async attribute can be used.

Is it the right conclusion ?
PS.
Complimentary question:
Is the fact of adding scripts at the end of the document, automatically "unblocks" the rendering of the document? As I could understand, some scripts blocks the rendering, without difference of their location in the document (the <head> or just before </body>)...

A:
1. Always use (for every <script src='my.js'>) the defer attribute.

You should only defer scripts that can be deferred. In some cases you may need to guarantee execution order, or rely on features that must happen inline. For example, scripts that call document.write must not be deferred.

2.  In case if the script is not "load critical" (like jQuery, or jQuery-ui) the async attribute can be used.

"load critical" doesn't have any specific meaning, so it's a poor choice of phrasing. async should be used for scripts that can execute in any order and aren't a dependency of other scripts.


text:
Q: Table Column Not Updating update
    table_1 as q
set
    q_sequence = (row_number() OVER(
            PARTITION BY
            q.account_uid
            ,q.c_c_uid
            ,q.a_uid
             order by q.a_time ASC) as new

This does not work, I get the following error message:

Query 1: ERROR:  syntax error at or near "as" LINE 10:     order by
q.a_time ASC) as new

Any suggestions?

A: You are incorrectly using the as keyword here.
as is used for aliasing a table or a column in a select statement:
https://www.w3schools.com/mysql/mysql_alias.asp
Removing as new should solve you syntax error.


text:
Q: How can mounting a VeraCrypt drive be done without root in Linux? I used TrueCrypt for a long time in Kubuntu, in which I used a keyboard shortcut to automatically mount a drive. Nowadays I use VeraCrypt, but I am always prompted for my sudo password after entering the password for the encrypted drive. This was never necessary in TrueCrypt.
It occurred to me that I could potentially mount the drive as a removable media (this is an operation that does not require a root password), but when mounting the drive to /mount/ (which is where removable media is mounted), I still get the sudo password request.
Furthermore, an option in VeraCrypt allows Volume Mounted as Removable Medium, but this option simply doesn't exist in the version I'm running in Linux (v1.19).
What is going on here? How can I request that the VeraCrypt mounting process behave like removable media? Entering my password every mount and dismount is irritating.

A: One option would be to set the the SUID bit on veracrypt. This would make sure it took on root privileges whenever run.
# chmod u+s /usr/bin/veracrypt

Generally, however, I try to avoid the SUID or SGID bits, as they allow any user with permission to execute the binary to use it at elevated privileges.
A better option:
Another option you have if you've got sudo is to create a group with password-free sudo privileges for veracrypt.
This is definitely a still a little less secure than always requiring a password, as is always the case when creating sudo rules like this. Make sure you read this carefully and understand what it entails to ensure you do not create a security risk!

Before you begin, you want to ensure that the /usr/bin/veracrypt binary is not writable by group or other.
Confirm that it is not writable by another other than the owner:
$ ls -lha /usr/bin/veracrypt
-rwxr-xr-x 1 root root 7.1M Sep 11  2019 /usr/bin/veracrypt

First, create a new group:
# groupadd veracrypt_group

Next, add your user(s) to the group:
# usermod -aG veracrypt_group your_user

Now you now use visudo to create a new sudo rule:
# visudo -f /etc/sudoers.d/veracrypt

This one will allow the veracrypt_group to run /usr/bin/veracrypt without a password.

%veracrypt_group ALL=(root) NOPASSWD:/usr/bin/veracrypt

A: I had this problem in Linux Mint when my veracrypt container was in a directory not owned by the user opening the container. Even though the user could write to that directory (and owned the container file). Moving it to a folder that the user owns stopped veracrypt from prompting for an admin password.


text:
Q: Getting exception while zip files I have a method that convert my bytes to files then zip that files:
public async Task<IActionResult> MultipleGet(MultipleProofOfDeliverySelectModel model)
    {
        try
        {
            async Task<IActionResult> DoMultipleGet()
            {
                var rModel = await _MyService.MultipleGet(model);

                var today = DateTime.Today.ToString("yyyyMMdd");
                var loggedUserName = Environment.UserName;
                var filePath = $"C:\\Users\\{loggedUserName}\\Test\\";
                var zipPath = $"C:\\Users\\{loggedUserName}\\Test\\test_{today}.zip";

                var fileExistIterator = 1;
                foreach (var file in rModel)
                {
                    if (!System.IO.File.Exists($"{filePath}{file.Name}"))
                    {
                        System.IO.File.WriteAllBytes($"{filePath}{file.Name}", file.File);
                    }
                    else
                    {
                        System.IO.File.WriteAllBytes($"{filePath}{fileExistIterator}{file.Name}", file.File);
                        fileExistIterator++;
                    }
                }

                //HERE IS THE ISSUE
               ZipFile.CreateFromDirectory(filePath, zipPath);

                return Ok(zipPath);

            }
            return await DoMultipleGet();
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

Problem is when application Zip files ZipFile.CreateFromDirectory(filePath, zipPath); it do the process but return an exception

The process cannot access the file test_20200708.zip' because it is
being used by another process.

Why that happen if I use only that method and no other do something with that files?


text:
Q: Send complex objects with cross references using web services JAVA and Axis2 Hi guys this is my first post in Stack Overflow, I'm a student and new develop in Java and I'm trying to solve a problem.
I have a objects structure and I'm trying to send it by web service to consume in an android application.
The problem is because this structure have a lot of cross references.
Now I'm trying to use Axis2 returning an object, but this give me an error because I use enums. And before this I tried to send a JSON in a String, but have problems creating the JSON with cross references.
In my structure I have classes, Interfaces, inheritances, abstracts classes and
generics.
I spent a lot of time in this trying to solve it. But when I solve one thing I have a new problem.
What is the best approach to solve this?


text:
Q: javascript window.open infinite loading I have a JQuery ajax request that can return error status and messages.
To handle them I use this code :
$.ajax("url", {
    options: options
}).done(function(text, statusText, data) {
    //Manage data
}).fail(function(data) {
    //Manage fail
});

In the fail handle I want, in case of 500: internal server error, to open a new tab with the response text (for debug purposes)
I do it this way :
if (data.status === 500) {
    var w = window.open("App error", "blank");
    w.document.write(data.responseText);
}

And it works !
Except one point : my browser loads the page, the content is displayed (and as it's static content all of this is not a real problem), but the tab is marked as loading... Loading... Loading...
I'm using Firefox 63.0(64bits).
Does anyone know where this comes from ? It's not really annoying, it's just a (fun ?) behavior I don't understand.
Here is a fiddle on which I get the exact same behavior.

A: The problem is that you are opening a tab without an url, and most browsers expect an url, that's what I do in order to get rid of it:
      const newWindow = window.open('#');
      if (newWindow) {
        newWindow.addEventListener('load', () => {
          newWindow.document.open();
          newWindow.document.write(request.responseText);
          newWindow.document.close();
          newWindow.stop();
        }, true);

You can replace # with any url path that doesn't exist, the important thing is that once it's loaded, you'll be able to override the content.
It's not the best solution but at least it makes the trick

A: It has to do with the w.document.write line. If you close the document, the loader will finish. Change the code to:
if (data.status === 500) {
    var w = window.open("App error", "blank");
    w.document.write(data.responseText);
    w.document.close();
}

Source: Open about:blank window in firefox


text:
Q: select estimate comboBox,date et time I want selects the contents of a ComboBox, and DateEdit TimeEdit
This did not work
it displays only the mat field
QSqlQuery qry;
qry.prepare("select * from Etudiant");
if(qry.exec()){
    while(qry.next()){
        ui->lineEdit_matE->setText(qry.value(0).toString());
        ui->comboBox_sexE->setCurrentIndex(qry.value(1).toInt());
        ui->dateEdit_dateA->setDate(qry.value(2).toDate());
        ui->timeEdit_heureA->setTime(qry.value(3).toTime());
    }
}

A: QSqlQuery qry;
qry.prepare("select * from Etudiant");
if(qry.exec()){
    if(qry.next) {
       do{
            ui->lineEdit_matE->setText(qry.value(0).toString());
            ui->comboBox_sexE->setCurrentIndex(qry.value(1).toInt());
            ui->dateEdit_dateA->setDate(qry.value(2).toDate());
            ui->timeEdit_heureA->setTime(qry.value(3).toTime());
        }while(qry.next());
    }
    else {
    qDebug << "No results found.";
    }

}
else
{
  qDebug << "Unable to execute query."
}

You will see if it returns a value.