text:
Q: The delete view doesn't erase the correspondent object I'm developing the backend of my personal blog and I've create a view that delete a single tag of the post.
views.py
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.text import slugify

from .forms import BlogTagForm
from .models import BlogTag

def deleteBlogTag(request, slug_tag):
    if request.method == 'POST':
        tag = BlogTag.objects.get(slug_tag=slug_tag)
        tag.delete()
    return redirect('tag_list')

models.py
from django.db import models
from django.urls import reverse

class BlogTag(models.Model):
    tag_name = models.CharField(
        'Tag',
        max_length=50,
        help_text="Every key concept must be not longer then 50 characters",
        unique=True,
        )
    slug_tag = models.SlugField(
        'Slug',
        unique=True,
        help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents",
        )

    def __str__(self):
        return self.tag_name

    def get_absolute_url(self):
        return reverse("single_blogtag", kwargs={"slug_tag": self.slug_tag})

    class Meta:
        ordering = ['tag_name']

urls.py
path("tags/", views.listTagAdmin, name='tag_list_admin'),
path("create-tag/", views.createBlogTag, name='create_tag'),
path("update-tag/<str:slug_tag>/", views.updateBlogTag, name='update_tag'),
path("delete-tag/<str:slug_tag>/", views.deleteBlogTag, name='delete_tag'),

tag_list.html

Tag List

        Tag
        Related Posts
        Actions

      {% for tag in tag_list %}

        {{ tag.tag_name }}
        {{ tag.tag_blogpost.count }}

            Update

            <button class="btn btn-danger btn-sm mx-1" type="button" data-toggle="modal" data-target="#deleteModal">Delete</button>

Delete Request

Are you sure to delete this tag?

{{ tag.tag_name }}

                    <button type="button" class="btn btn-primary btn-sm" data-dismiss="modal">No, don't do this</button>
                    <form action="{% url 'delete_tag' slug_tag=tag.slug_tag %}" method="POST">
                      {% csrf_token %}
                      <button class="btn btn-danger btn-sm" type="submit" name="button">Yes, delete it</button>
                    </form>

      {% endfor %}

The problem is that it's not possible to delete every single objects of the list but only the first object. Even if I try to delete the last object I delete the first object instead of the last.
Where I've wrong?

A: All your modal forms are named the same, hence it will pick one. If it searches for a specific id, it will pick one. In order to solve this, you should give your modals different ids:

      {% for tag in tag_list %}

        {{ tag.tag_name }}
        {{ tag.tag_blogpost.count }}

            Update

            <button data-target="#deleteModal{{ tag.pk }}" class="btn btn-danger btn-sm mx-1" type="button" data-toggle="modal">Delete</button>

Delete Request

Are you sure to delete this tag?

{{ tag.tag_name }}

                    <button type="button" class="btn btn-primary btn-sm" data-dismiss="modal">No, don't do this</button>
                    <form action="{% url 'delete_tag' slug_tag=tag.slug_tag %}" method="POST">
                      {% csrf_token %}
                      <button class="btn btn-danger btn-sm" type="submit" name="button">Yes, delete it</button>
                    </form>

So here we added a suffix to the id of the
, and used the same id in the <button target="#deleteModal{{ tag.pk }}" ...>.


text:
Q: How do I count the number of characters entered using MIPS? I prompt the user to enter a string of up to 40 characters. How do I count how many characters the user entered? As I count each character, I need to store the count of digits, uppercase and lowercase letters, spaces, and any other characters. How should I recognize the difference between these types of characters?
.text                # beginning of code
.globl main          # beginning of main

main:                # main procedure
   li  $v0, 4        # print_string service number
   la  $a0, prompt00 # load address of prompt
   syscall           # print prompt

   li  $v0, 8        # read_string service number
   la  $a0, buffer   # load address of buffer
   la  $a1, 40       # max length of 40
   syscall           # read_string

   li $v0, 4         # print_string service number
   la $a0, buffer    # load address of buffer
   syscall           # print buffer

   li  $v0, 10       # using service 10, terminate
   syscall           # terminate

.data                # beginning of data area

   buffer:           # container for input string
      .space  40     # max length of 40 characters
   newline:          # variable to represent a newline
      .asciiz "\n"   # a newline character

   prompt00: .asciiz "Enter up to 40 characters: "

A: You can check to see if the character in the register you are looking at falls within any of the applicable ranges: ASCII Values Table.
Strings should be stored with a null character '\0' at the end, so you can look for that to find the length.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deploying the java web application. some listenerStart error I have the next problem:
I am trying to deploy an application on my Tomcat 7.0 with jre 6.0...I created a servlet called ListenerTester:
    package com.example;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

class ListenerTester extends HttpServlet {

    public void doGet (HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

            response.setContentType("text/html");
            PrintWriter out = response.getWriter();

            out.println("text context attributes set by listener
");
            out.println("
");

            Dog dog = (Dog) getServletContext().getAttribute("dog");

            out.println("The dog`s breed is: " + dog.getBreed());

        }

    }

Class dog is a simple class which has only one field String breed and getter and Constructor with the parameter.
Next class is the MyServletContextListener:
   package com.example;

import javax.servlet.*;

class MyServletContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent e) {

        ServletContext sc = e.getServletContext();

        String dogBreed = sc.getInitParameter("breed");
        Dog f = new Dog(dogBreed);
        sc.setAttribute("dog", f);

    }

    public void contextDestroyed(ServletContextEvent e) {

    }

}

they are in the package called com.example. The top folder of the application is listenerTester.
web.xml:
    <?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0" >

<servlet>
    <servlet-name>ListenerTester</servlet-name>
    <servlet-class>com.example.ListenerTester</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>ListenerTester</servlet-name>
    <url-pattern>/ListenTest.do</url-pattern>
</servlet-mapping>

<context-param>
    <param-name>breed</param-name>
    <param-value>Sparky</param-value>
</context-param>

<listener>
    <listener-class>com.example.MyServletContextListener</listener-class>
</listener>
</web-app>

The problem is the next - when I try to run it - the browser does not show anything...at all..no mistake or anything.
When I look inside the catalina log file:

    08.11.2011 0:23:56 org.apache.coyote.AbstractProtocolHandler init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
08.11.2011 0:23:56 org.apache.coyote.AbstractProtocolHandler init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
08.11.2011 0:23:56 org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 331 ms
08.11.2011 0:23:56 org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
08.11.2011 0:23:56 org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.8
08.11.2011 0:23:56 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory listenerTest
08.11.2011 0:23:56 org.apache.catalina.core.StandardContext startInternal
**SEVERE**: Error listenerStart
08.11.2011 0:23:56 org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/listenerTest] startup failed due to previous errors
08.11.2011 0:23:56 org.apache.coyote.AbstractProtocolHandler start
INFO: Starting ProtocolHandler ["http-bio-8080"]
08.11.2011 0:23:56 org.apache.coyote.AbstractProtocolHandler start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
08.11.2011 0:23:56 org.apache.catalina.startup.Catalina start
INFO: Server startup in 233 ms

Could you please tell me what to do and what the mistake is? What is a listenerStart?

A: You should have your classes public instead of package-private.


text:
Q: What does std::ofstream::close() actually do? This question: How to protect log from application crash? has lead me to another - what does std::ofstream::close() actually do? I know it calls flush() and that's one thing. But what else? What closing the file actually is?
Edit:
Let me rephrase my question - is anything physically done to the actual file during the call to close() or is it just std::ofstream internal cleanup stuff?

A: Other than flushing the userspace buffers, i.e. flush(), close(2) is called on the underlying file-descriptor. It depends on the operating system what happens then, but most likely nothing happens to the actual storage occupied by the file.
What will happen is that the (if the file descriptor was the last reference in that process to that file) file entry associated with the file gets removed from the open-file table of the process. I.e. freeing process-associated kernel-memory.

A: Here is the trace of calls from documentation:

void std::basic_ofstream::close();

Effectively calls rdbuf()->close(). If an error occurs during operation, setstate(failbit) is called.

std::basic_streambuf<CharT,Traits>* std::basic_ofstream::rdbuf() const;

Returns the associated stream buffer. If there is no associated stream buffer, returns NULL.

std::basic_streambuf actually inherits std::basic_filebuf, therefore:

std::basic_filebuf<CharT, Traits>* std::basic_filebuf::close();

If a put area exist (e.g. file was opened for writing), first calls overflow(Traits::eof()) to write all pending output to the file, including any unshift sequences.
If the most recently called function, out of underflow(), overflow(), seekpos(), and seekoff(), was overflow(), then calls std::codecvt::unshift(), perhaps multiple times, to determine the unshift sequence according to the imbued locale, and writes that sequence to file with overflow(Traits::eof()).
Then, closes the file as if by calling std::fclose, regardless of whether any of the preceding calls succeeded or failed.
NOTE: close() is typically called through the destructor of std::basic_filebuf (which, in turn, is typically called by the destructor of std::basic_fstream.

First of all, we can see that it doesn't actually call flush() directly as you expected. Nevertheless, the flushing effect indeed occurs in the std::basic_filebuf::close() method. In addition, we can see that it still does a bit of tampering with a file, i.e. writing the unshift sequence. Nothing else special happens then, the file simply closes.
Pay attention to the NOTE above: in most cases you don't even need to call std::basic_ofstream::close() explicitly.

A: Closes the file currently associated with the object, disassociating it from the stream.
Any pending output sequence is written to the file.
If the stream is currently not associated with any file (i.e., no file has successfully been open with it), calling this function fails.
The file association of a stream is kept by its internal stream buffer:
Internally, the function calls rdbuf()->close(), and sets failbit in case of failure.
Note that any open file is automatically closed when the ofstream object is destroyed.
From: http://www.cplusplus.com/reference/fstream/ofstream/close/


text:
Q: Burning DVD's to Micro SD card on Win 7: I am running Windows 7 with WMP. I have DVD's I want convert to MP4's so I can view them on a mobile device. The mobile device uses Micro SD cards.
I cannot seem to get WMP to burn directly to the Micro SD card - have to burn to a DVD disk (2 required for my content), then copy the files from the DVD disk to the Micro SD card - very time consuming.
How can I shortcut this process and burn directly to the Micro SD card? (which has plenty of capacity)

A: On the heals of Huskekn, go great DVDFab (rip dvd) and Handbrake (convert to mp4. or appleTV 3 preset). They work great!! Convert to MP4, mount your SD, copy and away you go. I do this a lot for my kidos.


text:
Q: Add a second featured image and field name, later display it before add to cart button I'm building a property buying and selling site for agents using wordpress and woocommerce.
I'm using the oceanwp theme.
The targets is to show the agent's photo and name before the add to cart button.
(button has been changed to whatsapp and tel contact).
What I've tried to do :

*

*Add product attributes which contain photo link addresses from each agent.

*Adding product attributes containing the name of each agent.
The code snippet I use is as follows :
add_action('woocommerce_before_add_to_cart_button','misha_before_add_to_cart_btn' );

function misha_before_add_to_cart_btn(){
global $product;

$photo_val = $product->get_attribute('pa_photo');

print '';

$agent_val = $product->get_attribute('pa_agent');

echo "
".$agent_val."
";

}

The display is exactly what I wanted. (See)
But I noticed this method is less effective because it has to do many steps to achieve it.
So I thought, is there a way to add a custom photo (upload) and name (input) for the agent in the admin panel which is automatically displayed before the add to cart button without using an additional plugin?
Example of the desired view on the admin panel (see)
Example of the desired display on single product page (see)

How can I achieve that?
Any help will be greatly appreciated.

A: You can use this action hook woocommerce_before_add_to_cart_button to add any content just before add to cart button on a single product page.
Sample code that can go in your functions.php if you are editing a theme:
add_action( 'woocommerce_before_add_to_cart_button', 'content_before_addtocart' );

function content_before_addtocart() {
        echo '';
}


text:
Q: Typescript error compiling Aurelia with Intellij Idea Using IntelliJ Idea 2016.2 I'm encountering this error typing to compile an aurelia project generated with
aurelia_project/generators/binding-behavior.ts(2,52): error TS2307: Cannot find module 'aurelia-cli'.

aurelia cli is plainly in node_modules for both local and global. Given the path should this file even compile? perhaps it should be ignored?
if I understand tsconfig and my idea settings, these shouldn't even be built
{
  "compileOnSave": false,
  "compilerOptions": {
    "sourceMap": true,
    "target": "es5",
    "module": "amd",
    "declaration": false,
    "noImplicitAny": false,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "lib": ["es2015", "dom"]
  },
  "exclude": [
    "node_modules"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "./test/**/*.ts",
    "./typings/index.d.ts",
    "./custom_typings/**/*.d.ts"
  ],
  "atom": {
    "rewriteTsconfig": false
  }
}

au run --watch starts fine
How can I fix this issue so that Idea can build the project without errors?

A: Your will get the same issue when running the compiler in terminal - neither Idea (https://youtrack.jetbrains.com/issue/WEB-17991) not tsc itself support filesGlob, this is atom-specific option. So all files are compiled. And, as no .d.ts for  'aurelia-cli' can be found in the project, compiler errors are reported.
to work out the issue, you can either change the tsconfig.json to make sure that only need files are compiled, or disable TypeScript compiler and use aurelia to build your project

A: Add generators folder to exclude list - that folder is used internally by Aurelia CLI(if i remember correctly).
"exclude": [
  "node_modules",
  "aurelia_project"
],


text:
Q: Kafka Producer fails when one broker down We have a 3 node kafka(0.10.2.0) cluster + 3 node ZK(zookeeper-3.4.10) cluster. There are some 80 topics each having 10 partitions and 2 replication factor.
Each Producer is given list of all 3 brokers and each consumer is given list of all 3 zookeeper nodes.
Zookeeper properties:
initLimit=10
syncLimit=5
# disable the per-ip limit on the number of connections since this is a non-production config
maxClientCnxns=3000

# Auto purge feature keeps this ammount of most recent snapshots and the corresponding transaction logs
autopurge.snapRetainCount=3
# The time interval in hours for which the purge task has to be triggered
autopurge.purgeInterval=1
tickTime=2000

# minimum session timeout in milliseconds that the server will allow the client to negotiate.
minSessionTimeout=4000

# maximum session timeout in milliseconds that the server will allow the client to negotiate.
maxSessionTimeout=30000

kafka properties:
log.retention.check.interval.ms=300000
log.segment.bytes=1073741824
log.retention.bytes=10737418240
log.retention.hours=24
num.recovery.threads.per.data.dir=1
default.replication.factor=2
num.partitions=10
log.dirs=<PATH>
socket.request.max.bytes=104857600
socket.receive.buffer.bytes=102400
socket.send.buffer.bytes=102400
num.io.threads=8
num.network.threads=3
broker.id=<ID>
zookeeper.connect=<IPS>
# Timeout in ms for connecting to zookeeper
zookeeper.connection.timeout.ms=6000
delete.topic.enable=true

Producer configs:
compression.type: gzip
retries: 3
metadata.max.age.ms: 500

Consumer configs:
max.partition.fetch.bytes: 5242880
session.timeout.ms: 15000
heartbeat.interval.ms: 5000
enable.auto.commit: true
metadata.max.age.ms: 500

The developers are using reactor-kafka (I don't have much knowledge of it)
We have Kafka hosted on AWS EC2 instances with auto-scaling. When I terminate a broker instance, the producer gives following error:
java.util.concurrent.TimeoutException
    at reactor.core.publisher.FluxTimeout$TimeoutMainSubscriber.handleTimeout(FluxTimeout.java:259)
    at reactor.core.publisher.FluxTimeout$TimeoutMainSubscriber.doTimeout(FluxTimeout.java:243)
    at reactor.core.publisher.FluxTimeout$TimeoutTimeoutSubscriber.onNext(FluxTimeout.java:360)
    at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:72)
    at reactor.core.publisher.MonoDelay$MonoDelayRunnable.run(MonoDelay.java:107)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

When the broker is auto started(within 3-4 minutes), the producer keeps working again.
PS: Each broker in a cluster is assigned reserved IPs and hence when it is auto-started, it has same IP and broker.id. The same EBS volume is attached when a broker is restarted so all the partitions are there already when it comes up.
Any help would be appreciated.


text:
Q: TikZ-cd Diagrams Side-by-Side I have two diagrams – drawn in TikZ-cd – which I'd like to have side-by-side. However, even though I haven't left a blank line between the code for the two diagrams, they still appear above/below one another.
Here's a MWE:
\documentclass[12pt]{article}

\usepackage[margin=20mm]{geometry} %changes margins
\usepackage{mathrsfs} % fancy maths latters
\usepackage{amsmath} %improves equation environment

\usepackage{tikz-cd} %diagrams

\usepackage{subcaption} %side by side diagrams
\usepackage{caption} %customises captions

\title{Side-by-Side Diagrams MWE}

\begin{document}

\maketitle

Here are two diagrams that I would like to have side-by-side:

\begin{figure}[h!]
    \centering
    \begin{tikzcd}[column sep=small]
    \mathscr{L}_{1} &  & \mathscr{L}_{2}\\
    & p_{1} \arrow[lu] \arrow[ru] &\\
    & \text{Argument} \arrow[u] &\\
    \end{tikzcd} \caption{Many-one pluralism.}
    \begin{tikzcd}[column sep=small]
    \mathscr{L}_{1} &  & \mathscr{L}_{2}\\
    p_{1} \arrow[u] &  & p_{2} \arrow[u]\\
    & \text{Argument} \arrow[lu] \arrow[ru] &\\
    \end{tikzcd} \caption{One-many pluralism.}
\end{figure}

\end{document}

Which outputs:

I've also tried using mini-pages, sub-floats (e.g. Two diagrams side by side), and the subcaption package (e.g. Placing TikZ drawings in a minipage side by side) to solve the problem, but in each case I get loads of errors... (Maybe these packages are compatible with TikZ but not  TikZ-cd?) Thanks for your help!

A: You can have it with  floatrow, if you enable the replacement of & with \&:
\documentclass[12pt]{article}

\usepackage[margin=20mm]{geometry} %changes margins
\usepackage{mathrsfs} % fancy maths latters
\usepackage{amsmath} %improves equation environment
\usepackage{tikz-cd} %diagrams

\usepackage{subcaption} %side by side diagrams
\usepackage{caption} %customises captions
\usepackage{floatrow}
\title{Side-by-Side Diagrams MWE}
\author{I. Ego}
\begin{document}

\maketitle

Here are two diagrams that I would like to have side-by-side:

\begin{figure}[h!]
    \tikzset{column sep=small, ampersand replacement=\&}
\begin{floatrow}
    \centering
    \ffigbox{\begin{tikzcd}
    \mathscr{L}_{1} \& \& \mathscr{L}_{2}\\
    \& p_{1} \arrow[lu] \arrow[ru] \&\\
    \& \text{Argument} \arrow[u] \&\\
    \end{tikzcd}}{\caption{Many-one pluralism.}}
    \ffigbox{\begin{tikzcd}
    \mathscr{L}_{1}\& \& \mathscr{L}_{2}\\
    p_{1} \arrow[u] \& \& p_{2} \arrow[u]\\
    \& \text{Argument} \arrow[lu] \arrow[ru] \&\\
    \end{tikzcd}}{\caption{One-many pluralism.}}
    \end{floatrow}
\end{figure}

\end{document}


text:
Q: SSRS Report - Dynamic Parameters causing awful slowness I've built an SSRS Report with a series of parameters and data sets a user specifies a season (first parameter). There are several data sets -- see below.
The first is a procedure: called LRP_Weekly_Stats returns 9 fields (including, location, eventdata, option, season, and a few others.
The second data set pulls - all the distinct seasons from a view - that gets sent to the parameter drop down. select distinct season from myview it shows/returns just season.
2 additional data set exists it reads
select distinct location from myview where my season = parameter season

and
 select distinct option from myview where my season = parameter season

each of these data sets return location and option respectively.

We can't build this as 1 single data set because each of the 5 locations has each of the 4 options associated with and the data being returned gets multiplied by itself.
Data in my view looks like this
Location         option
-------------------------
Location1        option1
Location1        option2
Location1        option3
Location1        option4
Location1        option5
Location2        option1
Location2        option2
Location2        option3
Location2        option4
Location3        option1
Location3        option2
Location3        option4
Location3        option5
etc.

In order for the parameters to show each location once and each option 1 for the parameter drop down we do two separate queries.
I didn't build the view and can't adjust it and even if i could the data is such that each location can have each option.
so my two data sets each return the distinct list of possible locations and/or options by season.
in the parameters in the SSRS report the set up looks like this:

so the data coming in to my parameter is pulled from my data set. for each of the three parameters. location and option_1 and option_2. The code itself runs in under 5 seconds however because of all this linkage it takes a good 30+ minutes to run the report. This is completely unacceptable (and I can't remove the drop down data because the users need it).
Any advice about how to streamline this or make it more efficient. Please help.

A: Based on your reply in the comments on your initial question, it looks to me like the issue is either in the report procedure itself, or possibly a rendering issue.  I would look at performance tuning the main report queries.  And I'm afraid I can't be more specific than that without knowing a lot more details about your report's architecture.


text:
Q: sidebar WITH SIDE MARGIN with pure CSS? It's easy to create a simple sidebar with pure CSS:
#page-wrap {
    position: relative;
    margin: 0 auto;
    max-width: 600px;
}

#content {
    margin-right: 200px;
}

#sidebar {
    width: 190px;
    position: fixed;
    right: 0;
    height: 100vh;
}

The problem with this solution is that the #sidebar (red) sticks to the window and leaves a huge gap to the #content (yellow) if the window becomes large:

How can we solve this, i.e. how can we make that gap be added to the right of the sidebar instead to the left when the window width growths? Here is how we can solve this we JQuery:
#sidebar {
    width: 190px;
    position: absolute;
    right: 0;
    height: 100vh;
}

function updateSidebar(sidebar) {
    sidebar.css('top', $(window).scrollTop());
    sidebar.css('height', $(window).height() -
        sidebar[0].getBoundingClientRect().top);
}

updateSidebar($('#sidebar'));
$(window).on('scroll', function() {
    updateSidebar($('#sidebar'))
});

Is it possible to achieve the same wihthout JavaScript, i.e. with pure CSS?

A: I think you're looking for calc().
In your example, since #page-wrap and #sidebar have fixed widths, you can make the sidebar stick to the right border of the page wrap by setting
left: calc(50% + 110px);

The 110px is the result of 600px / 2 - 190px.
[ Updated fiddle ]

A: There is a simple explanation to that. A position:Fixed element needs to be positioned by XY axis from screen, and not from his relative parent. The element is positioned at zero pixel from right of the viewport.
The best solution is change to absolute, but maybe you don't want this behaviour.
Maybe you need to research about sticky positioned elements:
http://www.sitepoint.com/css-position-sticky-introduction-polyfills/


text:
Q: In a logistic regression, is the odds ratio for one variable biased by the presence of covariates? I'm trying to sort out an inconsistency in some data I have. I'm comparing a binarized cannabis use variable (yes/no within the last 60 days) between college kids in two states. 22.6% of kids in state A have smoked up recently, compared to 57.9% of kids in state B. Calculating an odds ratio from just these stats, I wind up with
(.579/.421) / (.226/.774) = 4.710
I've also run a logistic regression with cannabis use as the dv and state + demographics (age, race, ethnicity, etc.) as covarying IVs. Only my State variable has a significant effect there, but when I calculate the odds ratio from its coefficient I get
e^1.79 = 5.989
I feel like this suggests I've made some error in building my regression --- is it really possible that the presence of all these nonsignificant covariates would bias the OR this much? Or am I just wrong in assuming these two values should be very similar?

A: I think there are two issues here.
First, I think you should expect the odds ratio from a logit model with additional covariates to be different from the bivariate odds ratio, even if none of the covariates are significant. Remember that "not significant" (which I assume means "not significant at the 95% level) doesn't mean that the covariates have NO relationship with the dependent variable, just that the relationship isn't strong enough to be detected at a given level of confidence. So the presence of even non-significant covariates will impact the estimate of the adjusted odds ratio for "state"  by some amount.
Second, remember that odds ratios can only be meaningfully compared on a logarithmic scale. The difference between two ORs gets less important the bigger they are and any OR bigger than 3 is already so huge that the difference between an OR of 4.7 and 5.9 isn't that big of a difference. In your case the log of the odds is only going from 1.5 to 1.8 and if you check out the confidence interval around the coefficient from the logit model, it might even include 1.5 (which corresponds to the bivariate odds ratio), in which case you can't even say that the two odds ratios ARE different at the 95% level.
Anyways, both results are telling you substantively the same story. So no need to worry.
(PS: one thing to always remember when working with odds ratios is that very few people (even in the stats world) have any intuitive idea of what "the odds were 4 times as high" actually means. So if you want an intuitive sense of how "big" this effect is, in terms of changes in probability, then you will need to do some extra work to get that from the logit model - calculating average marginal effects or something)


text:
Q: Set theory. What are the best interpretations of a countable set. tldr: What are the set theory interpretations?
In science we have formalism (Schrodinger equation) and interpretations:

*

*Copenhagen

*Many-worlds interpretation

*Transactional interpretation of quantum mechanics

My colleague and I might believe different interpretations (and argue about it), but our results of the calculation are the same as long as we accept the same formalism.
Likewise there is a set theory formalism (e.i. ZFC axioms). I understand the formalism and can answer exam questions (just derive your answer from ZFC). But the only interpretation I know is the "infinite number of mathematicians in an hotel with infinite number of booked rooms".  And this interpretation doesn't feel right.
Are there better alternative interpretations for a set theory?

Update: I see there is uncertainty on what I am asking about. Well the question is this. When you are teaching set theory you can go for formal definitions of ZFC with formal derivation of results. Or, you can employ the "infinite mathematicians in infinitely sized hotel". Are there other models of teaching set theory?

A: Actually I just wanted to make it a comment, but a become a bit to long and maybe it even worth an answer:
I guess you are talking about Hilbert's hotel here, but that really is just to show how "unintuitive" infinity can become, especially when talking about countable sets because one maybe feels like to understand why the natural numbers are infinite but why they really should be the "same amount" as for example the rational numbers is quite baffling.
I think on thing to keep in mind here, is that this is mathematics and similar to your argument with quantum mechanics (where for daily life it doesn't matter what you think you are "actually" calculating) even more so this true for mathematics. And while as a physicist it is not unlikely that someone comes up to you and ask you about how finally to think about this wave function or space time or whatever, it is more than unlikely than anyone asks, what really is $\pi$? Or $0$. Sure we will say $0 := \emptyset$ and then define all natural numbers and then define the integers and then define rational numbers and finally $\pi$ is a map of a equivalence class of some Cauchy sequence of equivalence classes of rational numbers which are equivalence classes $\dots$. But of course on can wonder, that is super technical and even though it is consistent with modern set theory, it really doesn't answer at all "What is $\pi$?" And does it really exists? Maybe in a different "meta"physical world $\dots$.
From my (not so super vast) experience most mathematician don't care to much for these question or at least do not discuss them. And again very much different to physics it really wouldn't even make that big of a difference. Where as an Interpretation of QM really is of fundamental importance to not so few people.
Not sure if this addresses you question. But in conclusion I am pretty sure the approach is the former one with (depending on the teacher) some few heuristic arguments. After all setting up things rigorous and derive results is what mathematics is about, isn't?


text:
Q: Pyspark: Concatenating values into lists within certain time range I have a pyspark dataframe that contains id, timestamp and value column. I am trying to create a dataframe that first groups rows with the same id, then separate the ones that are, say longer than 2 weeks apart and finally concatenate their value into a list.
I have already tried to use rangeBetween() Window function. It doesn't quite deliver what I want. I think the code below illutrates my question better:
My dataframe sdf:
+---+-------------------------+-----+
|id |tts                      |value|
+---+-------------------------+-----+
|0  |2019-01-01T00:00:00+00:00|a    |
|0  |2019-01-02T00:00:00+00:00|b    |
|0  |2019-01-20T00:00:00+00:00|c    |
|0  |2019-01-25T00:00:00+00:00|d    |
|1  |2019-01-02T00:00:00+00:00|a    |
|1  |2019-01-29T00:00:00+00:00|b    |
|2  |2019-01-01T00:00:00+00:00|a    |
|2  |2019-01-30T00:00:00+00:00|b    |
|2  |2019-02-02T00:00:00+00:00|c    |
+---+-------------------------+-----+

My approach:
from pyspark.sql.window import Window
from pyspark.sql import functions as F

DAY_SECS = 3600 * 24
w_spec = Window \
         .partitionBy('id') \
         .orderBy(F.col('tts').cast('timestamp').cast('long')) \
         .rangeBetween((Window.currentRow)-(14*DAY_SECS), Window.currentRow)
out = sdf \
        .withColumn('val_seq', F.collect_list('value').over(w_spec))

Output:
+---+-------------------------+-----+-------+
|id |tts                      |value|val_seq|
+---+-------------------------+-----+-------+
|0  |2019-01-01T00:00:00+00:00|a    |[a]    |
|0  |2019-01-02T00:00:00+00:00|b    |[a, b] |
|0  |2019-01-20T00:00:00+00:00|c    |[c]    |
|0  |2019-01-25T00:00:00+00:00|d    |[c, d] |
|1  |2019-01-02T00:00:00+00:00|a    |[a]    |
|1  |2019-01-29T00:00:00+00:00|b    |[b]    |
|2  |2019-01-01T00:00:00+00:00|a    |[a]    |
|2  |2019-01-30T00:00:00+00:00|b    |[b]    |
|2  |2019-02-02T00:00:00+00:00|c    |[b, c] |
+---+-------------------------+-----+-------+

My desired output:
+---+-------------------------+---------+
|id |tts                      |val_seq|
+---+-------------------------+---------+
|0  |2019-01-02T00:00:00+00:00|[a, b]   |
|0  |2019-01-25T00:00:00+00:00|[c, d]   |
|1  |2019-01-02T00:00:00+00:00|[a]      |
|1  |2019-01-29T00:00:00+00:00|[b]      |
|2  |2019-01-30T00:00:00+00:00|[a]      |
|2  |2019-02-02T00:00:00+00:00|[b, c]   |
+---+-------------------------+---------+

To sum it up: I want to group rows in sdf with the same id, and further concatenate the value for rows that are not longer than 2 weeks apart and finally only show these rows.
I am really new to pyspark so any suggestions are appreciated!

A: Below code should work:
 w_spec = Window \
                 .partitionBy('id') \
                 .orderBy(F.col('tts').cast('timestamp').cast('long')) \
                 .rangeBetween((Window.currentRow)-(14*DAY_SECS), Window.currentRow)

        out1 = df.withColumn('val_seq', F.collect_list('value').over(w_spec)).withColumn('occurrences_in_5_min',F.count('tts').over(w_spec))

w_spec2 = Window.partitionBy("id").orderBy(col("occurrences_in_5_min").desc())
Out2=out1.withColumn("rank",rank().over(w_spec2)).filter("rank==1")


text:
Q: To search either of two strings in text file using findstr and echo errorlevel I need to search either of strings "HTS 3.0 678 NO" or "HTS 5.0 679 OK" from the text file abc.txt and echo errorlevel when either one of the strings are found using batch file . I tried the below code snippet but errorlevel is 1 even though "HTS 5.0 679 OK" is found.
 >nul findstr /C:"HTS 3.0 678 NO" /C:"HTS 5.0 679 OK" "C:\abc.txt"
    if %errorlevel% EQU 0 (
    echo "Success"
    ) else (
    echo "failure"
   )

Please advise how to achieve using findstr


text:
Q: Running Upgrade via command I was trying to run upgrade in ubuntu having run update via command but,afterwards, it displayed:
ldconfig deferred processing now taking place

please, what does that msg mean?

A:
ldconfig creates the necessary links and cache to the most recent
  shared libraries found in the directories specified on the command
  line, in the file /etc/ld.so.conf, and in the trusted directories
  (/lib and /usr/lib). The cache is used by the run-time linker, ld.so
  or ld-linux.so. ldconfig checks the header and filenames of the
  libraries it encounters when determining which versions should have
  their links updated.

Please check ldconfig manual man ldconfig


text:
Q: Angular bootstrap 4 select with search filter I have a project in Angular and I'm using Bootstrap 4 with it.
I have a select:
<select>
  <option value="one">One</option>
  <option value="two">Two</option>
  <option value="three">Three</option>
</select>

When the select opens I need some search filter or similar.
How can I do this?

A: You have to create a custom input with a dropdown selector. For example:

  <input type="text" (keyup)="onSeachDropdownValue($event)"/>

{{option}}

In your typescript:

options = ['option1', 'option2', 'option3'];
searchedOptions = [];

onSeachDropdownValue($event) {
 const value = $event.target.value;
 searchedOptions = options.filter(option => option.includes(value));
}

onSelectDropdownValue(option) {
  // Do something with selected value
}

You can use two way binding to fill the input with selected option with the method you want (tamplate or reactive method).
Hope it helped


text:
Q: XAMPP change PHP version I am working on an older project that uses functions not supported by the newer PHP version included in my version of XAMPP.
I want to temporarily change to an older version of PHP, so I'm looking for a way to switch between PHP versions in XAMPP.
Unfortunately, refactoring to use the newer version of PHP is not an option.

A: I would not dare to 'temporarily' shift my development machine.
I would suggest installing a virtual machine manager like VirtualBox and then install a older version of XAMPP in there.

A: I am really disappointed with the responses on this.
WAMP allows you to switch between PHP and MySQL versions pretty easily...

A: I did following steps on Windows:

*

*Download your XAMPP with your desired PHP version (the VC-11.zip version)

*Unzip on C:/xamppXXXX/ (XXXX -> Your PHP version, for example), so you'll have both C:/xampp/ (your first installed version) and the new.
3a. Find in all .conf, .ini, .bat files from the xamppXXXX folder /xampp/ and replace for C:/xamppXXXX/. You can use any IDE like SublimeText to find the string.
3b. Find in all .conf files from the xamppXXXX folder \xampp\ and replace for \xamppXXXX\

*You can start MySQL from your installed version control panel and open the C:/xamppXXXX/xampp-control.exe and launch Apache from this one.

I did this with php7 installed and php5 from zip and working fine. Opening different instances of XAMPP Control Panel is the best way to have all databases together and not losing them between versions.

A: Dont' use XAMPP for this. Use MAMP. It's a single click


text:
Q: Subtract fixed row value in reference to column value in pandas dataframe I would like to subtract a fixed row value in rows, in reference to their values in another column.
My data looks like this:
       TRACK    TIME  POSITION_X
0        1        0       12
1        1        30      13
2        1        60      15
3        1        90      11
4        2         0      10
5        2        20      11
6        2        60      13
7        2        90      17

I would like to subtract a fixed row value (WHEN TIME=0) of the POSITION_X column in reference to the TRACK column, and create a new column ("NEW_POSX") with those values. The output should be like this:
       TRACK    TIME  POSITION_X   NEW_POSX
0        1        0       12         0
1        1        30      13         1
2        1        60      15         3
3        1        90      11        -1
4        2         0      10         0
5        2        20      11         1
6        2        60      13         3
7        2        90      17         7

I have been using the following code to get this done:
import pandas as pd

data = {'TRACK':  [1,1,1,1,2,2,2,2],
        'TIME': [0,30,60,90,0,20,60,90],
        'POSITION_X': [12,13,15,11,10,11,13,17],
        }

df = pd.DataFrame (data, columns = ['TRACK','TIME','POSITION_X'])
df['NEW_POSX']= df.groupby('TRACK')['POSITION_X'].diff().fillna(0).astype(int)
df.head(8)

... but I don't get the desired output. Instead, I get a new column where every row is subtracted by the previous row (according to the "TRACK" column):
       TRACK    TIME  POSITION_X   NEW_POSX
0        1        0       12         0
1        1        30      13         1
2        1        60      15         2
3        1        90      11        -4
4        2         0      10         0
5        2        20      11         1
6        2        60      13         2
7        2        90      17         4

can anyone help me with this?

A: You can use transform and first to get the value at time 0, and then substract it to the 'POSITION_X' column:
s=df.groupby('TRACK')['POSITION_X'].transform('first')
df['NEW_POSX']=df['POSITION_X']-s

#Same as:
#df['NEW_POSX']=df['POSITION_X'].sub(s)

Output:
df
   TRACK  TIME  POSITION_X  NEW_POSX
0      1     0          12         0
1      1    30          13         1
2      1    60          15         3
3      1    90          11        -1
4      2     0          10         0
5      2    20          11         1
6      2    60          13         3
7      2    90          17         7


text:
Q: Layers not correctly generated using SAGA algorithms within QGIS 3.4.4-Madeira I am trying to use a few algorithms that may be useful for my work, that are part of the processing tools packaged with the latest LTR 64-bit version of QGIS in Windows 10 64 bit.. However, all of the SAGA algorithms that I have tried so far throw the same final error, regarding layers that were not correctly generated. The following image is the end of the log message I get. In red is the error I mention. It happens with all tools I have tried so far.

I checked other posts and read similar issues. Some suggestions to fix it included using different paths, and avoiding blank spaces in them.
I tried changing the path to a D:\Temp directory but no success.
Things I noticed:

*

*In the log, some paths appear with forward slash (/), as in Unix systems.

*Some long paths appear shortened, using the tilde (~). In particular, C:\OSGeo4W64 gets shortened to C:\OSGeo4~1

Any hints?
EDIT:
This is the output log provided in comments:
Procesando algoritmo...

Algoritmo 'Profiles from lines' comenzando…

Parámetros de entrada:

{ 'DEM' : 'F:/Dropbox/QGIS_Test/DEM.tif', 'LINES' : 'F:\\Dropbox\\QGIS_Test\\Lines.shp', 'NAME' : 'id', 'PROFILE' : 'C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/8d34e08d5a984c11a8ffce8b99fadd36/PROFILE.shp', 'PROFILES' : 'C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/acbe581a52b9406fb5db4af3292f919a/PROFILES.shp', 'SPLIT ' : True, 'VALUES' : '' }

io_gdal 0 -TRANSFORM 1 -RESAMPLING 3 -GRIDS "C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/635ead2d3ee34f7bbeda0d5905c407b0/DEM.sgrd" -FILES "F:\Dropbox\QGIS_Test\DEM.tif"

ta_profiles "Profiles from Lines" -DEM "C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/635ead2d3ee34f7bbeda0d5905c407b0/DEM.sgrd" -LINES "F:\Dropbox\QGIS_Test\Lines.shp" -NAME "id" -SPLIT true -PROFILE "C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/8d34e08d5a984c11a8ffce8b99fadd36/PROFILE.shp" -PROFILES "C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/acbe581a52b9406fb5db4af3292f919a/PROFILES.shp"

F:\Dropbox\QGIS_Test>set SAGA=C:/PROGRA~2/QGIS3~1.4/apps\saga-ltr

F:\Dropbox\QGIS_Test>set SAGA_MLB=C:/PROGRA~2/QGIS3~1.4/apps\saga-ltr\modules

F:\Dropbox\QGIS_Test>PATH=C:\PROGRA~2\QGIS3~1.4\apps\qgis\bin;C:\PROGRA~2\QGIS3~1.4\apps\Python37;C:\PROGRA~2\QGIS3~1.4\apps\Python37\Scripts;C:\PROGRA~2\QGIS3~1.4\apps\qt5\bin;C:\PROGRA~2\QGIS3~1.4\apps\Python27\Scripts;C:\PROGRA~2\QGIS3~1.4\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\system32\WBem;C:\PROGRA~2\QGIS3~1.4\apps\Python37\lib\site-packages\pywin32_system32;C:\PROGRA~2\QGIS3~1.4\apps\Python37\lib\site-packages\numpy\.libs;C:/PROGRA~2/QGIS3~1.4/apps\saga-ltr;C:/PROGRA~2/QGIS3~1.4/apps\saga-ltr\modules

F:\Dropbox\QGIS_Test>saga_cmd io_gdal 0 -TRANSFORM 1 -RESAMPLING 3 -GRIDS "C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/635ead2d3ee34f7bbeda0d5905c407b0/DEM.sgrd" -FILES "F:\Dropbox\QGIS_Test\DEM.tif"

____________________________

##### ## ##### ##

### ### ## ###

### # ## ## #### # ##

### ##### ## # #####

##### # ## ##### # ##

____________________________

SAGA Version: 2.3.2 (32 bit)

____________________________

library path: C:\PROGRA~2\QGIS3~1.4\apps\saga-ltr\modules\

library name: io_gdal

library : GDAL/OGR

tool : Import Raster

author : O.Conrad (c) 2007 (A.Ringeler)

processors : 8 [8]

____________________________

Parameters

Grids: No objects

Files: "F:\Dropbox\QGIS_Test\DEM.tif"

Select from Multiple Bands:

Alphanumeric Sorting: yes

Transformation: yes

Resampling: B-Spline Interpolation

loading: F:\Dropbox\QGIS_Test\DEM.tif

Driver: GTiff

Bands: 1

Rows: 5557

Columns: 7445

loading: DEM

F:\Dropbox\QGIS_Test>saga_cmd ta_profiles "Profiles from Lines" -DEM "C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/635ead2d3ee34f7bbeda0d5905c407b0/DEM.sgrd" -LINES "F:\Dropbox\QGIS_Test\Lines.shp" -NAME "id" -SPLIT true -PROFILE "C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/8d34e08d5a984c11a8ffce8b99fadd36/PROFILE.shp" -PROFILES "C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/acbe581a52b9406fb5db4af3292f919a/PROFILES.shp"

Error: dbf write: invalid table

____________________________

##### ## ##### ##

### ### ## ###

### # ## ## #### # ##

### ##### ## # #####

##### # ## ##### # ##

____________________________

SAGA Version: 2.3.2 (32 bit)

____________________________

library path: C:\PROGRA~2\QGIS3~1.4\apps\saga-ltr\modules\

library name: ta_profiles

library : Profiles

tool : Profiles from Lines

author : O.Conrad (c) 2006

processors : 8 [8]

____________________________

Load grid: C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/635ead2d3ee34f7bbeda0d5905c407b0/DEM.sgrd...

Load shapes: F:\Dropbox\QGIS_Test\Lines.shp...

Parameters

Grid system: 5; 5557x 7445y; 511960x 4649730y

DEM: DEM

Values: No objects

Lines: Lines

Name: id

Profiles: Profiles

Profiles: No objects

Each Line as new Profile: yes

failed

Save shapes: C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/acbe581a52b9406fb5db4af3292f919a/PROFILES.shp_1...

Save shapes: C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/acbe581a52b9406fb5db4af3292f919a/PROFILES.shp_2...

F:\Dropbox\QGIS_Test>exit

Ejecución completada en 12.90 segundos

Resultados:

{'PROFILE': 'C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/8d34e08d5a984c11a8ffce8b99fadd36/PROFILE.shp',
'PROFILES': 'C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/acbe581a52b9406fb5db4af3292f919a/PROFILES.shp'}

Cargando las capas resultantes

Las siguientes capas no se generaron correctamente.

C:/Users/Kais/AppData/Local/Temp/processing_5080f69b88474281943ae5c46597245d/8d34e08d5a984c11a8ffce8b99fadd36/PROFILE.shp

Puede comprobar el «Panel de mensajes del registro» en la ventana principal de QGIS para encontrar más información sobre la ejecución del algoritmo.

A: There are some problems with the Profiles from lines algorithm in QGIS.
Let's see first how it should work.
In SAGA GIS, at the command line:

*

*If you want to save Each Line as a New Profile, you need to use the -SPLIT and the -PROFILES options. Files will be saved as profile_01.shp, profile_02.shp, etc.

*If not, don't use -SPLIT option and use -PROFILE option. File will be saved as profile.shp.
In QGIS processing toolbox:

*

*Both -PROFILE and -PROFILES options are always used, so one of them always returns an error (The following layers were not correctly generated.).

*If you tick on Each Line as a New Profile (is ticked by default), -SPLIT option is used, and the files are saved as PROFILE.shp1, PROFILE.shp2, etc. That produced two errors (one for the -PROFILE empty layer and other for the invalid extensions).
A bug report was already opened: https://issues.qgis.org/issues/21294.
Meanwhile, a possible workaround is to not use the Each Line as a New Profile option (untick it) and ignore the error generated by the -PROFILE over option.


text:
Q: Is it possible to make an "if" statement affect two separate parts of code? I'm quite new to JavaScript and I was wondering if it is possible to make an if statement affect two separate parts of code. For example:
console.log(1);
console.log(2);
console.log(3);

The code above should print the numbers 1, 2, and then 3 in that order, but I want to add a test to it. If the test passes, all three commands should run, but if it fails only a 2 should be printed. I could add two if statements like this:
if (test()) {console.log(1)}
console.log(2);
if (test()) {console.log(3)}

My problem with this is the test() function is being run twice. Is there a way to only run the test once while preserving the order of the numbers? Sorry if there's an obvious answer and I'm just missing it.
(I should add that this is just an example of 3 events that have to happen in order, so I need an answer that would work not just for printing consecutive numbers but anything situation where you would want 3 things to happen in order.)

A: This is best done by storing the value in a variable that will handle the control flow execution (this variable is known as a flag). You can make it as simple as this:
let testResult = test();
if (testResult) {
    console.log(1);
}
console.log(2);
if (testResult) {
    console.log(3);
}

This will ensure that if testResult is false (i.e. test returns false or a falsy value) then you will only have 2 printed, but if test returns true or a truthy value, then 1, 2, 3 will all be printed.
If you only want a single if statement, then use if-else and print 2 in both of them:
let testResult = test();
if (testResult) {
    console.log(1);
    console.log(2);
    console.log(3);
} else {
    console.log(2);
}

(note you could eliminate the first line in the code block above and just use if (test()) since you only call test once, but I've kept it just so you can see it's usable in many situations).

A: You can try ternary operator!
(test()?(event1;event2;event3):(event2))

A: So another alternative is to use the flag into the function you can skip heavy calculations or something, the down side of this is if you whant to return null

var TheTestFlag = null;
let test = () => {
    if(TheTestFlag === null){
        console.log("Entered into heavy logic");
        //...do some stuff
        // don't return assigne to the flag
        //for exaple if(a>b) TheTestFlag = false;
        TheTestFlag = false;
    }
    //return the flag
    return TheTestFlag;
};
if (test()) {
    console.log(1);
}
console.log(2);
if (test()) {
    console.log(3);
}


text:
Q: How to concatenate variable and string in following scenario in PHP? I've following PHP code:
<?php
$rebate_no = 2;
echo "

              <select name='product_id_$rebate_no[1]' id='product_id_$rebate_no_1' class='form-control prod_list'>
                <option value='1'>Alabama</option>
                <option value='2'>Alaska</option>
                <option value='3'>Arizona</option>
                <option value='4'>Arkansas</option>
                <option value='5'>California</option>
              </select>

";
?>

In above code I'm having issues in concatenation of variable and string at following lines:

<select name='product_id_$rebate_no[1]' id='product_id_$rebate_no_1' class='form-control prod_list'>

I tried following trick but it didn't work for me.

<select name='product_id_$rebate_no[1]' id='product_id_'.$rebate_no.'_1' class='form-control prod_list'>

If I check in HTML source I'm getting following HTML:

<select id="product_id_" class="form-control prod_list" .2.'_1'="" name="product_id_">

Actually I want the HTML in following desired format:

<select name='product_id_2[1]' id='product_id_2_1' class='form-control prod_list'>

How to achieve this? Thanks in advance.

A: String concatenation
<?php
$rebate_no = 2;
echo "

              <select name='product_id_".$rebate_no[1]." id='product_id_".$rebate_no_1."' class='form-control prod_list'>
                <option value='1'>Alabama</option>
                <option value='2'>Alaska</option>
                <option value='3'>Arizona</option>
                <option value='4'>Arkansas</option>
                <option value='5'>California</option>
              </select>

";
?>

OR
If you want to use the Zend specification
<?php
    $rebate_no = 2;
    echo "

                  <select name='product_id_{$rebate_no[1]} id='product_id_{$rebate_no_1}' class='form-control prod_list'>
                    <option value='1'>Alabama</option>
                    <option value='2'>Alaska</option>
                    <option value='3'>Arizona</option>
                    <option value='4'>Arkansas</option>
                    <option value='5'>California</option>
                  </select>

";
    ?>

A: You started with double quotes, so you can do it this way:

or use curly braces {} around the variable:

Both are valid.

A: Try this:

    <select name='product_id_$rebate_no[1]' id='product_id_".$rebate_no."_1' class='form-control prod_list'>

when you are concating the string you need use double quotes since you started string with double quotes.

A: the problem lies with $rebate_no[1]. you can either store the value of that into a regular variable, append the value to the string like below, or surround it in curly brackets like so {$rebate_no[1]}
echo "

              <select name='product_id_" . $rebate_no[1] . "' id='product_id_$rebate_no_1' class='form-control prod_list'>
                <option value='1'>Alabama</option>
                <option value='2'>Alaska</option>
                <option value='3'>Arizona</option>
                <option value='4'>Arkansas</option>
                <option value='5'>California</option>
              </select>

";

A: you got the trick wrong.
instead of doing

do

A: There is easiest method Use (" ") double quotes instead of (' ') without making it complicated.

<select name="product_id_$rebate_no[1]" id="product_id_$rebate_no_1" class='form-control prod_list'>

instead of

<select name='product_id_$rebate_no[1]' id='product_id_$rebate_no_1' class='form-control prod_list'>

Reff : PHP: different quotes?


text:
Q: In Android, How can i use Youtube Player with indicator? In my project, i use youtube player.
my project is shopping app, i set youtube player in ViewPager.
It's perfect. no problem. however, my client want add circle indicator.
I can't understand, it has problem.
I add indicator in my XML file, youtube player play just one second. i click play, one sec play and stop again. What happen???
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/btnMusicPlayer"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_gravity="bottom|right"
        android:layout_margin="15dp"
        android:background="@drawable/btn_music" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="260dp">

        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager_main"
            android:layout_width="match_parent"
            android:layout_height="260dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true" />

        <me.relex.circleindicator.CircleIndicator
            android:id="@+id/indicators"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:layout_alignParentBottom="true" />

    </RelativeLayout>

</FrameLayout>

that's my activity xml code.
I insert lower xml to ViewPager by lower code.(ViewPager Adaptor)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <view
        android:id="@+id/video_viewpager_childvideo"
        class="com.google.android.youtube.player.YouTubePlayerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"/>

</RelativeLayout>

and it's ViewPager Adaptor.
    view= inflater.inflate(R.layout.layout_viewpager_child_video, null);

    final YouTubePlayerView video = (YouTubePlayerView)
    view.findViewById(R.id.video_viewpager_childvideo);
    String fullurl = mediaUrls.get(position).getUrl();
    YouTubeHelper youTubeHelper = new YouTubeHelper();

    final String videoUrl = youTubeHelper.extractVideoIdFromUrl(fullurl);

    listener = new YouTubePlayer.OnInitializedListener(){

        @Override
        public void onInitializationSuccess(YouTubePlayer.Provider provider,
    YouTubePlayer youTubePlayer, boolean b) {
            youTubePlayerInstance = youTubePlayer;
            youTubePlayer.cueVideo(videoUrl);
        }

        @Override
        public void onInitializationFailure(YouTubePlayer.Provider provider,
     YouTubeInitializationResult youTubeInitializationResult) {

        }
    };

    video.initialize(youTubeApiKey, listener);

if i remove me.relex.circleindicator.CircleIndicator, perfectly work.
if just change two view's position, it works too.
me.relex.circleindicator.CircleIndicator is just now try. i try 4 kind of insicator, anyone has problems.
one time I add just View for some black shadow, it has problem too.
this.
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/btnMusicPlayer"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_gravity="bottom|right"
        android:layout_margin="15dp"
        android:background="@drawable/btn_music"
        android:onClick="onClickMusic" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="260dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true" />

    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="4dp"
        android:layout_gravity="top"
        android:layout_alignParentTop="true"
        android:background="@drawable/shadow_down" />

</FrameLayout>

I cant understand, why btnMusicPlayer dosen't make error??
I think youtube player has problem when some view over that. isn't it?
Please help me!!

A: I think this is what you're looking for. It will allow you to use custom UI for the API. It is an open source library intended to be used as a replacement for the official YouTube Android Player API.
I hope it helps.

A: If you read your logcat you'll see that you cannot have views overlapping the YouTubePlayer, that's why it stops.
You have to alternatives:

*

*Remove the overlaying View.

*Use a WebView-based implementation, like android-youtube-player.


text:
Q: Entity Framework Query based on child object filter and at the same time on the main object I have a class called Query with a field called CreatedBy, the username who created it.
I also have a class called Permissions with the permissions for the query.
I created a query that returns me based on the current user, the queries the user has access to, based on the Permissions collection, but I need to JOIN that with the queries that the user also created.
If for some reason, the user who created it, its also in the Permissions collection, it shouldnt be returned twice.
Here is my code
public class Query
    {
        public int QueryId { get; set; }
        public string QueryName { get; set; }
        public string QuerySql { get; set; }
        public string CreatedBy { get; set; }
        public string QueryType { get; set; }
        public string RequestType { get; set; }
        public string Column1 { get; set; }
        public string Operator1 { get; set; }
        public string Value1 { get; set; }
        public string Connector2 { get; set; }
        public string Column2 { get; set; }
        public string Operator2 { get; set; }
        public string Value2 { get; set; }
        public string Connector3 { get; set; }
        public string Column3 { get; set; }
        public string Operator3 { get; set; }
        public string Value3 { get; set; }
        public virtual ICollection<Permission>  Permissions { get; set; }
    }

  public class Permission
    {
        public int PermissionId { get; set; }
        public string UserName { get; set; }
    }

   public IQueryable<Query> GetQueriesForUser(string userName)
        {
            return _context.Queries.Where(q => q.Permissions.Any(p => p.UserName.Equals(userName)));
        }

A: Are you sure you need a join? It looks like you need UNION ALL:
_context.Queries.Where(q => q.Permissions.Any(p => p.UserName == userName)).Concat(
    _context.Queries.Where(q => q.CreatedBy == userName));


text:
Q: winrt trouble with std::filesystem? I cloned https://github.com/kennykerr/cppwinrt, and added the two lines @line 70 (after including the filesystem header):
if (!std::experimental::filesystem::exists(winrt::to_string(file.Path())))
    exit(12345);

And it exits with 12345. Always. Why? I thought winrt was supposed to work with standard iso c++? Even if I hardcode a filename instead of the "to_string(data_file)", it still dies.
If it has something to do with UWP running in a sandbox, that's fine, but why isn't the filepicker working?
This is more or less the easiest example I can pull up. For some reason, no matter what I try, I cannot operate on files.

A: I suppose you missed the important fact that each winrt application runs in own sandbox. Each file path you try to access is relatively to application sandbox root, although a given path is absolute, it is absolute in sandbox and the system interprets it as relative path to sandbox root. To get access to files outside sandbox you should apply more efforts, declare a path with required files shared between sandboxes or place a file into already available system shared directories. In this case a path will not be absolute again, it will be accessed relative to shared path.


text:
Q: How can I change what time Deja Dup does its backup? I believe it automatically runs at midnight, but I would rather it run during an off-peak internet period to save my quota.
How can I change the time it runs?

A: That feature is on the wishlist, for now you can try setting the schedule to monthly in the preferences and setup your own schedule using crontab and deja-dup --backup.


text:
Q: Scope of SavePoint variable I am trying to upsert parent records in a class as well as it calls another class which inserts child records. I am trying to add Savepoint to rollback the transaction and prevent parent record from upserting , if child upsertion fails.
Below is high level code
// Class A

Class A{
    // statements and methods
if(condition){
    try{
         // statements
         **Savepoint sp = Database.setSavepoint();**
         **Database.upsert(Parentrecords);**
    }
    catch(DMLException dmlex){
        //log dml exception errors
    }
    catch(Exception){
        // log exceptions
    }
}
method() // Some method called
// Some statements, loops etc

if(condition){
    // Some more statements
    boolean isUpserted;
    **isUpserted = B.upsertChildRecords(childrecords);
    if(!isUpserted){
        Database.rollback(sp);
    }**
}
}
// Class B

Class B {
    boolean upsertChildRecords(list childrecords){
        try{
        database.upsert(childrecords);
        return true;
        }
        catch(DMLexception exception){
            //log dml exception
            return false;
        }
    }
}

It throws error- Variable does not exist: sp
What is the scope of the savepoint variable?


text:
Q: What's the ideal method for populating a drop down list via AJAX (AJAJ?) in razor/jquery? So I've got this @Html.DropDownList("Thangs") inside of a hidden div. When the user clicks a link to expose the div, I want to make an AJAX call to grab the things that should be in the list. It will be returned as JSON. How would I bind the incoming JSON objects as name/values into the DropDownList using jQuery?

A: you have not posted any sample json so
...
success:function(data){

$("#SelectList").empty(); //remove previous items in the ddl

//iterate the json
$.each(data,function(key,val){
  $("<option/>",{value:key,text:val}).appendTo("#SelectList");
  });
}

here is the DEMO


text:
Q: 401 when trying to implement CORS for SharePoint I would like to access listdata.svc (a sharepoint service) located on domainA.contoso.com from a web application located on domainB.contoso.com - Authentication seems to be an issue.
When attempting to access ListData.svc via a JQuery Ajax call, with CORS enabled, the server returns 401. If I run the same Query from an .htm page which I execute from inside of SharePoint, the call works fine, since the domain is the same.
SharePoint is using NTLM with anonymous authentication turned off - I presume that the 401 is a result of windows credentials not being passed to the SharePoint server - but I am at a loss of how to add these credentials properly to the header.  I have set xhrFields: { withCredentials: true }, but this does not seem to correct the authentication issue.
To enabled CORS, I have set the following HTTP Response Headers on SharePoint in IIS:

*

*Access-Control-Allow-Credentials: true

*Access-Control-Allow-Headers:Origin, Content-Type, Accept

*Access-Control-Allow-Origin: *

*Access-Control-Request-Methods: POST, GET, HEAD, OPTIONS

Windows Authentication is enabled in IIS for my web application, and I did not set the  "OPTIONSVerbHandler" HTTP Handler in IIS. Turning it to read doesn't seem to make a difference.
JQuery Ajax call (from application on subdomainB.contoso.com):
 $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: listUrl,
        xhrFields: { withCredentials: true },
        crossDomain:true,
        processData: false,
        async: true,
        dataType: "json",
        converters: {
            // WCF Data Service .NET 3.5 incorrectly escapes singles quotes, which is clearly
            // not required (and incorrect) in JSON specs.
            // http://bugs.jquery.com/ticket/8320?cversion=0&cnum_hist=1
            "text json": function (textValue) {
                return jQuery.parseJSON(textValue.replace(/(^|[^\\])\\'/g, "$1'"));
            }
        },
        success: function (data, status, xhr) {
            //successFunc(data.d.results);
            alert("working!");
        },
        error: function (xhr, status, error) {
            alert("failure!");
        }
    });

HTTP Header and 401 Response:
Key Value
Request OPTIONS /_vti_bin/ListData.svc/Contacts HTTP/1.1
Accept  */*
Origin  http://domainB.contoso.com
Access-Control-Request-Method   GET
Access-Control-Request-Headers  content-type, accept
Accept-Encoding gzip, deflate
User-Agent  Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Host    domainA.contoso.com
Content-Length  0
DNT 1
Connection  Keep-Alive
Cache-Control   no-cache

Key Value
Response    HTTP/1.1 401 Unauthorized
Server  Microsoft-IIS/7.5
SPRequestGuid   1e33061c-f555-451b-9d69-0d83eff5f5ea
WWW-Authenticate    NTLM
X-Powered-By    ASP.NET
MicrosoftSharePointTeamServices 14.0.0.4762
Access-Control-Allow-Headers    Origin, Content-Type, Accept
Access-Control-Allow-Origin *
Access-Control-Request-Methods  POST, GET, HEAD, OPTIONS
Access-Control-Allow-Credentials    true
Date    Wed, 15 May 2013 15:04:51 GMT
Content-Length  0

A: Late response, but I found another thread here which has an easy solution for IIS and which worked for me.
Basically the CORS standard specifies that a preflight request should not send any authentication information, thus the 401.  In that thread there's an example of restricting anonymous requests to the OPTIONS verb which allows a 200 response to the preflight (OPTIONS verb) request but still requires the authentication for the others.

A: I'm not sure what you mean by "anonymous authentication is disabled", but it sounds like that's exactly the reason you're getting a 401 (Unauthorized) response. It's not related to CORS, but the server is telling the client it requires a username and a password before it will allow access.
Try passing a username and password to $.ajax() (WARNING: it's just to test if that solves your problem, hardcoding such details in your JS code is a Bad Idea):
$.ajax({
  crossDomain:true,
  url: listUrl,
  username: VALID_USERNAME,
  password: VALID_PASSWORD,
  success: function(data){alert("hello json!") },
  error: function() {
    alert("epic fail");
  },
  dataType:'json'
});

A: You can't use wildcard (*) for Access-Control-Allow-Origin on the server when client sends "withCredentials: true".
You must set the domain explicitely.
CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true


text:
Q: how to get current cursor position in MASM I am writing an IQ test generation program in which i have to randomly generate questions that will include verbal non verbal questions. For generating non verbal questions i want to display questions in which alphabets and letters will appear in circular or triangular shape.
But i am not sure how to position them. E.g in a non verbal question i want to position alphabets and numbers in triangular shape by writing this code:
mov al, alpha
call writechar
add dl, 4
call gotoxy
mov al, num
call writedec
sub dl, 2
add dh, 1
call gotoxy
mov al, alpha
call writechar

This is what i already know

dh= rows
dl=columns
call gotoxy

Gotoxy positions cursor relative to starting position of console, not relative to current position.This is the problem that i'm getting.
I assume there should be a way of getting current cursors position so that i can position cursor back and forth by adding and subtracting from current value of dh and dl while generating shapes in series.

A: You can get the Irvine32 help online: http://programming.msjc.edu/asm/help/. There is a WinAPI function specified for getting the cursor position: GetConsoleScreenBufferInfo. Unfortunately the description of the structure CONSOLE_SCREEN_BUFFER_INFO is not correct. The name of the appropriate COORD structure is dwCursorPosition.
Here's an example how to use it:
INCLUDE Irvine32.inc
INCLUDELIB Irvine32.lib

.DATA
    txt1 db "Current Cursor Position is X=",0
    txt2 db " Y=",0
    BufferInfo CONSOLE_SCREEN_BUFFER_INFO <>

.CODE
main PROC

    lea edx, txt1
    call WriteString

    invoke GetStdHandle, STD_OUTPUT_HANDLE
    invoke GetConsoleScreenBufferInfo, eax, ADDR BufferInfo

    movzx eax, BufferInfo.dwCursorPosition.X
    call WriteInt

    lea edx, txt2
    call WriteString
    movzx eax, BufferInfo.dwCursorPosition.Y
    call WriteInt

    exit

main ENDP

END main


text:
Q: How to check SiteCore's serialisation tree into TFS We're using Sitecore and to share the content between developers we're serialising the content tree to the filesystem then checking this into source control.  This worked fine in the last project that used SVN, but this new project is using TFS.
Unfortunately TFS won't accept paths that have a dollar sign in them, ie
\serialization\master\sitecore\templates\Branches\Calendar\Agenda View Settings\$name.item

and this is a very common file name for Sitecore's serialisation structure.  Is there any way around this?  Can Sitecore be changed to not put the $ in front of the file names or do we have to switch to SVN?

A: Oh, and one more thing.
http://www.hhogdev.com/products/team-development-for-sitecore.aspx
I've not had the chance to test this tool myself yet, but it looks interesting and could potentially be the answer to your source control challenges.

A: Is the workaround suggested here (in the 'Community Content' at the bottom of the page) any use to you?

A: I did some digging around. It's doable, however not immediately straight forward.
When serializing a tree, Sitecore invokes: Sitecore.Shell.Framework.Commands.Serialization.DumpTreeCommand. This is defined in /App_Config/Commands.config. When de-serializing, the equivalent .LoadTreeCommand is invoked.
What these commands do, is little more than invoking:
protected override void Dump(Item item)
{
    Sitecore.Data.Serialization.Manager.DumpTree(item);
}

And unfortunately, to get to the functionality you need to override, it looks like you are going to have to 1) override the command in commands.config, and then create your own Serialization Manager (inheriting from Sitecore's).
I'm not entirely sure how easy this would be, since most of the methods in this class are static members. The method you would need to override/re-implement is this one:
public static void DumpItem(string path, Item item)
{
    Assert.ArgumentNotNullOrEmpty(path, "path");
    Assert.ArgumentNotNull(item, "item");
    Directory.CreateDirectory(Path.GetDirectoryName(path));
    using (new SecurityDisabler())
    {
        TextWriter writer = new StreamWriter(File.Create(path));
        try
        {
            ItemSynchronization.WriteItem(item, writer);
        }
        catch
        {
        }
        writer.Close();
    }
}

The filename, as you can see, is based entirely on the Item's path. The assumption is, you could perhaps get away with something like .Replace("$", "!dollartoken!") and implement the reverse in your de-serializer.
Seems a lot of work though, unfortunately.


text:
Q: данные в datagridview видны только при выделении ячейки DataTable table = new DataTable();
table.Columns.Add("Номер детали", typeof(string));
table.Columns.Add("Номер программы", typeof(string));
for (int i = 0; i < 10; i++)
{
   table.Rows.Add("ytwyetwe", "gswdhsgd");
}
dataGridView2.DataSource = table;

Visual studio 2013 пересмотрел много примеров, во всех данные в таблице видны сразу у меня только при выделении, т.е. при запуске приложения вся таблица пустая (белая) при нажатии на любую ячейку она (ячейка) становится синей и в ней видны данные.Код расположен в Form_load Спасибо!


text:
Q: How to change string depending on checkedlistbox Pretty self explanatory. I would like to change a string if a certain option is checked in the checkedListBox. And change it again when a different option is checked. I'd say that a if statement would work but how would I do that inside a if statement so that other objects can use that string?

A: You could make the string a constant and assign a value to it in the checkedListBox's SelectedIndexChanged event. Something like (pseudocode):
private readonly String clbResponse = String.Empty;
. . .
protected void clb_SelectedIndexChanged(object sender, eventargs e)
{
    int indexSelected = clb.SelectedIndex;
    case (indexSelected)
    0:
     clbResponse = "index 0 was selected";
     break;
    1:
     clbResponse = "index 0 was selected";
     break;
    . . .
    default
       break;
}


text:
Q: Remove Invalid Parenthesis Remove the invalid parenthesis using Python in O(n) time complexity and O(1) space. I have few approaches which will take O(n log n) and O(n^2) time and also O(n) both space and time. But, I am looking for one which minimal time. I tried searching in web but couldn't found any approach to solve.
For example:
input - {}{}{{}}}}}{{{{{}
output - {}{}{{}}{}

There are several other edge cases too.

A: In the given example, the nesting levels are as follows:
 { } { } { { } } } } } { { { { { }
 1 0 1 0 1 2 1 0-1-2-3-2-1 0 1 2 1

If you discard the negative ones (on the fly),
 { } { } { { } } { { { { { }
 1 0 1 0 1 2 1 0 1 2 3 4 5 4

Now repeat from the right.
 { } { } { { } } { { { { { }
-2-3-2-3-4-3-2-3-4-3-2-1 0 1

and
 { } { } { { } } { }
 0 1 0 1 0 1 2 1 0 1


text:
Q: Geoserver access REST in javascript - Why 403 Forbidden? The documentation of the Geoserver mentions about REST examples.
I managed to achieve that using PHP. But I fail with Javascript. It show Status Code 403, which means Forbidden.

Here's my javascript pure code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Action to be performed when the document is read;
    }
};
xhttp.open("GET", urlGeo, true);
xhttp.setRequestHeader('Authorization', "Basic YWRtaW46Z2Vvc2VydmVy");
xhttp.send();

Here's my jquery ajax code:
$.ajax({
url: urlGeo,
type: 'POST',
beforeSend: function (xhr) {
    xhr.setRequestHeader('Authorization', "Basic YWRtaW46Z2Vvc2VydmVy");
},
success: function (res) { console.log('res',res); },
error: function (err) {
console.log('err',err);
}
});

Both fail miserably. The thing is, no secret about the username and password. I am using the default for testing:
username: admin
password: geoserver

In this case, basic authorization is applied. Basic YWRtaW46Z2Vvc2VydmVy is being converted from btoa(username:password).
So, I wonder why it fails in Javascript?


text:
Q: How to set UPC-E not to expand to GTIN-13 iOS I am using ZBar iOS sdk to scan barcodes. Upon scanning UPC-E codes it adds up lots of zeros and brings 13 digit codes.
When I check with Zbar's website, I came across this.

UPC-E is a "zero compressed" version of UPC-A; certain of the zeros
  are removed from the UPC-A data to generate the UPC-E barcode. The
  ZBar decoder expands this compression by default, again to
  consistently report GTIN-13 product codes. You can choose to receive
the compressed 8-digit results instead by explicitly enabling UPC-E.

However, I couldn't find where to change this.
Any suggestions?

A: Doing this solved my issue,
//ADD: present a barcode reader that scans from the camera feed
ZBarReaderViewController *reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
reader.supportedOrientationsMask = ZBarOrientationMaskAll;

ZBarImageScanner *scanner = reader.scanner;

// Set zbar_cfg_enable to 1 for UPC-E
[scanner setSymbology: ZBAR_UPCE
               config: ZBAR_CFG_ENABLE
                   to: 1];


text:
Q: Change Cluetip background-image during run-time I would like to conditionally change the background image of my Cluetips during run-time via jQuery. I use 'rounded' as cluetipClass.
I thought this would do the trick:
$('.cluetip-rounded').css("background", "url(infobox_left.png)");

But in the Chrome Developer Toolbar, I can see that the CSS settings are completely untouched.
How can I change the cluetip CSS-settings?
Best,
David

A: Use this:
$('.cluetip-rounded').css("background-image", "url(infobox_left.png)");

and make sure path of image is valid.

A: It should work. Make sure you have a correct image path. Look at this:
http://jsfiddle.net/DRN3P/

A: cluetip "clones" the hidden div, make sure you invoke the cluetip again after changing the class or alter the "cloned" content.


text:
Q: How do you configure Msys's default size, color, and font? I've been exploring use of MSys lately as an alternative, 'nix-like shell for my windows development.  However, the default colors and size are driving me crazy.  Anyone have any idea as to how I can change the default size, color, and / or font?  Honestly, I'd be happy if I could make the default character width/height of the shell larger, but the others would be nice too...
Clarification: the msys shell is a separate app from the windows shell - the normal 'right-click-upper-left -> properties' configuration (like with the windows shell) is not present.
Looks like underneath it's firing off rxvt.  Thanks!

A: Open the msys.bat file an aroun line 72 it reads like this:
rem Setup the default colors for rxvt.
if "x%MSYSBGCOLOR%" == "x" set MSYSBGCOLOR=White
if "x%MSYSFGCOLOR%" == "x" set MSYSFGCOLOR=Black
if "x%MINGW32BGCOLOR%" == "x" set MINGW32BGCOLOR=LightYellow
if "x%MINGW32FGCOLOR%" == "x" set MINGW32FGCOLOR=Navy
if "%MSYSTEM%" == "MSYS" set BGCOLOR=%MSYSBGCOLOR%
if "%MSYSTEM%" == "MSYS" set FGCOLOR=%MSYSFGCOLOR%
if "%MSYSTEM%" == "MINGW32" set BGCOLOR=%MINGW32BGCOLOR%
if "%MSYSTEM%" == "MINGW32" set FGCOLOR=%MINGW32FGCOLOR%

change the first 4 lines with the colors you like, to change the font, just bellow:
start %WD%rxvt -backspacekey  -sl 2500 -fg %FGCOLOR% -bg %BGCOLOR% -sr -fn Courier-12 -tn msys -geometry 80x25 -e /bin/sh --login -i

change the Courier-12 with your favourite font and the 80x25 with your prefered window size.

A: I create HOME env var, which have value like 'e:\home' and put into %HOME% dir .Xdefaults file with such content:

Rxvt*background: white
Rxvt*foreground: black
Rxvt*geometry: 120x40
Rxvt*font: 7x14
Rxvt*scrollBar: on
Rxvt*saveLines: 5000

Also note that this config successfully work on Cygwin and various Unix boxes.

A: If you're running MSYS bash from a command line, Behind the scenes it's a windows command shell window, so configuring it is just the same.

*

*Right click on the title bar at the
top of the shell window and select
'properties'

*Configure the window with the options
on the tabs on the dialog; these
should be fairly self-explanatory.

*When you close the dialog, select
'Modify shortcut that started this
window' to save the configuration
back as defaults.
EDIT: If you're running the shell in an xterm or RXVT window through an X server,  start the xterm window with -fg (foreground), -bg (background) and -fn (font).  Can't remember what the RXVT switches are, but you should be able to see them in the man page.  You can also configure them through your .Xdefaults file.  Again, see the man page for details.
EDIT: Thanks Paulo - note that MSYS also comes with an X-less version of RXVT, which the OP seems to be using.  Here's a link for configuring RXVT on MSYS.

A: If you're tired of using cmd for msys git, I recommend using minty and/or ConEmu
:

to use mintty, download latest version from google code/mintty and drop it in the bin folder of git msys + make following shortcut:
"C:\Program Files (x86)\Git\bin\mintty.exe" --title "Git Bash" -w full --exec "C:\Program Files (x86)\Git\bin\sh.exe" --login -i

(set working dir to your home dir)
to use vim, make sure to read this bug report
for colors, make sure gitconfig is set to color = always
I set sublime as my default editor as vim didn't work, see notes below
note:

*

*vim packaged with msys expects cmd terminal and won't work with mintty

*interaction to enter username/password for git pushes using basic http auth won't work unless you host mitty in ConEmu. (ssh works fine on mitty by itself)

ref:

*

*rpavlik/git-windows-mintty - notice this does not bundle latest mintty version.

*/oumu/mintty-color-schemes


text:
Q: Mac Software that Detects Windows Malware I want to use my Mac to scan drives that have Windows partitions on them for malware. I know that there are a lot of security software packages out there for Macs but I'm not sure if they detect Windows based malware to the same extent that a Windows security software package would. Does anyone out there have experience using their Macs to detect viruses on Windows partitions and/or external drives that may have been infected with Windows based malware? What software is the best for this?

A: The antivirus tools I've used (Sophos and Malwarebytes) can scan for Windows viruses.
One issue that comes up is that typically macOS doesn't have write access to the bootcamp partition.
For external drives that macOS has write access to, the above tools had no problem identifying and quarantining suspected Windows malware.


text:
Q: Installation of Solaris 11 on Sun Fire T1000 I just want to install Solaris 11.4 on my Sun Fire T1000. I have successfully configured install server on VirtualBox, how it described here
After that, I connected to ALOM of T1000, and tried to boot using network.
After that I saw such messages:
Boot device: /pci@7c0/pci@0/pci@8/network@1,1  File and args: -v - install
1000 Mbps full duplex  Link up
<time unavailable> wanboot info: WAN boot messages->console
<time unavailable> wanboot info: configuring /pci@7c0/pci@0/pci@8/network@1,1

1000 Mbps full duplex  Link up
<time unavailable> wanboot info: http://10.100.8.28:5555/cgi-bin/wanboot-cgi
Found 10.100.8.28 @ 8:0:27:ca:20:7a
<time unavailable> wanboot progress: wanbootfs: Read 368 of 368 kB (100%)
<time unavailable> wanboot info: wanbootfs: Download complete
Tue Sep 24 10:27:26 wanboot progress: miniroot: Read 408100 of 408100 kB (100%)
Tue Sep 24 10:27:26 wanboot info: miniroot: Download complete
|
SC Alert: Host System has Reset
'cp
SC Alert: Host system has shut down.

And then my Sun Fire T1000 just reboot.
How I can fix that?

A: Solaris 11.4 is not supported on the T1000 (bolding mine):

Platform Support
Oracle Solaris 11.4 supports systems based on the Oracle SPARC T4 or
  later processors; the Fujitsu SPARC64 X, X+, or XII processors; or x64
  CPUs supporting either the Intel EM64T or AMD AMD64 instruction sets.
You will not be able to upgrade to Oracle Solaris 11.4 on any of the
  following platforms. See Oracle Solaris 11.3 Support (Doc ID
  2382427.1) for information about keeping these systems up to date with critical fixes for Oracle Solaris 11.3 until you can upgrade the
  hardware:

*

*SPARC Enterprise M3000, M4000, M5000, M8000, and M9000 systems that use SPARC64 VI, VII, or VII+ CPUs.

*Platforms based on UltraSPARC T1 CPUs - Sun Fire T1000 and T2000, Sun SPARC Enterprise T1000 and T2000, Netra CP3060, Netra T2000, and
  Sun Blade T6300

*Platforms based on UltraSPARC T2 CPUs - Sun SPARC Enterprise T5120 and T5220, Sun Blade T6230, Netra CP3260, and Netra T5220

*Platforms based on UltraSPARC T2+ CPUs: Sun SPARC Enterprise T5140, T5240 and T5440, Sun Blade T6340, Sun Netra T6340, and Netra T5440

*Platforms based on SPARC T3 CPUs: SPARC T3-1, T3-1B, T3-2 and T3-4, Netra SPARC T3-1, and Netra SPARC T3-1BA

*Sun Java Workstation models: W1100z, W2100z

*Sun Ultra Workstation models: 20, 20 M2, 40, 40 M2

*Sun Fire server models: V20z, V40z, X2100, X2100 M2, X2200 M2, X4100, X4100 M2, X4140, X4200, X4200 M2, X4240, X4440, X4540, X4600,
  X4600 M2, X4640

*Sun Blade server modules: X6220, X6240, X6440, X8400, X8420, X8440

*Netra X4200 M2


text:
Q: Rails IF Statement Not working I'm trying to conditionally show a link based upon some fields in the database, however, neither is set according to the IF statement and the link is showing anyway.
<% if :mobile.present? && :mobile_verified != true %>
    <%= link_to "(Verify Mobile)", :controller => 'users', :action => 'resend_verification', :method=> :post %>
<% end %>

Is something incorrect?

A: Those are symbols, not variables. You probably want to remove the :. Perhaps you meant to prefix them with @, which would be the case if they were instance variables.

A: When you use :, it declare ruby symbol. and when you variable begins with sign @ indicates that they are instance variables.
In general scenario we define instance variables in controller and then we use them in view file. So I guess your code should be like this:
<% if @mobile.present? && @mobile_verified != true %>
    <%= link_to "(Verify Mobile)", :controller => 'users', :action => 'resend_verification', :method=> :post %>
<% end %>

Don't forget to set these variables @mobile and @mobile_verified before using them in above code


text:
Q: Table view in UIViewController doesn't get hidesBarsOnSwipe functionality I have a table view as the first child of a regular UIViewController. I've tried adding the navigation controller's barHideOnSwipeGestureRecognizer gesture recognizer to both my view and table view, but no dice. In the snippet below, blah: is never getting called.
[self.navigationController setHidesBarsOnSwipe:YES];
[self.tableView addGestureRecognizer:self.navigationController.barHideOnSwipeGestureRecognizer];
[self.navigationController.barHideOnSwipeGestureRecognizer addTarget:self action:@selector(blah:)];

I feel like the barHideOnSwipeGestureRecognizer is the way to tap into this nice functionality when not using a top level scroll view controller (collection or table), but I can't figure out exactly how.

A: If you want to hide navigationbar on swipe, meaning when you scroll your tableview in upward direction (goes to down) then
 self.navigationController.hidesBarsOnSwipe = YES;

is enough to achieve this. It will hide the navigationbar and show it again on tap. Make sure you have set proper constraint to tableview. your constraint should be top,bottom,leading and trailing with constant of 0 with nearest neighbor.


text:
Q: MongoDB Aggregation Framework $group using nested operations I have several numeric fields that I need to aggregate. Let's say my document is structured as follows:
_id: 1234,
numValue1: 10,
numValue2: 20,
numValue3: 30,
numValue4: 40

If I wanted to add a computed field to my pipeline using one of the numeric fields, I could do something like this:
db.myCollection.aggregate(
{
  $project : {
    someComputedField : { $add:["$numValue1", 15] }
  }
})

If I wanted to add a computed field based on two of these fields, I know I could do something like this:
db.myCollection.aggregate(
{
  $project : {
    someComputedField : { $add:["$numValue1", "$numValue2"] }
  }
})

Now, my question is what if I needed to do $numValue1 + $numValue2 + $numValue3 + $numValue4?
Or even more interestingly $numValue1 * ($numValue2 + $numValue3) / $numValue4?

A: $add can accept multiple values, so the first case would be:
someComputedField: {$add: ['$numValue1', '$numValue2', '$numValue3', '$numValue4']}

And you can nest operators, so the second case would be:
someComputedField: {
    $divide: [
        {$multiply: [
            '$numValue1', {$add: ['$numValue2', '$numValue3']}
        ]},
        '$numValue4'
    ]
}

A: Better to use map/reduce when query is not simple add.

db.myCollection.mapReduce(function() {
   emit('result', this.numValue1 * (this.numValue2 + this.numValue3) / this.numValue4);
}, function(key, values) {
   var i=0; values.forEach(function(n){i+=n;}); return i;
});

Also aggregation framework and map/reduce have nearly same performance.


text:
Q: When should one use element.isPresent() over ExpectedConditions.presenceOf(element)? While end-to-end testing our app, I am often waiting for a state transition (a modal to close, a button to appear, etc). Blind experimentation has led me to sometimes use browser.wait(ExpectedConditions.presenceOf(someElement), and other times use browser.wait(someElement.isPresent()).
To me, the names imply they're interchangeable. But it isn't so. Is there something about the situations in which I use these that will help me tell which to use when?

A: In my experience, I have used element.isPresent() for when I do not want to specifically verify something. For example I can write:
element.isPresent().then(function(elm){
    if(elm) { //if the element is present, do something  }
    else    { //if the element is not present, do something else  }
});

But if I need some element to be present/visible/clickable in order to execute an expect or something else, then I would use a browser.wait(EC.presenceOf/visibilityOf/elementToBeClickable(element))
It also depends on the element you need to wait for. If its a button that you need to click, you'll have to use elementToBeClickable

A: If we take a look at the code, we will see that isPresent method looks like this
  isPresent(): wdpromise.Promise<boolean> {
    return this.count().then((count) => {
      return count > 0;
    });
  }

While presenceOf is dependent on isPresent
 presenceOf(elementFinder: ElementFinder): Function {
    return elementFinder.isPresent.bind(elementFinder);
  };

In fact they are doing the same. But note, that ExpectedConditions operators, like not, or and etc. expecting ExpectedConditions function as an argument whichpresenceOf is, while isPresent is not.
Sometimes you need more complicated conditions, than to check that one particular element is present browser.wait(someElement.isPresent()). This is where ExpectedConditions constructions are incredibly useful and this is where you would need presenceOf.


text:
Q: c# geocoordinate watcher not giving back correct coords I wrote a c# code to get my coarse position.
The program will run on a laptop, which doesn't have GPS sensors.
namespace WindowsFormsApplication1
{
    class Class1
    {
    private GeoCoordinateWatcher watcher;

    public void GetLocationDataEvent()
    {
        watcher = new System.Device.Location.GeoCoordinateWatcher();
        watcher.PositionChanged += watcher_PositionChanged;
        watcher.Start();
    }

    private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
    {

        String lat = e.Position.Location.Latitude.ToString();
        String lon = e.Position.Location.Longitude.ToString();

        MessageBox.Show(lat + "+" + lon);
        // Stop receiving updates after the first one.
        watcher.Stop();
    }
  }
}

Well, it works. But it gives me a coord that is nearly 30km away from my position. Are there any other approach to make it more accurate? I can afford about 1 or 2 kms of inaccuracy, but this is just too much.

A: What do you expect without GPS sensors?
GPS is accurate to about 5m on average.
If there are no GPS sensors your OS might:

*

*map your IP address (which is just a rough estimate)

*map your WLAN ID (better, but still just an estimate)

*if you have a GSM module, it may use the nearest GSM sender (accurate to 30 km)

Morale: If you need the exact position you need a GPS module.

A: Your code seems correct, but after starting the GeoCoordinateWatcher the first positions are often inaccurate.
If another application has used your position recently, the GeoCoordinateWather quickly can deliver a accurate position, but if not it first has to start other location services on your computer, and this can take some time.
You could add a check for accuracy:
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
    if (e.Position.Location.HorizontalAccuracy > 500)
    {
        return;
    }

    String lat = e.Position.Location.Latitude.ToString();
    String lon = e.Position.Location.Longitude.ToString();

    MessageBox.Show(lat + "+" + lon);
    // Stop receiving updates after the first one.
    watcher.Stop();
}

This will keep waiting until the accuracy is at least 500 meters.