text:
Q: Type 'Record[]' is not assignable to type 'Plugin[]' I am trying to implement chartJS in my angular project and I am using ng2-charts. When I follow the documentation written here: https://valor-software.com/ng2-charts/#GeneralInfo my project breaks down when registering the DatalabelsPlugin plugin.
package.jon
{
 "@agm/core": "3.0.0-beta.0",
 "@angular-builders/jest": "12.1.2",
 "@angular/animations": "^14.2.12",
 "@angular/cdk": "12.1.0",
 "@angular/common": "^14.2.12",
 "@angular/compiler": "^14.2.12",
 "@angular/core": "^14.2.12",
"chart.js": "3.9.1",
"chartjs-plugin-datalabels": "1.0.0",
"ng2-charts": "4.1.1",
}

my module where I import ng2-charts
import { NgChartsModule } from 'ng2-charts';

....

imports: [
    NgChartsModule
  ],

my ts:
import DatalabelsPlugin from 'chartjs-plugin-datalabels';

export class ClientInfoTabComponent implements OnInit {
  public pieChartPlugins = [ DatalabelsPlugin ];
}

my template:
  <canvas baseChart class="chart"
        [plugins]="pieChartPlugins">
</canvas>

What have I tried:
I have doubt that my versions are not right in some of the documentation it is mentioned that I need to register the plugin but when I tried this I also get errors ( I have tried different syntax on how to register plugin as described here:  How to import Chart.js chartjs-plugin-datalabels npm package into an Angular 7 project but with no luck.
I have also instaled typescript definitions for chart.js (didn't help)
The error I get is this one:
10 - error TS2322: Type 'Record<string, unknown>[]' is not assignable to type 'Plugin<any, AnyObject>[]'.

EDIT: this problem is gone after I add type any to pieChartPlugins like this:
public pieChartPlugins: any = [ DatalabelsPlugin ];

but now I have another error:
main.js:1 ERROR Error: Uncaught (in promise): ReferenceError: Cannot access 'Ja' before initialization
ReferenceError: Cannot access 'Ja' before initialization

Thank you!

A: chartjs-plugin-datalabels 1.0.0 is old and says it depends on Chart.js 2.x. Its type definitions (and, probably, its implementation) appear to be incompatible with Chart.js 3.x.


text: Q: how to add raw resources to a react-native native android library I've created a native library and I'm using it in my react-native application but I'd like to add a raw resource (sound file) to the library.  I tried just adding a res/raw directory with the file but it doesn't seem to generate an R.java file for the build.  How is this done?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Iterative gaussian convolution and decimation when the decimation/convolution ratios are not divisible by two? I have a bit of a mathematics problem.
I have an image $I_1$ that I have previously blurred (from an image $I_0$) with a Gaussian of standard deviation $\sigma_1$.
I would like to blur image $I_1$ with a Gaussian of standard deviation $\sigma_X$ to produce a new image, image $I_2$. The result, image $I_2$, should be as if $I_0$ has been blurred with a Gaussian of standard deviation $\sigma_2$.
This problem is not difficult, we know that the convolution of two Gaussian filters is the third filter. I can compute the $\sigma_X$ by:
$$
\sigma_X = \sqrt{ \sigma_2^2 - \sigma_1^2 }
$$
(this works because application of a Gaussian of $\sigma_1$ followed by application of Gaussian of $\sigma_2$, is as if a single Gaussian of $\sigma_3$ had been applied, where $\sigma_3^2 = \sigma_1^2 + \sigma_2^2$).
I can directly apply a Gaussian with $\sigma_X$ to image $I_1$ to achieve my desired image $I_2$.
Furthermore, I would like to decimate the image $I_2$ by a factor of $N$ (e.g., $0.5$ is decimation by half, $0.25$ is by fourth) after the blur. Keep in mind that neither of $1/N$ nor $\log_2(\sigma_2/\sigma_1)$ must be whole numbers, though they will always be positive.
Here is the problem. In the case where $\sigma_X$ is very large, the process becomes computationally expensive. Since I will be decimating the image anyways, I would like to apply the method often used in (dyadic) Gaussian pyramids, where one applies a blur followed by a decimation step, and then repeats this. However, since $\log_2(\sigma_2/\sigma_1)$ and $1/N$ are not guaranteed to be whole numbers, it is not straightforward to break the transform down into smaller blur-decimate steps so that I never have to apply a very large Gaussian convolution.
I have a feeling that this is possible.
Currently, I have:
    double sigmaratio = sigma2 / sigma1;
    double xsigma = sqrt( sigma2*sigma2 - sigma1*sigma1);
    double N = decimation_ratio //(e.g. 0.5 means decimate by half, 0.25 is by fourth, etc.)
    double sig_halves = log2( sigmaratio );
    double N_halves = -1 * log2(N); //will be =1 if we halve it once, =2 if twice, etc.

    //Taking floor to get the whole part...
    int intsighalves = (int) sig_halves;
    int intNhalves = (int) N_halves;
    int num = intsighalves;
    if( intNhalves < num )
     {
       num = intNhalves;
     }
    if( num >= 1 )
     {
       double Ndiff = N_halves - (double)num;
       double sigdiff = sig_halves - (double)num;
       //I need to apply num dyadic steps with some sigmaXprime at each step (getting 2x as large each time) and decimation by half at each step.
     }

My question is: how do I choose the sigmaXprime at each dyadic step for the whole parts, and when/how do I choose the partial sigmaXprimepartial and the partial decimation in order to get an exact implementation of the image $I_1$ convolved with Gaussian $\sigma_X$ followed by decimation by $N$?
Edit: Just a note, this may not be possible due to loss of information at each decimation step, but I think it should be possible since in the case of dyadic Gaussian pyramids, application of a single Gaussian / decimation step with the correct parameters is exactly equal to application of iterated Gaussian / decimation steps (see my answer to https://dsp.stackexchange.com/questions/667/image-pyramid-without-decimation/55654#55654 )


text:
Q: How can I save a Django field (as in the field object) to the database? I'm trying to implement a reusable form that users can download the source code in HTML which was site generated for them by the site. They can also create their forms using an interface where they get to choose the fields they want and rank them so the highest would appear first in the downloadable form.
They can then use the form in their sites to gather customer data and when the form gets submitted, the action parameter points back to our site so we can store the information on our servers.
Now, my question is, how can I save a Django Field object in my database? This is so I can store the forms that the users created, especially the Fields that they chose.
I need to store the Fields so that I can create a generic Django ModelForm and the users can save the Fields of that ModelForm in their downloadable forms. So when they submit back the information to us I can feed the information straight to the ModelForm (since the Fields would be recognizable) and do some further validation.
Also I have to add some basic javascript validations (like validation.js) for each field (must be present when the user downloads the form), and I know it will be easier if I can save the Fields themselves.

A: You could pickle the Field object:
import cPickle
field = forms.CharField()
dump = cPickle.dumps(field) # serializes field as an ASCII string
my_model.stored_field = dump

To unpickle:
field = cPickle.loads(my_model.stored_field)

http://docs.python.org/library/pickle.html


text:
Q: Can't publish "news.reads" action (paradox included!) I recently asked about some issues I encountered while try to get the Open Graph working. To solve the issue there, I had to create a second action called read. However, since Facebook prefers that their default actions be used, I am afraid that when I submit that action, facebook will reject it as it is too similar to their own news.reads.
I'd like to use news.reads, but when I try to make calls to it, I receive an OAuthException error stating that news.reads is not submitted, and can only be used by an admin, developer, or tester. Ironically, I am the sole admin, so this should be a non-issue.
If I try to submit news.reads, one of the requirements is to make at least one publish_action call to that action.
.. except I can't bloody well make that call if the Graph won't let me, can I? ;)
Is this a Graph API bug?

Edit: According to this question, the news.reads call was made public Jan 18th.

A: while reading https://developers.facebook.com/docs/reference/plugins/recommendationsbar/
...In order to use Open Graph publishing, the App must enable the "Enhanced Auth Dialog" migration. This can be done from the "Advanced" settings of the "Edit App" page.
have you enabled it?


text:
Q: Short exact sequence of modules induces short exact sequence of cokernels I have a commutative unital ring $A$, a short exact sequence $L\to M\to N$ of $A$-modules, a faithful exact contravariant functor $D:\text{Mod}_A\to\text{Mod}_A$ satisfying $$DM=0\iff M=0,$$ and monomorphisms $\chi_L:L\to D^2L$, $\chi_M$ and $\chi_N$ making the following diagram commute.
$$\require{AMScd}
\begin{CD}
L @>>> M @>>> N \\
@V{\chi_L}VV @V{\chi_M}VV @V{\chi_N}VV\\
D^2L @>>> D^2M @>>> D^2N;
\end{CD}$$
I have read that from this setup we obtain a short exact sequence $$\text{coker}(\chi_L)\to\text{coker}(\chi_M)\to\text{coker}(\chi_N)$$ via a 'diagram chase', but cannot quite see how to get this.
First of all we need a monomorphism $\text{coker}(\chi_L)\to\text{coker}(\chi_M)$. We have a short exact sequence $D^2L\to D^2M\to D^2N$ since $D$ is exact and contravariant, and therefore a monomorphism $D^2L\to D^2M$ which maps $\text{im}(\chi_L)\to\text{im}(\chi_M)$, but where to go from here?

A: Given a morphism $h \colon B \to C$ in $\textsf{Mod}_A$, a submodule $B'$ of $B$, and a submodule $C'$ of $C$; if $h[B'] \subseteq C'$, then $h$ induces a morphism $B/B' \to C/C'$ defined by $b+B' \mapsto h(b)+C'$.
Indeed, if $b_1+B'=b_2+B'$, then $b_1-b_2 \in B'$, and from $h[B'] \subseteq C'$ it follows that $h(b_1)-h(b_2) \in C'$, so $h(b_1)+C'=h(b_2)+C'$.
Now, consider $L \stackrel g \longrightarrow M \stackrel f \longrightarrow N$. Since the diagram $\newcommand{\im}{\operatorname{im}} \newcommand{\coker}{\operatorname{coker}}$
$$
\require{AMScd}
\begin{CD}
L @>{g}>> M @>{f}>> N \\
@V{\chi_L}VV @V{\chi_M}VV @V{\chi_N}VV\\
D^2L @>>{D^2g}> D^2M @>>{D^2f}> D^2N;
\end{CD}
$$
commutes, we have that
$$
(D^2g)[\im(\chi_L)] = (D^2g)[\chi_L[L]] = \chi_M[g[L]] \subseteq \chi_M[M] = \im(\chi_M)
$$
and therefore $D^2g$ induces a map $\coker(\chi_L) \to \coker(\chi_M)$. Similarly, $D^2f$ induces a map $\coker(\chi_M) \to \coker(\chi_N)$.


text:
Q: need help to understand recursion n = 10
10+9+8+7+6+5+4+3+2+1 = 55

here's a piece of code to add number starting from n, to every number before it.
public static int recursion(int index){
    if (index == 0){
        return 0;
    }
    else{
        return recursion(index-1) + index;
    }
}

sorry for stupid question, but here's what confuse me: when the index is not zero, it calls the recursion function again, with the index substracted by 1, so on until the index is zero. However, it's coded recursion(index-1) + index.
so why the index is not substracted by 1 and added by 10 (or any index number) each time the function is called?  why is it not something like this: (10+ (9+10) + (8+10) + (7+10) +....) ?

A: Try to write this sum as
sum(10) = 1+2+3+4+5+6+7+8+9+10

This will let you see that
sum(10) = (1+2+3+4+5+6+7+8+9)+10 = sum(9)+10

and
sum(9) = (1+2+3+4+5+6+7+8)+9

and so on
In other words
sum(i) = sum(i-1) + i;

or to be more precise
         {0            for i=0
sum(i) = {
         {sum(i-1) + i for i>0

BTW each time method is called its variables are separate instances in each method call which means index in recursion(10) is separate variable than index in recursion(9).

A: Evaluate it by hand. Start with index = 10:
Index is not zero so we go into the else:
return recursion(10 - 1) + 10

return recursion(9) + 10

Now, recursion(9) evaluates to
return recursion(9 - 1) + 9

return recursion(8) + 9

So, substituting into the above:
return recursion(8) + 9 + 10

So, carrying on the process
return recursion(0) + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10

And we know that recursion(0) returns 0 so the recursion stops at this point.

A: recursion(index-1) + index;

For this statement intiallty it will be
recursion(10-1) + index;

for evaluating that 10-1 will be done ie. 9
Then in order to find the ans of that statement recursion(9) has to be found so the function recursion is called again.
so expression becomes
recursion(9) + 10;

And recursion(9) wil be
recursion(9-1) + 9

This continues and finally it will be recursion(0) which returns 0.


text:
Q: Android shared element return transition works from 11 recyclerview element and above I want two textviews from recyclerview to have a correctly transition when return. Now it works very strange I mean return transition for both textwievs starts from 11 element and then it is what I want, but before that just one textview (title) has a return transition. Why then return transition starts from 11 item and how to have this transition of course from first element on recyclerview list?
Here is my code and explanation.
I have a recyclerview which sets transitionname for two textviews dynamically:
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    Note noteItem = noteItemList.get(position);

    holder.noteTitleText.setText(noteItem.getNoteTitle());
    ViewCompat.setTransitionName(holder.noteTitleText, "title" + position);
    holder.noteDetailsText.setText(noteItem.getNoteDetails());
    ViewCompat.setTransitionName(holder.noteDetailsText, "details" + position);
   (...)
}

in this adapter I have ViewHolder in which on parent view I set onclick like this:
        rlNumberToGradient.setOnClickListener(view -> noteTitleDetailsOnClickAction());

where
private void noteTitleDetailsOnClickAction() {
        boolean edit = true;
        if (fragment instanceof FragmentMain) {
            list = db.getAllNotes();
            isOnMove = ((FragmentMain) fragment).isOnMove;
        } else if (fragment instanceof FragmentFav) {
            list = db.getFavNotes();
        } else if (fragment instanceof FragmentSearch) {
            list = db.getSearchNotes(((FragmentSearch) fragment).onChange());
        }

        if (!isOnMove) {
            Bundle bundle = new Bundle();
            bundle.putBoolean("edit", edit);
            bundle.putInt("position", list.get(getAdapterPosition()).getId());
            ((ActivityMain) fragment.requireActivity()).onPassValuesToFragmentShowNote(bundle, noteTitleText, noteDetailsText);
        }
        isOnMove = false;
    }

don't care about isOnMove variable, for this purpose lets assume its always true.
Once I click on this rlNumberToGradient view onPassValuesToFragmentShowNote method from main activity is called. It looks like this:
@Override
public void onPassValuesToFragmentShowNote(Bundle bundle, TextView tvTitle, TextView tvDetails) {
    bundle.putString("transition_name_title", ViewCompat.getTransitionName(tvTitle));
    bundle.putString("title", tvTitle.getText().toString());
    bundle.putString("transition_name_details", ViewCompat.getTransitionName(tvDetails));
    bundle.putString("details", tvDetails.getText().toString());
    fragmentShowNote.setArguments(bundle);

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.setReorderingAllowed(true);
    ft.addSharedElement(tvTitle, ViewCompat.getTransitionName(tvTitle));
    ft.addSharedElement(tvDetails, ViewCompat.getTransitionName(tvDetails));
    ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
    ft.addToBackStack(fragmentShowNote.getClass().getSimpleName());
    ft.replace(R.id.content_frame, fragmentShowNote);
    ft.commit();
}

As we can see the fragment is showing up. Here is the key code here:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    sp = PreferenceManager.getDefaultSharedPreferences(requireContext());
    setSharedElementEnterTransition(TransitionInflater.from(requireContext()).inflateTransition(R.transition.change_image_transform));
    setSharedElementReturnTransition(TransitionInflater.from(requireContext()).inflateTransition(R.transition.change_image_transform));
    setExitTransition(TransitionInflater.from(requireContext()).inflateTransition(R.transition.change_image_transform));
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_show_note, container, false);

    if (getArguments() != null) {
        Bundle b = getArguments();
        position = b.getInt("position");
        transitionNameTitle = b.getString("transition_name_title");
        title = b.getString("title");
        transitionNameDetails = b.getString("transition_name_details");
        details = b.getString("details");
    }

    return view;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    if (((ActivityMain) requireActivity()).getSupportActionBar() != null) {
        ((ActivityMain) requireActivity()).getSupportActionBar().hide();
    }
    Toolbar toolbar = view.findViewById(R.id.toolbar);
    ViewCompat.setTransitionName(toolbar, transitionNameTitle);
    ((ActivityMain) requireActivity()).setSupportActionBar(toolbar);
    ((AppBarLayout) view.findViewById(R.id.app_bar_layout)).setExpanded(true);
    toolbar.setTitle(title);
    TextView tvNoteDescValue = view.findViewById(R.id.note_desc_value);
    ViewCompat.setTransitionName(tvNoteDescValue, transitionNameDetails);
    tvNoteDescValue.setText(details);
}

A: Solved. It turned out it was a uncompatibility. I tried to set transition on Toolbar and TextView. Once I get TextView from Toolbar with this method everything works fine:
    public static TextView getTextViewTitle(Toolbar toolbar){
    TextView textViewTitle = null;
    for(int i = 0; i<toolbar.getChildCount(); i++) {
        View view = toolbar.getChildAt(i);
        if(view instanceof TextView) {
            textViewTitle = (TextView) view;
            break;
        }
    }
    return textViewTitle;
}


text:
Q: Display the items in the cart in a jsp file from servlet I am building a E-Commerce simple solution in java and i am stucked in a critical point. I am not able to display the correct items. I am using a servlet that has a doGet a shoppingcart class, a products class and viewcart.jsp file. To pass the items between servlets  i am using the setAttribute of context. Here are my files i have build so far. Can anyone help me fix this problems? Every time i press add to car it adds the element but look like all the previous elements get overwritten by the last one i added.
package com.kd.ecommerce;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class addtocart
 */
@WebServlet("/addtocart")
public class addtocart extends HttpServlet {
private static final long serialVersionUID = 1L;
private shoppingcart shop = new shoppingcart();

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ServletContext thisContext = getServletContext();
    String name = request.getParameter("product");
    Connection cn = DBConnect.getInstance();
    try {
        Statement st = cn.createStatement();
        ResultSet rs = st.executeQuery("select * from inventory where name = '"+name+"' LIMIT 1");
        while(rs.next()){
            Products p = new Products(rs.getString(2),rs.getString(3),rs.getString(4),rs.getFloat(5));
            System.out.println(p.getName()+":"+ p.getPrice());
            shop.ins(p);
            thisContext.setAttribute("shop", shop.getIt());
            for(int i = 0; i< shop.getIt().size(); i++){
                System.out.println(shop.getIt().get(i)+":"+ shop.getIt().get(i).getPrice());
            }
            response.sendRedirect("inventory.jsp?addedto=success");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

}

Products.java
package com.kd.ecommerce;

public class Products {
private static String name;
private static Float price;
private static String desc;
private static String img;

public Products(String n, String d, String i,Float p){
    name = n;
    price = p;
    desc = d;
    img = i;
}

public String getName(){
    return name;
}

public Float getPrice(){
    return price;
}

public String getImage(){
    return img;
}

public String getDesc(){
    return desc;
}
}

shoppingcart.java
package com.kd.ecommerce;

import java.util.ArrayList;

public class shoppingcart {
private static ArrayList<Products> items;

public shoppingcart(){
    items = new ArrayList<Products>();
}

public void ins(Products p){
    items.add(p);
}

public void remove(Products p){
    items.remove(p);
}

public int getSize(){
    return items.size();
}

public ArrayList<Products> getIt(){
    return items;
}
}

viewcart.jsp
<jsp:include page="menu.jsp"></jsp:include>
<%
ServletContext sc = getServletConfig().getServletContext();
if(sc.getAttribute("shop") != null){
    ArrayList<Products> it = (ArrayList<Products>)sc.getAttribute("shop");
    out.println(it);
    for(int i = 0; i< it.size(); i++){
        out.println(""+it.get(i).getPrice()+"");
    }
}else{
    out.println("Shopping cart empty");
}
%>

-- EDIT --
My new viewcart.jsp using sessions
<%
if(session.getAttribute("shop") != null){
    shoppingcart sh = (shoppingcart)session.getAttribute("shop");
    ArrayList<Products> pd = sh.getIt();
    for(int i = 0; i< pd.size(); i++){
        out.println(""+pd.get(i).getPrice()+"");
    }
}else{
    out.println("Shopping cart empty");
}
%>

A: What's causing your problem is that you have made the shoppingcart an instance variable in your Servlet. That means that every HTTP request that your Servlet handles is sharing the same shoppingcart.  To fix this, move the following line from the class definition code:
private shoppingcart shop = new shoppingcart();

And move it into the doGet method before the following line:
shop.ins(p);

The doGet method will then contain the following two lines:
shoppingcart shop = new shoppingcart();
shop.ins(p);

You may even consider giving the shoppingcart class a constructor that takes a Products object as parameter and sets the items in the constructor. Then you could combine those two lines into one, as follows:
shoppingcart shop = new shoppingcart(p);

It's a common mistake to define objects as instance variables in Servlets. Just remember that every HTTP call to your servlet will share the instance variables. If you're wanting to store information for specific users, consider putting them in the session.
----EDIT----
I didn't actually answer the question, as it turns out. To keep a running tally of the added items, you have to save the items to a place that will not be shared by anyone--a place only the specific user will have his data saved to. The session is the place that was specifically designed for this purpose. You can use the session like this in your doGet method:
HttpSession session = request.getSession(true);
shoppingcart shop = (shoppingcart)session.getValue("shop");
if(shop == null) {
    shop = new shoppingcart();
    session.putValue("shop", shop);
}

shop.ins(p);

The line that gets the value from the session returns whatever object is stored with the key "shop". If this is the first item the user is adding, no shopping cart will have been saved yet, so shop will be null. That's why we do the null check; to create a shopping cart and then associate it with the "shop" key so that the next time the user adds an item, a shopping cart will have been associated with the key "shop".
Once we have a shoppingcart that is associated with the "shop" key for that particular user, you should see the items being added to that same cart object as multiple submissions are made.


text:
Q: Help with displaying UITabBarController i have created a custom Tabbarcontroller for my application. now i have a uiview where at the bottom i want to display my tabviewcontroller without any buttons selected. And when the user presses on any button it will then load the corresponding view of the tabbar item selected. Somehow my below code doesnt work. it displays a white screen in place of my uiview screen and doesnt display a tabbar at the bottom.
#import <UIKit/UIKit.h>
#import "UICustomTabViewController.h"

@interface AssignmentViewController : UIViewController<UITabBarDelegate, UITableViewDelegate,UITableViewDataSource> {
    NSMutableArray *listAssignments;
    NSMutableArray *staffImages;
    UICustomTabViewController *tabViewController;
    }

@property (nonatomic, retain) UICustomTabViewController *tabViewController;

@end
- (void)viewDidLoad {

    UICustomTabViewController *tvController = [[UICustomTabViewController alloc] initWithNibName:@"TabViewController" bundle:nil];

    self.tabViewController = tvController;

    [self.view addSubview:tvController.view];

    listAssignments = [[NSMutableArray alloc] init];
    staffImages = [[NSMutableArray alloc] init];

    //Add items
    [listAssignments addObject:@"TRANSPORTATION"];
    [listAssignments addObject:@"ROOMS"];
    [listAssignments addObject:@"FOOD & BEVERAGES"];

    //Set the title
    self.navigationItem.title = @"ASSIGNMENTS";

    [super viewDidLoad];
         [tvController release];

}

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

    tableView.separatorColor=[UIColor grayColor];
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    cell.textLabel.textColor=[UIColor blackColor];
    cell.textLabel.text=[listAssignments objectAtIndex:indexPath.row];
    cell.textLabel.font=[UIFont systemFontOfSize:16];
    return cell;
}

A: UITabBarController should be your parent. Try to add your navigationController to your tvControllers subview at the tab you want it to show. tvController.views = [NSArray arrayWithObjects:navigationController, someOtherController, nil];
To show a tableView, you add the tableView to your navigationController's view.


text:
Q: Changing the color of an image based on RGB value Situation:
You have an image with 1 main color and you need to convert it to another based on a  given rgb value.
Problem:
There are a number of different, but similar shades of that color that also need to be converted, which makes a simple 'change-all-(0,0,0)-pixels-to-(0,100,200)' solution worthless.
If anyone can point me in the right direction as far as an algorithm or an image manipulation technique that would make this task more manageable that'd be great.
I've been using PIL to attempt this problem but any general tips would be nice.
edit:
Also, I've used this other SO answer (Changing image hue with Python PIL) to do part of what I'm asking (the hue change), but It doesn't take into consideration the saturation or value
edit: http://dpaste.org/psk5C/ shows using pil to look at the rgb values that I have to work with and the hsv's that go along with some.

A: Refering to the solution in the linked question: You can adjust the shift_hue() function to adjust hue, saturation and value instead of just hue. That should then allow you to shift all of these parameters just as you like.
Original:
def shift_hue(arr, hout):
    r, g, b, a = np.rollaxis(arr, axis=-1)
    h, s, v = rgb_to_hsv(r, g, b)
    h = hout
    r, g, b = hsv_to_rgb(h, s, v)
    arr = np.dstack((r, g, b, a))
    return arr

Adjusted Version:
def shift_hsv(arr, delta_h, delta_, delta_v):
    r, g, b, a = np.rollaxis(arr, axis=-1)
    h, s, v = rgb_to_hsv(r, g, b)
    h += delta_h
    s += delta_s
    v += delta_v
    r, g, b = hsv_to_rgb(h, s, v)
    arr = np.dstack((r, g, b, a))
    return arr

Assuming you know the base color of your original image and the target color you want, you can easily compute the deltas:
base_h, base_s, base_v = rgb_to_hsv(base_r, base_g, base_b)
target_h, target_s, target_v = rgb_to_hsv(target_r, target_g, target_b)
delta_h, delta_s, delta_v  = target_h - base_h, target_s - base_s, target_v - base_v


text:
Q: "request not found" error in Spring MVC I am new to Spring.I am trying to create a Spring MVC HelloWorld project.There is no error in the code but for some reason when i run it on localhost i am getting "request not found" error.I have rechecked the program but not able to solve the issue.Can anyone tell me whats wrong?
ControllerClass.java (inside src folder)
@Controller
@RequestMapping("/hello")
public class ControllerClass {

    @RequestMapping(method = RequestMethod.GET)
    public String printHello(ModelMap model){

        model.addAttribute("message", "Hello Spring MVC Framework");
        return "hello";
    }
}

hello.jsp (inside jsp folder in web-inf )
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
    <title>Spring MVC example</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>

HelloWeb-servlet.xml (inside web-inf)
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.springmvcexample.xyz" />

 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
 </bean>

 </beans>

web.xml (inside lib folder of web-inf)
<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>Spring MVC Application</display-name>

<servlet>
    <servlet-name>HelloWeb</servlet-name>
    <servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>HelloWeb</servlet-name>
    <url-pattern>*.jsp</url-pattern>
</servlet-mapping>
</web-app>

A: Looks like your configuration is at the wrong location: by default HelloWeb-servlet.xml goes into the root of WEB-INF and not inside lib.
If you like to put it somewhere else you need to define a ContextLoaderListener in your web.xml.

A: change the url pattern in your web.xml file to /* instead of *.jsp
<servlet-mapping>
  <servlet-name>HelloWeb</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping>


text:
Q: PHP variables won't work after dropdown declaration I've been trying to figure out why my php variables aren't working after the declaration of a dropdown. I've narrowed it down to the dropdown after echoing the variable on all the lines leading up to the declaration, and I found that the variable stops echoing straight after the echo "<select id ='fav' name='fav'>"; Why is this happening? and how can it be fixed?
<?php
$fruit= $_POST['fruit'];
echo $fruit;
echo "
";
echo $fruit;
echo "
Favourite Fruit:";
echo $fruit;
echo "<select id ='fav' name='fav'>";
echo $fruit; //this doesn't echo
echo "<option value='Banana'>Banana</option>";
echo "<option value='Strawberry'>Strawberry</option>";
echo "<option value='No Preference'>No Preference</option>";
echo "</select>";
?>

A: You can't print any value directly. Try this will work for you.
<?php
                        $fruit= $_POST['fruit'];
                        echo $fruit;
                        echo "
";
                        echo $fruit;
                        echo "
Favourite Fruit:";
                        echo $fruit;
                        echo "<select id ='fav' name='fav'>";
                        echo "<option value='".$fruit."'>".$fruit."</option>";
                        .........................
                        .........................
                        echo "<option value='No Preference'>No Preference</option>";
                        </select>
                        ?>

A: If you look at the HTML that was generated using your browser's "view source" option, you will probably see that the echo worked fine. The reason you can't see it is that you are trying to put text inside a <select> but not inside any <option>, so there is nowhere for it to appear on the screen. This has nothing to do with it being a PHP variable.

A: Because you forgot close the select tag.close select tag :
            <?php
            $fruit= $_POST['fruit'];
            echo $fruit;
            echo "
";
            echo $fruit;
            echo "
Favourite Fruit:";
            echo $fruit;
            echo "<select id ='fav' name='fav'></select>";
            echo $fruit;
            ?>

A: I think you want this, if you put something inside
<select></select>

you have to use
<option></option>

or you can do it like,
  echo $fruit; //this doesn't echo
  echo "<select id ='fav' name='fav'>";

but not like,
 echo "<select id ='fav' name='fav'>";
 echo $fruit; //this doesn't echo

full code will be
<?php
$fruit= $_POST['fruit'];
echo $fruit;
echo "
";
echo $fruit;
echo "
Favourite Fruit:";
echo $fruit;
echo "<select id ='fav' name='fav'>";
echo '<option value="';
echo $fruit . '">';
echo $fruit;
echo '</option>';
echo '</select>';
.........................
.........................
.........................
?>

A: Your code should be like this, You can not call $fruit without any option tag.
$fruit= $_POST['fruit'];
echo "<select id ='fav' name='fav'>";
echo '<option value="';
echo $fruit . '">';
echo $fruit;
echo '</option>';
echo '</select>';
.........................


text:
Q: Have a transparent background in a plot exported from Octave I am using portable Octave 5.1.0 under Win 10.
I mean to write a plot to png with transparent background.
Disclaimer:
This question is similar to the two linked below.
I opted asking the present different question since I am adding further relevant information (by the same token, question #2 below was not a dupe of #1).
This is what I found:

*

*print(gcf,'-dpngalpha', 'myplot.png');, suggested in Saving a plot in Octave with transparent background, does not work for me.
It is remarkable that I did not find documentation on this option.

*This answer has a couple of issues for me: 1) for some unknown reason convert does nothing.   2) The requirement of an external package makes it cumbersome. For instance, I cannot simply send my Octave code to someone else for him to use it.

*Option svgconvert is the only official documentation I found.
But it would not apply to a png, e.g.

*imwrite seems to have the capability to write with transparency, but I couldn't find a way to transform a plot into and image suitable for imwrite.
(See also Matlab documentation).
Perhaps this is a possible route...
Is there any option available in Octave?
Related:

*

*Saving a plot in Octave with transparent background

*Printing / saving a plot as a png file with an alpha channel issue in Octave

*http://mlab.no/blog/2014/06/image-transparency-overlay-with-gnu-octave-using-ycbcr/

A: The imwrite option seems to work. First create the image file img_fname, then create an alpha layer for it.
It would be interesting to know if one could avoid the intermediate non-transparent file.
EDIT:
I managed to create the image directly from my plot, instead of requiring the intermediate file.
x = -10:0.1:10;
plot (x, sin (x));
# Print figure directly to image instead of file
im = print(gcf, '-RGBImage');
tcolor = [255 255 255];
alpha(:,:) = 255 * ( 1 - (im(:,:,1) == tcolor(1)) .* (im(:,:,2) == tcolor(2)) .* (im(:,:,3) == tcolor(3)) );
imwrite(im, 'temp.png', 'Alpha', alpha);

Notes:

*

*With a little simple algebra one could add transparency for any number of colors, and any opacity level for each color.
Moreover, one could move this into a function.

*The multiplication of im and tcolor could be possibly vectorized as well.
Related:
https://www.mathworks.com/matlabcentral/answers/57664-how-to-add-alpha-channel-to-the-image-and-convert-that-image-into-png-format


text:
Q: Getting error: Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes & CookieConsentProviderProps' After upgrading my packages today I started getting this error, is it possible to fix without downgrading the packages?
I saw other people having similar errors but with other packages - none of suggested fixes solved my problem.
It was working before but I'd like to keep the packages up to date, if possible.
Thank you!
The error when building:
./src/pages/_app.tsx:46:10
Type error: Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes & CookieConsentProviderProps'.

  44 |
  45 |       <SessionProvider session={session}>
> 46 |         <CookieConsentProvider>
     |          ^
  47 |           <AppContextProvider>
  48 |             {Component.auth ? (
  49 |               <Auth>

> Build error occurred
Error: Call retries were exceeded
    at ChildProcessWorker.initialize (C:\Projects\project1\node_modules\next\dist\compiled\jest-worker\index.js:1:11661)
    at ChildProcessWorker._onExit (C:\Projects\project1\node_modules\next\dist\compiled\jest-worker\index.js:1:12599)
    at ChildProcess.emit (node:events:526:28)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12) {
  type: 'WorkerError'
}
error Command failed with exit code 1.

My _app.tsx:
export interface CustomAppProps extends AppProps {
  Component: NextComponentType & { auth?: boolean };
}

function MyApp({ Component, pageProps: { session, ...pageProps } }: CustomAppProps) {
  return (
    <>
      <SessionProvider session={session}>
        <CookieConsentProvider>
          <AppContextProvider>
            {Component.auth ? (
              <Auth>
                <Component {...pageProps} />
              </Auth>
            ) : (
              <Component {...pageProps} />
            )}
          </AppContextProvider>
        </CookieConsentProvider>
      </SessionProvider>
    </>
  );
}

My package.json:
  "dependencies": {
    "@tailwindcss/forms": "^0.5.2",
    "@use-cookie-consent/react": "^0.3.6",
    "autoprefixer": "^10.4.8",
    "axios": "^0.27.2",
    "bcryptjs": "^2.4.3",
    "dateformat": "^5.0.3",
    "formik": "^2.2.9",
    "next": "^12.2.4",
    "next-auth": "^4.10.3",
    "postcss": "^8.4.16",
    "qs": "^6.11.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^4.4.0",
    "sass": "^1.54.4",
    "sharp": "^0.30.7",
    "swr": "^1.3.0",
    "tailwindcss": "^3.1.8",
    "yup": "^0.32.11"
  },

A: Its a problem with the library being incompatible with react 18. In react 18 they removed children as a default prop on the FC type. See https://github.com/use-cookie-consent/use-cookie-consent-react/issues/6
Until its fixed in the offending library to align with React 18, I'd stick a @ts-ignore in as its just an incorrect third party typing issue -- it will work fine if overridden:
export interface CustomAppProps extends AppProps {
  Component: NextComponentType & { auth?: boolean };
}

function MyApp({ Component, pageProps: { session, ...pageProps } }: CustomAppProps) {
  return (
    <>
      <SessionProvider session={session}>
        {/* @ts-ignore */}
        <CookieConsentProvider>
          <AppContextProvider>
            {Component.auth ? (
              <Auth>
                <Component {...pageProps} />
              </Auth>
            ) : (
              <Component {...pageProps} />
            )}
          </AppContextProvider>
        </CookieConsentProvider>
      </SessionProvider>
    </>
  );
}


text:
Q: MSGraph groups webhook eventTime I'm listening to groups endpoint via webhook.
I perform the follow actions via Outlook Online +Group

*

*Create Group

*Set Owner

*Add one member

I got a webhook event for all three at once, this is fine, I assume things are batched.  But the eventTime is identical – which makes it difficult to understand the order these events happened.  So I was asking for clarification whether the resourceData.eventTime should be the same, or should they have been different.

{
  "value": [
    {
      "changeType": "updated",
      "clientState": "its_me_flow",
      "resource": "Groups/7763cbdb-7f79-4b95-bb3b-d8e83413f7ad",
      "resourceData": {
        "@odata.type": "#Microsoft.Graph.Group",
        "@odata.id": "Groups/7763cbdb-7f79-4b95-bb3b-d8e83413f7ad",
        "id": "7763cbdb-7f79-4b95-bb3b-d8e83413f7ad",
        "organizationId": "26e65220-5561-46ef-9783-ce5f20489241",
        "eventTime": "2018-02-13T00:20:03.9107966Z"
      },
      "subscriptionExpirationDateTime": "2018-02-13T04:07:19.7318815+00:00",
      "subscriptionId": "c8c521bf-2bcb-4b93-821f-40a1fb72c0f8"
    },
    {
      "changeType": "updated",
      "clientState": "its_me_flow",
      "resource": "Groups/7763cbdb-7f79-4b95-bb3b-d8e83413f7ad",
      "resourceData": {
        "@odata.type": "#Microsoft.Graph.Group",
        "@odata.id": "Groups/7763cbdb-7f79-4b95-bb3b-d8e83413f7ad",
        "id": "7763cbdb-7f79-4b95-bb3b-d8e83413f7ad",
        "organizationId": "26e65220-5561-46ef-9783-ce5f20489241",
        "eventTime": "2018-02-13T00:20:03.9107966Z",
        "owner@delta": [
          {
            "id": "36e3b856-3c2e-4605-ac5f-99064d229c3a"
          }
        ]
      },
      "subscriptionExpirationDateTime": "2018-02-13T04:07:19.7318815+00:00",
      "subscriptionId": "c8c521bf-2bcb-4b93-821f-40a1fb72c0f8"
    },
    {
      "changeType": "updated",
      "clientState": "its_me_flow",
      "resource": "Groups/7763cbdb-7f79-4b95-bb3b-d8e83413f7ad",
      "resourceData": {
        "@odata.type": "#Microsoft.Graph.Group",
        "@odata.id": "Groups/7763cbdb-7f79-4b95-bb3b-d8e83413f7ad",
        "id": "7763cbdb-7f79-4b95-bb3b-d8e83413f7ad",
        "organizationId": "26e65220-5561-46ef-9783-ce5f20489241",
        "eventTime": "2018-02-13T00:20:03.9107966Z",
        "members@delta": [
          {
            "id": "36e3b856-3c2e-4605-ac5f-99064d229c3a"
          },
          {
            "id": "9b47aca9-efc6-488c-8afd-c323eccad4b4"
          }
        ]
      },
      "subscriptionExpirationDateTime": "2018-02-13T04:07:19.7318815+00:00",
      "subscriptionId": "c8c521bf-2bcb-4b93-821f-40a1fb72c0f8"
    }
  ]
}

see the eventTime is identical.  From the looks of the owner@delta and members@delta it looks like the order is correct, but is can I trust the array order?  Much prefer if the eventTime was sequential.

A: This is similar to receiving a page of changes via Delta Query, where many objects can be included a single page and order of changed object in a page follows some logic order. (eg: in your case owner add followed by member add).
Since ordering of events is not guaranteed with webhooks, eventTime is meant to help order pages of events received at different points of time. ex: Microsoft graph is attempting to send pages of changes P1 and P2 at time T1 and T2. However the target webhook endpoint was down at time T1, so Microsoft graph will retry with exponential delay upto 4 hours. While webhook endpoint might be available at time T2. So page P2 is received first, followed by P1 in this case. To help clients distinguish and order events on their end, eventTime field can be used.


text:
Q: i am getting this Exception "Parameter is not valid.at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)" i made the image re size Handler. i am getting this Exception.

"HttpApplication.ExecuteStep =>
  CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute
  => ImageHandler.ProcessRequest|System.ArgumentException: Parameter is not valid.    at System.Drawing.Bitmap..ctor(Int32 width, Int32
  height, PixelFormat format)    at
  Holmgrens.ImageResize.IMGHandller.ImageHandler.ProcessRequest(HttpContext
  context)".

Here is my code.
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Drawing;
using System.IO;

namespace Xyz.ImageResize.IMGHandller
{
    public class ImageHandler : IHttpHandler
    {

        // incoming query string variables

        private string imagePath = string.Empty;        // path=    virtual path required

        private string imageWidth = "0";                // w=   0 means use original

        private string imageHeight = "0";               // h=

        private string imageQuality = "0";              // q=

        private string constrainProportions = "true";   // cp=  true or false

        private string rotation = "0";                  // r= rotation in degrees, optional, 0 is default.

        private const Int32 maxQuality = 100;

        private const Int32 minQuality = 30;

        private const string imageNotFound = "~/SlideData/TempImg/Desert.jpg";

        private string mimeType = "image/jpeg";

        //get imag config item
        //ImageConfiguration imgconsetting = new ImageConfiguration();

        public void ProcessRequest(HttpContext context)
        {

            try
            {

                // get query string parameters

                imagePath = context.Request.QueryString["path"];

                imageWidth = context.Request.QueryString["w"];

                imageHeight = context.Request.QueryString["h"];

                imageQuality = context.Request.QueryString["q"];

                constrainProportions = context.Request.QueryString["cp"];

                rotation = context.Request.QueryString["r"];

                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(imagePath)))
                {

                    imagePath = HttpContext.Current.Server.MapPath(imagePath);

                }

                else
                {

                    // displays an empty image holder or make sure you have a not found image

                    imageQuality = "100";

                    imagePath = HttpContext.Current.Server.MapPath(imageNotFound);

                }

                //get file info

                FileInfo fi = new FileInfo(imagePath);
                if (fi.Extension.ToLower() == ".gif")
                    mimeType = "image/gif";
                else if (fi.Extension.ToLower() == ".png")
                    mimeType = "image/png";
                else
                    mimeType = "image/jpeg";

                // sets the HTTP MIME type of the output stream.

                // jpeg is default

                context.Response.ContentType = mimeType;

                // clear all content output from the buffer stream

                context.Response.Clear();

                // response is cacheable by clients and shared (proxy) caches
                context.Response.Expires = 24 * 60; //one day;
                string ETag = Hash.GetHash(string.Format("{0}{1}", imagePath, fi.LastWriteTimeUtc.ToString()), Hash.HashType.MD5);
                context.Response.Cache.SetCacheability(HttpCacheability.Public);
                context.Response.Cache.SetLastModified(fi.LastWriteTimeUtc);
                context.Response.Cache.SetETag(string.Format("\"{0}\"", ETag));

                // Buffer response so that page is sent

                // after processing is complete.

                context.Response.BufferOutput = true;

                //if image height is zero,calculate the image height with aspect ration of image
                if (imageHeight == "0")
                {
                    imageHeight = ImageHeightWithAspect(imagePath, Convert.ToInt16(imageWidth)).ToString();

                }

                Int32 originalWidth = 0;

                Int32 originalHeight = 0;

                Int32 newWidth = 0;

                Int32 newHeight = 0;

                Int64 quality = 0;

                // set the quality of the jpeg image returned.. 30 (low) - 100 (high)

                if (Int64.TryParse(imageQuality, out quality))
                {

                    if (quality > maxQuality) { quality = maxQuality; }

                    if (quality < minQuality) { quality = minQuality; }

                }

                else

                { quality = maxQuality; }

                // ENCODING

                System.Drawing.Imaging.Encoder encoder =

                  System.Drawing.Imaging.Encoder.Quality;

                System.Drawing.Imaging.EncoderParameter encoderParameter =

                    new System.Drawing.Imaging.EncoderParameter(encoder, quality);

                // create an array with one parameter; quality

                System.Drawing.Imaging.EncoderParameters codecParams =

                    new System.Drawing.Imaging.EncoderParameters(1);

                codecParams.Param[0] = encoderParameter;

                // Gets the codecs for this image type (jpeg)

                System.Drawing.Imaging.ImageCodecInfo codecInfo = getEncoderInfo();

                // Create a bitmap to hold new image, uses Bitmap.GetThumbnailImage

                using (System.Drawing.Bitmap bitmapOriginal = new System.Drawing.Bitmap(imagePath))
                {

                    originalWidth = bitmapOriginal.Width;

                    originalHeight = bitmapOriginal.Height;

                    Int32.TryParse(imageWidth, out newWidth);

                    Int32.TryParse(imageHeight, out newHeight);

                    if (newWidth > originalWidth) { newWidth = originalWidth; }

                    if (newHeight > originalHeight) { newHeight = originalHeight; }

                    // Constrain Proportions provides scaling by width

                    // False by default which forces width and height - when exact size required

                    if (!string.IsNullOrEmpty(constrainProportions)

                        && constrainProportions.Equals("true", StringComparison.OrdinalIgnoreCase))
                    {

                        newWidth = Convert.ToInt32(imageWidth);

                        Double scaleFactor = 0.0;

                        // scale the image based on the width

                        if (originalWidth > originalHeight)
                        {

                            // landscape

                            Int32 largestDimension = (Math.Max(originalWidth, originalHeight));

                            scaleFactor = ((Double)newWidth / (Double)largestDimension);

                        }

                        else
                        {

                            // portrait

                            Int32 smallestDimension = (Math.Min(originalWidth, originalHeight));

                            scaleFactor = ((Double)newWidth / (Double)smallestDimension);

                        }

                        newHeight = Convert.ToInt32((originalHeight * scaleFactor));

                    }

                    // Create the new bitmap image

                    using (System.Drawing.Bitmap bitmapNew = new System.Drawing.Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
                    {

                        // use the same resolution

                        bitmapNew.SetResolution(bitmapOriginal.HorizontalResolution, bitmapOriginal.VerticalResolution);

                        // Create the graphics object to draw the old bitmap on the new sized bitmap.

                        using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmapNew))
                        {

                            // resize using the highest possible quality for best results

                            graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                            graphic.DrawImage(bitmapOriginal,

                                new System.Drawing.Rectangle(-1, -1, newWidth + 1, newHeight + 1), // destination

                                new System.Drawing.Rectangle(0, 0, originalWidth, originalHeight), //source

                                System.Drawing.GraphicsUnit.Pixel); //using pixels
                            graphic.Dispose();

                        }

                        // Rotate the bitmap

                        switch (Convert.ToInt32(rotation))
                        {

                            case 90:

                                bitmapNew.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);

                                break;

                            case 180:

                                bitmapNew.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

                                break;

                            case 270:

                                bitmapNew.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);

                                break;

                            default:

                                // always show as original

                                bitmapNew.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipNone);

                                break;

                        }

                        // context.Response.OutputStream enables binary output to the outgoing HTTP content body.

                        // codecInfo is the image type (jpeg)

                        // codecParams is the quality
                        Bitmap bm = new Bitmap(bitmapNew);
                        bitmapNew.Dispose();
                        //bm.Save(context.Response.OutputStream, codecInfo, codecParams);
                        //bm.Dispose();
                        using (MemoryStream stream = new MemoryStream())
                        {
                            bm.Save(stream, codecInfo, codecParams);
                            stream.WriteTo(context.Response.OutputStream);
                            stream.Dispose();
                        }
                        bm.Dispose();

                    }
                    bitmapOriginal.Dispose();

                }
                encoderParameter.Dispose();
                codecParams.Dispose();
            }
            catch(Exception ex)
            {
                response.write(ex);

            }

        }

        /// <summary>

        /// Return the codec info for jpeg images

        /// </summary>

        /// <param name="mimeType"></param>

        /// <returns></returns>

        private System.Drawing.Imaging.ImageCodecInfo getEncoderInfo()
        {

            System.Drawing.Imaging.ImageCodecInfo[] encoders;

            encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();

            Int32 i = 0;

            while (i < encoders.Length)
            {

                if (encoders[i].MimeType == mimeType)
                {

                    return encoders[i];

                }

                i++;

            }

            return null;

        }

        public bool IsReusable

        { get { return true; } }

        private int ImageHeightWithAspect(string fileName,int newWidth)
        {

            Image original = Image.FromFile(fileName);

            //Find the aspect ratio between the height and width.

            float aspect = (float)original.Height / (float)original.Width;

            //Calculate the new height using the aspect ratio

            // and the desired new width.

            int newHeight = (int)(newWidth * aspect);

            //Dispose of our objects.

            original.Dispose();
            return newHeight;

        }
    }
}

please guide me how to remove this exception.
thanks
Humayoo

A: Either your newWidth or newHeight is incorrect in this line:
using (System.Drawing.Bitmap bitmapNew = new System.Drawing.Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb))

You need to debug your application to determine what the incorrect value is and how to fix it.


text:
Q: How should I mount docker volumes in mlflow project? I use mlflow in a docker environment as described in this example and I start my runs with mlflow run ..
I get output like this
2019/07/17 16:08:16 INFO mlflow.projects: === Building docker image mlflow-myproject-ab8e0e4 ===
2019/07/17 16:08:18 INFO mlflow.projects: === Created directory /var/folders/93/xt2vz36s7jd1fh9bkhkk9sgc0000gn/T/tmp1lxyqqw9 for downloading remote URIs passed to arguments of type 'path' ===
2019/07/17 16:08:18 INFO mlflow.projects: === Running command 'docker run
--rm -v /Users/foo/bar/mlruns:/mlflow/tmp/mlruns -e
MLFLOW_RUN_ID=ef21de61d8a6436b97b643e5cee64ae1 -e MLFLOW_TRACKING_URI=file:///mlflow/tmp/mlruns -e MLFLOW_EXPERIMENT_ID=0 mlflow-myproject-ab8e0e4 python train.py' in run with ID 'ef21de61d8a6436b97b643e5cee64ae1' ===

I would like to mount a docker volume named my_docker_volume to the container
 at
the path /data. So instead of the docker run shown above, I would like to
 use
docker run --rm --mount source=my_docker_volume,target=/data -v /Users/foo/bar/mlruns:/mlflow/tmp/mlruns -e MLFLOW_RUN_ID=ef21de61d8a6436b97b643e5cee64ae1 -e MLFLOW_TRACKING_URI=file:///mlflow/tmp/mlruns -e MLFLOW_EXPERIMENT_ID=0 mlflow-myproject-ab8e0e4 python train.py

I see that I could in principle run it once without mounted volume and then
copy the docker run ... and add --mount source=my_volume,target=/data but
 I'd rather use something like
mlflow run --mount source=my_docker_volume,target=/data .

but this obviously doesn't work because --mount is not a parameter for
mlflow run.
What's the recommened way of mounting a docker volume then?

A: A similar issue has been brought up on the mlflow issue tracker, see "Access large data from within a Docker environment". An excerpt from it says:

However, MLFlow Docker environments currently only have access to data baked into the repository or image or must download a large dataset for each run.
...
A potential solution is to enable the user to mount a volume (e.g. local directory containing the data) into the Docker container.

Looks like this is feature others would benefit from too. Best course of action here would be to contribute support for mounts, or keep track of the issue until someone else implements it.
Why do you need to mount /data folder in the first place? There's another issue, a PR containing a fix related to storing artifacts in a custom location on host machine, could it be something you're looking for?

A: Finally, to avoid the above problem and facilitate volume mounting, I now run my experiments using three interacting docker containers. One that runs the machine learning code, one that runs an mlflow server and one that runs a postgresql server. I closely followed this walk-through article to set things up. It works nicely and docker-compose makes volume mounting easy. Metrics, parameters and meta data are stored in a database that is mounted to a local persistent volume. Artifacts are logged in the directory /mlflow or if you prefer in a docker volume.
Note: There's a typo in the cited walk-through article
In docker-compose.yml it shouldn't be
volumes:
  - ./postgres-store:/var/lib/postgresql/data

which would bind a local folder named postgres-store.
Instead, to mount the docker volume postgres_store, you should use
volumes:
  - postgres-store:/var/lib/postgresql/data


text:
Q: Is there a way to exclude specific columns from post data while sending to the controller using iggrid saveChanges event? Is there any way that I can exclude specific columns from posting to the controller after "saveChanges" event called in the igGrid?
Example:
    $("#{{gridName}}").igGrid({
        autoGenerateColumns: false,
        primaryKey: "id",
        columns: JSON.parse('{{igniteTableColumns|raw}}'),
        updateUrl: "/path-to-controller-action",
        features: [
            {
                name : 'Updating',
                enableAddRow: false,
                enableDeleteRow: false,
                saveChangesSuccessHandler : function (data) {
                    $("#message").text("Changes were saved successfully").fadeIn(3000).fadeOut(5000);
                },
                columnSettings: [
                    {
                        columnKey: "id",
                        editorOptions: {
                            readOnly: true
                        }
                    },
                    {
                        columnKey: "event_date",
                        editorType: 'datepicker',
                        validation: true,
                        editorOptions: {
                            dateFormat: 'MM-dd-yy',
                            required: true,
                            dropDownTriggers: 'focus'
                        }
                    },
                    {
                        columnKey: "event",
                        editorType: 'text',
                        validation: true,
                        editorOptions: {
                            required: true
                        }
                    },
                    {
                        columnKey: "history",
                        editorOptions: {
                            readOnly: true
                        }
                    },
                    {
                        columnKey: "delete",
                        editorOptions: {
                            readOnly: true
                        }
                    }
                ]
            }
        ],
        width: "100%",
        autoCommit: true,
        dataSource: JSON.parse('{{igniteTableData|raw}}'),
        dataSourceType: "json",
        responseDataKey: "igniteTableData"
    });

    $("#saveChanges").click(function () {
        $("#{{gridName}}").igGrid("saveChanges");
    });

In the above example, all the specified columns are posting to the controller. But I want to exclude the "history" and "delete" columns from the post data.
Because I don't want to go through each array and manually remove these columns from the post data before pushing the data to the data base to save.

A: In general, the control assumes that you want to be posting the whole entity it has been bound to back to your service. If you want, you can modify the pending transactions object before calling saveChanges.
var trasnactions = $("#{{gridName}}").igGrid("option", "dataSource").pendingTransactions();

https://www.igniteui.com/help/api/2018.2/ig.datasource#methods:pendingTransactions


text:
Q: Reconstitute a user from time machine On OSX Catalina, I have deleted a user and did not set aside a backup. However, going back on Time Machine, I can find the user directory.
I am considering creating a new user with the same name as the old user, and then replacing the new user's directory with the old user directory from Time Machine. Are there other setting  or files from the old User I should also be restoring?
Is there a better way of doing this.


text:
Q: Install editable(-e) package using requirements.txt but constrained on Python Version I'm working on a Python project that has an existing pip-requirements.txt file.
In this file a certain dependency is brought in using the -e flag (editable) from an internal git repository:
# pip-requirements.txt

# Patched version of SomeDependency
-e git+https://github.com/internal-org/SomeDependency#egg=SomeDependency

The dependency, as the comment suggests is a patched(read: forked) dependency that fixes a certain bug and is needed for use with the Python Version that's currently being used.
We are in the process of upgrading our Python version and this dependency is now irrelevant for the newer Python version but still relevant for the older Python version.
We would like to install a specific version based on the Python Version that's being used. So We'd like to do something like this:
SomeDependency==2.0.0 ; python_version == "3.9"

# Patched version of SomeDependency
-e git+https://github.com/internal-org/SomeDependency#egg=SomeDependency ; python_version < "3.9"

This however does not work, and looking through the documentation I haven't found if this is possible with the -e flag.
I've tried setting a constraints file but this doesn't work, and also using different flags on the command but none seem to work/change the behaviour
Any help and guidance will be appreciated
Thanks!


text:
Q: Adding a message icon to Dijit Dialog I am new to Dojo and I am trying to create a (dijit) Dialog pop up that displays a message and an icon. I am doing this programatically and I have managed to create the Dialog but I have not been able to figure out how to add the icon image into the dialog.
I found a solution that seemed promising but it ended up not working.
Heres what I tried
dialog declaration in Dialog.js
this.myDialog = new Dialog({

                        title: this.title,
                        content: ""+this.content+""+"
",
                        doLayout: false,
                        style: "width: 50%"
                        });

Icon class in CSS
.myIcon {
 background: url("fakepath/images/32.png");
 background-repeat: no-repeat;
 width: 16px;
 height: 16px;
 text-align: left;
}

Declaring the dialog in the jsp
<ui:dialog title="Dialog Box" id="myDialog" content="Hi There"
     buttonType="OK" iconClass="myIcon"></ui:dialog>

I get a dialog pop up with a message but no icons or even a hint of one (the empty placeholder you get when the image path is wrong)

A: dijit/Dialog does not support an iconClass property, so nothing is being done with the value you set.
Where are you expecting the icon to appear?  In the title bar or as part of the content window?
If you want it in the title bar then you will need to override the template that the Dialog uses when you instantiate the widget and make a place for the icon in the overridden template.
See dijit/templates/Dialog.html
If you want it as part of the content window, then you need to write that into the html that you set as content.

      Your message here.


text:
Q: Generating key bytes without KeyGenerator With an environments without JCA(JCE) such as Java ME, would it be OK to generating key (or iv) bytes with java.util.Random?
// MIDP
// MIDP
// MIDP

private static final Random RANDOM = new Random();

/**
 * Generates a new encryption key. This method is not intended to be used in
 * production stage.
 *
 * @return a new encryption key.
 */
protected static byte[] newKey() {

    final Random random;
    synchronized (RANDOM) {
        random = new Random(RANDOM.nextLong());
    }

    final byte[] key = new byte[256]; // AES 256
    for (int i = 0; i < key.length; i++) {
        key[i] = (byte) random.nextInt(256);
    }

    return key;
}

Is there any crypto-graphic concerns?
Is there any typos in this question including the source codes and comments? (I'm not good at in Uslish.)


text:
Q: How to add new attribute that need to be calculated recursively in JavaScript I want to dynamically add new attribute to all of the items in an array using map. But while adding it to each item, the value of this attribute is the sum of all previous items newly added attribute
Consider this example :
let persons = [{
"name": "A",
 "salary": 2
}, {
"name": "B",
 "salary": 5
},{
"name":"C",
"salary":12
}];

I want to return :
[{
    "name": "A",
     "salary": 2,
     "sumSalary":2
    }, {
    "name": "B",
     "salary": 5,
     "sumSalary":7
    },{
    "name":"C",
    "salary":12,
    "sumSalary":19
   }];

I've tried this one:
let mutatedPersons = persons.map((currentValue, index, mutatedPersons) => ({
  ...currentValue,
    sumSalary: currentValue.name === 'A' ? currentValue.salary : mutatedPersons[index - 1].sumSalary + currentValue.salary
}))

but i keep getting this :
[
  0: {name: "A", salary: 2, sumSalary: 2}
  1: {name: "B", salary: 5, sumSalary: NaN}
  2: {name: "C", salary: 12, sumSalary: NaN}
]

A: The mutatedPersons you refer to is the original array (see map's parameters), and not the updated array, which doesn't actually exist before the map end. You can cache the previous sum in an external variable (prevSumSalary), and use it as the basis of the new one:

const persons = [{ name: "A", salary: 2 }, { name: "B", salary: 5 }, { name: "C", salary: 12 }]

let prevSumSalary = 0;
const mutatedPersons = persons.map((currentValue, index) => ({
  ...currentValue,
    sumSalary: (prevSumSalary = prevSumSalary + currentValue.salary)
}))

console.log(mutatedPersons);

Another option is to use Array.reduce(), since you have access to the accumulated values:

const persons = [{ name: "A", salary: 2 }, { name: "B", salary: 5 }, { name: "C", salary: 12 }]

const mutatedPersons = persons.reduce((r, currentValue) => [...r,
  ({
    ...currentValue,
      sumSalary: currentValue.salary + (r.length && r[r.length - 1].sumSalary)
  })
], [])

console.log(mutatedPersons);

A: You could use a closure over sum and take it for added sumSalary property.

var data = [{ name: "A", salary: 2 }, { name: "B", salary: 5 }, { name: "C", salary: 12 }],
    result = data.map((sum => o => ({ ...o, sumSalary: sum += o.salary }))(0));

console.log(result);

A:

let persons = [{
"name": "A",
 "salary": 2
}, {
"name": "B",
 "salary": 5
},{
"name":"C",
"salary":12
}];

let sum = 0;
persons.map(curr => {
  sum += curr.salary;
  curr.sumSalary = sum;
});

console.log(persons);

A: This is an ideal case for Array#reduce.
One can use an accumulator (the whole salarySum) to get direct access to the last salarySum value.
Whenever one thinks about an aggregate function, one should immediately think about Array#reduce in first place!
Also, I've provided you a solution which doesn't mutate the source persons but it creates a new array which has salarySum on each item:

const persons = [{
  name: "A",
  salary: 2
}, {
  name: "B",
  salary: 5
}, {
  name: "C",
  salary: 12
}]

const {
  persons: persons_,
  salarySum
} = persons.reduce((result, person) =>
  result.persons.push({
    ...person,
    salarySum: (result.salarySum += person.salary)
  }) && result, {
    salarySum: 0,
    persons: []
  })

console.log(persons_)
console.log(salarySum)


text:
Q: Why if I print an address does it solve my code problem? My code has a problem with a variable taking value from another one but when I print its address, it doesn't do it anymore. "Tiempo" keep taking the value from "Ahorrado" or "mes[2]".
When I printf the "tiempo" address, it stops doing it.
int main(void)
{
    int mes[2];
    int ahorrado=0;
    int tiempo=0;

    mes[0]=100;
    tiempo++;

    //printf("",&tiempo);

    printf("%d%c ",tiempo,167);
    printf("mes: %d\n",mes[0]);

    mes[1]=100;
    tiempo++;

    printf("%d%c ",tiempo,167);
    printf("mes: %d\n",mes[1]);

    mes[2]=mes[0]+mes[1];
    tiempo++;
    ahorrado=mes[2];

    printf("%d%c ",tiempo,167);
    printf("mes: %d\nAhorrado: %d\n",mes[2],ahorrado);

    mes[1]=mes[2];
    mes[2]=mes[0]+mes[1];
    tiempo++;
    ahorrado+=mes[2];

    printf("%d%c",tiempo,167);
    printf("mes: %d + %d\nAhorrado: %d\n",mes[0],mes[1],ahorrado);

    mes[0]=mes[1];
    mes[1]=mes[2];

    while(ahorrado<=20000)
    {
        tiempo++;
        printf("%d%c",tiempo,167);
        printf("mes: %d + %d\nAhorrado: %d\n",mes[0],mes[1],ahorrado);
        mes[2]=mes[0]+mes[1];
        ahorrado+=mes[2];
        mes[0]=mes[1];
        mes[1]=mes[2];
    }

    printf("%d",ahorrado);
    return 0;
}

i expect the "mes" showing 1 plus 1 not in high jump numbers.


text:
Q: UITextFieldDelegate textFieldShouldReturn with ReactiveCocoa I am trying to implement UITextFieldDelegate textFieldShouldReturn handling with ReactiveCocoa. Unfortunately the subscribeNext block is run when I subscribe for the signal.
The implementation using delegation would be:
- (void)viewDidLoad
{
    ...
    self.myTextField.delegate = self;
}

...

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.myTextField) {
        NSLog(@"Let's go!");
    }

    return YES;
}

In ReactiveCocoa I have added a category for UITextField in a similar fashion like UITextView+RACSignalSupport.
@implementation UITextField (RACKeyboardSupport)

static void RACUseDelegateProxy(UITextField *self)
{
    if (self.delegate == self.rac_delegateProxy) return;

    self.rac_delegateProxy.rac_proxiedDelegate = self.delegate;
    self.delegate = (id)self.rac_delegateProxy;
}

- (RACDelegateProxy *)rac_delegateProxy
{
    RACDelegateProxy *proxy = objc_getAssociatedObject(self, _cmd);
    if (proxy == nil) {
        proxy = [[RACDelegateProxy alloc] initWithProtocol:@protocol(UITextFieldDelegate)];
        objc_setAssociatedObject(self, _cmd, proxy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }

    return proxy;
}

- (RACSignal *)rac_keyboardReturnSignal
{
    @weakify(self);
    RACSignal *signal = [[[[RACSignal
                            defer:^{
                                @strongify(self);
                                return [RACSignal return:RACTuplePack(self)];
                            }]
                           concat:[self.rac_delegateProxy signalForSelector:@selector(textFieldShouldReturn:)]]
                          takeUntil:self.rac_willDeallocSignal]
                         setNameWithFormat:@"%@ -rac_keyboardReturnSignal", [self rac_description]];

    RACUseDelegateProxy(self);

    return signal;
}

@end

Here subscribeNext block is executed even if the Return Key was never pressed:
- (void)viewDidLoad
{
    ...
    [self.myTextField.rac_keyboardReturnSignal subscribeNext:^(id x) {
        Log(@"Let's go with RAC!");
    }];
}

I have to use skip:1 to avoid that problem:
- (void)viewDidLoad
{
    ...
    [[self.myTextField.rac_keyboardReturnSignal skip:1] subscribeNext:^(id x) {
        Log(@"Let's go with RAC!");
    }];
}

Any idea why this happens?
Solution:
- (RACSignal *)rac_keyboardReturnSignal
{
    RACSignal *signal = [[[self.rac_delegateProxy
                           signalForSelector:@selector(textFieldShouldReturn:)]
                          takeUntil:self.rac_willDeallocSignal]
                         setNameWithFormat:@"%@ -rac_keyboardReturnSignal", [self rac_description]];

    RACUseDelegateProxy(self);

    return signal;
}

A: You are returning a signal that immediately returns a value in your defer block, then concat-ing new values onto the stream when textFieldShouldReturn is invoked.
The code in UITextView+RACSignalSupport.m is calling reduceEach in order to return a string value that is extracted from the UITextView instance. The defer is used to merely have an initial value generated upon subscription.
Basically, I don't think you want the defer at all for your use case.


text:
Q: How do I stop only some instances of a coroutine in Unity I'm making a 2d game and I need to fade some elements in and out.
IEnumerator FadeOut(Renderer rend, float speed)
    {
        while (rend.material.color.a > 0)
        {
            Color objectColor = rend.material.color;
            float fadeAmount = objectColor.a - (speed * Time.deltaTime);
            objectColor = new Color(objectColor.r, objectColor.g, objectColor.b, fadeAmount);
            rend.material.color = objectColor;
            yield return null;
        }
    }

That's my FadeOut coroutine (the FadeIn script is this exact coroutine but inversed). The problem with this is that it bugs. For example if I enter and exit multiple times an area which needs to fade out, the whole game just blends black (or too bright). I solved this problem by using theStopAllCoroutines function.
One of the coroutine calls:
StopAllCoroutines();
StartCoroutine(FadeOut(tilemap,1f));

I would rather to not use StopAllCoroutines as I'm using multiple coroutines in the same game, entering a fade area would just shut down a half of the system.
I tried using StopCoroutine("name") (but from what I've found out, it's not compatible with newer versions of unity).
I also got on another thread on StackOverflow
Code from the thread:
routines[col] = StartCoroutine((DamageEverySecond(health, damageRate)));
[...]
StopCoroutine(routine);

Unfortunatelly this doesn't solve for my problem as there are multiple instances running at the same time.
How can I solve this problem?

A: That

Code from the thread
routines[col] = StartCoroutine((DamageEverySecond(health, damageRate)));
[...]
StopCoroutine(routine);

that code does not use the "name" .. it rather uses an instance of Coroutine which is returned by StartCoroutine and is exactly what you want to do:
private Coroutine fadeOutRoutine;

then when you start one you do e.g.
fadeOutRoutine = StartCoroutine(FadeOut(tilemap,1f));

and you can stop it using
StopCoroutine(fadeOutRoutine);

or if there are many routines you coud do
private List<Coroutine> fadeOutRoutines;

then when you start one you do e.g.
fadeOutRoutines.Add(StartCoroutine(FadeOut(tilemap,1f)));

and you can stop a specific (e.g. the last started) routine using
var index = fadeOutRoutines.Count - 1;

StopCoroutine(fadeOutRoutines[index]);
fadeOutRoutines.RemoveAt(index);


text:
Q: how to change default button from .Xdefaults? I am trying to hide/desensitize the default button in an application that although I have source for, I cannot/may not compile.
Here is (part of) the code:
_messageBox = XtVaCreateManagedWidget("_messageBox",
        xmMessageBoxWidgetClass,
        _form,
        XmNmarginHeight, 0,
                    XmNnavigationType, XmNONE,
        XmNtraversalOn, False,
                    XmNtopAttachment, XmATTACH_WIDGET,
                    XmNtopWidget, separatorBottom,
                    XmNrightAttachment, XmATTACH_FORM,
        NULL);

XtVaSetValues(XmMessageBoxGetChild(_messageBox, XmDIALOG_OK_BUTTON),
              XmNhighlightThickness, 0,
              NULL);

I would like to be able to something like the following in my .Xdefaults file:
tgui*_messageBox*DIALOG_OK_BUTTON*foreground: red

I don't know how to reference the button in the .Xdefaults file.
Any suggestions?


text:
Q: how to fix Javax. Naming.exception: nameNotFoundException  not found I got this exception while trying to deploy ejb-jar file on a glassfish 2.1 :
Javax. Naming.exception: nameNotFoundException  not found.
This drive me to be crazy !!!
I don't know why i got this exception while when i launch the hole application (ear) using Netbeans 6.7.1 with integrated glassfish 2.1 it work like magic !
But when i try to deploy it manually under another glassfish in an other pc it does not work
And i am having this exception when i try to deploy it
So i think that the ejb module does not find out how to link to the database
So it must be something that the netbeans do and i am not, when deploying the ejb-jar
Any help ?

A: I realise this is a bit old, but having just worked through this, I thought I may as well document it here.
For me the issue was the database connection. In your project you should have a persistence.xml file (mine was in the EJB project), which details the database connection parameters. I was using a localhost URL, but when I ran the database project, I noticed in my Services tab under Glassfish that no database connection was being registered.
Here's what I did:

*

*Create a new database connection (right click in Services, Java DB node)

*In Services, right click Java DB connection, Properties, check that the pool it's registered to is in the Glassfish JDBC Connection Pools and is the correct one, if not, make sure your database connection is correct, update persistence.xml

*Clean the project before running again

This worked for me, hope it's helpful for someone else.


text:
Q: Remove focus from all Edit Text after click on OK from Alert Dialog My Activity contain three EditText and one button.
I set custom AlertBox for get the User input on one EditText.
When I click on OK button from Alert Box , Focus Automatically goes to First EditText.
I used
editext.clearFocus();

I also tried
editText.clearFocus();
editText.setEnabled(false);

But doesn't work.
How to remove focus in All EditText after click on OK from AlertDialog.
Thanks in Advance.

A: To clear focus and remove cursor from editText
editText.clearFocus();
editText.setFocusable(false);
editText.setFocusableInTouchMode(true);
editText.setCursorVisible(false);

A: Try adding this in the root layout of your xml:
android:focusable="true"
android:focusableInTouchMode="true"

A: This worked for me
public void clicked(View v)
{
    final AlertDialog.Builder alert=new AlertDialog.Builder(this);
    alert.setTitle("Hello");
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            editText.setFocusable(false);
        }
    });

    alert.create();
    alert.show();
}

A: I am using this and it is working perfectly. On Clicking the option of submitting it will clear the focus and remove cursor on edit text.
getCurrentFocus().clearFocus();


text:
Q: Azure Service Bus - How to Add Topic Subscriber Programmatically I'm trying to implement a basic pub/sub system with dynamic subscribers. I need to dynamically register a topic subscriber in my .NET APIs, but it seems like I can only do that manually from the Azure Portal. When my program starts, I want to be able to register a subscriber to a topic in the format of subscribername-{timestamp} because I want to be able to deploy as many staging/dev versions as I want without having to manually create these subscribers each time.
I feel like this is a fundamental feature that I'm just blindly missing. I can do this when working with queues, but if I try to do the same with a topic, I get continuous errors of that subscriber path not found. I have searched the internet to no end and while I have found SOME solutions, they are very old and often not compatible with .NET 5 or the package is deprecated. I'm feeling like I'm going against the grain and missing something with what I'm coming up with, so I'd like to get some input on what the proper practice is for this.
I'm using Azure.Messaging.ServiceBus for publishing and subscribing currently. Below is some code -
var processor = ServiceBusClient.CreateProcessor(TopicName, $"DynamicSubscriber-{DateTime.Now}");

try
{
    processor.ProcessErrorAsync += ErrorHandler;
    processor.ProcessMessageAsync += MessageHandler;
    await processor.StartProcessingAsync();
}
catch (Exception e)
{
    await processor.DisposeAsync();
    await ServiceBusClient.DisposeAsync();
}
finally
{
    Console.WriteLine("Press a key to exit.");
    Console.ReadLine();
}

A: Thank You @PeterBons! Yes, when updating/creating/fetching/deleting the Service Bus entities, ServiceBusAdministrationClient is the client Class to be used.
Also, There are few error details given this article when using the method of Queue with ServiceBusAdministrationClient and this SO Thread.
The ServiceBusTopicSubscription class is used to setup the Azure Service bus subscription. The class uses the ServiceBusClient to set up the message handler, the ServiceBusAdministrationClient is used to implement filters and add or remove these rules. The Azure.Messaging.ServiceBus Nuget package is used to connect to the subscription.


text:
Q: Formulating both general and specific stub-methods? in order to test another class, I want to create a stub for an interface IFoo:
public interface IFoo
{
    int DoSomething(int value);
}

The stub is created in the SetUp (or TestInitialize)-method for the test fixture and stored in a property as almost all test methods need an IFoo:
this.Foo = MockRepository.GenerateStub<IFoo>();

As IFoo.DoSomething needs just to return the passed value in all cases except one I added this behavior to my SetUp method:
this.Foo.Stub(f => f.DoSomething(0)).IgnoreArguments().Return(0).WhenCalled(mi => mi.ReturnValue = mi.Arguments[0]);

Now, however, this one test requires different behavior: Rather than returning the passed argument, a constant should be returned if the passed value equals another constant. The following approach (written in the test method itself) does not work:
this.Foo.Stub(f => f.DoSomething(42)).Return(43);

The previous specified, more general stub seems to override the more specific stub.
Is there any way to specify both specific and general stubs on RhinoMock-objects?
One workaround would be recreating the stub in the test-method itself - a duplication I would like to avoid. I could live with this version, however.
What I also do not want is a explicit exclusion of the "42" in the general statement via Constraints as this will effect the other tests negatively.
Calling BackToRecord is also not an option as it seems to reset other stubs, too.
Thanks for your answers!

A: I don't think its possible to "reset" expectations. In this case I would avoid setting up this mock in the set up, instead I would create a method to easily set it up and call it from every test:
private IFoo SetUpFoo()
{
  IFoo foo = MockRepository.GenerateStub<IFoo>();
  foo.Stub(f => f.DoSomething(0)).IgnoreArguments().Return(0).WhenCalled(mi => mi.ReturnValue = mi.Arguments[0]);
}

Then just use this method in every test that needs the standard foo:
[Test]
public void StandardTest()
{
  IFoo foo = SetUpFoo();
  ...
}

in your special case you have to create foo manually and set up the expectation:
[Test]
public void SpecialTest()
{
  IFoo foo = MockRepository.GenerateStub<IFoo>();
  foo.Stub(f => f.DoSomething(42)).Return(43);
  ...
}

Of course you get some code duplication, but at least its clear which expectations are used in which test.

A: I just found the solution to actually "override" stubs / expectations:
Rhino Mocks: How to clear previous expectations on an object?
Applied to my problem I can now write:
this.Foo.Stub(f => f.DoSomething(42)).Return(43).Repeat.Any();

The documentation to Any says:

Repeat the method any number of times. This has special affects in that this method would now ignore orderring.

So this seems to be neither a bug or an undocumented feature.


text:
Q: Print next array after matching array I have an array of arrays that contain array key with the value, here the example :
$text = [
        [
         'Hotel'     => 'N',
         'Jayakarta' => 'NE',
         'Jaya'      => 'NE',
         'sangat'    => 'ADV',
         'nyaman'    => 'ADJ',
         'ditempati' => 'V.'
        ]
        ,
        [
         'Andi'     => 'NOB',
         'menginap' => 'V',
         'di'       => 'PREP',
         'Hotel'    => 'N',
         'Neo'      => 'NE',
         'Malioboro => 'NE',
         'selama'   => 'N',
         'satu'     => 'NUM',
         'minggu'   => 'N.'
        ]
    ];

And I have array prefix that contain :
$prefix = [ [0] => Hotel [1] => Hostel [2] => Losmen [3] => Motel [4] => Penginapan [5] => Pesanggrahan [6] => Pondok [7] => Wisma ]

If $prefix elements are in $text array then I will check next array value of text. If array value is N or NE then I will make an output from prefix text until the end of array that contain value N or NE.
Here's what I am doing for the moment:
foreach($text as $index => $tok){
    foreach ($tok as $tokkey => $tokvalue) {
        if(in_array($tokkey, $prefix)){
            echo $tokkey;
            $next = next($tok);
            if($tokvalue == "N" or $tokvalue == "NE"){
                echo key($tok);
            }
        }
   }
}

The output I got :
Hotel Jayakarta, Hotel menginap

The expected output should be:
- Hotel Jayakarta Jaya
- Hotel Neo Malioboro selama

Any help is much appreciated, Thank you.

A: From what I understand from your text, you need to replace your if() that only runs once, for a while() that runs while the next() string is NE or N.
foreach($text as $index => $tok){
    foreach ($tok as $tokkey => $tokvalue) {
        if(in_array($tokkey, $prefix)){
            echo $tokkey;
            next($tok);
            while($tokvalue == "N" || $tokvalue == "NE")
            {    echo key($tok);
                 next($tok);
                 $tokvalue = current($tok);
            }
            }
        }
        echo "\n";
   }
}

A: Below are the steps I followed to get the desired out put.
1) If tokkey present in prefix array, call a function.
2) Create a new array starting from the element which matches with prefix array.
3) Loop the new array and check for next value to be either 'N' or 'NE'
4) Display those keys from array.
foreach($text as $index => $tok){
    foreach ($tok as $tokkey => $tokvalue) {
        if(in_array($tokkey, $prefix)){
            getKeys($tokkey,$tok);
            echo "<br/>";
        }
    }
}

function getKeys($tokkey,$tok){
    $flag = 0;
    echo $tokkey.' ';
    foreach($tok as $k=>$v){
        if($k==$tokkey){
            $flag = 1;
        }
        if($flag){
            $new_array[$k]=$v;
        }
    }
    foreach($new_array as $k=>$v){
        $ff = next($new_array);
        if(($ff == 'NE' || $ff == 'N')){
             echo key($new_array).' ';
        }
    }
}

Out Put:
Hotel Jayakarta Jaya Hotel Neo Malioboro selama
http://sandbox.onlinephpfunctions.com/code/2777d3ab3d34c941c23886d42e537cde7fff2351


text:
Q: Effective way to add array item to object key I have one value from the server. It contains object with the same key as in my state object. Key value of that object is an array with one item. To handle this value in my reducer I need to add this array item to existing object key in my state.
In short:
I have from the server: { TEST: ['item1'] }
My state is: { TEST: ['item2'], TEST2: ['item3'] }
Expected result: { TEST: ['item1', 'item2'], TEST2: ['item3'] }
const handleCreateItemFilter = (state, { payload }) => {
  const { list  } = payload;
  const updatedList = { ...state.regions.list };
  updatedList[Object.keys(list).join()] = [...updatedList[Object.keys(list).join()], Object.values(list).join()];
  return {
    ...state,
    regions: {
      ...state.regions,
      list: updatedList,
    },
    selectedFilter: {
      ...state.selectedFilter, unassignedCountries: [], regions: Object.keys(list).join(),
    },
  };
};

Currently, I solved it like in the example above: create new updatedList, find appropriate key for my object from the server and assign to my new object array of old key value and new one. But I think it isn't good approach to solve this problem.

A: So, I really don't know why you are using object on root state instead of array, but, if I needed to use it I would do some like this:

const response = { TEST: ['item1'] }
const stateInitial = { TEST: ['item2'], TEST2: ['item3']}

const expected = JSON.stringify({ TEST: ['item1', 'item2'], TEST2: ['item3']})

const reducer = (state = stateInitial, { payload }) => {
  return [
    ...Object.entries(payload).map(([k, v]) => (
      typeof stateInitial[k] !== 'undefined' ?
      [ k,[...v, ...stateInitial[k],]] :
      [k, v]
    ))

  ].reduce((obj, [k, v]) => ({ ...obj, [k]: v }), stateInitial)
};

try {
  const output = JSON.stringify(reducer(undefined, { payload: response}))
  if (output != expected) {
    throw `reducer return something different: \n${output} \n\nand expect \n\n${expected}`
  }

  console.log('the test is passed')
} catch (error) {
  console.error(error)
}


text:
Q: Does Visual Studio Code have box select/multi-line edit? I heard Microsoft released a new editor called Visual Studio Code and it looks pretty good. One key feature that I need is multi-line edit and I can't seem to find anything about it having it.

A: Box Selecting
Windows & Linux: Shift + Alt + 'Mouse Left Button'
macOS: Shift + option + 'Click'
Esc to exit selection.
MacOS: Shift + Alt/Option + Command + 'arrow key'

A: Press Ctrl+Alt+Down or Ctrl+Alt+Up to insert cursors below or above.

A: The shortcuts I use in Visual Studio for multiline (aka box) select are Shift + Alt + up/down/left/right
To create this in Visual Studio Code you can add these keybindings to the keybindings.json file (menu File → Preferences → Keyboard shortcuts).
{ "key": "shift+alt+down", "command": "editor.action.insertCursorBelow",
                                 "when": "editorTextFocus" },
{ "key": "shift+alt+up", "command": "editor.action.insertCursorAbove",
                                 "when": "editorTextFocus" },
{ "key": "shift+alt+right", "command": "cursorRightSelect",
                                     "when": "editorTextFocus" },
{ "key": "shift+alt+left", "command": "cursorLeftSelect",
                                     "when": "editorTextFocus" }

A: For multiple select in Visual Studio Code, hold down the Alt key and starting clicking wherever you want to edit.
Visual Studio Code supports multiple line edit.

A: On Windows it's holding down Alt while box selecting. Once you have your selection then attempt your edit.


text:
Q: Rstudio notebook viewer doesn't show the code I have recently downloaded the Rstudio and I created a R Notebook. However the "Viewer" doesn't show me the Notebook when I save it (in the instructions says it works). I have seen the same issue in other forums, but with no answers.

A: I had the same doubt, but i found it here: Tools -> Global options -> R markdown -> Show output preview in, then select Viewer Pane. Next time you click preview (not save) it'll be showed where you want.

A: I don't clearly understand your question.
However, I'll show you some things related with "viewing", maybe one of this could solve your problem:

*

*The problem is that you are not seeing console

When you open a R Notebook, "Console" gets minimized, just press it to reverse it."Console" Screenshot. However, if you want to see the results on your console, you have to execute the lines on the console. Otherwise, results will be on the script file viewer.

*

*The problem is that you're pressing "save" and not "preview"

When you press save, you're just saving the code.
If you want to save the execution of the notebook (the document that gets created when executed, with code and plots and explanations) you have to press "Preview" down arrow and export to notebook (Preview Notebook), to html (Knit to HTML), to word (Knit to Word) or to pdf (Knit to PDF), this preview will be stored IN YOUR DIRECTORY.
"Preview" screenshot
If any of these answers are related with your question, please provide some images or try to explain your problem more precisely.


text:
Q: Struggling to put function into table. "Missing '(' near new." I have this code right here, in a file named "hframe.lua".
table.insert(handler.class, framename)
local func = [[
function new(())
print("Hello Stackoverflow!")
end
]] --The function test itself.
local a="table.insert(handler.class."..framename..", "..func..")" --I broke it in two to make things easier for me to read.
print(a) --Read out the variable so I can see what it looks like.
local b=load(a) --Load it up
b() --Nil error. Great.

"framename" is a constant from another file, which is simply declared as "frame". The error is a simple nil error. Upon running b(), it throws a local nil error. With an assert, I've discovered this error.
Error: Thread error (Thread: 0x04c7d2f0)

uicode/hframe.lua:16: [string "table.insert(handler.class.frame, function ne..."]:1: '(' expected near 'new'
stack traceback:
        [C]: in function 'assert'
        uicode/hframe.lua:16: in main chunk
        [C]: in function 'require'
        uicode/handlerthread.lua:165: in main chunk
stack traceback:
        [string "boot.lua"]:777: in function <[string "boot.lua"]:773>
        [C]: in function 'error'
        [string "boot.lua"]:631: in function <[string "boot.lua"]:630>
        [string "boot.lua"]:604: in function <[string "boot.lua"]:594>
        [C]: in function 'xpcall'

I'm not entirely sure WHY it's throwing this error, because clearly I define it as function new(). What I have I done wrong?

A: function new() end

is syntactic sugar for
new = function () end

This is an assignment. It does not resolve to a value. Hence you cannot use a function definiton where a value is expected.
In your case the code executed is
table.insert(handler.class.someFrameName,
  function new () print("Hello Stackoverflow!") end
)

The only thing that would make sense for Lua with the function keyword present in a list of expressions is an anonymous function and it expects a ( after function but finds new
You have two options to fix this.
If function new() end is equivalent to new = function () end, function () end must resolve to a function value. So we can create a function value in-place:
table.insert(handler.class.someFrameName,
  function () print("Hello Stackoverflow!") end
)

I'll leave it up to you to impelement this in the string you want to load.
Another option is to define the function first. You can do this both in the string or in the scope of your load call.
function new() print("Hello Stackoverflow")
table.insert(handler.class.someFrameName, new)

A: Lua load() function returns nil and the error if it failed to compile code. Since the passed code is invalid, b is nil. Therefore a error is raised when you attempt to call it.
The reason the code is invalid is because when a function declaration is used as an expression, the function name must be omitted, e.g.
table.insert(sometable, function() … end)
Please note that most likely you don't need to create code dynamically, the following will work:
table.insert(handler.class[framename], function() … end)