text:
Q: Recycle-view scrolling cause value change Recycle-view data loss focus when i scrolling view, My API and other things working fine and data change when i click on my adapter button but when i scroll my recyclview data its loss my changed data and back to the previous one.
My Code:
Activity:
  public void fetchNotification() {
    String Notification = "https://www.videobeaker.com/secure/assests/video-beaker-api/get-data.php?getPodiums=1";
    /*startAnim();*/
    StringRequest stringRequest = new StringRequest(Request.Method.GET, Notification, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            /*stopAnim();*/
          //  Log.e("podiums data", response);
            try {
                JSONObject jsonObject = new JSONObject(response);

                JSONArray jsonArray = jsonObject.getJSONArray("Podiums_data");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jobject = jsonArray.getJSONObject(i);
                    ComonPodium data = new ComonPodium();
                    data.setPodiumname(jobject.getString("podium_name"));
                    data.setPodium_description(jobject.getString("podium_description"));
                    data.setFollowers_data(jobject.getString("followers_data"));
                    data.setPodiumId(jobject.getString("podium_user_id"));
                   // data.setPodiumId(jobject.getString("podium_id"));
                    data.setPodium_cover_image(AppConstants.BASEIMG + jobject.getString("podium_cover_image"));
                    data.setPodium_image(AppConstants.BASEIMG + jobject.getString("podium_image"));
                    comonPodiums.add(data);
                }
                podiumAd.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
                showToast("No Record Found");
                //Toast.makeText(context,"No Record Found",Toast.LENGTH_SHORT).show();
            }

        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // Toast.makeText(getContext(), "Network Error,Please wait", Toast.LENGTH_SHORT).show();

        }
    });

    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(stringRequest);

}

Model Class:
public class ComonPodium {

public String getPodiumname() {
    return podiumname;
}

public void setPodiumname(String podiumname) {
    this.podiumname = podiumname;
}

public String getPodium_description() {
    return podium_description;
}

public void setPodium_description(String podium_description) {
    this.podium_description = podium_description;
}

public String getPodium_image() {
    return podium_image;
}

public void setPodium_image(String podium_image) {
    this.podium_image = podium_image;
}

public String getPodium_cover_image() {
    return podium_cover_image;
}

public void setPodium_cover_image(String podium_cover_image) {
    this.podium_cover_image = podium_cover_image;
}

public String getFollowers_data() {
    return followers_data;
}

public void setFollowers_data(String followers_data) {
    this.followers_data = followers_data;
}

private String podiumname;
private String podium_description;
private String podium_image;
private String podium_cover_image;
private String followers_data;

public String getPodiumId() {
    return podiumId;
}

public void setPodiumId(String podiumId) {
    this.podiumId = podiumId;
}

private String podiumId;

}
Adapter:
public class Podium_Ad extends RecyclerView.Adapter<Podium_Ad.ViewHolder> {
public static MyClickListener listener;
private List<ComonPodium> followingbean;
private Context context;

int poss;
String  podiumid1 ;

public Podium_Ad(Context context, List<ComonPodium> fproduct) {
    this.context = context;
    this.followingbean = fproduct;
}

@Override
public Podium_Ad.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.view_podiumitem, viewGroup, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(final Podium_Ad.ViewHolder viewHolder, final int i) {
    viewHolder.setIsRecyclable(false);

    viewHolder.podumname.setText(followingbean.get(i).getPodiumname());
    viewHolder.discription_tv.setText(followingbean.get(i).getPodium_description());
    viewHolder.followersCoount_tv.setText(followingbean.get(i).getFollowers_data());
    Picasso.with(context).load(followingbean.get(i).getPodium_cover_image()).placeholder(R.drawable.boy).into(viewHolder.userImage);
    Picasso.with(context).load(followingbean.get(i).getPodium_image()).placeholder(R.drawable.boy).into(viewHolder.coverimage);

}

@Override
public int getItemCount()
{
    return followingbean.size();
}

public void setMyClickListener(MyClickListener listener) {
    Podium_Ad.listener = listener;
}

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    private TextView podumname, discription_tv,followersCoount_tv, follow_tv;
    private ImageView userImage, coverimage;
    LinearLayout followunfollow;
    String unfollow, follower, followers_count;

    public ViewHolder(View view) {
        super(view);
        podumname = (TextView) view.findViewById(R.id.podiumname_txt);
        discription_tv = (TextView) view.findViewById(R.id.podumdiscripition_txt);
        followersCoount_tv = (TextView) view.findViewById(R.id.followercount_txt);
        userImage = (ImageView) view.findViewById(R.id.profile_image);
        coverimage = (ImageView) view.findViewById(R.id.coverImage);
        followunfollow = (LinearLayout)view.findViewById(R.id.userfoller);
        follow_tv = (TextView) view.findViewById(R.id.follow_btn);

        view.findViewById(R.id.profile_image).setOnClickListener(this);
        view.findViewById(R.id.podiumname_txt).setOnClickListener(this);
        view.findViewById(R.id.podumdiscripition_txt).setOnClickListener(this);
        view.findViewById(R.id.userfoller).setOnClickListener(this);

     followunfollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int s = getAdapterPosition();
                podiumid1 = followingbean.get(s).getPodiumId();
                // poss = getAdapterPosition();
                // podiumid1 = followingbean.get(poss).getPodiumId();
                Log.e("id ===>>>",podiumid1);
                System.out.println("podiumid_podiumid"+podiumid1 +"::"+poss);
                follow();
               // notifyDataSetChanged();
            }
        });

    }

    @Override
    public void onClick(View view) {
        listener.onItemClick(view, followingbean.get(getPosition()));
    }

    public void follow() {
        final String followurl = "https://www.videobeaker.com/secure/assests/video-beaker-api/get-data.php?follow=1";

        System.out.println("podiumid_podiumid"+podiumid1 +"::"+poss);
        Log.e("followurl", followurl);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, followurl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                try {
                    JSONObject jsonObject = new JSONObject(response);

                    Log.e("follow_response", response);

                    follower = jsonObject.getString("response");
                    unfollow = jsonObject.getString("response");
                    followers_count = String.valueOf(jsonObject.getInt("total_follow_count"));

                    if (follower.equalsIgnoreCase("1")) {
                        follow_tv.setText("Unfollow");
                        followersCoount_tv.setText(followers_count);

                    } else if (unfollow.equalsIgnoreCase("2")) {

                        unfollow();

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("error", "Error: " + error.getMessage());

            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("login_user_id", AppController.getInstance().getKeyString(AppConstants.USERID));
                params.put("podium_id", podiumid1);
                params.put("timezone", "Asia/kolkata");
                Log.e("all_param,", String.valueOf(params));

                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest);

    }

    public void unfollow() {
        final String recentupload = "https://www.videobeaker.com/secure/assests/video-beaker-api/get-data.php?unfollow=1";

        System.out.println("podiumid_podiumid"+podiumid1);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, recentupload, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                try {

                    JSONObject jsonObject = new JSONObject(response);
                    Log.e("unfollow", response);
                    unfollow = jsonObject.getString("response");
                    followers_count = String.valueOf(jsonObject.getInt("total_follow_count"));
                    //  followersCoount_tv.setText(followers_count);
                    if (unfollow.equalsIgnoreCase("1")) {
                        follow_tv.setText("Follow");
                        followersCoount_tv.setText(followers_count);

                    } else if (unfollow.equalsIgnoreCase("2")) {
                        follow();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("error", "Error: " + error.getMessage());

            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("login_user_id", AppController.getInstance().getKeyString(AppConstants.USERID));
                params.put("podium_id",podiumid1);
                params.put("timezone", "Asia/kolkata");

                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest);

    }

}

}
My xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="geek.vediobeaker.fragment.Following_Fragment">

<android.support.v7.widget.RecyclerView
    android:id="@+id/notification_recycler"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="@dimen/_10sdp"
    android:minHeight="@dimen/_120sdp" />

Can anyone say me how do I get the my scoll data correctly?

A: Add click listener in onBindViewHolder method
 @Override
public void onBindViewHolder(final Podium_Ad.ViewHolder viewHolder, final int i) {
ComonPodium comomPodium = followingbean.get(i);
viewHolder.setIsRecyclable(false);

viewHolder.podumname.setText(comomPodium.getPodiumname());
viewHolder.discription_tv.setText(comomPodium.getPodium_description());
viewHolder.followersCoount_tv.setText(comomPodium.getFollowers_data());
Picasso.with(context).load(comomPodium.getPodium_cover_image()).placeholder(R.drawable.boy).into(viewHolder.userImage);
Picasso.with(context).load(comomPodium.getPodium_image()).placeholder(R.drawable.boy).into(viewHolder.coverimage);

viewHolder.followunfollow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int s = getAdapterPosition();
            podiumid1 = followingbean.get(s).getPodiumId();
            // poss = getAdapterPosition();
            // podiumid1 = followingbean.get(poss).getPodiumId();
            Log.e("id ===>>>",podiumid1);
            System.out.println("podiumid_podiumid"+podiumid1 +"::"+poss);
            follow(comomPodium);
        }
    });
 }

In you follow method update ComonPodium on successful API call result
public void follow(ComonPodium comonPodium) {
    final String followurl = "https://www.videobeaker.com/secure/assests/video-beaker-api/get-data.php?follow=1";

    System.out.println("podiumid_podiumid"+podiumid1 +"::"+poss);
    Log.e("followurl", followurl);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, followurl, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {
                JSONObject jsonObject = new JSONObject(response);

                Log.e("follow_response", response);

                follower = jsonObject.getString("response");
                unfollow = jsonObject.getString("response");
                followers_count = String.valueOf(jsonObject.getInt("total_follow_count"));

                if (follower.equalsIgnoreCase("1")) {
                    follow_tv.setText("Unfollow");
            //Here you need to to update model class///
                     comonPodium.setFollowDate("your response data")
                    followersCoount_tv.setText(followers_count);

                } else if (unfollow.equalsIgnoreCase("2")) {

                    unfollow();

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("error", "Error: " + error.getMessage());

        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("login_user_id", AppController.getInstance().getKeyString(AppConstants.USERID));
            params.put("podium_id", podiumid1);
            params.put("timezone", "Asia/kolkata");
            Log.e("all_param,", String.valueOf(params));

            return params;
        }

    };

    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(stringRequest);

}

A: add this method in adapter , call podiumAd. setDatalist(comonPodiums) and remove podiumAd.notifyDataSetChanged();
 public void setDatalist(List< ComonPodium > list) {

                followingbean = list;

                notifyDataSetChanged();

            }


text:
Q: Django-CSRF: CSRF verification failed. Request aborted when click on login button I am trying to build a simple website where one can add data into MySQL database. I have a POST form with two text input(username, password). I have read all the related answer and tried to solve it but could not succeed.
index.html
<form action="/login/" method="post">{% csrf_token %}

    Username:
    <input type="text" class="text-box" value="{{ username }}" placeholder="Username"/>

    Password:
    <input type="password" class="text-box" value="" placeholder="Password"/>

    forget-link">Forget Your Passowrd?

views.py
def login(request):

    logout(request)
    username = password = ''
    if request.method :
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/main/')
    return render(request, 'index.html',{ 'username': username})

urls.py
urlpatterns = patterns('',

    url(r'^login/', 'mysite.views.login', name='login'),
)

I have applied {% csrf_token %} after form tag in index.html.
When I click on Login button, I have the below error:
CSRF verification failed. Request aborted.

A: The problem is that you're using the tag {% csrf_token %} in your template but you had not generated the token previously in the view so the template doesn't know anything about it.
Following the docs you have two options:
The first solution:

Use RequestContext, which always uses
  'django.core.context_processors.csrf' (no matter what your
  TEMPLATE_CONTEXT_PROCESSORS setting). If you are using generic views
  or contrib apps, you are covered already, since these apps use
  RequestContext throughout.

So you have to change the code in your view like this:
def login(request):
    logout(request)
    username = password = ''
    if request.method :
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/main/')

    template = loader.get_template('index.html')
    context = RequestContext(request,{ 'username': username})
    return HttpResponse(template.render(context))

The second solution:

Manually import and use the processor to generate the CSRF token and
  add it to the template context. e.g.:

And your code should be (as mcniac told you):
def login(request):
    logout(request)
    username = password = ''
    if request.method :
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/main/')
    context = { 'username': username}
    context.update(csrf(request))
    return render(request, 'index.html',)

A: I think you need to apply the csrf to your context, your view would endout like this
from django.shortcuts import render_to_response
from django.core.context_processors import csrf

def login(request):

    logout(request) # not sure what this function is, I guess must be on some part of your code
    if request.method == "POST" :
        username = request.POST['username'] or ''
        password = request.POST['password'] or ''
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/main/')
    context = { 'username': username, }
    context.update(csrf(request))
    return render_to_response(request, 'index.html', context)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I specify a return type of my derived object in MustOverride function? I am wanting to create a MustOverride Function in a MustInherit Class that would have a return type of the derived class.  I'll try to illustrate below...
Public MustInherit Class ModelBase
   Public MustOverride Function FindByUniqueAttributes() As _______
End Class

Public Class Person
   Inherits ModelBase

   Public Overrides Shared Function FindByUniqueAttributes() As _______
       ' ...
   End Function
End Class

With the setup above how should I go about filling in the blanks I've provided for the return types?  I want the derived class to contain it's own type as the return type.
Update
Public Overrides Function SaveChanges() As Integer
    For Each e In Me.ChangeTracker.Entries
        If e.State = EntityState.Added Then
            Dim mb = DirectCast(e.Entity, ModelBase) ' Erroring out after changes

            mb.CreatedAt = DateTime.Now
            mb.UpdatedAt = DateTime.Now
        End If
        If e.State = EntityState.Modified Then
            Dim mb = DirectCast(e.Entity, ModelBase) ' Erroring out after changes

            mb.UpdatedAt = DateTime.Now
        End If
    Next

    Return MyBase.SaveChanges()

End Function

A: As stated in my comment:

"A Shared member can never be Overridable."

With that being said you might want to use a generic type in your ModelBase. Something like this:
Public MustInherit Class ModelBase

    Public Shared Function FindByUniqueAttributes(Of TEntity)() As TEntity
    End Function

End Class

Or this:
Public MustInherit Class ModelBase(Of TEntity)

    Public MustOverride Function FindByUniqueAttributes() As TEntity

End Class

Public Class Person
    Inherits ModelBase(Of Person)

    Public Overrides Function FindByUniqueAttributes() As Person
    End Function

End Class


text:
Q: Get data in controller ( laravel ) from mongodb model and pass it to view I use jeremykenedy/laravel-auth
User is stored in postgres.
Position_info is stored in mongo.
need to get a document from mongo with user_id == $user->getAttribute('id')
In controller (UsersManagementController.php)
    ...
public function show(User $user)
{
    $position = Position_info::where('user_id', $user->getAttribute('id'));
    echo '<pre>';
    echo 'The Position ID is: '. $position->_id;
    echo '</pre>';
    return view('usersmanagement.show-user', compact('user'))->with('position', $position);;
}
    ...

Position_info.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class Position_info extends Eloquent
{
    protected $connection = 'mongodb';
    protected $collection = 'position_infos';

    protected $fillable = [
        'user_id', 'position', 'experience', 'additional_info'
    ];
}

routes from there
https://github.com/jeremykenedy/laravel-auth/blob/master/routes/web.php
What is displayed on the view
error: Property [_id] does not exist on the Eloquent builder instance.

A: Try this one.
$position = Position_info::where('user_id', $user->getAttribute('id'))->get()->toArray();

Then to get the _id use this:
echo 'The Position ID is: '. $position[0]['_id'];


text:
Q: LINQ expression instead of nested foreach loops I have these  two clases:
public class Client{
    public List<Address> addressList{get;set;}
}

public class Address{
    public string name { get; set; }
}

and I have a List of type Client called testList. It contains n clients and each one of those contains n addresses
List<Client> testList;

how can i do the following using LINQ:
foreach (var element in testList)
{
    foreach (var add in element.addressList)
    {
        console.writeLine(add.name);
    }
}

A: Well I wouldn't put the Console.WriteLine in a lambda expression, but you can use SelectMany to avoid the nesting:
foreach (var add in testList.SelectMany(x => x.addressList))
{
    Console.WriteLine(add.name);
}

I see little reason to convert the results to a list and then use List<T>.ForEach when there's a perfectly good foreach loop as part of the language. It's not like you naturally have a delegate to apply to each name, e.g. as a method parameter - you're always just writing to the console. See Eric Lippert's blog post on the topic for more thoughts.
(I'd also strongly recommend that you start following .NET naming conventions, but that's a different matter.)

A: foreach(var a in testList.SelectMany(c => c.addressList))
{
    Console.WriteLine(a.name);
}

It will not materialize any new collection.

A: This may helps:
testList.ForEach(i => i.addressList.ForEach(j => Console.WriteLine(j.name)));

A: foreach(var add in testList.SelectMany(element => element.addressList)){
    Console.WriteLine(add.name);
}

A: testList.SelectMany(c => c.addressList)
        .Select(a => a.name)
        .ToList()
        .ForEach(Console.WriteLine)

A: Use the ForEach method:
testList.ForEach(tl=>tl.addressList.ForEach(al=>console.writeLine(al.name)));

A: LINQ doesn't include a ForEach function, and they don't intend to, since it goes against the idea of LINQ being functional methods. So you can't do this in a single statement. List<T> has a ForEach method, but I'd recommend not using this for the same reasons that it's not in LINQ.
You can, however, use LINQ to simplify your code, e.g.
foreach (var add in testList.SelectMany(x => x.addressList))
{
    Console.WriteLine(add.name);
}
// or
foreach (var name in testList.SelectMany(x => x.addressList).Select(x => x.name))
{
    Console.WriteLine(name);
}


text:
Q: How do I find a rogue keyboard shortcut? Sometimes, I highlight text in an MS Word document and wish to add a comment about it to send to a co-author.  Following this official documentation about keyboard shortcuts (in the "Review documents" section), I then press Alt+Ctrl+M as the keyboard shortcut to insert a comment.  I usually use the modifier keys on the right side of the keyboard because they're close to the M and I can easily cover all three with the hand that didn't just use the mouse to select that text.  To within human perception time, I often press both modifier keys simultaneously, before the M (so I don't type an m).
However, about half the time, instead of inserting a comment, the highlighted text is deleted and replaced with a lowercase mu character (µ).  After years of being unable to figure out the pattern, I have finally found that on the right side of the keyboard, if I press Alt+Ctrl+M (with the Alt key going down first) I get the µ, and if I press Ctrl+Alt+M (with the Ctrl key going down first), I get the comment.  If I use the modifier keys on the left side of the keyboard, the order doesn't matter and I get the comment either way.
When I right click on the Ribbon and choose "Customize the Ribbon"→"Keyboard Shortcuts,"  I can see that the shortcut to insert a comment is listed as Alt+Ctrl+M:

Although the modifiers are listed in the wrong order, this matches the Office documentation.
When I go to the Insert→Symbol→More Symbols dialog, it says the shortcut key assigned to the mu character is Alt+X, nothing like Alt+Ctrl+M:

EDIT (thanks to Jonno for these questions): My Windows keyboard layout is US English.  The Ctrl key can be omitted in the right-side-Alt+M combination and I still get the µ character.  However, right-side-Alt+M (with or without Ctrl) does NOT produce the µ character in other Windows applications such as Notepad, WordPad, Firefox, or Chrome.  Therefore, I am doubting the "system keyboard mapping" theory (thanks Jonno!) that previously seemed promising.
There may have been some time in the past where I needed to type a lot of µ characters, but that time is not the present, and it's annoying to accidentally delete some portion of a document and replace it with an unexpected character, especially after most proofreading checks have taken place and shortly before that document is formally submitted.
Why am I getting µ characters for Alt+Ctrl+M or Alt+M (but only with right side modifiers, and not for Ctrl+Alt+M), and how do I get rid of this behavior?

A: AltGr+M, according to various online sources (I can't test it as my keyboard hasn't got AltGr) is the keyboard shortcut, with a lot of keyboard layouts, for the µ symbol (see here).

In terms of disabling this, one solution from here is to add the following registry key, to treat AltGr as the standard Alt:
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout]
"Scancode Map"=hex:00,00,00,00,00,00,00,00,02,00,00,00,38,00,38,e0,00,00,00,00

Alternately there is software called "SharpKeys" that will set this for you.
One other option is to use the Microsoft Keyboard Layout Creator to change your keyboard mappings and remove this particular shortcut. Some information on the usage of this can be found here.

A: Heads up: This is still just a partial answer.
In the "Insert Symbol" dialogue, pressing a keyboard shortcut of interest takes you to the character that would be inserted had you pressed that in the document.  (Here, it works even when putting the Ctrl key down first.)  This is a helpful tip for tracking down the rogue shortcut.
As it turns out, there is another character called the "Micro Sign" which is visually identical to the Greek Small Letter Mu.  This key has a baked-in assigned shortcut key of Alt+Ctrl+M as well, but if you click on "Shortcut Key…", it doesn't show up in the (empty) list of keyboard shortcuts:

Assigning an alternative shortcut causes the new shortcut to appear in place of Alt+Ctrl+M next to "Shortcut key" and in the list of "Current keys" as expected.  Unfortunately, it does not displace the Alt+Ctrl+M "functionality" of inserting µ, and if you remove the new shortcut the Alt+Ctrl+M shortcut key reappears next to "Shortcut key" but not in the list of Current keys (i.e., it's a return to the state shown above).


text:
Q: VBA - Remove Brackets {} from GUID Hi I just implemented the new fix for generating GUID codes after the microsoft update. I am very new with VBA, could you help me with removing the {} curly brackets generated with the GUID from the below code please.
 Private Type GUID_TYPE
            Data1 As Long
            Data2 As Integer
            Data3 As Integer
            Data4(7) As Byte
End Type
Private Declare PtrSafe Function CoCreateGuid Lib "ole32.dll" (guid As GUID_TYPE) As LongPtr
Private Declare PtrSafe Function StringFromGUID2 Lib "ole32.dll" (guid As GUID_TYPE, ByVal lpStrGuid As LongPtr, ByVal cbMax As Long) As LongPtr
Public Function GetGUID()
            Dim guid As GUID_TYPE
            Dim strGuid As String
            Dim retValue As LongPtr
            Const guidLength As Long = 39 'registry GUID format with null terminator {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}

            retValue = CoCreateGuid(guid)
            If retValue = 0 Then
                            strGuid = String$(guidLength, vbNullChar)
retValue = StringFromGUID2(guid, StrPtr(strGuid), guidLength)
                            If retValue = guidLength Then

GetGUID = strGuid
                            End If
            End If

End Function

A: Edited this line.
GetGUID = Replace(Replace(strGuid, "{", ""), "}", "")

A: Simply use Mid to remove the first and last character.
You could also use an array of bytes to hold the guid and the result string.
To generate a GUID:
Private Declare PtrSafe Function CoCreateGuid Lib "ole32.dll" (pguid As Byte) As Long
Private Declare PtrSafe Function StringFromGUID2 Lib "ole32.dll" (rguid As Byte, lpsz As Byte, ByVal cchMax As Long) As Long

Public Function GenerateGUID() As String
  Dim pguid(0 To 15) As Byte, lpsz(0 To 77) As Byte

  CoCreateGuid pguid(0)
  StringFromGUID2 pguid(0), lpsz(0), 39
  GenerateGUID = Mid$(lpsz, 2, 36)
End Function


text:
Q: Stopping previous item in RecyclerView MediaPlayer I have a RecyclerView in which each item contains a button that plays sound from online url.
The problem is that I don't want the items to play sound at the same time and when you click on different sound, the previous one gets off but I don't know how can I do that ?
I would be appreciate if you could guide me through this problem
public class VersionAdapter3 extends RecyclerView.Adapter<VersionAdapter3.VersionViewholder> {

Context context;
List<Version3> versionsList;
final Mediaplayer mediaplayer=new Mediaplayer();

public VersionAdapter3(Context context, List<Version3> versionsList) {
    this.context = context;
    this.versionsList = versionsList;

}

  @NonNull
@Override
public VersionViewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.raw3,parent,false);
    return new VersionViewholder(view);
}

@Override
public void onBindViewHolder(@NonNull VersionViewholder holder, int position) {
    Version3 version3 = versionsList.get(position);
    holder.codeNameTxt.setText(version3.getCodeName());
    holder.versionTxt.setText(version3.getVersion());
    holder.descriptiontxt.setText(version3.getDescription());

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
   try {
        mediaPlayer.reset();
        mediaPlayer.setDataSource(version3.getSong());
    } catch (IOException e) {
        e.printStackTrace();
    }

    mediaPlayer.prepareAsync();

    boolean isExpandable = versionsList.get(position).isExpandable();
    holder.expandableLayout.setVisibility(isExpandable ? View.VISIBLE : View.GONE);

   holder.btnplay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (mediaPlayer!=null) {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    version3.setIsplaying(false);

                }

            }
            try {

                            if (holder.btnplay.getText().toString().equals("pause")) {
                                mediaPlayer.pause();
                                version3.setIsplaying(false);
                                holder.btnplay.setText("play");

                            }

                        else {

                             holder.btnplay.getText().toString().equals("play");
                                mediaPlayer.start();
                                holder.btnplay.setText("pause");
                                version3.setIsplaying(true);
                            }

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

                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        holder.btnplay.setText("play");
                    }
                });

            }

    });

}
@Override
public int getItemCount() {
    return versionsList.size();
}

public class VersionViewholder extends RecyclerView.ViewHolder {

    TextView codeNameTxt, versionTxt, descriptiontxt;
    LinearLayout linearLayout;
    RelativeLayout expandableLayout;
    Button btnplay;
    public VersionViewholder(@NonNull View itemView) {

        super(itemView);
   codeNameTxt = itemView.findViewById(R.id.codename);
        versionTxt = itemView.findViewById(R.id.version);
        descriptiontxt = itemView.findViewById(R.id.description);
        btnplay = itemView.findViewById(R.id.track_play);
        linearLayout = itemView.findViewById(R.id.linear);
        expandableLayout = itemView.findViewById(R.id.expandable);

        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
           public void onClick(View view) {
                Version3 version3 = versionsList.get(getAdapterPosition());
                version3.setExpandable(!version3.isExpandable());
                notifyItemChanged(getAdapterPosition());

            }
        });

    }
}

}
when i click on the each item it get expanded and previous sound gets off but the button still shows in pause mode not play mode and I don't want the sound gets off when I expand a new item and I want that it gets off when I click on the next button
just in a case that you pause previous button it works but I want automatically it gets off when I click new play button and the previous one gets completely off
I would be so grateful if you could help me to fix my code and show me how can I edit it

A: Here is an example:
The MainActivity class:
public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private VersionAdapter3 adapter;

    private List<Version3> generateVersionList() {
        List<Version3> versionsList = new ArrayList<>();
        versionsList.add(new Version3("codeName 01", "version 01", "Description 01", "https://storage.googleapis.com/2waytech-apagar/Just%20a%20Miracle%20Apart%20-%20Lost%20European.mp3", Version3.State.STOPPED));
        versionsList.add(new Version3("codeName 02", "version 02", "Description 02", "https://storage.googleapis.com/2waytech-apagar/Newspaper%20And%20Lace%20-%20Lost%20European.mp3", Version3.State.STOPPED));
        versionsList.add(new Version3("codeName 03", "version 03", "Description 03", "https://storage.googleapis.com/2waytech-apagar/The%20Man%20in%20the%20House%20of%20Cards%20-%20Lost%20European.mp3", Version3.State.STOPPED));
        return versionsList;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.list);

        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);

        adapter = new VersionAdapter3(generateVersionList());

        recyclerView.setLayoutManager(llm);
        recyclerView.setAdapter(adapter);
    }
}

The VersionAdapter3 class:
public class VersionAdapter3 extends RecyclerView.Adapter<VersionAdapter3.VersionViewHolder> {
    private final List<Version3> versionsList;
    private final MediaPlayer mediaPlayer;
    private Integer currentlyPlayingIndex = -1;

    public VersionAdapter3(List<Version3> versionsList) {
        this.versionsList = versionsList;
        this.mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(mediaPlayer -> {});
    }

    private void setupMediaPlayer() {
        mediaPlayer.setOnPreparedListener(MediaPlayer::start);
        mediaPlayer.setAudioAttributes(
                new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .build()
        );
    }

    private void onPlayBtnTapped(int newIndex) {

        if(newIndex != currentlyPlayingIndex && currentlyPlayingIndex != -1) {
            versionsList.get(currentlyPlayingIndex).setState(Version3.State.STOPPED);
            notifyItemChanged(currentlyPlayingIndex);
            mediaPlayer.stop();
        }

        if(newIndex == currentlyPlayingIndex) {
            if(mediaPlayer.isPlaying()) {
                versionsList.get(newIndex).setState(Version3.State.PAUSED);
                mediaPlayer.pause();
            }
            else {
                versionsList.get(newIndex).setState(Version3.State.PLAYING);
                mediaPlayer.start();
            }

        } else {

            try {
                currentlyPlayingIndex = newIndex;
                Version3 version = versionsList.get(newIndex);
                String dataSource = version.getSong();
                version.setState(Version3.State.PLAYING);
                mediaPlayer.reset();
                mediaPlayer.setDataSource(dataSource);
                mediaPlayer.prepareAsync();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        notifyItemChanged(newIndex);
    }

    @Override
    public void onViewAttachedToWindow(@NonNull VersionViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        setupMediaPlayer();
    }

    @NonNull
    @Override
    public VersionViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.raw3, parent, false);
        return new VersionViewHolder(view);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull VersionViewHolder holder, int position) {

        Version3 version3 = versionsList.get(position);

        holder.codeNameTxt.setText(version3.getCodeName());
        holder.versionTxt.setText(version3.getVersion());
        holder.descriptiontxt.setText(version3.getDescription());
        holder.adjustBtnTextByState(version3.getState());
        holder.btnplay.setOnClickListener(view -> onPlayBtnTapped(position));
    }

    @Override
    public int getItemCount() {
        return versionsList.size();
    }

    public static class VersionViewHolder extends RecyclerView.ViewHolder {

        TextView codeNameTxt, versionTxt, descriptiontxt;
        Button btnplay;

        public VersionViewHolder(@NonNull View itemView) {
            super(itemView);
            codeNameTxt = itemView.findViewById(R.id.codename);
            versionTxt = itemView.findViewById(R.id.version);
            descriptiontxt = itemView.findViewById(R.id.description);
            btnplay = itemView.findViewById(R.id.track_play);
        }

        @SuppressLint("SetTextI18n")
        public void adjustBtnTextByState(Version3.State state) {
            switch (state) {
                case STOPPED:
                    btnplay.setText("stopped");
                    break;
                case PLAYING:
                    btnplay.setText("playing");
                    break;
                case PAUSED:
                    btnplay.setText("paused");
                    break;
            }
        }
    }

}

The Version3 class
public class Version3 {

    private String codeName;
    private String version;
    private String description;
    private String song;
    private State state;

    public Version3(String codeName, String version, String description, String song, State state) {
        this.codeName = codeName;
        this.version = version;
        this.description = description;
        this.song = song;
        this.state = state;
    }

    public String getCodeName() {
        return codeName;
    }

    public void setCodeName(String codeName) {
        this.codeName = codeName;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getSong() {
        return song;
    }

    public void setSong(String song) {
        this.song = song;
    }

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
    }

    public enum State {
        STOPPED, PLAYING, PAUSED
    }
}

The main_activity.xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

And the raw3.xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/codename"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="codename"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth="match_parent" />

    <TextView
        android:id="@+id/version"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:text="version"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/codename"
        app:layout_constraintWidth="match_parent" />

    <TextView
        android:id="@+id/description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:text="description"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/version"
        app:layout_constraintWidth="match_parent" />

    <Button
        android:id="@+id/track_play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="stop"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/description" />

</androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: How to limited the countries list in npm react-phone-number-input package when react-phone-number-input use this npm package i want to allow limited countries show in dropdown if user enter other country which is not in list it display error not allow this country there is no prop where i limit the countries

A: If you take a look at the docs here you'll see you can add a countries prop to the component, and provide it with an array of strings. Their example shows this array:
["RU", "UA", "KZ"]

This would limit the list of countries to just those 3.

A: Build a custom array of countries and then use the parseNumber function from libphonenumber-js library and get the country code from the user input number and compare it of your country list

A: To achieve this first create list of countries that you want to show in dropdown. Then on Blur run the validation if you want.
const whitelisted_conutries = ['WS',  'SB',  'TK',  'TO',  'TV',  'VU',  'WF',  'HK']:

then pass this to countries prop of PhoneInput like so,
import { isValidPhoneNumber } from 'react-phone-number-input';

      <PhoneInput
       defaultCountry="GB"
       flagUrl={'https://flag.pk/flags/4x3/{xx}.svg'}
       countries={whitelist}
       value={phone}
       onChange={(phone) => setState({ phone })}
       onBlur={() =>
       setState({
              hasEnterPhone: true,
              error: {
                ...error,
                phone: !phone
                  ? ''
                  : !isValidPhoneNo(phone) &&
                    'Please enter a valid mobile phone number.',
              },
            })
          }
        />

For more info on supported props refer developers docs tagged by @jamie in thread: Docs


text:
Q: How do I update my access token with a refresh token in msal? I used B2C and MSAL to configure the SPA certification.
Then, the backend API access token, refresh token, and ID token are obtained from B2C and stored in localstorage.
However, after about an hour I noticed that the access token was disabled.
At this time, I believe I can use a refresh token to update my access token.
I am a beginner and would be grateful if you could give me a sample or something.
Thank you in advance.

A: MSAL takes care of refresh token for you.
What you should do is always ask a token from MSAL before using one.
If it needs to refresh it using a refresh token, it will just do that behind the scenes.
You can see an example here: https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-spa-acquire-token.
There it shows a general pattern where you first try acquireTokenSilent, and if that fails, use a popup/redirect to get new tokens.


text:
Q: PHP - regex to allow unicode charcaters I was using the following regex with preg_replace to filter inputs:
/[^A-Za-z0-9[:space:][:blank:]_<>=@#£€$!?:;%,.\\'\\\"()&+\\/-]/

However this does not allow accented characters like umlauts so I changed it to:
/[^\w[:space:][:blank:]_<>=@#$£€!?:;%,.\\'\\\"()&+\\/-]/u

This however does work with the £ or € characters, nothing is returned, but I need to accept these characters, I have tried escaping them but that doesn't work.
Also I want to create an regex that is similar to just A-Za-z but will allow accented characters, how can I do that?

A: From http://php.net/manual/en/reference.pcre.pattern.modifiers.php

u (PCRE_UTF8) This modifier turns on additional functionality of PCRE
  that is incompatible with Perl. Pattern and subject strings are
  treated as UTF-8. An invalid subject will cause the preg_* function to
  match nothing; an invalid pattern will trigger an error of level
  E_WARNING. Five and six octet UTF-8 sequences are regarded as invalid
  since PHP 5.3.4 (resp. PCRE 7.3 2007-08-28); formerly those have been
  regarded as valid UTF-8.

That means that first you have to make sure the input string is proper UTF-8 text.
Secondly, have you heard of unicode categories? If not, head to http://www.regular-expressions.info/unicode.html and search for Unicode categories. For example you could use \p{S} to match all currency symbols, or \p{L} for all letters. Your regex could (probably) be written as follows: /[^\p{L}\p{P}\p{N}\p{S}\p{M}]/.
This will though match pretty much nothing, as it allows pretty much all characters to be used - ^ at the start of a regex character class (something between [ and ]) means "everything that is not what is in this class will be matched".
On top of that, your regex will only match input that has a length of exactly one - if you want to match everything, you should begin adding a + after your closing ] to keep matching characters until the pattern fails.
So, for that sake, what exactly are you trying to achieve? Maybe we can suggest you some more regex improvements if we know what you're trying to do.


text:
Q: Custom page variable in OctoberCMS Is it possible to use custom page variable in Configuration section in OctoberCMS?
When I do this:
url = "/blog"
layout = "default"

custom_var = "value"
==
{{ custom_var }}

my custom_var is deleting when edit page from admin panel.

A: It seems this was the old way of defining all stuff in single view (visual representation)
now its divided in 3 portion
1st name and url(slug) then 2nd markup(html) section

3rd code section

so you can follow new way of declaring things and it should work
use code section add this
public function onStart() {
    $this['custom_var'] = 'some value';
}

use markup section and add this
<h1>{{ custom_var }}</h1>

it will work, still any issue please comment.

A: Yes, its possible to set custom variable into page. you can try the following code into the php section
function onEnd() {
    $this->page->custom_var = 'some data';
}

And then you can use this custom_var into your layout file like
{{ this.page.custom_var }}

A: If you want to define new variables inside markup you can use following syntax:
{% set custom_var = 'some data' %}


text:
Q: Error: TargetInvocationException in Sitecore I have installed a fresh (and clean) Sitecore 5.3.1 on a Windows 2003 server. Setup the DB (SQL) and given Network service full access to both data, databases and website folder.
When i enter the backend, i can login, view the menu etc., but almost all the time, whenever i try to do something, like installing a package, it just freezes up, and comes with and error (cannot be null for instance).
When i look in the eventviewer on the server i see this;
Exception type: TargetInvocationException
Exception message: Exception has been thrown by the target of an invocation.

Thread information:
    Thread ID: 1
    Thread account name: NT AUTHORITY\NETWORK SERVICE
    Is impersonating: False
    Stack trace:    at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Sitecore.Shell.Framework.Commands.MethodCommandProcessor.Invoke(PipelineArgs args)
   at Sitecore.Nexus.Pipelines.NexusPipelineApi.Resume(PipelineArgs args, Pipeline pipeline)
   at Sitecore.Pipelines.Pipeline.Resume()
   at Sitecore.Pipelines.Pipeline.DoStart(PipelineArgs args)
   at Sitecore.Pipelines.Pipeline.Start(PipelineArgs args, Boolean atomic)
   at Sitecore.Shell.Framework.Commands.MethodCommand.Execute(CommandContext context)
   at Sitecore.Web.UI.Sheer.ClientPage.Dispatch(String command)
   at Sitecore.Web.UI.Sheer.ClientPage.RaiseEvent()
   at Sitecore.Web.UI.Sheer.ClientPage.OnPreRender(EventArgs e)
   at System.Web.UI.Control.PreRenderRecursiveInternal()
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

I have no clue what it is i am missing?


text:
Q: Field belongs to a class, but how to use polymorphism I have a method in a base class
class Base
{
   private static string Colour = "blue";
   string DoStuff() { return ColourProp; }

   protected virtual string ColourProp { get{ return Base.Colour; } }
}

that is called on an instance of this subclass
class Sub
{
   private static string Colour = "orange";

   protected override string ColourProp { get{ return Sub.Colour; } }
}

At the moment I'm using virtual properties, is this the only way? (considering that fields cannot be virtual)...

A: Yes, you do need to use either a virtual property or a virtual method to accomplish this.  The  CLR will dynamically dispatch all calls to ColourProp correctly based on the type of the object (i.e. polymorphism).

A: This looks totally fine. Don't worry about virtual properties. This provides not only an encapsulation of your data against other objects but also against subclasses.


text:
Q: Python : How to assign ranks to categorical variables within a group in Python Given I have a dataset containing only the first two columns, how do I create another column using Python which will contain the rank based on these ranges for each group separately. My desired output would look like this -

id
range
rank

1
10-20
2

1
20-30
3

1
5-10
1

2
20-30
2

2
10-20
1

2

3
10-20
2

3
5-10
1

3
20-30
3

3
30+
4

NOTE - These are the only 4 ranges [5-10, 10-20, 20-30, 30+] that can belong to any id at max. There can be blanks as well For example as given in the reproducible example, if for id 2 there are two ranges 10-20 and 20-30 the corresponding to 10-20 the rank will be 1 and corresponding to 20-30 the rank will be 2. I have checked that df.groupby can be used but I am not being able to figure out how in this case.

A: Convert your range column to a category dtype before apply rank:
df['range'] = df['range'].astype(pd.CategoricalDtype(
                  ['5-10', '10-20', '20-30', '30+'], ordered=True))

df['rank'] = df.groupby('id')['range'].apply(lambda x: x.rank())

>>> df
   id  range  rank
0   1  10-20   2.0
1   1  20-30   3.0
2   1   5-10   1.0
3   2  20-30   2.0
4   2  10-20   1.0
5   2    NaN   NaN
6   3  10-20   2.0
7   3   5-10   1.0
8   3  20-30   3.0
9   3    30+   4.0


text:
Q: GWT.create(clazz) "generics" approach I have to develop an "generic" wigdet for a GWT/GXT project and to do so I need to create an instance of an object which type is unknown. I found an approach that works perfectly in dev mode but as soon as I try to compile my project and deploy it I get an Only class literals may be used as arguments to GWT.create() error.
Here is a sample of what I do:
public class GenericEditableGrid<M> extends Grid<M>{
    private final ToolBar toolBar = new ToolBar();
    private final TextButton newItemButton = new TextButton();
    protected GridInlineEditing<M> editing;
    private final Class<M> clazzM;

    public GenericEditableGrid(Class<M> parametrizedClass, String gridTitle, ListStore<M> listStore, ColumnModel<M> cm) {
        super(listStore, cm);
        clazzM = parametrizedClass;
        // ... then I create my widget
        bind();
    }
    private void bind(){
        newItemButton.addSelectHandler(new SelectEvent.SelectHandler() {
            @Override
            public void onSelect(SelectEvent selectEvent) {
                editing.cancelEditing();
                // it is the folliwing line which is the problem obviously
                M element = GWT.create(clazzM);
                getStore().add(0, element);
                int index = 0;
                editing.startEditing(new Grid.GridCell(getStore().indexOf(element), index));
            }

        });
    }
}

And this is how I use it in my subclasses:
super(InternationalString.class, gridTitle, new ListStore<InternationalString>(isprops.key()), buildColumnModel());

Basically, I would like to know what the problem is exactly with this approach and eventually how I should do to make it well.
Please note that my concern is not just to make it work, but more to do it the right way. As I could just avoid the problem using an abstract method which would handle the GWT.create() method in the daughter classes. But this is not the design I want, it just doesn't look right.
What I don't get also is what's the difference between doing this:
MyClass e = GWT.create(MyClass.class);

and:
Class<MyClass> clazz=MyClass.class;
MyClass e = GWT.create(clazz);

Because as far as I am concerned I think this is basically what I am doing and it looks like the same thing. Isn't it?

A: There's a well-worded explanation in this forum:

As the error message indicates, only class literals may be passed to the GWT.create method. The reason for this is that all GWT.create calls are basically turned into constructors at compile time, using the deferred binding rules for your module. As a result, all classes must be decided at compile time - your code requires that the at runtime the class is decided. This is too late, and so cannot be compiled.
GWT is not proper java, and so cannot be always treated as java. This is one such example of things that cannot be done in gwt. ...
What is it you are trying to do? Either you are making it far more complicated than it needs to be, or you need to write a generator to do it instead of taking this approach.


text:
Q: C Temperature Conversion Program Keeps Outputting 0 For Fahrenheit to Celsius My temperature conversion program in C keeps outputting 0 when I attempt to convert Fahrenheit to Celsius. The conversion from Celsius to Fahrenheit seems to work just fine. I have done the exact same thing for both functions and portions but I keep getting 0 for the second conversion. Can someone please help me or tell me what I am doing wrong?
#include <stdio.h>

//Function Declarations

float get_Celsius (float* Celsius);       //Gets the Celsius value to be converted.
void to_Fahrenheit (float cel);           //Converts the Celsius value to Fahrenheit and prints   the new value.
float get_Fahrenheit (float* Fahrenheit); //Gets the Fahrenheit value to be converted.
void to_Celsius (float fah);              //Converts the Fahrenheit value to Celsius and prints the new value.

int main (void)
{
   //Local Declarations
   float Fahrenheit;
   float Celsius;
   float a;
   float b;

   //Statements
   printf("Please enter a temperature value in Celsius to be converted to Fahrenheit:\n");
   a = get_Celsius(&Celsius);
   to_Fahrenheit(a);
   printf("Please enter a temperature value in Fahrenheit to be converted to Celsius:\n");
   b = get_Fahrenheit(&Fahrenheit);
   to_Celsius(b);

   return 0;
} //main

float get_Celsius (float* Celsius)
{
   //Statements
   scanf("%f", &*Celsius);
   return *Celsius;
}

void to_Fahrenheit (float cel)
{
   //Local Declarations
   float fah;

   //Statements
   fah = ((cel*9)/5) + 32;
   printf("The temperature in Fahrenheit is: %f\n", fah);
   return;
}

float get_Fahrenheit (float* Fahrenheit)
{
   //Statements
   scanf("%f", &*Fahrenheit);
   return *Fahrenheit;
}

void to_Celsius (float fah)
{
   //Local Declarations
   float cel;

   //Statements
   cel = (fah-32) * (5/9);
   printf("The temperature in Celsius is: %f\n", cel);
   return;
}

A: cel = (fah-32) * (5/9);

Here, 5/9 is integer division, its result is 0, change it to 5.0/9

And in several lines, you are using
scanf("%f", &*Celsius);

&* is not necessary, simply scanf("%f", Celsius); would do.

A: cel = (fah-32) * (5/9);

5/9 is int/int and will give you results in int so that is 0.
Change it to
cel = (fah-32) * (5.0/9.0);

or
cel = (fah-32) * ((float)5/(float)9);


text:
Q: Labels are not showing in QGIS The coastline (the data I'm using) is including the small islands (Tarakan and Laut), I wanted to create two labels for these islands. The attribute table itself doesn't have specific names, so for this, I inserted a column named name_hoel in the attribute table, after setting, it shows me only the 'Laut', but NOT 'Tarakan'.
What shall I do to make both islands name appear? (at a scale 25 Mio.)
Layer Properties>Labels>Rendering and the box says: "Show all labels for this layer (including colliding labels)"---- checked! but it is still not showing.
image: 1) coastline with wanted islands (in yellow)

*it should look like this (please ignore its color):

*Layer Properties: 'placement' and 'rendering'


text:
Q: SPFx packages are referencing older versions I have created a new solution with option SharePoint 2016 onwards, including 2019 and SharePoint online. Then I have added a web part and did the gulp serve.
I got below error:

Now I checked the package.json file then it is showing as below.
"dependencies": {
    "@microsoft/generator-sharepoint": "^1.8.2",
    "@microsoft/sp-core-library": "~1.1.0",
    "@microsoft/sp-lodash-subset": "~1.1.0",
    "@microsoft/sp-office-ui-fabric-core": "~1.4.0-0",
    "@microsoft/sp-webpart-base": "~1.1.0",
    "@types/es6-promise": "0.0.33",
    "@types/react": "0.14.46",
    "@types/react-addons-shallow-compare": "0.14.17",
    "@types/react-addons-test-utils": "0.14.15",
    "@types/react-addons-update": "0.14.14",
    "@types/react-dom": "0.14.18",
    "@types/webpack-env": "1.13.1",
    "react": "15.4.2",
    "react-dom": "15.4.2"
  },
  "resolutions": {
    "@types/react": "0.14.46"
  },
  "devDependencies": {
    "@microsoft/sp-build-web": "~1.1.0",
    "@microsoft/sp-module-interfaces": "~1.1.0",
    "@microsoft/sp-webpart-workbench": "~1.1.0",
    "gulp": "~3.9.1",
    "@types/chai": "3.4.34",
    "@types/mocha": "2.2.38",
    "ajv": "~5.2.2"
  }

it is referencing older sharepoint framework packages. I have done so many solutions in my machine earlier. I am not sure whats wrong I have done here.
Update: I have tried to update the framework version as npm install -g @microsoft/generator-sharepoint, but nothing is updating in package.json file
Can anyone suggest me!!


text:
Q: How exactly do I compile my Java into a JAR file? So I'm trying to compile my game for my Object-Oriented Programming class into a jar file so it can be ran with java -jar javacoffeeadventure.jar.
My folder structure for a folder with java files removed looks like this:
audiomanager/
commandinterpreter/
gamemanager/
io/
logic/
META-INF/
player/
resources/
rooms/
main.class

Everything is packaged under javacoffeeadventure. For example, the main file is javacoffeeadventure.main. The META-INF folder contains one MANIFEST.MF file that I tried to edit and make the jar invoke main.class's main() method:
Manifest-Version: 1.0
Created-By: 1.8.0_60 (Oracle Corporation)
Main-Class: javacoffeeadventure.main

I know I use jar to compile into a jar file, but how would I use that command to create a jar file that is able to begin with javacoffeeadventure.main? Is my manifest wrong?
as a slight by-the-way, jar puns are funny to me if you guys have any. :)

A: In my experience, the following has worked, but if you utilize it, you may need to adapt your directory structure.
First, your folder structure needs to be of the form 'containing_folder.com.example.package', where your classes are in the 'package' folder.  You need to then place your manifest.mf file in the uppermost directory ('folder').  The manifest file should be as follows:
 Manifest-Version: 1.0
 Main-Class: com/example/package/javacoffeeadventure

including a carriage return after the second line.
From the initial folder compile with the following command:
jar cmvf manifest.mf javacoffeeadventure.jar com/example/package/*.class

making sure that beforehand you've compiled the classes in your package (use *.java)
Hope this helps.


text:
Q: How to start a new project with MEAN and sails.js I have created a web app with node.js, express, and angular.js in the past.  I am starting a new project and I want to also use MongoDB.  That would be the MEAN stack.  Using just MEAN, I could start a project with this: http://mean.io/.
Now, I have written REST API's in the past and I have heard about sails.js which sounds very compelling.  It can automatically create REST API's for you.
So my question is, what steps would I follow to start a new project with the MEAN stack AND sails.js?
Options:

*

*Would I clone the mean.io stack, run the npm install and then also npm install sails.js?

*Or, it seems like sails.js has it's own idea of what to do for a directory structure.  So would I install sails.js as per their instructions http://sailsjs.org/#!getStarted and then npm install Angular and Mongo?  (I think I would not need Mongoose since sails.js has its own ORM, waterline).

I am actually going to try option 2 today, but I would be very glad to know what steps have worked for others.
Thank you very much!

A: You are on the right path with npm install -g sails and sails new myproj. Since you want to use mongo, you will need to install the waterline adapter for mongo (in project dir) npm install sails-mongo --save and configure sails to use mongo.
Add the mongo config to the config/adapters.js file:
module.exports.adapters = {
  'default': 'mongo',

  mongo: {
    module   : 'sails-mongo',
    host     : 'localhost',
    port     : 27017,
    user     : 'username',
    password : 'password',
    database : 'your mongo db name here',

    // OR
    module   : 'sails-mongo',
    url      : 'mongodb://USER:PASSWORD@HOST:PORT/DB',

    // Replica Set (optional)
    replSet: {
      servers: [
        {
          host: 'secondary1.localhost',
          port: 27017 // Will override port from default config (optional)
        },
        {
          host: 'secondary2.localhost',
          port: 27017
        }
      ],
      options: {} // See http://mongodb.github.io/node-mongodb-native/api-generated/replset.html (optional)
    }
  }
};

Additionally, to create your API, (in the project dir) use sails generate NAME where NAME is the name of the model.  By default, anything can be added to the database, so you may want to limit the properties/fields and possibly even validate them.  Its easy.  The generate command created a few files for you, one of which is models/NAME.js.  In this file you can simply export an object with the attributes corresponding to the field you want and any restrictions/validations you want to happen before its saved.
// Person.js
var Person = {
  attributes: {
    firstName: 'STRING',
    lastName: 'STRING',
    age: {
      type: 'INTEGER',
      max: 150,
      required: true
    }
    birthDate: 'DATE',
    phoneNumber: {
      type: 'STRING',
      defaultsTo: '111-222-3333'
    }
    emailAddress: {
      type: 'email', // Email type will get validated by the ORM
      required: true
    }
  }
};

module.exports = Person;

This page lists all of the different types and validations you can have.
Once you are all set up, run sails lift to start your server.  The default port is 1337, but you can change that with the PORT env var or in your local configs
module.exports = {
    port: 80
    // ... more config things
}

Also, as for the 'A' in MEAN, check out Angular Sails.  Its a small angular service to let you easily take advantage of the socket.io things that sails is doing for you.  You can call all of your APIs over the socket connection to make them even lighter and faster.
In this case $sails replaces $http
app.controller("FooController", function ($scope, $sails) {
    $scope.bars = [];

    $sails.get("/bars", function (data) {
      $scope.bars = data;
    });
});

A: There's an awesome boilerplate project here that uses react.js instead of angular: https://github.com/lynnaloo/yacht-rock.


text:
Q: How can I search a word after selecting it in visual mode in Vim? Suppose I have selected a word in visual mode.
Now I want to search that word in the document.
How can I do that?
Thanks in advance.

A: If it's just a single word, you don't even have to select it. Just place the cursor on the word and press * (or # to search backwards). Note that this search will only match the whole word. To allow a search for foo to match foobar, use g* or g#.

A: Press y (you'll exit from visual mode after that) then press / Ctrl+r then " end hit enter.
You can use it to bind // for this action:
:vmap // y/<C-R>"<CR>

If you select special chars you better use this
:vmap <silent> // y/<C-R>=escape(@", '\\/.*$^~[]')<CR><CR>

A: I recommend https://github.com/thinca/vim-visualstar because you can use * for searching but with some selections you can run into problems.

A: I have this in my ~/.vimrc:
" Search for visually-selected text, forwards or backwards.
vnoremap <silent> * :<C-U>
  \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
  \gvy/<C-R><C-R>=substitute(
  \escape(@", '/\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR><CR>
  \gV:call setreg('"', old_reg, old_regtype)<CR>
vnoremap <silent> # :<C-U>
  \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
  \gvy?<C-R><C-R>=substitute(
  \escape(@", '?\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR><CR>
  \gV:call setreg('"', old_reg, old_regtype)<CR>


text:
Q: Speed of a simple operation over a long list What is the fastest procedure for counting elements smaller than 0.5 in a large list?
For example let
list=RandomReal[1, 10000000];

For a number of elements less than 0.5
Length[Select[list, # < 0.5 &] ] // Timing

{6.20313, 4996170}

Count[list, _?(# < 0.5 &)] // Timing

{7.75, 4996170}

Total[Table[Boole[list[[k]] < 0.5] // N, {k, 1, Length[list]}]] // Timing

{3.5625, 4.99617*10^6}

Total[(Sign[list - 0.5] + 1)/2] // Timing

{3.625, 5003830}

But for example
list.list // Timing

{0., 3.33561*10^6}

So the length of the list is not so big, rather the procedures used are slow. What's the faster way?

A: SeedRandom[1234];
list = RandomReal[1, 10000000];
Length[Select[list, # < 0.5 &]] // RepeatedTiming
Total[UnitStep[0.5 - list]] // RepeatedTiming

{4.77, 4998698}
{0.0698, 4998698}

And skipping multiplying list with -1., these are even a bit faster:
Length[list] - Total[UnitStep[list - 0.5]] // RepeatedTiming
Total[UnitStep[Subtract[0.5, list]]] // RepeatedTiming

{0.048, 4998698}
{0.050, 4998698}

Building on a compiled version by @ecoxlinux from this post (linked by Kuba), we can also define
countLessThan = Compile[{{vector, _Real, 1}, {bound, _Real}},
  Block[{counter = 0},
   Do[counter+=Boole[Compile`GetElement[vector, i]<bound], {i, 1, Length[vector]}];
   counter],
  CompilationTarget -> "C", "RuntimeOptions" -> "Speed"]

and use
countLessThan[list, 0.5] // RepeatedTiming

{0.0042, 4998698}

A: If the list is shorter than 10^16 the MachinePrecision numbers one gets from Clip won't be too imprecise:
Total[(Sign[list - 0.5] + 1)/2] // AbsoluteTiming
Round[Clip[list, {0.5, 0.5}, {0, 1}] // Total] // AbsoluteTiming

{4.8582906, 5002895}
{0.13461055, 5002895}

A: The fastest non-compiled approach is the one shown by @Henrik Schumacher, but I would like to point out a few subtleties about it.
You asked how many elements are less than 0.5. One of the proposed answers was Total@UnitStep@Subtract[0.5, list].  However, this counts how many elements are less than or equal to 0.5. Note that UnitStep[0] is 1.  The other proposed solution, Length[list] - Total@UnitStep@Subtract[list, 0.5], is the correct one.  Or one that is somewhat more amenable to generalization: Total[1 - UnitStep@Subtract[list, 0.5]].
The biggest problem with this approach is that it is hard to write and hard to read. As the answers above demonstrate, it is very easy to make small mistakes.  Consider a more complex situation, such as how many elements are within interval [a, b) ∪ (c, d] or similar.  It quickly becomes painful to write these expressions.
I have a small package called BoolEval that helps with this: all it does is translate relational and Boolean operations to the kinds of arithmetic expressions Henrik has shown.
<<BoolEval`

BoolCount[list < 0.5] // RepeatedTiming
(* {0.067, 4998698} *)

BoolCount[list <= 0.5] // RepeatedTiming
(* {0.047, 4998698} *)

Total@UnitStep@Subtract[0.5, list] // RepeatedTiming
(* {0.048, 4998698} *)

A: Inspired by the good performance of inner product, I find that the last one is not so bad:
Count[list - .5, _?Negative] // AbsoluteTiming

Count[list, _?(# < .5 &)] // AbsoluteTiming

Length[Select[list, # < .5 &]] // AbsoluteTiming

#.# &@UnitStep[.5 - list] // AbsoluteTiming

giving respectively
{2.94449, 5001117}

{4.62976, 5001117}

{4.11387, 5001117}

{0.0727141, 5001117}


text:
Q: Java, choose subsequence I have a problem with a part of my program.
In the following code, there are 27 letters in our alphabet.
The aim is: for every repetition of the outer for, we take the last n characters of text_generated, and for every letter of the alphabet, we count the number of occurrences in text_formatted of the n+1 characters obtained by adding the character to the last n characters of text_generated; then we choose the letter with the most occurrences and append it to text_generated.  The result I obtain is something like:
***aaaaaaaaaaaaaaaaaaa

why?
The code:
        int index;
        int[] occurrences = new int[27];
        int count;
        for(int a = 0; a < m; a++){     // m is the number of characters the user wants to add

            for(int b = 0; b < 27; b++){
                StringBuffer curr_word = new StringBuffer(text_generated.substring(text_generated.length()-n, text_generated.length()));
                count = 0;
                for(int c = 0; c <= text_formatted.length() -n-1;c++){
                    if(text_formatted.substring(c,c+n+1).equals(curr_word.append(array[b])))
                    count += 1;
                }
                occurrences[b] = count;
            }

            index = 0;
            for(int d = 1; d < 27; d++){
                if(occurrences[d] > occurrences[index])
                    index = d;
            }

            text_generated = text_generated.append(array[index]);

        }

A: You always set your index = 0, so first letter in array[] is chosen, which always is a.

A: The result that you get***aaaaaaaaaaaaaaaaaaa and this loop
index = 0;
for(int d = 1; d < 27; d++){
  if(occurrences[d] > occurrences[index])
    index = d;
}

indicates that that the every item in the occurrences array is 0. This means that your algorithm defaults to appending array[0] to the text_generated string. This means that the problem is in this block
for(int c = 0; c <= text_formatted.length() -n-1;c++){
  if(text_formatted.substring(c,c+n+1).equals(curr_word.append(array[b])))
    count += 1;
}

Possible problems:

*

*The loop is never entered, text_formatted.length() - n - 1 results in a negative value.

*The if always evaluates to false.

In both cases the problem is most likely related to the values of n and text_formatted.


text:
Q: regex wont find a match I am trying to pull some info here is my regex

([^<]+)<a href="([^<]+)" title="([^<]+)">([^<]+)<\/a><\/i><sup id="([^<]+)" class="([^<]+)"><a href="([^<]+)">[<\/span>1]<\/span><\/a><\/sup><\/td>
<a href="([^<]+)" title="([^<]+)">([^<]+)<\/a><\/td>
<a href="([^<]+)" title="([^<]+)">([^<]+)<\/a><\/td>
([^<]+)<\/td>
([^<]+)<\/td>

here is sample html

3Xtreme[18]
989 Studios
989 Studios
1999-03-31NA
NA

As of now i just want to get the data to find matches.. Can you see any reason why it would not match this?
for all the haters....
I dont care about your options on if i should use regex on html or not.. For this case it will work great. I have one page , the data i need is in a table.  Once i can get the data i will save it to my db and never have to use the regex again..  Soooo  if your comment or answer is about your option on using regex with html.. dont post.

A: ...Second line:
([^<]+)

cannot hope to match:

as you put a '+' equivalent to '{1,}' while there is nothing between your tags. Didn't check the rest of your regex, but anyway it can't work.
Edit:
Please also correct the "([^<]+)" and so on (I hope you see why)... And edit your regex when you correct it.
Edit 2:
Seeing as it's quite a disaster (sorry but it's the truth :/): please consider replacing all your ([^<]+) things that won't work for all your cases by a simple (.*?)
Edit 3:
[ and ] must be escaped. (\d will help you catch numbers)

A: [<\/span>1]<\/span>

Lots of problems here: you must escape the brackets and obviously 1 won't match 18


text:
Q: youtube crashing on slackware 14.0 Some video will play for a bit, then it simply says "an error occured, please try again later".
I'm using firefox 15, adobe flashplayer 11.  I didn't seem to have this problem on Slackware 13.37.
I've tried installing the SlackBuild of flashplayer as well as just copying the .so from the download to plugins.  I've also tried different browsers.
Chrome will play the video with no audio out (I have an HDMI out configured... aplay is able to play sounds through the HDMI and I'm able to watch movies in VLC with no problem).
If I use chrome, this is the output in bash when I fire up youtube:
ALSA lib pcm.c:7431:(snd_pcm_set_params) Rate doesn't match (requested 44100Hz, get 0Hz)
ALSA lib pcm.c:7442:(snd_pcm_set_params) Unable to set period time 23219 for PLAYBACK: Invalid argument

If I do:
aplay -D plughw:1.3 /usr/share/sounds/pop.wav

I get a sound, no problem (this is my HDMI card)
If I just do:
aplay /usr/share/sounds/pop.wav

Then I get "Channels count non available"
EDIT: ok, more weirdness.  When I play VLC and youtube video simultaneously, youtube no longer crashes.  Instead, the VLC plays audio through HDMI, while the youtube plays audio through the laptop speakers.

A: Flash not very good work in Linux+Firefox.
You may enable html5 mode in Youtube preferences
http://www.youtube.com/html5
I too using Slackware and not have problem with FF+html5 player, but my version of FF is 22

A: Have you tried setting up an ~/.asoundrc?
pcm.!default {
  type hw
  card 1
}

ctl.!default {
  type hw
  card 1
}

What channels does 'alsamixer' show when you run it?


text:
Q: R shiny: how to build a list of input elements and then return them as a single element for rendering in the UI? I want to generate a bank of R shiny slider inputs like:
label1:
<-------------slider1------------->
label2:
<-------------slider2------------->

For some variable number of inputs. However, I need to return all the generated elements as a single element or component for use in a higher level UI function, so I'm thinking of maybe wrapping the whole thing in a div(). I'm stuck at this point:
lapply(
    listOfSliderLabels, function(sliderLabel){
    #build a new slider: sliderInput(...)
    #how do I add this new slider to something like a div, and return the div?
})

A: do.call is great for programmatically building inputs. Here's an example that uses it with lapply to build slider inputs from a list of args:
sliderInputData <- list(
  list(inputId = "slider1", label = "slider1", min = 1, max = 5, value = 3),
  list(inputId = "slider2", label = "slider2", min = 2, max = 5, value = 4),
  list(inputId = "slider3", label = "slider3", min = 3, max = 5, value = 5)
)

buildSliderInputs <- function(inputData) {
  inputs <- lapply(inputData, function(args) {
    do.call(sliderInput, args)
  })

  do.call(div, inputs)
}

ui <- fluidPage(
  buildSliderInputs(sliderInputData)
)

server <- function(input, output, session) {}

shinyApp(ui, server)


text:
Q: Error: No valid exports main found for (Module path) I was reorganising documents on my mac and I have accidentally broken an app I am building.
I noticed the package.json had been removed along with the router.js. I added both files back and the koa dependency in package.json to test.
CONSOLE ERROR
Error: No valid exports main found for '/Users/devunderdog/Work space/Fantasy_Sports_Manager_Server/node_modules/koa'

at resolveExportsTarget (internal/modules/cjs/loader.js:611:9)
at applyExports (internal/modules/cjs/loader.js:492:14)
at resolveExports (internal/modules/cjs/loader.js:541:12)
at Function.Module._findPath (internal/modules/cjs/loader.js:643:22)
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:941:27)
at Function.Module._load (internal/modules/cjs/loader.js:847:27)
at Module.require (internal/modules/cjs/loader.js:1016:19)
at require (internal/modules/cjs/helpers.js:69:18)
at Object.<anonymous> (/Users/devunderdog/Work space/Fantasy_Sports_Manager_Server/index.js:1:13)
at Module._compile (internal/modules/cjs/loader.js:1121:30) {

  code: 'MODULE_NOT_FOUND'
}

INDEX.JS
const Koa = require('koa');
const app = new Koa();

This is where the "koa" require in index.js is trying to fetch the module.
Incorrect module path
module "/Users/devunderdog/Library/Caches/typescript/3.9/node_modules/@types/koa/index"

PACKAGE.JSON
   {
      "name": "fantasy_sports_manager_server",
      "version": "1.0.0",
      "description": "A fantasy sports management system designed to help you pick the best players based on their return on investment.",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "Lello De Luca",
      "license": "ISC",
      "dependencies": {
        "koa": "^2.13.0"
      }
    }

ALREADY TRIED

*

*Removing /node_modules/ and npm install

*Update NodeJS to v14.5.0

*Removing and adding all required dependencies from package.json

Thanks in advance for any effort. Let me know if you need more code to reproduce.
Devunderdog

A: I managed to fix the problem.

*

*Uninstall NodeJS, NPM and NVM | Here is how on Mac OS How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

*Install NVM(Node Version Manager) | Here is a decent Guide again for Mac OS https://nodesource.com/blog/installing-node-js-tutorial-using-nvm-on-mac-os-x-and-ubuntu/

*Install NodeJS with NVM | I installed v14.5.0 and it is working great.

I believe I may have moved the root/.nvm directory by mistake and uninstalling and reinstalling has fixed that. The error is gone.
Let me know if anyone is not coming right and we could try to reproduce and fix the issue together.

A: Just removing node_module/ and reinstalling doesn't resolve this problem,
upgrading node worked for me.
You can do this process manually, or with Homebrew if you're using MacOS, or you may do it with linuxbrew on Windows.

*

*run the following commands to upgrade Node version on macOS:
$ brew update
$ brew upgrade node

*After Node was upgraded, run the following commands to remove and reinstall /node_modules/.
$ rm -rf node_modules
$ npm ci

npm ci to install the project with a clean slate.


text:
Q: SQL Comparing 2 values that must be determined I need to Find out the course with the most passes from my table tblResults.
tblResults:
StuID       Course         Symbol
1001        CSC101         P
1001        RNG101         F
1002        CSC101         P
1002        RNF101         F
1003        HAP101         P
1004        HAP101         P

i.e should give CSC101 (And all other courses (HAP101) with the same ammount of passes)
I have tried:
CREATE VIEW Part1 AS
SELECT NumbF
FROM
  (SELECT COUNT(Course) AS NumbP,
          Course
   FROM tblResults
   WHERE Symbol = 'P')
GROUP BY Course);

CREATE VIEW Part2 AS
SELECT MAX(NumbP) AS Maxnum
FROM Part1,
     tblResults
WHERE Symbol = 'P'
GROUP BY Course;

SELECT Part1.Course
FROM Part1,
     Part2
WHERE Part1.NumbP = Part2.MaxNum

But I seem to be doing something incorrectly. Please help

A:     SELECT Course, count(StuID) count
    FROM tblResults
    GROUP BY Course
    HAVING count = (SELECT max(c)
                    FROM (SELECT count(StuID) c, Course
                          FROM tblResults
                          GROUP BY Course
                          WHERE Symbol = 'p'
                         ) counts
                   );

A: Something like this should work:
create view yourview as
select course, count(*) passcnt
from tblResults
where symbol = 'P'
group by course

select *
from yourview
where passcnt = (select max(passcnt) from yourview)

*

*SQL Fiddle Demo
Note, you don't need the view, I just left it for simplicity.

A: You can try the SELECT below, but I haven't tested it:
SELECT selA.Course, selA.NumPass FROM (
    SELECT Course, COUNT(Course) AS NumPass FROM
        tblResults GROUP BY Course HAVING Symbol = 'P') AS selA
INNER JOIN (
    SELECT MAX(NumPassCount) AS NumPassMax FROM (
        SELECT COUNT(Course) AS NumPassCount FROM
            tblResults GROUP BY Course HAVING Symbol = 'P') AS selB)
        AS selC ON selA.NumPass = selC.NumPassMax

A: Using a couple of sub queries
SELECT Sub3.Course
FROM
(
    SELECT MAX(Course) AS MaxCourseCnt
    FROM
    (
        SELECT Course, COUNT(*) AS CourseCnt
        FROM tblResults
        WHERE Symbol = 'P'
        GROUP BY Course
    ) Sub1
) Sub2
INNER JOIN
(
    SELECT Course, COUNT(*) AS CourseCnt
    FROM tblResults
    WHERE Symbol = 'P'
    GROUP BY Course
) Sub3
ON Sub2.MaxCourseCnt = Sub3.CourseCnt


text:
Q: I can't figure out what I'm doing wrong. I keep getting the same error I keep getting this error. 'Notice: Trying to get property of non-object in C:\xampp\htdocs\Homework\Sessions\Exercises\Includes\Login.php on line 21'
Here is my code below. I'm trying to connect and log into a mysql database but I keep getting thesame error.
Any ideas? Thanks
<?php
    $dbEntries = $_POST;
    foreach ($dbEntries as &$entry) {
        $entry = dbString($entry);
    }

    @$db = new mysqli('mysql13.ezhostingserver.com', 'webdata', 'W3bD@t@', 'allicense');

    if (mysqli_connect_errno()) {
        echo 'Cannot connect to database: ' . mysqli_connect_error();
    } else {
        $query = "SELECT id AS EmployeeID, first_name AS FirstName, last_name AS LastName
                    FROM northwind_employees
                    WHERE email_address = '" . $dbEntries['Email'] .
                "' AND password = '" . $dbEntries['Password'] . "'";
        $result = $db->query($query);

        if ($result->num_rows) {
            $row = $result->fetch_assoc();
            $msg = 'Logged in as ' . $row['FirstName'] . ' ' . $row['LastName'];
            $_SESSION['FirstName'] = $row['FirstName'];
            $_SESSION['LastName'] = $row['LastName'];
            $_SESSION['EmployeeID'] = $row['EmployeeID'];
            if (isset($_POST['Remember'])) {
                setcookie('eid', $row['EmployeeID'], time() + 60 * 60 * 24 * 7);
            }
        } else {
            $msg = 'Login Failed';
            unset($_POST['LoggingIn']);
            $dbEntries = $_POST;
        }
    }
?>


text:
Q: AttributeError with for loops I want to define a function called all_extreme() that takes a tuple of strings and returns True if all of the strings contain exclamation points. If any of the strings are missing exclamation points, then it should return False. This function needs to use the function extreme() that I have already defined. So all_extreme(("!","Bogus!","!YES!")) and all_extreme(("Nifty!","!!")) should both return True, but all_extreme(("Cool!","Okay...")) and all_extreme(("square","...")) should both return False.  Here is what I have so far:
def extreme(x):
    """returns True if the string contains at least one exclamation point

    str -> str"""
    if x.find('!') != -1:
        return True
    else:
        return False

def all_extreme(x):
    """returns true if all of the strings contain exclamation points

    str, str... -> str"""
    for word in x:
        if extreme(x) == True:
            return True
        else:
            return False

The problem that I am having is that I getting a AttributeError: 'tuple' object has no attribute 'find'. I am open to any and all suggestions.

A: It's extreme(word), not extreme(x).
Also, you will encounter a problem with the return statements - they'll return after only one iteration. Save a True flag at the beginning of all_extreme(), then if one of the words in x is not extreme, set the flag to False. Then return the value of the flag.
This task can also be accomplished more simply:
def all_extreme(x):
    return all('!' in word for word in x)


text:
Q: Is the algorithm which reviews questions when one clicks "review your question" customizable on a per-site basis? Since at least a few years ago (I cannot locate the announcement of this feature's introduction) most SE sites require at least two clicks to post a question -- first, one clicks the "Review your question" button, and then it turns into "Post your question", and it can be clicked for publication. In between, one gets feedback on the right of the screen which says things like "Your question is ready to be submitted".
Is it possible to customize the algorithm for this feedback on a per-site basis? For instance, on MathOverflow, our most common type of off-topic question is homework questions. But when I write a question titled "Please help me with my homework!!!", the system doesn't tell me my question looks problematic. It would be nice if "homework" could be a keyword, where, if it appears in the question, the feedback will be something like "Your question may be off-topic for this site, consider asking somewhere else.", outlined in yellow or orange rather than green (I'd imagine the user would still be allowed to post the question, just advised that it may not be suitable.) As it is, the feedback may be giving users a false sense of confidence about the suitability of their questions.
(Of course, that's not to say that all homework questions actually contain the word "homework", nor that all off-topic questions on MO are homework questions, but it would be nice to catch some of these easy cases.)
Other sorts of generic things which could be checked are whether the title is in all-caps, whether sentences start with capital letters, etc.
P.S. Any tagging help is appreciated. Thanks!


text:
Q: Theme not applying for new products page I have added new custom theme to my project. Everything working fine. But, when I click the any one of product in  product list my new theme not applying in that product page. How to solve this issue?

A: Firstly you need to open product in admin and check if Custom Design or Page Layout are changed https://monosnap.com/file/uYAfTXNUxDnsBni7KliBVYD8kXHZIO#
if Custom design is changed - this will mean that Magento will use other theme for product view page
if Page Layout is changed - this will mean Magento will look file for layout (ex. template/page/1column.phtml) in your theme firstly and after that (if not found) - will look for it in default magento theme (or theme which is choosed as Default in Admin - System - Configuration - Design)


text:
Q: Azure Service Bus: proxying topic subscription listeners Background
There's a RESTful API offering some operations. This RESTful API is consumed by third-parties that must be authenticated and authorized into the platform in order to get access to API's operations.
Third-parties require reliable data consumption, and the API must provide a publisher/consumer pattern-based solution to consume some data.
Since the so-called API won't reinvent the wheel, it's about to use Windows Azure Service Bus.
Problem
The RESTful API should abstract the actual service bus service. In the other hand, Service Bus is the solution to provide reliable messaging in the own platform.
Actually, Service Bus isn't an standalone service, but it's part of some workflows. Third-parties aren't supposed to have Windows Azure credentials.
Third-parties should connect to Windows Azure Service Bus using API-specific credentials that would give access to the Service Bus' topics (i.e. message queues).
Possible solutions

a. Authorize direct access to Windows Azure Service Bus

It seems the easiest solution. Let's see the flow:

*

*A third-party sends a request to the RESTful API in order to get Windows Azure Service Bus connection string - credentials -.

*Once it has the connection string, the third-party connects to Windows Service Bus and starts receving message from some topic subscription. NOTE: The connection string is encrypted in the server-side and it can only be decrypted by an accepted client.

Pros

*

*Easy. The API authorizes the third-party to use Windows Azure Service Bus and it has no other responsibility.

*Own API doesn't manage the high load of topic subscribers: this is handled by Windows Azure platform.

Cons

*

*Third-parties are very tied to Windows Azure.

*Third-parties can easly by-pass the RESTful API for some time.

b. Proxy access to Windows Azure Service Bus
Is this ever possible? The whole flow would be:

*

*A third-party asks a TCP API similar to RESTful one in order to get subscribed to some Windows Azure Service Bus topic.

*The TCP API makes the connection and it creates a proxy in order to mirror TCP API connection to Service Bus I/O to the TCP API-to-third-party.

*Now third-party is connected to the proxy and sends and receives messages.

Pros

*

*Third-parties are connected through a proxy, meaning that they don't own any Windows Azure credential and they can't potentially by-pass the TCP or RESTful API.

*Messaging isn't absolutely tied to Windows Azure anymore.

Cons

*

*What happens if Windows Azure Service Bus closes the connection?

*What happens if the platform proxy goes down?

c. Windows Azure Service Bus server wrapper
This is the definition and flow:

*

*The RESTful API server has pool of Windows Azure Service Bus subscription connections.

*Third-parties are subscribed to a TCP socket or WebSocket of the API server.

*Whenever Windows Azure Service Bus has a message, it's routed to the third-party connection pool and the third-party receives the message.

*Third-parties send messages using a RESTful API.

Pros

*

*Third-parties are completely agnostic of the service bus technology.

Cons

*

*Same as b. approach.

Questions

*

*Is b. approach possible?

*What's your advise about c. Windows Azure Service Bus server wrapper. Do you find an avoidable war the less reliability in terms of uptime and Windows Azure Service Bus to API and API to third-party synchronization?

*Am I wrong and there's some alternative to these approaches?

A: Finally, I opted-in with option a.: Authorize direct access to Windows Azure Service Bus.
This is using the Windows Azure Access Control Service.
Using this approach, third-parties receive an Azure Service Bus connection string with an issuer (an identity) that has specific permissions on some topics. For example: "consumer can only listen".
For more details about this:

*

*http://www.windowsazure.com/en-us/develop/net/how-to-guides/access-control/


text:
Q: Reading google home page using ruby: Connection attempt failed I'm attempting to make a very basic ruby script, to pull down the contents of a webpage as a string. Once I can pull down the page as a string, I'm sure the rest will be a matter of trial and error.
When I had trouble with the page I originally wanted to use (a https, redirected URL), I plugged in google instead, and stripped things back to nothing, and still I'm getting an error.
Here's the code:
require 'open-uri'
file = open('www.google.com')
contents = file.read
puts contents

and the error message I get is:
http.rb:763: in 'initialize': A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host failed to respond - connect(2) (Errno::ETIMEDOUT)

I've also tried:
https://www.google.com

and
http://www.google.com

with the same result.
Does anyone have any idea what i'm doing wrong?


text:
Q: How to make more posts/data appear on instagram I'm using this url: https://www.instagram.com/explore/tags/meugatonovet/?__a=1, to get hashtag data. With this parameter it shows a json, but returns only 39 posts/pots of 7,000 thousand.
Is there a tool, some parameter or something else that can make it return more data?

A: Using ?__a=1 parameter is a neat trick to get JSON data for any Instagram page, but it's not an official API; Instagram can block your IP address any time and the endpoint is not guaranteed to remain stable.
The official way to look up media via hashtag is with Graph API Hashtag Search.
See getting started for initial steps. You need a business account ID for your Instagram profile which is required parameter for hashtag search. Then you can do these steps:

*

*Find the ID of the hashtag you are looking for, for example:
GET https://graph.facebook.com/v13.0/ig_hashtag_search?user_id=<business account ID>&q=meugatonovet&access_token=<user access token>

This will return a JSON of the hashtag:
{
 "data": [
   {
     "id": "17878113037414936"
   }
 ]
}

*Use that ID in other requests, for example /recent_media:
GET https://graph.facebook.com/v13.0/17878113037414936/recent_media?user_id=<business account ID>&fields=id,media_type,comments_count,like_count,media_url&access_token=<user access token>

The response will also provide the pagination cursor which lets you read all the data within API limitations.
Other less official options are web scraping or using Instagram's private API (there are actively maintained libraries for that, like instagram-private-api), but mind that this might get you banned and it breaks Instagram's ToS. It's probably fine for a personal project, but not so fine for a commercial use.

A: This endpoint is not working anymore:
https://www.instagram.com/explore/tags/username/?__a=1

However, a possible solution is adding __d=dis to your payload:
https://www.instagram.com/explore/tags/username/?__a=1&__d=dis

Please, take into account that this is an unofficial method, and you can get banned as @jnv advised.
Best regards