text:
Q: ArrayList .get faster than HashMap .get? I had thought that HashMaps were faster for random access of individual values than ArrayLists . . . that is, to say, that HashMap.get(key) should be faster than ArrayList.get(index) simply because the ArrayList has to traverse every element of the collection to reach its value, whereas the HashMap does not.  You know, O(1) vs O(n) and all that.
edit: So my understanding of HashMaps was/is inadequate, hence my confusion.  The results from this code are as expected.  Thanks for the many explanations.
So I decided to test it, on a lark.  Here is my code:
import java.util.HashMap;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class Testing
{

    public static void main(String[] args)
    {
        ArrayList<SomeClass> alist = new ArrayList<>();
        HashMap<Short, SomeClass> hmap = new HashMap<>(4000, (float).75);
        ListIterator<SomeClass> alistiterator = alist.listIterator();
        short j = 0;
        do
        {
            alistiterator.add(new SomeClass());
            j++;
        }
        while(j < 4000);
        for (short i = 0; i < 4000; i++)
        {
             hmap.put(i, new SomeClass());
        }
        boolean done = false;
        Scanner input = new Scanner(System.in);
        String blargh = null;
        do
        {
            System.out.println("\nEnter 1 to run iteration tests.");
            System.out.println("Enter w to run warmup (recommended)");
            System.out.println("Enter x to terminate program.");
            try
            {
                blargh = input.nextLine();
            }
            catch (NoSuchElementException e)
            {
                System.out.println("Uh, what? Try again./n");
                continue;
            }
            switch (blargh)
            {
                case "1":
                    long starttime = 0;
                    long total = 0;
                    for (short i = 0; i < 1000; i++)
                    {
                        starttime = System.nanoTime();
                        iteratearraylist(alist);
                        total += System.nanoTime() - starttime;
                    }
                    total = (long)(total * .001);
                    System.out.println(total + " ns: iterating sequentially"
                                       + " through ArrayList");
                    total = 0;
                    for (short i = 0; i< 1000; i++)
                    {
                        starttime = System.nanoTime();
                        iteratearraylistbyget(alist);
                        total += System.nanoTime() - starttime;
                    }
                    total = (long)(total * .001);
                    System.out.println(total + " ns: iterating sequentially"
                                       + " through ArrayList via .get()");
                    total = 0;
                    for (short i = 0; i< 1000; i++)
                    {
                        starttime = System.nanoTime();
                        iteratehashmap(hmap);
                        total += System.nanoTime() - starttime;
                    }
                    total = (long)(total * .001);
                    System.out.println(total + " ns: iterating sequentially"
                                       + " through HashMap via .next()");
                    total = 0;
                    for (short i = 0; i< 1000; i++)
                    {
                        starttime = System.nanoTime();
                        iteratehashmapbykey(hmap);
                        total += System.nanoTime() - starttime;
                    }
                    total = (long)(total * .001);
                    System.out.println(total + " ns: iterating sequentially"
                                       + " through HashMap via .get()");
                    total = 0;
                    for (short i = 0; i< 1000; i++)
                    {
                        starttime = System.nanoTime();
                        getvaluebyindex(alist);
                        total += System.nanoTime() - starttime;
                    }
                    total = (long)(total * .001);
                    System.out.println(total + " ns: getting end value"
                                   + " from ArrayList");
                    total = 0;
                    for (short i = 0; i< 1000; i++)
                    {
                        starttime = System.nanoTime();
                        getvaluebykey(hmap);
                        total += System.nanoTime() - starttime;
                    }
                    total = (long)(total * .001);
                    System.out.println(total + " ns: getting end value"
                               + " from HashMap");
                    break;
                case "w":
                    for (int i = 0; i < 60000; i++)
                    {
                        iteratearraylist(alist);
                        iteratearraylistbyget(alist);
                        iteratehashmap(hmap);
                        iteratehashmapbykey(hmap);
                        getvaluebyindex(alist);
                        getvaluebykey(hmap);
                    }
                    break;
                case "x":
                    done = true;
                    break;
                default:
                    System.out.println("Invalid entry.  Please try again.");
                    break;
            }
        }
        while (!done);
        input.close();
    }

    public static void iteratearraylist(ArrayList<SomeClass> alist)
    {
        ListIterator<SomeClass> tempiterator = alist.listIterator();
        do
        {
            tempiterator.next();
        }
        while (tempiterator.hasNext());
    }

    public static void iteratearraylistbyget(ArrayList<SomeClass> alist)
    {
        short i = 0;
        do
        {
            alist.get(i);
            i++;
        }
        while (i < 4000);
    }

    public static void iteratehashmap(HashMap<Short, SomeClass> hmap)
    {
        Iterator<HashMap.Entry<Short, SomeClass>> hmapiterator =
        map.entrySet().iterator();
        do
        {
            hmapiterator.next();
        }
        while (hmapiterator.hasNext());
    }

    public static void iteratehashmapbykey(HashMap<Short, SomeClass> hmap)
    {
        short i = 0;
        do
        {
            hmap.get(i);
            i++;
        }
        while (i < 4000);
    }

    public static void getvaluebykey(HashMap<Short, SomeClass> hmap)
    {
        hmap.get(3999);
    }

    public static void getvaluebyindex(ArrayList<SomeClass> alist)
    {
        alist.get(3999);
    }
}

and
public class SomeClass
{
    int a = 0;
    float b = 0;
    short c = 0;

    public SomeClass()
    {
        a = (int)(Math.random() * 100000) + 1;
        b = (float)(Math.random() * 100000) + 1.0f;
        c = (short)((Math.random() * 32000) + 1);
    }
}

Interestingly enough, the code seems to warm up in stages.  The final stage that I've identified comes after around 120,000 iterations of all methods.  Anyway, on my test machine (AMD x2-220, L3 + 1 extra core unlocked, 3.6 ghz, 2.1 ghz NB), the numbers that really jumped out at me were the last two reported.  Namely, the time taken to .get() the last entry of the ArrayList (index == 3999) and the time taken to .get() the value associated with a Short key of 3999.
After 2-3 warmup cycles, testing shows that ArrayList.get() takes around 56 ns, while HashMap.get() takes around 68 ns.  That is . . . not what I expected. Is my HashMap all eaten up with collisions? All the key entries are supposed to autobox to Shorts which are supposed to report their stored short value in response to .hashcode(), so all the hashcodes should be unique.  I think?
Even without warmups, the ArrayList.get() is still faster.  That is contrary to everything I've seen elsewhere, such as this question.  Of course, I've also read that traversing an ArrayList with a ListIterator is faster than just using .get() in a loop, and obviously, that is also not the case . . .

A:
the ArrayList has to traverse every element of the collection to reach its value

This is not true. ArrayList is backed by an array which allows for constant-time get operations.
HashMap's get, on the other hand, first must hash its argument, then it must traverse the bucket to which the hash code corresponds, testing each element in the bucket for equality with the given key. This will generally be slower than just indexing an array.

A: Hashmaps aren't faster at retrieval of something at a known index.  If you are storing things in a known order, the list will win.
But say instead of your example of inserting everything into the list 1-4000, you did it in a total random order.  Now to retrieve the correct item from a list, you have to check each item one by one looking for the right item.  But to retrieve it from the hashmap, all you need to know is the key you would have given it when you inserted it.
So really, you should be comparing Hashmap.get(i) to
for(Integer i : integerList)
   if(i==value)
       //found it!

Then you would see the real efficiency of the hashmap.

A: ArrayList.get(index) acctualy uses constant time, since ArrayList is backed by an array, so it just uses that index in the bacing array. ArrayList.contains(Object) is a long operation in O(n) in worst case.

A: Big O for HashMap is O(1+α). Your α comes from hashcode collisions and a bucket must be traversed to check for equality.

Big O for pulling an item out of an ArrayList by index O(1)

When in doubt... draw it out...

A: Both ArrayList and HashMap are backed with arrays, HashMap has to compute a hash code of the key from which it derives the index to use for accessing the array while for accessing an and element in the ArrayList using get you provide the index. So its 3 operations vs 1 operation for the ArrayList.
But whether a List or a Map is backed with an array is implementation detail. So the answer may differ depending on which implementations you use.


text:
Q: HTML / CSS centering controls to the screen I am pretty new to ASP.Net and anything really web development related. Watched a few videos and got the basic idea.
The issue I have now is that I would like to center my views to the center of the page.
So as an example, I create a new ASP.Net MVC project in vs2015. I create a new view and my view looks like this.
@{
    ViewBag.Title = "Test Page";
}

   <button>Click me</button

I want the button to be in the center of the screen both horizontally and vertically. How do I achieve this?
I have looked all over the net and tried almost everything I could find but nothing seems to work.
Edit: Full credit to Luke who point me in the right direction.
In Site.css located in the Content folder I added the following.
.centerStuff {
   position: absolute;
   top: 50%;
   left: 50%;
   -ms-transform: translate(-50%, -50%);
   -webkit-transform: translate(-50%, -50%);
   transform: translate(-50%, -50%);
}

and now my view looks like this.
@{
    ViewBag.Title = "Test Page";
}

   <button>Click me</button

A: You will have to specify a height for the container.  Check this out:
body{
  position:relative;
  height:100%;
}
.full-height{
  text-align:center;
  display:table;
  height:300px;//this is just and example height
  width:100%;
  border:1px solid red;
}
.center{
  display:table-cell;
  vertical-align:middle;
   height:100%;
}

<!DOCTYPE html>

    <link rel="stylesheet" href="style.css">

test

To set the height of the the .full-height div, you will need to get height of the window via javascript, then set it like so (example below uses jQuery):
var winHeight = window.innerHeight;//gets height of window
$('.full-height').css('height':winHeight+'px');//sets the div height

hope this helps?

redpajama_set_name: RedPajamaStackExchange


text:
Q: WebAPI, DPAPI and LoadUserProfile We are trying to use DPAPI in our OWIN-based WebAPI self-hosted app. The app is configured for Windows authentication and runs as a service under SYSTEM account:
var listener = (HttpListener)app.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemes = AuthenticationSchemes.Ntlm;

In the controller we do something like this:
public IHttpActionResult SomeAction()
{
  var currentWindowsIdentity = (WindowsIdentity)this.User.Identity;

  // load user profile for currentWindowsIdentity and impersonate
  using (UserProfile.Load(currentWindowsIdentity)) // UserProfile is a wrapper arounf LoadUserProfileW
  using (currentWindowsIdentity.Impersonate())
  {
    ProtectedData.Unprotect(…);
  }
}

The call to ProtectedData.Unprotect fails with CryptographicException: Key not valid for use in specified state.
If the same user that is invoking the action is logon on to the machine where the app is running, then ProtectedData.Unprotect succeeds. It appears that LoadUserProfileW does not load some profile data related to DPAPI.
Are we missing something, or is it by design?


text: Q: Constant pop-up of print screen on clicking a particular button I am getting a print screen option on clicking a button. I made no changes to the js or HTML file of my webpage to change the onclick() behavior for the botton, I wrote some kind of a print command in the chrome debugger console and since then the pop-up is coming. I don't exactly remember the command. How do I undo this change? On pushing the code to GitHub, this behavior was repeated in the production environment.


text:
Q: How to make async call inside another async method in Webflux? Explanation of the question is bit a long. Kindly take a minute and help!
I have two http calls which will give the following data.
1st http request call will return <Mono<List<Chips>>
[
  {
    "id": 1,
    "name": "redlays"
  },
  {
    "id": 2,
    "name": "yellowlays"
  },
  {
    "id": 3,
    "name": "kurkure"
  }
]

Chips Model is
@Data
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Chips {
    private int id;
    private String name;
}

2nd http request call will return Mono<ChipsDetails> based on Id
{
    "id": 1,
    "color": "red",
    "grams": "50"
}

ChipsDetails Model as below,
@Data
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ChipsDetails {
    private int id;
    private String color;
    private String grams;
}

I have done the Implementation using Webflux. Here I have used three models which are Chips, ChipsDetails and ChipsFullDetails.
Model Chips will have two attributes id and name then Model ChipsDetails will have three attributes id,color and grams whereas Model ChipsFullDetails will have combination of Chips and ChipsDetails attributes which are id, name, color and grams
@RestController
@RequestMapping("/chips")
public class ChipsController {

    @Autowired
    ChipsService chipsService;

    @GetMapping
    public Mono<List<ChipsFullDetails>> getAllChips() {
        return chipsService.getChips()
                .map(f -> {
                            List<ChipsFullDetails> chipsFullDetails = new ArrayList<>();
                            f.forEach(a -> {
                                ChipsFullDetails chipsFullDetail = new ChipsFullDetails();
                                chipsFullDetail.setId(a.getId());
                                chipsFullDetail.setName(a.getName());

                                chipsService.getChipsDetails(a.getId())
                                        .subscribe(b -> {
                                            chipsFullDetail.setColor(b.getColor());
                                            chipsFullDetail.setGrams(b.getGrams());
                                        });
                                chipsFullDetails.add(chipsFullDetail);

                            });
                            return chipsFullDetails;
                        }
                );
    }
}

Here chipsService.getChips() will return Mono<List<Chips>> This is the 1st call and chipsService.getChipsDetails(a.getId()) will return Mono<ChipsDetails> This is the 2nd http request call.
The result of the implementation will be ChipsFullDetails
@Data
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ChipsFullDetails {
    private int id;
    private String name;
    private String color;
    private String grams;
}

The problem is ChipsFullDetails returns null for color and grams attributes which we are getting from the 2nd http call even though it is subscribed inside.
How to achieve when Second Http call i.e chipsService.getChipsDetails(a.getId()) depending on the result of 1st http call (chipsService.getChips()) in asynchronous way?
Is this possible to achieve without blocking both the calls?

A: I'd transform the initial Mono<List<Chips>> into a Flux<Chips> first, so that you can flatMap on each element, e.g. something along those lines:
public Mono<List<ChipsFullDetails>> getAllChips() {
    return chipsService
            .getChips()
            // Mono<List> to Flux:
            .flatMapIterable(Function.identity())
            // flat map on each element:
            .flatMap(this::buildChipsFullDetails)
            // Flux back to Mono<List>:
            .collectList();
}

private Mono<ChipsFullDetails> buildChipsFullDetails(Chips chips) {
    return chipsService
            .getChipsDetails(chips.getId())
            // once you get both chips and details, aggregate:
            .map(details -> buildChipsFullDetails(chips, details));
}

private ChipsFullDetails buildChipsFullDetails(Chips chips, ChipsDetails details) {
    // straightforward synchronous code:
    ChipsFullDetails chipsFullDetail = new ChipsFullDetails();
    chipsFullDetail.setId(chips.getId());
    chipsFullDetail.setName(chips.getName());
    chipsFullDetail.setColor(details.getColor());
    chipsFullDetail.setGrams(details.getGrams());
    return chipsFullDetail;
}

A: I basically disagree with the idea of working with a Flux, though I admit I have it as well.
I would say that if you want to get details for a list of chips then you should make an endpoint that does that. Then it will be a single call.
For you original question, there is a way to do it without going to Flux, but it reads a bit funny:
ParameterizedTypeReference<List<Chip>> chipList = new ParameterizedTypeReference<List<Chip>>() {};

public Mono<List<ChipDetails>> getChipDetails() {
    return webClient.get().uri("chips").retrieve().bodyToMono(chipList).flatMap(chips -> {
        return Mono.zip(chips.stream().map(chip -> webClient.get().uri("chipDetails?id="+chip.getId()).retrieve().bodyToMono(ChipDetails.class)).collect(Collectors.toList()), details -> {
            List<ChipDetails> chipDetails = new ArrayList<>();
            for (Object o : details) {
                chipDetails.add((ChipDetails) o);
            }
            return chipDetails;
        });
    });
}

This uses Mono.zip to create a sort of batch request out of each of the Chip entries in the list executes them all at once. Flux will probably end up doing more or less the same thing but not really.
If you just make the endpoint you need, then:
ParameterizedTypeReference<List<ChipDetails>> detailsList = new ParameterizedTypeReference<List<ChipDetails>>() {};

public Mono<List<ChipDetails>> getChipDetailsReal() {
    return webClient.post().uri("chipDetails").body(webClient.get().uri("chips").retrieve().bodyToMono(chipList), chipList).retrieve().bodyToMono(detailsList);
}

This approach avoids repeated calls to the same endpoint and is doing what you want.
I'm not a fan of using Flux when you really mean List. A Flux is a streaming thing with backpressure and sophisticated capabilities whereas a List is just a List.


text:
Q: How to set header layout of the DatePickerDialog in android I'm creating a DatePickerDialog in android, I want my datepickerdialog look like the left dialog in the image. But when I write my own code, it just horizontal the text date (dialog on the right)
What should I do?
My image
package com.example.luc.myapplication;
import android.app.DatePickerDialog;
import android.app.DialogFragment;

import android.os.Bundle;
import android.app.Fragment;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.DatePicker;
import android.app.Dialog;
import java.util.Calendar;

/**
 * A simple {@link Fragment} subclass.
 */
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
    //Use the current date as the default date in the date picker
    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);

    DatePickerDialog dialog =  new DatePickerDialog(getActivity(), this, year, month, day);
    return dialog;
}

public void onDateSet(DatePicker view, int year, int month, int day) {
    //Do something with the date chosen by the user
  LinearLayout layout = new LinearLayout(getActivity());
    layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    layout.setOrientation(LinearLayout.VERTICAL);

    view.setLayoutParams(layout.getLayoutParams());
    TextView tv = (TextView) getActivity().findViewById(R.id.tv);
    tv.setText("Date changed...");
    tv.setText(tv.getText() + "\nYear: " + year);
    tv.setText(tv.getText() + "\nMonth: " + month);
    tv.setText(tv.getText() + "\nDay of Month: " + day);

    String stringOfDate = day + "/" + month + "/" + year;
    tv.setText(tv.getText() + "\n\nFormatted date: " + stringOfDate);
}
}

I call the dialog when click a button in MainActivity

A: I would first change your layout to this, it will give you more control
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#008d7f"
    android:paddingBottom="2dp"
    android:paddingTop="5dp"
    android:text="Friday"
    android:textColor="#ffffff"
    android:gravity="center_horizontal"/>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:background="#009688"
    >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="5dp"
    android:paddingTop="5dp"
    android:id="@+id/week_day"
    android:textColor="#ffffff"
    android:textSize="30sp"
    android:text="MAY"
    android:gravity="center_horizontal"/>

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/day_of_month"
    android:textSize="60sp"
    android:paddingBottom="5dp"
    android:paddingTop="5dp"
    android:textColor="#ffffff"
    android:text="8"
    android:gravity="center_horizontal"
    android:layout_below="@+id/week_day"/>

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/year"
    android:paddingBottom="5dp"
    android:paddingTop="5dp"
    android:textSize="20sp"
    android:textColor="#ffffff"
    android:text="2017"
    android:gravity="center_horizontal"
    android:layout_below="@+id/day_of_month"/>

</RelativeLayout>

and change you java to:
package com.example.luc.myapplication;
import android.app.DatePickerDialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.app.Fragment;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.DatePicker;
import android.app.Dialog;
import java.util.Calendar;

 /**
 * A simple {@link Fragment} subclass.
 */
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {

@Override
 public Dialog onCreateDialog(Bundle savedInstanceState){
    //Use the current date as the default date in the date picker
    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);

    DatePickerDialog dialog =  new DatePickerDialog(getActivity(), this, year, month, day);
    return dialog;
}

public void onDateSet(DatePicker view, int year, int month, int day) {
  //Do something with the date chosen by the user
  LinearLayout layout = new LinearLayout(getActivity());
    layout.setLayoutParams(new
    ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
    ViewGroup.LayoutParams.WRAP_CONTENT));
    layout.setOrientation(LinearLayout.VERTICAL);

    view.setLayoutParams(layout.getLayoutParams());
    TextView tv_dayofweek = (TextView) getActivity().findViewById(R.id.day_of_week);
    TextView tv_month = (TextView) getActivity().findViewById(R.id.month);
    TextView tv_dayofmonth = (TextView) getActivity().findViewById(R.id.day_of_month);
    TextView tv_year = (TextView) getActivity().findViewById(R.id.day_of_week);
    tv.setText("Date changed...");
    tv_year.setText(tv.getText() + "\nYear: " + year);
    tv_month.setText(tv.getText() + "\nMonth: " + month);
    tv_dayofmonth.setText(tv.getText() + "\nDay of Month: " + day);

    String stringOfDate = day + "/" + month + "/" + year;
    tv.setText(tv.getText() + "\n\nFormatted date: " + stringOfDate);
    }
}

Just tested and this is the result:


text:
Q: Grid.MVC is raising an error when doing column filtering "JavaScript runtime error: Object doesn't support property or method 'hasAttribute'" I have installed the Grid.MVC http://gridmvc.codeplex.com/ inside my asp.net mvc5 web application. but now when i click on the filter icon beside a column i will get the following exception:-
> Unhandled exception at line 1, column 2416 in
> http://localhost:55951/Scripts/gridmvc.min.js
>
> 0x800a01b6 - JavaScript runtime error: Object doesn't support property
> or method 'hasAttribute'

here is the code that will raise the exception inside the gridmvc.min.js file:-
function(t,i){var o=n(this).attr("data-type")||"",r=t.getFilterWidgetForType(o),u,h,e,c;if(r==null)return!1;if(this.hasAttribute("data-rendered"))return u=t.openMenuOnClick.call(this,t

so can anyone adivce on this please?
EDIT
i commented the code which is causing the error inside the script file,
 //if (this.hasAttribute("data-rendered")) {
      //  var or = self.openMenuOnClick.call(this, self);
      //   self.setupPopupInitialPosition($(this));
      //    if (!or && typeof (widget.onShow) != 'undefined')
      //        widget.onShow();
      //  return or;
      //  }

And now the filter box will be shown, but if i select any thing inside the type drop down the same filter box will be shown as follow:-

Thanks

A: This issue in only in IE browser. Please check IE browser compatibility mode it should be "Edge".
Also add 'meta http-equiv="X-UA-Compatible" content="IE=edge"' in head tag.


text:
Q: Internal Int32 implementation in C# I'm curious about internal implementation of Int32 in C#. Int32 is type of structure. How it is getting inherited from System.ValueType?
I had googled it but not able to get satisfactorily answer. Hopefully someone will clear my question.

A: The struct keyword is specifically designed to indicate inheritance from ValueType.
From MSDN (emphasis mine):

Although ValueType is the implicit base class for value types, you cannot create a class that inherits from ValueType directly. Instead, individual compilers provide a language keyword or construct (such as struct in C# and Structure…End Structure in Visual Basic) to support the creation of value types.


text:
Q: iPhone hardware audio decoding with multiple simultaneous audio files I'm developing an iPhone app that plays long (~30min) m4a audio clips. The clips are all stored locally and I'm using AVAudioPlayer to handle the playback functions. My app crossfades audio so that one sound fades out while another one fades in.
According to Apple's documentation only one sound at a time will be played using hardware audio decoding. Assuming that the first sound is being hardware decoded and the second sound starts playing using software decoding, will the second sound switch to using hardware decoding once the first sound has finished playing, or will it use software decoding the entire time?
It seems like there's a way to test for the availability of the hardware decoder. I'm going to see if that can get me the answer I'm looking for, but I was just curious if someone already knew the answer. Even if you just know the correct methodology for testing this, I'd appreciate it. This is my first iOS app and my first time working with C, so I'm flying blind.


text:
Q: AppleScript execution stops when a error popup show up I am trying to execute an apple script to attach a file to outlook. Now when i attach a certain file, i get an expected error popup saying, "i do not have the permission to attach this file. Click ok or cancel". This is expected result. Now i need to handle this popup by clicking on the "OK" button of the popup. But my script halts at the point where the popup is launched. And the code to click the button does not gets executed. I should manually click ok and the code continues with the next steps. Please let me know how can i handle this..

A: Enclose your point of possible failure in a 'try' block, & provide a 'no fail' for the error.
try
-- your code
on error
-- do nothing
end try


text:
Q: How to make a class for button widgets I am going to have a bunch of buttons in my flutter app, and I want to make a class for it so I don't need to copy-paste it and make my code look long for the same type of code. I make the class, no problem there but I am struggling because I want every button to go to a different page when pressed. How to achieve this?

class thebuttonmaka extends StatelessWidget {
  final String texxt;
  final String buum;
  const thebuttonmaka(this.texxt);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Padding(
      padding: EdgeInsets.only(top: 30),
      child: Material(
        elevation: 5,
        borderRadius: BorderRadius.circular(30),
        color: Colors.lightBlue,
        child: MaterialButton(
          minWidth: 250,
          padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
          onPressed: WHAT TO PUT HERE?,
          child: Text(texxt,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 20)
                  .copyWith(color: Colors.white, fontWeight: FontWeight.bold)),
        ),
      ),
    );
  }
}

So I basically need help where I put what to put here. I want to add this option to constructor so whenever I call the class I can put where the button navigates to. Example
thebuttonmaka('signup',signuppage)

A: class thebuttonmaka extends StatelessWidget {
  final String texxt;
  final String buum;
  final Function function; // add this
  const thebuttonmaka(this.texxt, this.function, this.buum); // change this

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Padding(
      padding: EdgeInsets.only(top: 30),
      child: Material(
        elevation: 5,
        borderRadius: BorderRadius.circular(30),
        color: Colors.lightBlue,
        child: MaterialButton(
          minWidth: 250,
          padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
          onPressed: function, // add this here
          child: Text(texxt,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 20)
                  .copyWith(color: Colors.white, fontWeight: FontWeight.bold)),
        ),
      ),
    );
  }
}

You can use it like
thebuttonmaka('signup',signuppage)

A: You can define your class like this and customize literally everything about your button (you can pass textalignment and style as well, I am just showing an example) -
class CommonButton {
      static MaterialButton myButton(BuildContext context, int width, int l, int t, int r, int b, func, String text) {
        return MaterialButton(
              minWidth: width,
              padding: EdgeInsets.fromLTRB(l, t, r, b),
              onPressed: func,
              child: Text(text,
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 20)
                      .copyWith(color: Colors.white, fontWeight: FontWeight.bold)),
            );
      }
     }

When you want to use this somewhere, just call it like this -
CommonButton.myButton(...)

(You have to obviously pass the onPressed function as well)


text:
Q: STM32 ADC conversion using HAL I am trying to learn how to use "new" HAL library from stm32.
When I try to do simple ADC conversion it works just one time, but then it stops converting. I suppose End of conversion flag does not get set. I am using STM32f429I Discovery board, which has STM32f429ZI on board.
Note that I know about sprintf being bad practice and making adc with interrupt is better, I know that, please don't point it out, this is not relevant to the question, I am just testing HAL here.
So the question is why EOC flag is not set or what could I do to make it work? Googling is not helping much since very few good materials about HAL out there.
Here is the code:
__IO uint16_t ADCValue=0;
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc);

int main(void)
{
  char str[15];

  /* Various initializations */

  HAL_ADC_Start(&hadc1);
  while (1)
  {

        if (HAL_ADC_PollForConversion(&hadc1, 1000000) == HAL_OK)
        {
            ADCValue = HAL_ADC_GetValue(&hadc1);
            sprintf(str, "%d", ADCValue);
            BSP_LCD_DisplayStringAt(130,30, (uint8_t*)str, LEFT_MODE);
        }

  }

void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
    ADCValue = HAL_ADC_GetValue(&hadc1);
}

I also created the project with CubeMX, adc configuration is the following:

EDIT 1
I tried to debug everything and it seems that program gets stuck into checking for EOC flag - it sees that it is not shown and therefore issues timer waiting for EOC to show up(but it never gets set)
Here is the code where it gets stuck in debugger:
/* Check End of conversion flag */
  while(!(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC)))
  {
    /* Check for the Timeout */
    if(Timeout != HAL_MAX_DELAY)
    {
      if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
      {
        hadc->State= HAL_ADC_STATE_TIMEOUT;
        /* Process unlocked */
        __HAL_UNLOCK(hadc);
        return HAL_TIMEOUT;
      }
    }

A: In your original code, set the End of Conversion Selection to disabled.
 hadc1.Init.EOCSelection = DISABLE;

It turned out that #define ADC_EOC_SEQ_CONV ((uint32_t)0x00000000) value is equal to DISABLE. So actually the EOCSelection should be configured as:
to be able to poll the ADC multiple times.
Then you can read the ADC continously without stopping and starting the ADC:
int main(void)
{
    HAL_Init();
    SystemClock_Config();
    ConfigureADC();

    HAL_ADC_Start(&hadc1);
    while(1)
    {
        if (HAL_ADC_PollForConversion(&hadc1, 1000000) == HAL_OK)
        {
            ADCValue = HAL_ADC_GetValue(&hadc1);
        }
    }
}

This way it worked fine for me.
Since HAL is a quite new library there are not a lot of resources to be find but not impossible. I learned a lot from this tutorial, it demonstrates all possible ADC useage step by step; from simple polling, to using interrupts and DMA.

A: I would like to add that for my setup (nucleo-h743) it was not enough to set:
hadc1.Init.EOCSelection = ADC_EOC_SEQ_CONV;

I also had to enable the overrun setting as well:
hadc1.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN;

Without this the HAL_ADC_PollForConversion was still blocking. I do not fully understand why this was necessary but it does allow me to poll in continuous mode.

A: Hm... I found couple of tutorials that used HAL_ADC_Stop(&hadc1) to end the convertion... I was looking at these tutorials before and thought that this is rather barbaric way, seems it disables ADC completely, so I though there should be different method. But it seems, that this actually works well.
Be welcome to post answer if there is more elegant way of doing this, since I think using HAL_ADC_Stop() is pretty awful, but can be used for learning purposes.
while (1)
  {
        HAL_ADC_Start(&hadc1);
        if (HAL_ADC_PollForConversion(&hadc1, 1000000) == HAL_OK)
        {
            ADCValue = HAL_ADC_GetValue(&hadc1);
                        sprintf(str, "%d", ADCValue);
                        BSP_LCD_DisplayStringAt(130,30, (uint8_t*)str, LEFT_MODE);
        }
        HAL_ADC_Stop(&hadc1);

  }

A: This works for me, hope it will help:
if (HAL_ADC_Start(&hadc) != HAL_OK)
{
    /* Start Conversation Error */
    // Error_Handler();
}
if (HAL_ADC_PollForConversion(&hadc, 500) != HAL_OK)
{
    /* End Of Conversion flag not set on time */
    // Error_Handler();
    ADCValue=-1;
}
else
{
    /* ADC conversion completed */
    /*##-5- Get the converted value of regular channel ########################*/
    ADCValue = HAL_ADC_GetValue(&hadc);
}
HAL_ADC_Stop(&hadc);


text:
Q: Using sql:column function in xpath in values method I have two tables:

*

*One called @settings with xml values

*Another called @nodesToFind with a list of nodes to extract from the xml values in the first table

I want to get a list of the values for each NodePath for each RowId.
This query uses the sql:column function in the xpath of the values method on the Settings column but it returns the NodePath itself instead of the value:
declare @settings table (RowId int identity, Settings xml)
insert @settings (Settings) values ('<settings><Settings1><Settings1a><Setting1a1>1-1a1</Setting1a1></Settings1a><Setting1b>1-1b</Setting1b><Setting1c>1-1c</Setting1c></Settings1><Settings2><Setting2a>1-2a</Setting2a></Settings2></settings>')
insert @settings (Settings) values ('<settings><Settings1><Settings1a><Setting1a1>2-1a1</Setting1a1></Settings1a><Setting1b>2-1b</Setting1b><Setting1c>2-1c</Setting1c></Settings1><Settings2><Setting2a>2-2a</Setting2a></Settings2></settings>')
insert @settings (Settings) values ('<settings><Settings1><Settings1a><Setting1a1>3-1a1</Setting1a1></Settings1a><Setting1b>3-1b</Setting1b><Setting1c>3-1c</Setting1c></Settings1><Settings2><Setting2a>3-2a</Setting2a></Settings2></settings>')

declare @nodesToFind table (NodePath varchar(max))
insert @nodesToFind (NodePath) values ('/Settings/Settings1/Settings1a/Setting1a1')
insert @nodesToFind (NodePath) values ('/Settings/Settings1/Setting1b')
insert @nodesToFind (NodePath) values ('/Settings/Settings1/Setting1c')
insert @nodesToFind (NodePath) values ('/Settings/Settings2/Setting2a')

select
    S.RowId,
    NTF.NodePath,
    S.Settings.value('(sql:column("NodePath"))[1]', 'varchar(max)')
from @settings S
cross apply @nodesToFind NTF

The result is this:
RowId  NodePath                                   Value
-----  -----------------------------------------  -----------------------------------------
1      /Settings/Settings1/Settings1a/Setting1a1  /Settings/Settings1/Settings1a/Setting1a1
2      /Settings/Settings1/Settings1a/Setting1a1  /Settings/Settings1/Settings1a/Setting1a1
3      /Settings/Settings1/Settings1a/Setting1a1  /Settings/Settings1/Settings1a/Setting1a1
1      /Settings/Settings1/Setting1b              /Settings/Settings1/Setting1b
2      /Settings/Settings1/Setting1b              /Settings/Settings1/Setting1b
3      /Settings/Settings1/Setting1b              /Settings/Settings1/Setting1b
1      /Settings/Settings1/Setting1c              /Settings/Settings1/Setting1c
2      /Settings/Settings1/Setting1c              /Settings/Settings1/Setting1c
3      /Settings/Settings1/Setting1c              /Settings/Settings1/Setting1c
1      /Settings/Settings2/Setting2a              /Settings/Settings2/Setting2a
2      /Settings/Settings2/Setting2a              /Settings/Settings2/Setting2a
3      /Settings/Settings2/Setting2a              /Settings/Settings2/Setting2a

What is wrong with the S.Settings.value('(sql:column("NodePath"))[1]', 'varchar(max)') line?

A: The XQuery you are trying to use is effectively being run dynaimcally. Unfortunately, you cannot use dynamic XQuery in SQL Server. Each XQuery must be static.
What you could do in your specific situation, is to break up each node predicate into separate columns. Then in the XQuery you can descend to the relevant node by checking each column. For example:
declare @settings table (RowId int identity, Settings xml)
insert @settings (Settings) values ('<settings><Settings1><Settings1a><Setting1a1>1-1a1</Setting1a1></Settings1a><Setting1b>1-1b</Setting1b><Setting1c>1-1c</Setting1c></Settings1><Settings2><Setting2a>1-2a</Setting2a></Settings2></settings>')
insert @settings (Settings) values ('<settings><Settings1><Settings1a><Setting1a1>2-1a1</Setting1a1></Settings1a><Setting1b>2-1b</Setting1b><Setting1c>2-1c</Setting1c></Settings1><Settings2><Setting2a>2-2a</Setting2a></Settings2></settings>')
insert @settings (Settings) values ('<settings><Settings1><Settings1a><Setting1a1>3-1a1</Setting1a1></Settings1a><Setting1b>3-1b</Setting1b><Setting1c>3-1c</Setting1c></Settings1><Settings2><Setting2a>3-2a</Setting2a></Settings2></settings>')

declare @nodesToFind table (NodePath1 nvarchar(max), NodePath2 nvarchar(max), NodePath3 nvarchar(max), NodePath4 nvarchar(max))
insert @nodesToFind (NodePath1, NodePath2, NodePath3, NodePath4) values ('settings','Settings1','Settings1a','Setting1a1')
insert @nodesToFind (NodePath1, NodePath2, NodePath3, NodePath4) values ('settings','Settings1','Setting1b',null)
insert @nodesToFind (NodePath1, NodePath2, NodePath3, NodePath4) values ('settings','Settings1','Setting1c',null)
insert @nodesToFind (NodePath1, NodePath2, NodePath3, NodePath4) values ('settings','Settings2','Setting2a',null)

select
    S.RowId,
    NTF.*,
    S.Settings.value('((
        for $i1 in *[local-name() = sql:column("NodePath1")]
        return
            if (empty(sql:column("NodePath2")))
            then $i1
            else for $i2 in ($i1/*[local-name() = sql:column("NodePath2")])
                 return
                     if (empty(sql:column("NodePath3")))
                     then $i2
                     else for $i3 in $i2/*[local-name() = sql:column("NodePath3")]
                          return
                              if (empty(sql:column("NodePath4")))
                              then $i3
                              else $i3/*[local-name() = sql:column("NodePath4")]
    )/text())[1]', 'varchar(max)')
from @settings S
cross join @nodesToFind NTF

db<>fiddle
As you can see, it is made significantly more complex (and probably slow) by the fact that there are multiple possible node levels. If you can restrict it to only one level of node then you can remove the if else sections.


text:
Q: jQuery form login check without redirect, password and login returns blank I have got a login form that works great without any problems after I submit it to a PHP document. But I don't want it to redirect to a PHP document, so I am trying to do this:
<form id="login" name="login" class="col-1 login" action="blocks/loggedIn.php" method="post">
    <input type="text" name="loginEmail" id="loginEmail" placeholder="email :" class="inputLogin">

    <input type="password" name="loginPassword" id="loginPassword" placeholder="Password :" class="inputLogin">

    <input type="submit" id="loginSubmit" class="button" value="OK">

</form>
`

For some reason variables   lE   and   lP   returns blank after I submit form.
I have also tried to define them using this :
var lE = $('#loginEmail').val(); var lP = $('#loginPassword').val();
But still nothing...  any ideas what this can be?

A: You're doing this when the page loads:
var lE = document.forms["login"]["loginEmail"].value;
var lP = document.forms["login"]["loginPassword"].value;

Unless the user is really fast (as in, faster than the computer), no values will have been typed there yet.  So those variables will be empty (or will contain whatever default values you may have in those fields).
Instead, get the values when the form is submitted:
$('#loginSubmit').click(function(){
    var lE = document.forms["login"]["loginEmail"].value;
    var lP = document.forms["login"]["loginPassword"].value;
    //...


text:
Q: Determine functions in R in uninstalled packages? I know there are several ways to determine the functions in a given package in R, provided the package is already installed.  For instance, one can use any of the following to find the functions associated with the XML package:
lsf.str("package:XML")

help(package="XML")

ls(pos = "package:XML")

But I want to find all the functions for a package, listed in a format similar to the way one of these 3 methods presents them in R, without actually installing the package.  I know the pdf manual for a given package contains the list of functions; but I need something more dynamic (either that can be accessed in R or on a webpage, for instance).  And I am not finding anything like this on the CRAN website either.  Here is the XML site, for instance:  http://cran.r-project.org/web/packages/XML/index.html
And ideally I need this to generalize to any/all (or at least most) of the 5,000+ existing R packages.
Is this possible?


text:
Q: Check that projects have Warnings As Errors I have been automating all my builds through PSake and finding it really useful to get my TeamCity build more powerful.
One thing I would like to introduce is a step to make sure all projects in a solution have warnings as errors set to true. It isn't that often that I spot a project not having this but I am also now working on a legacy codebase where it is not so prevalent.
I was hoping to be able to create a quick check that the setting was on.
I am guessing there would be a way by checking for the correct text (
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>

) in the .*proj files but I hoped there might be a cleaner or more effective way.
Any ideas?

A: I don't understand what's wrong with probing the .*proj files, so I'll assume you wouldn't like to just search for a whole string literal.
Project files are XML based, so here's a Linq to XML code snippet that will let you find what you're looking for:
void VerifyTreatWarningsAsErrorsIsOn( string projFilename )
{
    XNamespace xmlns = "http://schemas.microsoft.com/developer/msbuild/2003";
    var twaeList = XDocument.Load( projFilename ).Descendants( xmlns + "TreatWarningsAsErrors" ).ToList();

    if ( twaeList.Count() > 0 )
    {
        var falseValues = twaeList.Where( x => x.Value == "true" );
        if ( falseValues.Count() > 0 )
        {
                // Not good..
        }
    }
    else
    {
        // None exist.. not good either..
    }
}

One thing that's a bit off in your problem domain is that you might have project files, which have the flag switched on for one configuration (e.g. debug), but you won't be able to tell if it even exists in other configurations.
So actually, you can extend the above code and traverse all configurations and look for the flag per configuration. Moreover - if the configuration doesn't exist, or is set to 'false' - you can just manipulate the XML document and insert / fix all these problems on the fly.
HTH.


text:
Q: Attribute selector with quotes? So I'm trying to add a locator constant in my Cypress page objects and I have to use a locator that looks similar to this:
[ng-if="this.customThing.length > 1 && customThing.code !== 'widget.this.thing'"]

The problem is, when I try to wrap the whole thing in quotes in my TypeScript Cypress page object class such as:
LOCATOR_CONSTANT_VARIABLE = "[ng-if="this.customThing.length > 1 && customThing.code !== 'widget.this.thing'"]"

Obviously this won't work due to the multiple uses of quotes and single quotes won't work either.
What's the best way to escape the quotes to use in TypeScript for such an occasion?

A: Backticks are valid string delimeters
const LOCATOR_CONSTANT_VARIABLE =
  `[ng-if="this.customThing.length > 1 && customThing.code !== 'widget.this.thing'"]`

A: You can escape the double quotes like this:
LOCATOR_CONSTANT_VARIABLE =
  "[ng-if=\"this.customThing.length > 1 && customThing.code !== 'widget.this.thing'\"]";


text:
Q: How to write a search query in android SQLite database? In SQL I use :
select * from Table_name  where col_name like 'ex'

What is the equivalent to the above query in sqllite android.
I have tried this in rawQuery(...), but it doesn't work.
I tried this:
Cursor res = dB.rawQuery ("select * from Record where name like 'comp'"+"");

A: The query will be like below
try {

        SQLiteDatabase db = this.getReadableDatabase();

        String _Query = "SELECT * FROM " + _Table_Name;

        Cursor cursor = db.rawQuery(_Query, null);

        if (cursor != null) {

            if (cursor.moveToFirst()) {

                do {

                    // here you get the data on each row.

                } while (cursor.moveToNext());

            }
            cursor.close();
            db.close();

        }

    } catch (Exception e) {

        Log.e("", "exception : " + e.toString());

    }


text:
Q: Problem writing serial data from Arduino to a text file on Raspberry Pi I am trying print data from serial port to a text file, but text file won't open and gives the error invalid byte sequence in conversion input.
here is the relevant part of the code
file = open('file name', 'a')
read_serial = ser.readline()
file.write(read_serial)
file.close()

I'm using a Pi Zero W. Does anyone know what could be going on?


text:
Q: Cache the result of a MySQLdb database query in memory Our application fetches the correct database server from a pool of database servers.  So each query is really 2 queries, and they look like this:

*

*Fetch the correct DB server

*Execute the query

We do this so we can take DB servers online and offline as necessary, as well as for load-balancing.
But the first query seems like it could be cached to memory, so it only actually queries the database every 5 or 10 minutes or so.
What's the best way to do this?
Thanks.
EDIT this is for a Pylons web application

A: Just make a cache(python dict) which stores the first query and return it everytime, clear the cache every N mins, for this you make a decorator or cache class e.g.
import time

cache = {}
lastTime = time.time()

def timedCacheDecorator(func):

    def wrap(*args, **kwargs):

        key = str(args)+str(kwargs)

        # cache for 5 seconds
        global lastTime
        if key not in cache or time.time() - lastTime > 5:
            lastTime = time.time()
            cache[key] = func(*args, **kwargs)

        return cache[key]

    return wrap

# lets test it

@timedCacheDecorator
def myquery():
    return time.time()

print myquery()
time.sleep(1)
print myquery()
time.sleep(5)
print myquery()
time.sleep(1)
print myquery()

Output:
1270441034.58
1270441034.58
1270441040.58
1270441040.58

Now this decorator can be used on any function whose results are to be cached upto a time or may be upto a event, I would make this decorator a class , so that it can take how many seconds to wait before cache refresh, and also you can see how best to generate key.

A: The easiest way would be to use the beaker cache, which is a library built into the pylons framework.
In your model class import the beaker decorator:
from pylons.decorators.cache import beaker_cache

Then on your function header, where you make the database call, add the following decorator:
@beaker_cache(expire = 300, type='memory')

Change the expire value to the amount of seconds you want (currently set to 5 minutes).


text:
Q: Get this empty folders and error in Project View Andoid Studio I all of a sudden (actually a while ago, but it only bothers me now that I started to work on that app again) just got these empty folders in my app under the Project view. It only shows in the Project view. Those folders are empty. The app still runs fine under the emulator.
I would appreciate help fixing those.

A: If they aren't causing any harm/hindrance while building your project, then you can try deleting them. Android Studio will automatically warn you if there any usages of a directory/file which you're trying to delete.
Thanks to Jetbrains for this amazing feature.


text:
Q: How to create a JsonConverter that instantiates a given object type based on an inner field using System.Text.Json Given the following json
{
  "filters": [
    { "filterType": "fooFilter", "min": 1, "max": 5, "size":3 },
    { "filterType": "barFilter", "multiplier": "1.953283", "average": "5.732837" },
    { "filterType": "bazFilter", "limit": 10, "createdBefore": "1641942136" }
  ]
}

I want to create an array of filter objects like so:
public class MyRootClass
{
    public IFilter[] Filters { get; init; } = default!;
}

public interface IFilter
{
    public string Name { get; }
}

public class FooFilter : IFilter
{
    public string Name => nameof(FooFilter);
    public int Min { get; init; }
    public int Max { get; init; }
    public int Size { get; init; }
}

public class BarFilter : IFilter
{
    public string Name => nameof(BarFilter);
    public decimal Multiplier { get; init; }
    public decimal Average { get; init; }
}

public class BazFilter : IFilter
{
    public string Name => nameof(BazFilter);
    public int Limit { get; init; }
    public long CreatedBefore { get; init; }
}

In the above example, I made Name as a auto get readonly property to show that the value from from the json does not need to be stored.  I included several types in each 'IFilter' type that should have built in converters already (ie. createdBefore is a string in json (quoted), but the built in converters will handle conversion to long automatically).
Also to note, there will only ever be either 0 or 1 of each filter type in the array, so there will be no collisions with multiple filters that are the same type.
What I need help with here is writing a JsonConverter that will read the "filterType" in each element of the array in 'filters' and create instances of that filter.
Producing an output similar to this:
var filters = new List<IFilter> {
  new FooFilter { Min = 1, Max = 5, Size = 3 },
  new BarFilter { Multiplier = (decimal) 1.953283, Average = (decimal) 5.732837 },
  new BazFilter { Limit = (int) 10, CreatedBefore = (long) 1641942136 }
}

How can I build the converter to automatically convert each of the types based on the 'filterType' value inside the individual array.  I am thinking along the lines of a switch / case inside of the converter for simplicity, but bonus gold stars for using reflection (in this case I have a pretty short list of Filter types, (less than 10), however down the road, I will be adding a plugin system to (other parts of) my application that could benefit from dynamic conversion using reflection, but I am pretty solid in reflection stuff, so I can do that later if you could explain how to just write the converter portion for this.
Also I am specifically using System.Text.Json libraries as the rest of my application uses that and I don't want to intermix other libraries such as NewtonSoft or Macross.Json.Extensions.  I am using the latest .NET6 (.NET Core) and C#10.
Edit:
As I may not have been clear, (I believe this needs to be done with a JsonConverter) so it is converted automatically as this is how I am deserializing:
using (var client = new HttpClient());

var response = await client.GetAsync(url);

if (response.IsSuccessStatusCode)
{
  var myRootClass = await response.Content.ReadFromJsonAsync<MyRootClass>();
}
else
{
  // Handle errors accordingly
}

so the ReadFromJsonAsync<T> method is what I am using to deserialize the json


text:
Q: Highcharts Stacked Percentage Column Hyperlink I have a Stacked % Column Highchart which without Hyperlinks on data sets works perfectly, however I need to link away to another page from the chart, If it was a standard column chart, I would have no issue (I have one already).  But i cannot seem to work out why I'm getting an undefined error on the link.
Ive searched around for a working example but havent been able to find one matching the stacked percentage column.
I've setup a fiddle to indicate where im up to, any help appreciated.
 $(function () {
 $('#container').highcharts({
   chart: {
     type: 'column'
   },
   title: {
     text: 'Space Overview'
   },
   xAxis: {
     categories: ['a', 'b', 'c', 'd']
   },
   yAxis: {
     min: 0,
     title: {
       text: 'Total Space (%)'
     }
   },
   tooltip: {
     pointFormat: '{series.name}: {point.y} ({point.percentage:.0f}%)
',
     shared: true
   },
   plotOptions: {
     column: {
       stacking: 'percent'
     },
     series: {
       cursor: 'pointer',
       point: {
         events: {
           click: function() {
             location.href = this.options.url;
           }
         }
       }
     }
   },
   subtitle: {
     text: '+ Items relate to items in the dispay cabinets.',
     align: 'left',
     x: 10
   },
   series: [{
     name: 'Free',
     data: [1498, 1123, 556, 1176],
     url: ['Spaces.aspx?box=a', 'Spaces.aspx?box=b', 'Spaces.aspx?box=c', 'Spaces.aspx?box=d']
   }, {
     name: 'Used',
     data: [1234,233,23,759],
     url: ['Spaces.aspx?box=a', 'Spaces.aspx?box=b', 'Spaces.aspx?box=c', 'Spaces.aspx?box=d']
   }]
 });

http://jsfiddle.net/Mooglekins/qv8z5a2o/

A: This is a great question! I did some digging and think I've found a good solution for you.
First, I needed to update how you defined the custom value in your series. To capture certain values in events, I moved the url attribute within each data point. So now, each point has their y value and the new url value.
(Note: I used dummy URLs here since I wouldn't be able to connect to the ones you provided outside your website.)
series: [{
    name: 'Free',
    data: [
        { y: 1498, url: 'http://www.google.com' },
        { y: 1123, url: 'http://www.yahoo.com' },
        { y: 556, url: 'http://www.bing.com' },
        { y: 1176, url: 'http://www.msn.com' }
    ]
    }, {
        // second series here
    }
]

Next, I updated your events call. Now that we've moved the url attribute to each point, we can refer to that value as point.url (as you could the y value using point.y).
What I also did here is use window.open vs. window.location. This will be a better experience for your users so they don't lose sight of the chart. Keep this if you wish.
plotOptions: {
    column: {
        stacking: 'percent'
    },
    series: {
        cursor: 'pointer',
        point: {
            events: {
                click: function (event) {
                    window.open(event.point.url);
                }
            }
        }
    }
}

Here's your updated fiddle with these changes: http://jsfiddle.net/brightmatrix/qv8z5a2o/5/
I hope this helps!


text:
Q: Adding exceptions to recurring events in android < version 4.0
Microsoft Office Project 2007 introduces effective work weeks and
  calendar exceptions, where all calendar data is associated with a set
  of "valid from/to" dates.
  --Microsoft Office Dev Center

Google also uses this feature.
Does Android Calendar (pre-ICS) support these features too? I tried Googling, but only found incomplete posts, such as https://stackoverflow.com/questions/13633577/android-8-sdk-14-recurring-event-exception.
I learned on a separate post that the way to access the calendar was through a content provider, however I have found no working solution
(for example, I tried using "content://com.android.calendar/exception", but it results in an exception saying that it is an unknown url).
Any help to steer me in the right direction would be extremely helpful, as I have been Googling to no avail, and this try and try again stuff is not working well.

A: No. Android Calendar exceptions are officially supported starting with ICS (API level 14):

-- Android Developer Guide
Some versions may allow you to use the Uri you discuss, since it is derived from the source code:
public static final String AUTHORITY = "com.android.calendar";
public static final Uri CONTENT_EXCEPTION_URI = Uri.parse("content://" + AUTHORITY + "/exception");

//hence, CONTENT_EXCEPTION_URI = Uri.parse("content://com.android.calendar/exception");

however since it is not officially supported, it should not be considered reliable.

A: To answer your first question, yes, older Android has ability to have exceptions to a repeating event.
Since that API was introduced in API 14, It's probably a lot different than the previous versions' code. This link has some hints on getting events from calendars on older versions.


text:
Q: CPython 2.7 + Java My major program is written in Python 2.7 (on Mac) and need to leverage some function which is written in a Java 1.8, I think CPython cannot import Java library directly (different than Jython)?
If there is no solution to call Java from CPython, could I integrate in this way -- wrap the Java function into a Java command line application, Python 2.7 call this Java application (e.g. using os.system) by passing command line parameter as inputs, and retrieve its console output?
regards,
Lin

A: *

*If you have lot of dependcieis on Java/JVM, you can consider using Jython.

*If you would like to develop a scalable/maintainable application, consider using microservices and keep Java and Python components separate.

*If your call to Java is simple and it is easy to capture the output and failure, you can go ahead with this running the system command to invoke Java parts.

A: A number of open source projects have been written to enable calling Java from CPython, depending on your needs.

*

*Pyjnius

*Py4J

*JPype forked (original JPype hasn't been updated in years)

*jpy


text:
Q: How can I send a POST request to receive data from a Url? I need to send a POST fetch request using pure javascript to a Url. I need to add an object to my code that looks like this: var data = {task: "getall"} but I don't know where or how to include it or how to start. I'm still very new to Js and I'd like to get some help with this task.
This is my html code for the table:

      <input id="postall" type="button" value="POST Users" />

            Id
            Name
            Street
            House Number

And this is my js code for displaying the data:
function renderUsers(users) {
    const tbody = document.getElementById("userTablePost");
    users.forEach(user => {
        let row = tbody.insertRow();
        let cell = row.insertCell();
        cell.textContent = user.id;
        cell = row.insertCell();
        cell.textContent = user.name;
        cell = row.insertCell();
        cell.textContent = user.street;
        cell = row.insertCell();
        cell.textContent = user.house_number;
    });
}

In theory I should receive data which can be seen in developer tools network option and than I should display that data on a Html page in a table.

A: What you need is to learn about creating something called "AJAX request". The 1st googled tutorial goes to this link: https://www.w3schools.com/xml/ajax_intro.asp which is not bad introduction, but I guess you will need to read a lot more.
Essentially, keywords you need to read about: XMLHttpRequest and AJAX to get your head around the concept. Then the next step, is to be aware of new API called "Fetch API" (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
If you're very new to JS, this may be your first time you will use something called "asynchronous API's". The idea is you DON'T "call a function" and "get the result" in "one go" with this. What you do instead is:

*

*You issue a REQUEST to do something (fetch data from server) - you do it by creating XMLHttpRequest() object (read tutorials).

*You tell your REQUEST object "hey, when you finish, call my function gotData()"

*Then your code finishes or does something else, like shows progress indicator or "please wait" thing.

*Some time later when the browser GETs/POSTs/does other magic, and have fetched the data for you, it will call your "gotData()" function.

...if it looks hard at the beginning - don't give up, it's really a very important programming pattern to understand as you will see more and more of that later.
Hope that helps!

A: Try something like this:
//Promise way
const postData = {task: "getall"};

fetch('https://api.github.com/gists', {
    method: 'post',
    body: JSON.stringify(postData)
}).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log('Response:', data);
});

//Async await
async function fetchData() {
  const response = await fetch('https://api.github.com/gists', {
      method: 'post',
      body: JSON.stringify(postData)
  });

  const json = await response.json();

  console.log(json)
}

fetchData();


text:
Q: Can Django's test client use a specific virtualenv? Is it possible to configure an instance of django.test.client.Client to use a specific virtualenv instead of the OS python install? If so, how?
thanks!
Edit:
I'm using django.test.client.Client from a fabric deploy script, not from within Django itself. Fabric is installed in the virtualenv. So I'm doing something like this:
from django.test.client import Client
response = Client().get(url_path)
if response.status_code == 200:                                                                             |
    return response.content
else:
    # handle error
    pass

A: The test client doesn't know or care at all about virtualenvs or Python versions.
As long as you've activated the virtualenv at the time of running the tests, the version of Python within the virtualenv will be used.

A: The test client will use whatever enviornment Django itself is running in. If you load up a virtualenv with Django installed in it, any management commands will use that Django install.


text:
Q: Why does a charlist not get displayed as a list? I am trying to iterate a charlist with the Enum.map function, but it does not behave how I would expect it to behave.
The first line does not treat the charlist as a list of chars, and in the second line I do not understand why modifying the anonymous function does it.
iex(32)> Enum.map('ABCD',fn(char)->char end)
'ABCD'
iex(33)> Enum.map('ABCD',fn(char)->[char] end)
['A', 'B', 'C', 'D']

I was expecting the first line to return ['A','B','C','D'] and the second line to return [['A'],['B'],['C'],['D']]. Why isn't this the case?

A: In Elixir, and not only (for example C also) char is a number, which represents ASCII code of a "character". Also, ' brackets represent a list, while " represents binaries (or strings).
So, this code probably will help you understand what is going on:
iex> is_list('ABCD')
true # it's list - as described
iex> is_binary('ABCD')
false # it's list of chars - not a string
iex> is_binary("ABCD")
true # with " brackets it's a string
iex> is_list('A')
true # Of cource this is list - list with one element. Like [65]
iex> [65]
'A' # Unexpected? As I told - char is a simple integer!
iex> [65, 66, 67, 68]
'ABCD' # Absolutely logical from previous line
iex> ?A
65 # We use ? sign to get "char" from "letter"
iex> [?A | 'BCD']
'ABCD' # List append works as expected
iex> [?A | [66, 67, 68]]
'ABCD' # The same - absolutely
iex> Enum.map('ABCD',fn(char)->char end)
'ABCD' # char "variable" here is 65, 66, 67, 68 -> maps into list [65, 66, 67, 68]
iex> Enum.map('ABCD',fn(char)->[char] end)
['A', 'B', 'C', 'D'] # You've got list of lists here. Quite crazy?
iex> [[65], [66], [67], [68]]
['A', 'B', 'C', 'D'] # This is your list

A: Ok found it... This is caused by iex that display in a user friendly way the char list.
If I use the settings:
iex(1)> IEx.configure(inspect: [charlists: :as_lists])

Then it display the real output :)


text:
Q: Failed to compile vue.js app due to axios get request I have this seemingly simple vue.js component which causes the app fail to compile:
<template>

    u R LOGED IN {{userid}}

    Token not found

</template>

The error that I get is:
 ERROR  Failed to compile with 1 errors

 error  in ./src/components/AboutMe.vue?vue&type=script&lang=js&

Syntax Error: SyntaxError: /home/me/vue-myapp/src/components/AboutMe.vue: Unexpected token, expected "," (122:9)

  120 |
  121 |   created: {
> 122 |     axios.get('http://127.0.0.1:3000/profile/aboutme/fwefwefewf'  )
      |          ^
  123 |     .then( res => {
  124 |       console.log(res);
  125 |

 @ ./src/components/AboutMe.vue?vue&type=script&lang=js& 1:0-222 1:238-241 1:243-462 1:243-462
 @ ./src/components/AboutMe.vue
 @ ./src/routes.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://192.168.1.10:8080/sockjs-node (webpack)/hot/dev-server.js ./src/main.js

I have used axiom in other components in the same app without any issues so have no clue what could be wrong here?
How can I fix it?

A: The created property needs to be a function, not an object:
import axios from 'axios';

export default {
  created() {
    axios.get(...
  }
}

A: Syntax error change to:
created: function(){
    axios.get('http://127.0.0.1:3000/profile/aboutme/somejibberish'  )
    .then( res => {
        console.log(res);

    })
    .catch( error => {
        console.log(error);
    })
}

Source: https://v2.vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks
Or as seen in thefallens answer!


text:
Q: FreeRTOS, Atmel Studio - Task not being blocked before it receives a binary semaphore I'm trying to switch to a blocked task after a button press. Basically I want task_player1 to do nothing until it receives a semaphore from task_ctrl. The way I'm giving the semaphore is on a button press. The code is bellow:
#define B1 PIO_PB26_IDX

#define TASK_STACK_SIZE (2048/ sizeof(portSTACK_TYPE))

xTaskCreate(task_ctrl, (const signed char * const) "Control", TASK_STACK_SIZE, NULL, 1, NULL);

xTaskCreate(task_player1, (const signed char * const) "Player1", TASK_STACK_SIZE, NULL, 1, NULL);

void task_player1(void *pvParameters)
{
    vSemaphoreCreateBinary(player1_signal);

    while (1)
    {
        if( xSemaphoreTake( player1_signal, portMAX_DELAY ) == pdTRUE )
        {
            printf("Semaphore taken\n");
            ioport_set_pin_level(L1, HIGH);
        }
    }
}

    void task_ctrl(void *pvParameters)
{
    static signed portBASE_TYPE xHigherPriorityTaskWoken;

    bool button1;
    while (1)
    {
        xHigherPriorityTaskWoken = pdFALSE;
        button1 = ioport_get_pin_level(B1);
        printf("TASK_CTRL RUNNING...\n");
        ioport_set_pin_level(L1, LOW);

        if (button1)
        {
            xSemaphoreGiveFromISR(player1_signal, &xHigherPriorityTaskWoken);
            printf("Semaphore given\n");

            vTaskDelay(1);
        }
    }
}

The problem is task_player1 is never blocked as it should be by portMAX_DELAY. As soon as I upload the code to the microchip the LED lights up while I only want it to light up once I press the button and the semaphore is given. What am I doing wrong here?
Due to Atmel Studio restrictions I'm using FreeRTOS v7.3.
Edit: Updated code

A: Binary semaphores in FreeRTOS are created in a "given" state, ie. with a count of 1. Therefore when task_player1() enters the while loop it will set the pin to high without blocking at the semaphore. You could call xSemaphoreTake() just after the semaphore is created to decrement the semaphore count to 0.
task_ctrl() should not be using xSemaphoreGiveFromIsr(), because it is a task and not an ISR.


text:
Q: Extending onclick argument of button_to_remote in rails I would like to extend my onclick parameter of button_to_remote with another javascript function call, but i couldn't find any answer for that.
So i have sg like this:
button_to_remote('>', :url => {:action => "show_dtree", :id => tree_child.id, :dir1 => dir11, :dir2 => dir12}

what generates the following code:
<input onclick="new Ajax.Request('/d_trees/show_dtree/3?dir1=1&dir2=2', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('2e8e2147c344bcee0edf40f8fe6072c12dc928d7')});" type="button" value=">" />

And my aim would be to call a foo() function after the ajax request object instantiated:
<input onclick="new Ajax.Request('/d_trees/show_dtree/3?dir1=1&dir2=2', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('2e8e2147c344bcee0edf40f8fe6072c12dc928d7')});foo();" type="button" value=">" />

Is there any way to this beside to generate the whole button by myself?
Thanks for your help!

A: Sure, just add your function as a callback:
button_to_remote '>',
  :url => { :action => "show_dtree", :id => tree_child.id, :dir1 => dir11, :dir2 => dir12 },
  :complete => "foo()"

This will call foo when the Ajax request is complete. Instead of :complete you could use any of the other stages, e.g. :loading, :success, etc.


text:
Q: Pass anchor id and button id to jquery I have this code which works just fine for one block and saves the div element as image. I am using html5 canvas. How I can achieve to pass the id and other variables to jquery if I have n numbers of such div with unique ids.
Here is my code below:-

        Codepedia.info

            Html to canvas, and canvas to proper image

    <input class="btn-Preview-Image" type="button" value="Preview"/>
    Download

Preview :

        Codepedia.info

            Html to canvas, and canvas to proper image

    <input class="btn-Preview-Image" type="button" value="Preview"/>
    Download

Preview :

        Codepedia.info

            Html to canvas, and canvas to proper image

    <input class="btn-Preview-Image" type="button" value="Preview"/>
    Download

Preview :

        Codepedia.info

            Html to canvas, and canvas to proper image

    <input class="btn-Preview-Image" type="button" value="Preview"/>
    Download

Preview :

        Codepedia.info

            Html to canvas, and canvas to proper image

    <input class="btn-Preview-Image" type="button" value="Preview"/>
    Download

Preview :

        Codepedia.info

            Html to canvas, and canvas to proper image

    <input class="btn-Preview-Image" type="button" value="Preview"/>
    Download

Preview :

        Codepedia.info

            Html to canvas, and canvas to proper image

    <input class="btn-Preview-Image" type="button" value="Preview"/>
    Download

Preview :

        Codepedia.info

            Html to canvas, and canvas to proper image

    <input class="btn-Preview-Image" type="button" value="Preview"/>
    Download

Preview :

        Codepedia.info

            Html to canvas, and canvas to proper image

    <input class="btn-Preview-Image" type="button" value="Preview"/>
    Download

Preview :

        Codepedia.info

            Html to canvas, and canvas to proper image

    <input class="btn-Preview-Image" type="button" value="Preview"/>
    Download

Preview :

A: Markup:
You have to add a parent div for each repeated group and change ID to class, and use find to query.

      Codepedia.info

            Html to canvas, and canvas to proper image

    <input class="btn-Preview-Image" type="button" value="Preview" />
    Download

Preview :

Script
$(document).ready(function() {
    $(".btn-Preview-Image").on('click', function() {
    parent = $(this).closest('.block-holder');
    element=parent.find('.html-content-holder')
    //  getCanvas;
    console.log(parent,element);
    preview = element.find(".previewImage");
    html2canvas(element, {
      onrendered: function(canvas) {
        $(".previewImage").html(canvas);

      }
    });
  });

  $(".btn-Convert-Html2Image").on('click', function() {
   parent = $(this).closest('.block-holder');
   getCanvas = parent.find('canvas')[0];
   console.log(parent,getCanvas)
    var imgageData = getCanvas.toDataURL("image/png");
    var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
    $(".btn-Convert-Html2Image").attr("download", "your_pic_name.png").attr("href", newData);
  });

});

You can see preview= element.find(".previewImage"), use same technique to for getcanvas variable and else.
Here is running fiddle https://jsfiddle.net/5cfz2ufp/10/


text:
Q: How should I link to user profile pages in ASP.NET MVC 5? I heard that it is not a good security practice to allow users to submit forms with user id's. This leads me to believe that its is not good practice to allow the user id to be seen in the url. But I need a way to allow users to see other users profiles.
I was wondering, instead of using
@Html.ActionLink("Details", "Details", new { id = item.Id })

If I should use
@Html.ActionLink("Details", "Details", new { id = item.username })

then in the controller find user by username and return user.
Is this the correct way of going about this?
this is now my link
@Html.ActionLink(person.FullName, "Details","User" , new { UserName = person.UserName }, null)

this is now my controller action
    // GET: /User/Details?UserName=bbob
    public ActionResult Details(string UserName)
    {
        if (UserName == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        ApplicationUser aspnetuser = UserManager.FindByName(UserName);

        if (aspnetuser == null)
        {
            return HttpNotFound();
        }
        return View(aspnetuser);
    }

A: I prefer the Username approach, as it eliminates the requirement of having to look up the Id if you already know the username, and it also makes it more difficult for users to "browse" user information by iterating through the list of possible ids.
And also this question is probably going to get flagged. :)


text:
Q: How quickly set up a python environment to work and tweak a GitHub downloaded repo? Can somebody simply explain to me what is the correct workflow to download a GitHub code and work on it, quickly try tweaks and fixes ?
Solution 1

*

*install the GitHub repo using pip

*then python "functions" are called using shell commands, not in Python shell, but in the macOS shell.

This is clearly not the good solution as I don't even know where is the source code. And not use the macOS shell. I want to see all the files, copy/paste, correct and try things.
Solution 2

*

*Download the GitHub repo in a working directory.

*Open a macOS shell.

*cd in the directory.

*Update PYTHONPATH to the current directory.

*Start the python shell.

*Load the desired script to try using the import directive.

*Edit the script using a text editor and repeat action 6 to try things.

It feels weird to update PYTHONPATH each time I want to work on it. But the weirder is that because the initial script is done to be used in the macOS shell, I cannot pass argument to the main() function when calling it through the Python shell.
Am I missing something here ? Is it normal that python repos look like released code that can hardly be tweaked and quickly tested ?

A: None of those solutions are the right way to do it. When you need to patch a python code, because you want to add a feature or fix a bug, you should proceed as follows:
Solution 3

*

*Find the project's main page (on github, gitlab or anywhere else), usually a lookup DDG or google or --help will point you the right direction.

*Read the project's README file, and look for a developers section

*Checkout the project issue tracker for feature requests and bug reports to be sure to check what you'll do isn't being worked on by someone else (and then you can offer your help), that's important for collaboration

*For building and developing, follow instructions from the README, which usually look like the following, or just follow this:

How to work on a python project

*

*copy the repository URL (https://github.com/<user>/<project>)

*open a terminal in a directory where you want to keep your on-going work (I like to use ~/Workspace)

*run git clone https://github.com/<user>/<project>

*cd <project>

*virtualenv var (you can use whatever name you want, but my preference goes for var)

*var/bin/pip install -r requirements.txt

*run var/bin/python and all the modules you're developing are available in the python REPL.

This should apply to the vast majority of python projects. Some projects will show you other tools like virtualenv for that step (hint: if there's a requirements.txt you know it's what you'll do), or will use zc.buildout or will use pipenv, but those will usually tell how to build in the README.
Your questions

It feels weird to update PYTHONPATH each time I want to work on it. But the weirder is that because the initial script is done to be used in the macOS shell, I cannot pass argument to the main() function when calling it through the Python shell.

you're right to feel weird doing that. Tools like virtualenv or buildout are there to create contained environments for you to develop comfortably. You'll even find the script you usually find in your path available in the env's bin directory. You'll also find the test suite so that you can test your changes against regressions!

Is it normal that python repos look like released code that can hardly be tweaked and quickly tested ?

usually development happens in a specific branch on a project. So on the github page, you might see the stable/release branch, whereas all the new stuff happens in the devel branch. always look at the issues, and first communicate with the project's maintainer before doing code, at risk of having your contribution rejected.


text:
Q: RequireJS is undefined After much frustration, I finally decided to install requirejs via npm. However, even with this basic example, it still won't work.
define(function(require) {

var requirejs = require('node/node/lib/node_modules/npm/node_modules/requirejs/require');

requirejs.config({
    //Pass the top-level main.js/index.js require
    //function to requirejs so that node modules
    //are loaded relative to the top-level JS file.
    nodeRequire: require
});

requirejs(['http'],
function   (http) {
// code here
});

});

The error:
TypeError: requirejs is undefined @ test.js:7

If I replace the long path with just require, I get instead:
 TypeError: requirejs.config is not a function @ test.js:11

A: You created a function with an argument of require.   Try changing your first line to function(somethingElse) and it should load.


text:
Q: Google apps script error DriveApp not defined in JavaScript a little help if possible.
In a Google Apps Script web application I have an error (DriveApp is not defined) in the following code in the JavaScript.html file:
<script type='text/javascript'>

$(function(){
    var runner = google.script.run.withFailureHandler(onFailure)
    runner.withSuccessHandler(onSuccess).getData()
});

...
var searchParams = "Parametri ricerca";
var files = DriveApp.searchFiles(searchParams);
    while (files.hasNext()) {
 var file = files.next();
 var fileName = file.getName());
 var fileUrl = file.getUrl());
}

</script>

A: Answer:
You can not use the Apps Script classes such as DriveApp from inside JavaScript files. You must use google.script.run to call an Apps Script method which uses it.
Code Example:
JavaScript:
function callGAS {
  google.script.run.withSuccessHandler(doSomething).getFileUrl()
}

function doSomething(fileUrl) {
  console.log(fileUrl) //or whatever you want to do with it
}

Apps Script:
function getFileUrl() {
  var searchParams = "Parametri ricerca";
  var files = DriveApp.searchFiles(searchParams);
  while (files.hasNext()) {
     var file = files.next();
     var fileName = file.getName());
     var fileUrl = file.getUrl());
  }
  return fileUrl // or whatever
}

References:

*

*Class google.script.run (Client-side API | Apps Script | Google Developers


text:
Q: Adding Back Tracks Does Not Work on WebRTC We create an app with React Native WebRTC and Janus Gateway. It works as wanted. Our app is  based on push to talk. So when an users in listen mode need to break microphone for other apps. And take back when anyone press to speak button.
Breaking Mic:
if (!globalTrack) {
     globalTracks = config.myStream.getTracks();
}
config.myStream.getTracks().forEach(t => {
    config.myStream.removeTrack(t);
});

Get Back the Tracks:
globalTracks.forEach(t => {
    config.myStream.addTrack(t);
});

pluginHandle.createOffer({
    media: { addVideo: true },
    success: function(jsep) {
        Janus.debug(jsep);
        pluginHandle.send({message: {audio: true, video: false}, "jsep": jsep });
    },
    error: function(error) {
        console.log("WebRTC error... " + JSON.stringify(error));
    }
});

// also I have try this:

devices = await mediaDevices.getUserMedia({audio: true, video: false})
// devices output https://pastebin.ubuntu.com/p/KQqBq2QRy3/
devices._tracks.forEach(t => {
    config.myStream.addTrack(t);
});

pluginHandle.createOffer({
    media: {audio: {deviceId: devices._tracks[0]['id']}, replaceAudio: true},
    success: function(jsep) {
        pluginHandle.send({message: {audio: true, video: false}, "jsep": jsep});
    },
    error: function(error) {
        console.log(("WebRTC error... " + JSON.stringify(error));
    }
});

Problem:
Problem: E.g: when a call came to the phone and answered it. The user's voice does not pass anymore even after restarting the app.
On Janus Gateway every things is normal. I think problem is about renegotiation.

*

*Problem occurred only on Android phones. And works after force stopping the app.

Janus Gateway Log which when I speak at room:
There's a message for JANUS AudioBridge plugin
Setting muted property: true (room 20, user 2301490876606211)
Notifying participant 329012611897879 (kardan)
Sending event to transport...
  >> 0 (Success)

A: We can not find a generic solution.
For now restarting app is works with react-native-restart


text:
Q: How to perfectly align different size text in react native i want to align three text views with different text sizes perfectly to left side, text is now aligned left without any issues but if i use a different text sizes it's gonna look imperfect i want to know is there a way align different sized text perfectly in react native.

This is how its looks like when all the fonts are same size

This is how its looks like when using different text sizes

A: You could solve it by separating your data into columns. For exampel Swivel is col1, List col2 etc . Here is a working (working but no perfect :)) example snack.


text:
Q: trying to run flutter application and it fails saying Build failed with an exception I'm trying to run an flutter app but for some reason that I can't figure out, it won't run. This is what I'm getting when I run. I did add the flutter/bin bath to the system path, but that didn't work either. This happened after I reformatted my windows. What I did exactly was:

*

*install Android Studio

*download flutter sdk

*added flutter plugin in the Android Studio.

and this is what i did the first time before I formatted my PC. And it worked.
Launching lib\main.dart on Mi 9T in debug mode...
Running Gradle task 'assembleDebug'...

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:signingConfigWriterDebug'.
> java.io.IOException: Unable to delete file: E:\codes\flutter\im_poor\build\app\intermediates\signing_config\debug\out\signing-config.json

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 5s
Finished with error: Gradle task assembleDebug failed with exit code 1

and this what flutter doctor said:
C:\flutter_windows_v1.9.1+hotfix.6-stable\flutter\bin\flutter.bat doctor --verbose
[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.17763.1098], locale en-US)
    • Flutter version 1.12.13+hotfix.8 at C:\flutter_windows_v1.9.1+hotfix.6-stable\flutter
    • Framework revision 0b8abb4724 (5 weeks ago), 2020-02-11 11:44:36 -0800
    • Engine revision e1e6ced81d
    • Dart version 2.7.0

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
    • Android SDK at C:\Users\Joseph\AppData\Local\Android\sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 29.0.3
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
    X Android license status unknown.
      Try re-installing or updating your Android SDK Manager.
      See https://developer.android.com/studio/#downloads or visit https://flutter.dev/setup/#android-setup for detailed instructions.

[√] Android Studio (version 3.6)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 44.0.2
    • Dart plugin version 192.7761
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)

[√] Connected device (2 available)
    • Mi 9T               • d8f2ce60      • android-arm64 • Android 10 (API 29)
    • AOSP on IA Emulator • emulator-5556 • android-x86   • Android 9 (API 28) (emulator)

! Doctor found issues in 1 category.
Process finished with exit code 0

A: I acutally solved this by creating a new Project and copied all the code from the old one .

A: go to file: E:\codes\flutter\im_poor\build\app\intermediates\signing_config\debug\out
and select signing-config.json file
then delete the file by shift+delete


text:
Q: SAS proc fcmp returns missing I have the following code:
options mprint mlogic symbolgen;
%macro get_vtype();
  %let table = %sysfunc(dequote(&table.));
  %let var = %sysfunc(dequote(&var.));

  data metadata.temp;
    set &table.;
    var = vtype(&var.);
    call symput('res',vtype(&var.));
  run;
%put &=res;
%mend;
proc fcmp outlib=work.functions.wrapper;
  function myvtype(table $,var $) $ 1;
    rc = run_macro('get_vtype',table,var,res);
    put rc;
    put res;
    return (res);
  endsub;
quit;
options cmplib=work.functions;
data temp;
  vtype = myvtype("sashelp.class","age");
run;

I expected to get N as result in temp. However it is missing. While Debugging I mentioned, that %put &=res; resolves to N, but put res;returns.`.
Waht is the problem?

A: My guess is that the metadata library is not assigned inside the run_macro session.
I've had some really weird and inconsistent results with run_macro, I'd avoid it where possible - try dosubl instead.  The following code works:
%macro get_vtype(table,var);
  data _null_;
    set &table.;
    var = vtype(&var.);
    call symputx('res',vtype(&var.),'g');
    stop;
  run;
%put &=res;
%mend;
proc fcmp outlib=work.functions.wrapper;
  function myvtype(table $,var $) $ 1;
    rc = dosubl(cats('%get_vtype(',table,',',var,');'));
    put rc;
    length res $1;
    res=symget("res");
    put res;
    return (res);
  endsub;
quit;
options cmplib=work.functions;
data test;
  vtype = myvtype("sashelp.class","age");
run;


text:
Q: Spring how to use non embbed database I learned from this article https://spring.io/guides/gs/accessing-data-jpa/. And I have a problem because every time the application is turned off and turn it again, the data from the database are lost and must be entered again. How do data to be stored permanently?

A: The data is lost because the tutorial uses an in-memory database. For the data to be persisted, you need to use a database like MySQL or Postgres. The following steps would alter the tutorial to use MySQL:

*

*Replace the dependency on H2 with MySQL. I.e., if you are using maven, in pom.xml, replace
<dependency>
    <groupId>com.m2database</groupId>
    <artifactId>h2</artifactId>
</dependency>

with
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

*Put MySQL connection info in src/main/resources/application.properties, like this:
spring.jpa.database: MYSQL
spring.jpa.hibernate.ddl-auto: update

spring.datasource.url: jdbc:mysql://localhost:3306/db-name
spring.datasource.username: your db-username e.g. root
spring.datasource.password: db-password

*Install MySQL if you haven't already, and create the database.


text:
Q: when added spin (spin.js) - web page lose functionality Please, I need help about spin function (using spin.min.js script)
Problem appears when I added it to my web page, web page loge functionality - I can not click on any link and can not mark anything with mouse. I don't know what's the problem, please help me.
SCRIPT IN BODY TAG

HTML

CSS
.loading{
background: #F7F7F7;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
z-index: 500;

.loading-out{
-webkit-opacity: 0;
-moz-opacity: 0;
opacity: 0;
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-ms-transition: all 1s ease;
-o-transition: all 1s ease;
transition: all 1s ease;

#spin{
margin: 0px auto;
position: absolute;
left: 50%;
top: 50%;

JQUERY
$(function()

    $(window).load(function() {
        // Fadeout loading
        $('.loading').addClass('loading-out');

        // Hide loading
        setTimeout(function() {
            $('.loading').hide();
        }, 800);
    });

A: *

*Your CSS definitions must be enclosed in {}. Right now it's only { without closing }

*Your jQuery anonymous function is missing {}. Change $(function() /* window load */ to $(function() {/* window load */}).

Check dev tools console to see if there is any errors. It may also be that your JS is taking huge amount of memory and browser is still executing JS while you try to interact with it.
Check if you have jQuery loaded before any script that uses $.


text:
Q: Java Security Ignoring Whitelist I'm running Oracle 1.8 on Ubuntu 15.04 and having no problems. However, I need too access some java apps from a website as part of a learning module. I am using Firefox 42.0 with the Java PlugIn installed and activated. I click the "Launch" button, the app starts, and I get the pop up telling me that Java Security has blocked the app because it does not have a security file in the .jar. No problem. I open up the control panel and whitelist the domain, the domain/, and the specific app URL. Restart everything and.... Java Security has blocked etc. In the CP the domain shows as whitelisted. And here's what has me talking to myself. After the dialogue closes I can right click the empty app page, click Page Info, and in the Security tab is shows Java as being set to "ALLOW" rather than "Default". So.... Java says the domain is whitelisted. The browser says that Java is set to allow for that domain. And yet... no love. Any ideas?
ETA:  The specific error is that there is no security manifest in the .jar.  According to Oracle's docs, this specific issue is eligible to be addressed by whitelisting.


text:
Q: Importing data with multiple IDs I need to import some data onto a server. The problem I have is the data isn't quite in the right format. To put it simply, it looks like this:
ITEMS_DIREC

ID | Co-ordinate
1  | 648
2  | 25
2  | 305
2  | 307
2  | 569
3  | 354
3  | 450
3  | 573
4  | 293
4  | 449
5  | 25
5  | 73

I want it to look something more like this:
1  | 648
2  | 25, 305, 307, 569,
3  | 354, 450, 573,
4  | 293, 449
5  | 25, 73

This is the code I have to alter (this code assumes that each ID is unique, so no multiples like above):
class Item:
    def __init__(self, iid, name):
        self.iid = iid
        self.name = name

class Data:
    def __str__(self):
        return "Item[iid=%s,name=%s]" % (self.iid, self.name)

    def __init__(self):
        self._items = {}
        self._items_file = "%s/%s" % (DATA_DIREC, ITEMS_DIREC)

    def add_item(self, item):
        self._items[item.iid] = item

    def __init_items(self):
        f = open(self._items_file, 'r')
        for line in f:
            data = line.rstrip('\r\n').split("|")
            self.add_item(Item(data[0], data[1]))
        f.close()
        print "Items added" % len(self._items)

So I get the impression that if I use this code on my original data, it won't consider the multiple ID's as one in the same. Not only that, but my data set is quite large (100,000+) and not every ID has the same number of co-ordinates so I can't simply construct a matrix and fill in the values.
Can anyone give me some help in the right direction? I'm not at all experienced with Python so everything I've tried so far has failed quite miserably.

A: You can use csv.reader and csv.writer to handle pipe delimited data and a collections.defaultdict to accumulate each value for key id. You can use islice to conveniently skip the first few rows that you don't require, then for final output, sort the rows by id and then write them out followed by a comma delimited list of values. eg:
import csv
from itertools import islice
from collections import defaultdict

dd = defaultdict(list)
with open('input') as fin:
    pipe_in = csv.reader(fin, delimiter='|')
    for key, val in islice(pipe_in, 3, None):
        dd[key].append(val)

with open('output', 'wb') as fout:
    pipe_out = csv.writer(fout, delimiter='|')
    pipe_out.writerows([k, ', '.join(v)] for k, v in sorted(dd.iteritems()))

# 1|648
# 2|25, 305, 307, 569
# 3|354, 450, 573
# 4|293, 449
# 5|25, 73