text:
Q: How to find out where the main function in an .exe file is? I created a simple .exe file that just assigns a value of 3 to an integer called "x" and then prints out that value.Here is a picture of the source code:
source code
I opened the .exe file with an hex editor(named HxD) and used the disassembly function of Visual Studio 2017 to show me the opcodes of my main function. After a bit of search i found out that the main function is stored in the file at Offset 0xC10
Here is the disassembly:disassembly
And here is the file in the Hex-Editor:hexadecimal view of .exe file
I know that some values of the .exe file in the hex editor vary from what the visual studio debugger says but i know that the main starts there because i changed the value of x in the hex editor and then when i started the .exe it printed out another value instead of the 3. My question is where in the .exe file is the value that says:"At that point of the file start the opcodes of the main function."
For example in a .bmp file the 4 bytes at positions 0x0A,0x0B,0x0C and 0x0D tell you the offset of the first byte of the first pixel.

A: On Windows, the entry point of an executable (.exe) is set in the PE Header of the file.
WikiPedia illustrates the structure of this header like this (SVG file).
Relative to the beginning of the file, the PE Header starts at the position indicated at the address

DWORD 0x3C Pointer to PE Header

      File Header / DOS Header
     +--------------------+--------------------+
0000 |  0x5A4D  |         |                    |
0008 |                    |                    |
0010 |                    |                    |
0018 |                    |                    |
0020 |                    |                    |
0028 |                    |                    |
0030 |                    |                    |
0038 |                    | PE Header addr     |
0040 |                    |                    |
.... | .................. | .................. |

And the entry point is designated at the position (relative to the address above)

DWORD 0x28 EntryPoint

      PE Header
     +--------------------+--------------------+
0000 | Signature          | Machine | NumOfSect|
0008 | TimeDateStamp      | PtrToSymTable      |
0010 | NumOfSymTable      |SizOfOHdr| Chars    |
0018 | Magic   | MJV| MNV | SizeOfCode         |
0020 | SizeOfInitData     | SizeOfUnInitData   |
0028 | EntryPoint (RVA)   | BaseOfCode (RVA)   |
0030 | BaseOfData (RVA)   | ImageBase          |
0038 | SectionAlignment   | FileAlignment      |
0040 | ...                | ...                |

from the beginning of the PE Header. This address is a RVA (Relative Virtual Address) what means that it is relative to the Image Base address that the file is loaded to by the loader:

Relative virtual addresses (RVAs) are not to be confused with standard virtual addresses. A relative virtual address is the virtual address of an object from the file once it is loaded into memory, minus the base address of the file image.

This address is the address of the main function.

A: A .exe is a portable executable.

Layout
Structure of a Portable Executable 32 bit
  A PE file consists of a number of headers and sections that tell the dynamic linker how to map the file into memory. An executable image consists of several different regions, each of which require different memory protection; so the start of each section must be aligned to a page boundary.[4] For instance, typically the .text section (which holds program code) is mapped as execute/readonly, and ...

So really it is a question of where the .text section is in the file.  Exactly where depends on the headers and locations of the other sections.


text:
Q: Using a form option value as a PHP variable to execute prepared SQL statement I just started using PHP last week and I've been searching around for a solution for this quite extensively but I can't wrap my brain around the answers I've come across.
I essentially have a form that looks like this in index.html:
<form method="post" action="actionTest.php">
    <select name="courseID">
        <option value = "111">Course 1</option>
        <option value = "222"> Course 2 </option>
        <option value ="333"> Course 3 </option>
    </select>
    <input type="submit" />
</form>

And then a prepared statement in my actionTest.php file
//variable for selected option value?
//$courseSelect = [???]

//query
$sql = "SELECT * FROM courses WHERE course_id = ?";

//prepare the query
$q = $con->prepare($sql);

//execute the statement
$q->execute();

//setting fetch mode for statement
$q->setFetchMode(PDO::FETCH_ASSOC);

//display fetched data
while($r = $q->fetch()){
    echo $r['name'] . "\n";
    echo $r['course_id'] . "\n";
    echo $r['description'] . "\n";
    echo "
";
}

I've written a simple PHP script that will echo what value has been selected when you submit the form, so I know I can retrieve the value I need.  I guess I'm generally confused about how to store the option value in a variable to pass to the query.  Any help or references to help are greatly appreciated!

A: It seems you are looking for PDO bindParam()
First, get your posted value. This code sets the variable to false if no value is posted:
$course_id= isset($_POST['courseID']) ? $_POST['courseID'] : false;

Then prepare your query:
// query
$sql = "SELECT * FROM courses WHERE course_id = ?";

// prepare query
$q = $con->prepare($sql);

// bind the parameter to the query
$q->bindParam(1,$course_id,PDO::PARAM_INT);

//execute the statement
$q->execute();

//display fetched data
while($r = $q->fetch(PDO::FETCH_ASSOC)){
    echo $r['name'] . "\n";
    echo $r['course_id'] . "\n";
    echo $r['description'] . "\n";
    echo "
";
}

Alternatively, in your context you can skip the bind and just execute with your parameter:
$q->execute(array($course_id));

A: By reading from the manual (http://nl1.php.net/pdo.prepared-statements) you can bind your param in this way:
$q = "SELECT * FROM courses WHERE course_id = ?";
$q->bindParam(1, $myValue, PDO::PARAM_INT);

// insert one row
$myValue = $_POST['courseID'];
$q->execute();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Semantic difference between "minimum suggested donation" and "suggested minimum donation"? For example, admission to a benefit concert may be afforded by a suggested minimum donation.  Or perhaps by a minimum suggested donation.  To me, the latter feels not quite right, like the minimum qualifier is being applied to the wrong place.
In fact, I think that adding minimum and suggested should be mutually exclusive here.  Either the donation is a suggested amount, or it has a specified minimum.  I can see, though, that the intention is to not place a hard limit on the entry fee, otherwise it's not really more than a ticket price.  And at the same time, they want to encourage donations that are more than the minimum.
So, given that both adjectives are applied, is there a semantic difference when you switch the order?

A: The meanings are definitely different in my mind. When you say "minimum suggested donation," you could be emphasizing that the donation is only a suggestion, not required. "Suggested minimum donation" could imply that a donation is required, and it should be at least this amount. There are other ways to interpret either, but these two seemed particularly likely to my ear. Any use of these  phrases requires additional context or prior understanding.

A: There is a subtle semantic difference. When you say "suggested minimum donation", it means that the minimum donation have already been explicitly suggested (i.e. there are alternative amounts suggested and one of them is already referred to as the "minimum donation"). On the other hand, "minimum suggested donation" may not have the qualifier "minimum" explicitly, when the suggested donation alternatives were listed (i.e. the alternatives are just listed without pointing out which one is the minimum). In this case, the readers or audience may need to do the figuring out which one is the minimum by going through the list and comparing each list element.


text:
Q: how to skip labels like category using GMAIL API I am using GMAIL API over REST Interface to read mails. I could see an API to get Label list for a user mailbox but my question is that can we differentiate between standard and custom folders and other category. Can I skip the categories like Forum, Personal, updates, social and also Unseen, UNREAD labels. Is there any enum defined for it because if I consider the names then it might get changed for different languages?
Thanks
Haseena

A: The resources returned by various label methods have a "type" field that indicates whether they are system-defined or user-defined labels: Users.labels - Gmail API — Google Developers


text:
Q: Django Sign Up with extra fields I have expanded my SignUp form with UserCreationForm and make email activations. And all works perfect, but I don't understand how I address the new variable.
I can't display it in a template and I do not find it in the user admin panel.
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from customuser.models import User

class SignUpForm(UserCreationForm):
    phone = forms.CharField(max_length= 20)   #<--my new variable

    class Meta:
        model = User
        fields = ('phone', 'email', 'password1', 'password2',)

views.py
def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            mail_subject = 'Activate your blog account.'
            message = render_to_string('reg/acc_active_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid':urlsafe_base64_encode(force_bytes(user.pk)),
                'token':account_activation_token.make_token(user),
            })
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(
                        mail_subject, message, to=[to_email]
            )
            email.send()
            return HttpResponse('Please confirm your email address to complete the registration')
    else:
        form = SignUpForm()
    return render(request, 'reg/signup.html', {'form': form})

def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        login(request, user)
        # return redirect('index')
        return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
    else:
        return HttpResponse('Activation link is invalid!')

If I try insert phone at the html template like {{ user.phone }} I can't see anything. If I try add phone at the admin.py file like this
admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from django.utils.translation import ugettext_lazy as _
from .models import User

@admin.register(User)
class UserAdmin(DjangoUserAdmin):
    """Define admin model for custom User model with no email field."""

    fieldsets = (
        (None, {'fields': ('email', 'phone' ,'password',)}),
        (_('Personal info'), {'fields': ('first_name', 'last_name')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'password1', 'password2'),
        }),
    )
    list_display = ('email', 'first_name', 'last_name', 'is_staff')
    search_fields = ('email', 'first_name', 'last_name')
    ordering = ('email',)

Error appears
Unknown field(s) (phone) specified for User. Check fields/fieldsets/exclude attributes of class UserAdmin.

My custom user model
models.py
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models
from django.utils.translation import ugettext_lazy as _

class UserManager(BaseUserManager):
    """Define a model manager for User model with no username field."""

    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """Create and save a User with the given email and password."""
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        """Create and save a regular User with the given email and password."""
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        """Create and save a SuperUser with the given email and password."""
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)

class User(AbstractUser):
    """User model."""

    username = None
    email = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

A: You need to understand the difference between a Form and a Model in Django. A Form (also a ModelForm) is just what it says, a Django representation of the HTML form you present to the user. It's only purpose is to make it easy to submit data via a POST request.
The form cannot just save to the database, unless there's an underlying model. With a plain Form, you would have to do this in your view handling the POST request:
if request.method == 'POST':
    form = MyForm(data=request.POST)
    if form.is_valid():
        my_model = MyModel(param1=form.cleaned_data['param1'], ...)
        my_model.save()
        return redirect(success_url)
    ...

As you can see, both the Model and the Form must have corresponding fields (in the example above param1, etc...).
To make it easier to create forms for a model, Django gives you a ModelForm, where the form 'knows' how to save the underlying model, so you can do:
if request.method == 'POST':
    form = MyModelForm(data=request.POST)
    if form.is_valid():
        my_model = form.save()
        ...

In this case the form will map the form fields to the model fields, so only those model fields that exist on the model can be saved. Your form could contain 5 extra fields not defined on the model, still validate, but nothing happens with those fields when you save the form, because the model doesn't have them.
Full documentation is here.


text:
Q: Occasional Blob not found error on a firebird database I'm useing Firebird in conjunction with IBX (I know one should not do that but it's a legacy application I need to maintain...).
When running that application (an apache shared module) under heavy load
I occasionaly get an exception message "blob not found" - and that although the query was executed a hundered times before without any problems.
When googling for that problem I found that forced write should be enabled (which actually is the case) but nothing else....
The query by the way is rather simple. Just a "select * from" with a left out join attached.
The problem occurs when reading a Blob (subtype text).....


text:
Q: streamlit plot Python I have a code that reads data and produces 4 plots, using the sidebar, the user can select which plot to display, up to 4, if none is selected, the page is clear, each plot has its own position, 4 corners, here is part of the plot that shows the case with the data needed:
import pandas as pd
import streamlit as st
import plotly.express as px
import streamlit as st

data = [['No','Time','Source','Destination','Protocol','Length'],
        ['1','26-02-23 12:17','192.168.0.105','192.168.0.1','TCP','66'],
        ['2','26-02-23 12:17','52.98.228.210','192.168.0.105','TLSv1.2','1151'],
        ['3','26-02-23 12:17','52.98.228.210','192.168.0.105','TCP','1514'],
        ['4','26-02-23 12:17','52.98.228.210','192.168.0.105','TLSv1.2','72'],
        ['5','26-02-23 12:17','192.168.0.105','52.98.228.210','TCP','54'],
        ['6','26-02-23 12:17','52.98.228.210','192.168.0.105','TLSv1.2','88'],
        ['7','26-02-23 12:17','192.168.0.105','52.98.228.210','TCP','54'],
        ['8','26-02-23 12:17','192.168.0.105','52.98.228.210','TCP','54'],
        ['9','26-02-23 12:17','192.168.0.105','239.255.255.250','UDP','698'],
        ['10','26-02-23 12:17','192.168.0.104','239.255.255.250','UDP','698'],
        ['11','26-02-23 12:17','192.168.0.105','192.168.0.1','TCP','66'],
        ['12','26-02-23 12:17','192.168.0.1','224.0.0.251','IGMPv2','60'],
        ['13','26-02-23 12:17','192.168.0.105','224.0.0.22','IGMPv3','54'],
        ['14','26-02-23 12:17','192.168.0.104','224.0.0.22','IGMPv3','60'],
        ['15','26-02-23 12:17','192.168.0.100','224.0.0.251','IGMPv2','60'],
        ['16','26-02-23 12:17','192.168.0.101','224.0.0.251','IGMPv2','60'],
        ['17','26-02-23 12:17','192.168.0.105','128.75.237.113','TCP','66'],
        ['18','26-02-23 12:17','128.75.237.113','192.168.0.105','TCP','66'],
        ['19','26-02-23 12:17','192.168.0.105','128.75.237.113','TCP','54'],
        ['20','26-02-23 12:17','192.168.0.105','128.75.237.113','HTTP','178']]

df = pd.DataFrame(data[1:],columns=data[0])

 #Setting page header
st.header('Network Monitoring Charts')

# Ploting top 10 Inbound traffic IP addresses
#st.header('Top 10 Inbound traffic IP addresses')
inbound_ip_count = df.groupby('Source').size().nlargest(n=10)
top_in_IP = px.bar(df['Source'],
                   x=inbound_ip_count.index, y= inbound_ip_count.values,
                   title='Top 10 incoming traffic IP addresses')

# Ploting top 10 Outbound traffic IP addresses
#st.header('Top 10 Onbound traffic IP addresses')
outbound_ip_count = df.groupby('Destination').size().nlargest(n=10)
top_out_IP = px.bar(df['Destination'],
                   x=outbound_ip_count.index, y=outbound_ip_count.values,
                   title='Top 10 Outbound traffic IP addresses')

# Ploting top 10 traffic ports
#st.header('Top 10 traffic ports')
port_count = df.groupby('Protocol').size().nlargest(n=10)
top_ports = px.bar(df['Protocol'],
                   x=port_count.index, y=port_count.values,
                   title='Top 10 Active Ports')

# Ploting top 5 inbound IP addresses and their top active ports
# Group by Source and Protocol, count the occurrences, and sort by count in descending order
sources_grp = df.groupby(['Source', 'Protocol'], as_index=False)['Destination']\
    .count().sort_values('Destination', ascending=False)

# Get the top 5 occurrences of Source
top_sources = df['Source'].value_counts()[:5].index.tolist()

# Filter the dataframe to only include the top 5 occurrences of Source
top_sources_df = sources_grp[sources_grp['Source'].isin(top_sources)]\
    .reset_index(drop=True)

# Rename the count column to 'Protocol Count'
top_sources_df = top_sources_df.rename(columns={'Destination': 'Protocol Count'})

# Get the top 5 occurrences of Protocol within the top sources
top_protocols = top_sources_df['Protocol'].value_counts()[:5].index.tolist()

# Filter the dataframe to only include the top 5 occurrences of Protocol
top_protocols_df = top_sources_df[top_sources_df['Protocol']\
                   .isin(top_protocols)].reset_index(drop=True)

# plot the long (tidy) dataframe
combo = px.bar(top_protocols_df, x="Source", y="Protocol Count",
               color="Protocol",\
               title="Top 5 inbound IP addresses and their top active Ports",\
               barmode='group')
combo.update_layout(xaxis_title='IP Addresses', yaxis=dict(tickformat=\
               "Protocol Count",))

#reports = ['Top Inbound IP Addresses', 'Top Outbound IP Addresses',\
#'Top Active Ports', 'Top Active IP-Ports']

st.sidebar.header('Please select your report to display')
# Diagrams selection - Sidebar
check1 = st.sidebar.checkbox('Top Inbound IP Addresses')
check2 = st.sidebar.checkbox('Top Outbound IP Addresses')
check3 = st.sidebar.checkbox('Top Active Ports')
check4 = st.sidebar.checkbox('Top Active IP-Ports')

left_column1, right_column1 = st.columns(2)
left_column2, right_column2 = st.columns(2)

if check1:
    left_column1.plotly_chart(top_in_IP, use_container_width=True)
if check2:
    right_column1.plotly_chart(top_out_IP, use_container_width=True)
if check3:
    left_column2.plotly_chart(top_ports, use_container_width=True)
if check4:
    right_column2.plotly_chart(combo, use_container_width=True)

I want to have the plots displayed according to the selection sequence, not pre-defined as per this code
Currently this code position each plot in a specific location, so if I pick the first and forth plots, they show diagonally, but I want them next to each other, and if the second one from the list is selected 3rd, then it will appear in the second row, as each row has two plots

*

*Streamlit version: 1.19.0

*Python version: 3.9.13


text:
Q: Simple ajax GET request not working on my Django webpage I'm very new to both Django and Ajax (it's my first time using both) and I am receiving an error with my code. Basically I have an HTML button, on a webpage generated by a template in Django, that should call a function onclick which is assigned using jquery. When clicked, the button should send a GET request to the webpage with the specified url. That's all I want it to do, however, it just does not seem to work. It keeps throwing an error. Here is some of the code:
<button class="btn btn-primary toChange">Click me</button>

and

    $(".toChange").click(function(){
        $.ajax({
            url: 'localhost:8000/MyApp/ajax_test',
            type: 'GET',
            success: function(data) {
                alert(data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(JSON.stringify(jqXHR));
                console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
            }
        });
      //alert("Something happened!")
    });

</script>

and my view for what I'm trying to get is:
def test(request):
    return HttpResponse("Congrats, you've got it!")

Currently, I am using firefox to look at the webpage on localhost:8000. If I look at the console when I click the button, this is what I see.
{"readyState":0,"status":0,"statusText":"[Exception... \"<no message>\"   nsresult: \"0x805e0006 (<unknown>)\"  location: \"JS frame :: https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js :: .send :: line 5\"  data: no]"}

AJAX error: error : [Exception... "<no message>"  nsresult: "0x805e0006 (<unknown>)"  location: "JS frame :: https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js :: .send :: line 5"  data: no]

I tried researching the errors and I'm not sure but it could be an error with firefox not allowing the request to go through. Can someone help me please?

A: Change your url from:
$(".toChange").click(function(){
    $.ajax({
        url: 'localhost:8000/MyApp/ajax_test', # change here

to
$(".toChange").click(function(){
    $.ajax({
        url: '/MyApp/ajax_test',


text:
Q: OpenCV Eye Tracking looses out for some frames I am pasting code below to track both eyes and overlay an image when both eyes are tracked.
I am using haar xml files to track both eyes of faces and overlaying an image over it.
My problem is I get result like this.
Img 1

Img 2

Img 3

Img 4

Img 5

Img 6

Img 7

Img 8

Img 9

Img 10

I am posting my code below
#include "cv.h"
#include "highgui.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <stdio.h>
#include <sys/stat.h>
#include <ctype.h>
#include <string>
using namespace cv;
using namespace std;

void detectAndDisplay( Mat frame );
String face_cascade_name = "/root/opencv/newtutorial/haarcascade_frontalface_alt.xml";
String eyes_cascade_name = "/root/opencv/newtutorial/haarcascade_eye_tree_eyeglasses.xml";
CascadeClassifier face_cascade;
CascadeClassifier eyes_cascade;
RNG rng(12345);
IplImage *disp,*neg_img,*cpy_img,*imga;
IplImage *pic;
IplImage  *image_n = 0;
int make=0;
CvMat* warp_matrix = cvCreateMat(3,3,CV_32FC1);
namespace {
    void makevdo(){
        bool flag = false;
        fstream fin;
        char filename_new[200],filename_new_after[200];
        int n=0;
        Mat frame;
        double frameRate = 25.0;
        CvVideoWriter *vdowriter = cvCreateVideoWriter( "/root/opencv/newtutorial/test_converted_next.mov", CV_FOURCC('j','p','e','g'), frameRate, Size(640,480) );
        VideoWriter(outputFile,CV_FOURCC('j','p','e','g'),frameRate,Size(640,480));
        while(flag==false){
            sprintf(filename_new,"/root/opencv/newtutorial/mydirnext/filename%.3d.jpg",n);
            sprintf(filename_new_after,"/root/opencv/newtutorial/framesaftertrack/filename%.3d.jpg",n);
            fin.open(filename_new,ios::in);
            if( fin.is_open() )
            {
                frame = imread(filename_new);
                pic = cvLoadImage("/root/opencv/newtutorial/pic.png");
                image_n = cvLoadImage(filename_new,1);
                disp = cvCreateImage( cvGetSize(image_n), 8, 3 );
                cpy_img = cvCreateImage( cvGetSize(image_n), 8, 3 );
                neg_img = cvCreateImage( cvGetSize(image_n), 8, 3 );
                std::vector<Rect> faces;
                Mat frame_gray;
                cvtColor( frame, frame_gray, CV_BGR2GRAY );
                equalizeHist( frame_gray, frame_gray );
                face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );
                CvPoint2D32f q[4];
                q[0].x= (float) pic->width * 0;
                q[0].y= (float) pic->height * 0;
                q[1].x= (float) pic->width;
                q[1].y= (float) pic->height * 0;
                q[2].x= (float) pic->width;
                q[2].y= (float) pic->height;
                q[3].x= (float) pic->width * 0;
                q[3].y= (float) pic->height;
                for( int i = 0; i < (int)faces.size(); i++ )
                {
                    faces[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 2, 8, 0 );
                    Mat faceROI = frame_gray( faces[i] );
                    std::vector<Rect> eyes;
                    eyes_cascade.detectMultiScale( faceROI, eyes, 1.1, 2, 0 |CV_HAAR_SCALE_IMAGE, Size(30, 30) );
                    if((int)eyes.size()==2 && (((eyes[0].x + eyes[0].width*0.5 ) < eyes[1].x) || ((eyes[1].x + eyes[1].width*0.5 ) < eyes[0].x))){
                        CvPoint2D32f p[4];
                        IplImage* blank  = cvCreateImage( cvGetSize(pic), 8, 3);
                        cvZero(blank);
                        cvNot(blank,blank);
                        if(eyes[0].x<eyes[1].x){
                            Point center0( faces[i].x + eyes[0].x + eyes[0].width*0.5, faces[i].y + eyes[0].y + eyes[0].height*0.5 );
                            float radius0 =  (eyes[0].width + eyes[0].height)*0.25 ;
                            Point center1( faces[i].x + eyes[1].x + eyes[1].width*0.5, faces[i].y + eyes[1].y + eyes[1].height*0.5 );
                            float radius1 =  (eyes[1].width + eyes[1].height)*0.25 ;
                            p[2].x= (float) center0.x - radius0;
                            p[2].y= (float) center0.y + radius0;
                            p[1].x= (float) center0.x - radius0;
                            p[1].y= (float) center0.y - radius0;
                            p[3].x= (float) center1.x + radius1;
                            p[3].y= (float) center1.y + radius1;
                            p[0].x= (float) center1.x + radius1;
                            p[0].y= (float) center1.y - radius1;
                        }
                        else{
                            Point center0( faces[i].x + eyes[1].x + eyes[1].width*0.5, faces[i].y + eyes[1].y + eyes[1].height*0.5 );
                            float radius0 =  (eyes[1].width + eyes[1].height)*0.25 ;
                            Point center1( faces[i].x + eyes[0].x + eyes[0].width*0.5, faces[i].y + eyes[0].y + eyes[0].height*0.5 );
                            float radius1 =  (eyes[0].width + eyes[0].height)*0.25 ;
                            p[2].x= (float) center0.x - radius0;
                            p[2].y= (float) center0.y + radius0;
                            p[1].x= (float) center0.x - radius0;
                            p[1].y= (float) center0.y - radius0;
                            p[3].x= (float) center1.x + radius1;
                            p[3].y= (float) center1.y + radius1;
                            p[0].x= (float) center1.x + radius1;
                            p[0].y= (float) center1.y - radius1;
                        }

                        cvGetPerspectiveTransform(q,p,warp_matrix);
                        cvZero(neg_img);
                        cvZero(cpy_img);
                        cvWarpPerspective( pic, neg_img, warp_matrix);
                        cvWarpPerspective( blank, cpy_img, warp_matrix);
                        cvNot(cpy_img,cpy_img);
                        cvAnd(cpy_img,image_n,cpy_img);
                        cvOr(cpy_img,neg_img,image_n);
                    }
                }
                cvSaveImage(filename_new_after,image_n);
                cvWriteFrame(vdowriter,image_n);
                cout<<"Read file filename"<< n <<endl;
            }
            else{
                flag=true;
            }
            fin.close();
            n++;
        }
        cvReleaseVideoWriter(&vdowriter);
        cvReleaseImage(&pic);
        cvReleaseImage(&imga);
        cvReleaseImage(&disp);
        cvReleaseImage(&neg_img);
        cvReleaseImage(&cpy_img);
        cvReleaseImage(&image_n);
    }

    int process(VideoCapture& capture) {
        char strFrame[]="/root/opencv/newtutorial/mydirnext";
        if(mkdir(strFrame,0777)==-1)
        {
            cout<<"Error Trying to delete"<<endl;
            if(system("rm -r /root/opencv/newtutorial/mydirnext")){
                cout << "Directory successfully deleted"<<endl;
            }
            if(mkdir(strFrame,0777)==-1){
                cout << "Error Again creating directory" << endl;
            }
        }
        int n = 0;
        char filename[200];
        string window_name = "video | q or esc to quit";
        cout << "press space to save a picture. q or esc to quit" << endl;
        namedWindow(window_name, CV_WINDOW_KEEPRATIO);
        Mat frame;
        for (;;) {
            capture >> frame;
            if (frame.empty())
                continue;
            imshow(window_name, frame);
            sprintf(filename,"/root/opencv/newtutorial/mydirnext/filename%.3d.jpg",n++);
            imwrite(filename,frame);
            char key = (char)waitKey(5);
            switch (key) {
            case 27:
                if(make==0){
                    make=1;
                    makevdo();
                }
            return 0;
            default:
            break;
            }
        }
        return 0;
    }
}
int main(int ac, char** av) {
    if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
    if( !eyes_cascade.load( eyes_cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
    if (ac != 2) {
        return 1;
    }
    std::string arg = av[1];
    VideoCapture capture(arg);
    if (!capture.isOpened())
        capture.open(atoi(arg.c_str()));
    if (!capture.isOpened()) {
        cerr << "Failed to open a video device or video file!\n" << endl;
        return 1;
    }
    return process(capture);
}

Sorry for posting so many Images SO, but No other way to explain my problem.

A: Start by extracting everything to methods/functions that you can be given a sensible name. We don't want to see methods longer than 10 lines. The images are not helpful at all. Remove the overlay and show what the algorithm claims to recognize, when it does so.
After you've done that, feed it sequences of the same images. First the ones where it recognizes, then those where it doesn't. That way you can get a better guess where the problem is. But first clean up the messy code.


text:
Q: Callback Event for Cordova inAppBrowser I have an app that access external link through Cordova inAppBrowser.
I want a way to listen to an event when a user returns to the app from the external url.
Currently i can listen to event when inAppBrowser is called like so.
        var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
        var myCallback = function(event) {
                        alert(event.url);
                    };
       ref.addEventListener('loadstart', myCallback);

I want to listen to an event when user returns to the app from the external link.

A: The load events documented for the InAppBrowser only work with the page you're loading in the InAppBrowser. I'm guessing you want to capture when the user clicks the done button and goes back to the app? If thats the case you should look into handling the exit event.
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {

    function onExit(){
        alert("InAppBrowser Closed!");
    }

    var inAppBrowser = cordova.InAppBrowser.open("http://apache.org" ,"_blank", "location=yes");

    inAppBrowser.addEventListener('exit', onExit);
}


text:
Q: Rewriting maximization and minimization of $|2x_1-3x_2|$ as linear programs
$$\begin{array}{ll} \text{maximize} & |2x_1-3x_2|\\ \text{subject to} & 4x_1+x_2 \le 4\\ & 2x_1-x_2 \le 0.5\\ & x_1,x_2 \ge 0\end{array} \tag{Problem 1}$$

$$\begin{array}{ll} \text{minimize} & |2x_1-3x_2|\\ \text{subject to} & 4x_1+x_2 \le 4\\ & 2x_1-x_2 \le 0.5\\ & x_1,x_2 \ge 0\end{array} \tag{Problem 2}$$

According to the question, one of them can be rewritten as a linear program (LP), and the other one cannot. The question asks the reader to determine which one can be rewritten as an LP, and why the other one cannot.
I've never converted to an LP an optimization problem whose objective function contains an absolute value. So, I think I have no way of determining the one that can be rewritten as an LP. But, I know the simplex method and I can solve an LP using it.

A: For problem $2$: replace the objective function by a new variable $t\ge 0$, and add the constraints
\begin{cases}
2x_1-3x_2 \le t \\
-2x_1 +3x_2 \le t
\end{cases}
These constraints are equivalent to $-t \le 2x_1-3x_2 \le t$, and so the absolute value is taken into account.
Since you are minimizing $t$, you are minimizing $\mid 2x_1-3x_2 \mid $ indeed.
It is not difficult to see that this does not work if you are maximizing $t$.

A: Let $f (x, y) := | 2 x - 3 y |$. Note that $f$ is convex. Its epigraph is the convex set
$$\left\{ (x,y,z) \in \mathbb R^3 \mid z \geq 2 x - 3 y \land z \geq - 2 x + 3 y \right\}$$
Hence, the minimization problem ("problem 2") can be written as the following linear program
$$\boxed{\begin{array}{ll} \text{minimize} & z\\ \text{subject to} & \begin{bmatrix} 2 & -3 & -1\\ -2 & 3 & -1\\ 4 & 1 & 0\\ 4 & -2 & 0\end{bmatrix} \begin{bmatrix} x\\ y\\ z\\ \end{bmatrix} \leq \begin{bmatrix} 0\\ 0\\ 4\\ 1\end{bmatrix}\\ & x, y, z \geq 0\end{array}}$$
The maximization problem ("problem 1") can be written in minimization form as follows
$$\begin{array}{ll} \text{minimize} & -|2 x - 3 y|\\ \text{subject to} & 4x + y \leq 4\\ & 4x - 2y \leq 1\\ & x, y \geq 0\end{array}$$
where the objective function $g (x, y) := - f (x, y)$ is concave. Thus, the epigraph of $g$ is non-convex and cannot be defined by the intersection of half-spaces. Although we cannot write "problem 1" as a linear program, we can write is as two linear programs, namely,
$$\begin{array}{ll} \text{minimize} & -2 x + 3 y\\ \text{subject to} & 4x + y \leq 4\\ & 4x - 2y \leq 1\\ & 2 x - 3 y \geq 0\\ & x, y \ge 0\end{array}$$
and
$$\begin{array}{ll} \text{minimize} & 2 x - 3 y\\ \text{subject to} & 4x + y \leq 4\\ & 4x - 2y \leq 1\\ & 2 x - 3 y \leq 0\\ & x, y \ge 0\end{array}$$
We solve both linear programs and then take the minimum of the two minima. Reversing the sign, we obtain the maximum of "problem 1".

Addendum
From Boyd & Vandenberghe:


text:
Q: Python Playwright with pytest - Test against different environments and different variables Im looking to use Playwright on python/pytest to test against a web page.
The system im working on has 3 different environments that we need to deploy against,
for example https://env1.com, https://env2.com, https://env3.com
The first question is how do I target the different Environment? In my pytest.ini I had a --base-url parameter but I need to override that.
In addition each environment has different login credentials, how can I create and override these as parameters per environment?


text:
Q: How to fix windows update error 800700A1? Windows update is trying to install KB3205401, however it always fails with 800700A1. How can I fix that?

A: You might find this article helpfull, https://answers.microsoft.com/en-us/windows/forum/windows8_1-update/kb3205401-december-update-fails-to-install-with/b9369e9b-2ac4-4c2c-98c3-ee45fb3cf79d
Also, The ONLY thing that worked for was this.

*

*I went into the C:\Windows\Temp directory as an administrator and made a copy.

*Then deleted all of the items in this directory (About four items were still in use).

*Then went back to Windows Update and got the windows update from Microsoft Update / Windows Update (Rather than WSUS).

*Installed all the updates that I needed.


text:
Q: StackExchange.Redis: No connection is available to service this operation: SET I created a Console Application running on .NET Core 1.1 and I'm referencing the StackExchange.Redis NuGet package, version 1.2.3
When running the code below, I get the following error:
It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketFailure on PING
using StackExchange.Redis;
using System;

namespace RedisConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
            IDatabase db = redis.GetDatabase();
            db.StringSet(BitConverter.GetBytes(5), "asdf");
        }
    }
}

If I change the Connect string to "localhost,abortConnect=false", then I get this error message:
No connection is available to service this operation: SET \u0005\0\0\0; SocketFailure on localhost:6379/Subscription, origin: Error, input-buffer: 0, outstanding: 0, last-read: 1s ago, last-write: 1s ago, unanswered-write: 27780s ago, keep-alive: 60s, pending: 0, state: Connecting, last-heartbeat: never, last-mbeat: -1s ago, global: 20s ago
I followed the Basics guide to get started using this library but I keep getting the errors above.
Am I missing some code or configuration?

A: It sounds like you might have only set up the StackExchange.Redis client, did you install and start up your local Redis server? If not, use HomeBrew to download and install Redis on your machine
brew install redis
brew services start redis

and start the server with
redis-server

A: Try adding ssl=True,abortConnect=False,sslprotocols=tls12 under your connection string


text:
Q: What happens if I don't close a txt file I'm about to write a program for a racecar, that creates a txt and continuously adds new lines to it. Unfortunately I can't close the file, because when the car shuts off the raspberry (which the program is running on) gets also shut down. So I have no chance of closing the txt.
Is this a problem?

A: Yes and no. Data is buffered at different places in the process of writing: the file object of python, the underlying C-functions, the operating system, the disk controller. Even closing the file, does not guarantee, that all these buffers are written physically. Only the first two levels are forced to write their buffers to the next level. The same can be done by flushing the filehandle without closing it.
As long as the power-off can occur anytime, you have to deal with the fact, that some data is lost or partially written.
Closing a file is important to give free limited resources of the operating system, but this is no concern in your setup.


text:
Q: Randomly skip 'X' percentage of words from Java Iterator I have some java code as :
   String line = value.toString();
   StringTokenizer tokenizer = new StringTokenizer(line);

   while (tokenizer.hasMoreTokens()) {
         // do someything
   }

However, I want the code to randomly skip X percentage of tokens.
Example :
If tokens are [a , b , c , d] and skip percentage is 50%
Valid execution could be printing any two tokens, say [ b , c ] or [a , d] etc
How can I implement it in the simplest manner?

A: first calculate the amount to skip i.e. (.50)*tokens.length
(note thats pseudo code)
Then I would create an array of length tokens.length and fill it with the selected amount of 1's and the rest 0's
i.e. for 50% of 10
[1,1,1,1,1,0,0,0,0,0]
Then do a simple shuffle algorithm (Random shuffling of an array)
to get something like
[0,1,1,0,0,1,0,1,1,0]
Then as you run through your tokenizer loop walk throught this array and check
(if thisArray[i]==1){
  print(token);
}

A: First Solution:
double percentage = 50.0;
int max = (int)percentage * token.length;

int[] skip = new int[token.length];
int count = 0;
while(count < max)
{
    int rand = rnd.nextInt(token.length);
    if(skip[rand] == 0){
        skip[rand] = 1;
        count++;
    }
}

//Use a for loop to print token where the index of skip is 0, and skip index of those with 1.

You may consider this. Create a 1D array of switches (Can be boolean too).
Generate 1D array of random switches with size similar to token length. Print token element if switch of the corresponding index is true, else don't print.

Second solution:
Convert your token of array to an arrayList.
int count = 0, x = 0;

while(printed < max){  //where max is num of elements to be printed

    int rand = rnd.nextInt(2); //generate 2 numbers: 50% chance

    if (rand == 0){
        System.out.println(list.get(x);
        list.remove(x);
        printed ++;
    }
    x++;
}

Roll a probability (e.g. 50% chance) whether to print current element for every iteration.
Once element is printed, remove it from list, so you won't print duplicates.

Third solution:
Randomly remove a percentage (e.g. 50%) of elements from your token. Just print the rest. This is probably one of the most straight forward way I can think of.

A: The following uses Floyd's subset selection algorithm to select a random subset of specified size.  This may be overkill for a small number of tokens, but it's pretty darned efficient for larger sets.
import java.util.HashSet;

public class FloydsSubsetSelection {

   /*
    * Floyd's algorithm to chose a random subset of m integers
    * from a set of n, outcomes are zero-based.
    */
   public static HashSet<Integer> generateMfromN(int m, int n) {
      HashSet<Integer> s = new HashSet<Integer>();
      for (int j = n-m; j < n; ++j) {
         if(! s.add((int)((j+1) * Math.random()))) {
            s.add(j);
         }
      }
      return s;
   }

   public static void main(String[] args) {
      // Stuff the tokens into an array.  I've used chars,
      // but these could be anything you want.  You can also
      // store them in any container which is indexable.
      char[] tokens = {'a', 'b', 'c', 'd', 'e', 'f'};
      int desired_percent = 50;     // change as desired

      // Convert desired percent to a count.  I added 1/2 to cause rounding
      // rather than truncation, change if different behavior is desired.
      int m = (int) (((desired_percent * tokens.length) + 0.5) / 100.0);
      HashSet<Integer> results = generateMfromN(m, tokens.length);
      for (int i: results) {                 // iterate through the generated subset
         System.out.print(tokens[i] + " ");  // to print the selected tokens
      }
      System.out.println();
   }
}

A:  String line = value.toString();
   StringTokenizer tokenizer = new StringTokenizer(line);
   double percentage = 1.0 / 0.5 // replace 0.5 with the percentage you want
   int x = 0;
   while (tokenizer.hasMoreTokens()) {
         ++x;
         if (x >= percentage) {
              // print here
              x = 0;
         }
   }


text:
Q: Could anyone tell me the basics about the differences of the browsers? Why is it that when you work with different browsers, there's usually different results? Why is simple HTML/css being read differently by the traditional browsers (IE, Mozilla, Chrome and Safari)?
I'm sorry if this question doesn't belong here. I just thought you guys would be the best source of this type of information :)
Have a nice day!

A: This is seemingly a simply question but with a complex answer. Each company has built their browser on a different "layout engines". You may have heard of "Gecko" - The Mozzila Foundation's engine, similarly, Microsoft developed "Trident", Apple uses "WebKit" and Opera uses "Presto". Each interprets the specifications differently, and some just haven't caught up yet. http://en.wikipedia.org/wiki/List_of_web_browsers#Notable_layout_engines
I imagine that your question really is about how to tell the differences, and avoid/work around them.
I found that most of the basic elements work in all browsers. If you have any questions w3schools.com will show with each element how it's supported across browsers. Also, if you keep to 5px increments you can avoid most of the pixel-level browser differences.
There are horrible issues when styling emails. So be extra careful with them.
And finally, DO make sure to check across all browsers when designing. You'll be - unpleasantly - surprised if you don't.


text:
Q: Why is this code stuck in an infinite loop? Why is head is going to some random value?
// Simple insertion at the starting of link list

#include<iostream>
using namespace std;
struct node{
    int d;
    node *next;
}; // creation of node

node *head=new node; // is there any problem?

void insert(int x)
{
    if (head==NULL) { // is there something wrong?
        head->d=x;
        haad->next=NULL;
    } else {
        node *t=new node;
        t->d=x;
        t->next=head;
        head=t;
    }
}

int main() {
    insert(1);           // function calling
    insert(2);           // function calling
    insert(3);           // function calling
    while(head!=NULL) {
        cout<<head->d<<" ";
        head=head->next;
    } // this is going on to infinity
    return 0;
}

This code is lopping till infinity and I am not able to understand why?
Why is head going to some random value after 3 2 1? Is there any problem in declaring head globally?

A: head is going to some random value because the last element in your list is pointing with next to a random value.
This last element is the first node you created in this line:
node *head=new node;

By doing that, you are allocating memory for this node on the heap, however, you're not setting any values to the node's fields, including next. Then in the loop, when head is pointing to the last node (that was allocated first) head->next is not NULL and therefore the loop continues.

Three side notes:

*

*Using head itself to iterate over the list elements is not a good idea since you're losing the pointer to the head of the list.

*head can be declared globally but usually you should have a good reason for that. In your program I'd define it in main() and pass it to the functions that need it.

*This code:
if (head==NULL) { // is there something wrong?
    head->d=x;
    haad->next=NULL;

doesn't make lots of sense: it will never run, and in case it will --> segmentation fault (because if head is NULL you cannot refer to its fields.
Hope it helps.


text:
Q: Vertically center div contained in floating div I have a div that's inside a float:left div and it doesn't want to vertically align.  I thought I could completely fill the floated div with the inner div and set that one to display: table-cell, but it doesn't seem to want to both FILL the div and allow this display?
JSFiddle Here

Report an Issue

Report an Issue

Report an Issue

Report an Issue

Styling:
#tabs-3 { /* Tab Content Panel (Right Panel)*/
    float: left;
    min-height: 300px; /* How tall is our tab box, minimum?*/
    text-align: center;
    background-color: pink;
}

#DivToCenter {
    width: 100%;
    height: 100%;
    background: red;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

#ButtonContainer {
    width: 100%;
    overflow: auto;
    padding-top: 10px;
    padding-bottom: 10px;
    background: green;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

#ButtonContainer > ul {
        padding: 0;
        margin: 0;
        display: inline-block;
}

#ButtonContainer > ul > li {
 display: inline-block; /*Puts the buttons in a line*/
}

.TemplateButton {
    padding-left: 5px;
    padding-right: 5px;
}

.ui-tabs-panel.ui-widget-content .TemplateButton > a {
    /* SHAPE */
    width: 119px;
    height: 119px;
    padding: 15px;
    margin-left: 3px;
    margin-right: 3px;
    border: 1px solid white;
    border-radius: 15px;
    -moz-border-radius: 15px;
    /* ALIGNMENT */
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    /* STYLING */
    font-weight: bold;
    font-size: 1.25em;
    color: white;
    background-color: #0c428f;
}

.ui-tabs-panel.ui-widget-content .TemplateButton > a:hover {
    background-color: #6795bb;
}

A: Just add display: table; to #tabs-3
Updated Demo


text:
Q: Image segmentation based on mouse click Using python framework we are able to create image segments as shown in attachment. Now, based on the mouse click in the image segment we need to highlight the segment with specific color.
Based on the mouse click I am able to get x/y coordinates of the specific location. Please suggest me how can I check on which image segment the coordinates belongs to?
The following is the code snippet:
from skimage.segmentation import felzenszwalb, slic,quickshift
from skimage.segmentation import mark_boundaries
from skimage.segmentation import find_boundaries
from skimage.util import img_as_float
from skimage import io

import matplotlib.pyplot as plt

from skimage import measure
from skimage import restoration
from skimage import img_as_float

import numpy as np

coords = []

def find_nearest(array,value):

    idx = (np.abs(array-value)).argmin()

    return array[idx]

def onclick(event):

    global ix, iy

    ix, iy = event.xdata, event.ydata

    print ('ix ',ix)

    print ("iy ",iy)

    color = np.float64([1,0,1]) # red color

    image[segments == 14] = color

    mark_boundaries(image, segments)

    ax.imshow(mark_boundaries(image, segments))

    coords.append((ix, iy))

    return

image=img_as_float(io.imread("amazon.jpg"))

segments = quickshift(image, ratio=1.0, kernel_size=20, max_dist=10,
           return_tree=False, sigma=0, convert2lab=True, random_seed=42)

fig = plt.figure("Superpixels -- %d segments" % (500))

ax = fig.add_subplot(1, 1, 1)

fig,ax = plt.subplots()

color = np.float64([1,0,0])

image[segments == 14] = color  # desired segment to be colored

fig.canvas.mpl_connect('button_press_event', onclick)

ax.imshow(mark_boundaries(image, segments))

plt.axis("off")

plt.show()

A: According to the documentation, quickshift returns an integer mask indicating segment labels. If you know what pixel the user clicked on, you can check the value of that pixel in your variable segments to get the segment number.
In you click handler, you can use
clicked_segment = segments[event.xdata, event.ydata]


text:
Q: Восстановление работы Windows Management Instrumentation (WMI) после фатального сбоя На компьютере под управлением Windows 10 перестала работать WMI.
Никакие скрипты, раньше нормально работавшие, теперь не функционируют. Диапазон возвращаемых ошибок достаточно велик: 0x80041XXX, 0x800420XX, 0x700310XX ("Инициализация класса WMI невозможна", "Вызов WMI запрещен", "WMI вернул некорректный ответ", "Ошибка в файле WMI.MOF" и так далее).
Возможно ли это исправить? Почему это произошло? Если нет, то можно ли работать без функционирующего WMI?

A: Я столкнулся с этой ситуацией на днях: мои студенты тестировали управление системными функциями и две машины в домене (на обеих – Windows 10) стали возвращать ошибки при работе с Windows Management Instrumentation. Основной админ ещё не вышел из отпуска, пришлось вспоминать, что я бывший руководитель Отдела ИТ :)
Сразу отвечу на третий вопрос: без рабочего WMI, на мой взгляд, можно оставлять лишь домашний игровой компьютер, на котором, кроме игр и просмотра видео, больше ничего не делается (разве что дети учатся программировать). В остальных случаях, особенно на корпоративных машинах, тем более в домене, WMI должна работать как часы. Это моё мнение, кто-то может не согласиться.
Теперь о причинах произошедшего: их может быть очень много. Забегая вперед, скажу что на одной машине это произошло из-за того, что на жестком диске закончилось место, а затем был сбой по питанию из-за сломанного ИБП (увы, никто не застрахован; сервера, конечно, защищены от подобного, а обычная рабочая машинка не была). На второй хуже: нефатальный сбой жесткого диска с последующим BSOD. В целом, разобраться с причинами не так уж и важно, главное, выяснить, что причиной не является вирус или попытка взлома. Впрочем, намеренное удаление или случайная порча системных файлов тоже должны быть рассмотрены достаточно пристально.
Восстановление работоспособности WMI следует проводить поэтапно, от щадящих методов к деструктивным. Следует быть готовым к тому, что в самом худшем случае систему придётся переустановить. Не стоит лишний раз напоминать, что большинство команд должно выполняться от имени администратора.
1 этап. Проверка работы сервиса.
Проверяем имеется ли в системе служба Windows Management Instrumentation (Winmgmt) и включена ли она. Вызываем Службы (в Windows 10 проще всего через Пуск/Средства администрирования/Службы, но я предпочитаю в любой версии Windows, кроме самых старых, напечатать в командной строке services.msc), ищем Инструментарий управления Windows/Windows Management Instrumentation, проверяем, запущена ли она:

Если она не запущена, пытаемся запустить, выставим режим запуска в «Автоматически». Если запущена, пытаемся перезапустить (Остановить/запустить). После этого проверяем работоспособность WMI. Проще всего сделать это, выполнив любой WMI-запрос в powershell (напоминаю, что powershell в Windows 10 запускается через Пуск/Windows PowerShell/Windows Power Shell, но проще, на мой взгляд, запустить командную строку с админовскими правами, а в ней уже набрать powershell), например, такой: (вы можете выполнить другой, свой любимый :))
Get-WmiObject -List -ComputerName localhost

Если у вас вылетела портянка объектов, всё в порядке. Если же полезли ошибки, значит, работоспособность не восстановлена, переходим ко второму этапу.
Между делом скажу пару слов об официальной утилите  Microsoft WMI Diagnosis. Все почему-то наперебой её рекомендуют, как хороший помощник при восстановлении. Увы, я убил достаточно много времени на анализ результатов действия этой утилиты: скрипт создал кучу лог-файлов, через которые продраться можно, если вы никуда не торопитесь, у вас есть куча времени и полкило пуэра/кофе-машина. В причинах сбоев я разобрался быстрее без неё. Вероятность того, что она может помочь непосредственно в скором восстановлении работы WMI – очень мала.
2 этап. Недеструктивное восстановление
Стоит попытаться вначале выполнить перерегистрацию библиотек и рекомпиляцию файлов расширения свойств объектов (Managed Object Format, MOF) и языковую составляющую этих файлов (MFL). Практически гарантированно сработает, если попытка WMI-запроса у вас вызывала ошибку вида "Ошибка в файле WMI.MOF" или любом другом MOF-файле. Для этого выполним следующие операции:

*

*Остановим службу WMI, обязательно запретив её автостарт

*Перерегистрируем все библиотеки в папке Windows\system32\wbem

*Перерегистрируем службы WMI и WMI Provider Host

*Запускаем службу WMI и разрешаем её автостарт

*Рекомпилируем MOF и MFL файлы

Можно собрать всё это в один BAT-файл и запустить:
# пункт 1
sc config winmgmt start= disabled
net stop winmgmt
# пункт 2
cd %windir%\system32\wbem
for /f %%s in ('dir /b *.dll') do regsvr32 /s %%s
#пункт 3
wmiprvse /regserver
winmgmt /regserver
#пункт 4
sc config winmgmt start= auto
net start winmgmt
#пункт 5
for /f %%s in ('dir /b *.mof') do mofcomp %%s
for /f %%s in ('dir /b *.mfl') do mofcomp %%s

Отмечу, что таким образом я восстановил работу WMI на первой машине. Со второй, увы не получилось. Если у вас не получается, пора переходить к 3му этапу
3 этап. Деструктивное восстановление
Фактически, на 3м этапе мы пересоздаем хранилище WMI, как таковое, которое находится в папке  Windows\System32\Wbem\Repository и является базой данных, в которой хранятся данные и определения стандартных WMI-классов и статическая информация дополнительных WMI-классов, если они создавались на вашей машине.
Перед операциями проверьте состояние жёсткого диска и файловой системы!!!
Проверяем целостность (На Windows XP и ниже не работает):
winmgmt /verifyrepository

В случае ответа отличного от "База данных WMI согласована", можно выполнить "мягкое восстановление" командой:
winmgmt /salvagerepository

с последующим перезапуском службы:
net stop Winmgmt
net start Winmgmt

Если мягкое восстановление не помогло, пробуем вернуть хранилище в начальное состояние (последствия: все дополнительные классы WMI, когда-либо зарегистрированные в вашей системе, скорее всего, придётся регистрировать заново):
winmgmt /resetrepository

с последующим рестартом системы. Отмечу, что вторая машина заработала после этого этапа. Последствия были не сильно удручающими, но серьёзными: пришлось переинсталлировать Visual Studio и Delphi Starter, MS Office отказался работать и его пришлось деинсталлировать вручную, удаляя папки, файлы и записи из реестра, с последующей повторной установкой. Также слетели все наши собственные классы WMI.
Но, если и это не помогло, придётся удалять и создавать хранилище заново. Это можно сделать следующим BAT-файлом:
# Остановим службу WMI, обязательно запретив её автостарт
sc config winmgmt start= disabled
net stop winmgmt
# проводим реинициализацию WMI
cd %windir%\system32\wbem
winmgmt /kill
winmgmt /unregserver
winmgmt /regserver
winmgmt /resyncperf
# создаем на всякий случай резервную копию нашего хранилища в папку WMI_VicoNT_Backup
# у вас, разумеется, может быть другое имя папки
if exist WMI_VicoNT_Backup rd WMI_VicoNT_Backup /s /q
rename Repository Repos_bakup
# воссоздаем хранилище
regsvr32 /s %systemroot%\system32\scecli.dll
regsvr32 /s %systemroot%\system32\userenv.dll
for /f %%s in ('dir /b *.dll') do regsvr32 /s %%s
for /f %%s in ('dir /b *.mof') do mofcomp %%s
for /f %%s in ('dir /b *.mfl') do mofcomp %%s
# запускаем службу WMI, заново регистрируем WMI Provider Host
sc config winmgmt start= auto
net start winmgmt
wmiprvse /regserver

Перегружаем компьютер. Если и после этих действий WMI не заработала, путь один – переустановка системы.


text:
Q: Why does my content get cut off without the option to scroll? I'm writing a small website to learn HTML and CSS and I'm having trouble getting my content to scroll in any direction.
When the browser window is resized to the point where any of the content cannot fit, instead of allowing a scroll, it just disappears. The Login button's div is supposed to appear 950px from the left. Meaning that if the browser window is smaller then that, it will allow you to scroll over, right?
And the News box will display any content written until it reaches the bottom of the browser window. Then it won't scroll or display.
Any suggestions?
The HTML is here is here and the CSS is here.

A: Your CSS has many position:fixed attributes in it. When an object's position is set to fixed, it will stay stationary, even if you are scrolling. Therefore, there was nothing that can move, so you couldn't scroll. Try changing your CSS to the following:
body {
background-color: #222222;
overflow: auto;
color: #ffffff;
font-family: verdana, sans-serif;
}
a { color: #ffffff; }
a:visited { color: #ffffff; }

#page_header {
margin-top: 55px;
margin-left: 100px;
font-size: 50px;
}

#user_info {
/*right: 50px;*/
left: 950px;
top: 60px;
position:absolute;
}
#user_info a {
padding: 15px;
text-decoration: none;
font-size: 35px;
}
#user_info a:hover {
background-color: #606060;
}

#boxes {
margin-top: 100px;
margin-left: 100px;
}

#left_content_box {
padding: 20px;
background-color: #00cdcd;
width: 600px;
float: left;
}
#left_content_box header {
top: 15px;
left: 50px;
font-size: 25px;
}
#left_content_box section {
padding: 10px;
}
#left_content_box section header {
padding-top: 25px;
position: relative;
font-size: 20px;
left: 0px;
}
#left_content_box section p {
position: relative;
top: 20px;
left: 10px;
font-size: 15px;
overflow: auto;
}

This will keep everything in the same position as it was, except the page can now scroll when the browser is resized to a point that it cannot display all its contents.


text:
Q: Detect language and translate string to English in Python I would like to detect the language of strings within a pandas series and translate the strings from their detected languages to English.
df['Comments'][:7]
0                                                        @bertelsen1986
1                               20 or 30 mm rise on the Renthal Fatbar?
2                                            Luckily I have one to
3                                   @hatsofftojj isn't this a dope bike
4                      My bike came with a old GX eagle I have big scam
5                                                                   NaN
6   Also ist ein Spulenschock jetzt ein Daumen hoch auf einem Spektral?
Name: Comments, dtype: object

Below is the code that is supposed to detect the language of the strings.
For only 22,000 rows, the code has run for almost an entire day (still running).
from langdetect import detect
lang = []
for row in df.Comments:
    lang = detect(r)
    df['Comments'] = str(df['Comments'])
    df['Language'] = df['Comments'].apply(detect)


text:
Q: Cannot Add Table (with primary key) to EF Designer I'm unable to drag a new table onto my entity framework designer. When I drag the table over the designer, the icon of a circle with a line through it shows up and I can't drop the table onto the designer.
From my research, it seems the biggest issue is the table missing a primary key. Well, my table has a primary key.
Another site suggested: "Please remember that your tables should be related to each other instead of isolating themselves from each other." I'm not sure how that makes sense. Some tables just aren't related to others.
Any ideas on what I'm missing?

A: I think I may have found it. This link states that if the Visual Database Tools DLL gets updated, that could cause the problem. I did indeed just recently install SQL Server Data Tools.
However, instead of trying that fix, I found a decent work-around: I simply right-clicked on the designer and chose Update Model from Database... That worked.
Hope this helps someone else that's having this issue...


text:
Q: Как вместо ползунка в QSlider сделать картинку? Нужно сделать вместо ползунка картинку, которую можно будет двигать. Получается вот так:
Код:

 volume_slider->setStyleSheet(
                "QSlider::handle:horizontal {"
                "background : url(:/images/icon.png); width 30px;         height 30px"
                "}"    );

Нужно чтобы картинка была по центру и полностью была видна (размер картинки: 48x48). Можете подсказать, как это сделать?


text:
Q: How can I update my number in while loop? (Number guessing game) I am going to write a guessing game with the computer.
I choose one number in my head and the Computer is going to find it out, and it can guess between a range.
The problem is I don't know how can I update this range during the program run.
import random
x = 1
y = 99
guess= random.randint(x,y)
print(guess)
play='true'
while play=='true':
    a=x
    b=y
    results = input()
    if results == 'd':
        play='false'
    else:
        if results == 'b':
            a=guess
            print('My number is bigger!')
            newguess= random.randint(a,b)
            print (newguess)
        elif results == 'k':
            b=guess
            print('My number is smaller!')
            newguess= random.randint(a,b)
            print (newguess)
print ('Wooow , computer you did it! ')

A: Sorry about all the explanations in the code but this is a version of the game that I did a while ago. What I did was I wanted to shrink the guessing range each time the user said high or low. e.g. if the computer chooses 50, and the user says 'High' then the program will not chose a number greater than 50, the same applies for 'Low". Enjoy
import random
count = 0 #Number of attemps. how many times while loop runs.
guess = random.randint(1,100)#The guess generator

(l,u) = (0,100)
lower_guess = l
upper_guess = u
n = 0

print('Chose a number between ', l,  ' and ', u , '.' )

#The game. These are outside the function so that they don't print in every loop because they are unwanted for some Y inputs.
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')#User states

#The function

while n != 'guess':

    count +=1 #adds 1 to count each time loop runs

    if Y == 'L':
        lower_guess = guess+1
        guess = random.randint(lower_guess , upper_guess)#Redifining guess to eliminate irrelevant guesses from the range
        print('Is it ' + str(guess))
        Y = input('Low = L, High = H and Yes = Y:')

    elif Y == 'H':
        upper_guess = guess - 1
        guess = random.randint(lower_guess, upper_guess)#Redifining guess to eliminate irrelevant guesses from the range
        print('Is it ' + str(guess))
        Y = input('Low = L, High = H and Yes = Y:')

    elif Y == 'Y':
        print('I guessed it in ' + str(count) + ' attempts')
        break

    else:
        count = 0
        lower_guess = l
        upper_guess = u
        guess = random.randint(1,100)
        print('That input was invalid. The game has restarted.')
        print('You can chose a new number or keep your old one.')
        print('Is it ' + str(guess))
        Y = input('Low = L, High = H and Yes = Y:')


text:
Q: Evenly spaced button in Layout I'm trying to make 4 buttons, evenly spaced in a portrait view on Android.
The space should scale up and down depending on the screen size, with an even amount of space between each button and the borders.
I tried using linear layout, weight and layout gravity but it seems that I cannot center the button vertically.
Is this a bug of Android layout? More probably is just me.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1"
android:layout_gravity="center"
>
<Button
android:id="@+id/btn_f"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="btn_f"
>
</Button>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_weight="1"
android:layout_gravity="center"
>
<Button
android:id="@+id/btn_b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="btn_b"
>
</Button>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1"
android:layout_gravity="center"
>
<Button
android:id="@+id/btn_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="btn_a"
>
</Button>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1"
android:layout_gravity="center"
>
<Button
android:id="@+id/settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Settings"
>
</Button>
</LinearLayout>
</LinearLayout>

A: Try this:
 <LinearLayout
  android:layout_width="wrap_content"
  android:layout_height="0dp"
  android:orientation="horizontal"
  android:weightSum="1"
  android:gravity="center">
     <Button
        android:id="@+id/btn_f"
        android:layout_width="0dp"
        android:layout_weight="0.5"
        android:layout_height="wrap_content"
        android:text="btn_f" />
 </LinearLayout>

This will set the button to occupy only half of the screens length.

A: Try something like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:orientation="vertical"
        android:layout_weight="1"
        android:gravity="center"
        >
        <Button
            android:id="@+id/btn_f"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="btn_f"
            />
    </LinearLayout>
    <!-- etc -->
</LinearLayout>

The changes from your original layout are that each inner LinearLayout has a height of zero and a gravity (not layout_gravity) of center. This should cause all the inner linear layouts to have the same height, evenly splitting the parent height, without stretching the buttons themselves.

A: You seem to be wrapping all buttons in another LinearLayout instead of just keeping them in the parent LinearLayout.
Remove all those immediate LinearLayout so that android:layout_weight takes effect.

To achieve stretching and spacing

*

*use android:layout_width="fill_parent" in the buttons themselves

*specify margin for spacing


text:
Q: Using laser scattering beams instead detectors in Double Slit Experiment? In the Double Slit Experiment for electrons could be possible the use of an appropriate laser pointer at one slit aiming up so when an electron passes through that distinct slit it get scattered up so its picture on the screen will show up in the upper part. The question that arises: will the electron path probability collapse?

A: If by any means you determine a slit the electron goes through, then the interference pattern will go away. So in this case there will be no interference pattern, as you will be able to associate a slit with each detection event.
Speaking a little more abstractly / loosely, by detecting the slit the particle goes through, the wave function is now being described as having a single source from that slit as opposed to two sources (one for each slit). As such, you will lose any double-slit interference pattern.


text:
Q: Tailing last frame of a growing video file On windows, I have a dynamically created uncompressed avi video file which grows overtime. The application which generates the video file can only write to a physical file. I can start/stop generation of video file and delete the old video file easily.
I would like to analyze the changing last frame of the growing video file to make some decision depending on the content of the current/latest image in real time. If I can achieve more than 10fps it should be enough.
I would like to get uncompressed images whenever a new frame available in the video file.
As a file format I think png could be the best options in that case but I am open to alternatives.
I wonder if such a thing is possible with ffmpeg or with a similar tool.
I prefer to analyze the image and make decisions by using a perl+Imager module.
Tha analyisis requirements are not complicated. Basically I just need to find existence of a few small images in certain locations inside the last frame.
I would also appreciate if you can suggest an efficient way to get this information in to my application from ffmpeg.
For example piping directly to my code or reading from saved png files.
I know perl already has an ffmpeg interface module but as far as I understand that module can't provide the functionality I need.

A: First off, I hope you realize the data rate of uncompressed video! E.g., at 720x480 (plain 'ol NTSC, not HD) with 16-bit color at 10fps, you're generating 6.6 megabytes per second. You fill a 1TB hard drive in less than two days. Handling that data rate in perl should be interesting.
Getting new frames from the file should be fairly simple, since its uncompressed video.

*

*Assume you're starting from the front of the AVI (you start capture along with processing, for example).

*Read the AVI header, making sure it is as expected (e.g., proper format).

*Note the current subsecond system timestamp (e.g., from Time::HiRes).

*You know the length of a single frame. Attempt to sysread it. Continue trying until either you get the full frame (updating your requested length each time, of course), or you get an EOF (sysread returns 0).

*If you got an EOF before full frame: sleep a small amount of time (say, 10ms, Time::HiRes will let you sleep for less than 1 second) and then try to read the rest of the frame again. sysread doesn't need an EOF indication reset; it'll try again each time you call it. Keep doing the delay/sysread cycle until you have a full frame.

*You now have a full frame. Since its uncompressed video, it really won't need much if any decoding before passing it to your computer vision code. (You may have to swap bytes around, or maybe convert from 16 to 32 bit, but nothing worse than that).

*Since you're reading 10fps video, sleep for the remainder of the 1/10 second before the next frame.

*Go back to (3).

You may find that if you use a library to implement your computer vision, it has functions to help with this—e.g., it may be able to read frames from an AVI file. OpenCV, for example, can.


text:
Q: Are large cardinals about more than just consistency? The other day, I was reading the preface of Kanamori's The Higher Infinite and noticed that he says large cardinals provide a useful 'measuring stick' for consistency. That raised the question of whether large cardinals are motivated simply by searching for their consistency strengths or if there are other motivations. If large cardinals have appeal outside of consistency strength, like mathematical beauty or interesting properties, are there any examples that someone with a moderate knowledge of set theory could understand?
Related question on MSE

A: Asaf Karagila already wrote an excellent answer at math.SE, but here is a simple point that may be helpful.  In any area of math, the natural course of research leads one to ask questions, pose conjectures (and prove them if possible), and impose extra structure on the objects of study if that seems to be necessary for them to have desirable properties.  Set theory is not any different in this regard, except that in set theory, we can often detect that some of our "conjectures" are hopeless, in the sense that Gödel's incompleteness theorems tell us that we cannot possibly prove them in the conventional mathematical sense.  So you can think of large cardinal axioms as "natural conjectures," except that we don't call them conjectures because we know we can't prove them.  Alternatively, you can think of increasingly strong large cardinal axioms as imposing increasing amounts of structure on $V$, giving it extra desirable properties.
One can still ask, if we're just looking for "natural conjectures," why do large cardinal axioms stand out?  Why aren't there lots of other, equally prominent axioms?  Well, as a matter of fact, there are other axioms that set theorists study, but large cardinals stand out because they somewhat miraculously seem to line up nicely in a single hierarchy.  This fact is not at all obvious a priori (for example, it is not at all obvious from the definition of a measurable cardinal that it must be inaccessible).  To some people, it suggests that the large cardinal axioms are "true," but even if you don't believe in truth in this sense, the large cardinal axioms bring a lot of order to what might otherwise be a chaotic universe.  Instead of a huge mess of "natural conjectures," we find that many other questions can be more-or-less answered by showing that they lie sandwiched in between two well-known large cardinal axioms.


text:
Q: Update from join only if it does not have a row with date higher than now I've got two tables one is Members and the other is Subscriptions
In the Members table I have the following
| Members |
-------------------------------
| Person_id | Name | Category |
-------------------------------
|     1     | Bob  |     2    |
|     2     | Anne |     2    |
-------------------------------

In the Subscriptions table I have the following
| Subscriptions |
---------------------------------------------------------
| Subscription_id | Person_id | Start_date |  End_date  |
---------------------------------------------------------
|       1         |     1     | 01-01-2017 | 01-02-2017 |
|       1         |     1     | 01-02-2017 | 01-03-2017 |
|       1         |     1     | 01-03-2017 | 01-04-2017 |
|       2         |     1     | 01-02-2017 | 01-02-2018 |
|       1         |     2     | 01-11-2016 | 01-12-2016 |
|       1         |     2     | 01-12-2016 | 01-01-2017 |
|       2         |     2     | 01-12-2015 | 01-12-2016 |
---------------------------------------------------------

I would like to set the Category in the Members table to 0 for Members who do not have a subscription in the Subscriptions table with a End_date higher than current date.
I managed to make a Select query for this but I couldn't change it into an update query
Here is the query
SELECT a.* FROM (
    SELECT m.Person_id, m.Category, MAX(s.End_date) as 'End_date_max'
    FROM
        Subscriptions s
    JOIN
        Members m
        ON m.Person_id = s.Person_id
        AND m.Category > 0
        AND m.Category IS NOT NULL
        AND m.Category <> 1
    GROUP BY m.Person_id
) a
WHERE End_date_max < curdate()

So in our case above I would want the member Anne's category changed to 0 because it doesn't have any subscription higher than today

A: Try the below query [I know I'm not using a Group by, but it should work]
UPDATE Members m
SET Category = 0
  WHERE m.Person_id NOT IN (SELECT s.Person_id FROM Subscriptions s
    WHERE s.End_date > curdate())
  AND m.Category > 0
  AND m.Category IS NOT NULL
  AND m.Category <> 1


text:
Q: C++ while loop, testing multiple arrays' subscripts How do you test multiple arrays in a while loop to see if their subscript values do not equal a certain value?
I also need to separate the arrays to end the loop when all of the subscripts in either array equal 0. This is what I thought would work, but it doesn't.
while(
      (pl_health[0] !=0 && pl_health[1] !=0 && pl_health[2] !=0 &&
       pl_health[3] !=0 && pl_health[4] !=0 && pl_health[5] !=0) ||
      (enemy[0].health !=0 && enemy[1].health !=0 && enemy[2].health !=0 &&
       enemy[3].health !=0 && enemy[4].health !=0 && enemy[5].health !=0)
     )

As you can see I tried to separate the 2 arrays using paranthesese and the or operator. The program runs free of errors, but the loop does not even iterate once. Even when some of the subscripts are not equal to 0.

A: The problem is you should switch the conditions, most likely (depending on what you are trying to do). One of the commenters pointed out that your logic is "proceed only while every player has health or every enemy has health." I am leaving the other part of my answer intact, as it is still relevant. Here is the while loop that I think expresses the condition you want, though.
while(
      (pl_health[0] !=0 || pl_health[1] !=0 || pl_health[2] !=0 ||
       pl_health[3] !=0 || pl_health[4] !=0 || pl_health[5] !=0) &&
      (enemy[0].health !=0 || enemy[1].health !=0 || enemy[2].health !=0 ||
       enemy[3].health !=0 || enemy[4].health !=0 || enemy[5].health !=0)
     )

A while loop with so many checks in the condition isn't the way to go here. A better approach might be something like:
bool playerAlive = true, enemyAlive = true;

while (playerAlive && enemyAlive) {
    // game logic etc

    playerAlive = false;
    enemyAlive = false;

    for (int i=0; i<6; i++) {
        if (pl_health[i] != 0) {
            playerAlive = true;
        }

        if (enemy[i].health != 0) {
            enemyAlive = true;
        }
    }
}

Mind you, the array approach to storing health is probably only suitable for a simple/small game at best. And of course you would probably want to remove the magic "6" from the for loop and have it be a constant.


text:
Q: ORA-00905: missing keyword Hibernate Query Oracle I have n columns in a table. I want to have selection criteria as if a value in column2 is null then select row based on column 1 and if column2 is not null then select based on the value of column 2. I have a long query which is working fine before introducing CASE WHEN THEN but I get ORA-00905 when I added case in my query. Sample query is as:
select * from table where table.testcolumn='some value' and ( case when table.column2 is NULL then  table.column1 = 'value' else table.column2 = 'value' end )

Exceptions:
Caused by: java.sql.SQLSyntaxErrorException: ORA-00905: missing keyword

    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:91)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1035)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:791)
    at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:866)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1187)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3386)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3430)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1491)
    at weblogic.jdbc.wrapper.PreparedStatement.executeQuery(PreparedStatement.java:128)
    at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:186)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:1787)
    at org.hibernate.loader.Loader.doQuery(Loader.java:674)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
    at org.hibernate.loader.Loader.doList(Loader.java:2213)

A: I think you can use an alternative statement without the usage of case when..:
select * from table
where table.testcolumn='some value'
and (
      (table.column2 is NULL and table.column1 = 'value')
      or (table.column2 = 'value')
    )


text:
Q: Method not applicable error using Jsoup in custom Java code I'm having issues using Jsoup in a tJavaRow component in Talend.
Here is my Job:

Through tLibraryLoad I load the .jar files for Jsoup and the java.io.File library and then import them into the tJavaRow_2 component:
import java.io.File;
import java.io.File;
import org.jsoup.Jsoup;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import org.jsoup.select.Elements;

And then try to run the following code in the main part of the tJavaRow_2:
Document document = Jsoup.parse(new File("C:/Talend/workspace/WEBCRAWLER/output/keywords_" + context.keywordname +".txt", "utf-8");
Document document = Jsoup.parse(new File("C:/Talend/workspace/WEBCRAWLER/output/keywords_" + context.keywordname +".txt", "utf-8");
        Elements el = document.select(".gutter10");
        Elements el = document.select(".gutter10");
        String result = el.text();
        String result = el.text();

        if(result.length() > 20)
        if(result.length() > 20)
            {context.lastpage = true;};

Seems logical to me so far.
But I get this error:

Can you help me resolve this problem? I don't understand what to do from this point on.
APPENDIX: Java Code that works in Eclipse:
import java.io.File;
import java.io.File;
//import java.util.regex.*;
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class regextest  {

    public static boolean regExChecker() throws IOException
    {
        boolean x = false;
        Document document = Jsoup.parse(new File("C:/Talend/workspace/WEBCRAWLER/output/absolventa_testquery.txt"), "utf-8");
        Elements el = document.select(".gutter10");
        String result = el.text();

        if(result.length() > 20)
            {x = true;};

        //System.out.println(x);
        return x;
    }

    public static void main(String[] args) throws IOException{
        System.out.println(regExChecker());
    }
}

A: You're missing a closing bracket in your code block. Your first line should be:
Document document = Jsoup.parse(new File("C:/Talend/workspace/WEBCRAWLER/output/keywords_" + context.keywordname +".txt"), "utf-8");

As it is, you're building a file from the path "C:/Talend/workspace/WEBCRAWLER/output/keywords_" + context.keywordname +".txt"), "utf-8" and then just pass that file object (it won't be a proper file object but for some reason the compiler hasn't spotted this) to the parse method of Jsoup.
Looking at Jsoup's documentation the only method call to parse that is a single value is when you pass a HTML document in a string to it. So it is expecting a string and instead gets a (broken) file.
The second error is the one that really points this out by saying you're missing a closing bracket for the VariableInitializer.


text:
Q: How to serialize data in example-in-example format for tensorflow-ranking? I'm building a ranking model with tensorflow-ranking. I'm trying to serialize a data set in the TFRecord format and read it back at training time.
The tutorial doesn't show how to do this. There is some documentation here on an example-in-example data format but it's hard for me to understand: I'm not sure what the serialized_context or serialized_examples fields are or how they fit into examples and I'm not sure what the Serialize() function in the code block is.
Concretely, how can I write and read data in example-in-example format?

A: The context is a map from feature name to tf.train.Feature. The examples list is a list of maps from feature name to tf.train.Feature. Once you have these, the following code will create an "example-in-example":
context = {...}
examples = [{...}, {...}, ...]
serialized_context = tf.train.Example(features=tf.train.Features(feature=context)).SerializeToString()
serialized_examples = tf.train.BytesList()
for example in examples:
    tf_example = tf.train.Example(features=tf.train.Features(feature=example))
    serialized_examples.value.append(tf_example.SerializeToString())
example_in_example = tf.train.Example(features=tf.train.Features(feature={
    'serialized_context': tf.train.Feature(bytes_list=tf.train.BytesList(value=[serialized_context])),
    'serialized_examples': tf.train.Feature(bytes_list=serialized_examples)
}))

To read the examples back, you may call
tfr.data.parse_from_example_in_example(example_pb,
    context_feature_spec = context_feature_spec,
    example_feature_spec = example_feature_spec)

where context_feature_spec and example_feature_spec are maps from feature name to tf.io.FixedLenFeature or tf.io.VarLenFeature.

A: First of all, I recommend reading this article to ensure that you know how to create a tf.Example as well as tf.SequenceExample (which by the way, is the other data format supported by TF-Ranking):
Tensorflow Records? What they are and how to use them
In the second part of this article, you will see that a tf.SequenceExample has two components: 1) Context and 2)Sequence (or examples). This is the same idea that Example-in-Example is trying to implement. Basically, context is the set of features that are independent of the items that you want to rank (a search query in the case of search, or user features in the case of a recommendation system) and the sequence part is a list of items (aka examples). This could be a list of documents (in search) or movies (in recommendation).
Once you are comfortable with tf.Example, Example-in-Example will be easier to understand. Take a look at this piece of code for how to create an EIE instance:
https://www.gitmemory.com/issue/tensorflow/ranking/95/518480361
1) bundle context features together in a tf.Example object and serialize it
2) bundle sequence(example) features (each of which could contain a list of values) in another tf.Example object and serialize this one too.
3) wrap these inside a parent tf.Example
4) (if you're writing to tfrecords) serialize the parent tf.Example object and write to your tfrecord file.


text:
Q: Get Element By id or Name in Curl My target site contains code like this
<form>
<input type="text" name="suggest" value="www.google.com">
<input type="submit" value="submit">
</form>

I Get this page with Curl Php
<?php
$url="http://mysite.com";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
$result = curl_exec ($ch);
echo $result;
curl_close($ch);
?>

How can I get an element value using id or name? For example "www.google.com" in input name="suggest". Thanks for helping me.
I cant use this code for remote like this :
<?php
require 'Path/QueryPath.php';
qp('http://hipfile.com/bbgfom5ej9tm/zakhme_shaneie_haava_dvdrip.wmv.html/')-

find('[password="login"]')->writeHTML();
      ?>

and return this error

Fatal error: Uncaught exception 'QueryPathParseException' with message 'DOMDocument::load() [domdocument.load]: AttValue: " or ' expected in http://hipfile.com/bbgfom5ej9tm/zakhme_shaneie_haava_dvdrip.wmv.html/, line: 18 (C:\xampplite\htdocs\test1\Path\QueryPath.php: 2106)' in C:\xampplite\htdocs\test1\Path\QueryPath.php:2346 Stack trace: #0 [internal function]: QueryPathParseException::initializeFromError(2, 'DOMDocument::lo...', 'C:\xampplite\ht...', 2106, Array) #1 C:\xampplite\htdocs\test1\Path\QueryPath.php(2106): DOMDocument->load('http://hipfile....', 0) #2 C:\xampplite\htdocs\test1\Path\QueryPath.php(179): QueryPath->parseXMLFile('http://hipfile....', NULL, NULL) #3 C:\xampplite\htdocs\test1\Path\QueryPath.php(23): QueryPath->__construct('http://hipfile....', NULL, Array) #4 C:\xampplite\htdocs\test1\index.php(3): qp('http://hipfile....') #5 {main} thrown in C:\xampplite\htdocs\test1\Path\QueryPath.php on line 2346

Can help me? I used two DOM And simplehtmldom but not working for me . it works for local page only.

A: You'll have to use a DOM parser. Lately I've been using Query Path: http://querypath.org/
qp($result)->find('[name="name"]');

A: Try this
<?php

$url="http://mysite.com";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
$result = curl_exec ($ch);
echo $result;
curl_close($ch);

// include simple_html_dom class here
// which can be downloaded from http://simplehtmldom.sourceforge.net/

$oDom = new simple_html_dom();
$oDom->load($result);
$textFieldValue = $oDom->find('[name="suggest"]',0)->value;
echo $textFieldValue; // will return www.google.com

?>


text:
Q: Why do I get two different Project Context for my Spring mvc web application? Following is my pom.xml
<project xmlns="Page on apache.org" xmlns:xsi="Page on w3.org"
xsi:schemaLocation="Welcome to Apache Maven/POM/4.0.0 Page on apache.org">
<modelVersion>4.0.0</modelVersion>
<groupId>com.MyStartUp.www</groupId>
<artifactId>MyStartUp</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>MyStartUp Maven Webapp</name>
<url>Welcome to Apache Maven</url>
<properties>
<spring.version>4.0.2.RELEASE</spring.version>

</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.6.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-api</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-core</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-servlet</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<build>
<finalName>MyStartUp</finalName>

<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

I use tomcat server v7.0 to deploy and I use maven to build.
Whenever I make a change I go to maven terminal and use "mvn clean install" and go to localhost:8080/manager and deploy the war by browsing the application in my desktop. After this I see "MyStartUp" in tomcat manager window in browser.
My project name in eclipse looks as "mystartup".
When I add the project in Eclipse IDE using "Add or remove" after right click the server, I see "mystartup" and I add it. Then if I refresh localhost:8080/manager/
I see two different project deployed.
1) MyStartUp  (Url : localhost:8080/MyStartUp --> Works)
2) mystartup  (Url : localhost:8080/mystartup --> Doesn't Work)
When I click the second one, I am not able to access the application. But if I use the first one, it works
Because of this, each time, I do "mvn clean install" in IDE and I manually undeploy "MyStartUp" and deploy new install of "MyStartUp". This takes away my time. I want to add my project to Server in IDE and restart it when I make a change and run the application. How to fix this issue?
PS:
Here is my web.xml
<web-app version="2.2" id="WebApp_ID">

    <!-- <display-name>Archetype Created Web Application</display-name> -->

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/mvc/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>/WEB-INF/jsp/template.jsp</welcome-file>
    </welcome-file-list>
</web-app>

This is how my git clone looks
git clone https://MyStartUp@bitbucket.org/MyStartUp/mystartup.git