Q: All of the dihedral groups are factor groups of the infinite dihedral group.
Show that $\operatorname{Aut}(\Bbb{Z}) \cong \{\pm 1 \}$ and write $\alpha : \mathbb Z_2 \rightarrow \operatorname{Aut}(\Bbb{Z})$ for the nontrivial homomorphism. The semidirect product $\Bbb{Z} \rtimes_{\alpha} \Bbb{Z_2}$ is called the infinite dihedral group. Show that the dihedral groups $D_{2n}$ are all factor groups of the infinite dihedral group.

We know that $\Bbb{Z}$ only has two generators, $1$ and $-1$. So there are only two possibilities: sending $1$ to $1$ and sending $1$ to $-1$. So $\operatorname{Aut}(\Bbb{Z}) \cong \{\pm 1\}$. There is an example in our textbook that shows that $\Bbb{Z}_n \rtimes_{\alpha} \Bbb{Z}_2 \cong D_{2n}$. So I only need to show that $$(\Bbb{Z} \rtimes_{\alpha} \Bbb{Z}_2)/\langle n \rangle \cong \Bbb{Z}_n \rtimes_{\alpha} \Bbb{Z}_2$$ right?
Suppose that $\Bbb{Z} = \langle b \rangle$ and $\Bbb{Z}_2 = \langle a \rangle$. We can see that $(\Bbb{Z} \rtimes_{\alpha} \Bbb{Z_2})/\langle n \rangle = \{b^ia^j \text{mod n} : b^i \in \Bbb{Z}, a^j \in \Bbb{Z}_2\} = \{b^ia^j : b^i \in \Bbb{Z}_n, a^j \in \Bbb{Z}_2\} = \Bbb{Z}_n \rtimes_{\alpha} \Bbb{Z_2}$.
Is my answer correct? I'm just curious because it seems too short.
Thank you in advance

A: Your answer has a couple of issues as discussed in the comments:

*

*You are using $n$ to denote the pair $(n,0)$ (recall that the elements of $\mathbb Z\rtimes \mathbb Z_2$ are defined as pairs).

*More importantly, you are basically arguing that $\mathbb Z\rtimes \mathbb Z_2/\langle n\rangle$ and $\mathbb Z_n\rtimes \mathbb Z_2$ are equal as sets, which isn't really true or relevant; you want to show that they are isomorphic as groups.

You are correct however in your argument that $\mathbb Z$ has only two automorphisms, and your intuition that $\mathbb Z\rtimes \mathbb Z_2/\langle (n,0)\rangle \cong \mathbb Z_n\rtimes \mathbb Z_2$ is also right. To prove this, we consider the map $f:\mathbb Z\rtimes \mathbb Z_2\to \mathbb Z_n\rtimes \mathbb Z_2$ defined by $f((a,b))=([a]_n,b)$. Clearly this is a surjective map with kernel $\langle (n,0)\rangle$. We have
$$\begin{align}
f((a,b)(c,d)) &=f((a+(-1)^bc,b+d))\\
&=([a+(-1)^bc]_n,b+d)\\
&=([a]_n+(-1)^b[c]_n,b+d)\\
&=([a]_n,b)+([c]_n,d)\\
&=f((a,b))f((c,d))
\end{align}$$
thus $f$ is a homomorphism, so by the First Isomorphism Theorem we have $\mathbb Z\rtimes \mathbb Z_2/\langle (n,0)\rangle \cong \mathbb Z_n\rtimes \mathbb Z_2$ as desired.

A: The way to show this, is to note that any of the dihedral groups have a cyclic condition.  When this condition is removed, the elements are infinite.
In essence, the cyclic groups can be written with a $mod(Z)$ condition, while the infinite group is just $z$.  Thus, every cyclic group becomes the infinite group with a cyclic remainder.


Q: java vCenter SDK how to multiple network to a vApp? I'm testing the vCloud Java SDK and I have some problems with the network settings.
I've achieved to create the vApp from a template, but the problem is that the vApp gets the wrong network interfaces.
I have two interfaces named (see the picture):

1.) 4PM-GR-test-Routed
2.) 4PM-GR-test-LAN-servers-arc-VLAN
I when I create the vApp via the template with
Vapp vapp = vdc.instantiateVappTemplate(instVappTemplParams);

if I control the instVappTemplParams there are both network in the params but the final created vApp has two networks both named 4PM-GR-test-Routed
I use the folowing code :
public static Vapp newvAppFromTemplate(ReferenceType vAppTemplateReference, Vdc vdc) throws VCloudException {
    System.out.println("Instantiating " + vAppTemplateReference.getName() + " " + vAppTemplateReference.getHref());
    System.out.println("-------------------------------");

    // get the href of the OrgNetwork to which we can connect the vApp network
    if (vdc.getAvailableNetworkRefs().size() == 0) {
        System.out.println("No Networks in vdc to instantiate the vapp");
        System.exit(0);
    }

    List<ReferenceType> networks = new ArrayList<ReferenceType>(vdc.getAvailableNetworkRefs());

    // fill in the NetworkConfigSection
    NetworkConfigSectionType networkConfigSection = new NetworkConfigSectionType();
    MsgType networkInfo = new MsgType();
    networkConfigSection.setInfo(networkInfo);
    List<VAppNetworkConfigurationType> vAppNetworkConfigs = networkConfigSection.getNetworkConfig();

    // specify the NetworkConfiguration for the vApp network
    Iterator<ReferenceType> networkIterator = vdc.getAvailableNetworkRefs().iterator();
    while(networkIterator.hasNext()){

        ReferenceType networkReference = networkIterator.next();
        System.out.println(networkReference.getName());
        NetworkConfigurationType networkConfiguration = new NetworkConfigurationType();
        networkConfiguration.setParentNetwork(networkReference);
        networkConfiguration.setFenceMode(FenceModeValuesType.BRIDGED.value());

        VAppNetworkConfigurationType vAppNetworkConfiguration = new VAppNetworkConfigurationType();
        vAppNetworkConfiguration.setConfiguration(networkConfiguration);
        vAppNetworkConfiguration.setNetworkName(networkReference.getName());

        vAppNetworkConfigs.add(vAppNetworkConfiguration);
    }

    // fill in remaining InstantititonParams (name, Source)
    InstantiationParamsType instantiationParams = new InstantiationParamsType();
    List<JAXBElement<? extends SectionType>> sections = instantiationParams.getSection();
    sections.add(new ObjectFactory().createNetworkConfigSection(networkConfigSection));

    // create the request body (InstantiateVAppTemplateParams)
    InstantiateVAppTemplateParamsType instVappTemplParams = new InstantiateVAppTemplateParamsType();
    instVappTemplParams.setName("4pm-test-00004");
    instVappTemplParams.setSource(vAppTemplateReference);
    instVappTemplParams.setInstantiationParams(instantiationParams);

    // make the request, and get an href to the vApp in return
    Vapp vapp = vdc.instantiateVappTemplate(instVappTemplParams);
    return vapp;
}

And when I call the method to set the filan IP-s I got two networks with the same name as I said before.
The code for setting the ip-a is:
public static void configureVMsIPAddressingMode(ReferenceType vappRef,Vdc vdc) throws VCloudException, TimeoutException {

    System.out.println("    Configuring VM Ip Addressing Mode");
    Vapp vapp = Vapp.getVappByReference(vcloudClient, vappRef);
    List<VM> childVms = vapp.getChildrenVms();

    for (VM childVm : childVms) {
        NetworkConnectionSectionType networkConnectionSection = childVm.getNetworkConnectionSection();
        List<NetworkConnectionType> networkConnections = networkConnectionSection.getNetworkConnection();
        for (NetworkConnectionType networkConnection : networkConnections) {
            String neteworkName = vdc.getAvailableNetworkRefs().iterator().next().getName();
            networkConnection.setIpAddressAllocationMode(IpAddressAllocationModeType.MANUAL.value());
            networkConnection.setNetwork(neteworkName);

            System.out.println(neteworkName);

            if(neteworkName.equals("4PM-GR-test-Routed")){
                networkConnection.setIpAddress("192.168.135.4");
            }else{
                networkConnection.setIpAddress("10.30.1.4");
            }

        }
        childVm.updateSection(networkConnectionSection).waitForTask(0);
        for (String ip : VM.getVMByReference(vcloudClient,childVm.getReference()).getIpAddressesById().values()) {
            System.out.println("        " + ip);
        }
    }
}

A: I figured out that it was a bug in my code
this code was giving me always the same name
String neteworkName = vdc.getAvailableNetworkRefs().iterator().next().getName();

it should be
String neteworkName = networkConnection.getNetwork();


Q: WordPress custom post type queries I'm using custom post types and listing them in single-[customposttype].php?type=example
<?php if (have_posts()) : while(have_posts()) :  the_post();the_content(); endwhile; endif; ?>

Now I have 2 different custom post type "customtype1" and "customtype2". "customtype1" is top category for "customtype2". When I add a new post on "customtype2" select category from metabox(I have a selectbox which listed "customtype1" posts.) in "customtype1" list. My question is how can I use a query for listing customtype2 posts which belongs top category page(single-customtype1.php)

A: This all depends on what you're actually saving in your post meta. If you're actually saving the ID you could create a secondary query on your single-post_type.php page.
<?php if( have_posts() ) : ?>
    <?php while( have_posts() ) :
            the_post();
            $cpt2_meta = get_post_meta( $post->ID, '_meta_name', true ); // Get out Post Type 2 Meta
    ?>
        <?php the_content(); ?>
    <?php endwhile; ?>
<?php endif; ?>

<?php if( ! empty( $cpt2_meta ) ) :
    $cpt2_posts = new WP_Query( array(
        'post_type' => 'cpt2_slug',
        'posts_per_page' => -1,
    ) );

    if( $cpt2_posts->have_posts() ) :
?>
    <?php while( $cpt2_posts->have_posts() ) : $cpt2_posts->the_post(); ?>

<?php the_title(); ?>

    <?php endwhile;?>
  <?php endif; ?>

<?php endif; ?>

First we get the Post Meta ( category ) then we run a secondary query on that "category". Again, this may change depending on what you're saving as your post meta. For more information you can read into WP_Query.

A: You can use like this
<?php
$id = get_the_ID();
$squery = new WP_Query( array(
    'post_type' => 'lyrics',
    'posts_per_page' => -1,
    'meta_key' => 'your_meta_key',
    'meta_value' => $id,
) );

if( $squery->have_posts() ) : ?>
<?php while( $squery->have_posts() ) : $squery->the_post(); ?>

<?php the_title(); ?>

<?php endwhile;?>


Q: How do I select shapefiles to be converted to GeoJSON in folder with multiple shapefiles? How do I only select .shp's to read and then convert to .geojson. The homefolder has 3 different shapefiles and this code currently converts every single file in the folder to a .json. Just trying to speed up the running process. I have some other issues too with naming conventions that I will deal with next. Among other things, this is a work in progress.
homefolder = "D:/UW/Winter_2016/501/pythonProject/publicLandsData/newShapefiles/"

# read the shapefiles
filenames = os.listdir(homefolder)

for filename in filenames:
  reader = shapefile.Reader(homefolder + os.path.splitext(os.path.basename(filename))[0])
  print filename
  fields = reader.fields[1:]
  field_names = [field[0] for field in fields]
  buffer = []
  print filename + "buffer dictionary done"
  for sr in reader.shapeRecords():
      atr = dict(zip(field_names, sr.record))
      geom = sr.shape.__geo_interface__
      buffer.append(dict(type="Feature", \
      geometry=geom, properties=atr))

# write the GeoJSON file
#currently it saves into the wrong directory..and all one shapefile, might be nice to be in multiple geojson's
#list directory "homefolder" in variable filenames
  filenames = os.listdir(homefolder)

  for filename in filenames:
#for loop to rename local government to loca
    geojson = open(((os.path.splitext(os.path.basename(filename))[0]) + ".json"), "w")
    #os.rename(os.path.join(homefolder, filename), os.path.join(homefolder, (filename.replace('.shp', 'shp'))))
    geojson.write(dumps({"type": "FeatureCollection",\
      " features": buffer}, indent=2) + "\n")
    geojson.close()

I have tried using basename, selecting only ".shp" files with .endwith() etc to no avail. Suggestions?
I found this shp to geojson conversion code at the link below:
https://gist.github.com/frankrowe/6071443

A: Try replacing line 4 with this:
filenames = [ f for f in os.listdir(homefolder) if os.path.isfile(os.path.join(homefolder,f)) and f.endswith(".shp")]

This will create a list containing only files with the extension ".shp"
Expanded for clarity:
# create empty list
filenames = []
# begin iterating over files in homefolder directory
for f in os.listdir(homefolder):
    # if the file is indeed a file and it ends with .shp append the name to the list
    if os.path.isfile(os.path.join(homefolder,f)) and f.endswith(".shp"):
        filenames.append(f)

A: Look at PyShp_geointerface.py with a generator
import shapefile
def records(filename):
   # generator
   reader = shapefile.Reader(filename)
   fields = reader.fields[1:]
   field_names = [field[0] for field in fields]
   for sr in reader.shapeRecords():
      geom = sr.shape.__geo_interface__
      atr = dict(zip(field_names, sr.record))
      yield dict(geometry=geom,properties=atr)
 # for one file
  buffer = [rec for rec in records('shapefile.shp')]
  result = {"type": "FeatureCollection"," features": buffer}

For many files, simply loop through the files
for dir, subdir, files in os.walk(a_folder):
    for fname in files:
        if fname.endswith(".shp"):
           buffer = [rec for rec in records(os.path.join(dir, fname))]
           result = {"type": "FeatureCollection"," features": buffer}
           # write the resulting GeoJSON file
           name = os.path.splitext(fname[0]+'.geojson')
           with open(name, "w") as outfile:
               json.dump(result,outfile)


Q: How to route on basis of Http headers in Envoy Proxy I am sending an http request with below header.
Header = {"InstanceId" : "1"}
How to route to an cluster(endpoint) using this header value i.e. 1
What i actually want to do in envoy.yaml :
If (header. InstanceId == 1)
Route to cluster A

Else If (header. InstanceId == 2)
Route to cluster B

Can someone please help me out.
Thanks in advance.

A: If you want to redirect traffic to different clusters based on the headers, you can define the following listener (the interesting part is the static_resources.listeners[0].filter_chains[0].filters[0].route_config.virtual_hosts[0].routes part, with the two matches defined) :
static_resources:
  listeners:
  - address:
      socket_address:
        address: 0.0.0.0
        port_value: 8080
    filter_chains:
    - filters:
      - name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          codec_type: AUTO
          stat_prefix: ingress_http
          route_config:
            name: local_route
            virtual_hosts:
            - name: backend
              domains:
              - "*"
              routes:
              - match:
                  prefix: "/"
                  headers:
                    - name: "InstanceId"
                      exact_match: "1"
                route:
                  cluster: clusterA
              - match:
                  prefix: "/"
                  headers:
                    - name: "InstanceId"
                      exact_match: "2"
                route:
                  cluster: clusterB
          http_filters:
          - name: envoy.filters.http.router


Q: Python loops in Kivy I'm just now learning Kivy for some UI options when creating stuff with Python. The thing I'm strugling right now are loops and how to make them work with Kivy.
Example below is a very straightforward loop that should print each number to a Kivy label (replacing previous).
Currently when pressing the button I only get the last digit on screen because the entire function runs completely - which makes sense. But my question is how can I setup the button so that when I press it, it runs only one iteration of the loop.
My .py file:
from kivy.app import App
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.widget import Widget

Window.size=(300,300)
Builder.load_file('loop.kv')

class MyLayout(Widget):
    def loop(self):
        for i in range(10):
            self.ids.label_print.text = str(i)
    pass

class LoopApp(App):
    def build(self):
        return MyLayout()

if __name__=='__main__':
    LoopApp().run()

My .kv file:
<MyLayout>
    BoxLayout:
        orientation: 'vertical'
        size: root.height, root.width

        Label:
            id: label_print
            font_size: 32
        Button:
            text: 'Loop'
            on_press: root.loop()

Currently it only shows 9 as a result and I would expect to go from 0 and add 1 for each button press:

A: Basically your loop works correctly, but happens immediately so you only see the 9 and not a sequence or anything. What you can do is to use kivy.clock to schedule an interval to a callback function, specify the interval time and stop the schedule at a certain point. If you would skip the kivy.clock part, your GUI is frozen until the function is finished. Example:
from kivy.app import App
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.clock import Clock
from timeit import time

Window.size=(300,300)
Builder.load_file('loop.kv')

class MyLayout(Widget):
    loop_thread = None

    def callback_to_loop(self, dt):  # dt is the interval-time
        # this is required because initially the text is an empty string
        try:
            current = int(self.ids.label_print.text)
        except:
            current = 0

        # simply add up the numbers
        self.ids.label_print.text = str(current+1)

        # stop at a certain point and unschedule the thread
        if current == 11:
            Clock.unschedule(self.loop_thread)

    def loop(self):
        # schedule the thread with an interval-time = 1
        self.loop_thread = Clock.schedule_interval(self.callback_to_loop, 1)

    pass

class LoopApp(App):
    def build(self):
        return MyLayout()

if __name__=='__main__':
    LoopApp().run()


Q: Rails inserting multiple records for single model How shall I set the form fields to be able to insert multiple rows in the database for a single model.
I am updating a div with another link and cannot use the form helper. So I need to set the field names manually.
I have a post model and it has a title field.
  I want to insert i posts to db like post[0][title] But when I name the form field like this It gets 0 as string and does not record.
Also I tried to set the Array my self from Rails Console like
post = Array.new
post << [:title => "title 1"]
post << [:title => "title 2"]
sav = Post.new(post)
sav.save

And still nothing is saved.

A: posts = Array.new
posts << {:title => "title 1"}
posts << {:title => "title 2"}
Post.create(posts)

A: is this what you're trying to do?
posts = []
posts << Post.new(:title => "title 1")
posts << Post.new(:title => "title 2")

posts.each do |post|
  post.save
end


Q: Check for a valid guid How can you check if a string is a valid GUID in vbscript? Has anyone written an IsGuid method?

A: This function is working in classic ASP:
Function isGUID(byval strGUID)
      if isnull(strGUID) then
        isGUID = false
        exit function
      end if
      dim regEx
      set regEx = New RegExp
      regEx.Pattern = "^({|\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\))?$"
      isGUID = regEx.Test(strGUID)
      set RegEx = nothing
End Function

A: This is similar to the same question in c#. Here is the regex you will need...
^[A-Fa-f0-9]{32}$|^({|()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|))?$|^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$
But that is just for starters. You will also have to verify that the various parts such as the date/time are within acceptable ranges. To get an idea of just how complex it is to test for a valid GUID, look at the source code for one of the Guid constructors.

A: In VBScript you can use the RegExp object to match the string using regular expressions.

A: Techek's function did not work for me in classic ASP (vbScript). It always returned True for some odd reason. With a few minor changes it did work. See below
Function isGUID(byval strGUID)
  if isnull(strGUID) then
    isGUID = false
    exit function
  end if
  dim regEx
  set regEx = New RegExp
  regEx.Pattern = "{[0-9A-Fa-f-]+}"
  isGUID = regEx.Test(strGUID)
  set RegEx = nothing
End Function

A: there is another solution:
try
{
  Guid g = new Guid(stringGuid);
  safeUseGuid(stringGuid); //this statement will execute only if guid is correct
}catch(Exception){}


Q: Question about charging and using an iPad mini I just purchased a cellular iPad mini but I cant seem to find out if charging an iPad mini while using the device affects battery life, and does charging overnight affect battery life?

A: You should be fine using the iPad while it is charging. The thing you want to avoid that affects battery life is always keeping it plugged in. You want to make sure you regularly "use" your battery, allowing it to drain and then recharging to full. If it is always plugged in and sitting at full you'll start to notice a decrease in performance when the battery finally does get drained.


Q: Extract text inside HTML tags using XSLT I have an XML file that has some CDATA with html tags. Example:
<TextElement>
  <Data>
    <![CDATA[
My Header Text
 ]]>
  </Data>
</TextElement>

I need to be able to display "My Header Text" without the H2 tag.
Thank you!

A: Using
<xsl:param name="start-tag"><![CDATA[
]]></xsl:param>
<xsl:param name="end-tag"><![CDATA[
]]></xsl:param>

and then a substring-after(substring-before combination
<xsl:template match="Data">
  <xsl:value-of select="substring-before(substring-after(., $start-tag), $end-tag)"/>
</xsl:template>

should do. http://xsltransform.net/naZXpY6.


Q: Grails persistence in Spring's "Async" annotated methods not working I have a problem on persisting Grails domain objects in Spring Async annotated service methods.
Here is the simplified code:
class DocumentService {

@Async
def process(Long documentId, Organization organization) {

    ...

    def organizationCari = new OrganizationCari(organization: organization, active: true)
    organizationCari.save(flush: true, failOnError: true)

    print "Document processing..."

    ...

    print "Document processed..."

}

}
I have the method running asynchronously, but then I can't seem to get anything printed on the console, since thread ends upon save operation. I get no errors and the domain object is still not persisted.
Removing Async annotation solves the problem, but I have to run the method asynchronously.
I'm using Grails 2.1.1 with Spring 3.1.2.

A: The problem is that there is no hibernate session in the new asynchronous thread, and the default AsyncTaskExecutor is not logging the exception.
You can verify this yourself by putting a try/catch block inside your @Async method and logging the exception yourself.
The solution is to use Domain.withNewSession around the GORM code in your service method:
import org.springframework.scheduling.annotation.Async

class MyService {

    @Async
    void myAsyncMethod() {
        MyDomain.withNewSession {
            MyDomain m = new MyDomain(...)
            m.save()
        }
    }
}

If you have many asynchronous methods, you may consider creating your own AsyncTaskExecutor as in this SO answer.


Q: advice on the best method of positioning my active tab link correctly and consistently I'm having trouble trying to place my active anchor tab over the main content area border, i have tried adding position: relative etc but have had no joy, the tab also has to be positioned over the ul border so i think i may have set this up wrong, can anyone give me some pointers on how I could achieve this effect correctly?
My link http://jsfiddle.net/eBnUt/1/
Thanks
Kyle

A: You just need to add margin-top: -2px; to .boxBody. Live example: http://jsfiddle.net/tw16/eBnUt/2/
.boxBody{
    border: 2px solid #343434;
    background: #fff;
    /*width: 100%;*/
    min-height: 70px;
    padding: 20px;
    margin-top: -2px; /* add this */

    -webkit-border-bottom-right-radius: 10px;
    -webkit-border-bottom-left-radius: 10px;
    -moz-border-radius-bottomright: 10px;
    -moz-border-radius-bottomleft: 10px;
    border-bottom-right-radius: 10px;
    border-bottom-left-radius: 10px;
}


Q: Как с помощью регулярных выражений достать два числа из строки? У меня есть строка: '/randomNumber 0-1' мне надо достать два числа из этой строки (тире ставится для обозначения диапазона). Получение чисел из строки (до тире и после него) у меня вызвало некоторые трудности, так как я не очень знаком с модулем re. Вот отрывок кода, в котором я пытаюсь получить эти два числа, в строке 6,7 мне нужно записать числа в переменные, но получение этих чисел у меня вызвывает трудности, так как числа могут быть любые (десятизначные, отрицательные):
 1  import re
 2  from randomizer import randomNumber
 3
 4  answer = input()   # здесь вводится '/randomNumber "___"-"___"'
 5
 6  firstNumber = re.  # cюда надо записать
 7  secondNumber = re. # эти числа
 8
 9  response = randomNumber(firstNumber, secondNumber) # здесь числа передаются в функцию
10
11  print("",answer, answer[:13], "", firstNumber, secondNumber, sep="\n") # здесь выводится всё, делаю это только для теста.

Подскажите, пожалуйста, как мне их достать?

A: Можно не думать над регулярками и просто разбить строку
firstNumber = answer.split(" ")[1].split("-")[0]
secondNumber = answer.split(" ")[1].split("-")[1]


Q: Changing background colour of a Manipulate element Please consider the following:
 Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}];

Now, I would like to change the background colour to yellow. I tried the following, but in this case the nice looking rounded corners of the manipulate element get lost:
Panel[#, Background -> Yellow] &@
 Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2},
  Paneled -> False]

Maybe somebody has a better idea.
EDIT
The background colour of Manipulateis by default grey.

In addition the graphical element in which the Manipulate is embedded has rounded corners
 which I would like to keep. Applying my approach will change the colour but I loose the rounded corners.

A: Wrapping Manipulate in Style and using DefaultOptions to set background color of Panel and then adjusting FrameMargins manually:
Panel[Style[Manipulate[
Plot[Sin[x (1 + a x)], {x, 0, 6}, Background -> None], {a, 0, 2}],
DefaultOptions -> {Panel -> {Background -> LightBlue}}],
FrameMargins -> {{-3, -2}, {-2, -3}}]

you get

Panel[Style[Manipulate[
Plot[Sin[x (1 + a x)], {x, 0, 6}, Background -> LightBlue], {a, 0, 2},
FrameMargins -> {{-4, -3}, {-2, -2}}],
DefaultOptions -> {Panel -> {Background -> LightBlue}}],
      FrameMargins -> {{-3, -2}, {-2, -3}}]

gives

Update: Screenshot of free-cdf version deployed as stand-alone and viewed in browser window:

A: If you would like to change background of Manipulate function - this is a way. Note I'll show you most difficult case when you have to go from light to dark colors change - then you have to pay attention to styling of internal graphics too, so everything (like ticks) are visible.
st = {FontColor -> GrayLevel[.7]};
Framed[Manipulate[
  Plot[Sin[x (1 + a x)], {x, 0, 6}, Background -> GrayLevel[.3],
   PlotStyle -> {Thick, Orange}, Frame -> True, BaseStyle -> st,
   ImageMargins -> 7], {{a, 1, "frequency"}, 0, 2,
   Appearance -> "Labeled"}, Paneled -> False], FrameMargins -> 30,
 Background -> Black, BaseStyle -> st, RoundingRadius -> 10]

A: Not sure if you can do it in a Manipulate wrapper, but you could technically build your own as such:
Panel[Column[{Manipulator[Dynamic[a], {0, 10}],
   Dynamic[Plot[Sin[x (1 + a x)], {x, 0, 6}]]}],
 Background -> LightGreen]

Or...
Panel[Column[{Manipulator[Dynamic[a], {0, 10}],
   Panel[Dynamic[Plot[Sin[x (1 + a x)], {x, 0, 6}]],
    Background -> LightGreen]}]]


Q: ionic: HTML5 audio tag not working on iOS 11 I am developing an ionic framework test app which streams audio from a server using the HTML5 audio tag. I've been testing it in some Android and iOS devices and it works just fine.
Today I got an iOS 11 device to test and I found that the stream does not work. I created a simple web to test the device with safari and worked. I uploaded the app to ionic view and worked too.
Is there something new on iOS 11 that disables streamings on apps?
Is it something with the HTML5 audio tag?

A: I solved the issue by adding type="audio/mpeg" to the audio tag.


Q: what is the meaning of "n/n/n" in the header of csv file? how can I make a data frame from this file? Dataframe after importing csv file

[Kunde;Produkt;Kampagne;Vermarkter/Verlag;Werbeträger;Datum von;Datum bis;Platzierung;Werbeform;Menge;Einheit;n/n/n;Tracking-ID;AdGap-ID]

I am trying to expand this data to a pandas data frame, but I am confused about this header. After importing this *.csv file into my python data frame there are two columns.
So far I have made two data frame, using the first column and second column. But how I can combine them? what is the relation between this two data frames?
Data frame 1
Data frame 2


Q: loop only showing first value when using variable I am trying to show products that are added in a custom attribute in the backend but it is only showing the first item
<?php
$bundle_products = $_product->getbundle_products();
if ($_product->getAttributeText('bundle') == yes):
$product_ids = array($bundle_products);
$collection = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('entity_id', array('in' => $product_ids));

foreach($collection as $eachproduct){
echo 'getProductUrl() . '">getImageUrl() . '" title="' . $eachproduct->getName() . '" height="50" width="50">';
$combined_price += $eachproduct->getFinalPrice()/100*10;
}
endif;
?>

If I hard code it in as: $product_ids = array(3,138,194);
It works fine. Am I missing something?
If I echo $bundle_products It outputs 3,138,194

A: Use below code:
<?php
    $bundle_products = $_product->getbundle_products();
    if ($_product->getAttributeText('bundle') == yes):
    //$product_ids = array($bundle_products);
    $product_ids = explode(',',$bundle_products);
    $collection = Mage::getModel('catalog/product')
        ->getCollection()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('entity_id', array('in' => $product_ids));

    foreach($collection as $eachproduct){
    echo 'getProductUrl() . '">getImageUrl() . '" title="' . $eachproduct->getName() . '" height="50" width="50">';
    $combined_price += $eachproduct->getFinalPrice()/100*10;
    }
    endif;
    ?>

You are almost did all things right. Only you need to convert the string into array. that's why i use explode(',',$bundle_products).
Hope it will solve your problem. Happy learning


Q: What is the cost of try catch blocks? How much better is:
 if (condition) {
  try {
   //something
  } catch(SomeEx ex) {}
 }

instead of this:
 try {
   if (condition) {
     //something
   }
 } catch(SomeEx ex) {}

What actually JVM do when I enter try block ?
EDIT:
I don't want to know that in second example always go in to try... Please answer the question.

A: try {if (condition) {...}} catch(SomeEx ex) {}

Here you handled the exception if it is arised condition of if also if arised inside if-block.
if (condition) {try {...} catch(SomeEx ex) {}}

Here you handle exception if is arised only inside the if-block. If something goes wrong in if condition then it will not be handled.
So it is depends upon the actual senario.

A: Execution wise at run time, as long as there is no exception, try does not cost you anything. It only costs run time as soon as an exception occurs. And in that situation it is much slower that an if evaluation.
In the JVM spec, you see that there is no extra byte code generated on the execution path:
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.12

A: From the perfomance point of view it should be the same. Throwing of the exception is a costly  operation (for starters, the stacktrace must be created and populated). The mere existence of the try block has no (or negligible) performance penalty.
See Should java try blocks be scoped as tightly as possible.

What actually JVM do when I enter try block ?

From JLS 14.20.1. Execution of try-catch:

A try statement without a finally block is executed by first executing the try block. Then there is a choice:

*

*If execution of the try block completes normally, then no further action is taken and the try statement completes normally.

*If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:

*

*If the run-time type of V is assignment compatible with (§5.2) a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed, and then there is a choice:

*

*If that block completes normally, then the try statement completes normally.

*If that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.

*If the run-time type of V is not assignment compatible with a catchable exception class of any catch clause of the try statement, then the try statement completes abruptly because of a throw of the value V.

*If execution of the try block completes abruptly for any other reason, then the try statement completes abruptly for the same reason.

EDIT:
For a complete Exception description see the JVM 2.10 link in The New Idiot's answer.

A: if (condition) {
  try {
   //something
  } catch(SomeEx ex) {}
 }

is better to use since it executes the try block if the condition is ok.JVM compiles the try block and validated the catch block or a finally block. I think advantage is not in the compile time but in the run time. Compile time I think no advantage at all

A: Exceptions should be exceptional case , not every time the code runs. So better to check for the condition before trying !
if (condition) {
  try {
    //something
  } catch(SomeEx ex) {}
}

Make sure , if (condition) itself doesn't throws an Exception.
It depends on your usage and functionality . For example this would be better :
if (someObject!=null) {
  try {
     someObject.getSomething(); // getSomething() potentially throws some Exception
  } catch(SomeEx ex) {}
}

What actually JVM do when I enter try block ?

Read JVM spec 2.10.

A: If you see oracle docs
>try {
    code
}
catch and finally blocks . . .

The segment in the example labeled code contains one or more legal lines of code that could throw an exception.

So,If you feel doubt on your If condition that it will throw an exception  put it inside.Otherwise put outside.


Q: JavaScript's functions and objects assignment to other variables I was going through some practice sessions and I came to learn that in JS, functions are also object. So I tried the following.

function say() {
  console.log("hi")
}
var obj1 = say;
obj1.hello = "hello";
console.log(say.hello); // hello

then I tried doing the same with an object, but got undefined and I expected to get winter.

var obj2 = { weather: "summer", time: "noon" };
var name = obj2;
name.favoriteWeather = "winter";
console.log(name.favoriteWeather); //undefined

Why JS behaves the way it does? how can I get winter as result from name.favoriteWeather


Q: How do I debug a Xamarin app + webapi + SQL Server set-up? I'm brand new to Xamarin.Forms and Visual Studio (2017 on PC). I'm working with code another (experienced) dev wrote in C# and .NET.
I have a Xamarin app. The app asks me to input data. Then, it saves that data to a SQL Server database via a Web API. Next, later, the app gets that data back from the database to do something.
I can build and publish all projects and the app runs on Android simulator. However, it looks like the data I input is either:

*

*Not sent to the DB

*Not used by the DB

I can tell because when I get the data back from the database, the "something" is wrong.
So here's my question: how do I debug that set-up? I'm familiar with debugging my Xamarin app inside VS 2017, but I don't know how to debug the Web API, or how to look inside the database to see if the data I input are recorded correctly.
At this point, I'm not sure where the bug is, or how to find it. Thanks for your help!

A: Xamarin application:
As you already mentioned, you can debug your Xamarin app in Visual Studio just like you would any other .Net projects.
Web API:
Similarly, you can also debug your Web API project in Visual Studio.

*

*Run the Web API project locally.

*Note the address from the address bar and use that in Postman or other similar tools to send/receive the API requests/response.

SQL Server Database:
You cannot technically 'debug' a database, but you can verify the CRUD operations using SQL Server Management Studio (or SSMS) provided you have the necessary access/credentials.
To find where the error is, I would suggest:

*

*Start from your Xamarin application and verify if the app is sending the JSON as expected;

*Then send the same JSON from postman to your Web API and verify if it is accepting/processing the JSON as expected;

*And finally, check your database tables in SSMS if the data is stored as expected.

Refer the following links:
https://www.c-sharpcorner.com/article/asp-net-web-api-with-fiddler-and-postman/
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-ssms
Hope it helps. Cheers!

A: Found out you can debug a web API using Visual Studio almost the same way you debug a Xamarin app. Here's a nice tutorial for that:
https://learn.microsoft.com/en-us/azure/app-service/web-sites-dotnet-troubleshoot-visual-studio#remotedebug


Q: Trouble Installing Plone on Solaris 11 I am new to Plone and Solaris - I'm attempting to install Plone 5 on Solaris 11.  Seems to be hanging up on the Zope install.  Here is the install.log:
Detailed installation log
Starting at Wed Oct 14 11:41:13 AKDT 2015
The directory '/home/dotasdis/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/dotasdis/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Processing ./packages/zc.buildout-2.4.3.tar.gz
Requirement already satisfied (use --upgrade to upgrade): setuptools>=8.0 in /opt/plone/zinstance/lib/python2.7/site-packages (from zc.buildout==2.4.3)
Installing collected packages: zc.buildout
  Running setup.py install for zc.buildout
Successfully installed zc.buildout-2.4.3
/opt/plone/zinstance/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
Creating directory '/opt/plone/zinstance/parts'.
Creating directory '/opt/plone/zinstance/develop-eggs'.
Not found: /opt/plone/buildout-cache/downloads/dist/ZODB3/
Not found: /opt/plone/buildout-cache/downloads/dist/ZODB3/
Getting distribution for 'ZODB3==3.10.5'.
gcc: cg: No such file or directory
gcc: unrecognized option '-Qoption'
gcc: unrecognized option '-KPIC'
gcc: language O5 not recognized
gcc: language O5 not recognized
error: Setup script exited with error: command '/usr/gcc/4.5/bin/gcc' failed with exit status 1
An error occurred when trying to install ZODB3 3.10.5. Look above this message for any errors that were output by easy_install.
While:
  Installing.
  Getting section instance.
  Initializing section instance.
  Installing recipe plone.recipe.zope2instance.
  Getting distribution for 'ZODB3==3.10.5'.
Error: Couldn't install: ZODB3 3.10.5

Any help is greatly appreciated.


Q: Make taxonomy terms appear in the order they were made IS it possible to make taxonomy terms appear in the order they were made, in the backend?
They keep appearing in alphabetical order. I tried using sort but it doesn't seem to be working.
This is my code for creating custom taxonomies:
$taxonomies['size'] = array(
            'hierarchical' => true,
            'query_var' => 'size',
            'sort' => true,
            'rewrite' => array(
                'slug' => 'size',
            ),
            'labels' => array(
                'name' => 'Size',
                'singular_name' => 'Size',
                'update_item' => 'Update Color',
                'edit_item' => 'Edit Size',
                'add_new_item' => 'Add Size',
                'new_item_name' => 'Add New Size',
                'all_items' => 'All Sizes',
                'search_items' => 'Search Sizes',
                'popular_items' => 'Popular Sizes',
                'popular_items_with_comments' => 'Separate sizes with commas',
                'add_or_remove_items' => 'Add or remove sizes',
                'choose_from_most_used' => 'Choose from most used sizes'
            )
        );


Q: Error installing jira on pip I am trying to install jira on pip, but am getting the following errors:

  /usr/lib64/nagios/plugins]#python -m pip install jira
Collecting jira
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/
  Could not find a version that satisfies the requirement jira (from versions: )
No matching distribution found for jira

Any help would be highly appreciated.

A: The ProtocolError says that pip is trying to resolve /simple/jira/ as a DNS hostname instead of pypi.python.org. The problem may reside in ~/.pip/pip.conf.
Are you in a container by any chance?


Q: Two onPointerOver events conflict in React My screen is divided in two zones: left zone and right zone.
The left zone appears always. When you point over the left zone, it should make appear the right zone.
Once the right zone is displayed, both zones should make the right zone display.
But its not working as expected, the right zone disappear when "trying" to point over it.
Check the demo HERE
export default function App() {
  const [pointOverLeftZone, setPointOverLeftZone] = useState(false);
  const [pointOverRightZone, setPointOverRightZone] = useState(false);

  const shouldDisplayRightZone = pointOverLeftZone || pointOverRightZone;

  return (

 {
          if (!pointOverLeftZone) setPointOverLeftZone(true);
        }}
        onPointerOut={() => {
          if (pointOverLeftZone) setPointOverLeftZone(false);
        }}
      >

Point over here to display the right zone

      {shouldDisplayRightZone && (

 {
            if (!pointOverRightZone) setPointOverRightZone(true);
          }}
          onPointerOut={() => {
            if (pointOverRightZone) setPointOverRightZone(false);
          }}
        >

            Once open the right zone, both zones should activate the display of
            this right zone, but the bug is here: when you mouse the move here
            it dissapear

      )}

  );
}

A: Value of shouldDisplayRightZone depends on value of pointOverLeftZone, pointOverRightZone so you should make it an independent state and wrap into an useEffect and update whenever there are changes in pointOverLeftZone, pointOverRightZone
const [shouldDisplayRightZone, setShouldDisplayRightZone] = useState(
  pointOverLeftZone || pointOverRightZone
);

useEffect(() => {
  setShouldDisplayRightZone(pointOverLeftZone || pointOverRightZone);
}, [pointOverLeftZone, pointOverRightZone]);

Forked codesandbox

A: import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [pointOverLeftZone, setPointOverLeftZone] = useState(false);
  const [pointOverRightZone] = useState(false);

  const shouldDisplayRightZone = pointOverLeftZone || pointOverRightZone;

  return (

 setPointOverLeftZone(true)}
      >

Point over here to display the right zone

      {shouldDisplayRightZone && (

 setPointOverLeftZone(false)}
        >

            Once open the right zone, both zones should activate the display of
            this right zone, but the bug is here: when you mouse the move here
            it dissapear

      )}

  );
}

Something like this?

A:  import React, { useState } from "react";
 import "./styles.css";

export default function App() {
const [pointOverLeftZone, setPointOverLeftZone] = useState(false);
 const [pointOverRightZone, setPointOverRightZone] = useState(false);
const [flag, setFlag] = useState(true);
const [int, setIni] = useState(false);
 const shouldDisplayRightZone = pointOverLeftZone || pointOverRightZone;

return (

  {flag === true ? (

 {
        if (!pointOverLeftZone) {
          setPointOverLeftZone(true);
        }
      }}
    >

Point over here to display the right zone

  ) : (

right zone open

        Once open the right zone, both zones should activate the display of
        this right zone, but the bug is here: when you mouse the move here
        it dissapear

   )}

   {shouldDisplayRightZone && (

 {
        if (!pointOverRightZone) {
          setFlag(false);
          setPointOverRightZone(true);
        }
      }}
      onPointerOut={() => {
        if (pointOverRightZone) setPointOverRightZone(false);
      }}
    >

        Once open the right zone, both zones should activate the display of
        this right zone, but the bug is here: when you mouse the move here
        it dissapear

   )}

 );
 }

i have changed the code in sandbox you can check it there.Let me know if it works


Q: Regular expression for two following proper nouns I am trying to build a script that should give you a list of the proper names of a text. I want to build a regular expression that matchs every word that starts with a capital letter and that doesn't start a stence. An example from the text:

"But while he thought about these things, behold, an angel of the Lord
  appeared to him in a dream, saying: Joseph, son of David, do not be
  afraid to take to you Mary your wife, for that which is conceived in
  her is of the Holy Spirit. She is going to have a son. You must give him the name Jesus. That’s because he will save his people from their sins.

I want that the regexp matches: "Lord", "Joseph", "David", "Mary", "Holy" and "Spirit". It should not match "But", "She", "You" or "That". So I did this:
[a-z,;:] +([A-Z][a-z]+)[\W]

This matchs Lord, Joseph, David, Mary and Holy, BUT not Spirit. And that is my problem: after finding "Holy", the regexp keeps going searching in the text the pattern; to find "Spirit", the regexp should take the "y" of "Holy" in consideration for the first square bracket. So, after finding "Holy" should restart not after "Holy". I have tried it also with non matching groups, like:
(?:[a-z,;:]) +([A-Z][a-z]+)[\W]

But that is also not the answer. I would be very thankful if anyone would help.
Regards!

A: Regex
(?<=[a-z,;:] )([A-Z][a-z]+)

Demo
Output:
MATCH 1
1.  [65-69] `Lord`
MATCH 2
1.  [106-112]   `Joseph`
MATCH 3
1.  [121-126]   `David`
MATCH 4
1.  [160-164]   `Mary`
MATCH 5
1.  [221-225]   `Holy`
MATCH 6
1.  [226-232]   `Spirit`

A: You can try
(?<![.!?;]) ([A-Z]\w+)

demo


Q: Is it idiomatic to say "don't bite me in the arm"? We can say "to poke me in the arm" as stated in dictionaries.
the verb "bite" is somehow similar to "poke" in its meaning because both mean to push into or through something.
But I don't see the structure "to bite somebody in the eye/arm" in dictionaries.

bite [intransitive, transitive] to use your teeth to cut into or
  through something
Does your dog bite?
Come here! I won't bite! (= you don't need to be afraid)
bite into/through something She bit into a ripe juicy pear.
bite somebody/something She was bitten by the family dog.
Stop biting your nails!
bite off something/sth off He bit off a large chunk of bread/He bit a
  large chunk of bread off.

It seems that the dictionary suggests to use "to bite something", for example, "to bite the arm/ the leg/ etc"
or, "to bite into something", for example, "to bite into the arm/ the leg/ etc".
But they don't have examples of "to bite somebody into something".
Is it idiomatic to say "don't bite me in the arm"?

A: Your construction is grammatically valid, but it would be more idiomatic to say “don’t bite my arm!”
The only idiomatic use of “bite me in” is the idiom “bite [person] in the ass”.

A: No, this construction is impossible as idiomatic in the modern USA and UK variants of English. The verb bite has a large number of idiomatic grammar constructions and idiomatic expressions. All have been defined by its use for many years. Therefore, they are stable with their meaning in the modern usage. The expression don't bite me in the arm is the result of so called logical intersection of two well-known grammar constructions with own established meaning, if we take it as an idiom. That is why it could be totally incomprehensible as idiomatic for the native American and British English speakers.
Though, it is fairly possible that such construction could be acceptable as an idiom in some variants of minor dialects and slang of English in these countries.


Q: Accessing $scope variable from another method in the same controller Angularjs how can I  call/access $scope.mydata from another method in the same controller in Angularjs?
My scenario is
.controller("myCtryl", function($scope,  $http) {
  $scope.functionA = function(){
     $scope.data = "some data";
  }
  $scope.functionB = function(){
     //access $scope.data here//
  }

}

A: It is fine to access $scope in that function.
.controller("myCtryl", function($scope,  $http) {
  $scope.functionA = function(){
     $scope.data = "some data";
  }
  $scope.functionB = function(){
     $scope.data //this id valid
  }

}

A: You can just access $scope.data in functionB the same way you access it in functionA. It will work. The $scope variable is in the same lexical scope for both functions.


Q: What is the difference between ASM LHI and LGHI? In the *.s file of a compiled cpp code by gcc, there are some LHI and LGHI command. I know they mean load address, very similar to LA, but what is the exact difference between them? Is there any document about this? Thanks!


Q: Calculation of Latitude and Longitude from given point and radius I have latitude, longitude and a radius. Can you please help me in finding the another latitude and longitude from given points (latitude and longitude) and radius.

A: Are you trying to find out if another latitude and longitude is within a certain radius of your initial latitude and longitude?  If so, check out this other StackOverflow post.

A: You will need more information than a point and a radius. You are also going to need the angle of the point in the circle.
Using the radius and the angle you have to apply trigonometric laws and draw and imaginary triangle with dimensions radius, height and width. The height and width will give you the distance from the current latitude and longitude.
For example:
for (int angle = 0; angle < 360; angle++){
    double x = getDistanceX(radius, angle);
    double y = getDistanceY(radius, angle);
    if (angle > 180)
        x *= -1;
    if (angle > 90 && angle < 270)
        y *= -1;
    double newLatitude = getCalculateLatitude(latitude, x);
    double newLongitude = getCalculateLatitude(longitude, y);
}


Q: background is divided for some reason can someone take a look at my webpage and help me figure out what is wrong
for some a reason the background gradient is divided and start a new one again.
I want the gradient to continue to the entire page.
this is the html
https://www.csupomona.edu/~lannguyen/Test/Template.html
this is the css for it
https://www.csupomona.edu/~lannguyen/Test/mystyle.css
Thanks

A: Get a tool like Firebug for Firefox and learn to use it.  It makes finding issues like this simple.
The answer is clear, once you have the right tool: the gradient, which is applied to the body element, does not extend all the way down because the body element does not go the full height of the browser.
Add:
html, body {
    height: 100%;
}

and it will be fixed.


Q: Function to check if the db value matches the current Select option I am creating a customer account page which displays the relevant information in the database and allows customers to edit their information. The code below retrieves and displays the customer's account information from the database and pre-selects the values matching their information, but since there are a few hundred select and/or multiselect elements I'd like to create a function which would check if the db value (i.e. $rows['gift_privacy']) matches the current option.
<?php
try {
$stmt = $conn->prepare("SELECT * FROM customer_info WHERE user_id = :user_id");
$stmt->bindValue(':user_id', $user_id);
$stmt->execute();
}catch(PDOException $e) {echo $e->getMessage();}
$row = $stmt->fetch();
?>
<form action="account_information-exec.php" method="post">
<select name="gift_privacy">
    <option value="Standard" <?php if($row['gift_privacy']=='Standard') echo "selected='selected'"; ?>>Standard</option>
    <option value="Gift_ID_Req" <?php if($row['gift_privacy']=='Gift_ID_Req') echo "selected='selected'"; ?>>Require program ID</option>
    <option value="Not_Enrolled" <?php if($row['gift_privacy']=='Not_Enrolled') echo "selected='selected'"; ?>>Do not enroll</option>
</select>
<input type="submit" value="submit">
</form>

Edit - The code differs slightly for the multiselect elements. The element names are followed by square brackets (i.e. name="notifications[]"), and values are inserted into the database as imploded arrays implode(',', $_POST['notifications']). Those commas are then stripped from fetched values in order to properly compare them to the option's values $row1 = str_replace(',', '', $row);
Existing Function
This function applies selected="selected" to the correct options, but it's too cumbersome for me to use with so many elements and I'm not sure how to modify the code so that it could be easily applied to all the select and/or multiselect elements. Also, since the page currently uses standard select elements with hard-coded options I'm hoping for a solution that doesn't require creating arrays for each element.
<select name="gift_privacy">
    <?php
    $gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll");
    $gift = $row['gift_privacy'];
    foreach($gifts as $key => $value) {
    if($key == $gift) {
        echo '<option selected="selected" value="'. $key .'">'. $value .'</option>';
    } else {
        echo '<option value="'. $key .'">'. $value .'</option>';
    }
    }
    ?>
</select>

A: I faced the same problem once and solved it by creating a function (or a class static method) to handle my option lists.
To print out your options you will have to cycle through them anyway, so while you cycle there is nothing bad in checking for each one if it must be the currently selected.
Just create a function like:
function printSelectOptions($dataArray, $currentSelection) {
    foreach ($dataArray as $key => $value) {
        echo '<option ' . (($key == $currentSelection) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
    }
}

Giving $dataArray as your key/value options array, and $currentSelection as the key of the selected option.
So in your code you will have just calls to this function, like:
<select id='mySelect' name='mySelect'>
    <?php echo printSelectOptions($gifts, $gift); ?>
</select>

This should do the work!
EDIT: Adding sample to work with select multiple...
<?php
$options = array(   1   =>  "Test 1",
                    2   =>  "Test 2",
                    3   =>  "Test 3");

$selected = array(1, 3);

function printSelectOptions($dataArray, $selectionArray) {
    foreach ($dataArray as $key => $value) {
        echo '<option ' . (in_array($key, $selectionArray) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
    }
}
?>

<select multiple>
    <?php echo printSelectOptions($options, $selected); ?>
</select>

The trick is passing the selected values as an array of keys, instead of a single key. In the sample I provided dummy arrays, but obviously you'll have to build yours from database... :)
EDIT: Select multi with arrays taken from the question...
<?php
$gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll");
$gift = array($row['gift_privacy']);

function printSelectOptions($dataArray, $selectionArray) {
    foreach ($dataArray as $key => $value) {
        echo '<option ' . (in_array($key, $selectionArray) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
    }
}
?>

<select multiple>
    <?php echo printSelectOptions($gifts, $gift); ?>
</select>

EDIT: Explode multiple selected values
If you have mutliple selected values as a comma separated string, you just have to explode it before passing to the function I provided...
$selectedOptionsArray = explode(',', $selectedOptionsString);

So the ending code will look like...
<?php
$gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll");
$gift = explode(',', $row['gift_privacy']);

function printSelectOptions($dataArray, $selectionArray) {
    foreach ($dataArray as $key => $value) {
        echo '<option ' . (in_array($key, $selectionArray) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
    }
}
?>

<select multiple>
    <?php echo printSelectOptions($gifts, $gift); ?>
</select>

A: You could use a function like this to simplify it:
<?php
function renderOption($key, $value, $current) {
    echo '<option value="' . $key . '"' . ($key == $current ? ' selected="selected"' : '') . '>' . $value. '</option>';
}
?>

<select name="gift_privacy">
    <?php
    $gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll");
    $gift = $row['gift_privacy'];
    foreach($gifts as $key => $value)
        renderOption($key, $value, $gift);
    ?>
</select>

A: Use simpler method:
<?php
 echo '<option '.($key == $gift ? 'selected="selected" ' : '').'value="'. $key .'">'. $value .'</option>';
?>

Edit: second option
 echo '<option '.selected_option($key, $gift).'value="'. $key .'">'. $value .'</option>';

 function selected_option($val1, $val2){
  if($val1 == $val2){
   return 'selected="selected" ';
  }else{
   return '';
  }
 }

A: There is nothing wrong with what you have, and this, or something very similar is the typical approach to this problem.
You would/could wrap it in an actual function, say print_select( $array, $selected ); which would/could print out the entire <select> including the select themselves.
The final code might be:
print_select( $gifts, $selected_gift );
print_select( $colors, $selected_color );
// etc


Q: Problems displaying content generated by php, wordpress build in IE Here's the site http://www.therustyzip.com/
I just can't seem to get it working at all

A: From the source of your page it can be seen that your problem start with:
<html> lang="en">

you need to change that to:
<html lang="en">


Q: Why is QCameraImageCapture saving an image to the hard drive? Part of an application I have written has the ability to capture pictures from the webcam. I am using a QCamera with a QCameraViewfinder to display the current view, and then when a shutter button is clicked, it snaps a picture with a QCameraImageCapture set to capture to buffer, then handles it from there. I have just discovered that it is also saving a copy of the image in the local Pictures folder. Why is this happening, and how can I stop it?

A: This is just my point of observation:
Based on the documentation, after you call capture, irrespective of destination location ( I mean CaptureToFile or CaptureToBuffer) the image is saved to a file.
note this statemet in below link: If an empty file is passed, the camera backend choses the default location and naming scheme for photos on the system.
http://doc.qt.io/qt-5/qcameraimagecapture.html#capture
The additional advantage with "CaptureToBuffer", your image is saved in some specified buffer format.
My wild guess, if at all they are not supporting ( as i am unable to find any offical information on it) only capture to buffer,
the reason could be,
the user is allowed to set the bufferformat using setBufferFormat. And the device may not support the buffer format (isCaptureDestinationSupported() is there to check it.). May be because of this they are saving to local pictures folder always.
If this saving is unavoidable by capture, and if your business strictly needs not to maintain those saved files, when your buffer is doing good, probably you can delete them in below slot.
QObject::connect(YOURCAMERACAPTUREOBJECT, SIGNAL(imageSaved), this,SLOT(saved(int id, const QString &fileName)));

void saved(int id, const QString &fileName)
{

//Delete the file by checking you have content in buffer.
//to check the buffer probably you can use "imageAvailable" signal

}

A: I believe that bug you are describing were in GStreamer camerabin plugin. When you look to https://code.qt.io/cgit/qt/qtmultimedia.git/tree/src/plugins/gstreamer/camerabin/camerabinsession.cpp?h=5.15#n587 m_imageFileName is setup independently on capture destination. File is saved by this filter then https://code.qt.io/cgit/qt/qtmultimedia.git/tree/src/plugins/gstreamer/mediacapture/qgstreamercapturesession.cpp?h=5.15#n404
edit: This bug seems to be fixed somehow in Qt 5.15.


Q: MissingSchemaError: Schema hasn't been registered for model "Blog" I am getting above error which I am stuck I am a beginner of mongodb, expressjs
My Index.js:

 const mongoose= require('mongoose')
 let modelspath ='./models'
fs.readdirSync(modelspath).forEach(function(file){
    if(~file.indexOf('.js'))
    console.log(file)
    require(modelspath +'/' + file) //if block checks weather file ending with .js ext
})

my controller file

const BlogModel = mongoose.model('Blog')
let testRoute = (req, res) =>
{
    console.log(req.params)
    res.send(req.params)
}

my model.blog.js file

const mongoose = require('mongoose')
const Schema = mongoose.Schema;
let blogSchema =new Schema(
    {
        blogId :{
            type: string,
            unique:true
        },

mongoose.model('Blog',blogSchema);

my routing file

const express =require('express')
//here we can find routees logic path
const control =require('./../controllers/controller')
let setRouter =(app) =>{
//here we are getting our logics and assigning for a Http verbs (get,post,put,del)
 app.get('/test/route/:param1/:param2',control.testRoute)
 app.get('/example',control.example)
//  app.post('/hello', control.postmethod)
}
module.exports={
    setRouter:setRouter
}

Can anyone help me out of this error


Q: Saving file to remote domain I'd like to host an uploading script on one server but have it store the uploaded files to a remote server.
Currently I have a script that saves to a writable folder on my server. This works fine, but when I change it to the absolute link (ie. "http://www.somedomain.com/uploads/" instead of "/uploads/") it says the folder is not writable. The permissions on the folder are 0777. Am I doing something wrong?
Eventually I would like to save the uploads to a remote server (ie. "http://www.someotherdomain.com/uploads/"). Any insights? How could I do this with password permissions to eliminate the potential for anybody to upload files to this folder?
Thanks in advance!

A: Following is an option:
Upload a file temporarily to your server. Once uploaded to localhost, use curl to upload the file to remote server.
For password protection you can use an access token which expires every 1 hour or so. Pass access_token as a variable with your upload request. Remote server verifies that access_token exists and has not expired before accepting the upload.
Set a username and password for the access. If access token does not exist or has expired use curl to post username and password to remote server, which will verify if username and password are valid and returns new access_token.

A: Try in via ftp
http://php.net/manual/de/book.ftp.php

A: I think I have ever experience this problem.  If I am not wrong to understand your issue, my issue is like this.  I create upload.php in server A and receive in server A too, let's say the file is receive.php (it works normally).  Then I upload the receive file (receive.php) to server B, and modify the upload.php in server A (which is the upload.php destination's is server B).
Is it the issue?  If the issue like this, it might be firewall issue.  But the server that I use both of them is centos.  What I do then is, I switch off selinux, and use firehol to adjust the firewall in my centos.  Then it's work fine.
Other option, you can still receive file in your server A.  Then in your receive you transfer the file via ftp to server B, but I think this need more effort to do.  Cause you need to adjust the ftp configuration (is it ftp, sftp, or sftp using pem / pkk).


Q: SCCM+ MS Office 2013 deployment This is a 2 part question.
Issue: I've created a script that executes the following scripts (in order) Officescrub10.vbs(created by microsoft), LyncRemove2010.vbs(i created), and Office2013Install.vbs script(silent install of 2013 via Microsoft). Right now it uses .txt  for flags to know when each part is done. Also it reboots/logs in as system user during install.
Problem: I found out I need to use SCCM to deploy script, instead of creating a GPO. I've never used SCCM (always a GPO).
Question:
1.) If I deployed masterdeploy2013.vbs via unc path, what would my best option via SCCM? How would I deploy the script via SCCM Server?
2.) The goal is to uninstall Office 2010 & then install 2013. Could I just do this via SCCM with out scripts?  I want simple but don't know how to make it simple via SCCM Server.
If I use SCCM can I create to deploy to a test user (single user) at 1st?
Thanks!

A: Well to deploy a script or application is the same in SCCM.  Assuming SCCM is already configured you need to setup your application files and deployment packages.  The wizards in SCCM are pretty straight forward with walking you thru the process.
However - you have multiple scripts you want to deploy and run in order.  You can either try to wrap those up into a single package or you you need to configure a task sequence to execute them.  I'm not a strong SCCM guy or I would provide you with Step by Step on it.
You may want to consider Microsoft guide on deploying O365 Office Pro Plus with SCCM here:  https://technet.microsoft.com/en-us/library/dn708063.aspx
You can first run your uninstaller script and then push out the ProPlus installation via the above guide.


Q: How does this print a reversed linked list How does this piece of code print a linked list reversed?  I'm pretty curious how the new list comes to this way.
class Empty:
    def __init__ (self):
        self.IsEmpty = True
Empty = Empty()

class Node:
    def __init__ (self,value,tail):
        self.IsEmpty = False
        self.value = value
        self.tail = tail

l = Node(1,Node(2,Node(3,Node(4,Empty))))

c = l
nl = Empty

while not l.IsEmpty:
    nl = Node(l.value,nl)
    l = l.tail

while not nl.IsEmpty:
    print(nl.value)
    nl = nl.tail

A: It doesn't print reversed, nl is built reversed:
while not l.IsEmpty:
    nl = Node(l.value,nl)
    l = l.tail

each new nl is the tail of the next one. So 1 is the tail for 2, and so on.

A: Think about what is happening in the first while loop. It builds a new list in reverse. We start with Empty. Then each iteration:
new_list = Node(l.current_value, Node(l.previous_value))

Where previous_value is the value encountered first while iterating through the original list. So, this could be expanded to:
Node(l.last_value, Node(l.second_to_last, Node(...Node(l.first_value, Empty)...)))

A: It builds a forwards list
l = Node(1,Node(2,Node(3,Node(4,Empty))))

Then builds a backwards list from that forwards list
nl = Empty

while not l.IsEmpty:
    nl = Node(l.value,nl)
    l = l.tail

Then prints that list out in order, which is the reverse of the first list.
This is a pretty convoluted way of doing things.  Better would be something recursive, like:
def printer(curr):
    if curr.isEmpty:
        return
    printer(curr.tail)
    print(curr.value)


Q: How can I edit Android-grabbed MP4 files in Virtualdub? Android's command adb shell screenrecord x.mp4 is supposed to produce MPEG-4 files. VirtualDub is supposed to support MPEG-4 files through the use of the FFInputDriver plugin.
The latter is true because I've been able to open this sample MP4 video in VirtualDub 1.10.4 with the plugin, so I'm questioning the former. Is Android's adb screenrecord function really producing MPEG-4? Why can't virtualdub read it?
The symptoms when opening the file in VirtualDub is that I only see the first frame. Clicking play does nothing. Attempting to convert it to another format does nothing.
Here is a sample video I have dumped from my Nexus 5 phone. It says .mp4 but I'm unsure.
My OS is Windows 10.0.10240


Q: Chrome extensions disable reopening of an extension created tab I couldn't find any similar question to this, but is it possible to create a new tab within chrome extension (using chrome.tabs.create) and then after closing it using the same extension prohibit user from reopening it using ctrl+shift+t or undo close tab command?

A: You can open an incognito tab; it will have the requested behavior.
I don't think you can clear session data, and simply clearing history does not prevent reopening.


Q: Printing Average Score for Unique ID's I have a table
id | playerID | score
1  |    1     | 100
2  |    1     | 155
3  |    5     | 132

etc..
What I want to do is get the Average 'score' for each unique playerID. I can get the DISTINCT playerIDs
SELECT DISTINCT
    playerID
FROM
    dbo.scores

and I can get the average of all scores,
SELECT
    AVG(score)
FROM
    dbo.scores

but I can't seem to figure out how to combine the two.

A: Use group by!
SELECT playerID, AVG(score) AS avg_score
FROM dbo.scores
GROUP BY playerID

A: The use of dbo suggests that you are using SQL Server.  SQL Server does an integer average of integer values, so the average of 0 and 1 is 0, not 0.5.
I would recommend:
SELECT s.playerID, AVG(10. * s.score) AS avg_score
FROM dbo.scores s
GROUP BY s.playerID


Q: Ubuntu 20.04 LTS - Intel Wireless/WiFi dropping in and out Summary of the problem:
Since upgrading from Ubuntu 19.04 to Ubuntu 20.04 LTS I notice in VOIP calls I was cutting in and out. I then noticed that this was happening regularly and the wifi was reauthenticating with the WAP.
Details and any research already conducted:
I ran the dmesg command to see if any diagnostic information was being logged for the problem and I could see the below:
$ dmesg -T | grep "wlp0s20f3\|iwlwifi"
[Sat May 16 23:00:43 2020] wlp0s20f3: disconnect from AP 90:02:18:6f:0e:be for new auth to 80:72:15:1c:c1:72
[Sat May 16 23:00:43 2020] wlp0s20f3: authenticate with 80:72:15:1c:c1:72
[Sat May 16 23:00:43 2020] wlp0s20f3: send auth to 80:72:15:1c:c1:72 (try 1/3)
[Sat May 16 23:00:43 2020] wlp0s20f3: authenticated
[Sat May 16 23:00:43 2020] wlp0s20f3: associate with 80:72:15:1c:c1:72 (try 1/3)
[Sat May 16 23:00:43 2020] wlp0s20f3: RX ReassocResp from 80:72:15:1c:c1:72 (capab=0x1411 status=0 aid=2)
[Sat May 16 23:00:43 2020] wlp0s20f3: associated
[Sat May 16 23:02:10 2020] iwlwifi 0000:00:14.3: Unhandled alg: 0x71b
[Sat May 16 23:02:11 2020] iwlwifi 0000:00:14.3: Unhandled alg: 0x71b
[Sat May 16 23:02:12 2020] iwlwifi 0000:00:14.3: Unhandled alg: 0x71b
[Sat May 16 23:02:13 2020] iwlwifi 0000:00:14.3: Unhandled alg: 0x71b
[Sat May 16 23:36:54 2020] wlp0s20f3: disconnect from AP 80:72:15:1c:c1:72 for new auth to 90:02:18:6f:0e:be
[Sat May 16 23:36:54 2020] wlp0s20f3: authenticate with 90:02:18:6f:0e:be
[Sat May 16 23:36:54 2020] wlp0s20f3: send auth to 90:02:18:6f:0e:be (try 1/3)
[Sat May 16 23:36:54 2020] wlp0s20f3: authenticated
[Sat May 16 23:36:54 2020] wlp0s20f3: associate with 90:02:18:6f:0e:be (try 1/3)
[Sat May 16 23:36:54 2020] wlp0s20f3: RX ReassocResp from 90:02:18:6f:0e:be (capab=0x1411 status=0 aid=2)

I am using an Intel Wireless controller.
$ lspci | grep Wireless
00:14.3 Network controller: Intel Corporation Cannon Point-LP CNVi [Wireless-AC] (rev 11)

Further information can be found at pastebin:
Wireless Diagnostic Script Output: Click Here
What I have already tried:
I have already tried the below:

*

*Try the proprietary driver vs the opensource driver (Made no difference).

*Forced the wireless card to only use the 2.4 band.

*Adjusted the power save settings for the wifi card to disable.

[connection]
wifi.powersave = 2

*Fresh install of Ubuntu 20.04 and installed all updates available.

I have already had a look at existing posts and they don't seem to be having the same problem as me so any help would be greatly appreciated, I have tried to provide as much information as I can but please let me know if I have missed anything.

A:
I was cutting in and out. I then noticed that this was happening
  regularly and the wifi was reauthenticating with the WAP.

I would expect no less! In reviewing your wireless diagnostic results, we see that you are connected to the access point SKYEBYCK. Your scan results show no less than eight instances of SKYEBYCK. We also see in the message log, evidence that your wireless is disconnecting from one instance to reconnect to another, looking for a better signal.
[15898.927207] wlp0s20f3: disconnect from AP <MAC 'SKYEBYCK' [AC8]> for new auth to <MAC 'SKYEBYCK' [AC11]>
[15898.940638] wlp0s20f3: authenticate with <MAC 'SKYEBYCK' [AC11]>
[15898.950051] wlp0s20f3: send auth to <MAC 'SKYEBYCK' [AC11]> (try 1/3)
[15898.994714] wlp0s20f3: authenticated
<snip>
[16996.211084] wlp0s20f3: associate with <MAC 'SKYEBYCK' [AC1]> (try 1/3)
[16996.223252] wlp0s20f3: RX ReassocResp from <MAC 'SKYEBYCK' [AC1]> (capab=0x1411 status=0 aid=1)
[16996.242642] wlp0s20f3: associated

In the diagnostic report, AC8, AC11 and AC1 are redactions of the MAC addresses for the access points.
I recommend that you bind Network Manager to the MAC address of the SKYEBYCK instance with the strongest signal strength. You can find it with:
sudo iwlist scan

Here is a post that describes the process:  Ubuntu connect drops. Worked for a while then started dropping again

A: I'm not affiliated with the  tlp software. I had a similar issue with my Inspiron 5759 laptop that has an Intel Wireless 3160 adapter that also uses the iwlwifi driver. I saw somewhere someone was saying it's a power issue, but they didn't elaborate a fix or anything. I installed TLP and am just using the default power profile and I haven't experienced issues since.
https://linrunner.de/tlp/


Q: running bash shell code in IPython notebook I am trying to run a code in jupyter notebook Python3 see below:
%% bash
rm rvd2.txt
rm rvd22.txt
 rm lsfdout.lsf

    cat wrench.txt | sed 's/[[:space:]]/\n/g' | sed 's/^[ \t]*//' |
 sed 's/[ \t]*$//' | \
 sed '/^$/d'| tr -cd '[:alnum:] [:space:]' >> rvd2.txt

 awk 'length>3'  < rvd2.txt > rvd22.txt

 cat rvd22.txt | sort | uniq -c | sort -nr | head -n 250 > lsfdout.lsf

The error I get is this,
 File "<ipython-input-33-7c6457f6d2eb>", line 2
  %% bash
   ^
  SyntaxError: invalid syntax

I am totally out of clue why this happens, as a multiline code is supposed to be using double percent sign before bash


Q: Java Packages and Subpackages printed in alphabetical order I need to get Packages and Subpackages of Java printed in alphabetical order. I did this:
import java.util.Arrays;
public class J0602 {
    public static void main (String args[]) {
    Package[] packs = Package.getPackages();
    String[] packageNames =new String[packs.length];
    int i=0;
    for (Package pack:packs){
        packageNames[i] = pack.getName();
        System.out.println(pack.getName());
        i++;
    }
    Arrays.sort(packageNames);
}

}
..but it doesn't work. Is there anything I'm missing about Packages? Why Arrays.sort(); doesn't work here?
Thank you in advance!

A: It could be because you are Sorting your array after you have printed out the elements.
Try arranging your code this way
Arrays.sort(packageNames);
for (Package pack:packs){
         System.out.println(pack.getName());
}

Alternatively you could Dump your array in a TreeSet and Iterate through it vis
tr
TreeSet<Package> packages = new TreeSet<Package>(Arrays.asList(packageNames));

then
for (Package pack:packages){
    System.out.println(pack.getName());
}

Note that this will remove duplicate packages from your array.


Q: ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:748) Estoy usando geopy en una aplicación Python 3.6y tengo que ejecutarla en una máquina anticuada que usa Windows 2012 Server. El problema surge cuando desde la aplicación se llama a esta librería (geopy) en este servidor, ya que devuelve el siguiente error:
File "C:\ServAPI\Util.py", line 12, in getLocation
location = geolocator.geocode(name)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\geopy\geocoders\osm.py", line 193, in geocode
self._call_geocoder(url, timeout=timeout), exactly_one
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\geopy\geocoders\base.py", line 171, in _call_geocoder
raise GeocoderServiceError(message)
geopy.exc.GeocoderServiceError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:748)

¿Álguien sabe cómo solucionar este error?
Gracias
UPDATE
El código que da el error es el siguiente:
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut
# Dado el nombre de una ciudad, devuelve sus coordenadas
def getLocation(name):
    geolocator = Nominatim()
    try:
        location = geolocator.geocode(name, timeout=5)
        return location
    except GeocoderTimedOut as e:
        print("Error: geocode failed on input %s with message %s" % (e.msg))

Además, cuando lo ejecuto en mi máquina local (Windows 10), funciona sin problemas (ya, lo se, suena a "en local me funciona", pero es la verdad)

A: Posiblemente, en win2012 esté anticuada la librería SSL. Prueba a indicarle explícitamente que el scheme sea http:
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut

# Dado el nombre de una ciudad, devuelve sus coordenadas
def getLocation(name):
    geolocator = Nominatim(scheme='http')
    try:
        location = geolocator.geocode(name, timeout=5)
        return location
    except GeocoderTimedOut as e:
        print("Error: geocode failed on input %s with message %s" % (e.msg))


Q: Show Image after choosing it from html form I am trying to show picture after choosing it from html form following this code:
http://jsfiddle.net/LvsYc/
and my code is:

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <meta name="description" content="">
  <meta name="author" content="">
  <link rel="icon" href="bootstrap/favicon.ico">

  <title>Image Test</title>
  <link href="bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

  <link href="bootstrap/signin.css" rel="stylesheet">

    <form id="form12" runat="server">
      <input type='file' id="imgInp" />

    </form>

But the chosen image is not shown. What am I doing wrong? It looks almost like the example above.


Q: Calculating Prediction Intervals for multistep univariate time series forecasting using Bootstrapping I understand the way to compute the prediction interval at 5% and 95% for one step forward forecast based on Bill's answer to the question at Bootstrap prediction interval. The idea being that based on the residuals in the time series using bootstrapping(replacement with sampling multiple times) one can construct the distribution at 5% and 95% percentiles for the first forecast point. What I am struggling to understand is how to calculate the prediction interval for the second point (and other points in the future thereafter). Based on the bootstrap distribution we get one value each of the 5% and 95% percentiles, and the residuals should be added over time
So,
e{5, t+1} = obtained from bootstrap distribution
e{5, t+2} = e{5, t+1} + e{5, t+1}
e{5, t+3} = e{5, t+1} + e{5, t+1} + e{5, t+1}

It will just end up giving a diverging cone with straight lines, and I feel I am missing something here. I am trying to find the prediction intervals solely based on the nature of residuals in historical data and the output that I have from a black-box forecast method. Would love some insights into this

A: You can refer to Forecasting: Principles and Practice - 3.5 Prediction Intervals (Hyndman and Athanasopoulos, 2018). In short, for each bootstrap sequence, you can sample from residuals to generate forecast for t+1; then you treat the forecast at t+1 as groundtruth and generate forecast for t+2 in the same way; repeat until you generate forecast for t+k (essentially generating forecast in an autoregressive fashion while bootstrapping residuals). After you obtained multiple bootstrap sequences until t+k, you can compute the empirical quantiles of the bootstrap forecasts at t+k to obtain desired prediction interval (e.g., 0.025 and 0.975 quantiles for 95% prediction interval).
The described bootstrap method doesn't consider uncertainty associated with parameter estimate or model misspecification. So the prediction interval is very likely to be too narrow and fail to cover 95% predictions in practice. For a better (and more computationally expensive) way to construct bootstrap prediction interval see Forecasting: Principles and Practice - 11.4 Bootstrapping and bagging


Q: Duplicate property '' for [simple type, on Deserialization I'm currently facing an issue using Jackson 2.4.4 with the xml module.
The XML I want to deserialize looks like this:
<product>
    <sku>1000668-1</sku>
    <name/>
    <image>/url/or/something.jpg</image>
    <brand>test</brand>
    <sizeCM>36 mm / 19.5 cm</sizeCM>
    <colors>
        <color id="335061" name="Green"/>
    </colors>
    <genders>
        <gender id="362843" name="M"/>
    </genders>
    <occasions>
        <occasion id="322620" name="First"/>
        <occasion id="322621" name="Second"/>
        <occasion id="322627" name="Thrid"/>
        <occasion id="322628" name="..."/>
        <occasion id="322630" name="next"/>
        <occasion id="369680" name="and again"/>
    </occasions>
    <categories>
        <category id="CGO_010_002" name="Stackoverflow"/>
    </categories>
</product>

And my Product Class looks like this:
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JacksonXmlRootElement(localName = "product")
@JsonPropertyOrder({ "sku", "image", "brand", "sizeCM", "colors", "genders",
        "occasions", "categories" })
public class Product {

    @JsonProperty("sku")
    @JacksonXmlText
    private String sku;

    @JsonProperty("image")
    @JacksonXmlText
    private String image;

    @JsonProperty("brand")
    @JacksonXmlText
    private String brand;

    @JsonProperty("sizeCM")
    @JacksonXmlText
    private String sizeCM;

    @JsonProperty("colors")
    @JacksonXmlProperty(localName = "colors")
    private Colors colors;

    @JsonProperty("genders")
    @JacksonXmlProperty(localName = "genders")
    private Genders genders;

    @JsonProperty("occasions")
    @JacksonXmlProperty(localName = "occasions")
    private Occasions occasions;

    @JsonProperty("categories")
    @JacksonXmlProperty(localName = "categories")
    private Categories categories;

    // setter & getter ...

Next step was to map it during reading it from a file:
public static void main(String[] args) {
    JacksonXmlModule module = new JacksonXmlModule();
    XmlMapper xmlMapper = new XmlMapper(module);
         xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    product(xmlMapper);
}

public static void product(XmlMapper xmlMapper){
    String s = "/tmp/product.xml";
    Product test = null;
    try {
        test = xmlMapper.readValue(new File(s), Product.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(test.getSku());
}

After trying it like that I facing this exception:
com.fasterxml.jackson.databind.JsonMappingException: Duplicate property '' for [simple type, class com.example.jackson.model.Product]
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:266)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:241)
at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationConexample.java:394)
at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:3169)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3062)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2115)
at com.example.jackson.main.TheMain.product(TheMain.java:32)
at com.example.jackson.main.TheMain.main(TheMain.java:23)

Next thing is - same Method - same ObjectMapper - another pojo + xml works fine (even the list's). Any Help or Hint wanted, I really don't know what I should do - because the exception Duplicate property '' isn't so great because the '' are really empty!

A: Solution for this was that I switched from @JacksonXmlTextto @JacksonXmlProperty. I misunderstood how @JacksonXmlTextshould be used.
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JacksonXmlRootElement(localName="product")
@JsonPropertyOrder({ "sku", "image", "brand", "sizeCM", "colors", "genders",
        "occasions", "categories" })
public class Product {

    @JsonProperty("sku")
    @JacksonXmlProperty(localName="sku")
    private String sku;

    @JsonProperty("image")
    @JacksonXmlProperty(localName="image")
    private String image;

    @JsonProperty("brand")
    @JacksonXmlProperty(localName="brand")
    private String brand;

    @JsonProperty("sizeCM")
    @JacksonXmlProperty(localName="sizeCM")
    private String sizeCM;

    @JsonProperty("colors")
    @JacksonXmlProperty(localName = "colors")
    @XmlElement(name="colors")
    private Colors colors;

Allowed me to parse the xml without any problem.


Q: union in c++ with a single non trivial type I have a simple struct that can carry either a result, or error, never both.
Both are the same type, but I want two members just for clarity.
From reading cppreference.com it looks like the following code snippet would be valid c++?
With a placement delete in the union destructor to tidy up the non trivial class (std::string in this instance).
struct Result {
  union {
    std::string resultText;
    std::string errorText;
    ~(){ resultText.~string();}
  };
};

It looks like, to use this, the containing struct would need to implement the rule-of-5 members to explicitly copy/move resultText.

A: A union is just going to decrease readability of your code. And depending on how you use it will increase maintenance too. Actually the fact that you mentioned "implementing the rule of 5" despite having a std::string member suggests that your class is going to be a nightmare to maintain.
I would look at these options (not enough detail in the question to determine what would be best):

*

*Use an exception. You can make a custom exception by deriving from std::exception

*Use Boost.Optional.
boost::optional<std::string> do_something() { ... };

std::string result = do_something().value_or("error!");


Q: Updating a Server Side Text File via Android I'm building an app that needs to periodically append lines to a server side text file. So far, the best way I've come up with for doing this is using the Dropbox API, where the user has to download the text file, update it, and then upload it back - obviously this is not ideal. What would be the best (free) way to do something like this? I'd like a solution where I don't have to personally host a server, but can use some third party cloud (like Dropbox).

A: Google's Android Backup Service seems appropriate for this, and is free.


Q: How to use XCode Distribute App Development Method when i archive and start to distribute my app in Xcode, there is 4 choice
App Store Connect, Ad Hoc, Enterprice and Development.
i've been wondering how to use the development method, i have upload all the file generated from the xcode to my site but it just return error "The server encountered something unexpected that didn't allow it to complete the request", of course i open the url using safari.
i also have check the box "include manifest for over the air installation" but i have no idea how to use this. most tutorial is only upload to app store or ad hoc. just wondering how this development thingy work
Is there any addition work to do this?


Q: CDI Injection into a Servlet not working I have a Controller with a producer.
@Named
@SessionScoped
public class UserController{

    private User user;

    //other methods

    @Produces
    @User
    public User produceUser() {
        return user;
    }
}

If I inject the user into a Servlet, I get always the same user(I compared the object IDs) - also in different sessions. If I inject the User in a CDI Bean, it's working and I get the user of the current session.

A: UserController is session-scoped, but the producer is not. I.e. the producer has @Dependent scope, so the User bean gets injected once when the servlet is initialized.
Try adding @SessionScoped to your producer method.


Q: Setting global array from inside readFile I'm probably missing something simple here, but for some reason, when I set an array's value from inside a function, I can no longer read that array once outside of that function.
    var threadArray = [];

    function getThreads() {
      var fs = require('fs');
      // read list of threads
      fs.readFile('./database/threadList.txt', function(err, data) {
        var threadIds = data.toString().split("\n");
        for(i in threadIds) { threadArray[i] = threadIds[i].split(","); }
        console.log("This works: " + threadArray[0])
      })
      console.log("This does not work: " + threadArray[0] + " Returns [undefined]")
    }

What am I missing here? I'm assuming something to do with the way I declared the array?

A: This is a timing issue. fs.readFile is an asynchronous operation - your second console.log that doesn't work is getting processed immediately after fs.readFile starts running and your threadArray is not yet populated. You can use fs.readFileSync instead
try {
  var threads = fs.readFileSync('./database/threadList.txt');
  var threadIds = threads.toString().split('\n');
  for(i in threadIds) {
     threadArray[i] = threadIds[i].split(",");
  }
  console.log("This works: " + threadArray[0]);
} catch (e) {
  console.error("Error reading file: ", e);
}


Q: Responsive image shrink I have somewhat of a dilemma right now with responsive images. Right now, the amount of images shown per pixel is correct, however the images seem to shrink tremendously. Is there something I can do to fix this?

img {
  max-width: 200%;
  height: auto;
  margin: 0 0 10px 0;
}

/* Section Inner */

div.section-inner {
  max-width: 1100px;
  height: auto padding: 0 75px;
  margin: 0 auto;
}

/* Body Content */

div.body-content {
  padding: 50px 0;
  background-color: #FFF;
}

/* Thirds */

div.thirds {
  padding-bottom: 50px;
}

div.one-third {
  width: 15%;
  float: left;
  margin-right: 5%;
}

div.one-third-last {
  margin: 0;
}

@media screen and (max-width: 1000px) {
  div.one-third {
    width: 30%;
  }
  div.one-third-second {
    margin: 0;
  }
  div.one-third-last {
    margin: 0;
  }
  img {
    width: 100%;
    height: auto;
  }
}

div.nav ul li {
  width: 25%;
  border-bottom: 1px solid #bababa;
}

@media screen and (max-width: 600px) {
  div.nav ul li {
    width: 33%;
  }
  div.one-third {
    width: 50%;
    margin: 0;
  }
  div.one-third-second {
    margin: 0;
  }
}

@media screen and (max-width: 500px) {
  div.nav ul li {
    width: 33%;
  }
  div.one-third {
    width: 33%;
    margin: 0;
  }
  div.one-third-second {
    margin: 0;
  }
}

Chinese_Dragon

Gringotts_dragon

Hydra

Ice_dragon

The "I_Hate_Mondays" Dragon

Sassy_Dragon