text:
Q: Is there a general form for the 1-sided right inverse? For a matrix $A\in\mathbb{R}^{r\times n}$ of rank $r$ with $r<n$ does there exist a general form for a right-inverse $\bar{A}$ such that $A\bar{A}=I_r$?
The most commonly used inverse I see in the literature is $\bar{A}=A^T\left(AA^T\right)^{-1}$, but clearly $\bar{A}=XA^T\left(AXA^T\right)^{-1}$ for $X$ an arbitrary $n\times n$ matrix would also suffice.
Hence my question is, can all possible right-inverses of a rectangular, real valued matrix $A$ be expressed in this form? Or does there exist another general formulation of right-inverses?

A: The matrix equation $AB=I$ with $B:=[b_1,\ldots,b_r]$ is equivalent to the set of linear systems
$$\tag{1}
Ab_i=e_i,
$$
where $e_i$ is the $i$th column of the $r\times r$ identity. Since $\mathrm{Im}(A^T)\oplus\mathrm{Ker}(A)=\mathbb{R}^n$, we can express $b_i$ as $b_i=A^Tc_i+d_i$, where $c_i\in\mathbb{R}^r$ and $d_i\in\mathrm{Ker}(A)$. Putting this to (1) gives the system for $c_i$:
$$
AA^Tc_i=e_i.
$$
Since $AA^T$ is nonsingular (in fact, positive definite), the system has always as solution. Hence
$$
b_i=A^T(AA^T)^{-1}e_i+d_i
$$
and
$$\tag{2}
B=A^T(AA^T)^{-1}+D,
$$
where $D$ is an arbitrary $n\times r$ matrix such that $AD=0$. With $D=0$, one obtains the Moore-Penrose pseudoinverse.
Note that $I-A^T(AA^T)^{-1}A$ is an orthogonal projector onto $\mathrm{Ker}(A)$. So a $D$ can be expressed also as $D=[I-A^T(AA^T)^{-1}A]Z$, where $Z$ is now an arbitrary $n\times r$ matrix. This turns (2) to
$$
B=A^T(AA^T)^{-1}+[I-A^T(AA^T)^{-1}A]Z=A^T(AA^T)^{-1}(I-AZ)+Z.
$$
Remark: Not all right inverses can be written as $B=XA^T(AXA^T)^{-1}$. You can again add any matrix $D$ such that $AD=0$ to $XA^T(AXA^T)^{-1}$  and obtain a right inverse. In addition, $XA^T(AXA^T)^{-1}$ does not need to be well defined as $AXA^T$ can be singular even if $X$ is nonsingular and $A$ is of rank $r<n$.


text:
Q: Pop up flowing out of a video container I have simple HTML 5 video player, I have a function which opens a pop up when the current time is 0:07s, unfortunately, the pop on a small device flow out of a div.
Problem in graphic:

I want the popup to be centered in inside a video player in all devices like this.

Here is Plunker of what I am trying to do: HTML 5 Video Player
Here is HTML

        <video id="video1" class="video-js vjs-default-skin" controls autoplay="true">
            <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
            Your browser does not support the video tag.

        </video>

Rose Deep Hydration Moisturizer

                        An ultra-hydrating gel cream powered
                        by hyaluronic acid and time-release
                        technology for petal-soft skin.

                        299,00 zł

KUP TERAZ

Here is css I have so far
body{
    background-color: #f0f0f0;
    overflow-x: hidden;
    margin: 0em 0em;
    margin: 0;
    padding: 0;
    border: 0;
    font: inherit;
    vertical-align: baseline;
}

h1, h2, h3, h4, h5, h6{
    margin: 0;
    font-weight: bold;
}

p{
    margin: 0;
}
a{
    text-decoration: none;
}

video{
    width: 1266px;
    height: 100%;
    left: 0px;
    top: 0px;
    margin-left: 0px;
    margin-top: 0px;
}

img{
    float: left;
    margin-right: 25px;
}

.container{
    width: 100%;
    margin: 0px auto;
    overflow: hidden;
    margin-top: 50px;
}

.descArea{
    background-color: #fff;
    box-shadow: 0 0 3px #c8c8c8;
    padding: 15px;
    box-sizing: border-box;
}

/* .videoArea{
    position: relative;
} */
.video-container{
    position: relative;
    height: 100%;
    width: 100%;
    background-color: #000;
    margin:0 auto;
}

.box1{
    position: absolute;
    background-color: rgba(40, 169, 220, 0);
    width: 200px;
    height: 200px;
    top: 50px;
    left: 630px;
    cursor: pointer;
}

.box2{
    position: absolute;
    background-color: rgba(207, 50, 53, 0);
    width: 200px;
    height: 200px;
    top: 70px;
    left: 150px;
    cursor: pointer;
}

.lightbox{
    display: none;
}

.longBtns{
    display: block;
}
.buy-button {
    background-color: #555;
    color: #fff;
    font-size: 2em;
    cursor: pointer;
    width: 182px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    /* right: 10px; */
    /* bottom: 41px; */
}
.product-modal{
    background-color: #f5f5f5;
    font-size: 1.2em;
    width: 65em;
    height: 46.3em;
}
.row-no-padding{
    display: flex;
}

.sku-label-brand{
    font-family: georgia;
    letter-spacing: .2em;
}
.description-text {
    margin-top: 1%;
    line-height: 1.4;
    /* font-size: 1.7em; */
    /* width: 50%; */
    font-size: 24.444px;
    font-family: "Century Gothic";
    color: rgb(0, 0, 0);
    line-height: 1.2;
    text-align: left;
    margin-bottom: 60px;
}
.product-right-col{
    width: 60%;
}
.product-left-col{
    width: 50%;
    margin-right: 45px;
}
#popinMainPic{
    width: 100%;
    height: 100%;
}
.sku-link{
    margin-bottom: 20px;
}
.product-price{
    margin-bottom: 20px;
    font-size: 36px;
    font-family: "Century Gothic";
    color: rgb(0, 0, 0);
    font-weight: bold;
    line-height: 1.2;
    text-align: left;
}
.prodcut-title > h1{
    font-size: 30.556px;
    font-family: "Century Gothic";
    color: rgb(0, 0, 0);
    font-weight: bold;
    line-height: 1.2;
    text-align: left;
    margin-bottom: 14px
}

.vjs-marker{
    width: 6px !important;
    border-radius: 30%;
    background-color: white !important;
    margin-left: -3.5px;
    left: 29.2002%;
    height: 6px !important;
    border-radius: 100px !important;
    bottom: 11px;
    -webkit-border-radius: 100px !important;
    -moz-border-radius: 100px !important;
    -ms-border-radius: 100px !important;
    -o-border-radius: 100px !important;
}

.video-js .vjs-big-play-button {
    display: none !important;
}
.vjs-has-started .vjs-control-bar {

    background: linear-gradient(to bottom,rgba(0,0,0,.1) 0,rgba(0,0,0,.69) 99%,rgba(0,0,0,.7) 100%);
}

.video-js{
    width: 100% !important;
}

.video1-dimensions {
height: 100% !important;
width: 100% !important;
}

.featherlight .featherlight-content{
    transform: scale(0.7);
    -webkit-transform: scale(0.7);
    -moz-transform: scale(0.7);
    -ms-transform: scale(0.7);
    -o-transform: scale(0.7);
}

I have tried to add overflow:hidden to parent div still the same.
What is wrong with my code? any idea or help will be apreciated.

A: featherlight basically provides you a window sized popup that has position: fixed and is set to be placed at center horizontally and vertically. If you look at the CSS of featherlight, then you'll see it has top: 0; bottom: 0; left: 0; right: 0;. This is the intended behaviour of this plugin.

Moreover, the way this plugin works is by cloning your modal content to its own div and then displaying it. Hence giving you little less control over its positioning.

To override this behaviour, you need to manually calculate top, left and height of the video and then apply this to .featherlight by javascript. This would force the featherlight modal to be displayed over the video only irrespective of the the device width/height.

Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# ASP.NET Middleware read Request Stream I´ve got a Middleware for my ASP.NET WebApi, which should Log the Request in case its something we cannot work with. There for I´ve invented the following Attribute to declare which Methods uses the Middleware:
public class UseMiddlewareAttribute : Attribute
{
    public Type MiddlewareType { get; }

    public UseMiddlewareAttribute(Type middlewareType)
    {
        MiddlewareType = middlewareType;
    }
}

And a example controller:
[HttpPost]
[DisableRequestSizeLimit]
[UseMiddleware(typeof(PlausibilityMiddleware))]
public async Task<ActionResult> ImportPersonsAsync(List<Person> persons)
{
    return Ok(persons);
}

And here the middleware:
internal class PlausibilityMiddleware
{
    #region Fields

    private static readonly Logger Log = LogManager.GetCurrentClassLogger();

    private readonly RequestDelegate _next;
    private readonly IServiceProvider _provider;

    #endregion

    #region Constructor

    public PlausibilityMiddleware(RequestDelegate next, IServiceProvider provider)
    {
        _next = next;
        _provider = provider;
    }

    #endregion

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            if (!CanProcess(context))
            {
                await _next(context);
                return;
            }

            var requestBody = DoSomeMagic();
            Log.Trace(requestBody);

        }
        catch (Exception ex)
        {
            // do not skip _next(context) ---> This method calls the Controller behind
            Log.Error("Unknown error occured while validate pre import");
            Log.Error(ex);
        }

        await _next(context);
    }

    private bool CanProcess(HttpContext context)
    {
        var endpoint = context.Features.Get<IEndpointFeature>()?.Endpoint;
        var attribute = endpoint?.Metadata.GetMetadata<UseMiddlewareAttribute>();

        return attribute != null && attribute.MiddlewareType.Equals(GetType());
    }

Firstly the context.Features.Get<IEndpointFeature>()?.Endpoint returns null, so I cannot access the attributes, also I don´t know how to read Request-Body.

A: To access the given Attribute I needed to configure the app, it´s neccessary to Add the Middleware between UseRouting and UseEndpoint:
            app
            .UseRouting()
            .UseMiddleware<PlausibilityMiddleware>()
            .UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            })

To read the Request-Body I need to EnableBuffering and use a StreamReader. But then the StreamReader disposes the underlying Stream, so the Controller cannot access the Stream anymore. You can use CopyTo and use another MemoryStream but that is overhead. StreamReader has a Consturctor parameter leaveOpen finaly:
    private static async Task<string> DoSomeMagic(HttpContext context)
    {
        context.Request.EnableBuffering();

        using var reader = new StreamReader(context.Request.Body, leaveOpen: true);

        var result = await reader.ReadToEndAsync();
        context.Request.Body.Position = 0;

        return result;
    }

Also its nice to know you cannot access the stream as synchronously read ReadToEnd() if you want to, you need to set AllowSynchronousIO = true
    var syncIOFeature = httpContext.Features.Get<IHttpBodyControlFeature>();
    if (syncIOFeature is not null)
        syncIOFeature.AllowSynchronousIO = true;

Then you can ReadToEnd as Synchronously method.


text:
Q: Convert ls Output Into an Array I want to put the output of an ls into an array so I can loop through it and eventually use a entry the user will specify.
What I did is the following
SETUPS="$(ls)"
IFS=$' ' read -rd '' setup <<<"$SETUPS"

when I run echo $setup[0] it will already show me all the files that are present
while I should be able to run echo $setup[0] and only get the first entry.
Could anyone tell me what I'm doing wrong here?
I already tried SETUPS="$(ls -1)" to seperate it with IFS=$'\n' read -rd '' setup <<<"$SETUPS" but that didn't work either.
Right now I'm looping through it like this
n=0
for i in `echo ${setup} | tr "," " "`
   do
   n=$((n+1))
   echo $n". $i"
done

which works to echo every entry with a number in front of it but I can't possibly select an entry out of there since every value seems to be stored as 1 value

A: If you want to get all the files in this directory in an array you can use globbing:
files=(*)
printf '%s\n' "${files[@]}"

will store all the files matched by the glob in the array files and then you can print them with printf if you so desire, or do whatever else you want with looping over the array.
n=0
for current in "${files[@]}"; do
    n=((n+1))
    printf '%s %s\n' "$n" "$current"
done

You don't even need to store it in an array in the middle if you don't need it for some other purpose:
for current in *; do

works just fine

A: See, why not parse output of ls, but rather use a proper while loop with process-substitution (<()).
#!/bin/bash

while IFS= read -r -d '' file
do
    printf "%s\n" "${file#*/}"
done < <(find . -maxdepth 1 -mindepth 1 -type f -print0)

(or) if you are interested in storing the folder contents in an array
fileContents=()
while IFS= read -r -d '' file
do
    fileContents+=("${file#*/}")
done < <(find . -maxdepth 1 -mindepth 1 -type f -print0)

printf "%s\n" "${fileContents[@]}"


text:
Q: Admobs interstitial ad won't show iOS So, I had the interstitial ads working fine by following the code on the Admob website and then recently I updated my pods and with it the GoogleAdMob SDK.
Now when my interstitial Ad should present, nothing happens and in the console I have this error:
<GoogleThe provided view controller is not being presented.
[ProcessSuspension] 0x110adfbd0 - ProcessAssertion::processAssertionWasInvalidated()
Here is my code:
extension FirstViewController: GADInterstitialDelegate {

    func showInterstitialAd() {
        if interstitial.isReady {
            interstitial.present(fromRootViewController: self)
          } else {
            print("Ad wasn't ready")
          }
    }

    func createAndLoadInterstitial() -> GADInterstitial {
        var interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
        interstitial.delegate = self
        interstitial.load(GADRequest())
        return interstitial
    }

    func interstitialDidDismissScreen(_ ad: GADInterstitial) {
        interstitial = createAndLoadInterstitial()
    }

}

In viewDidLoad I call:
func setUpInterstitial() {

        interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
        interstitial.delegate = self

        let request = GADRequest()
        interstitial.load(request)
    }

and in ViewWillAppear
if InterstitialAd.counter >= 3 { self.showInterstitialAd(); InterstitialAd.counter = 0}

The intended logic is every 3 times a user views a page, namely FirstViewController, an interstitial ad shows.
Thank you in advance :)

A: You can update your code like below:
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    if InterstitialAd.counter >= 3 {
        self.showInterstitialAd();
        InterstitialAd.counter = 0
    }
}

Remove your code from viewWillAppear.


text:
Q: what is wrong in my searching in object ArrayList by a String?
*

*What's wrong with the searchStudent method that returns 0 every time?
int searchStudent(String target)Finds and gives the desired index by name.
import java.util.ArrayList;
class Student {
String name;
double gpa;

public Student(String name, double gpa) {
    this.name = name;
    this.gpa = gpa;
}

public String getName() {
    return name;
}

}
public class StackOverflow {
static ArrayList<Student> stu = new ArrayList<>();

public static void main(String[] args) {
    stu.add(new Student("Hadi", 2.3));  // <-- every time shows 'Hadi'
    stu.add(new Student("Jack", 1.8));
    stu.add(new Student("Sara", 4.6));

    System.out.println("----- Searching For A Student -----");
    int recurse = searchStudent("Jack");
    if (recurse == -1) {
        System.out.println("There is no Student with this name !!");
    } else {                       //if 'Jack' was in List show his name
        System.out.println(getStudent(recurse).getName());
    }
}

public static int searchStudent(String target) {
    int indexTarget = -1;
    for (Student z : stu) {
        if (z.getName() != null && z.getName().contains(target)) {
            indexTarget = z.getName().indexOf(target);
        }
    }
    return indexTarget;
}

public static Student getStudent(int index) {
    return stu.get(index);
}

}

A: tl;dr
Your searchStudent method is confusing (a) the index number returned by String::indexOf with (b) needing to keep a running tally of hits found.
I suggest you write out the search method's algorithm in plain prose, then compare to your code.
Index 0 means match at front of string
The method String::indexOf returns an index (a zero-based position number) indicating the first position where your desired target string was found. For more about index-counting, see Wikipedia: Zero-based numbering.
When calling String::indexOf, a resulting index of zero (0) means your target is being found at beginning of the string under examination. For example, you are doing the equivalent of looking for Bob in the name Bobby (or in Bob for that matter).
String name = "Bobby" ;
String target = "Bob" ;
int index_Bob = name.indexOf( target ) ;
System.out.println( "index_Bob: " + index_Bob ) ;

index_Bob: 0

When calling String::indexOf, a resulting index of negative one (-1) means your target was not found, is not contained in the string.
String name = "Bobby" ;
String target = "Xyz" ;
int index_Xyz = name.indexOf( target ) ;
System.out.println( "index_Xyz: " + index_Xyz ) ;

index_Xyz: -1

Look for by in Bobby, and we get a result of 3 (the index for the 4th letter).
int index_by = name.indexOf( "by" ) ;
System.out.println( "index_by: " + index_by ) ;

index_by: 3

See this code run live at IdeOne.com.
Count
If you are trying to get a count of any "contains" test succeeding, and you don't really care where the target matched, just that it did match, then there is no need to call indexOf at all.
Change this:
        count = z.getName().indexOf(target);

… to this:
        count = ( count + 1 ) ;  // Increment the count of matches.

Stream
By the way, an advanced way to get the count is to use a Stream (see Tutorial). See my example code below.
I don't have your Student class, so I am just using String here. You would change it ( Student student ) -> student.getName().contains( "Bob" ) for your code.
    List< String > names = List.of(
        "Alice", "Bobby", "Bobette" , "Carol"
    );

    long countBobs =
        names
        .stream()
        .filter(
            ( String name ) -> name.contains( "Bob" )
        )
        .count()
    ;

See this code run live at IdeOne.com.

countBobs: 2


text:
Q: How to switch onclick button function using JS I would like to make a PLAY/PAUSE button to responsive-voice.js lib. It will start reading after clicking PLAY and change button label on PAUSE When again I will click this button it will of course pause and change the label on RESUME. After click RESUME it will continue reading the text from PHP. Right now my script not working.
<input id=playsound; onclick='changeState("<?php echo $step[' description ']; ?>");' type='button' value='PLAY' />

                            <script>
                                function changeState(tekst) {

                                    var buttonvalue = document.getElementById('playsound').value;
                                    switch (buttonvalue) {
                                        case "PLAY":
                                            document.getElementById('playsound').value = "PAUSE";
                                            document.getElementById('playsound').onclick = responsiveVoice.speak(tekst, "Polish Female");
                                            break;

                                        case "PAUSE":
                                            document.getElementById('playsound').value = "PLAY";
                                            document.getElementById('playsound').onclick = responsiveVoice.pause();
                                            break;

                                    }
                                }

                            </script>

A: document.getElementById('playsound').onclick = responsiveVoice.speak(tekst, "Polish Female");

On this line you are changing element's onclick property to speak function. So next time you will click the button it will execute this speak function.
document.getElementById('playsound').onclick = responsiveVoice.pause();

This line is also doing the same thing (changing onclick property).
Instead what you would like to do is call the functions like this. So every time you click just just the value property of element is changed and not onclick property.
switch (buttonvalue) {
   case "PLAY":
      document.getElementById('playsound').value = "PAUSE";
      responsiveVoice.speak(tekst, "Polish Female"); // call speak function
      break;

   case "PAUSE":
      document.getElementById('playsound').value = "PLAY";
      responsiveVoice.pause(); // call pause function
      break;
}

You would like to read more about events and addEventListener method on MDN.
Edit
Apparently you missed some quotes around id attribute's value(i.e. playsound) in html. That's why no element was selected.

A: hope can help you.
This is a short-way to do that and i think can help you some 'flag' to check the current state of your application.
Basic HTML
<input id="playsound" onclick='changeState()' type='button' value='PLAY' />

Relative JS
var states = ["PLAY","PAUSE"], // your possible states
                        current_state = 0; // your flag

                            function changeState() {
                              current_state=!current_state; // switch
                              document.getElementById('playsound').value=states[current_state?1:0]; // write your state
                            }


text:
Q: why this code isn't working in real-time pleace cheack this code this code isn't working in real-time.. it works only whenever I restart/refresh the app. I am using Cloud Firestore. plzz change code am noob help me. & sorry For My bad English
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 public class Category_List_Activity extends BaseActivity {

        List<CardModel> list = new ArrayList<>();
        RecyclerView recyclerView;
        RecyclerAdapter adapter;
        android.app.AlertDialog dialog;
        private static final String TAG = "CategoryListActivity";
        FirebaseFirestore db;
        String name, id,node,lastid,time;
        boolean islast;
        SessionManager sessionManager;
        LinearLayout banner;
        private InterstitialAd interstitial;
        TextView settitel;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.category_list);
            FirebaseApp.initializeApp(this);
            db = FirebaseFirestore.getInstance();
            Bundle bundle = getIntent().getExtras();
            banner = findViewById(R.id.banner_bottom_main);
            sessionManager=new SessionManager(this);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);

            StartAppAd.showAd(this);

            new AdsHelper().createBanner(this, banner, sessionManager.getBanner());

            if (bundle != null) {
                name = bundle.getString("name");
                id = bundle.getString("id");
                lastid = bundle.getString("lastid");
                node=bundle.getString("node");
                islast=bundle.getBoolean("islast");
            }
    ///////////////////////////Action bar custiom//////////////////////////////////////////
            ImageView imgFavorite = (ImageView) findViewById(R.id.previous);
            imgFavorite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });

            ImageView imgFavorsite = (ImageView) findViewById(R.id.refrashing);
            imgFavorsite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getData();
                }
            });

            settitel = findViewById(R.id.event_name);
            settitel.setText(name);
    ///////////////////////Action bar custiom end///////////////////////

            recyclerView = findViewById(R.id.rec);
            adapter = new RecyclerAdapter(list, this);
            recyclerView.setHasFixedSize(true);
            AutoFitGridLayoutManager layoutManager = new AutoFitGridLayoutManager(this, 10000);
            recyclerView.setLayoutManager(layoutManager);
    //        recyclerView.setLayoutManager(new GridLayoutManager(this,1));

            recyclerView.setAdapter(adapter);

            getData();

            if(isCastApiAvailable()) {
                castContext = CastContext.getSharedInstance(this);
                if (castContext.getCastState() == CastState.CONNECTED) {
                    findViewById(R.id.castMiniController).setVisibility(View.VISIBLE);
                }else{
                    findViewById(R.id.castMiniController).setVisibility(View.GONE);
                }
            }else{
                findViewById(R.id.castMiniController).setVisibility(View.GONE);
            }

        }

        CastContext castContext;

        @Override
        protected void onResume() {
            super.onResume();

            try {
                if (HelperClass.vpn(this)) {
                    finish();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }

        @Override
        public boolean onCreateOptionsMenu(@NonNull Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(@NonNull MenuItem item) {
            if(item.getItemId() == R.id.refrish){
                getData();
                return true;
            }

            else if (item.getItemId() == android.R.id.home) {
                onBackPressed();
            }

            return super.onOptionsItemSelected(item);
        }

    //    @Override
    //    public boolean onOptionsItemSelected(MenuItem item) {
    //
    //        if (item.getItemId() == android.R.id.home) {
    //            onBackPressed();
    //        }
    //
    //        return true;
    //    }

        //////////////////sports diglo start///////////////
        @Override
        public void onDestroy() {
            dismissProgressDialog();
            super.onDestroy();
        }
        private void showProgressDialog() {
            if (dialog == null) {
                dialog = new SpotsDialog.Builder().setContext(this).build();
                dialog.setMessage("Please wait...");
                dialog.setCancelable(false);
            }
            dialog.show();
        }

        private void dismissProgressDialog() {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    //////////////////sports diglo end///////////////

        private void getData() {
            showProgressDialog();
            Query query;
            if (islast) {
                query = db.collection(node)
                        .document(lastid)
                        .collection("list")
                        .document(id)
                        .collection("list");
            } else {
                query = db.collection(node)
                        .document(id)
                        .collection("list");
            }

            query.get()
                    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            dismissProgressDialog();
                            if (task.isSuccessful()) {

                                list.clear();
                                int i = 0;
                                boolean match = false;
                                try {
                                    for (DocumentSnapshot snapshot : task.getResult().getDocuments()) {
                                        CardModel mainModel = snapshot.toObject(CardModel.class);
                                        mainModel.setId(snapshot.getId());
                                        if (mainModel.enable) {
                                            boolean onOff=mainModel.cOnOff;
                                            if (mainModel.countries != null
                                                    && mainModel.countries.size() > 0) {
                                                if (!sessionManager.getLocation().isEmpty()) {
                                                    if(onOff) {
                                                        if (mainModel.countries.contains(sessionManager.getLocation())) {
                                                            match = true;
                                                            list.add(mainModel);
                                                        } else {
                                                            list.remove(mainModel);
                                                        }

                                                    }else{
                                                        if (mainModel.countries.contains(sessionManager.getLocation())) {
                                                            match = true;
                                                            list.remove(mainModel);
                                                        } else {
                                                            list.add(mainModel);
                                                        }
                                                    }
                                                } else {
                                                    list.add(mainModel);
                                                }
                                            } else {
                                                list.add(mainModel);
                                            }
                                        } else {
                                            list.remove(mainModel);
                                        }
                                        Log.d("view imgs", "data is " + mainModel.toString());

                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                adapter.notifyDataSetChanged();

                            }
                            adapter.notifyDataSetChanged();
                            dismissProgressDialog();
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                          dismissProgressDialog();
                            Toast.makeText(Category_List_Activity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    })
            ;
        }

    }


text:
Q: Paso automatico de input me encuentro con el desarrollo de un proyecto en JavaScript, HTML y CSS, y tengo una duda. Os comento, estoy utilizando Materialize, y tengo una serie de inputs, los cuales necesito que se pasen automáticamente de uno a otro, una vez que se escribe en ellos, las posibles respuestas que se escribe son caracteres sueltos y la palabra "NADA" . Por ejemplo: La casa es _erde y hay una _aca.(Siendo _ un input), si contesto el primero, se debería pasar automáticamente al siguiente input, estando este input en vacio y dando la posibilidad de escribir sobre él. Para contestar pongo en el valor de los inputs el valor que haya en los tags NFC document.activeElement.value=valor;, por tanto la escritura no se hace por teclado, así que descartamos keyup. El código es el siguiente:
mostrarEjercicio:function (nombreEjercicio,textoEjercicio){
  var text=textoEjercicio;
  var textSeparado=textoEjercicio.split("@");
  var nInput=textSeparado.length-1;
  var idInput=0;

  for (var i=0;i<text.length;i++){
  // Genero inputs
    if(text.charAt(i)=="@"){
      var inputN='<input id="'+idInput+'" type="text" readonly>'
      text = text.replace("@", inputN);
      idInput++;
    }
  }

  var cadena = '

'+ nombreEjercicio +'

'+ text + '

';
  cadena=cadena+'
';
  cadena=cadena+'<button id="verBorradorBtn" class="btn waves-effect waves-light" type="submit">Ver borradoredit</button> ';
  cadena=cadena+'

';
  $('#messageDiv').append(cadena);

},

Gracias por la ayuda de antemano.

A: Creo que estás buscando hacer esto:

$(':input').keyup(function(){
  $(this).next().focus();
});

<input type="text" id="input1">
<input type="text" id="input2">
<input type="text" id="input3">
<input type="text" id="input4">
<input type="text" id="input5">
<input type="text" id="input6">

Si no es así, comentanos.


text:
Q: Reverse(s) function (I can't speak English very well, so I'm sorry for my mistakes)
I'm learning C language, (I'm reading The C Programming Language, second edition). I can't complete exercise 4-13:

Write a recursive version of the function reverse (s), which
  reverses the string s in place.

I have to create this function without using pointers or things that I haven't studied yet.
This is my code:
void reverse(char s[])
{
     int c;
     static int i, k;
     i = 0;
     k = 0;
     if ((c = s[i]) != '\0')
     {
          i++;
          reverse(s);
     }
     if (c != '\0')
          s[k++] = c;
}

but it doesn't work. Could you help me, please?

A: You are resetting values of "i" and "j" to zero in the function.
static variables are initialized only once in the declaration statement.
Initialize the variables like this :
static int i=0, k=0;

You can also do away with initializing static variables to 0 as it would be done automatically. But it is a good programming practice to initialize variables during declaration.

A: See @vikas answer, however, that will work only one time as to reverse a second string, i and k must be reset again. The following does that:
static int i, k;
void reverse(char s[]);

int main(void)
{
    char s[]="hello world";

    i= k= 0;
    reverse(s);

    return 0;
}

void reverse(char s[])
{
     int c;
     if ((c = s[i]) != '\0')
     {
          i++;
          reverse(s);
     }
     if (c != '\0')
          s[k++] = c;
}

A: Using recursive algorithms in C is a bad idea(with few exceptions,of course) because of the space cost and the poor performance when the compared to the equivalent iterative versions. That said,here's my recursive implementation of reverse(s):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void reverse(char s[],const size_t start,const size_t end);

int main(void)
{
    char s[] = "C is a great programming language";
    reverse(s,0,strlen(s) - 1);
    printf("Reversed string: %s\n",s);
    return EXIT_SUCCESS;
}

static void reverse(char s[],const size_t start,const size_t end)
{
    if(start < end && NULL != s)
    {
        char tmp = s[end];
        s[end] = s[start];
        s[start] = tmp;
        reverse(s,start + 1,end - 1);
    }
}

PS: sorry for my bad english,i'm not a native speaker.


text:
Q: Eclipse "Run as" does not show "Run as TestNg" option with TestNg installed & all relevant jar files I have Windows 8.1 64 Bit in my laptop and I have installed Eclipse Mars R-win32-X86-64 and jdk-8u71-windowsX64.
Now when I am trying to run simple selenium code ,"Run as" does not show a "Run as TestNg" option. I have already added TestNg  and all relevant jar files in my code.
What can I do to fix this?
My code is below:
package newpkg;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.Random;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Google {

    WebDriver driver = new FirefoxDriver();
    String baseurl = "https://www.google.co.in/";

    @BeforeTest
    public void initial() {

        driver.get(baseurl);

    }

    @Test
    public void test() {
        driver.findElement(By.xpath("//*[@id='gs_htif0']")).sendKeys("Facebook");
        driver.findElement(By.xpath("//*[@id='sblsbb']")).click();

    }
}

I have added TestNG plugin but on running it is showing following errors:

-Unknown option: -serport Usage: [-d output-directory] default output directory to : test-output [-testclass list of .class files or list of class names] [-sourcedir a source directory] [-annotations javadoc or JDK] Specifies the default annotation type to be used in suites when none is explicitly specified. This version of TestNG (15) supports both "javadoc" and "JDK" annotation types. [-groups comma-separated list of group names to be run] works only with -testclass

Edit:
I have installed from this link and now Run as > Run as TestNG option is shown. But with error in console which I have posted above and Firefox driver cannot be launched.
Edit2:
No longer getting the above errors, but am now getting:

eclipse.buildId=4.5.0.I20150603-2000 java.version=1.8.0_71 java.vendor=Oracle Corporation BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US Framework arguments: -product org.eclipse.epp.package.jee.product Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product org.eclipse.epp.logging.aeri.ui Warning Sat Feb 20 00:32:02 PST 2016 The notification timed out Version: 1.0.0.v20150617-0732 org.eclipse.epp.internal.logging.aeri.ui.l10n.Logs$LogTraceException at org.eclipse.epp.internal.logging.aeri.ui.l10n.Logs$LogTraceException

A: If the TestNG JARs are installed, you will be able to use all the annotations. But to run as TestNG, the plugin needs to be installed from Eclipse Market Place.

A: Try installing testng plugin from eclipse market place..


text:
Q: C# DBF File default ordering I need to write records to a DBF file in C# (which is working fine) but the requirement is that when the user opens the resulting dbf file, the records are sorted according the values in one of the columns. I have accomplished this with other formats by simply setting the column as the primary key. However, I am unable to create a primary key, as I get the the error ("not supported for non-dbc"). Is there any other way I can achieve the "sorting"?

A: Data being stored in a DBF or any other database is NOT ever stored sequentially but utilize indexes and ORDER BY clauses when retrieving data.  So, I would just worry about your query when RETRIEVING the data to include as such...
select * from whateverTable order by Column1, Column8, Column20
(or whatever columns are of concern)
Then, it doesn't matter WHAT order they are actually entered....

A: For free DBF files, you will need to write the records in the order you wish for them to appear.
Note: I know your comment above says you are doing this, but this is the answer. If you don't tell us and/or show us how you are writing out to the table, we can't help any further.

A: Tables that aren't in a database ("free tables" in foxpro nomenclature) support Candidate indexes:

Similar to a primary index, a
  candidate index contains an index key
  for each record in a table and
  prohibits duplicate values in the
  fields or index expression specified
  for generating index keys.


text:
Q: ionic typescript installation ubuntu I installed ionic and cordova.
I created the ionic project

ionic start myapp blank

I added gulp-tsc on my project

npm install gulp-tsc

I edited gulpfile.js at the root of the ionic project :

var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var sh = require('shelljs');
var typescript = require('gulp-tsc');

var paths = {
  sass: ['./scss/**/*.scss']
  typescript: ['./www/scripts/**/*.ts']
};

gulp.task('default', ['sass', 'compile']);

function compileTypeScript(done) {
 gulp.src(paths.typescript)
 .pipe(typescript({ sourcemap: true, out: 'tslib.js', sourceRoot: '../scripts' }))
 .pipe(gulp.dest('./www/js/'))
 .on('end', done);
}

gulp.task('compile', compileTypeScript);

gulp.task('sass', function(done) {
  gulp.src('./scss/ionic.app.scss')
    .pipe(sass({
      errLogToConsole: true
    }))
    .pipe(gulp.dest('./www/css/'))
    .pipe(minifyCss({
      keepSpecialComments: 0
    }))
    .pipe(rename({ extname: '.min.css' }))
    .pipe(gulp.dest('./www/css/'))
    .on('end', done);
});

gulp.task('watch', function() {
  compileTypeScript();
  gulp.watch(paths.sass, ['sass']);
  gulp.watch(paths.typescript, ['compile']);
});

gulp.task('install', ['git-check'], function() {
  return bower.commands.install()
    .on('log', function(data) {
      gutil.log('bower', gutil.colors.cyan(data.id), data.message);
    });
});

gulp.task('git-check', function(done) {
  if (!sh.which('git')) {
    console.log(
      '  ' + gutil.colors.red('Git is not installed.'),
      '\n  Git, the version control system, is required to download Ionic.',
      '\n  Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
      '\n  Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
    );
    process.exit(1);
  }
  done();
});

I added a simple ts file on www/scripts folder (a class), and when I run ionic serve, tslib.js is not generated. I don't have any error.
What I missed to do to generate the js file from ts files ?
Thanks.

A: You may try this example:https://github.com/anchann/angularjs-typescript-e2e.
You have to have a separate grunt task running that watches your .ts files and compiles them into the tslib.js.

A: Some times the dependency does not install in the same, what happens, when you install ionic then typescript automatically install as a dependency,
I suggest you run this command to install manually typescript dependency.
sudo npm install -g typescript


text:
Q: Restructuring/stacking columns with duplicate ID in r data frames I have looked already on the forum and there are some similar questions, but each time slightly different. Therefore I decided to post a new one. I just can't figure this out.
Consider I have these data
   id score
1  1     3
2  1     6
3  2     2
4  2     4
5  2     3
6  3     9
7  3     2

And I want it to look like this:
  id     score
1  1     3, 6
2  2     2, 3, 4
3  3     2, 9

Suggestions are very welcome! Thank you in advance.

A: aggregate() can do that:
df <- read.table(header=TRUE, text=
'   id score
1  1     3
2  1     6
3  2     2
4  2     4
5  2     3
6  3     9
7  3     2')

aggregate(score ~ id, data=df, FUN=paste0)
# > aggregate(score ~ id, data=df, FUN=paste0)
#   id   score
# 1  1    3, 6
# 2  2 2, 4, 3
# 3  3    9, 2


text:
Q: adb shell: cannot copy files: Read-only file system I have rooted my nexus-7 and everything is working smooth except that I am enable to copy files:
./sdcard# cp myfile.conf /etc/.

or create folders:
.# mkdir usr

within the root folder.
Searching on the internet, nothing seems to be working .. I tried to change the chmod, but it show me this:
Read-only file system

so, I tried to mount /myfile.conf and make it read/write as follow:
adb shell
su
mount -o remount,rw /sdcard/myfile.conf

but it gives me:
Usage: mount [-r] [-w] [-o options] [-t type] device directory

I am browsing and doing everything on my tablet through the ADB from my PC .. so am I doing something wrong .. or am I missing anything ?


text:
Q: GPGError using DejaDub I perform a DejaDub backup of my home directory every week and this has worked without problems for years now. I upgraded to 20.04 several months ago and the backups continued to work until this week. I perform regular software updates and so suspect one of those has broken DejaDup. This week each time I try and do a backup I get this message:
GPGError: GPG Failed, see log below:
===== Begin GnuPG log =====
gpg: AES256 encrypted data
gpg: encrypted with 1 passphrase
gpg: decryption failed: Bad session key
===== End GnuPG log =====

I found this suggestion to fix the problem https://superuser.com/questions/984977/duplicity-restore-failing-no-secret-key but it suggests making changes to ~/.gnupg/gpg.conf and ~/.gnupg/gpg-agent.conf but neither of those files are in my ~/.gnupg directory.
How to repair my DejaDub backup app?

A: I fixed this by making a new directory and setting DejaDub to save the backups there. DejaDup then asked me for a new password, asked for confirmation and then performed a first backup.
I don't know if this is a proper fix or why the old directory stopped working. The folder for GnuPG-Keys under "Passwords and Keys" is empty. (before and after the new backup). I will play around a little with restoring from the older backups to see if they still work.


text:
Q: How to install Python and PostgreSQL on CentOS I have a dedicated server running centOS.
I want to install python 2.6 and postgreSQL on it so python users can host their web apps on my server. (Apache)
Can anyone give me a detailed tutorial for that ?
And is Django or something similar necessary to run python with Apache ??

A: (I don't use either python or PostgreSQL, but perhaps this will point you in the right direction)
On CentOS,
install  mod_python with yum install mod_python (if you want it embedded in Apache). You will need to configure Apache, see HowtoForge: embedding python
install python with yum install python26 (if you want to go the CGI route, or run standalone scripts)
install PostgreSQL with yum install postgresql-server (will automatically install the client)
I believe Django is a framework - in which case it is not required. The users who want to use it will provide it as part of their code.
Hope this helps.
Edit: As per the comment below, it does appear that mod_wsgi is preferred over mod_python.
It can be installed via yum install mod_wsgi
If you need to compile mod_wsgi, there are instructions here. You can also find RPMs compiled against python 3.1.
If python is already on your system, run  python --version to determine the version. If it is an older version, and you compile from source, this article provides a procedure at the start (for not overwriting the existing python).
If you don't have an up-to-date python in your yum repository, you can try EPEL, which has python26-2.6.5-6


text:
Q: How to establish output connection to Oracle server by Log Parser query? I am trying to execute a Log parser query through command prompt whose output is supposed to be stored into an Oracle table.
I have tried and achieved to do so when using SQL Server, with the following code:
logparser -i:TEXTLINE  "Select  LogFilename as LogFile, substr(text, 0, 23) as col1 INTO LOG_ERROR_TABLE  from C:\temp\ErrorLog*" -o:sql -server:localhost -database:MyDB1 -username:Max -password:password

But When trying to execute the below query in Oracle server , I am getting :
logparser -i:TEXTLINE  "Select  LogFilename as LogFile, substr(text, 0, 23) as col1 INTO LOG_ERROR_TABLE  from C:\temp\ErrorLog*" -o:SQL -oConnString:"Driver={Oracle in OraDB18Home1};Server=OracleServerName;Uid=Max;Pwd=password;"

I saw plenty of other ODBC drivers installed in the server but I am not sure which one to use(if that's where I am going wrong)
The version of Oracle installed is: 18.0.0.0.0 on Windows Server 2016.


text:
Q: Why do I get the error "unexpected end of string while parsing JSON string" when decoding a URI-encoded JSON string? I'm trying to POST some JSON data to my Perl script, but the JSON module seems to be unable to cope with this string:
[{"":"#","jednostka":"","login":"SA"}]

I used encodeURIComponent() in JavaScript, so my string actually looks like this:
[{%22%22:%22#%22,%22jednostka%22:%22%22,%22login%22:%22SA%22}]

Error log:
JSON::PP::decode_error('unexpected end of string while parsing JSON string') called at C:\strawberry\perl\lib/JSON/PP.pm line 837
|   JSON::PP::string() called at C:\strawberry\perl\lib/JSON/PP.pm line 960
|   JSON::PP::object() called at C:\strawberry\perl\lib/JSON/PP.pm line 724
|   JSON::PP::value() called at C:\strawberry\perl\lib/JSON/PP.pm line 907
|   JSON::PP::array() called at C:\strawberry\perl\lib/JSON/PP.pm line 725
|   JSON::PP::value() called at C:\strawberry\perl\lib/JSON/PP.pm line 688
|   JSON::PP::PP_decode_json('JSON::PP=HASH(0xd0c2534)', '[{%22%22:%22#%22,%22jednostka%22:%22%22,%22login%22:%22SA%22}]', 0) called at C:\strawberry\perl\lib/JSON/PP.pm line 148

A: Do you realise that you ned to escape the data only for GET requests? That's why the function is called encodeURIComponent, because the resulting string is for use within a URL. In POST requests the data is passed in the message body, not in the URL
I see that you're using the JSON::PP module, which works fine with the simple JSON string that you show. Here's an example program that shows the resulting data structure dumped using Data::Dump
Acccording to the error log you're encoding the JSON data when you shouldn't be. If I replace the JSON data below with encodeURIComponent then I get the error message

unexpected end of string while parsing JSON string, at character offset 3 (before "22%22:%22#%22,%22jed...")

which is as you described, and what the error log confirms
use strict;
use warnings 'all';

use JSON::PP;
use Data::Dump;

my $json = '[{"":"#","jednostka":"","login":"SA"}]';

my $data = JSON::PP::decode_json($json);

dd $data;

output
[{ "" => "#", "jednostka" => "", "login" => "SA" }]

A: Another way to get the "unexpected end of string while parsing JSON string" from Perl's JSON::decode_json() function, is if your JSON file contains trailing commas, like this:
{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500,
    }  }}

The JSON specification does not allow a trailing comma (this is unrelated to URI-encoding, btw). You should be able to catch such JSON format violations using JSON::Parse::valid_json().

A: It looks like you're decoding it in Perl, but attempting to decode an empty variable name.  Give the first variable a name.


text:
Q: Sonata admin form mapper one-to-many relation with too many entries I have a performance problem with sonata.
I built a form with a one-to-many relation that works great between operation on several products, everything is fine in dev environment, but in production, I have 250000 products to be managed that makes queries very slow…
I have an ajax query to replace my selector's content according to the maker of the product, but the first call (which param all the CRUD logic) is far too long…
Here is my form mapper
->add( 'operationhasproducts', 'sonata_type_model',
        array(
             'class' => 'MyBundle\Entity\Operationhasproducts',
             'query' => $this->modelManager->createQuery('MyBundle\Entity\Product'),
             'multiple' => true,
             'by_reference' => false,
             'btn_add' => false,
             'required' => false
       )
)

How can I keep the logic without loading 250000 products on loading the page
I tried to put 'query'=> $this->modelManager->createQuery('MyBundle\Entity\Product')->setMaxResults(10), the form displays but then the crud logic no longer works, I have a data transformation error
Symfony\Component\Validator\ConstraintViolation

Object(Symfony\Component\Form\Form).children[operationhasproducts] = [0 => 2739, 1 => 29217]

Caused by:
Symfony\Component\Form\Exception\TransformationFailedException

Unable to reverse value for property path "operationhasproducts": Could not find all matching choices for the given values

Caused by:
Symfony\Component\Form\Exception\TransformationFailedException

Could not find all matching choices for the given values

Any help will be welcome


text:
Q: Can a matrix $A$ commute with $e^B$ without commuting with $B$? As in the title. Is it possible that $[A,B]\neq0$, but $[A,e^B]=0$? I tried expanding the exponential and using $[A,B^n]=\sum_k {n\choose k} B^{n-k}[A,B]B^k $ but this doesn't seem to give any insight.
I'm inclined to think the answer is yes, because a sum of terms being $0$ is a weaker requirement than each term being $0$, but I was wondering if there's a clearer way to see it.
EDIT: in light of lisyarus' answer, what if the matrices in question are hermitian and have real eigenvalues?

A: Yes, this can happen.
Take $B$ to be diagonal, with entries $2\pi i k$ with different $k$ (so that $B$ is not a scalar matrix). Then, $\exp B = 1$, so it commutes with anything.
Now, since $B$ is not a scalar matrix, there is some $A$ that doesn't commute with $B$.

A: Referring to your question in the comment to @lisyarus, if $A,B$ are hermitian then $\left[A,e^{B}\right]=0\Longrightarrow\left[A,B\right]=0$.
To see this, observe that two hermitian matrices commute iff they can be simultaneously diagonalized. Thus, if $\left[A,e^{B}\right]=0$ there exist a unitarian $U$ such that both $U^{\dagger}AU$ and $U^{\dagger}e^{B}U$ are diagonal. Now
$$U^{\dagger}BU=U^{\dagger}\ln e^{B}U=\ln\left(U^{\dagger}e^{B}U\right)$$
is also diagonal and therefore $\left[A,B\right]=0$. Note that indeed
$$B=\ln e^{B}$$
since in the diagonal basis this translates to $\lambda_{i}=\ln e^{\lambda_{i}}$ where $\lambda_{i}$ are the real eigenvalues. This fails for non-hermitian matrices because in that case $\ln$ is multivalued and not injective.


text:
Q: c++ profiling of the g++ based application with libraries I'm trying to find performance problems inside melt framework and especially with affine transformations.
I've tried 3 profilers: gprof, Zoom and GooglePerfomanceTools.
I've compiled all code with disabled optimizations and explicitly removed any inline functions changing it by ordinary functions.
But all of this profilers getting me unresolved function names in a Call Graph. In the true is that the most of these functions are the most time consuming.
So the question is what is the correct procedure to profile g++ based application with libraries
Thanks,

A: you need to compile your program with debugging info enabled (which I assume you did, but mentioning it nonetheless), install debug enabled versions of your dependency libraries, and link your program against them.
in debian based linux environments, they are usually named like the original library, with a -dbg suffix. for example, libxml2-dbg.
hope this helps.


text:
Q: IRC connectivity issue in Python I have a Python script which has an infinite while loop. It joins an IRC channel, does some computation, prints some message, sleeps for 5 minutes, and then repeats. Periodically the scripts errors out with the following:
Traceback (most recent call last):
  File "db_alerts.py", line 65, in <module>
    if data.split()[0].find('PING') != -1:
IndexError: list index out of range

The IRC handle leaves the channel with the following message: (03:00:56 PM) TestBOT left the room (quit: Ping timeout: 121 seconds).
My code is as follows:
import json
import socket
import time

if status:
    env = "prod"
    time_of_last_check = 0
    channelfile = 'irc_channels.json' #File to store channel and password in json format
    channelinfo = open(channelfile,'r').read()
    botnick = json.loads(channelinfo)[env]["nick"]
    network = 'irc.xxxx.com'
    ircsock = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
    ircsock.connect((network, 6667))
    ircsock.send("NICK "+ botnick +"\r\n")
    ircsock.send('USER '+ botnick +' userrxxxxx - :'+botnick +"\r\n")
    time.sleep(2)
    ircsock.send ( 'PRIVMSG NickServ :IDENTIFY zzzzzzzz\r\n')
    for channel,password in json.loads(channelinfo)[env]["channel"].iteritems():
        ircsock.send("JOIN "+ channel + " " + password + "\r\n")
    while 1:
        if time.time() - time_of_last_check > 350:
            localtime = time.asctime( time.localtime(time.time()) )
            print "Last run time :", localtime
            for message,ticket in get_data():
                if str(message) != 'None' and str(ticket) != 'None':
                    for channel,password in json.loads(channelinfo)[env]["channel"].iteritems():
                        if channel == "#X":
                            message = "TEST"
                            ircsock.send('PRIVMSG %s :%s \r\n' % (channel,message))
                            time.sleep(1)
                        else:
                            message1 = "TEST1"
                            ircsock.send('PRIVMSG %s :%s \r\n' % (channel,message1))
                            time.sleep(1)
            data = ircsock.recv (4096)
            if data.split()[0].find('PING') != -1:
                            ircsock.send('PONG ' + data.split()[1] + '\r\n' )
            for message,ticket in get_data1():
                                if str(message) != 'None' and str(ticket) != 'None':
                                        for channel,password in json.loads(channelinfo)[env]["channel"].iteritems():
                                               if channel == "#X":
                            message = "TEST"
                            ircsock.send('PRIVMSG %s :%s \r\n' % (channel,message))
                            time.sleep(1)
                        else:
                            message1 = "TEST1"
                            ircsock.send('PRIVMSG %s :%s \r\n' % (channel,message1))
                                                        time.sleep(1)
            time_of_last_check = time.time()
        data = ircsock.recv (4096)
        if data.split()[0].find('PING') != -1:
            ircsock.send('PONG ' + data.split()[1] + '\r\n' )

A: When connection is closed (EOF), ircsock.recv(4096) returns an empty string. In turn ''.split() returns empty list. And trying to get the first item from an empty list [][0] raises IndexError.


text:
Q: Change NSFetchedResultsController with UISegmentedControl I've seen another question here that helped me a lot, but I'm still having issues with my particular configuration. I'm using what some people refer to as 'slim view controllers' which means that I have an object with a single protocol method to configure tableViewCells and the tableview's dataSource/delegate and NSFetchedResultsController delegate methods. The biggest reason I'm using this particular setup is I can create a single superclass with that has all my segues and a single dataSource property. It's been working well, except for one page that has a UISegmentedControl where I have to change this dataSource object for the view controller. I can set it and interact with the view controller as expected, but as it is now, I can set the selectedSegmentIndex to 1, and I can reset it to 0, but the tableView doesn't update correctly (it still will show as having a selectedSegmentIndex of 1). For a long time I was having trouble making the tableView work at all when the selectedSegmentIndex was 1 — I was getting messages saying that An Objective-C message was sent to a deallocated 'LSTFetchedResultsControllerDataSource' object (zombie) at address: 0x198a90f0.
Any ideas why I can reset the selectedSegmentIndex to 0, but the corresponding tableView doesn't show the proper data?
// ViewController - LSTFavoriteSpeeches.h
@interface LSTFavoriteSpeeches : LSTSpeechBaseTBVC <FetchedResultsControllerDataSourceDelegate>

@property (nonatomic, strong) LSTFetchedResultsControllerDataSource *currentDataSource;
@property (weak, nonatomic) IBOutlet UISegmentedControl *favoriteSegmentedControl;
- (IBAction)toggleFavoriteSpeechesandSpeakers:(id)sender;

@end

// ViewController - LSTFavoriteSpeeches.m
@interface LSTFavoriteSpeeches ()
@property (nonatomic, strong) LSTFetchedResultsControllerDataSource *favoriteSpeechesDataSource;
@property (nonatomic, strong) LSTFetchedResultsControllerDataSource *favoriteSpeakersDataSource;
@property (nonatomic, strong) NSFetchedResultsController *favoriteSpeechesFRC;
@property (nonatomic, strong) NSFetchedResultsController *favoriteSpeakersFRC;
@property (nonatomic, strong) NSFetchedResultsController *currentFRC;
@property (nonatomic, copy)   NSString *currentCellNibName;
@property (nonatomic, copy)   NSString *currentCellIdentifier;
@end

@implementation LSTFavoriteSpeeches

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    NSManagedObjectContext *managedObjectContext = [[LSTSharedMOC sharedMOC] sharedManagedObjectContext];

    /* Set the favoriteSpeechesFRC, if tere are any favorite speeches to be fetched, otherwise, set it to nil */
    self.favoriteSpeechesFRC = [managedObjectContext executeFetchRequest:[LSTFetchData favoriteSpeakersSortedByTitle:NO] error:nil]
        ? self.favoriteSpeechesFRC = [[NSFetchedResultsController alloc] initWithFetchRequest:[LSTFetchData favoriteSpeechesSortedByTitle:NO] managedObjectContext:managedObjectContext sectionNameKeyPath:@"speechType" cacheName:nil]//;@"LSTFavoriteSpeeches"];
        : nil;

    self.favoriteSpeakersFRC = [[NSFetchedResultsController alloc] initWithFetchRequest:[LSTFetchData favoriteSpeakersSortedByTitle:NO] managedObjectContext:managedObjectContext sectionNameKeyPath:@"lastNameInitial" cacheName:nil];

    [self toggleFavoriteSpeechesandSpeakers:self.favoriteSegmentedControl];
}

- (void)configureCell:(id)cell withObject:(id)object {
    super.dataSource = self.currentDataSource;
    [super configureCell:cell withObject:object];
}

- (IBAction)toggleFavoriteSpeechesandSpeakers:(UISegmentedControl *)sender {

    if (sender.selectedSegmentIndex == 0) {
        self.favoriteSpeechesDataSource = [[LSTFetchedResultsControllerDataSource alloc] initWithTableView:self.tableView withFetchedResultsController:self.favoriteSpeechesFRC reuseIdentifier:LSTSpeechCellIdentifier andNibName:LSTSpeechTableCellNibName];

        self.currentCellIdentifier = LSTSpeechCellIdentifier;
        self.currentCellNibName = LSTSpeechTableCellNibName;
        self.favoriteSpeechesDataSource.delegate = self;
        self.currentDataSource = self.favoriteSpeechesDataSource;
    } else {
        self.favoriteSpeakersDataSource = [[LSTFetchedResultsControllerDataSource alloc] initWithTableView:self.tableView withFetchedResultsController:self.favoriteSpeakersFRC reuseIdentifier:LSTSpeakerCellIdentifier andNibName:LSTSpeakerTableCellNibName];

        self.currentCellIdentifier = LSTSpeakerCellIdentifier;
        self.currentCellNibName = LSTSpeakerTableCellNibName;
        self.favoriteSpeakersDataSource.delegate = self;
        self.currentDataSource = self.favoriteSpeakersDataSource;
    }

    [self.tableView registerNib:[UINib nibWithNibName:self.currentCellNibName bundle:nil] forCellReuseIdentifier:self.currentCellIdentifier];
    [self.tableView reloadData];
}

@end

// DataSource - LSTFetchedResultsControllerDataSource.h
@interface LSTFetchedResultsControllerDataSource : NSObject <UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate>

@property (nonatomic, weak) id <FetchedResultsControllerDataSourceDelegate> delegate;
@property (readonly, strong) NSFetchedResultsController *fetchedResultsController;
@property (readonly, strong) UITableView *tableView;
@property (readonly, copy) NSString *reuseIdentifier;
@property (readonly, copy) NSString *nibName;
@property (readonly) NSEntityDescription *entity;

- (id)initWithTableView:(UITableView *)tableView
withFetchedResultsController:(NSFetchedResultsController *)fetchedResultsController
        reuseIdentifier:(NSString *)reuseIdentifier
             andNibName:(NSString *)nibName;

@end

// DataSource - LSTFetchedResultsControllerDataSource.m
@interface LSTFetchedResultsControllerDataSource ()

@property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSString *reuseIdentifier;
@property (nonatomic, copy) NSString *nibName;

@end

@implementation LSTFetchedResultsControllerDataSource

#pragma mark - Initilializers

- (id)initWithTableView:(UITableView *)tableView withFetchedResultsController:(NSFetchedResultsController *)fetchedResultsController reuseIdentifier:(NSString *)reuseIdentifier andNibName:(NSString *)nibName {
    if (self = [super init]) {
        _tableView = tableView;
        _tableView.dataSource = self;
        _fetchedResultsController = fetchedResultsController;
        _fetchedResultsController.delegate = self;

        NSError *error;

        if ((self.fetchedResultsController != nil) && (![self.fetchedResultsController performFetch:&error])) {
            NSLog(@"Unresolved error %@ -- %@", error, error.userInfo);
            abort();
        }

        _reuseIdentifier = reuseIdentifier;
        _nibName = nibName;
    }

    return self;
}

#pragma mark - UITableViewDataSource Delegate Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex {...}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {...}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {...}

#pragma mark - NSFetchedResultsController Delegate Methods
- (void)controllerWillChangeContent:(NSFetchedResultsController*)controller {
    [self.tableView beginUpdates];
}

- (void)controllerDidChangeContent:(NSFetchedResultsController*)controller {
    [self.tableView endUpdates];
}

- (void)controller:(NSFetchedResultsController *)controller
  didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
           atIndex:(NSUInteger)sectionIndex
     forChangeType:(NSFetchedResultsChangeType)type {

    switch(type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            NSLog(@"NSFetchedResultsChangeInsert");
            break;

        case NSFetchedResultsChangeMove:
            NSLog(@"section changed - type - NSFetchedResultsChangeMove");
            break;

        case NSFetchedResultsChangeUpdate:
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            NSLog(@"NSFetchedResultsChangeUpdate");
            break;

        case NSFetchedResultsChangeDelete:
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            NSLog(@"NSFetchedResultsChangeDelete");
            break;
    }
}

- (void)controller:(NSFetchedResultsController*)controller
   didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath*)indexPath
     forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath*)newIndexPath {

    switch(type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeDelete:
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeMove:
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeUpdate:
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//            [self.tableView reloadRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationNone];
            break;
    }
}

@end


text:
Q: Is there a way to Sign in to two or more websites simultaneously A simple question. I have 2 wordpress websites, 1st is an e-commerce, 2nd will act as support ticket system. I want users to register on both sites, which I accomplished with "User Sync" plugin.
Another thing I wanted was if the user is logged into 1st website, when he switch to 2nd one, he should be logged in there too. like stack overflow works, or google network works, when I am logged in to Gmail, I am logged into youtube, gdrive, calendars, google search, etc.
How this "single sign in" or "sign in once" thing will work and with what plugin?


text:
Q: How do you create your own quick commands in Vivaldi? I am using the new Vivaldi browser. On the Vivaldi website, it says:

Quick commands menu is highly customizable allowing you to create your own commands and run them instantly.

But, how do you create your own quick commands in Vivaldi?

A: This may be a case of marketing people taking artistic liberties on the web page promoting Vivaldi.  "Creating your own commands" appears to be a bit of a misnomer.
I posed the question on the Vivaldi forum and the gist of the responses (from a moderator and a "platinum" member) is that this refers to several features of the Quick Commands menu.

*

*You can customize the menu by adding shortcuts for commands to the menu (creating new menu selections, or "commands").
Creating shortcuts: http://vivalditips.com/customization/shortcuts
The main Vivaldi web page shows the shortcuts being included in the menu.  I didn't find documentation on explicitly adding them to the menu, so I'm just assuming that this is automatic.

*You can type a free-form "command", which initiates an indexed search as you type to bring up existing commands that might include what you want: http://vivalditips.com/efficiency/quick-commands
Since what you type isn't an existing command and it leads to executing the action you want, you've "created your own command".


text:
Q: In a card game. why does it make a difference if I draw cards simultaneously Four cards are successively drawn without replacement from a deck of 52 playing cards. What is the probability that all four cards are kings ?
There are two ways to approach this
i) There are $4$ favorable events out of $ ^{52}C_4$ events so the probability is
$\frac{4}{^{52}C_4}$
way two
there are $\frac{4}{52}$ ways of selecting the first card, $\frac{3}{51}$ dor the second and so on, which gives us a probability of $\frac{1}{270725}$.
why are there two different answers , and why is the $2^{nd}$ one right?

A: $$
\text{Probability}=\frac{\binom{4}{4}\binom{48}{0}}{\binom{52}{4}}.
$$


text:
Q: Override JQuery function with CSS in responsive design I ran into a little obstacle in my site. In the mobile version (<480px), I have a toggle button for comments. >480px version, the button is hidden, and I want to always show the comments. It is a responsive design so it is the same page when resized. How can I do that?
$(document).ready(function(){
  $('#comments-container').addClass('mobile-hide');

   $('#show-comments').click(function()
   {
      $('#comments-container').filter(':not(:animated)').slideToggle();
   });
});

.mobile-hide is just display: none;. When I toggle the content to show then hide, and resize the browser to >480px, the content remains hidden. I've tried to set .mobile-hide { display: block; } for the >480px stylesheet, but it doesn't work.

A: Have you considered using media queries in CSS to achieve this? It sounds like you don't need to use JS for this but I am a little unclear. For example:
#comment-button {display:block;}

@media only screen and (max-device-width: 480px) {
  #comment-button {display:none;}
}

To listen for browser width you can either set a tick event (happens every x seconds with setInterval) or use the resize event:
$(window).on('resize', function(ev) {
    if($(window).width() > 480)
        $('html').removeClass('mobile-device').addClass('desktop-device');
    else
        $('html').removeClass('desktop-device').addClass('mobile-device');
});

html.mobile-device .toggle-button {display:none;}


text:
Q: Set Label HeightRequest automatically depending on how much space the text needs I have a Label inside a StackLayout inside a Frame:
<Frame Grid.Row="0" Margin="0, 0, -10, 0" OutlineColor="Transparent" HasShadow="False" Grid.Column="1" BackgroundColor="{StaticResource rightBubbleColor}">
  <StackLayout>
    <Label
      Style="{StaticResource rightBubbleStyle}"
      TextColor="{StaticResource rightBubbleFontColor}"
      Text="{Binding message}" />
  </StackLayout>
</Frame>

This gives me this result:

The problem here is that the last message actually has more text which would need 6 rows to display the whole text.
If I set a value for HeightRequest for the Label, it changes the height of the Frame as well. For example if I set a value of 150, I get this result:

I need to dynamically set a value for HeightRequest depending on how much height the Text needs.
Does anyone know how I can achieve that (preferably in xaml) or is this even a wrong approach to my problem?
Edit 1:
Removing the style from the Label doesn't solve the problem. It only occurs on UWP. Note that I don't have a Windows Phone to test it, the problem occurs on my local machine (Windows 10 Desktop).
Edit 2:
According to the Xamarin documentation, the height should be autosized dependon on the content:

When the app developer sets the ListView.HasUnevenRows property to true, the behavior of the list view still depends on the ListView.RowHeight property. First, if the developer either does not set the ListView.RowHeight property or sets it to -1, list view items are autosized to fit their contents. This is the desired behavior and the intended use case for a ListView.HasUnevenRows value of true, as noted above.

A: I found a solution. This was the problem:
<RowDefinition Height="*" />

I set the value to Auto and now it's working. Strange that it has a different behaviour on iOS and Android tho.


text:
Q: Google map plugin not working with wordpress 3.8 I am using wordpress 3.8 CMS in which i am using google-maps-for-wordpress plugin but it is not working:
Showing Errors in console:
ReferenceError: GBrowserIsCompatible is not defined
[Break On This Error]

if (GBrowserIsCompatible()) {

Please help me to solve this!
Thanks!

A: That looks like a problem with your API key. You need to generate a new one by following the instructions provided here


text:
Q: How to design below effect in a div without using any Images
How can we design tip in bottom just like above without using any images.
Below is my trail code:

TIP: UPLOAD YOUR
 COVER IMAGE HERE

#coverImageToolTip {
    position: absolute;
    z-index: 10;
    padding: 0px 4px;
    background-color: gray;
    bottom: 100px;
    left: 20%;
    border-radius: 10px;
    font-weight: bold;
    border-bottom: 5px solid black;
}

/* #tail1 {
    position:absolute;
    bottom:100px;
    left:20px;
    width:0;height:0;
    border-color:#a0c7ff transparent transparent transparent;
    border-width:10px;
    border-style:solid;
} */

#tail2 {
    position:absolute;
    bottom:-18px;
    left:20px;
    width:0;height:0;
    border-color: red transparent transparent  red  ;
    border-width:10px;
    border-style:solid;
    transform:rotate(90deg);
    -ms-transform:rotate(90deg); /* IE 9 */
    -moz-transform:rotate(90deg); /* Firefox */
    -webkit-transform:rotate(90deg); /* Safari and Chrome */
    -o-transform:rotate(90deg); /* Opera */
}

A: A minimal markup version:
DEMO
HTML:

  tip: upload your cover image here

Relevant CSS:
.tooltip {
  position: relative;
  margin: 1em auto;
  padding: .5em .2em;
  width: 10.5em; height: 3em;
  border-radius: .25em;
  box-shadow: 0 .2em 0 black;
  background: #999;
  font: 700 1.6em/1.5 sans-serif;
}
.tooltip:before {
  position: absolute;
  top: -.75em; right: -.75em;
  border: solid .2em;
  width: 1.5em; height: 1.5em;
  border-radius: 50%;
  background: black;
  color: #999;
  font: 900 .65em/1.5 sans-serif;
  content: 'x';
}
.tooltip:after {
  position: absolute;
  z-index: -1;
  right: 25%; bottom: -.75em;
  width: 2em; height: 2em;
  box-shadow: 0 .35em 0 black;
  transform: rotate(30deg) skewY(-60deg);
  background: inherit;
  content: '';
}
.highlight:after, .highlight:before {
  position: absolute;
  top: 100%; right: 31.025%;
  width: 1.725em; height: .2em;
  transform: skewX(-30deg);
  background: #999;
  content: '';
}
.highlight:after {
  right: 30.65%;
  transform: skewX(-60deg);
}

A: please see Pure css close button ( the close button in CSS ) and http://v2.desandro.com/resources/css-speech-bubble-icon/ for the actual trail.

A: You can do the close button and arrow in css but shadow for arrow is not possible.
Look at the code below
HTML

X

    TIP: UPLOAD YOUR
 COVER IMAGE HERE

CSS
      .close a{
    position:absolute;
    right:-5px; top:-8px;
    display:inline-block;
    background:black;
    padding:2px 6px;
    color:white;
    border:solid grey 3px;
    border-radius:22px;
    font-size:12px;
    text-decoration:none
}
        #tail2 {
            position:absolute;
            bottom:-19px;
            left:80px;
            width:0;height:0;
            border-color: grey transparent transparent  grey  ;
            border-width:10px;
            border-style:solid;
            transform:rotate(90deg);
            -ms-transform:rotate(90deg); /* IE 9 */
            -moz-transform:rotate(90deg); /* Firefox */
            -webkit-transform:rotate(1deg); /* Safari and Chrome */
            -o-transform:rotate(90deg); /* Opera */
        }

DEMO

A: You can use before and after to simulate a shape close to your image for the arrow. Have a look at this demo: http://jsfiddle.net/j34um/3/


text:
Q: Templates when using vectors instead of doubles as input I am trying to achieve a very simple thing using C++ templates. I would like to build a generic sign function that could handle the case sgn(x)where x could be either doubleor std::vector<double> (that is returning a std::vector<double> containing the results). In order to achieve that I am using templates
double f(double x) {
    return (x>=0)?1.0:-1.0;
};

template<typename T>
T F(T x) {
   // ?
};

I would like to cast the template and either use f if double or a for loop if std::vector<double>. Unfortunately my function does not use any arithmetic operator and the conditional operator cannot be overloaded. How should I proceed ?

A: This is solved by overloading, not templates.
double sign(double x) {
    return x < 0.0 ? -1.0 :
           x > 0.0 ?  1.0 : 0.0;
};

std::vector<double> sign(std::vector<double> const& x) {
    // ?
};

That said, I'd doubt whether a sign function is meaningful for vectors.
This, by the way, has got nothing to do with "arithmetic" versus "non-arithmetic" functions, as alleged in the title of the question. This distinction doesn't exist in C++.

A: While overloading is the best way to achieve what you want, it is not
really the way to work with the C++ standard library.
If you want to apply a function to all elements of a container (either
mutating them or creating new results), use std::transform or
std::for_each with the function you want to use.
std::vector<double> doubles, results;
std::transform(begin(doubles), end(doubles), std::back_inserter(results), sgn);

That separates concern far better than your current approach. Only
operate on whole containers if it is really required, in all other
cases use iterators and higher-order functions.


text:
Q: Cannot get PowerShell string match to return True I have an array of string values and am trying to run a loop to match (using -eq operator) and return true if another variable matches one of the string values in the array. Even though I know the values should match, the loop is returning false.
I am currently taking the PS objects and pulling out the string values of a particular property of the object for the matching. I tried other operators aside from -eq, including -like using a wildcard and -match but there is no change in behavior. I also am currently constructing a list using $XXXX.Add($XXXX), but also had no luck with just populating an array with =+.
foreach ($Server in $UpdateGroupMembers) {
    if ($Server -eq $NodeName) {
        Write-Host "$Server is a match, loop terminated"
        return $true
        #break
    } else {
        Write-Host "There is no match"
        return $false
    }
}

$NodeName in the code above is a value that I know exists in the array/list, so I am quite lost.

A: If you just need to check whether a list or array contains an item, you can use the -in operator:
if ($NodeName -in $UpdateGroupMembers) {
    "$NodeName is a match"
    $true
}
else {
    "There is no match"
    $false
}

If you truly only need a True or False return, then you can do a one-liner:
$NodeName -in $UpdateGroupMembers

A: It seems to me that you are exiting the function after hitting the first servername that doesn't match.
If my understanding is correct the code should look like:
$found= $false
foreach ($Server in $UpdateGroupMembers) {
    if ($Server -eq $NodeName) {
        Write-Host "$Server is a match, loop terminated"
        $found = $true
        break
}
if ($found -eq $false) {write-host "no match found for $NodeName "}
return $found

Make sure that $NodeName is a string and $UpdateGroupMembers is a collection of names not a collection of objects so you can compare them. I use something like $UpdateGroupMembers | get-member to see exactly what I am working with.


text:
Q: DEVICE_CREDENTIAL dosent work if fingerprint is there So I have been working on implementing an authentication feature in my app so first I implemented Fingerprint authentication it works perfectly. But now am trying to add an option for pin too I have added that option with the help of documentation in the android developer
link
https://developer.android.com/training/sign-in/biometric-auth
So now the problem is I have implemented but in-app when I use fingerprint it works fine but when I use pin it doesn't work as nothing happens. But the pin actually works when there is no fingerprint saved on the device
So here's the code
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();

    if (firebaseUser != null) {
        SharedPreferences sharedPreferences = getSharedPreferences("Authentication", 0);
        String bio = sharedPreferences.getString(TEXT, "");

    if (bio.equals("1")) {

        BiometricManager biometricManager = androidx.biometric.BiometricManager.from(this);
        switch (biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK | DEVICE_CREDENTIAL)) {

            // this means we can use biometric sensor
            case BiometricManager.BIOMETRIC_SUCCESS:

                break;

            // this means that the device doesn't have fingerprint sensor
            case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:

                break;

            // this means that biometric sensor is not available
            case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:

                break;

            // this means that the device doesn't contain your fingerprint
            case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:

                break;
            case BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED:
                break;
            case BiometricManager.BIOMETRIC_ERROR_UNSUPPORTED:

                break;
            case BiometricManager.BIOMETRIC_STATUS_UNKNOWN:

                break;
        }
        // creating a variable for our Executor
        Executor executor = ContextCompat.getMainExecutor(this);
        // this will give us result of AUTHENTICATION
        final BiometricPrompt biometricPrompt = new BiometricPrompt(StartActivity.this, executor, new BiometricPrompt.AuthenticationCallback() {
            @Override
            public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) {
                super.onAuthenticationError(errorCode, errString);
            }

            // THIS METHOD IS CALLED WHEN AUTHENTICATION IS SUCCESS
            @Override
            public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) {
                super.onAuthenticationSucceeded(result);
                Toast.makeText(getApplicationContext(), "Login Success", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(StartActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onAuthenticationFailed() {
                super.onAuthenticationFailed();
            }
        });
        // creating a variable for our promptInfo
        // BIOMETRIC DIALOG
        final BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder().setTitle("Authentication")
                .setDescription("Use your fingerprint to login ")
                .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_WEAK|DEVICE_CREDENTIAL).build();

        biometricPrompt.authenticate(promptInfo);

    }else {
        Intent intent = new Intent(StartActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

I hope these are enough information for my problem


text:
Q: XamlReader throwing up undeclared prefix error I defined a resource as follows:
<DataTemplate xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
            <Grid x:Name="grdArticle" Height="190" Width="190" toolkit:TiltEffect.IsTiltEnabled="True">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>

                <Image Source="samplePhoto.jpg" Grid.Row="0" Stretch="UniformToFill"/>
                <Grid Grid.Row="0" Height="55" VerticalAlignment="Bottom">
                    <Rectangle Grid.Row="0" Fill="{StaticResource PhoneAccentBrush}"/>
                    <TextBlock Grid.Row="0" Text="{Binding Title}" Canvas.ZIndex="2" VerticalAlignment="Bottom" TextWrapping="Wrap" Margin="5,5,5,5" Height="50" FontStyle="Normal">
                        <TextBlock.Foreground>
                            <SolidColorBrush Color="#BFFFFFFF"/>
                        </TextBlock.Foreground>
                    </TextBlock>
                </Grid>
            </Grid>
        </DataTemplate>

When I'm trying to parse it using:
DataTemplate dtTmplt = XamlReader.Load(PhoneApp5.Resource1.Datatemplate_lst) as DataTemplate;

I'm getting XamlParseException,saying "undeclared prefix" at line 2,position 104.
I have tried many xmlns tags from the internet,but nothing seems to work.Any help?

A: It's the toolkit prefix that is undeclared.  You need to add
xmlns:toolkit="..."

to either the <DataTemplate> or the outer <Grid> element.  Replace ... with whatever you're binding xmlns:toolkit to elsewhere in your application.
Incidentally, is there a reason you're parsing the contents of a resource as XAML this way?  Normally, I'd put a DataTemplate in a Resources resource-dictionary somewhere, or in Application.Resources.  That way, the compiler would check that it is valid XAML.


text:
Q: Add active class to menu on scroll point or id as well as on click I am trying to get the menu items to get the "active" class not only when they are clicked on but also when scrolled to the id's of #main, #features etc. Right now I have some jquery that adds an active class and removed it from other menu items on click, but as soon as a scroll obviously that menu item stats active, as its only working on clicks and not scroll points.

Home

Features

About

Contact us

The theme i bought is using stellar.js and I think this is the js creating scroll points:
jQuery('a[href*=#]:not([href=#])').click(function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

    var target = jQuery(this.hash);
    target = target.length ? target : jQuery('[name=' + this.hash.slice(1) + ']');
    if (target.length) {
        jQuery('html,body').animate({
            scrollTop: target.offset().top - 100
        }, 1000);
         return false;
    }
}
});

I just need this to add an active class to my menu and remove it from other items but also on scroll point or target id. Any help would be much appreciated please :)
Updated code I am playing with, not working properly:
jQuery('a[href*=#]:not([href=#])').click(function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

    var target = jQuery(this.hash);
    target = target.length ? target : jQuery('[name=' + this.hash.slice(1) + ']');
    if (target.length) {
        jQuery('html,body').animate({
            scrollTop: target.offset().top - 100
        }, 1000);

        jQuery(".menu-item a").removeClass("active");

        target.addClass("active");
        target.hasClass("active").find(this).addClass("active");

        return false;
    }
}
});

A: win.scroll(function(e){
    jQuery.each(items, function(key, value){
        var item = jQuery(value);
        if(win.scrollTop() >= item.offset().top){
            jQuery('.menu-item a.active').removeClass('active');
            var id = item.attr('id');

            jQuery.each(navItems, function(key, value){
                var navItem = jQuery(value);
                if(navItem.attr('href') == '#'+id) navItem.addClass('active');
            });
        }
    });
});

Sorry I misunderstood your question. I think this is what you're looking for:
http://jsfiddle.net/pnsxg2zh/
So basically on scroll I get the scroll position of the window, and then use offset().top to find the position of the elements you want to scroll to. I check if the window's scroll position is >= the top of the element, if it is I add the active class to the nav item who has the href equal to the id of that element.

A: so you need to add class "active" when menu-item is clicked and the element (#main and other) is visible on the screen.
to add "active" class on clicked, do this:
jQuery('.menu-item').click(function(){
    jQuery('#menu-main-menu li').removeClass('active');
    jQuery(this).removeClass('menu-item').addClass('menu-item active');
});

to check element visibility please read this post
Check if element is visible after scrolling


text:
Q: How can I install pyautogui on a Debian environnement on a Python2.7? I am trying install this pyautogui, unsuccesfully.
I tried: pip install pyautogui
Result: it started to installing, pillow in local, collecting zip file, etc, and suddenly stop and write this error message:

"File /usr/lib/python2.7/dist-packages/HERE CHANGE A FEW TEXT LIKE
  pip, PyTweenig,etc.. and after these OS ERROR: [ERRNO13] permission
  denied
  'usr/local/lib/Python2.7/dist-packages/PyTweening-1.0.2.dist_info'

If I am trying with : sudo pip install pyautogui
Result:

Xlib.Error.DisplayConnectionError:Can't connect to display:"1" No
  protocol specified. Command "python setup.py egg_info" failed with
  error code 1 in tmp/pip-build-2t6aey/pyautogui

What can i do?

A: I solved with this :
sudo chmod 777 'usr/local/lib/Python2.7/dist-packages'


text:
Q: CS50 Pset4 filter-more blur() function not working Link to the problem (blur part only) here.
In this code I am trying to blur a bmp image by taking the weighted sum across 3x3 matrix for each pixel and replacing the original value with the average obtained.
I have tried various different things, the code compiles correctly (there is no error), and also I couldn't find any problem while debugging the code , but the output image obtained is not what was desired, it is a black and colored pattern repeated 3 times vertically instead of the edges of the input photo.
Thanks for helping out.
Here is the main code of the function:
// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
    // Array for storing corresponding blur values of the pixels.
    RGBTRIPLE(*blur)[width] = calloc(height, width * sizeof(RGBTRIPLE));
    if (image == NULL)
    {
        printf("Not enough memory to store blur pixels.\n");
        return;
    }

    for (int row = 0; row < height; row++)
    {
        for (int col = 0; col < width; col++)
        {
            sum3x3(row, col, height, width, image, blur);
        }
    }

    for (int row = 0; row < height; row++)
    {
        for (int col = 0; col < width; col++)
        {
            image[row][col] = blur[row][col];
        }
    }

    free(blur);
    return;
}

Here is the code for sum3x3 function:
void sum3x3(int row, int col, int height, int width, RGBTRIPLE matrix[row][col], RGBTRIPLE new_matrix[row][col] )
{
    float counter = 0;
    float blue = 0;
    float green = 0;
    float red = 0;

    for (int i = -1; i < 2; i++)
    {
        for (int j = -1; j < 2; j++)
        {
            // skip rows out of range.
            if ( (i + row) < 0 || (i + row >= height)) continue;
            // skip columns out of range.
            if ( (j + col) < 0 || (j + col >= width)) continue;
            // add to sum.

            counter ++;

            blue += matrix[i + row][j + col].rgbtBlue;
            green += matrix[i + row][j + col].rgbtGreen;
            red += matrix[i + row][j + col].rgbtRed;

        }
    }

    new_matrix[row][col].rgbtBlue += round(blue/counter);
    new_matrix[row][col].rgbtGreen += round(green/counter);
    new_matrix[row][col].rgbtRed += round(red/counter);
}

The RGBTRIPLE data structure:
typedef struct
{
    BYTE  rgbtBlue;
    BYTE  rgbtGreen;
    BYTE  rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

Update: I made some changes to the code according to the suggestions in comments but still not getting the desired output.


text:
Q: Terraform how to force AWS ASG to create new instances when lauch config is updated When I update the launch config of an AWS ASG, the ASG is updated but the existing running instances are not recreated with the new launch config.
How can I tell ASG to recreate instances?
This is my current terraform config:
resource "aws_launch_configuration" "app-lc" {
  image_id             = "${var.ami}"
  instance_type        = "m4.large"
  security_groups      = ["${split(",", var.security_groups)}"]
  user_data            = "${file("user_data.sh")}"
  key_name             = "${var.key_name}"

  root_block_device {
    volume_type           = "standard"
    volume_size           = "50"
    delete_on_termination = "true"
  }

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_autoscaling_group" "app-asg" {
  name                      = "my-asg"
  max_size                  = "${var.asg_size}"
  min_size                  = "${var.asg_size}"
  desired_capacity          = "${var.asg_size}"
  launch_configuration      = "${aws_launch_configuration.app-lc.name}"
  health_check_type         = "EC2"
  health_check_grace_period = "600"
  vpc_zone_identifier       = ["${split(",", var.server_subnets)}"]
}


text:
Q: Open Layers 3 Drag & Drop feature, get file name of file dropped Dragging and dropping vector layers can be achieved as per the instructions on the Openlayers 3 demo page:
http://openlayers.org/en/v3.15.1/examples/drag-and-drop.html
This works perfectly fine, so I shan't post the source code here.
My question is: How can I get the file name (or layer name) that's being added to the map?  Nothing stands out to me in the API documentation here.

A: I've sussed it out, it isn't present in the API docs as far as I can tell, but via Firebug I was able to get the value from within the dragAndDropInteraction event handler:
dragAndDropInteraction.on('addfeatures', function(event) {
     var file_name = event.file.name;
});


text:
Q: How to deal with unused imports in a python module I want to make use of an existing python module (called "module.py"). I'm only interested in one function from that module ("my_function()"). The module also contains a lot of other functions, which I'm not using. These other functions cause the module to have a lot of imports that are not used in my_function.
"""module.py"""
import useful_import
import useless_import1
import useless_import2

def my_function():
return useful_import.do()

def other_function1():
return useless_import1.do()

def other_function2():
return useless_import2.do()

The code I've written (main.py) imports only my_function, but it still requires me to include/install the other useless modules. I've checked and none of the useless modules run any code on import, so I should be able to safely remove them.
"""main.py"""
from module import my_function

print my_function()

How do I best deal with this?

*

*Should I included the useless imports in my project anyway?

*Should I make a copy of module.py and edit it so that it only contains my_function and the right imports?

*Should I copy my_function and its imports into main.py?

*(some other option I didn't think/know of)?

A: It kind of depends on the context, e.g. how will this code be used later, who will maintain it, what kind of code is it realy etc etc.
But my suggestion under most circumstances would be:

*

*refactor my_function and its needed imports into a new_module.py

*use this module in main.py

*Either remove module.py from your code base, or have it import from new_module


text:
Q: How to store Pre-Shared keys securely? I Analyse possible implentation for storing Pre-Shared keys securely.
If data are encrypted by pre-shared keys, how to we store them in a securly on the client side?
Any idea?
I investigated but still don't have clue.