text:
Q: Swift enum multiple generic types involving depending protocols protocol ProtocolA {
    func someFunc() -> Any
}

protocol ProtocolB: ProtocolA {
    var someVar: Any { get }
}

enum MyEnum<T: ProtocolA, U: ProtocolB> {
    case A(T)
    case B(U)
}

protocol DataObject {
    ...
}

extension DataObject where Self: ProtocolB {
    func doSomething() {
        let x = MyEnum.B(self)
        /// Compiler error:
        /// Cannot invoke 'B' with an argument list of type '(Self)'
    }
}

I don't understand why the above is giving me an error.
Strangely, removing either of the two enum generic constraints, leaving the enum with a single constraint, solves the problem...
Note that ProtocolB extends ProtocolA. Is this not supported when used with generic constraints?

UPDATE
Changing MyEnum to this solves the problem:
enum MyEnum {
    typealias T = ProtocolA
    typealias U = ProtocolB

    case A(T)
    case B(U)
}

However, I still don't quite get why...

A: The error is a little misleading. Let's simplify the problem to explore it.
protocol ProtocolA {}

protocol ProtocolB: ProtocolA {}

enum MyEnum<T: ProtocolA, U: ProtocolB> {
    case A(T)
    case B(U)
}

struct AThing: ProtocolA {}

struct BThing: ProtocolB {}

let bThing = BThing()
let thing = MyEnum.B(bThing) // error: cannot invoke 'B' with an argument list of type '(BThing)'

So now we have the same problem without needing DataObject. Why does this fail?
MyEnum is generic. That means that in order to create a concrete type, it must know the types of T and U. You provided constraints on those types (one conforms to ProtocolA and the other to ProtocolB), but you didn't say specifically what types they are.
When we get to this line:
let thing = MyEnum.B(bThing)

What type is thing? With type inference, we can work out what U is, but what is T?
let thing: MyEnum<?, BThing> = MyEnum.B(bThing)

There's just not enough context here to work it out, so we have to tell the compiler explicitly:
let thing = MyEnum<AThing, BThing>.B(bThing)

So the full type of thing is MyEnum<AThing, BThing>, which is a different type than MyEnum<OtherAThing, BThing>. (Exactly like [Int] is different type than [String], which is why let xs = [] won't compile without an explicit type definition.)
Your second example that works is not generic, so there's no problem. It simplifies to:
enum MyEnum {
    case A(ProtocolA)
    case B(ProtocolB)
}

Bound typealiases just rename types, they don't create new types (like an unbound typealias would, or as Swift 2.2 calls it, associatedtype). So we know that A takes any ProtocolA and B takes any ProtocolB, and all MyEnum instances have the same type.
The error is unfortunate because the compiler is confused. You'd get a clearer error if you simplified this down to the most basic case. This fails for exactly the same reason as your example.
enum MyEnum<T> {
    case A
}

let x = MyEnum.A // error: generic parameter 'T' could not be inferred


text:
Q: Hide Download files page (IDP)? I use "Inno download plugin" in my inno installer, I wish to download the files before I get to "wpInstalling" and to hide the IDP download page,
Now here is the problems I encountered:

*

*If I use "idpAddFile" function i must specify "idpDownloadAfter" and thus i cant hide the IDP download page from the user

*If i use "idpDownloadFile" function my inno setup becomes "slaggy" and slow for some strange reason

redpajama_set_name: RedPajamaStackExchange


text:
Q: PyCharm/Python don't import packages from Anaconda I am using PyCharm as IDE and Anaconda as a package manager. Pyhton is 3.6 version
When I import pandas I get
pyptz: No moudle name 'pyptz'
dateutil: No moudle name 'dateutil'

However in PyCharm interpreter I have all these packages are updated.
Another problem, I don't know if it is related, is I have pip 20.0.2   however in the command line (that is in the same directory of my Python console) it says my pip version is 9.0.1
It seems that no matter if I have my packages in anaconda up to date, those packages do not interact with PyCharm/Python.
PS: I also have my /PATH with the Anaconda directory.

A: *

*Open your PyCharm project

*Go to File>Settings. Then Project:[YOUR_PROJECT_NAME]>Project Interpreter

*After that, you'll see the image below

*Choose your Anaconda Interpreter from the list

*If you don't find it in the list, the go-to Show All ... and select your Interpreter.

*Apply and Save the Settings

A: I solved this by reinstall the Anaconda Software in C:/Users/"User name"/AppData/Local
I am not sure if it is because the pip folder is in this directory, but I tested a lot of solutions, and this is the only one that worked.


text:
Q: Linq expression with eager loading only top n records I am using entity framework core. I am eager loading a navigation property for an entity. What I want to achieve here is only load top 5 records ordered by creation date along with the main entity. I have following query.
Context.Foo.Where(f => f.Id == fid)
    .Include(f1 => f1.Bars.OrderByDescending(b => b.CreateDate).Take(LIMIT))
    .FirstOrDefault();

It throws error that property expression is not valid. I understood that the expression should just evaluate to a property we want to include, but is there a way where we can fine tune the selection of properties?

A: Filtering includes is not allowed in EF Core to the best on my knowledge.  It does look like there is a github project that adds this feature which may work in your case. https://github.com/zzzprojects/EntityFramework-Plus/wiki/EF-Query-IncludeFilter-%7C-Entity-Framework-Include-Related-Entities-using-Where-Filter


text:
Q: Kiosk mode in wxpython? Is there a way to create a 'kiosk mode' in wxpython under Windows (98 - 7) where the application disables you from breaking out of the app using Windows keys, alt-tab, alt-f4, and ctrl+alt+delete?

A: If an application could do that it would make a great denial-of-service attack on the machine.
In particular Ctrl+Alt+Delete is the Secure Attention Sequence.  Microsoft goes to great lengths to insure that when the user hits those keys, they switch to a secure desktop that they can be confident that the logon box is the real Windows logon and not a counterfeit.
What you need to look at isn't functions that your application can call, but System Administration options that allow an Administrator to configure a machine for limited use.  These exist, but it's more a question for Super User than for Stack Overflow.
This should get you started
http://msdn.microsoft.com/en-us/library/aa372139(VS.85).aspx

A: wxPython alone cannot be done with that.
You need to do Low Level Keyboard Hook with C/C++ or with equivalent ctypes, for
Windows keys, alt-tab, alt-f4,
but Ctrl-Alt-Del, I don't think so for Windows XP and above.


text:
Q: Vector calculus in statistics I'm teaching a class on integration of functions of several variables and vector calculus this semester. The class is made up most of economics majors and engineering majors, with a smattering of math and physics folks as well. I taught this class last semester, and I found that a lot of the economics majors were rather bored during the second half. I was able to motivate multiple integrals by doing some calculations with jointly distributed random variables, but for the vector analysis part of the course the only motivation I could think of was based on physics.
So I'm wondering if anybody knows a statistical/probabilistic interpretation of any of the main theorems of vector calculus: Green's theorem, Stokes' theorem, and the divergence theorem.  Part of the problem is that vector fields don't seem to come up very often in probability theory, let alone divergence, gradient, or curl.  I also posted this question on math.stackexchange a few days ago, but I'm still looking for more ideas.

A: One example you could look into is quasi-likelihood. The discussion of these in McCullagh & Nelder: Generalized Linear Models uses (for the theoretical part) gradients and path-integrals in an essential way!  See chapeter 9 of that book.

A: I doubt many statisticians will have to use vector calculus as it is taught for physics and engineering. But for what it's worth here are a few topics that would use it, at least tangentially. The underlying theme here is that holomorphic functions from complex analysis, which are composed of harmonic functions, are intimately linked through the Cauchy Riemann equations to both Stokes' and Green's theorems. These functions can be studied both by examining the the interior of their domain along with their boundary.
Probability Currents. This isn't just for quantum mechanics. In general, probability diffusions arise when studying time-varying probability distributions which change smoothly. This includes stochastic version of classical systems, such as the heat equation, Navier Stokes for fluid dynamics, wave equations for quantum mechanics, etc. Examples of equations include the Fokker-Planck equation and Kolmogorov Backwards/Forwards equations involve divergences, which in turn relate to heat equations, Feynan-Kac integrals, dirichlet problems and Green's functions. The keywords here are complex harmonic functions, which satisfy the mean value property, which in turn is a consequence of Green's integral theorem and Stokes' theorem. A classical example is calculating the exit time of a diffusion from a closed region, which reduces to evaluating integrals on the boundary of the surface and exploiting harmonicity within the region.
The main example here is problems involving Brownian motion, and in general the wide class of Ito Diffusions. A wonderful (and eccentric!) book on this is Green, Brown and Probability by the legendary Kai Chung.
The Disintegration Theorem for probability is implicity Stokes' Thoerem, in that one disintegrates a 3 dimensional probability measure onto the boundary of the surface that encloses its support.
In statistical mechanics and in markov random fields, there is a large prevalence of conservation in the form of currents. The Ising Model, especially at criticality, and its relatives can be studied from the point of view of discrete harmonic and holomorphic functions. From the Cauchy Riemann equations, one recovers both Green's Theorem and Stokes's theorem, in that currents are both divergence free and curl free, which together imply that the underlying field is holomorphic. A great reference on this is from the work of Smirnov, Chelkak and Dominil-Copin.


text:
Q: Keep listview colored while scrolling My listview has a button per line. When clicked I change this line color.
The problem is while scrolling it... return to default or other lines are colored.
The button listening is coded inside the adapter
public CustomAdapter(Context context, List<Map<String, String>> items, int resource, String[] from, int[] to) {
    super(context, items, resource, from, to);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);

    final View line = view;
    TextView txtid = (TextView) view.findViewById(R.id.txtid);
    TextView txtnumber = (TextView) view.findViewById(R.id.txtnumber);

    Button btn = (Button) view.findViewById(R.id.btncheck);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (txtnumber.getText().toString().equals(KEY-CODE)){
                line.setBackgroundColor(0x7F00FF00);
            }else {
                line.setBackgroundColor(0x7FFF0000);
            }
        }
    });

    return view;
}

A: I faced somthing like this once, you can save the state of the button using HashMap where the the boolean indicate the state of the button ( true if it was clicked and false otherwhise ), know inside getItemView check if current button is clicked or not from the HashMap.
A little bit of code :
inside getItemView first initialize each button to false (not clicked)
if(map.get(v.findViewById(R.id.button)) == null)
      map.put(v.findViewById(R.id.button)),false);

and after clicking the button set the Boolean to true :
map.put(v.findViewById(R.id.button)),true);

and finally check if the Boolean is set to true or false and set the color.


text:
Q: Google App Engine Channel API MESSAGE QUEUES If a client is connected and then disconnects - say his connection is lost for 5 mins;  does the server queue the messages that can't be delivered?
On the local development server this seems to be the case?
If this is the case in production - how long are the messages queued for?
Thanks

A: In production the messages are dropped if your server receives the /_ah/channel/disconnected/ POST.
In practice there's a tiny bit of caching. If you eg. lose your connection very briefly because your wifi connection drops, a message sent during that time could be queued up and delivered. But you shouldn't get the disconnect POST in that case.


text:
Q: Passing props from child function to parent function with React Native Within Session() I want to access stateABC, which is in Item5().
The setup of my code looks like this:
Session.js:
function Session() {
//get handleRender(item).props.stateABC here
    return (
        <View>
            {handleRender(item)}
        </View>
    );
}

handleRender.js:
export function handleRender(item) {

    if(item == "Item5"){
        return (
                {Item5()}
            );
    }
}

Item5.js:
 export function Item5() {

        const [stateABC, setStateABC] = useState("123");

        return (
                    ....
                );
    }

I tried to get the value in Session() by using handleRender(item).props.stateABC, but all I get is an empty value.
Is it possible to receive properties from a function like that or are props only accessible in class components?
Any help is appreciated.
Thanks

A: If you need to access to stateABC value from Session component you have to pass a callback prop down from Session to Item5 and call it every time you update stateABC with setStateABC, passing the new value to the callback.
This is the simplest approach, you could also use React Context API or even something like Redux if you think that your app will grow in complexity.
Also, the approach that you tried to use is a bad idea. It works only in class component but in any case you should not use it, it's a bad thing to access props directly.


text:
Q: Can't update hosts file on mac When I try to save changes made in /etc/hosts file on mac i get this error:
"hosts" E212: Can't open file for writing
How can I update it?

A: Launch the Terminal
  $ sudo vi /etc/hosts

and after the modifications
 :wq!

A: I found the solution:
just use "sudo" before vi hosts (it will ask for administrator password). By doing this I, basically, open hosts file with Administrator privileges:
$ sudo vi hosts

and the after modifications :wq works just fine!

A: My problem was that I was running sudo vi etc/hosts instead of sudo vi /etc/hosts ¯_(ツ)_/¯


text:
Q: Calculate the probability that the circumferecnce of triangle CDE is smaller than $1+ \sqrt \frac{11}{2}$. Let page of square ABCD have length 1. On the page AB, point E is randomly selected. Calculate the probability that the circumferecnce of triangle CDE is smaller than $1+ \sqrt \frac{11}{2}$.
I have used Pythagorean theorem for pages ED and EC, and then observed case where circumference is equal to $1+ \sqrt \frac{11}{2}$, but I got to a polynomial equation of $4$th degree ( $64x^4 - 128x^3 -112x^2-16x-175=0$, where $x$ is distance between A and E) which doesn't have "easy" readable solution. Is there any better way to solve this?

A: If you denote the distance $AE=t$ it follows that $EB=1-t$. Moreover the question can be reformulate as $CE+DE<\sqrt{\frac{11}{2}}$. $CE=\sqrt{1+t^2}$ and $DE=\sqrt{1+(1-t)^2}=\sqrt{2-2t+t^2}.$
Consider equality:
$$\sqrt{2-2t+t^2}+\sqrt{1+t^2}=\sqrt{\frac{11}{2}}$$
Then, we take the square:
$$2-2t+t^2+1+t^2+2\sqrt{2-2t+t^2}\sqrt{1+t^2}=\frac{11}{2}$$
$$2\sqrt{2-2t+t^2}\sqrt{1+t^2}=-2t^2+2t+\frac{5}{2}$$
$$4(2-2t+t^2)(1+t^2)=4t^4+4t^2+\frac{25}{4}-8t^3+10t-10t^2$$
$$4t^4-8t^3+8t^2+8-8t+4t^2=4t^4+4t^2+\frac{25}{4}-8t^3+10t-10t^2$$
$$18t^2-18t+\frac{7}{4}=0$$
The equation has two symmetric solution $t_1=\frac{1}{2}-\frac{\sqrt{\frac{11}{2}}}{6}$ and $t_2=\frac{1}{2}+\frac{\sqrt{\frac{11}{2}}}{6}$. The set of point that satisfy the request has Lebesgue measure $t_2-t_1=\frac{\sqrt{\frac{11}{2}}}{3}$
If we suppose a uniform probability, the answer is $\frac{\sqrt{\frac{11}{2}}}{3}$.


text:
Q: About Build Definition file (XAML) in TFS 2010 Changes made to build definition file (XAML) takes affect ( shows in build) only when its checked in , is this a normal behavior , What I would like to make all the necessary changes build them and then check it in.

A: This is normal behaviour. TFS gets the xaml file from source control (where else could it get it from?) so you need to check in your changes to the xaml templates.

A: Check out this post, I have followed the suggestion by J.Reed.
 With that, I always know that my build script is going to work.
I consider this a de-facto best practice.


text:
Q: AWS STS credentials access permission cross account I have 3 AWS accounts. Account A has a lambda (Lambda_Account_A), Account B has a role (Role_Account_B) and Account C has a s3 bucket (S3_Account_C). The resource in account C  is configured with a bucket policy that says - Role_Account_B can access this bucket.
If the lambda in Account A assumes Account B role (Role_Account_B) and generate STS credentials, will those credentials have access to Account C resource s3 bucket?
Account B and C has been configured to trust each other.
Account A lambda code:
try {
    AssumeRoleRequest roleRequest = new AssumeRoleRequest()
            .withRoleArn(assumeRole) //arn of the role in account B
            .withPolicy(policy) // policy contains "arn:aws:s3:::my_bucket"
            .withDurationSeconds(3600)
            .withRoleSessionName(SESSION_NAME);

    // Assume the IAM role
    AssumeRoleResult assumeResult = stsClient.assumeRole(roleRequest);

    final BasicSessionCredentials temporaryCredentials = new BasicSessionCredentials(
            assumeResult.getCredentials().getAccessKeyId(),
            assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());

    return temporaryCredentials;
} catch (AWSSecurityTokenServiceException e) {}

Bucket Policy in Account C:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::account_No:role/Account_B_role"
            },
            "Action": [
                "s3:Get*",
            ],
            "Resource": "arn:aws:s3:::my_bucket/*"
        }
    ]
}

Role_B Permission policy is
{
    "Version": "2012-10-17",
    "Statement": [

        {
            "Action": [
                "s3:*"
            ],
            "Resource": "*",
            "Effect": "Allow"
        }
    ]
}

It's trust relationship has both the Account A and Account C

A: When you assume a role in another account its treated as if you're in that account.
As long as account B has the IAM permissions on this IAM role to access bucket in account C it will be able to perform those actions.
To prevent unauthorised access to certain permissions you can lockdown by using external ids which are optionally specified when you assume a role. This allows you to lockdown specific permissions in the roles IAM policy by using conditions referencing the sts:ExternalId.
More information about external ids are available in this blog post.


text:
Q: How to transfer photo sent as SMS to Photos/iPhoto.app Somebody sent me six images with SMS to my iPhone. I want to email these and get them on my Mac to use there. Short of copying them one by one into an email on my iPhone is there any way I can transfer these into Photos so that iPhoto will import them to my Mac?

A: If you visit the conversation in your iPhone/iPad in Messages, click on the 'Details' button in the upper right hand corner, scroll down to attachments, then press and hold one of the photos you'd like to transfer. Select "More" from the menu that appears.
You should then see Apple's 'Select' arrows appear in the bottom of each attachment. From there, select your photos, and share them however you'd like (email all 6 or save them to your photo app).
Hope that helps!

A: Another way:

*

*Tip on each foto and save it to your Pictures Gallery.

*Open the Photos App, select them and send them by email.

*Delete the photos afterwards.


text:
Q: Java: what is this datastruct called? I want to have something like MOTIVE { GET_PLAYER, GET_FLAG }.
And in my object, I want something like
this.motive = MOTIVE.GET_PLAYER

How can I do this?

A: Something like this perhaps?
/**
 * Don't use caps for a "class" name :)
 */
public enum Motive {
  GET_PLAYER,
  GET_FLAG;

}

or (with extra fields):
/**
 * Don't use caps for a "class" name :)
 */
public enum Motive {
  GET_PLAYER("Assessination Quest"),
  GET_FLAG("Capture the Flag PvP");

  private Motive(final String desc) {
     this.description = desc;
  }

  public String getDescription() {
    return description;
  }

  private final String description;
}

usage:
public final class MyClass {
    private Motive motive;

    public MyClass(final Motive motive) {
        this.motive = motive;
    }
}

Also consider a Motive.UNKNOWN as a default case to which you can initialize fields, so you don't get possible nulls.
And switch statements can switch on enums!
One concern: You cannot compile the enum class, compile the enum-using class, change the enum class (and compile it again) and expect it to work. enums are kind-of inlined at compile time; the compiler is allowed to use in the enum-using class hard-coded "ordinals" of the enums. Always recompile both enum classes and enum-using classes so they stay in sync,

A: You are talking about enum.

A: enum  examples & doc


text:
Q: Listview is not animating For some reason the listview is not animating, only the textviews are. I have a feeling it has to do with the LayoutInflater but I am not sure. This is where I define the JazzyListView and its animation:
public class RssFragment extends Fragment implements AdapterView.OnItemClickListener {

private ProgressBar progressBar;
private View view;
private View view2;
private JazzyListView listView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (view == null) {

        view = inflater.inflate(R.layout.fragment_layout,container, false);
        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
 listView= (JazzyListView) view.findViewById(R.id.listView);
        listView.setOnItemClickListener(this);
        startService();
    } else {

    }
    return view;
}

private void startService() {
    Intent intent = new Intent(getActivity(), RssService.class);
    intent.putExtra(RssService.RECEIVER, resultReceiver);
    getActivity().startService(intent);
}

private final ResultReceiver resultReceiver = new ResultReceiver(new Handler()) {
    @SuppressWarnings("unchecked")
    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        List<RssItem> items = (List<RssItem>) resultData.getSerializable(RssService.ITEMS);

        if (items != null) {
            RssAdapter adapter = new RssAdapter(getActivity(), items);
            listView.setAdapter(adapter);

        } else {
            Toast.makeText(getActivity(), "The RSS feed is unable to be downloaded at this time",
                    Toast.LENGTH_LONG).show();
        }

        progressBar.setVisibility(View.GONE);
        listView.setTransitionEffect(JazzyHelper.GROW);
        listView.setVisibility(View.VISIBLE);
    };
};

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    RssAdapter adapter = (RssAdapter) parent.getAdapter();
    RssItem item = (RssItem) adapter.getItem(position);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    startActivity(intent);
}
}

Here is my layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:baselineAligned="false">

 <ImageView
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:id="@+id/imageView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:background="#ff090eae"  />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="KGHS"
    android:id="@+id/button"
    android:layout_alignBottom="@+id/imageView"
    android:layout_centerHorizontal="true" />

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageButton"
    android:layout_alignBottom="@+id/imageView"
    android:layout_alignParentRight="true"
    />

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" />

<com.twotoasters.jazzylistview.JazzyListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/listView"
    android:divider="#b5b5b5"
    app:effect= "grow"
    android:dividerHeight="10dp"
    android:layout_below="@+id/searchView"
    android:layout_marginBottom="60dp"/>

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView2"
    android:layout_below="@id/imageView"
    android:layout_centerHorizontal="true" />

<SearchView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/searchView"
    android:layout_below="@+id/imageView"
     />

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="60dp"
    android:id="@+id/imageView3"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:background="#ffdedede" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="EVENTS"
    android:id="@+id/button2"
    android:layout_alignBottom="@+id/imageView3"
    android:layout_toLeftOf="@+id/button3"
    android:layout_toStartOf="@+id/button3"
    android:layout_centerHorizontal="true"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="STAFF"
    android:id="@+id/button3"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/button"
    android:layout_toEndOf="@+id/button" />

</RelativeLayout>

As I mentioned before the textviews (the textviews are in a different xml by themselves) are animating but the actual listview  is not. I already tried changing the fragment to an activity in order to rid the view/layout inflater. Not sure what else to try.
[edit 1] Is this Android SDK animation? This is an image from the JazzyListView library sample application... I was under the impression the jazzylistview animated the listview as well, otherwise what is the point???

A: Animation of JazzyListView animates its items but not itself. If you want to animate a JazzyListView, then you have to use animations provided by Android SDK, I am afraid.

A: To add an animation in ListView, you first need to define an
XML containing your animation. In my case I created a fade_in.xml.
You need to put this file in res->anim->fade_in.xml folder
/res/anim/fade_in.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />
</set>

Then, I created a class derived from BaseAdapter so that I can override the getView
function and that is where you can insert the animation code.
@Override
public View getView(int i, View view, ViewGroup viewGroup)
{
  View view = inflater.inflate(R.layout.task_item_large_one_line, null);
  ...
   Animation animation = AnimationUtils.loadAnimation(mainActivity, R.anim.fade_in);
   animation.setStartOffset(i*500);
   view.startAnimation(animation);
  return view;
}


text:
Q: FHD monitor only works after booting from other monitor and switching when running This is a weird one.. I have a FHD AGI260T 26z monitor connected with DVI-D (computer) to VGA (monitor). Computer is a Cisco VXC 6215 box running Debian, Ubuntu or whatever live usb. Problem with all these versions is the same: when booting with monitor connected, screen is blank.
But when I boot from a different external HD ready monitor (DVI-D to DVI-D) and switch the monitors when I see Linux running, the first monitor IS working. Right up until a reboot.
I've tried to set different resolutions with GRUB, but the resolution remains the same, I cannot see what it is, but it appears 1024x768
Any ideas?

A: I'll answer this myself. Turned out to be the DVI-D to VGA adapter... sjees.. bought a direct DVI-D to VGA cable off Amazon and it works without problems


text:
Q: Is there any way to get rabbitmq cluster address using CachingConnectionFactory for writing Unit Tests I have Implemented Clustering & HA with two rabbitMQ nodes.
I am trying to connect with my cluster using Spring-AMQP as below:
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setAddresses("rabbit1:5672,rabbit2:5672");

It also works fine.
Now I started writing Unit Test Cases, but I am not able to get these addresses in Test file. There are no getter methods available in spring to get these addresses (I am using Spring 4.2.1).
I tried to perform connectionFactory.getHost() also, But it is also not working.
Is there any way to get these addresses using ConnectionFactory (which I can capture in Unit Test file & assert them) ?

A: Not sure what is the problem to extract addresses as variable or even external property and use it twice: in the CachingConnectionFactory bean definition and in the test-case.
I mean something like this (e.g. application.properties):
rabitmq.addresses=rabbit1:5672,rabbit2:5672

In the @Configuration:
@Bean
CachingConnectionFactory connectionFactory(@Value("rabitmq.addresses") addresses) {
   CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
   connectionFactory.setAddresses(addresses);
   return connectionFactory;
}

And in the test-case:
@Value("rabitmq.addresses")
private String addresses;

UPDATE
In Spring AMQP tests we do like this:
@Test
public void setAddressesTwoHosts() throws Exception {
    ConnectionFactory mock = mock(com.rabbitmq.client.ConnectionFactory.class);
    CachingConnectionFactory ccf = new CachingConnectionFactory(mock);
    ccf.setAddresses("mq1,mq2");
    ccf.createConnection();
    verify(mock).newConnection(isNull(ExecutorService.class),
            aryEq(new Address[] { new Address("mq1"), new Address("mq2") }));
    verifyNoMoreInteractions(mock);
}


text:
Q: AWS Glue 3.0 PySpark: different behavior when installing dependencies using wheels vs installing same dependencies with Glue itself Having a problem launching PySpark job that utilizes connection to RedShift via awswrangler lib.
Everything works fine if using --additional-python-modules: awswrangler==2.10.0 parameter (which I suppose makes Glue to utilize pip install awswrangler==2.10.0 under the hood). But this approach is restricted because we're using company's artifactory as dependency repo.
However, if I set awsrangler wheel (and it's connected dependencies as a wheels) using Glue's 'Python libraries path', I'm getting redshift connection error (NotADirectoryError, which caused by ssl settings presumably). The question is why behavior is different?
The list of wheels I'm getting by 'pip freeze' after awswrangler installation on clear virtual env.
Will be appreciated to any clues\ideas.
Upd: the second question is: can custom artifacts repo be set for pulling dependencies by Glue?


text:
Q: Unexpected distingration energy value during alpha decay equation I am trying to solve the disintgration value of the below decay equation but the issue I am having is my result seems way to high compared to what is expected (around 5-6 MeV).
$$^{213}At  \rightarrow \vphantom{Bi}^{209}Bi + \vphantom{\alpha}^4\alpha + Q$$
My Math as follows:
$$Q = (m_{At} - (m_{Bi} + m_{α} )) * C^2$$
$$Q = (212.992937 - (4.001506179127 + 208.9803987)) * 2997924582$$
$$Q = 9.914739 * 10^{14}$$
to get in MeV:
$$Q = ((212.992936514 - (4.001506179127 + 208.9803987)) * 2997924582) * (1.66054 * 10^{-27}) * (6.242 * 10^{12})$$
$$Q = 10.2767168514 MeV$$
This value of 10 seems to be double what I am expecting and I do not know why.
I would also note I just made this equation myself rather than from any textbook just for my own understanding but I believe the decay parent and children are accurate based on research.
Inputting other mass values such as Thorium and Uranium work to get around 5 MeV so I know my method is correct but I feel like I am missing something theoretical or in my calculation, any insight would be appreciated.

A: *

*Why do you expect around 5 MeV?  My 16th edition of the Chart of the Nuclides lists 9.08 MeV as the decay energy

*I believe that there is a slight math error (about 1MeV)
The actual reaction starts with 85 orbital electrons on the astatine atom.
The actual products have the same 85 electrons on the actual daughter isotope Bismuth atom and none in the alpha-particle.
BUT..
The tabulated mass for the astatine atoms is for the neutral atom, including the 85 orbital atoms. So far, so good.
The tabulated value for the bismuth isotope is again for the neutral $83$ electron atom.  To get figures for the actual daughter isotope mass, you would need to include two more electron masses.
If you use the mass of a neutral helium-4 atom instead of the mass of a helim-4 nucleus, everything would take care of itself.
Look at it this way: The daughter isotope keeps 83 of its electrons, and dumps two on the alpha particle, so you should use the the tabulated values for the isotopes, and the He-4 mass for the alpha particle.
EDIT:
Apply the electron count correction to your calculation and you should hit the value of @jon custer exactly...


text:
Q: Given W is a solution space for Ax=0 and dim(w) is 3 find rank(A) Given W is a solution space for Ax=0 and A is a 4x4 matrix and Dim(W)=3 determine the rank of A?
Isn't it just 3? It seems too simple if that's the case

A: Use the Rank-Nullity Theorem. Namely $\text{dim}(V) = \text{dim}(N(A)) + \text{dim}(R(A)) $. Where $V$ is the whole space, $R(A) $ is the range of the mapping $A$  and $N(A) $ is the kern of $A$ i.e. solution space of $Ax=0$. So $N(A) =W$.  Since $A$ is 4 by 4 matrix $\text{dim} (V) =4$. A simple calculation gives us $\text{dim}(R(A)) = 1$. The dimension of the range of $A$ is the same as the rank of $A$ so it is $1$.


text:
Q: Does DbUnit support sequences in inserts using Hibernate? I have integrated DbUnit into my app which uses Hibernate and Oracle SQL; I created the datamodel as tables only however sequence creation failed:
create sequence CARS_LOGIN_SEQ
minvalue 1
maxvalue 999999999999999999999999999
start with 1
increment by 1;

I couldn't believe it; no problem, I skipped the sequences, and selects work, however when my app comes to insert a row in the test case, it fails!
Here's my use of the sequence in the hibernate XML file:
<id name="id" column="PARTY_ID">
    <generator class="sequence">
        <param name="sequence">cars_party_seq</param>
    </generator>
</id>

What does this mean, if my code uses sequences, then I can't use DbUnit?
Note I'm using DbUnit 2.4.8, but could upgrade if needed.

A: OK so it turns out sequences are supported, which makes sense.
However, the sequence creation SQL should be simply like this (if you don't want to start with 0):

create sequence CARS_LOGIN_SEQ start with 5;


text:
Q: connecting two table with id I need to create two tables programmatically with c# and those tables will have some columns and one of them is the on ID. The ID needs to be a counter that starts at 1 and always adds 1 for each row and that ID must be foreign key on the second table. How can I do it? I've already searched on internet but didnt found antything conclusive.

A: You have to create a table A that has a relation to another table B.
So in table B will be a column with foreign key pointing to the ID of table A.
Table A
  ID          Column1     Column1  . . .
   1          name1       value1
   2          nam2        value2

Table B
  ID          Column1    Column2   table_A_id  . . .
   1          name1      value1       1
   2          name2      value1       1
   3          name3      value1       2

A: public class DataStack1
{
    [System.ComponentModel.DataAnnotations.Key]
    public int id { get; set; }
    public string somedata { get; set; }
}
public class DataStack2
{
    [System.ComponentModel.DataAnnotations.Key]
    public int id { get; set; }
    public int DataStack1id { get; set; }
    public DataStack1 DataStack1 { get; set; }
    public string somedata { get; set; }
}

When you create their DBSets, Entity Framework will recognize this relation.
To create their DBSets, use the following code:
public class DataContext : DbContext
{
    public DbSet<DataStack1> DataStack1 { get; set; }
    public DbSet<DataStack2> DataStack2 { get; set; }
}

Use the following code to access your tables:
using (var dataset = new DataContext())
{
    var Data = dataset.DataStack1.ToList();
}

You can add the following connection string to your App.config file:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data.mdf;Initial Catalog=Data-Project;Integrated Security=True" providerName="System.Data.SqlClient" />  </connectionStrings>

A: DataTable table1 =new DataTable();
DataColumn autoIncrement=new DataColumn("AutoIncrement",typeof(System.Int32));
table1.Columns.Add(autoIncrement);
autoIncrement.AutoIncrement=true;
autoIncrement.AutoIncrementSeed=1;
autoIncrement.ReadOnly =true;

DataTable dtEmployee = getEmployeeRecords();
DataTable dtDepartment = getDepartmentRecords();

DataColumn obj_ParentDepartmentID, obj_ChildDepartmentID;
DataSet ds = new DataSet();
ds.Tables.Add(dtDepartment);
ds.Tables.Add(dtEmployee);
obj_ParentDepartmentID = ds.Tables["Department"].Columns["DeptID"];
obj_ChildDepartmentID = ds.Tables["Employee"].Columns["DeptID"];

dtEmployee.Columns.Add("DepartmentName");
DataRelation obj_DataRelation = new DataRelation("dept_reln", obj_ParentDepartmentID, obj_ChildDepartmentID);
ds.Relations.Add(obj_DataRelation);

foreach (DataRow dr_Employee in ds.Tables["Employee"].Rows)
{

DataRow dr_Department = dr_Employee.GetParentRow(obj_DataRelation);
dr_Employee["DepartmentName"] = dr_Department["DeptName"];

}
DataTable dtResult = ds.Tables["Employee"].DefaultView.ToTable(false, "EmployeeID", "EmployeeName", "FatherName", "DepartmentName");


text:
Q: Dependent and independent vectors. The  indexed family  $u_{1},u_{2}$ where $u_{1}=u_{2}  \neq \vec{0}$ are  linearly dependent ( because $u_{1}$ and $u_{2}$ are collinear) and  linearly independent at the same time ! we have  $\alpha _{1}u_{1} +\alpha_{2}u_{2}=(\alpha_{1}+\alpha_{2})u_{2}=\alpha u_{2}=\vec{0} \Rightarrow  \alpha=0$
what's wrong?I know that this impossible but I can't find the flaw.help!

A: $(\alpha_1,\alpha_2)=(1,-1)$ gives $u-v=0$, which is one possible non-trivial linear relation. So a vector is not linearly independent from itself.

Note that it is somewhat common for textbooks to define linear (in)dependence for sets of vectors -- what they really should be talking about here is indexed families of vectors. If you're restricting yourself to sets, then you can't even speak about whether $v$ and $u$ are linearly independent when $v=u$, because then $\{v,u\}=\{v,v\}=\{v\}$. With an indexed family this problem goes away.
In the case of finitely many vectors we can speak of simply ordered tuples of vectors rather than indexed families. This is usually -- more or less implicitly -- the case when we're speaking about bases.


text:
Q: Setting environment variables for Sublime Text on OSX desktop I'd like to be able to access my JAVA_HOME variable that has been set in my .bash_profile from within my sublime text build. When I build I get the following error.
Error: JAVA_HOME is not defined correctly.
  We cannot execute ....
This is obviously because ST2 doesn't read in my bash profile. Is there any hack around for this?
Thanks!

A: On UNIX child processes inherit the environment of the parent process. In this case, Sublime Text is not launched through a process chain which would include bash shell which in turn is reading its profile file.
.bash_profile is usually executed on shell login. Depending on your operating system it is not executed when you enter to your desktop environment. Thus, the environment variables are not avaiable.
Workarounds

*

*Put environment variables to a file which is read on the computer boot always (no idea which file unless you tell your operating system) (e.g. lanchd.conf for OSX GUI applications or /etc/profile on Linux)

*Modify your dekstop launcher icon

*Put hardcoded paths to your build file

*Launch Sublime Text using subl alias from your bash shell instead of desktop icon
More about .bash_profile and .bashrc


text:
Q: How to put stuff in a hash map and use new instances with the same value of fields to get the corresponding value I am developing an android app to help little kids learn maths. It will display some questions and the user can answer them. At the start page there would be some options to choose from. For example, the number of digits and the operation type (i.e. +, -, *, +/-) and whether the timer is enabled. So I created a QuestionOptions class.
public class QuestionOptions implements Parcelable{
    protected QuestionOptions(Parcel in) {
        digitCount = in.readInt ();
    }

    public static final Creator<QuestionOptions> CREATOR = new Creator<QuestionOptions> () {
        @Override
        public QuestionOptions createFromParcel(Parcel in) {
            return new QuestionOptions (in);
        }

        @Override
        public QuestionOptions[] newArray(int size) {
            return new QuestionOptions[size];
        }
    };

    public QuestionOptions (OperationType operationType, int digitCount, boolean timerEnabled) {
        this.operationType = operationType;
        this.digitCount = digitCount;
        this.timerEnabled = timerEnabled;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeParcelable (this, flags);
    }

    public enum OperationType {
        ADDITION,
        SUBTRACTION,
        ADD_AND_SUB,
        MULTIPLICATION
    }

    public boolean isTimerEnabled() {
        return timerEnabled;
    }

    public void setTimerEnabled(boolean timerEnabled) {
        this.timerEnabled = timerEnabled;
    }

    public OperationType getOperationType() {
        return operationType;
    }

    public void setOperationType(OperationType operationType) {
        this.operationType = operationType;
    }

    public int getDigitCount() {
        return digitCount;
    }

    public void setDigitCount(int digitCount) {
        this.digitCount = digitCount;
    }

    private OperationType operationType;
    private int digitCount;
    private boolean timerEnabled;
}

Note that I implement Parcelable because I want to send it to another activity.
So far so good. But then I want to add a feature to give prizes to the user. Now I found some pictures online to be the trophies and stuff. Here's how i want them to work: For each possible question option, there is a different prize. After some calculations, I found out there are 22 possible question options! So I decided to use a hashmap to store the possible question options (key) and the resource id of the pictures of the trophies (value).
Because this is the first time I use a hash map, I did some experiments with it and soon found out that I can't use it.
The HashMap.get method compares the references of the question options not the fields inside it. Here is my test:
HashMap<QuestionOptions, Integer> map = new HashMap<> ();
map.put(new QuestionOptions (QuestionOptions.OperationType.ADDITION,
            1, false), 0);
map.put(new QuestionOptions (QuestionOptions.OperationType.ADDITION,
            2, false), 1);
map.put(new QuestionOptions (QuestionOptions.OperationType.ADDITION,
            3, false), 2);
System.out.println (map.get(
            new QuestionOptions(QuestionOptions.OperationType.ADDITION,
            1, false)));

And it prints "null"...
After all that reading, you guys must be asleep... I just want to ask:
How to put all the possible question options in a hash map and use new instances to get them out or is there another way to achieve the requirement? If yes, how?

A: You need to implement hashcode() and equals() methods of QuestionOptions. As you said

The HashMap.get method compares the references.

That's the default implemetnation of hashCode() method which is used by the HashMap to compare the keys
You can read more about hashCode and equals method here


text:
Q: How can I get the exit code or exit status after finish a robotium test on the command line Now I wrote a batch script to run the command like:
adb -s emulator-5556 shell am instrument -e class com.example.test.locationListTest -w com.example.test/android.test.InstrumentationTestRun

Then at the console I get results like FAILURE!!! Tests run: 5 fail:4 or OK.
I use if errorlevel 0 to determine the upper command, but it gives me 0 no matter the upper command gives me,  OK or FAILURE.
I need to do this in batch script like this:
if(adb -s emulator-5556 shell ..... test.InstrumentationTestRun == SUCCESS )
do (.........)
else (.........)

A: Try this:
@echo off
setlocal

set "adb=adb -s emulator-5556 shell am instrument -e class com.example.test.locationListTest -w com.example.test/android.test.InstrumentationTestRun"
for /f "tokens=*" %%a in ('%adb%^|find /i "Ok"') do (
  if not errorlevel 1 (
         Echo Success
  ) else (
         echo Failure
  )
)

This way, errorlevel will work because it's coming from Find.

A: if errorlevel 0 is always true.
You need to use if not errorlevel 1 when you use that style of line for testing.

A: What about something simple, like:
adb -s emulator-5556 shell am instrument -e class com.example.test.locationListTest -w com.example.test/android.test.InstrumentationTestRun | grep "Failures"
if [ $? -eq 0 ]; then
    echo "## TEST FAILED ##"
    exit 1
fi

A: Rather than doing it via adb you can instead run your instumentation tests with gradle.
Here is an example bash script to do this:
#!/bin/bash
CMD="./gradlew connectedAndroidTest"
$CMD
RESULT=$?
if [ $RESULT -ne 0 ]; then
 echo "failed $CMD"
 exit 1
fi
exit 0


text:
Q: NetBeans not seeing javax I have a servlet & a class sitting in the same package on a NetBeans web project.
(these class locations are for example only--
this is nowhere near my ideal organization of classes.)
In the servlet, everything is alright-- it is seeing javax and whatever i'm looking for in it.
However, in the plain java class, it's not even recognizing the imports-- giving me "Package javax.* does not exist" let alone fixing the imports itself.
What's missing here?
EDIT: I've seen java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong? along with some other discussions.

A: Added the javax.mail jars to the project lib.
Netbeans must be using the libraries depending on the type of the project and the classes


text:
Q: How to replace the text in an HandleBar template I would like to replace the text within a template but when I use 'replaceWith' I get an error.
http://jsfiddle.net/gdiamond/52g8x/1/
I have a list of days and each time a click on one I want to replace the text.

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

Sunday

the javascript

A: I have updated my function modèle.
if li's size is greater than 1 than remove the li's elements.
function modele(data){
    //console.log(data);
    var template = Handlebars.compile( $('#template').html() );
    var temp = template(data);

    /* UPDATE */
    var ul = $("ul.dayofweek");
    var lis = ul.children().size();
    //console.log(lis);

    //if li.length is greater than 1 so remove all elements
    if (lis > 1){
        $("ul.dayofweek li").remove();
    }
    $('ul.dayofweek').append(temp);
}


text:
Q: Magento 2 Invalid template file I am trying to override sales_order_create_index.xml to remove the custom payment method but getting this error
1 exception(s): Exception #0 (Magento\Framework\Exception\ValidatorException): Invalid template file: 'Custom_Module:order/create/billing/method/info.phtml' in module: 'Magento_Sales' block's name: 'order_create_billing_form'
sales_order_create_index.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="order_create_billing_form">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">Custom_Module::order/create/billing/method/info.phtml</argument>
            </action>
        </referenceBlock>
    </body>
</page>

Template Path:

A: Your file name is form.phtml and you have set template name info.phtml. So either update your file name to info.phtml or update template name in xml file to form.phtml and clean cache once.


text:
Q: Ajax.BeginFrom Not refresh IE I have a form in a MVC4 website using
@using (Ajax.BeginForm("Action","Controller", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "Results", OnSuccess = "OnSuccess" }))
{
   HTML....
}

In the same page my script:
function OnSuccess() {
         alert("Ok");
         Do More things...
    }

Everything works fine (Chrome, FF ...) not in IE (I'm using IE10). The script works and display the alert, but the content is not being rendered. If I click on the page then IE refresh it and shows the content.
Any ideas?
Thanks in advance!

A: Just change the insertionMode to InsertAfter and it is working now


text:
Q: Nativescript application crashes with "Encountered undefined provider!" before module loaded on IOS but works on Android I am using nativescript  5.1.1 with android version 5.1.0 and ios version 5.1.1. When the application starts on ios it immediately crashes with the following error:
JavaScript stack trace:
1   _reportError@file:///app/tns_modules/@angular/compiler/bundles/compiler.umd.js:19223:31
2   @file:///app/tns_modules/@angular/compiler/bundles/compiler.umd.js:19072:43
3   forEach@[native code]
4   _getProvidersMetadata@file:///app/tns_modules/@angular/compiler/bundles/compiler.umd.js:19057:30
5   getNgModuleMetadata@file:///app/tns_modules/@angular/compiler/bundles/compiler.umd.js:18776:84
6   _loadModules@file:///app/tns_modules/@angular/compiler/bundles/compiler.umd.js:26060:74
7   _compileModuleAndComponents@file:///app/tns_modules/@angular/compiler/bundles/compiler.umd.js:26041:52
8   compileModuleAsync@file:///app/tns_modules/@angular/compiler/bundles/compiler.umd.js:26001:68
9   bootstrapModule@file:///app/tns_modules/@angular/core/bundles/core.umd.js:17836:42
10  _bootstrapper@file:///app/tns_modules/nativescript-angular/platform-common.js:87:50
11  @file:///app/tns_modules/nativescript-angular/platform-common.js:150:32
12  notify@file:///app/tns_modules/tns-core-modules/data/observable/o<…>
JavaScript error:
file:///app/tns_modules/@angular/compiler/bundles/compiler.umd.js:19223:31: JS ERROR Error: Encountered undefined provider! Usually this means you have a circular dependencies. This might be caused by using 'barrel' index.ts files.
Additionally when looking at the console from the device i see this.
[19-02-08 11:56:23.932] (CLI) (node:39256) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'pipe' of undefined
    at WebSocketServer.server.on (/usr/local/lib/node_modules/nativescript/lib/device-sockets/ios/app-debug-socket-proxy-factory.js:124:32)
    at WebSocketServer.emit (events.js:182:13)
    at handleUpgrade (/usr/local/lib/node_modules/nativescript/node_modules/ws/lib/websocket-server.js:79:18)
    at WebSocketServer.completeUpgrade (/usr/local/lib/node_modules/nativescript/node_modules/ws/lib/websocket-server.js:293:5)
    at options.verifyClient (/usr/local/lib/node_modules/nativescript/node_modules/ws/lib/websocket-server.js:210:16)
This doesn't seem to be in my module because it runs properly in Android.
I'm mainly looking for some help in debugging the issue. I don't have any way to debug the dynamic code being pushed to the emulator or phone.

A: What are the versions of the following packages:
 nativescript-angular, nativescript-dev-webpack and angular?
You mentioned you updated nativescript but maybe you should update the above mentioned packages as well.

A: I figured it out. There was an import of the AndroidApplication class without a platform check. The error that was thrown was just not great. If someone else comes across this perhaps that will help.


text:
Q: What is a mapping type for Object[] from java to c++ in calling function? What is a mapping type for Object[] from Java to C++ when calling Java function from C++? The Java function has parameter Object[].
I know for string it's java/lang/String; but for Object[] (jobjectarray) cannot find.

A: It's [Ljava/lang/Object;. The [ denotes an array of the following type.


text:
Q: What is the best method for saving a lot of objects states? I am currently integrating serialization into a Unity3D game, where I need to store up to thousands of game object positions to file as the user will be placing them down themselves. This will be done on mobile and saving an entire scene during play will hang the processor way too long.
What is the best method for saving the game state?

*

*Save each objects position when it is changed

*Save all objects when the application is quit or paused

How should I save the objects?

*

*Each as an individual file for faster saving (and include a manager
class that maintains reference to the serialized files names)

*An entire hierarchy with all objects at a time for simplicities sake
which will hang the processor when saving

Also should I keep a memory stream open the entire game, or only open it when an object is saved?


text:
Q: cellForRowAtIndexPath is never called I have a storyboard which contains UIViewController which has UITableview and UITableViewCell, everything is hooked up properly and I have put all the required code for UIViewController.
When I run the app in the simulator one of the datasource function cellForRowAtIndexPath is never called but numberOfRowsInSection is called

*

*"func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int" is called

*But "func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell" IS NEVER CALLED
Below is my code for view controller:
import UIKit

class DVViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{

    @IBOutlet var tableView : UITableView?
    var tableData = ["Row 1", "Row 2", "Row 3"]
    let kCellID = "cell"

    override func viewDidLoad()
    {
        super.viewDidLoad()

        self.tableView?.delegate = self;
        self.tableView?.dataSource = self;

        //load cell
        self.tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: kCellID);
        self.tableView?.reloadData();
    }

    //MARK: Tableview delegates
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return self.tableData.count;
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
       //var cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: kCellID)
        let cell : UITableViewCell = UITableViewCell (style: UITableViewCellStyle.Default, reuseIdentifier: kCellID);
        return cell;
    }
}

Can someone suggest why cellForRowAtIndexPath is never called?

A: Here is what I did, uninstalled Xcode 5 & 6 both the  reinstalled Xcode 6 only, Ran the project and it WORKED. After 2 days of debugging its the reinstall which did the trick.

A: I have just checked your code, it works.
Check to see whether or not numberOfRowsInSection is called. if not check the connection in storyboard.

A: Try this:
class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
func viewDidLoad(){
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
}


text:
Q: SPF and DMARC - how is the SPF policy used My domain has a strict DMARC policy (p=reject) and a standard SPF policy with ~all catchall.
My email provider is Google Workspace.
I received an email spoofing my sender address. It came from 41.174.75.34 - a Zambian IP address which is blacklisted in a few spam databases. Gmail did flag the email as spam. Running the headers through Google's Messageheader analyzer I get the following verdict:

*

*SPF: softfail

*DMARC: fail

My understanding from some online documentation and this question or this question is that this email should have been completely rejected because it failed DKIM and the source IP was not in the allowed SPF range. I did not expect it to make it to my mailbox at all, even if it did get flagged as spam.
What is the correct DMARC and SPF configuration to reject spoofed emails, considering the example I witnessed? Ideally, please provide references for your answer.
Update 1
Here are the values of the relevant DNS records for reference:
DMARC record
v=DMARC1; p=reject; rua=mailto:<redacted>; ruf=mailto:<redacted>; fo=1

SPF record
v=spf1 include:_spf.google.com include:_spf.salesforce.com include:<redacted> ~all

Update 2
Here are the full mail headers with minor redactions:
Delivered-To: <user-redacted>@<domain-redacted>
Received: by 2002:a05:6214:aaa:0:0:0:0 with SMTP id ew10csp427451qvb;
        Thu, 25 Feb 2021 07:46:07 -0800 (PST)
X-Google-Smtp-Source: ABdhPJxFPuLVmXBoRU+vQaU0r38lcka6Mby1RlA787SCOD8Rb7QkX5EOXGpiMC/Tenm4pXpACNBR
X-Received: by 2002:a62:68c5:0:b029:1ee:863:8c55 with SMTP id d188-20020a6268c50000b02901ee08638c55mr3732841pfc.37.1614267967132;
        Thu, 25 Feb 2021 07:46:07 -0800 (PST)
ARC-Seal: i=1; a=rsa-sha256; t=1614267967; cv=none;
        d=google.com; s=arc-20160816;
        b=wFGGZzBJaDIOxatWEKE7LE2TBMVhqNpktIexiXikL9SJWCMTxvXV7EAooox3TKoWI2
         JpquJ/v+fsFHvHGp/AaFghBTQcvEv9MDRPtdDKDX1zulGa2vGF5P4pE8EVcPrCZ7OEZ6
         hjky81yTDLBMnowYRefHs9/UhjkrrS944a/HnLJeYN2E/UEQW7a0YjXjmFRo87g9l35g
         fBml7hP9NFmW9ZECvOU6K/cXYr/W/Fl/53X6t+kfFbschLf3/NoB0KvIi8cBA+9NiXtF
         p12/7MjR2M4gd9gqYqGzpYyfZ2FK2T/3fgJFNa07CQldfLW8qkGNBJJIFAG0boPQlEs1
         enJQ==
ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816;
        h=importance:mime-version:date:subject:to:from:message-id;
        bh=1beLMfc/QIXWzdWj0auhMhJreQONuvV9O2Srp9s2OQY=;
        b=u/KHc8DIEQxX0NzfQWqE8d/wu3hGQR0UHANF4dZZjSpAKgrVeAki+WYNaXdk3s5owS
         82yew5mZcS6PJ9b3k8LnjXX1gALocBFqZcn23FbnxFoIT/9WQdYWya/dqYI42nDLByB7
         5O/c4f9tKwZjF3VDHLAVg97P6hSPhCWrIhElqIjev60huc6jm/+FjPgBq1Umpbjv1720
         hZbi95+vetbIkPZMmhXw6iOwiB/YG3RDhhUyLwCnJhr8ixf3dg3MwgCMgqHb+ky/wn5b
         x0F4D4PHZ+3MCuIFPMkMR1kvhUFPidY6RRzjL72nWGVGJ1NbQs+aVgviVTqBJKWCGxI9
         fhBQ==
ARC-Authentication-Results: i=1; mx.google.com;
       spf=softfail (google.com: domain of transitioning <user-redacted>@<domain-redacted> does not designate 41.174.75.34 as permitted sender) smtp.mailfrom=<user-redacted>@<domain-redacted>;
       dmarc=fail (p=REJECT sp=REJECT dis=REJECT) header.from=<domain-redacted>
Return-Path: <<user-redacted>@<domain-redacted>>
Received: from [41.174.75.34] ([41.174.75.34])
        by mx.google.com with ESMTP id p11si6119467plo.125.2021.02.25.07.46.00
        for <<user-redacted>@<domain-redacted>>;
        Thu, 25 Feb 2021 07:46:07 -0800 (PST)
Received-SPF: softfail (google.com: domain of transitioning <user-redacted>@<domain-redacted> does not designate 41.174.75.34 as permitted sender) client-ip=41.174.75.34;
Authentication-Results: mx.google.com;
       spf=softfail (google.com: domain of transitioning <user-redacted>@<domain-redacted> does not designate 41.174.75.34 as permitted sender) smtp.mailfrom=<user-redacted>@<domain-redacted>;
       dmarc=fail (p=REJECT sp=REJECT dis=REJECT) header.from=<domain-redacted>
Message-ID: <20644A25380E0B57133D524F797C2064@8AIF179>
From: <<user-redacted>@<domain-redacted>>
To: <<user-redacted>@<domain-redacted>>
Subject: 情報リクエストに関する個人的な
Date: 26 Feb 2021 04:37:43 +0100
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="----=_NextPart_000_003F_01D70BF1.06CD2753"
X-Priority: 3
X-MSMail-Priority: Normal
Importance: Normal
X-Mailer: Microsoft Windows Live Mail 16.4.3505.912
X-MimeOLE: Produced By Microsoft MimeOLE V16.4.3505.912

Update 3
Here is the rua report - this is the only report which mentions the offending 41.174.75.34 IP address. I cut out the irrelevant <record> entries. The softfail is right there, but the question is why?
<?xml version="1.0" encoding="UTF-8" ?>
<feedback>
  <report_metadata>
    <org_name>google.com</org_name>
    <email>noreply-dmarc-support@google.com</email>
    <extra_contact_info>https://support.google.com/a/answer/2466580</extra_contact_info>
    <report_id>...redacted...</report_id>
    <date_range>
      <begin>1614211200</begin>
      <end>1614297599</end>
    </date_range>
  </report_metadata>
  <policy_published>
    <domain>...redacted...</domain>
    <adkim>r</adkim>
    <aspf>r</aspf>

reject

    <sp>reject</sp>
    <pct>100</pct>
  </policy_published>
... redacted multiple <record> entries ...
  <record>
    <row>
      <source_ip>41.174.75.34</source_ip>
      <count>7</count>
      <policy_evaluated>
        <disposition>reject</disposition>
        <dkim>fail</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>...redacted...</header_from>
    </identifiers>
    <auth_results>
      <spf>
        <domain>...redacted...</domain>
        <result>softfail</result>
      </spf>
    </auth_results>
  </record>
... redacted multiple <record> entries ...
</feedback>

A: So, aspf=s means it should be strict on SPF matching, which means you need -all and not ~all
adkim=s means it should be strict on DKIM matching, which means it provided a DKIM signing key going out, and the public component of that DKIM keypair matched a public DNS record for which it was meant to pair up with.
The above two settings are part of the DMARC record.
Your current aspf and adkim settings are r (relaxed).
Looking at the headers it seems the sender delivered the email to mx.google.com which I would imagine is within _spf.google.com coverage, so I think ultimately you will need to set strict dkim alignment, since the idea is that ultimately that user will need to send emails with a signing key for your domain, instead of just easily sending from Google's IP ranges.
Feel free to sign up with an email provider that offer authenticated smtp for sending emails remotely via Gmail over SMTP/SMTPS to test this out, maybe use it to email a testing email from www.mail-tester.com and analyze the results.
Some links for you:
https://mxtoolbox.com/dmarc/details/dmarc-tags/aspf
https://mxtoolbox.com/dmarc/details/dmarc-tags/adkim
https://www.dmarcanalyzer.com/dmarc/dmarc-record-setup-guides/google-g-suite-dmarc-setup-guide/
https://support.google.com/a/answer/2466563?hl=en
https://mha.azurewebsites.net/


text:
Q: What does amsmath do to \@currentlabel? Can someone explain what amsmath does to \@currentlabel in the align environments?
Better yet: if I want to write what would be expected to be the \@currentlabel together with some other information into an auxiliary output file, what's the best way to access that information in the align environments?
\documentclass{article}
\usepackage{amsmath}

\makeatletter
\newcommand\storelabel[1]{%
    \xdef#1{\@currentlabel}}
\makeatother

\begin{document}

\begin{equation}
    A = B  \storelabel{\firstone}
\end{equation}
Now
\begin{align}
    C &= D \storelabel{\secondone}\\
    C' &= D' \storelabel{\thirdone}
\end{align}
\begin{equation}
    E = F \storelabel{\fourthone}
\end{equation}
The counters are \firstone, \secondone, \thirdone, \fourthone.
\end{document}

A: The behaviour of \refstepcounter in equation and align (for example) is different in the sense that

*

*in equation the \incr@eqnum command (a wrapper for \refstepcounter etc.) is used right at the start of the environment, so \storelabel can access \@currentlabel

*in align however, the \storelabel command is used before the tag is set, i.e. \@currentlabel is just empty at that time of usage.

Either the \make@display@tag command is patched or shortly redefined where the shifted definition of \xdef...{\@currentlabel} is used after \incr@eqnum.
The \storelabel command is actually a fake command now, just defining the next name to be set, but the true definition of the macro name is done later on.

\documentclass{article}
\usepackage{amsmath}

\makeatletter

\usepackage{etoolbox}

\newcommand{\extractstoretag}{%
  \@ifundefined{nextstoretag}{%
  }{%
    \expandafter\xdef\csname \nextstoretag\endcsname{\@currentlabel}
    \let\nextstoretag\relax
  }%
}
\AtEndEnvironment{equation}{%
  \extractstoretag%
}

\def\make@display@tag{%
  \if@eqnsw \incr@eqnum \extractstoretag \print@eqnum
  \else \iftag@ \df@tag \global\let\df@tag\@empty \fi
  \fi
  \ifmeasuring@
  \else
    \ifx\df@label\@empty
    \else
      \@xp\ltx@label\@xp{\df@label}%
      \global\let\df@label\@empty
    \fi
  \fi
}

\newcommand\storelabel[1]{%
  \xdef\nextstoretag{#1}%
}%
\makeatother

\begin{document}
\begin{equation}
    A = B  \storelabel{firstone}
  \end{equation}
  Now
\begin{align}
    C  &= D   \storelabel{secondone} \\
    C' &= D'  \storelabel{thirdone}
\end{align}
\begin{equation}
    E = F \storelabel{fourthone}
\end{equation}
The counters are \firstone, \secondone, \thirdone,\fourthone.
\end{document}

Here's the version with \..... macros in the \storelabel command:
\documentclass{article}
\usepackage{amsmath}

\usepackage{etoolbox}

\makeatletter

\newcommand{\extractstoretag}{%
  \@ifundefined{nextstoretag}{%
    \relax%
  }{%
    \expandafter\xdef\csname \nextstoretag\endcsname{\@currentlabel}
    \let\nextstoretag\relax
  }%
}
\AtEndEnvironment{equation}{%
  \extractstoretag%
}

\def\make@display@tag{%
  \if@eqnsw \incr@eqnum \extractstoretag \print@eqnum
  \else \iftag@ \df@tag \global\let\df@tag\@empty \fi
  \fi
  \ifmeasuring@
  \else
    \ifx\df@label\@empty
    \else
      \@xp\ltx@label\@xp{\df@label}%
      \global\let\df@label\@empty
    \fi
  \fi
}

\newcommand{\storelabel}[1]{%
    \xdef\nextstoretag{\expandafter\@gobble\string#1}%
  }%
\makeatother

\begin{document}
\begin{equation}
    A = B  \storelabel{\firstone}
  \end{equation}

  \begin{align}
    C  &= D   \storelabel{\secondone} \\
    C' &= D'  \storelabel{\thirdone}
  \end{align}
  \begin{equation}
    E = F \storelabel{\fourthone}
\end{equation}

The counters are \firstone, \secondone, \thirdone\ and \fourthone.
\end{document}

Update/Edit
Apparently, another solution to get the 'real' content what is written to the .aux file can be achieved by using the \getrefnumber from the package refcount by Heiko Oberdiek.

A: From the amsmath documentation (section 15.2 Implementing tags and labels, p 39):

Sometimes it is necessary for a \tag command to store a tag in a safe place
  and to process it later, e.g., for a tag in a row of an alignment where the tag
  can only be typeset when the \\ at the end of the row was seen. Such a tag is
  stored in the macro \df@tag (for 'deferred tag'). For this purpose we provide
  the \make@df@tag macro. It is built very similar to the \maketag@@ macro [..].
\let\df@tag\@empty
\def\make@df@tag{\@ifstar\make@df@tag@@\make@df@tag@@@}

\make@df@tag sets \@currentlabel and defines \df@tag appropriately.
To simplify the task of tracking \tag and \label commands inside math display
  environments, we defer \label commands until the tag is typeset, similar
  to the way that \tags themselves are deferred. This allows arbitrary placement
  of \label and \tag commands and also means we only increment the \equation
  counter when we really need to, thus avoiding the \setb@ck nonsense that used
  to be required.
\def\make@df@tag@@#1{%
  \gdef\df@tag{\maketag@@@{#1}\def\@currentlabel{#1}}}

Autogenerated number:
\def\make@df@tag@@@#1{\gdef\df@tag{\tagform@{#1}%
  \toks@\@xp{\p@equation{#1}}\edef\@currentlabel{\the\toks@}}}

The crucial part of the above discussion is the mention that within a display, amsmath takes control of the \label and \tag, deferring the former until the tag has been set. It allows for ease-of-use from a user's perspective*.
So you will either have to tap into the setting of the tag in order to extract the correct \@currentlabel, or you'll have to stick to using a \label-\ref system. refcount is another option for extracting the reference in an expandable way, still using a \label-\ref-like setup:

\documentclass{article}

\usepackage{amsmath,refcount}

\begin{document}

\begin{equation}
  A = B  \label{firstone}
\end{equation}
Now
\begin{align}
  C &= D \label{secondone} \\
  C' &= D' \label{thirdone}
\end{align}
\begin{equation}
  E = F \label{fourthone}
\end{equation}
The counters are \getrefnumber{firstone}, \getrefnumber{secondone}, \getrefnumber{thirdone}, \getrefnumber{fourthone}.

\end{document}

*In an analogous (yet opposite) way there's no control over the placement of the \caption inside a float - it's set inline with the placement. As such, the user has to make sure that \label comes after the \caption; amsmath tries to accommodate the user by allowing them to place \label wherever inside the display - before or after the \tag even without a \tag.


text:
Q: Remove listener from Firebase when having multiple listeners on the same reference I needed to listen to a reference on firebase realtime database that will be updated very often, so I tried to encapsulate the listeners in a component in a way that, if the components were not viewable by the user, the listeners would be turned off.
I created a high order component to avoid leaking listeners that looks like this:
const FirebaseListener = (WrappedComponent) => {
    return class extends Component {
        state = {
            ref: null,
            data: {},
        }

        componentDidMount() {
            const { device } = this.props;

            const ref = repository.listenDevice(device.id);
            ref.once('value').then((snapshot) => {
                const data = snapshot.val();
                this.setState({ data });
            });

            ref.on('child_changed', (snapshot) => {
                const value = snapshot.val();
                const prop = snapshot.key;
                const { data } = this.state;
                this.setState({ data: { ...data, [prop]: value } });
            });
            this.setState({ ref });
        }

        componentWillUnmount() {
            const { ref } = this.state;
            if (ref !== null) {
                ref.off();
            }
        }

        render() {
            const { data } = this.state;
            return (
                <WrappedComponent data={data} {...this.props} />
            );
        }
    };
};

But in the way I structured the app, I ended up making two listeners on the same reference and when I call ref.off(), I lose both of the listeners which is not the intended behavior.
It happens like this:
1. already          2. push configview into stack   3. has another
has listener        and adds another listener       listener
------------             ------>                 --------------
|           |                                    |             |
|           |                                    |             |
| listview  |                                    |  configview |
|  screen   |                                    |   screen    |
|           |                                    |             |
-------------            <-------                ---------------
5. doesn't have           4. pops configview from stack
listener anymore       and removes both listeners

Basically, is there any way to remove only a specific listener from a reference on firebase?

A: You can precisely control what listener(s) gets removed. The key here is that you need to have a reference to the callback function. With anonymous function declarations, you can get that reference as the return value from on():
let listener = ref.on('child_changed', (snapshot) => {
    const value = snapshot.val();
    const prop = snapshot.key;
    const { data } = this.state;
    this.setState({ data: { ...data, [prop]: value } });
});

Then later you can remove that listener with:
ref.off('child_changed', listener);

Also see the reference documentation of on and off.


text:
Q: a question in c++ primer about copy constructor Point global;

Point foo_bar(Point arg)
{
    Point local=arg,*heap=new Point(global);
    *heap=local;

    Point pa[4]={ local,*heap };
    return *heap;
}

the question is how many places are copy constructors used?
The supporting answer of this book says that * heap = local uses the copy constructor, but I don't think so. Isn't the copy assignment operator used here
Is there a problem with my understanding or is the answer wrong?

A: To test this out, lets write a test program.
#include <iostream>

struct CopyConstructCheck {
    CopyConstructCheck() {}
    CopyConstructCheck(const CopyConstructCheck& other) { std::cout << "Copy constructed!\n"; }
    CopyConstructCheck(CopyConstructCheck&& other) noexcept { std::cout << "Move constructed!\n"; }

    CopyConstructCheck& operator=(const CopyConstructCheck& other) { std::cout << "Copy assigned!\n"; return *this; }
};

CopyConstructCheck global;
CopyConstructCheck* heap = nullptr;

CopyConstructCheck foo(CopyConstructCheck arg)
{
    CopyConstructCheck local = arg; heap = new CopyConstructCheck(global);
    *heap = local;

    CopyConstructCheck pa[2] = { local, *heap };
    return *heap;
}

int main()
{
    CopyConstructCheck ret = foo(CopyConstructCheck());

    delete heap;
    return 0;
}

Now when you run the above program, this is the output.
Copy constructed!
Copy constructed!
Copy assigned!
Copy constructed!
Copy constructed!
Copy constructed!

Now lets dissect this.
The first copy construction happens here CopyConstructCheck local = arg; as your assigning the value from arg to the local variable upon instantiation.
The second is in heap = new CopyConstructCheck(global); as your explicitly calling the copy constructor.
Third and forth copy constructions happen in this line CopyConstructCheck pa[2] = { local, *heap }; as your initializing the array with existing data, thus calling the calling the copy constructor of each element.
Finally the last happens in CopyConstructCheck ret = foo_return; line as your constructing the ret variable with the value returned by the function. Note that I first assign the return to a reference variable so that we can handle delete the allocated memory block later.
Now after analyzing, we see that there has been an copy assignment happening right after the 2nd copy construction. If we trace back, its this line *heap = local;. And this proves that your hypothesis is true, it is indeed copy assignment. That's because your not constructing anything there, your assigning data to an existing variable.
Minor touches:
The sample code is the same as the OP's post but fixed a few errors like,

*

*Initializing an array with the size of 4 by using 2 variables in the initializer list.

*The heap allocated block was not deleted once everything is done.

*Dereferencing a pointer and then trying to assign a newly allocated pointer to it.


text:
Q: regular expression character followed by number php I want to add backslashes to following string where u followed by number 0-9 with regular expression in PHP.
$string="u00fehehu2122k ru00f0ru00f0u00c4 ytu201ekuu2122e";

i want this result after converted.
$result="\u00feheh\u2122k r\u00f0r\u00f0\u00c4 yt\u201eku\u2122e";

i have write,
$string= preg_replace("/.u/", "\", $string);

but is does allow me to add "\" in second parameter.
so is there any other way to do this.

A: Using capturing group to capture digit part.
$string = preg_replace('/u(\d)/', "\\u$1", $string);


text:
Q: How to export AWS Glue Crawler schema in a text-human-readable format? AWS Glue Crawler is a powerful tool to infer schema from large data source but I find it quite challenging to share the inferred schema with colleagues, in particular when the schema is relatively complex.
Is there any easy way to export it in a Spark fashion for example? (namely printSchema() method)


text:
Q: Where to load Tensorflow model in Django application I am working on a Django project that should load a saved Tensorflow model from a file. Where should I run this code to have a global model variable? Currently, I am just loading in the model in the views.py file outside of all functions and it is working, but I am unsure if this runs only once and if it is a clean solution.

A: I recommend you to start using mlops, and leave everything preloaded as much as you can, so that when you call the api, django only takes care of generating the predict. I leave you here my project, I have several with ML/Django/Tflite.
Models can be grouped in media files, you can even use DVC to your git/bucket/gdrive, to avoid saturating the git repository with large files.
By doing this you don't need to create global variables, just instantiate the model, you can generate predict whenever you want.
If you have any doubt don't hesitate to ask me.
Link to my project: https://github.com/Nouvellie/django-mlops-docker/blob/main/src/main/apps/mlops/utils/model_loader.py


text:
Q: Asking possibly "trivial" questions to increase SO's knowledge I know that SO is supposed to basically be a knowledge repository when it comes to programming. It's also important to do your research before asking a question.
I notice there are several questions that could be looked up else where fairly easy but are still seen as viable for SO. Personally, I like to look at SO questions for said research (though I'll certainly look else where) because the answers here are usually fairly comprehensive, you don't have to dig for them, and they're written in an easy to understand format.
Is it wrong to ask questions that can be found else where in an attempt to increase the answers SO has available? I'm specifically interested in answers that are already documented else where but fall in grey area between absolute basic (which should be available at thousands of locations) and more intermediate (which may have several easy to find resources).

A: Stack Overflow should not be a replacement for a search engine.
Of course it's totally okay to ask questions that exist elsewhere, but: if the answer to a question can be unequivocally answered with a simple search that leads to official or quasi-official documentation  ("How do I concatenate two strings in JavaScript?"), it should not probably not exist on Stack Overflow.
In my opinion, trivial SO content already tends to clog search engine results.

A: It's not important for every single nugget of programming knowledge to exist on Stack Overflow.  It's purpose is to cover information not found elsewhere, not to have a monopoly on information.  If the answer to a given question is easily discoverable elsewhere on the web (regardless of the difficulty level of the question) then it is not a good SO question.
Now, questions like these get asked many times a day, and their reception does vary.  Some people really like to see these questions even though they are easily discoverable elsewhere, even though many do not, so while it is uncommon, it's also not unheard of to see very simple questions for which the answers can be easily found on other sites to be open or have some upvotes.  While this does happen from time to time, I would discouraging you from posting a question if you know that it's easy to find the answer; there's so much information that not easy to find that, if nothing else, you can come up with better uses of your time.

A: Do not like.
Stack Overflow gets enough questions by the day. We know what programming problems people are actually facing, because people search for, find, or ask (over and over and over again) about those programming problems every second of every day.
We do not need people guessing what information Stack Overflow doesn't have and trying to fill in the gaps. We have it. If not, we'll get it as soon as somebody actually needs it. We're just that good at what we do. What if nobody ever asks? Then obviously nobody needed it, and you just wasted your valuable time.
Spend your time answering questions that already exist and helping clean up content that is not up to our standards or is duplicated (we get a lot of that, too).

tl;dr: If you ask a trivial question that is useful for no one or I can easily find the answer on Google, I will downvote that question without sympathy.

A: The word "trivial" really has two meanings in common usage:  one is "easy" and the other is "unimportant".
If a question is trivial because it's unimportant, that comes pretty close to the criterion for "too localized" used to close some questions.
If a question is easy because finding the answer is easy, even using an "obvious" search key, then that's a question of how much value the added answer in SE adds, versus how much clutter the Q and the A add.
I would say that if a Wikipedia article gives a thorough answer to the question as usually asked, and if most seekers are likely to find the Wikipedia answer, that's enough reason to just let it be.
The tricky case is when a good answer is easily found if and only if the question is asked in precisely the right way, but most seekers are going to ask in a more vague way, because they don't know what they are looking for.  Some of those might be usefully included here.  Others not.


text:
Q: Как открыть в Go-сервере статический HTML-файл по идентификатору в URL? Как открыть в Go-сервере статический HTML-файл по идентификатору в URL?
Типа по URL www.site.com/blog/t5544 открыть файл $/www/site.com/page10.html
Такое вообще возможно?

A: Возможно, конечно :)
Если я правильно понял, то нужно получить параметр из URL, открыть шаблон и передать туда этот параметр. Пакет net/http не умеет парсить URL, поэтому нужно будет воспользоваться внешним пакетом. Установим:
go get github.com/julienschmidt/httprouter

Меньше слов, больше примеров:
package main

import (
  "fmt"
  // Пакет net/http не умеет парсить параметры из URL, поэтому воспользуемся этим пакетом
  "github.com/julienschmidt/httprouter"
  "html/template"
  "net/http"
)

type responseData map[string]interface{}

func main() {
  // Создаем роутер
  router := httprouter.New()

  // Регистрируем пути
  router.GET("/test", func(response http.ResponseWriter, request *http.Request, params httprouter.Params) {
    _ = loadTemplate("test").Execute(response, responseData{})
  })

  // :id - и есть наш параметр
  router.GET("/user/:id", func(response http.ResponseWriter, request *http.Request, params httprouter.Params) {
    _ = loadTemplate("user").Execute(response, responseData{
      "user_id": params.ByName("id"),
    })
  })

  fmt.Println("We are alive on :8181")
  _ = http.ListenAndServe(":8181", router)
}

// Можно прочитать файл и отдать его содержимое, а можно загрузить файл как шаблон, передать туда параметры
// и отдать пользователю
func loadTemplate(tpl string) *template.Template {
  // Загружаем
  return template.Must(template.ParseFiles(fmt.Sprintf("./page/%s.html", tpl)))
}

В test.html нет ничего интересного, а вот в user.html есть использование параметра:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    Страница пользователя с ID {{ .user_id }}
</body>
</html>

После запуска пройдем по адресу http://localhost:8181/user/100500
UPD. Вероятно, я неправильно понял вопрос, исправляюсь
Отдать любой статичный файл, как подметили в комментарии, можно так:
package main

import (
    "fmt"
    "net/http"
)

func main() {

    http.Handle("/", http.FileServer(http.Dir("static")))

    fmt.Println("We are alive on :8181")
    _ = http.ListenAndServe(":8181", nil)
}

В директории static размещаются файлы, которые должны быть доступны извне

A:

type filesHandler struct {
    // Таблица "ID файла" и положения на диске.
    files map[string]string
}

func (h *filesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    var f = h.files[r.RequestURI]
    if f == "" {
        http.NotFound(w, r)
        return
    }

    http.ServeFile(w, r, f)
}

https://play.golang.org/p/T6rzOAvr1mE


text:
Q: Auto populate select tags using jQuery and JSON I'm trying to get one select tag to populate based on the value of another select tag. The values for the populated select tag come from a JSON document.
The practical use here is for departing ferry terminals and what terminals they can reach.
Here is the code snippet I'm using
$(function(){
  $("select#departingfrom").change(function(){
    $.getJSON("/database.json", $(this).val(), function(ferries){
      var options = '';
      for (var key in ferries) {
        options += '<option value=' + key + '>' + key + '</option>';
      }
      $("select#arrivingto").html(options);
    });
  });
});

Here's a small example of the JSON document
var ferries = {
  "horseshoebay": {
    "departurebay": {},
    "langdale": {}
  },
  "departurebay": {
    "horeshoebay": {}
  },
  "tsawwassen": {
    "swartzbay": {},
    "dukepoint": {}
  },
  "swartzbay": {
    "tsawwassen": {},
    "fulfordharbour": {}
  },
  "dukepoint": {
    "tsawwassen": {}
  },
  "langdale": {
    "horeshoebay": {}
  },
  "fulfordharbour": {
    "swartzbay": {}
  }
},

And then the HTML
<select id="departingfrom">
  <option selected="selected"></option>
  <option value="tsawwassen">Tsawwassen (Vancouver)</option>
  <option value="swartzbay">Swartz Bay (Victoria)</option>
  <option value="dukepoint">Duke Point (Nanaimo)</option>
  <option value="departurebay">Departure Bay (Nanaimo)</option>
  <option value="horseshoebay">Horseshoe Bay (North Vancouver)</option>
  <option value="langdale">Langdale (Sunshine Coast)</option>
  <option value="fulfordharbour">Fulford Harbour (Salt Spring Island)</option>
</select>

<select id="arrivingto">
  <option selected="selected"></option>
</select>

I can't seem for the life of me to get the "function(ferries)" to run, so it makes me think that the .val is not working correctly. Let me know if you guys have any suggestions!

A: Your JSON document needs to be refactored a bit for easier iteration.
Let's take this class for example.
public class City
{
    public int CityID { get; set; }
    public string Name { get; set; }
    public int StateID { get; set; }
}

And let's say (using ASP.NET MVC & C#) we are returning JSON by doing this:
    // the theStateID will be for California in this example
    public JsonResult FilterCitiesByStateID(int theStateID)
    {
        List<City> citiesList = null;

        citiesList = new CustomDb().Cities.Where(x => x.StateID ==
                                                    stateID).ToList();

        return Json(citiesList, JsonRequestBehavior.AllowGet);
    }

This will give us back a list of City objects for California. (Pretend the CityID's are meaningful.)

So now you just need to append them to your select list with the proper value and text.
var $request = $.get('/Controller/Action/', { theStateID: 1 });

$request.success(function (listOfOptions) {
    // Iterate over the cities returned and append them to the
    // select list you need
    $.each(listOfOptions, function (key, obj) {
        $('select#YourSelect')
            .append($("<option></option>")
                         .attr("value", obj.CityID) // The value will be the CityID
                         .text(obj.Name) // The text will be the City's Name
                     );
     });
});

A: It seems your problem is that your JSON object isn't actually properly formed if your ajax request is actually returning:
var ferries = { ... }

Your JSON object should simply be
{ ... }

with no variable assignment in the response from the server.


text:
Q: A question related to a NPN transistor having a DC bias
β = current gain
I made the circuit of the above picture with LTspice.

(A graph of Vce)

(A graph of Vbe)
And I was able to get 4.2966V for the value of Vce and 0.6543V for the value of Vbe.
However, when I solved it by hand, the value of Vce was very different.

Watch, please
I translated Korean to English, as follows:
Korean(English)
e.g. 등가회로(Equivalent circuit)
As you can see, the value of Vce solved by hand is 2.9181V.
I really don't understand. How can the error of Vce value occur so big?
Did I design the LTspice wrong? Or, did I solve it wrong?
Please, help me.....

A: The KVL equation \$-10 + 7\,[\text k\Omega]\cdot1\,[\text{mA}] + V_{CE}\$ neglects the voltage drop across the current source I1, and that loop cannot be easily solved with KVL alone, because we don't have an equation that tells us the voltage across a current source.
Instead, you know that \$\beta = 100\$ so the base current is \$I_B = 10\,[\mu\text{A}]\$. You can instead solve KVL around this loop:

We can get \$-10\,[\mu\text{A}]\cdot60\,[\text k\Omega] - V_{BE} + V_{CE} + 7\,[\text k\Omega]\cdot1.01\,[\text{mA}] - 10 = 0\$. When we solve, we get around 4.3 V for Vce which agrees with LT Spice.
In closer detail, the above is equivalent to applying the same step by step logic:

*

*The base is at -600 mV because of a voltage drop of \$R_B\cdot I_B\$.

*The emitter is at -1.3 V because it's one \$V_{BE}\$ drop below the base.

*The collector current is \$1\,[\text{mA}] \cdot (1 + \beta)\$ so the voltage drop across \$R_C\$ is 7.07 V.

*This makes the collector voltage 2.93 V.

*If emitter is at -1.3 V and collector is at 2.93 V, \$V_{CE}\$ is  4.23 V.

*The error between this result and LT Spice probably arises because we assumed a fixed value for \$V_{BE}\$.

Edit to address comment:
In order to get a Vbe, you need to know a transistor parameter called Saturation Current (\$I_S\$) and then solve the equation \$I_E = I_S( e^{\frac{V_{BE}}{V_T}} - 1)\$. \$V_T\$ is proportional to temperature and is approximately 26 mV at room temperature.
Unfortunately this behavior is really sensitive to temperature and manufacturing variations, so it's hard to always get exact values for Vbe. 0.6 or 0.7 is a good estimate to start. You will find that many circuits use techniques like degeneration and feedback to make them less sensitive to these effects so that the exact saturation current or collector current isn't as important to get exactly right. Also, there are many circuits that have two transistors where we don't care about the actual value of Vbe, only that it's the same for both. In that case there are manufacturing techniques that help ensure this matching.


text:
Q: Varying the proportions of 3D Point symbols in QGIS (3D View) I am translating a 3D visualization lab from ArcMap to QGIS 3.22. The lab is very simple; draping imagery over a DEM and showing 3D points that are earthquake epicenters underneath the terrain.
The problem I am facing: In ArcMap, we were able to vary the symbology of the 3D points based on their magnitude values. The instructions are written up here:
"To do this, right-click on the eq_3D layer name and choose Properties →  Symbology.   Next to the symbol, click the Advanced button and from the drop-down menu, choose Size, then choose  and click the calculator button to open the Expression Builder.  We want to scale the symbols proportionally to magnitude, but the units for magnitude are numerically small compared to the size (in meters) of our desired symbols, so use an expression like [Magnitude] * 500".
Simple enough!
In QGIS however, it does not seem possible to change the proportions of 3D point symbols based on some value. I have been doing lots of Googling, but haven't seen anyone asking this question. In the 3D Symbol tab in Properties, I attempted to type in expressions into the Radius box, or to do some sort of rule-based 3D symbol but to no avail. To be fair, my expression-writing is not particularly strong, so I could be doing it wrong.
Do you know of any ways to vary the proportions of 3D point symbols in QGIS 3.22 (LTR)?

A: This indeed does not seem to be possible as of QGIS 3.28 out of the box. There is, however, a workaround: create a Rule-based 3D style and define a separate rule for each case - like attribute-value=12 -> size=12 etc.:

A: For an expression based styling of 3D vector features in QGIS, you can use the plugin Qgis2threejs. No need to make prior 3D settings on your layer, everything is done in the plugin - install the plugin and open the interface from Menu Web.
Greatest thing: when satisfied, with a few clicks you can export the whole setting as interactive scene for the Web so everyone can zoom, rotate, pan, set transparency etc. - cool! See interactive example here.
Setup is simple and intuitive: in the plugin's interface, right click the layer you want to style and click  Properties. Then you can select a type (like Sphere, Cylinder, Cone etc.) and make the available settings, where you can use attributes and expressions for Altitude, Size, Color etc. as can be seen on the screenshot:


text:
Q: How to output result of SELECT statement which is executed using native dynamic SQL? I have a string which contains SQL SELECT statement.
I wonder how can I output result of the execution of that statement on the screen, execution will be done using native dynamic SQL (EXECUTE IMMEDIATE).
example:
DECLARE
v_stmt VARCHAR2 := 'SELECT * FROM employees';
BEGIN
EXECUTE IMMEDIATE v_stmt; -- ??? how to output result of that select on the screen.
END;

Important remark: structure of table can be any. I have to write a procedure which accepts name of the table as parameter, so I can't hardcode a table structure and don't want to do it.
Thanks for responses. Any ideas very appreciated/

A: If you are on Oracle 12c with a 12c client, this should work:
declare
    rc sys_refcursor;
begin
    open rc for 'select * from dual';
    dbms_sql.return_result(rc);
end;

A: Yes we can execute select statement dynamically.
Let say we have a table test. It has four column Row_id,Name,Rank etc
When we do select * from test;
Result will be
Row_id Name   Rank
1      R1    5
2      R2    1
3      R3    2
4      R4    4

Now we can use DBMS_SQL package to execute dynamically SELECT Sql Statament.
Code is below:
   DECLARE
        v_CursorID  NUMBER;
        v_table VARCHAR2(50):='test';
        v_SelectRecords  VARCHAR2(500);
        v_NUMRows  INTEGER;
        v_MyNum INTEGER;
        v_Myname VARCHAR2(50);
        v_Rank INTEGER;

    BEGIN
         v_CursorID := DBMS_SQL.OPEN_CURSOR;
        v_SelectRecords := 'SELECT * from ' || v_table ;
        DBMS_SQL.PARSE(v_CursorID,v_SelectRecords,DBMS_SQL.V7);
        DBMS_SQL.DEFINE_COLUMN(v_CursorID,1,v_MyNum);
        DBMS_SQL.DEFINE_COLUMN(v_CursorID,2,v_Myname,50);
        DBMS_SQL.DEFINE_COLUMN(v_CursorID,3,v_Rank);

        v_NumRows := DBMS_SQL.EXECUTE(v_CursorID);
   LOOP
        IF DBMS_SQL.FETCH_ROWS(v_CursorID) = 0 THEN
             EXIT;
        END IF;

        DBMS_SQL.COLUMN_VALUE(v_CursorId,1,v_MyNum);
        DBMS_SQL.COLUMN_VALUE(v_CursorId,2,v_Myname);
        DBMS_SQL.COLUMN_VALUE(v_CursorId,3,v_Rank);

        DBMS_OUTPUT.PUT_LINE(v_MyNum || ' ' || v_Myname || ' ' || v_Rank  );

   END LOOP;

   EXCEPTION
        WHEN OTHERS THEN
                  RAISE;
        DBMS_SQL.CLOSE_CURSOR(v_CursorID);
        end;


text:
Q: Global choice and skeletons of large categories It is stated on the nlab that the axiom of choice is equivalent to the statement that all small categories have a weak skeleton, meaning a skeletal category which is equivalent to them.

Is the axiom of global choice in MK equivalent to the statement that all (possibly large) categories have weak skeletons?

A: The answer is yes, by the same argument as for small categories and regular choice. First, assuming global choice, you can form skeleta by picking out one element from each isomorphism class of objects.
EDIT: As Sergei Akbarov points out in the comment, the argument is not quite right - to apply global choice we need to apply it to a class of sets, but the collection of isomorphism classes need not consist of just sets (in fact most natural categories don't have this property). One way to salvage this argument is to exploit Scott's trick: replace each isomorphism class $I$, which may be a proper class, with a set $I\cap V_\alpha$, where $V_\alpha$ is the least level of the cumulative hierarchy whose intersection with $I$ is nonempty. Thus we have replaced each isomorphism class with its nonempty subset, and we can apply global choice to the resulting class of sets.

Conversely, suppose we have a class $F$ of nonempty sets and we want to find a choice function for it. Take a category $C$ whose objects are the disjoint union of elements of $F$, and we have exactly one morphism between any two objects belonging to one element of $F$. Then the sets of $F$ are the isomorphism classes from $C$, and any (weak) skeleton constitutes a choice function for $F$.


text:
Q: How to undo all in Photoshop quickly What is the quickest method to undo all changes back to the source of the history?
Version: 2022

A: If you're talking about reverting to the previous save then just use
function revert_it()
{
  var idRvrt = charIDToTypeID( "Rvrt" );
  executeAction( idRvrt, undefined, DialogModes.NO );
}

You can also get the number of history states from  the current document
var history = app.activeDocument.historyStates.length;

You can add revert to a shortcut menu: