text:
Q: Clang error: Cannot compile builtin function I'm compiling a code which has GCC library extra separately added. While  compiling it with clang error
cannot compile

is showing
I've tried added flags. -std=89gnu does not work with a clang. After some inspection found the same function in compiler file.
BUILTIN(__builtin_init_dwarf_reg_size_table, "vv*", "n")

Error:
gcc/unwind-dw2.c:1336:3: error: cannot compile this __builtin_init_dwarf_reg_size_table

A: That's a really weird error message, can you put the full one here? Also, I'm surprised that you want to compile libgcc with clang, I don't think anyone has really tried before. Some better repro instructions would help though as this seems to work:
echristo@jhereg ~/tmp> cat foo.c
char x[16]; void a() { __builtin_init_dwarf_reg_size_table(x); }

echristo@jhereg ~/tmp> clang -S -o - foo.c --target=x86_64-linux-gnu
    .text
    .file   "foo.c"
    .globl  a                       # -- Begin function a
    .p2align    4, 0x90
    .type   a,@function
a:                                      # @a
    .cfi_startproc
# %bb.0:
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register %rbp
    movb    $8, x
    movb    $8, x+1
    movb    $8, x+2
    movb    $8, x+3
    movb    $8, x+4
    movb    $8, x+5
    movb    $8, x+6
    movb    $8, x+7
    movb    $8, x+8
    movb    $8, x+9
    movb    $8, x+10
    movb    $8, x+11
    movb    $8, x+12
    movb    $8, x+13
    movb    $8, x+14
    movb    $8, x+15
    movb    $8, x+16
    popq    %rbp
    .cfi_def_cfa %rsp, 8
    retq
.Lfunc_end0:
    .size   a, .Lfunc_end0-a
    .cfi_endproc
                                        # -- End function
    .type   x,@object               # @x
    .comm   x,16,16

    .ident  "clang version 9.0.0 (https://github.com/llvm/llvm-project.git b669fea42f5c2a5b203c3f0da2a6b04b90bfd5a7)"
    .section    ".note.GNU-stack","",@progbits
    .addrsig
    .addrsig_sym x


text:
Q: Joint query in Linq to SQL to select all records even there are some null in the columns of foreign keys
I'd like to take all suggestion either in C# or VB.NET.

I have a DB diagram like the image below. I also include the database script here @ http://pastebin.com/pDC25Gkm

In the Students table, CountryId and RoomId column are allowed null. Because some records do not have info about room and country yet.
Also, some students do not have essays.
I'm doing a joint query with all tables. I want to select all students to
project the result like this:
Wanted query result.

Here's my current query that gives the result like the image below:
    Dim db As New DBDataContext

    Dim query = From st In db.Students _
                Join c In db.Countries On c.Id Equals st.Id _
                Join r In db.Rooms On r.Id Equals st.RoomId _
                Join b In db.Buildings On b.Id Equals r.BuildingId _
                Join es In db.Essays On es.StudentId Equals st.Id _
                Select st, c, r, b, es

    'put query result into datatable
    Dim dt = New DataTable("Result")
    dt.Columns.Add("Id", GetType(Integer))
    dt.Columns.Add("Name", GetType(String))
    dt.Columns.Add("Room", GetType(String))
    dt.Columns.Add("Building", GetType(String))
    dt.Columns.Add("Country", GetType(String))
    dt.Columns.Add("Essay", GetType(String))

    For Each q In query

        dt.Rows.Add(New Object() {q.st.Id, q.st.FullName, q.r.RoomNumber, q.b.BuildingName, q.c.CountryName, q.es.Eassay})

    Next

    'bind to list view
    lvStudent.DataSource = dt
    lvStudent.DataBind()

current query result

I got only one result back because I have (2) William NoMan record in every table. But I don't get anything about others, like (3) Sync Master who has everything but RoomId.
What do I need to modify the query above so it will give me all students like in the wanted query image above? Thank you.

A: I used the following query:
    Dim query = From st In db.Students _
             From c In db.Countries.Where(Function(c) c.Id = st.CountryId).DefaultIfEmpty _
             From r In db.Rooms.Where(Function(r) r.Id = st.RoomId).DefaultIfEmpty _
             From b In db.Buildings.Where(Function(b) b.Id = r.BuildingId).DefaultIfEmpty _
             From es In db.Essays.Where(Function(es) es.StudentId = st.Id).DefaultIfEmpty _
             Select st.Id, st.FullName, c.CountryName, r.RoomNumber, b.BuildingName, es.Eassay

It gives the result I wanted but I'm not sure if it's good query. There must be another way better than this.

A: This is how you can achieve this using sql server query.
select students.id, fullname, isnull(roomid,'') as Room,
isnull((select top 1 buildingid from rooms where rooms.id = roomid), '') as building,
isnull((select top 1 countryname from countries where Countries.id = countryid), '') as Country,
isnull((select top 1 eassay from essays where Essays.studentid = Students.id), '') as essay from students

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP PATH environment SET Properly but in windows 7 not detected I m having a weird problem.I set the php path variable, E:\xampp\php , manually in windows 7. which didnt work , then from command prompt as  SET PATH=%PATH%;E:\xampp\php
which also didnt work, if I want to check php version by php -v it shows that system is finding all the dll files from E:\xampp\php... , somehow that path is NOT replaced anyway by my new path setting.I restarted the pc several times but to NO avail.I m using xampp portable version. is there another way I can get xampp portable to know my php path by hardcoding the varible.


text:
Q: Uninstall old ruby version completely So I have ruby-2.2.1 and ruby-2.2.3 installed on my mac.
I run $ rvm remove rbx-2.2.1 to uninstall Ruby 2.2.1 but when I run $ rvm list , I still get ruby-2.2.1 [ missing bin/ruby ] and ruby-2.2.3 [ x86_64 ].
I tried uninstall commands but nothing works out. Please advise.
Thanks!


text:
Q: Vue3 js v-bind css tailwind conditionally based on status value I have a status property that can change  and I need to change CSS tailwind each time that value changes using v-bind :class on vue3 3 how to achieve so ?

A: You could do something like this
<div :class="{ 'tailwind-class': status }">


text:
Q: cannot use angular js ng-app directive I'm going through the angular tutorial and it asked me to do the following:
<html lang="en" class="no-js" ng-app="appname">

And then in my app.js:
app = angular.module('appname',[]);

I'm loading all of the angular files, including the angular-route.min.js.
Can someone please explain what I am doing incorrectly? The error I am receiving and cannot find a solution to is:
Uncaught Error: [$injector:modulerr]

UPDATE:
Here is my app.js
    var spinner,app;
    $(document).ready(function(){
        spinner = new Spinner();
        bindSearch();
        $(".phonenumber").mask("(999) 999-9999? x99999",{placeholder:" "});
        $(".zipcode").mask("99999?-9999",{placeholder:" "});
        if(useDataTable){
            $("#loadingdiv").after(spinner.spin().el);
            reloadSearchItems();
        }
        app = angular.module('appname',[]);
    });

Here is my html:
<html lang="en" class="no-js" ng-app="appname" ng-strict-di>


text:
Q: Anything wrong with the type declaration? I am reading the book "Programming in Haskell". One exercise asks me to define map f using an higher-order function. I choose to define map (+1) like the following:
unfold p h t x | p x       = []
               | otherwise = h x : unfold p h t (t x)

-- equivalent to `map (+1)`
mapinc = unfold (==[]) ((+1).head) tail

(Taken straight from the exercise question) The function unfold p h t produces the empty list if the predicate p is true of the argument value, and otherwise produces a non-empty list by applying the function h to this value to give the head, and the function t to generate another argument that is recursively processed in the same way to produce the tail of the list.
I have checked my implementation of mapinc and it looks fine:
*Main> mapinc [1,2,3]
[2,3,4]

However, after I add the type declaration:
mapinc :: Num a => [a] -> [a]
mapinc = unfold (==[]) ((+1).head) tail

Then reload the script in WinGHCi, it gives the following error:
• Could not deduce (Eq a) arising from a use of '=='
  from the context: Num a
    bound by the type signature for:
               mapinc :: forall a. Num a => [a] -> [a]
    at D:\7a.hs:4:1-29
  Possible fix:
    add (Eq a) to the context of
      the type signature for:
        mapinc :: forall a. Num a => [a] -> [a]
• In the first argument of 'unfold', namely '(== [])'
  In the expression: unfold (== []) ((+ 1) . head) tail
  In an equation for 'mapinc':
      mapinc = unfold (== []) ((+ 1) . head) tail
  |
5 | mapinc = unfold (==[]) ((+1).head) tail   |                  ^^^^

Any clue why it happens?

A: Your signature is too broad. The predicate you have written is == []. Haskell can only check if two lists are equal, if the elements of the list can be checked as well. In the source code we see something like:
instance Eq a => Eq [a] where
    ...
Yes, here we will never check the equality of two items, since we check with the empty list, but the compiler of course does not know that: it simply sees that in order to check whether two lists are equal, we need to be able to check if elements are equal.
The Num typeclass does not imply that the type is also an Eq type. We can do two things here:

*

*add the Eq type constraint to the signature:
mapinc :: (Eq a, Num a) => [a] -> [a]
mapinc = unfold (==[]) ((+1).head) tail

*more elegant: do not rely on the fact that we need to be able to compare elements, but use null :: [a] -> Bool instead (a function that checks if the list is empty):
mapinc :: Num a => [a] -> [a]
mapinc = unfold null ((+1).head) tail


text:
Q: Does it make sense to work on a c# project, for a windows server, developing it on linux? I'm a PHP/JS developer, now I have a proposition of making a project based on C#, which would then work on a Windows server.
I have no experience with either (C# or Windows server) but I was given some time to learn it, if we agree on the details.
The project is about an API (web service, RESTful).
And now I have two questions - I haven't touched Windows for about 10 years, so:

*

*Am I right that I have to learn C# and the .NET framework? Is the .NET some sort of standard on MS servers?

*Is this reasonable to work on the project using Linux machine as the work environment and then upload it to the Windows test server for testing?
BTW, right now the project is very simple, probably only a few classes. If I'll make it, I can later install Windows on my workspace, but for this very small project, where time allowed for the implementation is about one day (excluding my learning process) I would prefer to avoid it.

A: *

*C# is a programming language, .NET is a framework. There is an old .NET Framework that is windows only and the newer .NET Core (the newest version is called just .NET 5), which is cross-platform.

*You can develop .NET core apps on linux as well. Note that you won't be able to use Visual Studio (IDE), which is only available for Windows and Mac.


text:
Q: Details of the criterion for representability of a functor of S-schemes I've come across a problem that's made me look back over representabiilty of scheme functors and I'm having a lot of trouble piecing together some  categorical details that I used to think I understood. To give ourselves a concrete example with which to work, let $S$ be a noetherian separated scheme and let $\mathcal{E}$ be a quasicoherent sheaf of $\mathcal{O}_{S}$-algebras.
I would like to show that there is a scheme $\bf{Spec}(\mathcal{E}) \rightarrow S$ via a representability criterion.
Let $F: \text{Sch}/S \rightarrow \text{Set}$ be a contravariant functor defined as follows: On objects it sends $(T \stackrel{\mu}{\rightarrow}S)$ to the set $\text{Hom}_{\mathcal{O}_{S}-alg}(\mathcal{E}, \mu_{*} \mathcal{O}_{T})$. To show it is representable it is enough to show that it is a sheaf for the big Zariski site on $S$, and that it is locally representable.
Let's assume we have shown already that it is a Zariski sheaf. I want to clarify exactly what more must be shown.
We begin with a morphism of functors,
$$
\eta: F \longrightarrow \text{Hom}_{S}(-, S).
$$
Now firstly, am I correct that the functor $\text{Hom}_{S}(-, S)$ will an object $(T \stackrel{\mu}{\rightarrow} S)$ and simply return that same object?
Now let $\{ U_{i} \}$ be an affine cover of $S$ with inclusions $\tau_{i}: U_{i} \hookrightarrow S$. We want to show that the pulled back functors,
$\require{AMScd}$
\begin{CD}
F_{i} @>{}>> F\\
@VVV @VVV{\eta}\\
\text{Hom}_{S}(-, U_{i}) @>{\tau_{i}^{*}}>> \text{Hom}_{S}(-, S)
\end{CD}
are representable. But I'm not even sure what this pullback is supposed to be. In terms of functors, a pullback is supposed to define a functor from slice categories
$$
\mathcal{C}/a \longrightarrow \mathcal{C}/b
$$
based on a morphism $b \rightarrow a$. But here my morphism is a morphism of functors $$\text{Hom}_{S}(-, U_{i}) \stackrel{\tau_{i}^{*}}{\rightarrow} \text{Hom}_{S}(-, S).$$

So what category precisely is the pulled back functor $F_{i}$ defined on? I
  would like it to be the category $\text{Sch}/U_{i}$ so I can then
  apply the known construction to the affine case. But I don't see why
  from a purely formal viewpoint the functor should be defined on that
  category rather than just still on $\text{Sch}/S$.


text:
Q: Drop Down menu Validation with Alert If drop down menu is left unanswered provide an alert to the user.
I already have the code for providing the alert for an unanswered drop down menu. However, I am trying to add this code to my existing Javascript.
The code creates a form that gathers information regarding users. The form has 5 steps:

*

*User information (Name, email, phone, age, gender)

*Yes or No question (Drop down menu)

*Yes or No question (Drop down menu)

*Yes or No question (Drop down menu)

*Yes or No question (Drop down menu)

The code also has embedded animation for every time the user presses the next/previous button.
How do I add my drop down menu validation alert, to my existing Javascript (for steps 2-5). Please visit this site for better understanding of what the animation looks like.

var current_fs, next_fs, previous_fs; //fieldsets
var left, opacity, scale; //fieldset properties which we will animate
var animating; //flag to prevent quick multi-click glitches

$(".next").click(function(){

    //text inputs
    if(!document.getElementById('fullname').value){
        alert('Full Name is required');
        return false;
    }

    else if(!document.getElementById('email').value){
        alert('Email is required');
        return false;
    }

    else if(!document.getElementById('phone').value){
        alert('Phone Number is required');
        return false;
    }

    else if(!document.getElementById('age').value){
        alert('Age is required');
        return false;
    }

    //radio buttons
    var genderSet = false;
    var genderBtns = document.getElementsByName('gender');
    //console.log(genderBtns);
    for(var i=0, btn; btn=genderBtns[i];++i){
        if(btn.checked){
            genderSet=true;
            break;
        }
    }
    if(!genderSet){
        alert('Gender is required');
        return false
    }

    if(animating) return false;
    animating = true;

    current_fs = $(this).parent();
    next_fs = $(this).parent().next();

    //activate next step on progressbar using the index of next_fs
    $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

    //show the next fieldset
    next_fs.show();
    //hide the current fieldset with style
    current_fs.animate({opacity: 0}, {
        step: function(now, mx) {
            //as the opacity of current_fs reduces to 0 - stored in "now"
            //1. scale current_fs down to 80%
            scale = 1 - (1 - now) * 0.2;
            //2. bring next_fs from the right(50%)
            left = (now * 50)+"%";
            //3. increase opacity of next_fs to 1 as it moves in
            opacity = 1 - now;
            current_fs.css({'transform': 'scale('+scale+')'});
            next_fs.css({'left': left, 'opacity': opacity});
        },
        duration: 800,
        complete: function(){
            current_fs.hide();
            animating = false;
        },
        //this comes from the custom easing plugin
        easing: 'easeInOutBack'
    });
});

$(".previous").click(function(){
    if(animating) return false;
    animating = true;

    current_fs = $(this).parent();
    previous_fs = $(this).parent().prev();

    //de-activate current step on progressbar
    $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

    //show the previous fieldset
    previous_fs.show();
    //hide the current fieldset with style
    current_fs.animate({opacity: 0}, {
        step: function(now, mx) {
            //as the opacity of current_fs reduces to 0 - stored in "now"
            //1. scale previous_fs from 80% to 100%
            scale = 0.8 + (1 - now) * 0.2;
            //2. take current_fs to the right(50%) - from 0%
            left = ((1-now) * 50)+"%";
            //3. increase opacity of previous_fs to 1 as it moves in
            opacity = 1 - now;
            current_fs.css({'left': left});
            previous_fs.css({'transform': 'scale('+scale+')', 'opacity': opacity});
        },
        duration: 800,
        complete: function(){
            current_fs.hide();
            animating = false;
        },
        //this comes from the custom easing plugin
        easing: 'easeInOutBack'
    });
});

$(".submit").click(function(){
    return false;
})

<fieldset>

Step 1

Background Information

    <input type="text" id="fullname" name="fullname" placeholder="Full Name">
    <input type="text" id="email" name="email" placeholder="E-Mail">
    <input type="text" id="phone" name="phone" placeholder="Phone">
    <input type="number" id="age" name="age" placeholder="Age">

Gender

            <input type="radio" name="gender" value="male" id="gender-male"/>
            Male

            <input type="radio" name="gender" value="female" id="gender-female"/>
            Female

Description

            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Consectetur adipiscing elit, sed do eiusmod tempor.

    <input type="button" name="next" id="btnNext" class="next action-button" value="Next" />
</fieldset>

<fieldset>

Step 2

Please select one of the following

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

        <select name="past" id="past">
            <option value=""disabled selected>Select One</option>
            <option value="a">Yes</option>
            <option value="b">No</option>
        </select>

    <input type="button" name="previous" class="previous action-button" value="Previous" />
    <input type="button" name="next" class="next action-button" id="PastNext" value="Next" />
</fieldset>

<fieldset>

Step 3

Please select one of the following

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

        <select>
            <option value=""disabled selected>Select One</option>
            <option value="a">Yes</option>
            <option value="b">No</option>
        </select>

    <input type="button" name="previous" class="previous action-button" value="Previous" />
    <input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<fieldset>

Step 4

Please select one of the following

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

        <select>
            <option value=""disabled selected>Select One</option>
            <option value="a">Yes</option>
            <option value="b">No</option>
        </select>

    <input type="button" name="previous" class="previous action-button" value="Previous" />
    <input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<fieldset>

Step 5

Please select one of the following

    Can you come to this location?

        <select>
            <option value=""disabled selected>Select One</option>
            <option value="a">Yes</option>
            <option value="b">No</option>
        </select>

Terms and Conditions

            <input id="terms" type="checkbox">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

    <input type="button" name="previous" class="previous action-button" value="Previous" />
    <input type="submit" name="submit" class="submit action-button" value="Submit" />
</fieldset>

DROP DOWN MENU ALERT CODE:

$("#PastNext").click(function(event){
    var validate = $("#past").val();
    if(validate == "")
    {
        event.preventDefault();
        alert("You have not selected any option");
    }
});

A: Right before if(animating) return false;
 like this:
//First select
if($("#past").val()=="")
{
   alert("You have not selected any option");
   return false;
}
//Next select
else if($("#past2orwhateverthenameis").val()=="")
{
   alert("You have not selected any 2nd option");
   return false;
}

Do for all 5.


text:
Q: Onclick is being called multiple times I have a list view with a checkbox and clickable textviews defined as below:
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:focusableInTouchMode="false"
        android:focusable="false">
        <CheckBox
            android:id="@+id/favouritebutton"
            android:layout_width="60dp"
            android:layout_height="40dp"
            android:layout_centerHorizontal="true"
            android:text="Like"
            android:focusable="false"
            android:clickable="true"
            android:layout_centerVertical="true"
            android:gravity="center_vertical"
            android:textSize="12sp">
        </CheckBox>
        <TextView
            android:id="@+id/behindPlanItemLabel"
            android:layout_width="60dp"
            android:layout_height="40dp"
            android:drawablePadding="-5dp"
            android:focusable="false"
            android:clickable="true"
            android:gravity="center_vertical"
            android:text="Plan"
            android:textColor="#000000"
            style="@style/behindPlanItemLabel"
            android:textSize="12sp" />
        <TextView
            android:id="@+id/behindTimeItemLabel"
            android:layout_width="60dp"
            android:layout_height="40dp"
            android:drawablePadding="-5dp"
            android:gravity="center_vertical"
            android:text="Timer"
            android:focusable="false"
            android:clickable="true"
            android:textColor="#000000"
            style="@style/behindTimerItemLabel"
            android:textSize="12sp" />
    </LinearLayout>

I have defined a CustomerAdapter which extends CursorAdapter and implements onClickListener.
In the newView method, i am adding the listener on each of the button and text views as
        viewHolder.timerView.setOnClickListener(this);
        viewHolder.likeBox.setOnClickListener(this);
        viewHolder.planView.setOnClickListener(this);

I have overriden the Onclick view to catch the click.
When I click the timer which is the 3rd item in the layout,
the onclick is called once but when I click the 'plan' which is the 2nd item in the layout,
the onCLick is called twice and when i click the 'like' which is the 1st item in the layout onclick is called 3 times.
I need to get only oneClick callback for any click.
Any suggestion on what I am doing wrong here ?
Below is the full onCLick code
      @Override
        public void onClick(View view) {
            int actionType;

            switch (view.getId()) {
                case R.id.favouritebutton:
                    Log.d(LOG_TAG, "favourite button");
                    actionType = Constants.CLICKED_FAV;
                    // Do something
                case R.id.behindPlanItemLabel:
                    Log.d(LOG_TAG, "plan button");
                    actionType = Constants.CLICKED_PLAN;
                    // Do something
                case R.id.behindTimeItemLabel:
                    Log.d(LOG_TAG, "timer button");
                    actionType = Constants.CLICKED_TIMER;
                    // Do something
            }
    }

A: Thanks for your inputs. My problem is now fixed by adding return in the each switch case statement.
           switch (view.getId()) {
                case R.id.favouritebutton:
                    Log.d(LOG_TAG, "favourite button");
                    actionType = Constants.CLICKED_FAV;
                    // Do something
                 return;
                case R.id.behindPlanItemLabel:
                    Log.d(LOG_TAG, "plan button");
                    actionType = Constants.CLICKED_PLAN;
                    // Do something
                   return;
                case R.id.behindTimeItemLabel:
                    Log.d(LOG_TAG, "timer button");
                    actionType = Constants.CLICKED_TIMER;
                    // Do something
                    return;
            }

A: use this in your onclick listener inside adapter if it goes to other activity. intentName.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);


text:
Q: Method-Object pairs in Java I'd like to create a list of method-object pairs. Each method is a function returning a boolean. Then:
foreach(pair) {
   if method evaluates to true {
      do something with the object
   }
}

One way of modelling this that I can think of is to have a class Constraint with a method isValid() and for each constraint produce an anonymous class (overriding the isValid() method). I feel like there could be a nicer way. Can you think of any?

A: In Java there are no method pointers, so the only (better) way of doing this is using a common Interface as you said:
public interface Constraint {
    boolean isValid();
}

This way you can create a map (or a List of Tuple, as you wish), iterate over the elements, call the Constraint isValid method and perform the operation based on the response:
public void doThings(Map<Constraint, Object> map) {
    for (Entry<Constraint, Object> entry: map.entrySet()) {
        if (entry.getKey().isValid()) {
            Object obj = entry.getValue();
            // Do whatever you want with the object
        }
    }
}

Hope it helps.
Regards!

A: This would be easier in Java if functions were first class objects, but your approach of returning an anonymous class will work. I think a cleaner approach however is the Domain Driven Design specification pattern. The idea is defining an interface:
interface Specification {
    boolean isSatisfiedBy(Criteria criteria)
}

interface Criteria {
    /* what goes on here is up to you */
}

This would let you iterate through say a collection of Specification entities as:
for (Specification s : specifications) {
    if (!s.isSatisfiedBy(criteria) { continue; }
    /* do something */
}

A: Program through an interface that you implement with your class:
package test;

public interface Constraint {
  boolean isValid();
}

Use the interface as your variable and it doesn't matter what class is in the list as long as it implements the interface.  Program to interfaces...
package test;

import java.util.LinkedList;
import java.util.List;

public class Main {
  public static void main(String[] args) {

    List<Constraint> list = new LinkedList<Constraint>();

    list.add(new A());
    list.add(new B());

    for (Constraint con : list) {
      if (con.isValid()) {
        System.out.println("True");
      }
      else {
        System.out.println("False");
      }
    }

  }
}

class A implements Constraint {
  @Override
  public boolean isValid() {
    return false;  // add real code for valid check
  }
}

class B implements Constraint {
  @Override
  public boolean isValid() {
    return true;  // add real code for valid check
  }
}

A: Have a look at Google's Guava library. It already contains 2 interfaces that may interest you.
The Predicate is an interface that is very similar to what you are doing with Constraint. Instead of isValid() it has a method called apply() which returns a boolean to indicate whether or not something should be done to the object passed in. This is paired with other collection functions within the Guava library to perform (or not perform) operations on entire collections. Which is exactly what you appear to be doing with your for:each loop.
The Function interface may interest you as well, but only because you brought up Function pointers. I think the Predicate interface with some of the other collection classes in Guava will do exactly what you need in a minimal amount of readable code.
An example of this would be:
for(Pair pair : Collections2.filter(pairs, pairPredicate)){
  // Do something. All pairs that get to this point have been validated
}


text:
Q: redirect all traffic from server A (Linux) to another server B (Linux) without intercepting ssh to server A I would like to forward all traffic from a server (Linux) to another server (Linux) without  losing ssh access to first server.
Authorities (government) have been shutting down the Internet, we have a hard time accessing outside of the country's Internet.
I have configured Server B with OpenConnect Server and I can connect successfully from local to Server B
Local Machine === (via vpn) ===> Server B

But sometimes Server B is not reachable form local and I only can access it from Server A (only thought A to B)
Local Machine === (ssh) ===> Server A === (ssh) ===> Server B

Here is the workflow I try to get it right in order to redirect (or forward) all traffic from Server A to Server B
Local Machine === (via vpn) ===> Server A === (via vpn) ===> Server B

So I can connect from local to Server B, while Server A is a helper and

*

*it is a OpenConnect server (so I can connect from local to this)

*all traffic is forwarded to Server B (via opencoonect client)

*I can SSH to Server A to manage it (which is is connected to Server B)

I try to use OpenConnect client to make a connection from Server A to Server B.
And I know this operation cuts my SSH connectivity and Server B incoming traffic.
Question 1. Is it possible using OpenConnect to solve this issue or no, another solution like using a MicroTik is better, or turning Server A into a router ...
Question 2. if using OpenCoonect can get it done, how to configure Server A?
I have tried some ip command as well as iptables on Server A, but did not work.

Server A (VM, Debian 11)

*

*has public IP address (inside my country)

*has only one interface (eth0)

Server B (VM, Ubuntu 20)

*

*has public IP address (outside of my country)

*has only one interface (eth0)

*is an OpenCooenct Server

Regards.

A: Can you elaborate on the desired outcome vs the perceived issue please? Like what is the specific goal. A router that tunnels all WAN traffic encrypted, to exit elsewhere like TOR. IS it just for web browsing (HTTP proxy) or other application (SoCKS proxy), etc?
IF that is the case, I do this at home to bypass my cell provider's bandwidth steering. I use a cellular modem ATT thinks is a phone for home internet. They can be very finicky about what sites they allow full barrel and what they like to nanny. I have a very basic linux router that does a proxy to an SSH server on another network I control elsewhere and not ATT. Then I use that for the whole LAN by setting up SOCAT As a service, and relaying that through the SSH proxy listening on 127.0.0.1.
My LAN clients set the firewall as their proxy, and the internet thinks all the clients are on the other network when they reach the world.
So in your case you would need someone in a non restricted area, and a port/protocol that would pass whatever they are filtering. From there all your traffic would go through that tunnel, and NOT be subject to inspection.
IS this what you are going for, if so I could provide instruction on how to do that....
SSH tunneling
https://www.baeldung.com/linux/ssh-tunneling-and-proxying
SOCAT socket forwarding (relay to and from proxy at 127.0.0.1 to LAN accessible interface IP)
https://www.redhat.com/sysadmin/getting-started-socat
Very basic linux router to wrap it into.
https://gridscale.io/en/community/tutorials/debian-router-gateway/
If you do the minimal install "Expert install" your router/firewall will be very small.
Can do the same for the remote endpoint, really it is just an SSH server that allows dynamic forwarding, again, bare minimum linux install required, and very meager resources.'
Easy to preconfigure and ship to someone out of the country to run in something like KVM or virtualbox.
Use Pubkey at least for SSH authentication if you plan on putting on the internet.
Suggested pubkey + password to be safer, and if you are comfortable use MFA like google authenticator as well.
https://kb.iu.edu/d/aews
https://goteleport.com/blog/ssh-2fa-tutorial/
Then all you have to do is trust whomever is running the remote side.

A: After more searching, I found there are two ways to solve this issue

*

*site to site VPN (e.g. using MikroTik RouterOS)

*client to server VPN (e.g using OpenConnect or SoftEther)

In site to site VPN, the tunnel is created from a network gateway (to another network gateway), so we have no issue SSH-ing to our VM.
But in client to client/site VPN, since we run the VPN client within the VM we have SSH-ed into, the traffic of our SSH session is blocked, since the whole VM traffic is routed thought the VPN client interface (e.g tun0).
For solving this issue, simply we can add a static route for our SSH session before running the VPN client. See the answer

*

*Prevent SSH connection lost after logging into VPN on server machine
Now I am able to SSH to a VM, from there run the VPN client, bypassing all network restriction (in my country) while my SSH session is active and functioning.

Finally I could solved the issue.
From my local machine to ServerA (a VPN server) using one of these protocols:

*

*OpenVPN

*WireGuard

*SSTP

*OpenConnect

and from there (Server A) to Server B (second VPN server) using SoftEther SSTP.
So I am able to do this:
Local Machine === (via vpn) ===> Server A === (via vpn) ===> Server B
# and finally
# local machine IP = Server B IP


text:
Q: Using NODE_DELETE without refetching data Using a NODE_DELETE requires the parent, and to actually return the parent of the connection:
Relay Error when deleting: RelayMutationQuery: Invalid field name on fat query
Unfortunately, using this refetches ALL my nested items, which is simply unacceptable for my use case.
  fragment on deleteItemNested @relay(pattern: true) {
    id
    ok
    item {
      nested {
        edges {
          node { id }
        }
      }
    }
    clientMutationId
  }

Is there a way to delete an item from a connection/list without refetching all data? Trying not to fetch for the edges in nested results in nested being just an empty object.

A: All the nested items are refetched because @relay(pattern: true) was used in the query. This makes the query to match against the tracked query, which already includes the nested fields. See an excellent answer by steveluscher to the question Purpose of @relay(pattern:true).
The code example of NODE_DELETE in mutation documentation is worth taking a look.


text:
Q: Windows Phone 8 Panorama SelectionIndex not changing on swiping through items I have created Panorama control and binded PanoramaItem from ItemSource. Now when i am changing the selected Panoramaitem by swiping over them the Selected index is always set to -1. I dont know what wrong i am doing while implementation. neither selectionchange event is getting fired.
Code:
<phone:Panorama Grid.Row="1"  Visibility="Visible"
       x:Name="PnrVwMainNews"
       ItemsSource="{Binding ParnormaItemsData}"
       ItemContainerStyle="{StaticResource PanoramaContainerItemStyle}">
    <phone:Panorama.ItemTemplate>
        <DataTemplate>
            <!-- Panorma Items Template -->
            <Controls:DynamicContentControl Content="{Binding UsrCntrlDynamic}" />
        </DataTemplate>
    </phone:Panorama.ItemTemplate>
</phone:Panorama>

PanoramaContainerItemStyle
<Style x:Key="PanoramaContainerItemStyle" TargetType="phone:PanoramaItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        <Setter Property="VerticalContentAlignment" Value="Stretch" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="phone:PanoramaItem">
                    <Grid Background="{TemplateBinding Background}" Margin="12,0,0,0">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="auto" />
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>

                        <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" Grid.Row="1" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

A: I can't see any Selection_Changed event implemented/hooked here.
SelectionChanged="Panorama_SelectionChanged"

You should at first define this event on Panorama level.
(Not inside the PanoramaContainerItemStyle)

A: assign null to SelectedItem at last in SelectionChanged event handler, so that new item will get selected every time.


text:
Q: How to monitor multiple node insertions at different levels in dom using MutationObserver I have a parent node  in my dom. I have to call a method when a specific element is inserted in the parent node (newly inserted node is not a direct child, its a subtree, may be present at 2/3 level deep).
I have a code for single element insertion which works as expected
var parentNode = jQuery('.parent-node');
var observer = new MutationObserver(function (mutations) {
    if (parentNode.find('.sub-class-1')[0] !== undefined) {
        //call method
        this.disconnect();
    }
 }).observe(parentNode[0], {childList:true, subtree: true });

But i want to execute callbacks for multiple sub elements creations. i tried this by using forEach on sub-class elements array.
arr.forEach(function (ob) {
    new MutationObserver(function (mutations) {
        if (parentNode.find(ob.className)[0] != undefined) {
            //ob.callback()
            this.disconnect();
        }
    }).observe(parentNode[0], { attributes:false, childList: true, subtree: true });
});

But after processing one subclass, it does not processes the rest subclasses. I guess we can only create on object on particular node.
So, how to detect all this nodes on creation to execute specific callbacks using MutationObserver or is there any better alternative approach.

A: Hi please try this,
var config = { attributes: true, childList: true, characterData: true };
var observers = [];
function createObserver(target, index) {
var observer = new MutationObserver(function(mutations) {
    var $this = this;
    mutations.forEach(function(mutation) {
        if (parentNode.find('.sub-class-1')[0] !== undefined) {
            $this.disconnect();
        }else{
            observers.push($this);
        }
    });
});
observer.observe(target, config);
}
$('.parent-node').each(function(i, el) {
createObserver(el, i)
});


text:
Q: Need help changing this NGINX config to APACHE2 So I've been trying to rewrite this NGINX config to apache2 for over a few hours now.
But nothing seems to be working.
Current NGINX configuration:
server {
  listen 80;
  server_name dash.mcworld.cc;
  return 301 https://$server_name$request_uri;
}
server {
  listen 443 ssl http2;

location /afkwspath/ {
  proxy_pass "http://localhost:8080/afkwspath";
  proxy_read_timeout     60;
  proxy_connect_timeout  60;
  proxy_redirect         off;
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection 'upgrade';
  proxy_set_header Host $host;
  proxy_cache_bypass $http_upgrade;
}

  server_name dash.mcworld.cc;
  ssl_certificate /etc/letsencrypt/live/dash.mcworld.cc/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/dash.mcworld.cc/privkey.pem;
  ssl_session_cache shared:SSL:10m;
  ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
  ssl_ciphers  HIGH:!aNULL:!MD5;
  ssl_prefer_server_ciphers on;

  location / {
    proxy_pass http://localhost:8080/;
    proxy_buffering off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_read_timeout     60;
    proxy_connect_timeout  60;
    proxy_redirect         off;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}
}

I've tried a few things but the /afkwspath I can't seem to find a alternative.
Could someone help me with this? I'd be very grateful
Thanks


text:
Q: How to draw a curved line in tikz-cd instead of tikz? I was working on a project and was trying to give Tikz-cd a shot but I was having trouble with adding a curved arrow beneath from one end to the other.
I have done something similar to this between two nodes before just using tikz, but since nodes aren't necessarily defined the same way when using tikz-cd I wasn't sure how I should go back and add the line.  I included the regular tikz example to show how I had done it before and my new diagram exactly as it should appear except for another curved line from 0 to 0. Can anyone help explain how to do this in the new setting?
Also, the new arrow does not need to be a \mapsto arrow, but ideally would be.
mwe:
\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath,amssymb}
\usepackage{graphicx,tikz,tikz-cd}
\usepackage[margin=2.25cm]{geometry}
\usepackage{fancyhdr}
\pagestyle{fancy}
\lhead{Tikz vs. Tikz-cd}
\cfoot{}
\begin{document}
I have done this using just Tikz in the past.
\[\begin{tikzpicture}[node distance=2cm]
    \node (Q1){$0$};
    \node[right of=Q1] (Q2){$L$};
    \node[right of=Q2] (Q3){$M$};
    \node[right of=Q3] (Q4){$N$};
    \node[right of=Q4] (Q5){$0$};
    \draw[->,thick] (Q1) -- (Q2);
    \draw[->,thick] (Q2) -- node[pos=.5,above]{$\psi$}(Q3);
    \draw[->,thick] (Q3) -- node[pos=.5,above]{$\varphi$}(Q4);
    \draw[->,thick] (Q4) --(Q5);
    \draw [bend left,->,dashed] (Q4) to node[pos=.5,below]{$\alpha$}(Q3);
    \draw [bend left,->,dashed] (Q3) to node[pos=.5,below left]{$\beta$}(Q2);
\end{tikzpicture}\]

Now I am trying to switch to using Tikz-cd, and I would like to add a curved under arrow from the zero on one end to the other. I have been able to solve the rest of it but I am not very fluent with the tikz-cd syntax yet.

\[\begin{tikzcd}[node distance=2cm]
   0 \arrow[mapsto]{r}{\varphi^{(1)}_{1}}
& 24 \arrow[mapsto]{r}{\varphi^{(1)}_{1}}
& 17 \arrow[mapsto]{r}{\varphi^{(1)}_{1}}
& 18 \arrow[mapsto]{r}{\varphi^{(1)}_{1}}
& 0
\end{tikzcd}\]

\end{document}
Okay, I was able to add this line:
& 0 \arrow[mapsto, bend left]{l}

which got me the curved line, but only back one node instead of 4 if that helps.

A: tikz-cd basically a matrix of nodes or, in other words, a table. So if you write \arrow[mapsto, bend left]{l} it goes left (l) only one node, because you're indicating only one cell.
Replace it with \arrow[mapsto, bend left]{llll}.

A: This can be another approach with tikz-cd.

\documentclass[a4paper,12pt]{article}

\usepackage{tikz-cd,amsmath,amssymb}

\begin{document}
\begin{tikzcd}
0 \arrow[r, "\varphi^{(1)}_{1}", maps to] & 24 \arrow[r, "\varphi^{(1)}_{1}", maps to] & 17 \arrow[r, "\varphi^{(1)}_{1}", maps to] & 18 \arrow[r, "\varphi^{(1)}_{1}", maps to] & 0 \arrow[llll, maps to, bend left]
\end{tikzcd}
\end{document}


text:
Q: When is hdfs-site.xml loaded by hadoop? I have hive and hadoop installed in my system.
This is my hdfs-site.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>dfs.replication</name>
        <value>1</value>
    </property>
</configuration>

If i do bin/start-all.sh and go to my hive and run a select query I get the error  :
The ratio of reported blocks 0.0000 has not reached the threshold 0.9990. Safe mode will be turned off automatically.

If I wait for some time and run the hive query again, it works.
I read that the safemode threshold is set using the property: dfs.namenode.safemode.threshold-pct
I added that property in my hdfs-site.xml
<property>
     <name>dfs.namenode.safemode.threshold-pct</name>
     <value>0.500f</value>
</property>

Again i started all hadoop nodes, and run the hive query, But i was still getting the same error
The ratio of reported blocks 0.0000 has not reached the threshold 0.9990. Safe mode will

It means that either my xml is wrong, or I have to do something else to actually load the hdfs-site.xml.
Can someone tell me what I am doing wrong?

A: I was doing a mistake. I went a checked the hdfs-default.xml in the src folder and found this
<property>
<name>dfs.safemode.threshold.pct</name>
<value>0.999f</value>
<description>
Specifies the percentage of blocks that should satisfy
the minimal replication requirement defined by dfs.replication.min.
Values less than or equal to 0 mean not to start in safe mode.
Values greater than 1 will make safe mode permanent.
</description>
</property>

I think i am using old version of hadoop because dfs.safemode.threshold.pct is deprecatd.
Modified my hdfs-site.xml,stopped and started the namenode
<property>
<name>dfs.safemode.threshold.pct</name>
<value>2</value>
</property>

and it worked!
The ratio of reported blocks 0.0000 has not reached the threshold 2.0000. Safe mode will be turned off automatically.


text:
Q: Referencing several models from one model class- Bad practice? I want to obtain all notifications for current user with this code:
current_user.follows.each do |follow|
    follow.followable.open_notifications.each do |notification|
        if !notification.reads.include?(current_user)
            @open_notifications += notification
        end
    end
end

So far I had this code in my controller however I know this kind of logic should be place in model class.
After moving code:
OpenNotification Controller:
OpenNotification.fetch_unread(current_user)

OpenNotification Model:
def self.fetch_unread(user)
    @open_notifications = []
    user.follows.each do |follow|
        follow.followable.open_notifications.each do |notification|
            if !notification.reads.include?(user)
                @open_notifications += notification
            end
        end
    end
    @open_notifications
end

EDIT:
Classes involved:

*

*User

*Follow - who(user) follows what(followable)

*Followable(polymorphic - may be User, Event or a Place)

*OpenNotification - stores information about the change of followable object

*Read - who read which notification (user_id and open_notification_id)

User:
has_many :follows, class_name: 'Follow',
                 source: :user

has_many :follows_as_fallowable,
                class_name: 'Follow',
                as: :followable

has_many :followers, through: :follows_as_fallowable,
                   source: :user

Event:
has_many :follows, as: :followable
has_many :followers, through: :follows,
                         source: :user

has_many :open_notifications, as: :followable

OpenNotification:
belongs_to :followable, polymorphic: true
has_many :reads

Reads:
belongs_to :user
belongs_to :open_notification

My question is if it is a good practice to refer to multiple classes from the class responsible for one particular resource?
If this is not a good practice, how the code should be refactored?

A: Referencing several models from within one model is perfectly fine as long as you can justifiably say that your Notification model should be aware of the User model (basically do a majority of notification interactions deal with users as well?).  In the little that you show here I would say it does however you'll have to consider this question application wide and re-evaluate it.  If you think that that may be a bit of a stretch I would recommend ecapsulating this logic into a separate class to keep your code more maintainable and predictable if someone were to ever collaborate with you on this (think Service Object).  Also, where you're appending notifications to @open_notifications you should consider using << since that won't reconstruct the @open_notifications object every time whereas += will instantiate it over and over again leaving more work for the garbage collector.  On large operations you'll see a massive speed gain here.


text:
Q: DataTables and how the filtering methods works Can anyone help me understand how the DataTables $.fn.dataTableExt.afnFiltering.push method works?
I know that you can subscribe some methods to do some filtering on DataTables (using a predefined signature - which accepts Settings, Data and DataIndex as inputs, and must return true or false indicating if the row should or not be shown).
My doubt is about the table in which it operates. Assuming we have more than one DataTable on a page, how can we define in which of those tables the subscribed method will be used for filtering? Will it always be used? And if this is the case, can I test (somehow) for which element is the method being executed (so i could do the filtering for the right DataTable and leave the others untouched)?
Thanks in advance.

A: Ooops. Found it. Here's where i found it: How to apply filter to specific datatable
And here's what i did:
$.fn.dataTableExt.afnFiltering.push(function(oSettings, aData, iDataIndex) {
// check if current table is the table i want
if (oSettings.nTable == $('#myTableId'))
{
    return (aData[IndexOfColumnToFilter] = filterCondition)
}
// for other tables, just do not filter...
return true;
}


text:
Q: nonfree (SIFT, SURF) usage in android with java I am having trouble with nonfree methdos usage in android. SIFT and SURF methods are not included in opencv-android-2.4.8. They are needed to be complied seperately.
https://sites.google.com/site/wghsite/technical-notes/sift_surf_opencv_android
This is the main tutorial about nonfree module compilation. However, the jni part for java users are not included. I have searched how to use compiled .so libraries but I could not achieve.
I wonder that someone can share the jni part for nonfree modules or detailed explanation for it, because I work on that issue over a week and I could not do it.
Thanks.

A: I am the author of the tutorial. I will be adding another tutorial showing the JNI part. Hope that will help. Please go back and check the tutorial in the next couple of days. I will post it soon.

A: I solved the problem. When you follow the tutorial(the link given in the question) you get the necessary libraries(.so files). In order to use them in java you do not need to implement jni part. When you load the libraries in your java code (System.load(libraryName)), then you can use sift and surf methods like the other detectors or descriptors. You can directly use the code pattern supplied by the opencv-2.4.8.

A: Assuming that you've already gotten OpenCV 4 Android to work on your Android device;
1) I placed libnonfree.so, libopencv_java.so and libgnustl_shared.so (not sure if the last one is needed) in the correct folder for your platform, in my case jniLibs/armeabi-v7a. Already compiled version can be find in the demo folder here; https://github.com/bkornel/opencv_android_nonfree
2) Make sure you load both libraries.
static {
    System.loadLibrary("opencv_java");
    System.loadLibrary("nonfree");
}

This was all that was required in order for it to work for me.

A: @fetifati, Do you mean to say that if I copy libnonfree.so and libopencv_java.so in say lib/armeabi folder and do System.load("nonfree"); System.load("opencv_java"), I can use code like:
private static final FeatureDetector detector = FeatureDetector
        .create(FeatureDetector.SIFT);
private static final DescriptorExtractor extractor = DescriptorExtractor
        .create(DescriptorExtractor.SIFT);

directly ? ... It doesn't seem to work for me. I am getting some errors.


text:
Q: Prove that $R\left[x\right]/I\left[x\right]\cong\left(R/I\right)\left[x\right]$ Let $I$ be an ideal of a ring $R$, define $I[x]$ to be the set of all polynomials whose coefficients are in $I$. Prove that $R\left[x\right]/I\left[x\right]\cong\left(R/I\right)\left[x\right]$
Help me some hints

A: It suffices to consider the map :
$$\phi :R[X] \rightarrow (R/I)[X]$$
such that :$\phi(a_0+a_1X^2+...+a_nX^n)=\bar{a_0}+...+\bar{a_n}X^n$ then it is clear that $\phi$ is surjective and $Ker(\phi)=I[X]$ so we have : $$R[X]/I[X]\cong (R/I)[X].$$


text:
Q: Why I cannot log into jaeger-agent docker container? The only container that I cannot get into and check what's inside is jaeger-agent, downloaded from here.
Why is this so? How can I get inside?
Ideally:
docker exec -it jaeger-agent bash

would let me in the container

A: Because it is super minimalist and I do not have the necessary apps on it.
However with newer versions things are better.


text:
Q: JQuery. Simple drop down selection menu behavior question I have a simple html option/select (dropdown) menu.  I want to use JQuery to redirect links when an option is selected.  I have a "go" button in noscript tags in case javascript is disabled, but in the case that the user has javascript..I would like the redirection to happen automatically on-click.  Could somebody please guide me on how to accomplish this using jquery (I have this done using simple javascript 'onclick' events but I'd like to move all of my code to jquery)?
Right now my code looks like this (the function gets call from the 'onclick' event):
function option(dropdown) {
        var myindex  = dropdown.selectedIndex
        var SelValue = dropdown.options[myindex].value
        var baseURL;
        if(SelValue=="1")
            baseURL="something1";
        else if(SelValue=="2")
            baseURL="something2";
        else if(SelValue=="3")
            baseURL="something3";
        top.location.href = baseURL;

        return true;
}

A: To bind the click element in jQuery you can do
$('#elementId').click(function(){
  //do redirection
});

But for you case I think you need to bind the change event
$('#elementId').change(function(){
  var optionSelectedValue = $('#elementId option:selected').val();
  if(optionSelectValue == value1) {
     newUrl = url1;
  }
  else if(optionSelectValue == value2) {
     newUrl = url2;
  }
  top.location.href = newUrl;
});


text:
Q: How to remove multiple cells from tiled map editor when collision with object that spans over multiple tiles I am creating a brick breaker game using libgdx, using the TiledMapEditor to create my levels. i have a layer for my brick graphics and a layer for my brick objects. i have collision working with my brick objects, i have the tile in the brick graphics layer set to null when Collison happens and working. Great, Awesome... except i have created my brinks to be multiple tiles in size. so when i collide with my brick object it turns collision off and removes that specific cell graphic. Leaving me with half the brick still showing on the screen. i have checked the documentation on tiledMaps, the libdx dox and searched slack/goodle/youtube/tiled dox. i thought of creating a method to check if the cells around is not null then to turn them null, but that wont work when i have bricks right beside each other. any ideas or suggestions or even a hint to where to look would be much appreciated. Or to change my sizing of my bricks to fit in one tile. i would rather figure a way out to remove all cells that are over the specified objects
Class for creating my interactive objects
    public InteractiveTileObject(World world, TiledMap map, Rectangle rect) {
        this.world = world;
        this.map = map;
        this.rect = rect;

        bDef = new BodyDef();
        fDef = new FixtureDef();
        shape = new PolygonShape();

        bDef.type = BodyDef.BodyType.StaticBody;
        bDef.position.set((rect.getX() * Arma.VSCALE) + (rect.getWidth() * Arma.VSCALE / 2),
                (rect.getY() * Arma.VSCALE) + (rect.getHeight() * Arma.VSCALE / 2));

        body = world.createBody(bDef);

        shape.setAsBox(rect.getWidth() * Arma.VSCALE / 2, rect.getHeight() * Arma.VSCALE / 2);
        fDef.shape = shape;
        fixture = body.createFixture(fDef);
    }

    public abstract void onHit();

    public void setCategoryFilter(short filterBit){
        Filter filter = new Filter();
        filter.categoryBits = filterBit;
        fixture.setFilterData(filter);
    }
    public TiledMapTileLayer.Cell getCell(){
        int column = (int)(body.getPosition().x / Arma.VSCALE / 50);
        int row = (int)(body.getPosition().y / Arma.VSCALE / 50);
        TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(2);
        return layer.getCell(column,row);
    }
}

Class that pulls objects from TiledMapEditor
public B2WorldCreator(PlayScreen screen) {
        World world = screen.getWorld();
        TiledMap map = screen.getMap();

        BodyDef bDef = new BodyDef();
        PolygonShape shape = new PolygonShape();
        FixtureDef fDef = new FixtureDef();
        Body body;

        //create boundy body/fix
        for (MapObject object : map.getLayers().get(3).getObjects().getByType(RectangleMapObject.class)) {
            Rectangle rect = ((RectangleMapObject) object).getRectangle();
            new Boundary(world, map, rect);
        }
        //create bricks body/fix
        for (MapObject object : map.getLayers().get(4).getObjects().getByType(RectangleMapObject.class)) {
            Rectangle rect = ((RectangleMapObject) object).getRectangle();
            new Brick(world, map, rect);
        }

        //create wall light body/fix
        for (MapObject object : map.getLayers().get(5).getObjects().getByType(RectangleMapObject.class)) {
            Rectangle rect = ((RectangleMapObject) object).getRectangle();
            new Wall(world, map, rect);
        }
    }
}

Brick Class
public class Brick extends InteractiveTileObject{

    public Brick(World world, TiledMap map, Rectangle bounds) {
        super(world, map, bounds);
        fixture.setUserData(this);
        setCategoryFilter(Arma.BRICK_BIT);
    }

    @Override
    public void onHit() {
        Gdx.app.log("Brick", "Collision");
        setCategoryFilter(Arma.DEYSTROYED_BIT);
        getCell().setTile(null);

    }
}

i created this method which works but still need to enter the size of the objects, i would much rather get your method working Tobias.
public void getCells(int width, int height){
        int column = (int)((body.getPosition().x / Arma.VSCALE -25) / 50);
        int row = (int)((body.getPosition().y / Arma.VSCALE -25) / 50 );
        TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(2);
        for (int i = 0; i < width; i++){
            for (int k = 0; k < height; k++){
                if (layer.getCell(column + i, row + k) != null)
                    layer.getCell(column + i, row + k).setTile(null);
            }
        }

A: You are selecting the cells, that you want to remove by their position on the tiled map. You can do the same for the other cells, that are in the range of the Box2D body, that was hit. The only difference is, that it's a bit more difficult to check whether the tested position is still inside the body (currently you are only checking the body's position).
A solution could look like this:
public class InteractiveTileObject {

    // ... other methods

    public Array<TiledMapTileLayer.Cell> getCells(){
        Array<TiledMapTileLayer.Cell> cells = new Array<>();
        TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(2);

        for (int i = 0; i < MAX_NUMBER_OF_CELLS_PER_BODY; i++) {
            for (int j = 0; j < MAX_NUMBER_OF_CELLS_PER_BODY; j++) {
                float x = body.getPosition().x + i * SIZE_OF_A_TILE_CELL;
                float y = body.getPosition().y + j * SIZE_OF_A_TILE_CELL;
                if (doesBodyContainPoint(body, x, y)) {
                    int column = (int)(x / Arma.VSCALE / 50);
                    int row = (int)(y / Arma.VSCALE / 50);
                    cells.add(layer.getCell(column, row));
                }
            }
        }

        return cells;
    }

    private boolean doesBodyContainPoint(Body body, float x, float y) {
        // to check whether the body contains a point you need to check whether any of the body's fixtures contains the point:
        for (Fixture fixture : body.getFixtureList()) {
            if (fixture.testPoint(new Vector2(x, y)) {
                return true;
            }
        }
        return false;
    }
}

After you filled in the constants of MAX_NUMBER_OF_CELLS_PER_BODY and SIZE_OF_A_TILE_CELL you should be able to find every cell, this body contains. Then you can just remove them like you did before.


text:
Q: Logistic Regression Gradient Descent in Matlab Here is the code
function [theta] = LR(D)
% D is the data having feature variables and class labels

% Now decompose D into X and C
%Note that dimensions of X =  , C =

C = D(:,1);
C = C';
size(C)
X = D(:,2:size(D,2));
size(X)
alpha = .00001;

theta_old = zeros(1,34);
theta_new = .001.*ones(1,34);
count = 1;
for count = 1:100000
    theta_old = theta_new;
    theta_new = theta_new + alpha*(C-sigmoid(X*theta_new')')*X;
    llr =  sum(LLR((X*theta_new').*(C')))
end
thetaopt = theta_new

end

function a = LLR( z )
a= 1.*log(1.0 + exp(-z));
end

function a = sigmoid(z)
 a = 1.0 ./ (1.0 + exp(-z));
 end

The problem I have is that the log likelihood ratio first decreases, and then starts increasing. Is this a problem with the Gradient Descent algorithm or with the code.

A: It looks like there could be a problem with your objective function.
If the labels (C) are in {0,1}, then you should be using the loss C.*LLR(X*theta')+(1-C).*(LLR(X*theta')+X*theta')
If your labels are in {-1,1}, then the loss should be LLR(C.*X*theta').
You seem to be using only the first part of the first type of loss function.


text:
Q: How figure out, if the webserver is still active I forward the incoming messages from Kafka to a webserver via websocket client.
The following code shows, how I am doing it:
import akka.Done
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.ws._
import akka.kafka.scaladsl.Consumer
import akka.kafka.{ConsumerSettings, Subscriptions}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Flow, Keep, Sink, Source}
import com.typesafe.scalalogging.Logger
import org.apache.kafka.clients.consumer.ConsumerConfig
import org.apache.kafka.common.serialization.StringDeserializer

import scala.concurrent.{Future, Promise}

final case class WsGraph(logger: Logger, sink: Sink[Message, Future[Done]])(implicit val system: ActorSystem) {

  private implicit val materializer = ActorMaterializer()
  private implicit val akka = system.settings.config.getConfig("akka.kafka.consumer")
  private implicit val executor = system.dispatcher
  private val consumerSetup = system.settings.config.getConfig("kafka.consumer.setup")
  private val wsSetup = system.settings.config.getConfig("websocket.setup")

  private val consumerSettings: ConsumerSettings[String, String] =
    ConsumerSettings(akka, new StringDeserializer, new StringDeserializer)
      .withBootstrapServers(consumerSetup.getString("bootStrapServers"))
      .withGroupId(consumerSetup.getString("groupId"))
      .withProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest")

  private val kafkaAsSource: Source[Message, (Consumer.Control, Promise[Option[Message]])] = Consumer
    .plainSource(
      consumerSettings,
      Subscriptions.topics(consumerSetup.getString("topics"))
    )
    .map(msg => TextMessage(msg.value()))
    .concatMat(Source.maybe[Message])(Keep.both)
    .mapAsync(Runtime.getRuntime.availableProcessors())(Future(_))

  private val socketFlow: Flow[Message, Message, (Consumer.Control, Promise[Option[Message]])] =
    Flow.fromSinkAndSourceMat(sink, kafkaAsSource)(Keep.right)

  private val (upgradeResponse, (draining, _)) =
    Http().singleWebSocketRequest(
      WebSocketRequest(wsSetup.getString("server")),
      socketFlow)

  val create: Future[Either[String, Done]] = upgradeResponse.map { upgrade =>
    // just like a regular http request we can access response status which is available via upgrade.response.status
    // status code 101 (Switching Protocols) indicates that server support WebSockets
    if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
      logger.info("Switching protocols")
      Right(Done)
    } else {
      Left(s"Connection failed: ${upgrade.response.status}")
    }
  }

  sys.addShutdownHook {
    draining.shutdown()
    logger.info("Draining websocket ressource.")
  }

}

The problem here is, if the webserver can not be reached, the actor above gets closed.
The question is, how to figure out, if the webserver is not more available, then the actor should restart and try to connect again.

A: I think your code
private val (upgradeResponse, (draining, _)) =
Http().singleWebSocketRequest(
  WebSocketRequest(wsSetup.getString("server")),
  socketFlow)

has return type
(Future[WebSocketUpgradeResponse], T)

As you are only using upgradeResponse i.e Future[WebSocketUpgradeResponse]
May be you can try rewriting your code using Recover with Retries
So you have to replace your
val create: Future[Either[String, Done]] = upgradeResponse.map { upgrade =>
// just like a regular http request we can access response status which is available via upgrade.response.status
// status code 101 (Switching Protocols) indicates that server support WebSockets
if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
  logger.info("Switching protocols")
  Right(Done)
} else {
  Left(s"Connection failed: ${upgrade.response.status}")
}
}

with
planB = Source.empty
Source.fromFuture(upgradeResponse).recoverWithRetries(3, {
   case ex: RuntimeException => logger.error("Error", ex); planB
}).runWith(Sink.ignore).map {upgrade =>
// just like a regular http request we can access response status which is available via upgrade.response.status
// status code 101 (Switching Protocols) indicates that server support WebSockets
if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
  logger.info("Switching protocols")
  Right(Done)
} else {
  Left(s"Connection failed: ${upgrade.response.status}")
}
}

Here you can add exception handling for the RuntimeException
Please refer https://doc.akka.io/docs/akka/2.5.5/scala/stream/stream-error.html for more details
I hope this will help. Please let me know in case any error.
Thanks


text:
Q: How do I stop Windows XP showing the login screen after a few minutes of inactivity? After leaving Windows XP alone for a few minutes, it shows the user login screen.
I use Windows XP in VMs, so I'd rather switch this feature off.

A: Aha:

*

*Control Panel

*If necessary, "Switch to Classic View"

*Display

*Screen Saver tab

*Uncheck "On resume, display Welcome screen"

Props to Jimmy Greystone on CNET forums.


text:
Q: Why am I having a conflict between two StaticResource on the same control? I have the following markup declared in my control's resources:
<conv:ActionItemToBooleanConverter x:Key="ActionItemToBooleanConverter" />

    <Style TargetType="{x:Type ListBox}">
        <Setter Property="ListBox.ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <RadioButton  Content="Foo2"
                                  GroupName="FOo"
                                  IsChecked="{Binding CurrentProcessPoint, Converter={StaticResource ActionItemToBooleanConverter}, Mode=TwoWay}"
                                  Style="{StaticResource {x:Type ToggleButton}}" />
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>

For the RadioButton, when I introduced the Converter={StaticResource ActionItemToBooleanConverter} on my IsChecked Property it suddenly caused a problem for my Style="{StaticResource {x:Type ToggleButton}}". A blue squiggly appears under the style and says 'The resource {x:Type ToggleButton} could not be resolved'.
Why is this happening? What is it about the introduction of a StaticResource for my Converter that prevents me from Styling my RadioButton as a ToggleButton?
What can I add/fix to resolve the conflict?
Thanks

A: Try to rebuild de project and see what happens.


text:
Q: Hangman game code I would like to get some help regarding the hangman game. I've created this piece of code and have spent a lot of time trying to refine it but I still can't get the correct output. Would really appreciate your help!
word = choose_word(wordlist)
letters = 'abcdefghijklmnopqrstuvwxyz'
numLetters = len(word)
print numLetters

import re

def hangman(word, numLetters):
    print 'Welcome to the game, Hangman!'
    print 'I am thinking of a word that is', numLetters, 'letters long'
    remainingGuesses = 8
    print 'You have', remainingGuesses, 'guesses left.'
    letters = 'abcdefghijklmnopqrstuvwxyz'
    print 'Available letters:', letters
    guess = raw_input("Please guess a letter:")

    def filled_word(wordy, guessy):
        emptyWord = ['_']*numLetters
        if wordy.find(guessy) != -1:
            position = [m.start() for m in re.finditer(guessy, wordy)]
            for x in position:
                emptyWord[x] = guessy
            strWord = ''.join(emptyWord)
            print 'Good guess =', strWord

        else:
            strWord = ''.join(emptyWord)
            print 'Oops! That letter is not in my word:', strWord

    filled_word(word, guess)
    emptyWord =  ['_']*numLetters
    print 'emptyWord =', ['_']*numLetters

    while '_' in emptyWord and remainingGuesses>0:
        remainingGuesses -= 1
        print 'You have', remainingGuesses, 'guesses left'
        letters = 'abcdefghijklmnopqrstuvwxyz'

        def unused_letters(letters):
            letters = 'abcdefghijklmnopqrstuvwxyz'
            unusedLetters = str(list(letters).remove(guess))
            letters = unusedLetters
            return unusedLetters

        letters =  unused_letters(letters)
        print 'Available letters:', letters
        guess = raw_input("Please guess a letter:")

        if word.find(guess) != -1:
            position = [m.start() for m in re.finditer(guess, word)]
            for x in position:
                emptyWord[x] = guess
                strWord = ''.join(emptyWord)
                print 'Good guess ='+strWord
                emptyWord = list(strWord)

        else:
            strWord = ''.join(emptyWord)
            print 'Oops! That letter is not in my word:', strWord

print hangman(word, numLetters)
print '___________'
print 'Congratulations, you won!'

So the problem is that when I run this, the code runs smoothly until from the second guess onwards, I get Available letters = None instead of the specific letters.
Also, the letter I guess which does appear in the word is not stored. i.e. in guess 1, the code returns the word (for example) 'd____', but in guess 2, upon guessing 'e', the code returns the word 'e_' instead of 'd_e__'. Is it because of the assignment of variables? Of local and global variables? Am quite confused about this.
Would really appreciate the help! Thanks a lot! :)

A: def choose_word():
    word = 'alphabeth'
    return {'word':word, 'length':len(word)}

def guess_letter(word_, hidden_word_, no_guesses_, letters_):
    print '---------------------------------------'
    print 'You have', no_guesses_, 'guesses left.'
    print 'Available letters:', letters_

    guess = raw_input("Please guess a letter:")
    guess = guess.lower()

    if guess in letters_:
        letters_ = letters_.replace(guess, '')

        if guess in word_:
            progress = list(hidden_word_)
            character_position = -1
            for character in word_:
                character_position += 1
                if guess == character:
                    progress[character_position] = guess
            hidden_word_ = ''.join(progress)
            print 'Good guess =', hidden_word_
        else:
            print 'Oops! That letter is not in my word:', hidden_word_
            no_guesses_ = no_guesses_ - 1
    else:
        print 'The letter "', guess, '" was already used!'
        no_guesses_ = no_guesses_ - 1

    if hidden_word_ == word_:
        print 'Congratulations, you won!'
        return True
    if no_guesses_ == 0 and hidden_word_ != word_:
        print 'Game over! Try again!'
        return False
    return guess_letter(word_, hidden_word_, no_guesses_, letters_)

def hangman():
    hangman_word = choose_word()
    print 'Welcome to the game, Hangman!'
    print 'I am thinking of a word that is', hangman_word['length'], 'letters long.'

    hidden_word = ''.join(['_'] * hangman_word['length'])
    no_guesses = 8
    letters = 'abcdefghijklmnopqrstuvwxyz'

    guess_letter(hangman_word['word'], hidden_word, no_guesses, letters)

hangman()

A: There are multiple errors in the code. Here it is corrected:-
import re

def unused_letters( letters, guess ): # your main problem is corrected here.
    unusedLetters = list( letters )
    unusedLetters.remove( guess )

    letters = ''.join( unusedLetters )
    return letters

def filled_word( wordy, guessy ):
    if wordy.find( guessy ) != -1:
        position = [m.start() for m in re.finditer( guessy, wordy )]
        for x in position:
            filled_word.emptyWord[x] = guessy
        strWord = ''.join( filled_word.emptyWord )
        print 'Good guess.'
        print 'Current word: %s' % ''.join( filled_word.emptyWord )
    else:
        strWord = ''.join( filled_word.emptyWord )
        print 'Oops! That letter is not in my word:', strWord

def hangman( word, numLetters ):  # you dont need the previous check. Let all be done in the main loop
    print 'Welcome to the game, Hangman!'
    print 'I am thinking of a word that is', numLetters, 'letters long'
    remainingGuesses = 8
    letters = 'abcdefghijklmnopqrstuvwxyz'
    try:
        # # memoizing the current word. for more info, try to understand that functions are
        # # also objects and that we are assigning a new attribute the function object here.
        filled_word.emptyWord
    except:
        filled_word.emptyWord = ['_'] * numLetters
    while '_' in filled_word.emptyWord and remainingGuesses > 0:

        print 'You have', remainingGuesses, 'guesses left'

        print 'Available letters:', letters
        guess = raw_input( "Please guess a letter:" )
#         print 'guess: %s' % guess
        if guess in letters:
            filled_word( word, guess )
            letters = unused_letters( letters, guess )
        else:
            print 'You guessed: %s, which is not in Available letters: %s' % ( guess, ''.join( letters ) )
            print 'Current word: %s' % ''.join( filled_word.emptyWord )

        remainingGuesses -= 1

word = "godman"

print hangman( word, numLetters = len( word ) )
if '_' in filled_word.emptyWord:
    print 'Ahh ! you lost....The hangman is hung'
else:
    print 'Congratulations, you won!'

You can still make it better by checking if the remaining number of guesses are less than the letters to be filled, and take a decision on whether to fail the player or allow it to continue playing.

A: class Hangman():
    def init(self):
        print "Welcome to 'Hangman', are you ready to die?"
        print "(1)Yes, for I am already dead.\n(2)No, get me outta here!"
        user_choice_1 = raw_input("->")
    if user_choice_1 == '1':
        print "Loading nooses, murderers, rapists, thiefs, lunatics..."
        self.start_game()
    elif user_choice_1 == '2':
        print "Bye bye now..."
        exit()
    else:
        print "I'm sorry, I'm hard of hearing, could you repeat that?"
        self.__init__()

def start_game(self):
    print "A crowd begins to gather, they can't wait to see some real"
    print "justice. There's just one thing, you aren't a real criminal."
    print "No, no. You're the wrong time, wrong place type. You may think"
    print "you're dead, but it's not like that at all. Yes, yes. You've"
    print "got a chance to live. All you've gotta do is guess the right"
    print "words and you can live to see another day. But don't get so"
    print "happy yet. If you make 6 wrong guess, YOU'RE TOAST! VAMANOS!"
    self.core_game()

def core_game(self):
    guesses = 0
    letters_used = ""
    the_word = "pizza"
    progress = ["?", "?", "?", "?", "?"]

    while guesses < 6:
        guess = raw_input("Guess a letter ->")

        if guess in the_word and not in letters_used:
            print "As it turns out, your guess was RIGHT!"
            letters_used += "," + guess
            self.hangman_graphic(guesses)
            print "Progress: " + self.progress_updater(guess, the_word, progress)
            print "Letter used: " + letters_used
        elif guess not in the_word and not(in letters_used):
            guesses += 1
            print "Things aren't looking so good, that guess was WRONG!"
            print "Oh man, that crowd is getting happy, I thought you"
            print "wanted to make them mad?"
            letters_used += "," + guess
            self.hangman_graphic(guesses)
            print "Progress: " + "".join(progress)
            print "Letter used: " + letters_used
        else:
            print "That's the wrong letter, you wanna be out here all day?"
            print "Try again!"

def hangman_graphic(self, guesses):
    if guesses == 0:
        print "________      "
        print "|      |      "
        print "|             "
        print "|             "
        print "|             "
        print "|             "
    elif guesses == 1:
        print "________      "
        print "|      |      "
        print "|      0      "
        print "|             "
        print "|             "
        print "|             "
    elif guesses == 2:
        print "________      "
        print "|      |      "
        print "|      0      "
        print "|     /       "
        print "|             "
        print "|             "
    elif guesses == 3:
        print "________      "
        print "|      |      "
        print "|      0      "
        print "|     /|      "
        print "|             "
        print "|             "
    elif guesses == 4:
        print "________      "
        print "|      |      "
        print "|      0      "
        print "|     /|\     "
        print "|             "
        print "|             "
    elif guesses == 5:
        print "________      "
        print "|      |      "
        print "|      0      "
        print "|     /|\     "
        print "|     /       "
        print "|             "
    else:
        print "________      "
        print "|      |      "
        print "|      0      "
        print "|     /|\     "
        print "|     / \     "
        print "|             "
        print "The noose tightens around your neck, and you feel the"
        print "sudden urge to urinate."
        print "GAME OVER!"
        self.__init__()

def progress_updater(self, guess, the_word, progress):
    i = 0
    while i < len(the_word):
        if guess == the_word[i]:
            progress[i] = guess
            i += 1
        else:
            i += 1

    return "".join(progress)

game = Hangman()

A: You can take an idea from my my program. RUN IT FIRST.
import random
# Starter code start
# The variable word is a random word from the text file 'words.txt'
words = list()
with open("words.txt") as f:
    for line in f:
        words.append(line.lower())

word = random.choice(words).strip().upper()
# This is the starter code that chooses a word
# Starter code end
letter = ''
# This is the input of letters the user will type in over and over
word_index = 0
# This is the index for the input correct word to be checked against the correct letters
correct_letters = ''
# This is the variable for the correct letters as a list, once the user types them in and they are deemed correct
correct_letters_index = 0
# This is the index to print the correct letters from, in a while statement below. This gets reset to 0 after every time the letters are printed
incorrect_letters = ''
# This is the variable to hold the incorrect letters in.
lives = 6  # ♥
#  is the variable to hold the 6 lives, printed as hearts in
win_user = 0
# This is the variable that determines if the user wins or not
guessed_letters = ''
# this variable checks for repeated letters (incorrect + correct ones)
while win_user != len(word) and lives != 0:  # 1 mean yes the user have win

    if lives == 6:
        print(
        '''
        |--------------------|
        |                    |
        |
        |
        |
        |
        |
        |
        |
        |
        |
        |
        |
        |
        |
        |_________________________________________
        '''
        )
    elif lives == 5:
        print(
        '''
        |--------------------|
        |                    |
        |                  **|**
        |                 * ()() *
        |                **  ▼   **
        |                ** (---) **
        |                  *****
        |
        |
        |
        |
        |
        |
        |
        |
        |_________________________________________

        '''
        )
    elif lives == 4:
        print(
            '''
            |--------------------|
            |                    |
            |                  **|**
            |                 * ()() *
            |                **  ▼   **
            |                ** (---) **
            |                  *****
            |                    |
            |                    |
            |                    |
            |
            |
            |
            |
            |
            |_________________________________________

            '''
        )
    elif lives == 3:
        print(
            '''
            |--------------------|
            |                    |
            |                  **|**
            |                 * ()() *
            |                **  ▼   **
            |                ** (---) **
            |                  *****
            |                 \  |
            |                  \ |
            |                   \|
            |
            |
            |
            |
            |
            |_________________________________________

            '''
        )
    elif lives == 2:
        print(
            '''
            |--------------------|
            |                    |
            |                  **|**
            |                 * ()() *
            |                **  ▼   **
            |                ** (---) **
            |                  *****
            |                 \  |  /
            |                  \ | /
            |                   \|/
            |
            |
            |
            |
            |
            |_________________________________________

            '''
        )

    elif lives == 1:
        print(
            '''
            |--------------------|
            |                    |
            |                  **|**
            |                 * ()() *
            |                **  ▼   **
            |                ** (---) **
            |                  *****
            |                 \  |  /
            |                  \ | /
            |                   \|/
            |                    |
            |                    |
            |                   /
            |                 /
            |               /
            |_________________________________________

            '''
        )

    # This is the while loop that prints only if the player has remaining lives and has not won yet; It prints the ascii drawing for the hangman with the body parts
    print("Remaining lives:", end=' ')
    for left_lives in range(lives):
        print("♥", end=' ')  # This prints the remaining lives as hearts

    print()

    # labels all correct letters like: cake into _ _ _ _
    while word_index != (len(word)) and word_index <= (len(word) - 1):
        while correct_letters_index != (len(correct_letters)) and word_index <= (len(word) - 1):
            if word[word_index] != correct_letters[correct_letters_index]:
                correct_letters_index += 1
            elif word[word_index] == correct_letters[correct_letters_index]:
                print(word[word_index], end=' ')
                word_index += 1
                correct_letters_index = 0
        if word_index <= (len(word) - 1):
            print("__", end=' ')
            correct_letters_index = 0
            word_index += 1
    print()

    # This goes through the correct word, and prints out the correct letters that have been typed in, in order
    # It also types out the blank spaces for letters

    if win_user != len(word):
        # This asks the user for another letter, and sets the checking value on the correct word back to 0 for the next run through
        letter = str(input("Enter a letter: ")).upper()

        if letter in guessed_letters:
            print("The letter had already been guessed: " + str(letter))

        if letter not in guessed_letters:
            if letter not in word:
                incorrect_letters += letter
                guessed_letters += incorrect_letters
                lives -= 1
            elif letter in word:
                correct_letters += letter
                guessed_letters += correct_letters
                for user_word in word:
                    if letter in user_word:
                        win_user += 1
        # This takes in the letter if it has not previously been deemed in a variable, either correct or not.
        # It also checks if the letter is correct, or not, and adds it to the variable
        # If the letter has already been typed, it will also let the user know that

    word_index = 0

if lives == 0:
    print(
        '''
        |--------------------|
        |                    |
        |                  **|**
        |                 * ()() *
        |                **  ▼   **
        |                ** (---) **
        |                  *****
        |                 \  |  /
        |                  \ | /
        |                   \|/
        |                    |
        |                    |
        |                   /  \\
        |                 /     \\
        |               /        \\
        |_________________________________________

        '''
    )
    # This prints the full hangman, and that the user loses if their lives reach 0
    print("User Looses !!")
    print("Incorrect letters typed: " + str(incorrect_letters))
    print("The word is: " + str(word))

elif win_user == len(word):
    print("The word is: " + str(word))
    # This prints the user wins if all characters are printed out for the correct word
    print("Incorrect letters typed: " + str(incorrect_letters))
    print("User Wins !")
    print(
        '''
        ☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺
        ☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺
        '''
    )


text:
Q: Complete vs General Integral of first order PDE The following is an excerpt from Landau's Course on Theoretical Physics Vol.1 Mechanics:

... we should recall the fact that every first-order partial differential equation has a solution depending on an arbitrary function; such a solution is called the general integral of the equation. In mechanical applications, the general integral of the Hamilton-Jacobi equation is less important than a complete integral, which contains as many independent arbitrary constants as there are independent variables.

Can someone clarify what's a complete integral and what's a general integral of a first order partial differential equation?
Thanks.


text:
Q: how could I change the opacity of a div? I am new in javascript and I am trying to change the opacity of a div and I don't know how to do it, and I didn't find anything online.
here is my code so far:
Javascript
function close_images(){
    document.getElementsByClassName("modificar_imagen").style.opacity="0";
}

HTML

A: document.getElementsByClassName("modificar_imagen") retrieves a HTMLCollection. It would be better to use document.querySelectorAll() so that you can use the forEach() method to iterate over the image collection:
    document.querySelectorAll(".modificar_imagen").forEach(el=>el.style.opacity="0");

That should do it.

function close_images(){
    document.querySelectorAll(".modificar_imagen").forEach(el=>el.style.opacity="0");
}

close_images()


text:
Q: The hierarchy of the type MyInBound is inconsistent when extending MessageInbound For Broadcasting message from server am having servlet extending WebSocketServlet, inside am writing class which extends MessageInbound which results in compile time error in eclipse(hierarchy type inconsistent).
public class MyWebSocketTest extends WebSocketServlet {
    public class MyInBound extends MessageInbound{

     }
}

I suggested to put tomcat-coyote JAR Since Tomcat's WsOutbound has indirect dependency. Eventhough same error existing.


text:
Q: Pass SelectedRows from LWC Datatable to Apex I'm still very new to Salesforce/Apex development but I'm struggling to understand how I would pass the SelectedRows of a datatable through to Apex. I've managed to pass simple data types through on the click of a button but I'm not sure as to what the datatype of the list/array would need to be within Apex. Ideally I would still need to access not only the Id of the SelectedRow but also the data contained within the row. Any help would be greatly appreciated!!
LWC JS
handleConfirm(){
    createNewRec({stringNameType: this.stringNameType, lstSelectedRecords})
    .then(result =>{
        this.result = result;
    })
    .catch(error =>{
        this.error = error;
    })
}

Apex
@AuraEnabled
public static String createNewRec(String stringNameType, List<???>lstSelectedRecords){
    String returnResult = 'something';
    system.debug('stringNameType: ' + stringNameType + ' lstSelectedRecords ' +lstSelectedRecords);
    return returnResult;
}

A: Per documentation:
selectedRows - The data in the rows that are selected.
Standard/Custom Objects
If your datatable displays some kind of Standard or Custom object.
You can pass List<YourStandardObject> or List<YourCustomObject>
@AuraEnabled
public static void createNewRecord(List<Account> selectedRecords) {
    insert selectedRecords;
}

Others
You can always pass List<Map<String, Object>> and do some mapping in Apex.
@AuraEnabled
public static void createNewRecord(List<Map<String, Object>> selectedRecords) {
    // mapping here
    // example
    List<Account> accountsToInsert = new List<Account>();
    for (Map<String, Object> fields : selectedRecords) {
         accountsToInsert.add(
            new Account(
               Name = fields.get('Name')
            )
         );
     }
    insert accountsToInsert;
}


text:
Q: how to add space after the text overflow ellipsis dots(...) and text hi i am using truncate function to cut off my text .
i can get the expected result but needs some styling , not sure how to do it .
current output is :
...texttext
expected output is:
... texttext
i need to add space after those 3 dots before the text. can anyone help with this
i am using  the following code,
   .title{
     font-size: 8pt;
     direction: rtl;
     -webkit-line-clamp: 3;
     -webkit-box-orient: vertical;
     white-space: nowrap;
     overflow: hidden;
     text-overflow: ellipsis;
     font-weight: bold;
     text-indent:2px;
    }

A: Not sure if this could be achieved using pure CSS. However, you could apply some javascript logic to check and put a class like follows:

var p = document.querySelector(".title");

if (p.scrollWidth > p.offsetWidth) p.classList.add("ellipsis");

while (p.scrollWidth > p.offsetWidth) {
  p.innerHTML = p.innerHTML.slice(0, -1);
}
p {
  width: 50px;
  border: 1px solid;
  padding: 2px 5px;
  /* BOTH of the following are required for text-overflow */
  white-space: nowrap;
  overflow: hidden;
}

.ellipsis:after {
  content: " ... "
}
<body>
  <p class="title">
    Testing overflow: look at me ! Testing overflow: look at me !Testing overflow: look at me !
  </p>
</body>


text:
Q: How to customize the UIKeyboard in my app? I want to change the Return button to Go button.
Any suggestions??
Thanks,

A:  *yourtextfieldname*.returnKeyType=UIReturnKeyGo;

A: UITextField and UITextView both follow the UITextInputTraits protocol, which defines a returnKeyType property. Set that to UIReturnKeyGo and you're good to, er, go.