text:
Q: How do I move an HTML div with PHP content using CSS I have created a web-based e-learning module. Users will use a web browser to view and navigate through the module. I have two buttons labeled as 'back' and 'next' for users to get through the module. All content on each page is controlled by PHP arrays to place the text that the user sees on the page. My HTML/PHP code is:

<?php echo $module; ?>

Myths

<?php echo $heading[$page-1]; ?>

            <?php echo $ref[$page-1];?>

            <?php

                if ($page != 1) {
                    echo 'Back';
                }

                if (!in_array($page+1, $progress_pages) && $page != $last_page) {
                    echo 'Next';
                }
                else {
                    echo 'Next';
                }

                ?>

My problem is that the navigation buttons 'back' and next appear on top of the content see below:

How do I fix this? is it a CSS problem? The CSS is
.ref{
    width: 50%;
    margin-left: auto;
    margin-right: auto;
    overflow-y: auto;
    overflow-x: hidden;
    border:  1px, solid #ccc;
    padding: 0px 7px;

}

.nav-btns {
    width: 100%;
    position: absolute;
    top:600px;
}

A: Try to change
.nav-btns {
    width: 100%;
    position: absolute;
    top:600px;
}

to
.nav-btns {
    width: 100%;
    display: block;
}

Let me know the result!

A: To add it at the bottom of the page ( just like a 'sticky-footer' ) you can use flexbox. See example below.

.nav-btns {
  width: 100%;
  box-sizing: border-box;
  text-align: center;
}
.nav-btns a {
  display:inline-block;
  line-height:20px;
  color: #fff;
  background: blue;
  padding: 5px 40px;
  margin: 0 5px;
  text-decoration: none;
}
#white {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}
.ref {
   flex: 1;
}
body {
  margin:0
}

Header here

    Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium

    Back
    Next

A: The issue in your code is that you are using absolute position. Instead you should use fixed position. This would solve your issue. And you would need to add padding-bottom to your content div so the content doesn't get cut behind navigation.
Additionally, I would suggest to use class instead of id unless you are using them in javascript. I have created a quick basic structure if you would like to use.

*, *:before, *:after {
    box-sizing: border-box;
}

body {
    padding: 0;
    margin: 0;
    min-height: 100%;
    font-family: 'Arial', sans-serif;
}

.wrapper {
    background-color: #fff;
}

.container {
    display: flex;
    flex-direction: column;
}

.header {
    min-height: 50px;
    background-color: #666;
}

.content {
    width: 90%;
    max-width: 800px;
    margin-left: auto;
    margin-right: auto;

    /* Padding bottom should be same as footer height.
     * Increase this value if there is increase in navigation height
     */
    padding-bottom: 36px;
}

.nav {
    background-color: #eee;
    text-align: center;
    padding: 4px;
    position: fixed;
    bottom: 0;
    width: 100%;
}

.nav a {
    font-size: 16px;
    background-color: #00c8ff;
    color: #fff;
    display: inline-block;
    padding: 5px 10px;
    text-decoration: none;
}
<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

Myth#1

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi asperiores, culpa earum illo inventore, laudantium maxime non numquam omnis quo quod tempore, veritatis vitae voluptas.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam aspernatur atque blanditiis corporis illum, soluta unde. At deleniti doloribus minima optio! Aspernatur atque illo ipsam ipsum labore modi omnis provident quasi. Adipisci assumenda aut eius enim expedita facilis labore magnam nihil porro, quod rem repudiandae tenetur? Delectus doloremque ex modi perferendis possimus! Cumque eaque harum obcaecati quaerat. A ab consequatur dolorum error est eveniet fugit harum, hic ipsam ipsum laboriosam libero magnam mollitia nemo nulla obcaecati repellendus sapiente similique unde voluptate! Amet, deleniti illum libero nemo repudiandae sapiente tenetur veritatis. Ad blanditiis, commodi corporis, delectus doloremque expedita facere illo iusto natus necessitatibus nesciunt nobis obcaecati odio qui sequi sint vel. Accusamus ad adipisci asperiores atque autem cum dolor dolore dolores doloribus dolorum ducimus esse eum fuga fugit illo ipsa ipsam iste laborum magni, minima numquam obcaecati odio perferendis perspiciatis placeat quae quam qui quidem ratione rem reprehenderit repudiandae, sequi suscipit.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur atque culpa delectus doloribus ducimus et, facere labore laborum maxime nam nesciunt quaerat quas quidem suscipit tempora veritatis voluptatibus! Ipsa nobis similique vero voluptatem? Ab accusamus alias aliquid animi consectetur corporis delectus dolorem eaque eligendi error esse et expedita facere, hic id illo illum in ipsum labore maiores molestiae nam odit placeat porro provident quaerat qui quisquam ratione reiciendis sint sunt totam vel voluptas? Accusantium adipisci, consequuntur fugit illo itaque sapiente temporibus? Architecto, cupiditate eius, esse et ex illum inventore labore magnam maiores omnis quae, quod quos rem repellat similique voluptatum!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi asperiores, culpa earum illo inventore, laudantium maxime non numquam omnis quo quod tempore, veritatis vitae voluptas.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam aspernatur atque blanditiis corporis illum, soluta unde. At deleniti doloribus minima optio! Aspernatur atque illo ipsam ipsum labore modi omnis provident quasi. Adipisci assumenda aut eius enim expedita facilis labore magnam nihil porro, quod rem repudiandae tenetur? Delectus doloremque ex modi perferendis possimus! Cumque eaque harum obcaecati quaerat. A ab consequatur dolorum error est eveniet fugit harum, hic ipsam ipsum laboriosam libero magnam mollitia nemo nulla obcaecati repellendus sapiente similique unde voluptate! Amet, deleniti illum libero nemo repudiandae sapiente tenetur veritatis. Ad blanditiis, commodi corporis, delectus doloremque expedita facere illo iusto natus necessitatibus nesciunt nobis obcaecati odio qui sequi sint vel. Accusamus ad adipisci asperiores atque autem cum dolor dolore dolores doloribus dolorum ducimus esse eum fuga fugit illo ipsa ipsam iste laborum magni, minima numquam obcaecati odio perferendis perspiciatis placeat quae quam qui quidem ratione rem reprehenderit repudiandae, sequi suscipit.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur atque culpa delectus doloribus ducimus et, facere labore laborum maxime nam nesciunt quaerat quas quidem suscipit tempora veritatis voluptatibus! Ipsa nobis similique vero voluptatem? Ab accusamus alias aliquid animi consectetur corporis delectus dolorem eaque eligendi error esse et expedita facere, hic id illo illum in ipsum labore maiores molestiae nam odit placeat porro provident quaerat qui quisquam ratione reiciendis sint sunt totam vel voluptas? Accusantium adipisci, consequuntur fugit illo itaque sapiente temporibus? Architecto, cupiditate eius, esse et ex illum inventore labore magnam maiores omnis quae, quod quos rem repellat similique voluptatum!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi asperiores, culpa earum illo inventore, laudantium maxime non numquam omnis quo quod tempore, veritatis vitae voluptas.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam aspernatur atque blanditiis corporis illum, soluta unde. At deleniti doloribus minima optio! Aspernatur atque illo ipsam ipsum labore modi omnis provident quasi. Adipisci assumenda aut eius enim expedita facilis labore magnam nihil porro, quod rem repudiandae tenetur? Delectus doloremque ex modi perferendis possimus! Cumque eaque harum obcaecati quaerat. A ab consequatur dolorum error est eveniet fugit harum, hic ipsam ipsum laboriosam libero magnam mollitia nemo nulla obcaecati repellendus sapiente similique unde voluptate! Amet, deleniti illum libero nemo repudiandae sapiente tenetur veritatis. Ad blanditiis, commodi corporis, delectus doloremque expedita facere illo iusto natus necessitatibus nesciunt nobis obcaecati odio qui sequi sint vel. Accusamus ad adipisci asperiores atque autem cum dolor dolore dolores doloribus dolorum ducimus esse eum fuga fugit illo ipsa ipsam iste laborum magni, minima numquam obcaecati odio perferendis perspiciatis placeat quae quam qui quidem ratione rem reprehenderit repudiandae, sequi suscipit.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur atque culpa delectus doloribus ducimus et, facere labore laborum maxime nam nesciunt quaerat quas quidem suscipit tempora veritatis voluptatibus! Ipsa nobis similique vero voluptatem? Ab accusamus alias aliquid animi consectetur corporis delectus dolorem eaque eligendi error esse et expedita facere, hic id illo illum in ipsum labore maiores molestiae nam odit placeat porro provident quaerat qui quisquam ratione reiciendis sint sunt totam vel voluptas? Accusantium adipisci, consequuntur fugit illo itaque sapiente temporibus? Architecto, cupiditate eius, esse et ex illum inventore labore magnam maiores omnis quae, quod quos rem repellat similique voluptatum!

            Prev
            Next


text:
Q: Function not working on dynamic value but works on string, int or whatever I manually enter I have a function, which formats phone numbers, that is exported like so :
export function formatPhoneNumber(phoneNumber) {
    var replace = ('' + phoneNumber).replace(/\D/g, '');
    var format = replace.match(/^(\d{3})(\d{3})(\d{4})$/);

    return (!format) ? null : "(" + format[1] + ") " + format[2] + "-" + format[3];
}

and I am importing it into another file like so:
import {formatPhoneNumber} from '../ui/format_phone_number';

All is well and working, with the import. I wanted to mention that just in case there was some related issue.
I am looping over an object and want to format a phone number using the imported function. The odd thing is that when I try to format the value from the object, it returns null, but if I manually enter an int, or string it handles it correctly.
Here is my code:
$.each(signVendor, function( fieldId, value) {
    if(fieldId == 'phone') {
        console.log(value); // 262321345
        console.log(formatPhoneNumber(8885551234)); // (888) 555-1234
        console.log(formatPhoneNumber('8885551234')); // (888) 555-1234
        console.log(formatPhoneNumber(value)); // null
        value = formatPhoneNumber(value);
    }
    $formSignVendor.find('input[name=' + fieldId + ']').val(value);
 });

Here are the console results in the same order as above:

redpajama_set_name: RedPajamaStackExchange


text: Q: more than 16 colours on graphics.h in C++ in Ubuntu 12.04 I was just wondering if there is way to output more than 16 colours in graphics.h? I am using Ubuntu 12.04, and currently I can only output 16 colours. I have been trying to find a way to do it, but have not been able to do so. I feel it has something to do with the parameters passed to the initgraph function. I would like to be able to draw 8 bit and even 24 or even 32 bit per pixel bitmaps in graphics.h in C++ in Ubuntu 12.04.


text: Q: Как реализовать совместное редактирование списка ToDol ist Появилась идея создать небольшое приложение ToDo list. В качестве повышения сложности, решил реализовать редактирование списка несколькими пользователями. Какие способы реализации подобной функции существуют ?


text:
Q: java.lang.ClassCastException: com.example.Entity cannot be cast to com.example.Entity I'm creating a JSF+JPA project for and GlassFish 4. A couple of times I get an exception at the at this point:
List<User> users = connection.getUserList();

for (User u : users) { //exception

...
    public List<User> getUserList() {

    EntityManager em = Persistence.createEntityManagerFactory("project").createEntityManager();
    List<User> users = em.createQuery("SELECT c FROM User c", User.class).getResultList();
    em.close();
    return users;
}

stacktrace:
javax.faces.el.EvaluationException: java.lang.ClassCastException: de.sep.ateam.sap.norris.model.User cannot be cast to de.sep.ateam.sap.norris.model.User
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.ClassCastException: de.sep.ateam.sap.norris.model.User cannot be cast to de.sep.ateam.sap.norris.model.User
    at de.sep.ateam.sap.norris.controller.beans.LoginBean.doLogin(LoginBean.java:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at javax.el.ELUtil.invokeMethod(ELUtil.java:326)
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:536)
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:269)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 35 more

A: If you are sure that you don`t have multiple versions of the same class loaded in the application server, you might try to reset the server cache.
Follow this steps:

*

*Undeploy the application;

*Stop the application server;

*Delete the osgi cache folder of your application server. I.e. if you are
using glassfish, it is the folder:
E:\glassfish-3.1.2.2\glassfish\domains\domain1\osgi-cache

*Restart the server;

*Deploy the application.

A: I had the same issue, and I finally found a workaround on java.net :
Copy all org.eclipse.persistence jar files from glassfish4/glassfish/modules to WEB-INF/lib.
Then go in your glassfish-web.xml, and set class-delegate to false.
Worked for me !

A: I had a similar problem  because I was serializing classes and the serialized versions couldn't be deserialized after the classes updated and the app was restarted without restarting the container.

A: Typically this happens when there is more than one instance of the same jar in a different class loader.  Most app servers have a global class loader and a web-app specific class loader (some also have others like contrib, etc.).  If the class loader that is higher up in the food chain has that class defined already and it gets redefined by a lower level class loader this sort of situation can occur (the same class in a different class loader is considered different even though its definition is the same).  The order of how/when jars get loaded is not guaranteed which could explain why you sometimes see the error and sometimes don't.  Long story short, make sure you haven't already deployed the jar that contains this class somewhere else in the server that is visible to your web app.


text:
Q: Unable to get roster list from XMPP server I have created two accounts on https://www.blah.im for testing purposes. I use agsXMPP client library for communicating with server. The connection is authenticated right and member is logged in. But roster is not displayed.
This is my code
xmpp.Open(userName, password);
    xmpp.OnLogin += new ObjectHandler(xmpp_OnLogin);
    Console.WriteLine(xmpp.XmppConnectionState);
    Console.WriteLine("Authenticated {0},", xmpp.Authenticated);

  Console.WriteLine("Wait");
      int i = 0;
      do {
       Console.Write(".");
       i++;
       if (i == 10)
           _wait = false;
       Thread.Sleep(3000);
     } while (_wait);

Console.WriteLine("Connection state   {0}", xmpp.XmppConnectionState);
Console.WriteLine("Authenticated {0},", xmpp.Authenticated);

 agsXMPP.protocol.client.Presence p =
 new agsXMPP.protocol.client.Presence
(ShowType.chat, "Online");
 p.Type = PresenceType.available;
  xmpp.Send(p);
    xmpp.OnPresence += new agsXMPP.protocol.client.PresenceHandler(xmpp_OnPresence);
     Thread.Sleep(3000);
     Console.WriteLine("Who do you want to connect ");
      string friend = Console.ReadLine();
       Console.WriteLine("Start Chat");

static void xmpp_OnPresence(object sender, agsXMPP.protocol.client.Presence pres)
   {
          Console.WriteLine("Available Contacts: ");
          Console.WriteLine("{0}@{1}  {2}", pres.From.User, pres.From.Server, pres.Type);
          Console.WriteLine();

    }

Is there any subscription stuff that must be done to get the available members ?

A: yes you need to add all the contacts to your contact list (aka roster), and be subscribed to them properly in order to get their presence.
Add the OnRosterItem event to see your contacts and their subscription status,


text:
Q: Upgrading via Terminal from LinuxMint 18.3 to 19.3--How much disk space? I would like to know how much space I need to upgrade from 18.3 to 19.3...it reads 1500 MB necessary to download and 1600 MB of additional disk space will be used. Are the 1500 MB already extracted, or will it extract those 1500 MB to like 3000 MB and then only delete the original downloaded files? or does it immediately and directly install the 1500 MB of files on the disk without unpacking, so that the end up being 1600 MBs then?

A: It depends on what do you install on your computer.  I don't know mint, but I have seen fresh recent ubuntu install that takes ~4GB.  This This was a minimum standard install though, and everything else you add there quickly fills up your harddisk. So if you just download and install, it would not take 15GB, but if you install/update the software you use, you quite likely end up using this much. E.g. a recent ubuntu 20 fills 13GB, and an older ubuntu 18 fills 26GB.  Note though that these are not just the files that are copied from the repos, but also various kind of runtime and temporary files.
How much free space do you need also depends on how do you partition the the disk, and what do you do with your computer.  In particular, where are /var and /tmp, and what will be stored there.  Assuming your /var and /tmp are on the system partition /, and this is separate from /home, I'd say 5GB is the absolute minimum for something like a desktop system (but special installations may be much smaller).  To be on safe side, I'd say reserve at least 25GB for your system partition, better if >=50GB.  But again, it depends on what you do and how do you organize your hard disk.


text:
Q: Merge "delphi-prism" tag into "oxygene"? I was wondering what the process is for initiating a merge of the above two tags. I'm representing RemObjects Software, the vendor/creator of the Oxygene language. "Delphi Prism" is an old name that was used when Oxygene was licensed to Embarcadero to distribute the product under that name.
Right now, the majority of Oxygene-related questions are tagged with delphi-prism, and few are tagged with oxygene. There's two reasons/arguments for merging the two:

*

*The "Delphi Prism" brand name is no longer used for the product at all (even the version resold by Embarcadero dropped that branding)

*Having two tags for the same language only serves to spit the already tiny/niche (compared to more mainstream languages) community and their questions
Merging the tags and keeping oxygene would consolidate on the actual proper name of the language, and make it easier for users to find existing questions in one place.

A: The only reason I can see for not merging the tags is that there are answers that apply to Delphi Prism that don't apply to Oxygene. If a question that is asked about Delphi Prism would have a different answer if asked about Oxygene, then the question should be tagged delphi-prism, not oxygene.
If there isn't any difference between Delphi Prism and Oxygene, then I would merge the two tags, and make oxygene the main tag.
In the case there are questions that apply to Delphi Prism but not Oxygene (or vice versa), then this case is similar to  the one of drupal-7 and drupal-8. Drupal 8 and Drupal 7 are so different that they are like two different products; if I merge the tags, I would create confusion, since what applies to Drupal 7 could not apply to Drupal 8.

A: Delphi Prism was just a rebranding of Oxygene. All questions about Delphi Prism are actually questions about Oxygene. Delphi Prism is no longer a product, but the Oxygene name (which predated Prism) continues to be around. They should be merged.


text:
Q: ASP.net c# LINQ for loop // Load all the links
ArtworkingDataContext dc = new ArtworkingDataContext();
var q = (from Labels in dc.tblArtworkLabels where Labels.templateID == this.ID select new { LabelID = Labels.ID });

// Create labels array
this.Labels = new ArtworkLabel[q.Count()];
for (int i = 0; i < q.Count(); i++)
{
    this.Labels[i] = new ArtworkLabel(q.LabelID);
}

The q.LabelID isn't working, I can't really use a foreach because I have to invoke a new ArtworkLabel on each iteration.

A: This would work:
var queryList = q.ToList();
for (int i = 0; i < queryList.Count; i++)
{
    this.Labels[i] = new ArtworkLabel(queryList[i].LabelID);
}

Also you can directly project from your query:
this.Labels = dc.tblArtworkLabels
                .Where( x=> x.templateId == this.Id)
                .Select( x=> new ArtworkLabel(x.ID))
                .ToArray();

A: Try like this:
this.Labels = q.Select(x => new ArtworkLabel(x.LabelID)).ToArray();

A: You could potentially just do this, right?
ArtworkingDataContext dc = new ArtworkingDataContext();

this.Labels =
    from label in dc.tblArtworkLabels
    where label.templateID == this.ID
    select new ArtworkLabel(label.ID).ToArray();

A: You should be able to do it all in one linq statement.
ArtworkingDataContext dc = new ArtworkingDataContext();
this.Labels = (from Labels in dc.tblArtworkLabels where Labels.templateID == this.ID select new ArtworkLabel(Labels.ID)).ToArray();

A: I tried this recently, a linq for loop.. this is what I came up with..
        var query = from ii in Enumerable.Range(0, xml.AllIndexesOf("<item").Count())
                    where ii < xml.AllIndexesOf("<item").Count()
                    select new { Start = xml.AllIndexesOf("<item").ToList()[sii], Count = xml.AllIndexesOf("</item").ToList()[sii] - xml.AllIndexesOf("<item").ToList()[sii] };


text:
Q: Doubts in histogram in python: frequency graph I'm very confused to create a frequency histogram in python using matplotlib.pyplot.
I have two list: one is the frequency list and another is category list. E.g:
Frequency list:
freq = [123,142,543,77866,8,2424,3]

category list:
category = [-1.23,0,2.13,5.4345,7.45,9.00,12.32]

So, each item from freq list relates with the item from the category the same position, e.g: 123: -1.23, 543:0 ...
That's my doubt...
How to using those list in the hist ?
plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)

I'm very confused each parameters i have to use in the instruction..
Could you help me about it?
Here is the sample of hist I'd like to create.


text:
Q: Multindex to one hot vector in pandas I have a multiindex dataframe like this
                    bill
    City   Month
    3          01        14586
               02        14316
               03        17261
               04        16642
               05        14977
               06        14237
               07        14486
               08        14216
               09        17461
               10        16742
               11        14677
               12        14637

    4          01        24586
               02        24316
               03        27261
               04        26642
               05        24977
               06        24337
               07        24486
               08        24216
               09        27461
               10        26742
               11        24677
               12        24637

That I get from this line of code
df = df.groupby(['City', 'Month']).sum()
I'd like to get one hot encoding for Month index and convert it to 12 columns in order to have such a dataframe
     City   M1 M2 M3 ... M12   bill
     3       1 0   0     0       46
     3       0 1   0     0       64
     3       0 0   1     0       386
    ...
     4       1 0   0     0       546
     4       0 1   0     0       686
    ...

Numbers don't match but I think idea is clear. My target is bill and
Month are features for ML model

A: First convert MultiIndex to columns by DataFrame.reset_index, then use get_dummies and last for last column bill reaasign column by DataFrame.pop:
df = df.reset_index()

df = pd.get_dummies(df, columns=['Month'], prefix='M', prefix_sep='')
df['bill'] = df.pop('bill')
print (df)
  City  M01  M02  M03  M04  M05  M06   bill
0    3    1    0    0    0    0    0  14586
1    3    0    1    0    0    0    0  14316
2    3    0    0    1    0    0    0  17261
3    3    0    0    0    1    0    0  16642
4    3    0    0    0    0    1    0  14977
5    3    0    0    0    0    0    1  14337


text:
Q: Get the size of xtick/ytick labels I need to get the size of xtick/ytick labels (the xtick.labelsize or ytick.labelsize in a matplotlibrc file).
I've looked around the API of axes but there's apparently no method for doing this.
Can this be done?

A: To access the current matplotlibrc file, use matplotlib.rcParams which is a dictionary containing the corresponding settings. For example:
xtick_labelsize = matplotlib.rcParams['xtick.labelsize']


text:
Q: Question regarding assembly language I am reading the book The Art of Assembly Language. I came across these two lines.
the three byte encoding for mov ax, [1000] would be 0C6h, 00h,
10h and the three byte encoding for mov ax, [2000] would be 0C6h, 00h, 20h.

Can anybody show me how mov ax, [1000] converted to oc6h, ooh, 10h and mov ax, [2000]  converted to  0C6h, 00h, 20h. Can anybody show me the calculations? Thanks in advance.
EDIT: I am a starter in assembly programming, kindly explain with description.

A: Just guessing, but looks to me like:
0C6h - This is the opcode for "mov ax,"
00h 10h - This is the address 1000h, Little Endian
00h 20h - This is the address 2000h, Little Endian

A: I'm assuming your confusion lies in the fact that 1000 was encoded as 10h.
ax is an alias for the bottom 16 bits of the 32 bit eax register. So mov ax, 1000 knows that this is a 16-bit operation. 1000 is encoded as 00 10 in memory because it was encoded using little-endianness which basically means that the most significant byte is last in physical order.

A: 00h is the LoByte of the Memory Address
20h is the HiByte of the Memory Address
OC6h is the OpCode instruction for mov, ax

A: The opcodes for all x86 instructions can be found at http://download.intel.com/design/intarch/manuals/24319101.pdf (mov is at page 442). Chapter 2 describes how opcodes are encoded with register arguments.
Other answers already explain the encoding :-)


text:
Q: List arguments for ssoadm Can anyone tell me how to separate list arguments in an openam ssoadm call? For example how do i list multiple trusted providers in the create-cot call?
ssoadm -u amadmin -f conf/pwd -e myRealm -t myCOT -trustedproviders "what goes here"
I cannot seem to find an example anywhere.

A: Try this:
ssoadm -u amadmin -f conf/pwd -e myRealm -t myCOT -trustedproviders "trustedprovider1" "trustedprovider2"


text:
Q: Can __setattr__() can be defined in a class with __slots__? Say I have a class which defines __slots__:
class Foo(object):
    __slots__ = ['x']

    def __init__(self, x=1):
        self.x = x

    # will the following work?
    def __setattr__(self, key, value):
        if key == 'x':
            object.__setattr__(self, name, -value) # Haha - let's set to minus x

Can I define __setattr__() for it?
Since Foo has no __dict__, what will it update?

A: All your code does, apart from negate the value, is call the parent class __setattr__, which is exactly what would happen without your __setattr__ method. So the short answer is: Sure you can define a __setattr__.
What you cannot do is redefine __setattr__ to use self.__dict__, because instances of a class with slots do not have a __dict__ attribute. But such instances do have a self.x attribute, it's contents are just not stored in a dictionary on the instance.
Instead, slot values are stored in the same location a __dict__ instance dictionary would otherwise be stored; on the object heap. Space is reserved for len(__slots__) references, and descriptors on the class access these references on your behalf.
So, in a __setattr__ hook, you can just call those descriptors directly instead:
def __setattr__(self, key, value):
    if key == 'x':
        Foo.__dict__[key].__set__(self, -value)

Interesting detour: yes, on classes without a __slots__ attribute, there is a descriptor that would give you access to the __dict__ object of instances:
>>> class Bar(object): pass
...
>>> Bar.__dict__['__dict__']
<attribute '__dict__' of 'Bar' objects>
>>> Bar.__dict__['__dict__'].__get__(Bar(), Bar)
{}

which is how normal instances can look up self.__dict__. Which makes you wonder where the Bar.__dict__ object is found. In Python, it is turtles all the way down, you'd look that object up on the type object of course:
>>> type.__dict__['__dict__']
<attribute '__dict__' of 'type' objects>
>>> type.__dict__['__dict__'].__get__(Bar, type)
dict_proxy({'__dict__': <attribute '__dict__' of 'Bar' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Bar' objects>, '__doc__': None})


text:
Q: Determine whether a point is inside a partial cone Can someone please help me with a way to determine whether a point, given as (px,py,pz) is inside a "partial upside down" cone. The cone is always aligned with the z-axis. The cone is defined with height, bottom radius, top radius, x and y where:
-height is the z value of the top of the cone. The bottom of the cone is always on the xy plane.
-bottom radius is the radius of the cone at the bottom.
-top radius is the radius of the cone at the top. (top radius >= bottom radius)
-x and y is the position of the centre point if the cone on the xy plane
NOTE: The given point's Z coordinate will always be between the bottom and top of the cone.
Any help will be appreciated.

A: Let the cone be defined by the height $h$, bottom radius $r_0$ (at $z = 0$), and top radius $r_h$ (at $z = h$), and the $x$ and $y$ coordinates $c_x, c_y$ of the center of the cone, and let the point be described by $p = (p_x, p_y, p_z)$.
As the radius of the cone at height $z \in [0, h]$ scales linearly with $z$, we can find a formula for $r_z$, the radius at arbitrary height $z$:
$$r_z = r_0 + \frac{z}{h} (r_h - r_0) = \frac{(h-z) \cdot r_0 + z \cdot r_h}{h}. \qquad (z \in [0, h])$$
Observe that indeed $r_z \to r_0$ as $z \to 0$ and $r_z \to r_h$ as $z \to h$.
Finally, given a point $p = (p_x, p_y, p_z)$, to figure out if it is inside this cone, we must check whether $(p_x, p_y)$ is inside the circle at center $(c_x, c_y)$ and radius $r_z$ with $z = p_z$. This corresponds to checking whether the following condition holds:
$$(p_x - c_x)^2 + (p_y - c_y)^2 \quad \stackrel{?}{\leq} \quad r_{p_z}^2.$$
If you want to have an explicit condition in terms of the original variables, we can simply substitute the earlier formula for $r_z$ to obtain
$$h^2 (p_x - c_x)^2 + h^2 (p_y - c_y)^2 \quad \stackrel{?}{\leq} \quad \left[(h-p_z) \cdot r_0 + p_z \cdot r_h\right]^2.$$
If this evaluates to true, it is inside the cone, while if this condition is not satisfied the point $p$ lies outside the cone.


text:
Q: If statements - msgbox I'm now trying to write an IF statement to say something to the effect of: If file is more than 5 days old, do not run macro. If more than 5 days old, run macro.
I would like to this to be a yes or no dialogue box. Here is my code. Please help. I'm still trying to learn this vba code.
Sub LastModifiedFile()

'Function FileLastModified(strFullFileName As String)
    Dim fs As Object, f As Object, s As String, dtmodpath As String

    dtmodpath = "\\jdshare\pdcmaterials\5_Tools\FTP\Cancelled_Report.txt"
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(dtmodpath)

    's = UCase(strFullFileName) & vbCrLf
    s = f.DateLastModified
    FileLastModified = s

    Set fs = Nothing: Set f = Nothing

Range("E5").Value = FileLastModified

'If FileExists(strFullName) Then
    'MsgBox FileLastModified(strFullName)
    'Else
        'MsgBox "File Older than 5 Years : " & vbNewLine & strFullName
    'End If

'End Function

End Sub

A: Congrats for using correctly the .DateLastModified property!
Instead of the MsgBox-es call a function. The DateAdd() returns date, which is 5 days before the current date, thus it is easy to compare. This shows a MsgBox() which informs whether the file has more or less than 5 days from the last modification:
Option Explicit

Sub LastModifiedFile()

    Dim fileObject As Object
    Dim file As Object
    Dim modPath As String

    modPath = "\\jdshare\pdcmaterials\5_Tools\FTP\Cancelled_Report.txt"
    Set fileObject = CreateObject("Scripting.FileSystemObject")
    Set file = fileObject.GetFile(modPath)

    If DateAdd("d", -5, Now) < file.DateLastModified Then
        MsgBox "Less than 5 days."
    Else
        MsgBox "More than 5 days."
    End If

End Sub

If you want to put a MsgBox in the whole story with Yes and No, then this should be ok:
Sub LastModifiedFile()

    Dim fileObject As Object
    Dim file As Object
    Dim modPath As String

    modPath = "\\jdshare\pdcmaterials\5_Tools\FTP\Cancelled_Report.txt"
    Set fileObject = CreateObject("Scripting.FileSystemObject")
    Set file = fileObject.GetFile(modPath)

    Dim msgBoxStatement As String

    If DateAdd("d", -5, Now) < file.DateLastModified Then
        msgBoxStatement = "This file is NOT older than 5 days!" & vbCrLf & _
            "Should it be deleted?"
    Else
        msgBoxStatement = "This file is older than 5 days!" & vbCrLf & _
            "Should it be deleted?"
    End If

    Select Case MsgBox(msgBoxStatement, vbYesNo Or vbQuestion, "Delete?")
        Case vbYes
            'run the for deletion
        Case vbNo
            'do not run the code for deletion
    End Select

End Sub

A: Use DateDiff function to compute your number of days.
Its not totally clear what you want to do with your Yes/No message box, here's an attempt :
Sub LastModifiedFile()

    Dim fs As Object, f As Object, s As String, dtmodpath As String
    Dim dtLastMod As Date
    Dim intDays As Long

    dtmodpath = "\\jdshare\pdcmaterials\5_Tools\FTP\Cancelled_Report.txt"

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(dtmodpath)
    dtLastMod = f.DateLastModified

    ' Here you compute the number of days between the file last mod date, and the current date
    intDays = DateDiff("d", dtLastMod, Now)

    Set fs = Nothing: Set f = Nothing
    Range("E5").Value = dtLastMod

    If intDays > 5 Then

        If MsgBox("File is " & intDays & " days old, proceed with macro ?", vbYesNo, "Continue?") = vbYes Then
            ' RUN MACRO GOES HERE
        End If
    Else
        MsgBox "File is " & intDays & " days old, cancelling"
    End If

End Sub


text:
Q: How can fill a variable of my own created data type within Oracle PL/SQL? In Oracle I've created a data type:
TABLE of VARCHAR2(200)

I want to have a variable of this type within a Stored Procedure (defined locally, not as an actual table in the DB) and fill it with data.
Some online samples show how I'd use my type if it was filled and passed as a parameter to the stored procedure:
SELECT column_value currVal FROM table(pMyPassedParameter)

However what I want is to fill it during the PL/SQL code itself, with INSERT statements.
Anyone knows the syntax of this?
EDIT: I should have clarified: my source data is entered as a VARCHAR2 parameter passed to the stored procedure: a separator (like comma) delimited string. I'm already iterating through the delimited string to get every separate value - I would like to INSERT each one into my type so I can treat it as a TABLE for the rest of the logic.

A:
"I want is to fill it during the PL/SQL
  code itself, with INSERT statements"

It's like populating any other PL/SQL variable: we have to use INTO.  Only because we're populating multiple rows we need to use the BULK COLLECT syntax.
declare
    l_array your_nested_table_type;
begin
    select col1
    bulk collect into l_array
    from t72;
end;
/

If the result set returns a lot of records it is a good idea to use the LIMIT clause inside a loop.  This is because PL/SQL collections - just like every other PL/SQL variable - are held in session memory.  So we don't want the array to get too big, otherwise it might blow the PGA.  Find out more.
edit

"I edited the question to clarify
  specifically what I want"

sigh  Tokenizing a string is an altogether different issue.  I have previously posted solutions in two SO threads.  If you're using 9i or earlier use this approach.  Otherwise use this regex solution (actually this splits the string into numeric tokens, but it is easy enough to convert to characters).
edit 2

"I only want to be able to use the
  type "internally" (within the Stored
  Procedure) by adding values to it. Is
  this something I can do with the first
  link?"

Sure.  Why not?
SQL> declare
  2      local_array tok_tbl;
  3  begin
  4      local_array := parser.my_parse('Keith Pellig,Peter Wakeman,Ted Bentley,Eleanor Stevens');
  5      local_array.extend();
  6      local_array(5) := 'Reese Verrick';
  7      for i in local_array.first()..local_array.last()
  8      loop
  9          dbms_output.put_line(local_array(i));
 10      end loop;
 11  end;
 12  /
Keith Pellig
Peter Wakeman
Ted Bentley
Eleanor Stevens
Reese Verrick

PL/SQL procedure successfully completed.

SQL>

Here I have re-used my SQL type, but it would work just as well if TOK_TBL were declared in the PL/SQL package instead.

A: you don't mention if the type you created is a SQL type or a PL/SQL type. They are used similarly in Pl/SQL so I will assume you created a SQL type with a command like this:
SQL> CREATE TYPE tab_varchar IS TABLE of VARCHAR2(200);
  2  /

Type created

This is a nested-table. Find out how to manipulate collections in PL/SQL it in the documentation, for example:
SQL> DECLARE
  2     lt tab_varchar;
  3  BEGIN
  4     /* initialization */
  5     lt := tab_varchar('a', 'b', 'c');
  6     /* adding elements */
  7     lt.extend(1);
  8     lt(4) := 'd';
  9     FOR i IN lt.FIRST .. lt.LAST LOOP
 10        dbms_output.put_line('lt(' || i || ')=' || lt(i));
 11     END LOOP;
 12  END;
 13  /

lt(1)=a
lt(2)=b
lt(3)=c
lt(4)=d


text:
Q: Proxy settings in RStudio for third party API access I'm using RStudio on a server that is behind my company's firewall. I referred to the link here and did the same changes in my RProfile script:
RProfile
http_proxy=http://proxy.dom.com:80
http_proxy_user=user:passwd

I'm trying to access an API (Omniture a.k.a. api.omniture.com) using the package RSiteCatalyst and even though I mentioned the proxy, I'm unable to bypass the firewall. Below is what I do:
library(RSiteCatalyst)
SCAuth('username','shared-secret') # Authentication

And the error that I get
Error in function (type, msg, asError = TRUE)  :
Could not resolve host: api.omniture.com

Before going to IT I came here for the StackOverflow gods to help out. Would greatly appreciate it. Thanks.

A: I think that article has a typo. Can you put the http_proxy lines in your .Renviron rather than your .Rprofile, then restart RStudio? (If that does the job, we'll update the article!)


text:
Q: Activity por defecto en Android Studio problema Hola como están tengo una consulta:
Lo que sucede es que tengo mi aplicación hecha en Android Studio y tengo tres actividades el Login el menu y el submenu.
Cuando estoy deslogeado y cierro mi aplicación aparece de nuevo en el login para iniciar sesión y eso esta correcto.
El problema esta en que cuando le dejo logueada a la aplicación  y la cierro totalmente, esta en vez de iniciar en el menú principal que quisiera que se abra, siempre se abre en la actividad del sub menú.
Y mi objetivo es lograr que cuando  el usuario logueado así se cierre la aplicación siempre aparezca el menú principal
la pregunta seria hay alguna forma de poner a este menu principal como por defecto cada vez que abro mi aplicación?
Loging esta hecho con Firebase
Esta actividad del sub menu cree primero antes que la del menu principal
creo que puede ser que este sub menu este por defecto y no se si puedo cambiarla.
Por favor si alguien me puede ayudar con alguna idea.

A: yo diria que pongas el siguiente codigo en la funcion onCreate de tu login.
En Kotlin.
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    var mAuth = FirebaseAuth.getInstance().currentUser

    if(mAuth!=null){
        intent = Intent(this, EjemploActivity::class.java)
        startActivity(intent)
    }
}

En Java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    FirebaseUser mAuth = FirebaseAuth.getInstance().getCurrentUser();
    if(mAuth!=null){
        startActivity(new Intent(getApplicationContext(),EjemploActivity.class));
    }
}

A: Lo que tenes que usar es un AuthStateListener , esto se va a encargar de escuchar si el mAuth.getCurrentUser() es distinto de null. Si lo es, podemos enviar al usuario a otra pantalla , ya que no nos haria falta volverlo a loguear.
Primero creamos el authListener
private FirebaseAuth.AuthStateListener mAuthListener;

Dentro del onCreate() declara este listener, esto lo hacemos con la intencion de que cada vez que el usuario pase por Login.class el listener se dispare y escuche por cambios en el auth, si el usuario esta ya logueado lo dirigimos a la pantalla del submenu
mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    startActivity(new Intent(Login.this,SubMenu.class);
                }
            }
        };

Luego en el Override del onStart() vamos a atachar este listener para que escuche por cambios a nuestro mAuth.
@Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

Por ultimo onAuthStateChanged  se va a lanzar cada vez que

*

*Despues de que el Listener fue añadido.

*Cuando el usuario esta logueado.

*Cuando el usuario se desloguea.

*Cuando el usuario actual cambia.

Esto esta marcado en esta documentacion.


text:
Q: filter flowable list of object by category and group into another list of object in flow is it possible to filter and group Flow<List<Object A>>  by categories.
i found issue quite similar here , but no luck :(
here i'm sharing my approach which i tried,
code inside viewModel :
class HomeViewModel: ViewModel() {

 data class Car(val id: Int, val name: String, val category: Int)
 data class CarsByCategory(val categoryId:Int, val categoryName: String, val carList: List<Car>)

    private val categoryList =
        mapOf<Int, String>(1 to "Audi", 2 to "BMW", 3 to "Chevrolet", 4 to "Dodge", 5 to "Others")

    private val mutableCarList: MutableList<CarsByCategory> = mutableListOf()
    private val _mutableStateFlowCarList: MutableStateFlow<List<CarsByCategory>> = MutableStateFlow(emptyList())

    val filteredCarList: StateFlow<List<CarsByCategory>> = _mutableStateFlowCarList

    private fun getAllCarsAsFlow(): Flow<List<Car>> {
        val cars = listOf(
            Car(id = 1, name = "A1", category = 1),
            Car(id = 1, name = "A2", category = 1),
            Car(id = 1, name = "BMW X1", category = 2),
            Car(id = 1, name = "BMW X7", category = 2),
            Car(id = 1, name = "M Roadster", category = 2),
            Car(id = 1, name = "Bolt EUV", category = 3),
            Car(id = 1, name = "Blazer", category = 3),
            Car(id = 1, name = "Challenger", category = 4),
            Car(id = 1, name = "Neon", category = 4),
            Car(id = 1, name = "Frontier", category = 5)
        )
        return flowOf(cars)
    }

   private fun filterCarByCategory(){
        getAllCarsAsFlow().map { carList ->
            for (key in categoryList.keys) {
                val filteredList = carList.filter { car -> car.category == key }
                mutableCarList.add(
                    CarsByCategory(
                        categoryId = key,
                         categoryName= categories.getValue(key),
                        carList = filteredList
                    )
                )
            }
            _mutableStateFlowCarList.value = mutableCarList.toList()
        }
    }

    init {
        filterCarByCategory()
    }
}

code in  fragment:
  ....

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        lifecycleScope.launchWhenStarted {
            homeViewModel.filteredCarList.collect {
                Log.d(TAG, "onViewCreated: ${it.size}")
//                here getting car list size is 0
            }
        }
    }

  ...

i don't know is it right approach or not , please let me know how to solve this problem using flow

A: A flow doesn't emit any value until it is collected. So you need to collect your flow:
private fun filterCarByCategory(){
    viewModelScope.launch {
        getAllCarsAsFlow().collect { carList ->
            // Rest everything same
        }
    }
}

Edit: If the sole purpose of _mutableStateFlowCarList is to provide data to UI, you need not use a StateFlow here, just a normal Flow would do the job.
val filteredCarList = getAllCarsAsFlow().map { carList ->
    categoryList.map { (id, name) ->
        CarsByCategory (
            categoryId = id,
            categoryName = name,
            carList = carList.filter { car -> car.category == id }
        )
    }
}


text:
Q: How to make high score based on collected coins? I'm creating small 2d platformer on Unity. The core is that you have 30 sec to spend on a level + plus an enemy chasing you. You have to act fast and aggressive to get those coins. So, actually how to make the score go up after I touch a coin? And how to make it disappear after that? I thought I could make a trigger, but I want the coin to be driven by physics, because it looks cool when it falls from midair on the ground.

A: insert this sample on your coins and add Coillder + trigger it
private void OnTriggerEnter(Collider other)
{
     if(other.gameObject.tag == "yourplayertag"){
           PlayerPrefs.SetInt("yourCoin", PlayerPrefs.GetInt("yourCoin") + 1); // if your coins stored in playerprefs

           Destroy(gameObject);
     }
}

and advice, you need to learn more about unity and this is not here on Stack, your question is very basic, do some research first and try many times, tutorials and unity manual will help


text:
Q: How to get return value in php class function In my test. I have defined a class which has getLastTradeTime function
Here is class code:
<?php
namespace model;

//class Trade {//works fine
class Trade Extends \Mysql\Crud {// works fail
protected $table = 'ms_trade';
protected $pk    = 'id';
private $hh;// hh is not related to class /Crud

 public function getLastTradeTime($uid, $ip) {
    $this->hh="stringtest";
    return $this->hh;
}
}

Now I want to call this class function, I should get "stringtest" return.
But It is unlucky, there is nothing i have got.
Here is html code:
<body style="height:100%" >

<?php
include "o1ws1v/class/model/Trade.php";
$trade_model = new \model\Trade();

$lastTrade_time = $trade_model->getLastTradeTime("654651","127.0.0.1");
echo $lastTrade_time;
?>
</body>

I mean it is simply class, and normal way to call function. It seems nothing wrong
Who can give me a favor

A: i am not having namespace model so i removed it.
It seems that something wrong with your path. ("o1ws1v/class/model/Trade.php")
Kindly double check it.
below code is working using below files.
1.Trade.php
<?php
class Trade {
    protected $table = 'ms_trade';
    protected $pk    = 'id';

    public function getLastTradeTime($uid, $ip) {
        $hh="stringtest";
        return $hh;
    }
}
?>

2.child.php
<?php
include "Trade.php";
$trade_model = new Trade();
$lastTrade_time = $trade_model->getLastTradeTime("654651","127.0.0.1");
//can also called as below.
//$lastTrade_time = $trade_model::getLastTradeTime("654651","127.0.0.1");
echo $lastTrade_time;
?>

call child file in your server.
if you having any query, feel free to ask.


text:
Q: BCNF decomposition that results in different decompositions (both faithful or faithless)? This is a question 19.10 (4) in the textbook Database management systems by Raghu Ramakrishnan, Johannes Gehrke (in case anyone's curious - answer not included of course, which is why I needed to ask)
And I noticed that there are two ways to make the BCNF decomposition:
We're given R = ABCD
and the functional Dependencies: A -> B, B -> C, C -> D
Key: A
We can decompose it to BCNF by either using B -> C or C -> D at the start
If decompose along B -> C at the start, get R1 = AB , R2 = BC , R3 = BD (this is not faithful)
If decompose along C ->D at the start, get R1 = AB, R2 = BC , R3 = CD  (this is faithful)
I'm quite new to the doing BCNF decomposition, is this correct? So it's possible to have multiple different BCNF decompositions depending on your chosen starting FD?
Thanks in advance :)


text:
Q: How to show icons on row hover in angular using syncfusion tables How to show icons on row hover in syncfusion tables.
Please see the below provided screenshot(captured from gmail)
I am working with angular7.x and Syncfusion UI Components.
Please let me know if any answers available
Thanks in advance

A: You can simply append your own component with the last child of the Grid row while hovering it. Code snippet,
export class AppComponent {
public data: Object[];
public initialPage: Object;
public button: HTMLElement;

@ViewChild('grid')
public gridInstance : GridComponent ;

ngOnInit(): void {
    this.data = data;
    this.initialPage = { pageSizes: true, pageCount: 4 };
    let btn = document.createElement("input");
    btn.type = "button";
    btn.id = "btn";
    btn.classList.add("e-btn");
    btn.value = "button";
    btn.style.marginLeft = "10px";
    btn.onclick = function(e) {
      console.log("Button clicked");
    };
    this.button = btn;
}

load(args) {
  this.gridInstance.element.addEventListener("mouseover", function(e){
    if((e.target as HTMLElement).classList.contains("e-rowcell")) {
        let ele: Element = e.target as Element;
        let row = parentsUntil(ele, "e-row");

        let previousButton = document.getElementById("btn");
        if(!isNullOrUndefined(previousButton)) {
          previousButton.remove();
        }

        row.lastChild.appendChild(this.button);
    }
  }.bind(this))
}

}
sample for your reference: https://stackblitz.com/edit/angular-hjfcyi?file=main.ts
In here I have created one new button in ngOnInit and appended that button in each row last child while hovering it.
Note: I have used Grid load event to bind the mouseover event to Grid.


text:
Q: php - APC memory caching for a large array variable (22MB) I have a large 2D array that I serialized to be stored in a file.  The serialized file is about 9.5MB and takes about .05 seconds to read from disk.  To access the array, the unserialize process takes about 1.3 seconds, which is too long.
What I want to do is to unserialize the array first and then store that array as an APC cache variable.  I am running into a problem of having a server time out/not found error when I use apc_store or apc_add.   If I comment out the apc_store code, then it would be fine but then the array is not cached.  I have no problem with caching smaller test files/array of around 1MB.  From my php code below, I found that the memory size of the array in question is about 22MB.
These are my apc settings in the php.ini
apc.shm_segments = 1
apc.shm_size = 512M
apc.ttl = 7200
apc.user_ttl = 7200
apc.num_files_hint = 1024
apc.enable_cli = 1
apc.max_file_size = 512M
apc.stat=1

I am testing my code on a local machine setup using xampp. Could anyone suggest how I can fix/get around this problem of server timing out?
Here is just my cache testing routine:
$startunser = microtime(true);

if ($quote = apc_fetch('serialfile')) {

        echo "
 serfile [cached] ";
}
else {

    $start_memory = memory_get_usage();
    $sF = "seri.txt";
    $sxx = file_get_contents($sF);
    $pro = unserialize($sxx);
    apc_store('serfile', $pro, 10);

    echo "
serfile is NOT cached ";
    echo memory_get_usage() - $start_memory;
}

$elapsedunser = microtime(true) - $startunser;
echo "
The unserialize process took $elapsedunser seconds";

return;

Also as an interesting side note for anyone's curiosity, when I recall (using apc_fetch) an array from APC that was unserialized from a serialized file of approximately 1MB, the fetch process actually was longer than just reading the file from disk and unserialize the file (.5 vs .4 seconds).  I did not believe that at first either.
TIA

A: APC isn't really suitable for storing data that large. Have you tried serialising the data as PHP code (using var_dump, for example), and writing it out as a .php file to be included in?  That might still be too large to handle though.


text:
Q: getWindowHandle() Selenium Webdriver Javascript Made some changes based on help from engineering. Here is the final code I used for grabbing the new window handle:
localdriver = @driver
@driver.getAllWindowHandles()
.then (handles) ->
    localdriver.switchTo().window(handles[1])

I'm currently running an automation stack that uses Selenium Webdriver, Mocha, Chai, and Grunt. I'm creating scripts in Coffeescript, but an answer to my question in Javascript would be perfectly fine.
What I'm trying to do:

*

*Click button on main browser window

*Switch driver to the second window that opens after button click

*Perform actions in the second window

*Close second window and return to the first.

I've scoured the internet looking for an answer on how to do this. Just started learning all this stuff a few months ago, and I'm still stumbling through creating stuff. I'm seeing a lot of Java and C+ examples, but not much on the Javascript side. Can anyone provide an example of how to set up the code for the above scenario using Selenium Webdriver and Javascript?

A: What you want is driver.getAllWindowHandles(), but because this returns a promise, make sure that you then use the handles inside of the then function
// select the newly opened window
driver.getAllWindowHandles().then(function gotWindowHandles(allhandles) {
    driver.switchTo().window(allhandles[allhandles.length - 1]);
});

A: var parent = driver.getWindowHandle();
var windows = driver.getAllWindowHandles();

driver.switchTo().window(windows[1]);

// do some stuff

driver.close();
driver.switchTo().window(parent);

A: Whenever new tab opens, it takes some time to come up and render. In this situation, it is difficult to switch the tab because the tab is not opened yet and driver.getAllWindowHandles() will not give handler for that tab. I solved this problem in this way, I am assuming I have one opened tab and on some button click, I am opening new 2nd tab.
function openNewTab(driver) {
  driver.wait(function () {
    return driver.getAllWindowHandles().then(function (handles) {
      var isHandleCount2 = (handles.length == 2);
      if (isHandleCount2) {
        driver.switchTo().window(handles[1]);
      }
      return isHandleCount2;
    });
  }).then(function () {
  // Now do some stuff in new tab
    var buttonElement = driver.wait(until.elementLocated(By.xpath("//td[*//span[text()='Click me']]")));
    buttonElement.click();
  });
}

This code will wait until the number of handles or tabs will not equal to 2.

A: @Jai Prak's answer is brilliant.What about the case of three tabs or more? The newest tab will always be the last Tab.
return await driver.wait(async function () {
    return await driver.getAllWindowHandles().then(async function (handles) {
       // var isHandleCount2 = (handles.length == 2);
        if (handles.length > 1) {
            return driver.switchTo().window(handles[handles.length - 1]);
        }
        return false;
    });
}).then(function () {
    // Now do some stuff in new tab

});

The above will apply except in cases you switch between Tabs.To move the next tab, get the current Tab's index -1


text:
Q: Example of RestSharp ASYNC client.ExecuteAsync () works Could someone please help me modify the code below:
client.ExecuteAsync(request, response => {
    Console.WriteLine(response.Content);
});

Basically I want to use ExecuteAsync method above but don't want to print but return response.Content to the caller.
Is there any easy way to achieve this?
I tried this but doesnt' work:
public T Execute<T>(RestRequest request) where T : new()
{
    var client = new RestClient();
    client.BaseUrl = BaseUrl;
    client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
    request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment); // used on every request
    var response = client.ExecuteAsync(request, response => {
        return response.data);
    });
}

The above code is from
https://github.com/restsharp/RestSharp

A: With the help of @spender, this is what i got:
You can add new file in RestSharp project, and add this code:
public partial class RestClient
{
    public Task<IRestResponse<T>> ExecuteAsync<T>(IRestRequest request)
    {
        var tcs=new TaskCompletionSource<IRestResponse<T>>();

        this.ExecuteAsync(request, response =>
            {
                tcs.SetResult(
                    Deserialize<T>(request, response)
                );
            });

    return tcs.Task;
    }
}

This will practically return the full response, with status code and everything, so you can check if the status of the response is OK before getting the content, and you can get the content with:
response.Content

A: There's the thing... you can't return an asynchronously delivered value, because your calling method will already have returned. Blocking the caller until you have a result defeats the point of using ExecuteAsync. In this case, I'd return a Task<string> (assuming response.Content is a string):
Task<string> GetResponseContentAsync(...)
{
  var tcs=new TaskCompletionSource<string>();
  client.ExecuteAsync(request, response => {
    tcs.SetResult(response.Content);
  });
  return tcs.Task;
}

Now, when the task completes, you have a value. As we move to c#5 async/await, you should get used to stating asynchrony in terms of Task<T> as it's pretty core.
http://msdn.microsoft.com/en-us/library/dd537609.aspx
http://msdn.microsoft.com/en-us/library/hh191443.aspx

A: From reading the code it looks like you want to use ExecuteAsGet or ExecuteAsPost instead of the async implementation.
Or maybe just Execute- not sure exactly what type Client is.

A: At some point, there was a bunch of overloads introduced that support System.Threading.Tasks.Task and had the word "Task" in them. They  can be awaited (like HttpClient's methods).
For instance:

*

*ExecuteTaskAsync(request) (returns Task<IRestResponse>)

*ExecuteGetTaskAsync(request) (returns Task<IRestResponse>)

*ExecuteGetTaskAsync<T>(request) (returns Task<IRestResponse<T>>)

Those then became deprecated in later v106 versions in favour of Task-support being the default I believe, e.g. the first one became client.ExecuteAsync(request).
So these days you can just do:
var response = await client.ExecuteAsync(request);
return response.Content;


text:
Q: How to interface ethernet with STM32 Microcontroller? The project uses an ethernet loop which is connected through the STM32 Microcontroller. I have to use ethernet switch IC(4 port). What are the topics that I have to know so that I can use the ethernet in the project? Also how to interface the ethernet switch IC, transceiver with the MCU? How to read and transfer data (integer data) through the ethernet.

A: It does not matter what you want to send over ethernet and how many ports your switch has. You need to know what protocol your other devices use. At the moment you most of them use TCP/IP and you need to implement it in your app. CubeMX has support for LWIP stack.
You can also use external chips with built in TCP/IP stack like Wiznet W5100, 55000 or other chips.

How to read and transfer data (integer data) through the ethernet.

You will need to read about TCP, UDP, ports, sockets etc. It a too wide topic to be answered in the forum post


text:
Q: Is "Black" correct, incorrect, or could it be used as either "Black" or "black"? I was reading an article that I was assigned by my professor, and I came across the following:

"We're the ones getting killed," Los Angeles Clippers coach Doc Rivers, who is Black, said in an emotional postgame speech Tuesday
night.

Is the usage of the capital B in "black" correct, is it incorrect, or does it fall into a completely different category altogether? Also, is it racist to say "black" with a capital B, but not for example, 'the white man' not using a capital W as I have seen in the past? And this is not a typo because it also turned up earlier in the article:

Taylor, a 26-year-old Black woman, was fatally shot when police officers burst into her Louisville, Kentucky apartment using a no-
knock warrant during a narcotics investigation on March 13.

Here is a link to the article: Article about BLM and sports

A: Since you are quoting from what appears to be a U.S. newspaper article, its decision to capitalize black as Black when the word is used as a racial term probably reflects Associated Press style. That style has changed within the past six months, as explained in John Daniszewski, "The decision to capitalize Black" (June 19, 2020):

AP's style is now to capitalize Black in a racial, ethnic or cultural sense, conveying an essential and shared sense of history, identity and community among people who identify as Black, including those in the African diaspora and within Africa. The lowercase black is a color, not a person.
We also now capitalize Indigenous in reference to original inhabitants of a place.
These changes align with long-standing capitalization of other racial and ethnic identifiers such as Latino, Asian American and Native American. Our discussions on style and language consider many points, including the need to be inclusive and respectful in our storytelling and the evolution of language. We believe this change serves those ends.

I believe that the designation white as a racial term remains lowercase under current AP style preferences. This split in treatment may or may not persist over the long term—but it is by no means unheard of for style guides and dictionaries to treat similarly situated terms dissimilarly. Thus, for example, The American Heritage Dictionary of the English Language, fifth edition (2010), endorses policymaker (one word) but decision maker (two words).
In any event, the decisive authority of The Associated Press Stylebook ends in the editorial rooms of newspapers that are committed to enforcing its preferences. Writers and editors operating outside the authority of AP style can instead follow the dictates of some other style manual or even make their own decision regarding the initial-capping or lowercasing of either or both of these terms.

A: Historically, names of racial/ethnic groups, such as "Africans" or "Caucasians", must be capitalized, while categories referring to a particular feature (such as "blacks" or "whites", referring to the skin color) are not. However, people referred to in the article are by no means "Africans" (they probably have been living in the US their whole life), so it makes sense to promote "Black" to a name of a racial group describing such people, and therefore capitalize it.
It is still possible to use "black" and "white" as categories referring to the skin color, e.g. "the white man" or "the black people", which are not capitalized.


text:
Q: What does the star mean in the `PackageReference` in C#? What does the star mean in the PackageReference in C#?
E.g. here:
<PackageReference Include="MyApp.Misc.Utils" Version="3.0.*" />

Does it mean that as soon as there is an upgrade in the least significant version of the MyApp.Misc.Utils, that update will reach the project which references the MyApp.Misc.Utils?
I.e. if the current used version of the MyApp.Misc.Utils is 3.0.5 and I release a new version of the MyApp.Misc.Utils to the registry and that version number is 3.0.6, then the MyApp.Misc.Utils dependency will be automatically updated to the 3.0.6. Is it correct?


text:
Q: Baysian probability of false positive COVID-19 test I am wondering what the probability of a false positive COVID-19 test would be in my city. I'm attempting to use Bayes Theorem to calculate this, however I'm getting very different results based on how I formulate the problem.
Here are the probabilities given:

*

*1 in 41 people in my city have COVID.

*The analytical false positive rate of a PCR test is 2 in 1,000

*The proportion of positive tests is 6.8%.

If I ask the probability of not being infected given a positive test, I get 2.9%.
P(Not Infected given Positive test) = P(Positive test given Not Infected) * P(Not Infected) / P(Positive test)
= (.002) * (.976) / (.068)
= 2.9%
However if I ask the probability of being infected given a positive test, I get 36%.
P(Infected given Positive test) =
P(Positive test given Infected) * P(Infected) / P(Positive test)
=(.998) * (.024) / (.068)
=36%
Can you set me straight here? I must be making an error. Given a positive test, I would expect the probabilities of being infected or not infected to sum to 1.
A note on the probabilities given:

*

*1 in 41 people infected is based on a model but should be interpreted as the ratio of infected people in the population as a whole, not necessarily the population being tested. I believe it's fair to use this as the pre-test odds of a person being infected if we know nothing else about them.

*PCR tests are generally described as very specific (i.e., very low false positive rate). Lets assume that of 1000 known covid-free samples, only 2 would return a positive result.

*6.8% test positivity rate is based on the number of tests that come back positive. Note that we are not testing the entire population, and you can assume that the population that receives a test is more likely to have covid than the population at large.

A: NOTE this answer precedes the OP's note about percentages. This answer assumed:

*

*1/41 is the prior probability of infection in the tested population (not the population as a whole)

*2/1000 is the false negative rate of the PCR test $P(PCR^{-}|Infected)$

I may be confused myself as my calculations do give probabilities summing to 1.

The analytical false positive rate of a PCR test is 2 in 1,000

I assumed you mean false negative rate, right? Otherwise how can you have 2.4% true positives (1/41), 6.8% positive tests but only 0.2% false positives?
Here's my reasoning. First let's set up a simple tree with 100k people (there is some rounding here):
                      100000 people
                           |
                 --------------------
                 |                  |
              Infected          Not infected
              P = 1/41           P = 40/41
               2439                97561
                 |                   |
         -------------          ------------
         |           |          |          |
       PCR+        PCR-        PCR+       PCR-
     P = 0.998   P = 0.002   P = 0.044   P = 0.956
       2434          5         4366       93195

Here P = 0.044 is the false positive rate and comes from 0.068 - (0.998 * 1/41).
And here's the probabilities:
$$
P(inf^{-}|PCR^{+}) = \frac{P(inf^{-}) \cdot P(PCR^{+}|inf^{-})}{P(inf^{-}) \cdot P(PCR^{+}|inf^{-}) + P(inf^{+}) \cdot P(PCR^{+}|inf^{+})} \\
= \frac{(40/41) \cdot 0.044}{(40/41) \cdot 0.044 + (1/41) \cdot 0.998} = 0.638
$$
and
$$
P(inf^{+}|PCR^{+}) = \frac{P(inf^{+}) \cdot P(PCR^{+}|inf^{+})}{P(inf^{-}) \cdot P(PCR^{+}|inf^{-}) + P(inf^{+}) \cdot P(PCR^{+}|inf^{+})} \\
= \frac{(1/41) \cdot 0.998}{(40/41) \cdot 0.044 + (1/41) \cdot 0.998} = 0.362
$$
If I'm correct, your mistake is in using 0.068 as denominator in the Bayes formulas.

A: Your first half of the reasoning seems correct.
$$\begin{array}{}P(\text{not infected | positive}) &=& \frac{P(\text{positive | not infected})\cdot P(\text{not infected})}{P(\text{positive})} \\ &=& \frac{0.002 \cdot 0.976}{0.068} \\ &=& 0.0287
\end{array}$$

However we get strange values when we try to deduce $P(\text{positive | infected})$ from
$$\begin{array}{rcl}P(\text{infected | positive}) &=& \frac{P(\text{positive | infected})\cdot P(\text{ infected})}{P(\text{positive})} \\ 0.9713&=& \frac{? \cdot 0.024}{0.068}
\end{array}$$
or alternatively from
$$\begin{array}{rcl}
P(\text{pos}) &=& P(\text{pos | $\neg$ inf})\cdot P(\text{$\neg$ inf}) + P(\text{pos |  inf})\cdot P(\text{ inf})\\
0.068 &=& 0.002 \frac{40}{41} + P(\text{pos |  inf}) \frac{1}{41}
\end{array}$$
or
$$P(\text{pos |  inf}) = 0.068 \cdot 41 - 0.002\cdot 40 = 2.708$$
Which is not possible. Intuitively we can see this more directly... If only 1 in 41 people are sick (2.43 %)then it is strange to find that 6.8% of the tests are positive. The percentage of positive tests is much higher than the people that are sick.
This can be explained in two ways:

*

*The false positive rate is not correct (it should be much higher and somewhere close to this 6.8%).
However, if this is a realistic example about Covid-19 testing then the false positive rate is probably not so high (unless something went very wrong).

*Among the people that are performing tests there are a higher
proportion of sick people (higher than 1 in 41).
If you would know that $P(\text{pos |  $\neg$ inf}) = 0.002$ and $P(\text{pos |  inf}) = 0.998$ then you could deduce the prior $P(\text{$\neg$ inf})$ and $P(\text{inf})$ from
$$\begin{array}{rccccccc}
\underbrace{P(\text{pos})}_{0.068} &=& \underbrace{P(\text{pos | $\neg$ inf})}_{0.002}\cdot P(\text{$\neg$ inf}) + \underbrace{P(\text{pos |  inf})}_{0.998}\cdot \underbrace{P(\text{ inf})}_{1-P(\text{$\neg$ inf})}\\
\end{array}$$
which leads to
$$P(\text{$\neg$ inf}) = \frac{0.998-0.068}{0.996} \approx 0.934$$
and
$$P(\text{$\neg$ inf| pos}) = \frac{0.002 \cdot \frac{0.998-0.068}{0.996}}{0.068} \approx 0.0275 $$


text:
Q: Gradient overlay doesn't end nicely in the background color I'm using compass to overlay a gradient on an image. But the problem is that I want my gradient to end stronger so that the image just fades into the current background color.
This is my scss:
.hero {
    width: 100%;
    height: 500px;
    background: url('../images/MacBookAir.jpg') center center no-repeat;
    @include background-size(cover);

    &:before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background-image: linear-gradient(rgba(255,255,255,0.2), rgba(255,255,255,1));
    }
}

html is simply:

It's hard to see since the background is white here also but I'm guessing since I'm ending my gradient in 100% white it should just fade into the background?
Can somebody help me with this or maybe provide a better(cleaner) solution in compass to get this done?

A: Alright, so what I did, is actually give a height to your &:before so that it knows how tall it should go, while this might not be the most responsive choice, it works.
So your Sass would look like this:
.hero {
    width: 100%;
    height: 500px;
    background: url('http://placesheen.com/1200/500') center center no-repeat;
    background-size:cover;

&:before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    height: 508px;
    background-image: linear-gradient(rgba(255,255,255,0.2), rgba(255,255,255,1));
    }
}

The before wasn't reaching the full height, so it needs to extend 8 more pixels, thus 508px. You could probably play with percentages as well to achieve the same effect.
I created a little tid bit on Sass Meister for you to take a look at, I wrapped it in a container just so it was easier to view in the Sass Meister tool...
http://sassmeister.com/gist/3528cb23d3e831231949

A: Why not just take the image into photoshop and fade it out to a solid color? Seems to me like you're adding in code that doesn't need to be there. But if that isn't an option, and you must use a CSS gradient, you can always apply multiple gradients by separating the gradients with commas to darken it further since it already ends in 100%.


text:
Q: Create a function in Python that takes in n, a, b and returns the number of positive values raised to the nth power that lie in the range [a, b] power_ranger(2, 49, 65) ➞ 2
2 squares (n^2) lie between 49 and 65, 49 (7^2) and 64 (8^2)
power_ranger(3, 1, 27) ➞ 3
3 cubes (n^3) lie between 1 and 27, 1 (1^3), 8 (2^3) and 27 (3^3)
power_ranger(10, 1, 5) ➞ 1
1 value raised to the 10th power lies between 1 and 5, 1 (1^10)
My code doesn't seem to work properly for n=3. Have no idea why.
def power_ranger(n, a, b):
    count = 0
    for i in range(a, b+1):
        if (i**(1/n))%1 == 0:
            print(i)
            count += 1

    return count

in: power_ranger(2, 49, 100)
out: 49
64
81
100
4
in: power_ranger(3, 1, 72)
out: 1
8
27
3
in: power_ranger(4, 1, 10000)
out: 1
16
81
256
625
1296
2401
4096
6561
10000
10

A: A drastically more efficient solution for your current power_ranger (which is now iterates over all range whatever big size that is) is to find max value which is when raised to the power of n results to high boundary (of the range) and min value which is when raised to the power of n results to low boundary. The difference between those gives the number of values that fall into the needed range:
def power_ranger(n, low, high):
    max_val = int(high ** (1 / n))
    min_val = round(low ** (1 / n))
    return (max_val + 1) - min_val

print(power_ranger(2, 49, 65))
print(power_ranger(2, 49, 100))
print(power_ranger(3, 1, 72))
print(power_ranger(4, 1, 10_000))
print(power_ranger(5, 100, 500_000))

2
4
4
10
11


text:
Q: How to implement Django 'UserCreationForm' to check users from an existing mysql database? I am beginning a Django app using UserCreationForm, the default´s Django app for users. It creates a table in mysql and then you are able to create new users. But what I need is to compare the users with an existing database in MySQL. How can I specify the database in wich the UserCreationForm has to look for the users?
My view for the main with the fields to fill login:
def mainview(request):
    if not request.user.is_anonymous():
        return HttpResponseRedirect('/private')
    if request.method == 'POST':
        formulario = AuthenticationForm(request.POST)
        if formulario.is_valid:
            usuario = request.POST['username']
            clave = request.POST['password']

            acceso = authenticate(username=usuario, password=clave)
            if acceso is not None:
                if acceso.is_active:
                    login(request, acceso)
                    return HttpResponseRedirect('/privado')
                else:
                    return render_to_response('noactivo.html', context_instance=RequestContext(request))
            else:
                return render_to_response('nousuario.html', context_instance=RequestContext(request))
    else:
        formulario = AuthenticationForm()
    return render_to_response('mainview.html',{'formulario':formulario}, context_instance=RequestContext(request))

A: Two ways to do this, create an own User model and make username unique, but the easiest way; inherit UserCreationForm and add a clean_username function.
So something like:
class MyUserCreationForm(UserCreationForm):
    def clean_username(self):
        username = self.cleaned_data["username"]
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError("Username already exists")
        # return is not required Django 1.7 and up, but do it anyway
        return username

==== Update after comment ====
There are two databases, so you need to add the second database within your settings (https://docs.djangoproject.com/en/1.8/ref/settings/#databases).
Lets say you name the second database 'usernames'. Now there again two options. First option is, doing raw SQL with a cursor (https://docs.djangoproject.com/en/1.8/topics/db/sql/#executing-custom-sql-directly).
from django.db import connections
cursor = connections['usernames'].cursor()

Second option is create a Model which has the same design as your current table. Use the above form, but use using on the queryset. So something like this:
if YourModel.objects.using('usernames').filter(username=username).exists():
    raise forms.ValidationError("Username already exists")


text:
Q: Random Forests with modified partitioning criteria Here is the context of my question : I'm doing binary classification with unbalanced classes. The measure of performance I'd like to maximise is a modified F-measure :
$$ F_{\alpha} = \frac{1}{\frac{\alpha}{P}+\frac{1-\alpha}{R}} = \frac{1}{\frac{\alpha}{\frac{TP}{TP+FP}}+\frac{1-\alpha}{\frac{TP}{TP+FN}}}=\frac{TP}{VP+\alpha FP+(1-\alpha)FN}$$
with $\alpha = 0.25$. P=precision ; R=recall ; TP = true positive ; FN = False negative and FP = false positive.
This criteria is not to be discussed. Consider it as given.
So in order to classify my observations I'm using random forests. In this model, in order to partition the space of predictors two common criterias are used : either the accuracy or the gini indice. At a given step we are looking for the potential predictor which once divided minimizes the most the misclassification error rate or the gini indice (or sometimes the cross entropy).
But since my final objective is the $F_{0.25}$ measure, why shouldn't I use it directly as the criteria for partitioning ? That is to say at a given step, looking for the predictor which once divided maximises the $F_{0.25}$.
Then two questions : has someone had that kink of idea ? Is there some already implemented variants of random forests with different criteria of partitioning then the usual ones ? Or is it completely a stupid idea..?
Hope my explanations are clear enough.
Cheers.

A: It is a good observation. If you want to optimize some objective function, using another one as a proxy might not be the best idea. If function $f$ and function $g$ measure kind of the same thing, minimizing $f$ will reduce $g$, but it is not a given that it will minimize it.
In some cases, it is acceptable to use the standard cost functions for growing a tree. If the function you want to minimize is related to the function for growing the tree, it might still be a good idea to use the Gini or Entropy cost function, as they are very fast to compute. This will allow you to grow more trees in the same time, which may lead to a better model once average.
However, if your cost function is measuring something else (or something opposite!) than the Gini or Entropy cost function, your model will not have much meaning in the context you are evaluating it in. In such cases, adapting the cost function might help.
Existing options
After a quick look, I don't think Matlab, Scikit-learn nor R support custom cost functions for single tree growing or Random Forest. However, it is possible to add class weight. By putting more or less weight on the positive class, you might be able to manipulate the precision and recall of the grown tree. If you are already familiar with Random Forest in one of those environments, it might be the easiest thing to try first. It just becomes one additional hyperparameter.
I think that the reason to why tree growing is so limited in term of cost functions comes down to efficiency. The number of split points to be evaluated is huge, and the function needs to be evaluated quickly. But there is an effort going on to be able to minimize arbitrary cost function using simple techniques, known as Gradient Boosting (Wikipedia).
Gradient Boosting allows the optimization of any cost function, and it fits trees sequentially by selecting the tree that best corrects the error of the current model, according to your cost function. One thing you should be careful about, is that you should probably consider the True Positives and other measures with regard to a soft assignment, using the probability that the class is a positive instead of the $0,1$ approach, in order to smooth the function. Boosting seems to be used with good results in the Learning to rank problem (Wikipedia), and I think this may be due in part to the ability to adapt to the cost functions used in this framework. Most environment propose gradient boosting, Scikit-Learn, R, XGBoost.
Another option would be to implement trees and random forests using the F-score as a split criterion, but you might suffer through a lot of technical details needed to get your implementation to par with existing systems.


text:
Q: Trouble filtering on paramteter in Report Builder I am having trouble filtering my table on a parameter and keep getting the error:
"The FilterValue expression for the dataset 'DataSet1' contains a colon or a line terminator.  Colons and line terminators are not valid in expressions."
Filter is...
Expression : Month      Date/Time
Operator : >
Value: =IIF(Parameters!City.Value = "Dallas", 8/1/2018, 10/1/2018)
When I put just a date in the 'Value' box the query works fine. It is when I try to link to parameter I start getting issues.

A: Just wrap a CDate() around it. Also check if your report language is set to a value.
'Expression with a Date/Time Filter
=IIF(Parameters!City.Value = "Dallas", CDate("8/1/2018"), CDate("10/1/2018")


text:
Q: Access table field dynamically in django using for loop def xyz():
site_data=site.objects.all()
site_fields = site._meta.get_fields()
site_fields_name = [f.name for f in site_fields][1:]
return render(request, "Demoapp/InputGssA1.html", {'headers': table_structure,'site_data':site_data,'site_fieldname':site_fields_name})

this is i am render from function inside view.py and want to show in table format in InputGssA1.html,
here table code is like
{% for i in site_data %}

{% for x in site_fieldname %}
    {{i.x}}
{% endfor %}

{% endfor %}
but problem is I can't access object.fieldname using i.x in my code , i.fieldname statically work but this way it not working, How I access object's fieldname this way inside template tag??

A: You don't need such complicated solution. You can simply try with values():
# view
def xyz(request):
    site_fields = site._meta.get_fields()
    site_fields_names = [f.name for f in site_fields][1:]
    site_data=site.objects.values(*site_fields_name)
    return render(request, "Demoapp/InputGssA1.html", {'headers': table_structure,'site_data':site_data})

# template
{% for data in site_data %}
{% for field, value in data.items %}

    {{ value }}

{% endfor %}
{% endfor %}


text:
Q: Get calendars from owncloud with C# UWP app using caldav I have a raspberry pi with windows 10 IOT and remote program it with visual studio in c# from my windows 10 PC. I now want to show the calendars from my online owncloud on a display connected to my raspberry pi. Now I have the problem to read the calendar informations from my owncloud.
The only code I found online is this link: this: https://ovaismehboob.com/2014/03/30/sync-calendar-events-using-caldav/
The problem now is, that I have to use a UWP app, because of my raspberry and this code is not usable in UWP. I have read that I need a System.Net.Http webclient, but I have no idea how to do this.
So please can anybody give me a sample code of how I can read the calendar informations from owncloud by using caldav?


text:
Q: How to create an empty array within a TypeScript function, and add objects to it every time the function is called Using TypeScript and Angular, I am trying to create an empty array within my testConnection function that allows the addition of objects every time the function is called, without clearing the array.
testConnection function:
  testConnection(system) {
    var systemList = [];
    this.service.testConnection(system)
      .subscribe(conn => {
        if (conn == 'Success') {
          this.snackBarHandler.open('Connection Found', 'success');
          system.isClicked = false;
          system.connection = true;
          systemList.push(system);
        }
        else {
          this.snackBarHandler.open('Connection Failed', 'failure');
          system.isClicked = false;
          system.connection = false;
          systemList.push(system);
        }
      }, err => console.log(err));
  }

Currently, with the logic I have, it is adding the system object to the array, but since the empty array declaration is within the function, it is clearing and restarting this process every time the function is called. I have tried to declare the systemList at the top of the class (systemList = any[]), but when I try to reference it within the function, it is showing up as undefined.
How am I able to add system objects to the array any time the function is called, without clearing the existing objects out of the array?

A: You should be able to set a component variable outside of the function, then the list will persist.
export class SystemComponent implements OnInit {

  constructor(private service: TestConnectionService) {}

  systemList = []

  testConnection(system) {
    this.service.testConnection(system)
      .subscribe(conn => {
        this.systemList.push(system);
        if (conn === 'Success') {
          this.snackBarHandler.open('Connection Found', 'success');
          system.isClicked = false;
          system.connection = true;
        }
        else {
          this.snackBarHandler.open('Connection Failed', 'failure');
          system.isClicked = false;
          system.connection = false;
        }
      }, err => console.log(err));
  }
  ngOnInit(): void {}
}

Another option is to create a service and use the service to hold the state of the system list which is more useful if you want multiple components to access the systemList.
interface System {
  some: string
  props: string
}

@Injectable({ providedIn: 'root' })
export class SystemService {
  private _systemList$$ = new BehaviorSubject<System[]>([])

  get systemList(): System[] {
    return this._systemList$$.value
  }

  addToSystemList(system: System) {
    this._systemList$$.next([...this.systemList, system])
  }

  constructor() {}
}

then your testConnection function would use it like this.
testConnection(system) {
  this.service.testConnection(system).subscribe(
    conn => {
      this.systemService.addToSystemList(system)
      if (conn === 'Success') {
        this.snackBarHandler.open('Connection Found', 'success')
        system.isClicked = false
        system.connection = true
      } else {
        this.snackBarHandler.open('Connection Failed', 'failure')
        system.isClicked = false
        system.connection = false
      }
    },
    err => console.log(err)
  )
}


text:
Q: AWS Amplify searchable field by geo distance (location) I'm developing an application that will allow users to search for other users by ordering them by geo location.
According to the information found on the internet, to do this on amplify I have to perform the following steps:

*

*create an elastic search mapping, indicating the type 'geo_point' on the lastPosition attribute (I would like to define it once in the project file and not at each build in the elastic search console)

*create a custom query and a custom vtl resolver and set the sort by lastPosition (of type '_geo_distance') in it.

But I don't understand how to do these 2 steps, so I need some suggestion :(.
// my schema.graphql
   type User
  @model
  @auth(rules: [{allow: owner}, {allow: private, operations: [read]}])
  @searchable {
  // ...other fields
  id: ID!
  lastPosition: Position
  positionUpdatedAt: AWSDateTime
}

type Position {
  lat: Float!
  lon: Float!
}

// my custom searchUsers query in graphql/custom_queries.ts
export const searchUsersNearby = /* GraphQL */ `
  query SearchUsersNearby(
    $filter: SearchableUserFilterInput
    $sort: [SearchableUserSortInput]
    $location: PositionInput // current user position that i need to use in vtl resolver to sort users by distance,
    $limit: Int
    $nextToken: String
    $from: Int
    $aggregates: [SearchableUserAggregationInput]
  ) {
    searchUsersNearby(
      filter: $filter
      sort: $sort
      limit: $limit
      nextToken: $nextToken
      from: $from
      aggregates: $aggregates
    ) {
      items {
        id
        // ...other fields
        lastPosition
        positionUpdatedAt
        createdAt
        updatedAt
        owner
      }
      nextToken
      total
      aggregateItems {
        name
        result {
          ... on SearchableAggregateScalarResult {
            value
          }
          ... on SearchableAggregateBucketResult {
            buckets {
              key
              doc_count
            }
          }
        }
      }
    }
  }
`;

I use amplify v8.1.0 with transformer v2.
Thank you guys


text:
Q: Formating dates with SQLite and SQLAlchemy query to get Month and Year for ploting graphs I am trying to format a datetime in SQLAlchemy like I can do in pure MYSQL:
DATE_FORMAT(datetime, '%Y-%m')

However, I am using SQLite as a database and would like to use SQLAlchemy rather than RAW sql code.
I understand that func.date() would turn the datetime into a date with SQLite and SQLAlchemy, but I need to get the year and month only like you can with:
func.to_char(datetime, '%Y-%m')

However, this only seems to work with PostgreSQL.
Any help would be greatly appreciated, thanks

A: I have found that the following works for SQLite with sqlalchemy:
func.strftime('%Y-%m', datetime)


text:
Q: Bounds intersection Given a Bounds structure like this:
struct Bounds {
  public double xMin;
  public double xMax;
  public double yMin;
  public double yMax;
}

I'm trying to find out how two Bounds A and B intersect. Possible results are:

*

*A and B do not intersect at all

*A and B are equal

*A fully contains B

*B fully contains A

*A and B intersect each other

My first and naive attempt at it, is to test how many points of A are in B and how many points of B are in A, but I need this test to be as fast as possible and there is probably a better way to do it.
Thanks a lot !

A: Try it in 2D 1D first. It should be clear how to test two [xmin, xmax] objects for those five possible results. Then do the same for [ymin, ymax]. Then combine the two results:

*

*(no intersection)x + (anything)y = (no intersection)

*(equal)x + (something)y = (something)

*(A contains B)x + (A contains B)y = (A contains B)

*(A contains B)x + (A and B intersect)y = (A and B intersect)

*(A contains B)x + (B contains A)y = (A and B intersect)

(I think that covers it.)


text:
Q: Updating scope inside of directive controller I think my problem will be related to $scope.$apply but I am not sure where to put it. It's also possible its related to just a poor understanding of a generic concept. Any clarity would be greatly appreciated.
A couple of key points, I'm using a browserify worflow so I am exporting my directives, they are fully functional in the app.
I've got this following code:
exports.gestutGallery = function() {
    return {
        scope: {
            auto: '='
        },
        controller: function($scope){
            $scope.galleryImages = [];
            $scope.totalImages = $scope.galleryImages.length-1;
            $scope.currentImageIndex = 0;
            // Ternary check to set previous image
            $scope.previousImageIndex =
                $scope.currentImageIndex - 1 >= 0 ? $scope.currentImageIndex - 1 : $scope.totalImages;
            // Ternary check to set next image
            $scope.nextImageIndex =
                $scope.currentImageIndex + 1 <= $scope.totalImages ? $scope.currentImageIndex + 1 : 0;

            //Function References
            this.addToImages = function(image, cb){
                $scope.galleryImages.push(image);
            };
            this.pushImage = function(image){
                console.log(image);
            };
            this.pushPreviousImage = function(){
                pushImage($scope.galleryImages[$scope.previousImageIndex])
            };
            this.pushNextImage = function(){
                pushImage($scope.galleryImages[$scope.nextImageIndex])
            };
        },
        restrict: 'A',
        link: function(scope, elem, attrs) {
            console.log(scope.totalImages);
        }

    };
};

exports.gestutGalleryNavigation = function() {
    return {
        scope:true,
        require: "^gestutGallery",
        link: function(scope, elem, attrs, gsGlCtrl) {
            var navElements = elem.children();
            for(var i=0; i<navElements.length; i++){
                gsGlCtrl.addToImages(navElements[i].getAttribute('data-full-size-image'));
            };
        }

    }
};

I would like to be able to update the values of  totalImages, previousImageIndex, nextImageIndex etc after I've inserted the images from my dom into the images array. But it doesn't work. Where/how would I update those values? I've tried working with $observe with no luck and i've tried calling $scope.$apply() after the loop but always get an error that the digest is already in process.
Thanks for helping explain what I'm doing wrong.
UPDATE:
So, after some further research, I've settled on nesting my $scope.value dependent numbers inside of a $watchCollection, like this:
        $scope.galleryImages = [];
        $scope.currentImageIndex = 0;

        $scope.$watchCollection('galleryImages', function() {

            $scope.totalImages = $scope.galleryImages.length-1;
            // Ternary check to set previous image
            $scope.previousImageIndex =
                $scope.currentImageIndex - 1 <= 0 ? $scope.totalImages : $scope.currentImageIndex - 1;
        // Ternary check to set next image
            $scope.nextImageIndex =
                $scope.currentImageIndex + 1 <= $scope.totalImages ? $scope.currentImageIndex + 1 : 0;

        });

I feel like this might be more expensive than I am wanting since I think that $watch function get's called on each image insert. However, it works and for the use case it's fast enough. I'll leave this open for the rest of the day to see if anyone can suggest a more elegant solution that's more "angular-y", otherwise I'll accept my own answer.

A: You can change $scope.totalImages, $scope.previousImageIndex and $scope.nextImageIndex to functions:
$scope.totalImages = function(){ return $scope.galleryImages.length; };

// Ternary check to set previous image
$scope.previousImageIndex = function(){
  $scope.currentImageIndex - 1 >= 0 ? $scope.currentImageIndex - 1 : $scope.totalImages();
};

// Ternary check to set next image
$scope.nextImageIndex = function (){
  $scope.currentImageIndex + 1 <= $scope.totalImages() ? $scope.currentImageIndex + 1 : 0;
};