text:
Q: Connecting to existing EKS cluster using kubectl or eksctl I have created one kubernetes cluster on EKS. I used eksctl create cluster to create the cluster. I am able to access everything which is great.
However, my colleague has created another cluster, and I am wondering how will I generate / get Kubeconfigs so that I can point to the cluster that my colleague has created.

A: There are 2 ways you can get the kubeconfig.

*

*aws eks update-kubeconfig --name <clustername> --region <region>

*eksctl utils write-kubeconfig --cluster=<clustername>
Provided you have the EKS on the same account and visible to you.
Once you get the kubeconfig, if you have the access, then you can start using kubectl.
If you don't have access, you need to ask the owner to give your userID permissions to the cluster.
Complete details are listed here

A: Accessing a private only API server
If you have disabled public access for your cluster's Kubernetes API server endpoint, you can only access the API server from within your VPC or a  connected network. Here are a few possible ways to access the Kubernetes API server endpoint:

*

*Connected network  – Connect your network to the VPC with an  AWS transit gateway  or other  connectivity  option and then use a computer in the connected network. You must ensure that your Amazon EKS control plane security group contains rules to allow ingress traffic on port 443 from your connected network.

*Amazon EC2 bastion host  – You can launch an Amazon EC2 instance into a public subnet in your cluster's VPC and then log in via SSH into that instance to run  kubectl  commands. For more information, see  Linux bastion hosts on AWS. You must ensure that your Amazon EKS control plane security group contains rules to allow ingress traffic on port 443 from your bastion host. For more information, see  Amazon EKS security group considerations.
When you configure  kubectl  for your bastion host, be sure to use AWS credentials that are already mapped to your cluster's RBAC configuration, or add the IAM user or role that your bastion will use to the RBAC configuration before you remove endpoint public access. For more information, see  Managing users or IAM roles for your cluster  and  Unauthorized or access denied (kubectl).

*AWS Cloud9 IDE  – AWS Cloud9 is a cloud-based integrated development environment (IDE) that lets you write, run, and debug your code with just a browser. You can create an AWS Cloud9 IDE in your cluster's VPC and use the IDE to communicate with your cluster. For more information, see  Creating an environment in AWS Cloud9. You must ensure that your Amazon EKS control plane security group contains rules to allow ingress traffic on port 443 from your IDE security group. For more information, see  Amazon EKS security group considerations.
When you configure  kubectl  for your AWS Cloud9 IDE, be sure to use AWS credentials that are already mapped to your cluster's RBAC configuration, or add the IAM user or role that your IDE will use to the RBAC configuration before you remove endpoint public access. For more information, see  Managing users or IAM roles for your cluster  and  Unauthorized or access denied (kubectl).
Take a look here: eks-endpoints-access.
Isolation through multiple clusters
A possible alternative is to use multiple single tenant Amazon EKS clusters. With this strategy, each tenant will have the possibility to use its own Kubernetes cluster, within a shared AWS account or using dedicated accounts within an Organization for large enterprises.
Once clusters are deployed, you might want to have an overview of all deployed clusters to monitor each tenant, make sure we are running the latest version of EKS control plane and operate at scale. Rancher is a popular open-source tool used to manage multiple Kubernetes clusters, make sure to check out  this article on the Open Source blog  for details on how to deploy and use it.
Clusters in the same VPC
If your colleague's cluster is in the same VPC I advice you to use AWS App Mesh.  App Mesh is a service mesh that lets you control and monitor services spanning two clusters deployed in the same VPC.
Architecture:

Prerequisites
In order to successfully carry out the base deployment:

*

*Make sure to have newest  AWS CLI  installed, that is, version 1.16.268 or above.

*Make sure to have  kubectl installed, at least version  1.11  or above.

*Make sure to have  jq installed.

*Make sure to have  aws-iam-authenticator installed, required for eksctl

*Install  eksctl, for example, on macOS with  brew tap weaveworks/tap  and  brew install weaveworks/tap/eksctl, and make sure it's on at least on version  0.1.26.

Note that this walkthrough assumes throughout to operate in the  us-east-1  Region.
Assuming that both of cluster are working and
Update the  KUBECONFIG  environment variable on each cluster according to the  eksctl  output, respectively:
Run the following in respective tabs.
export KUBECONFIG=~/.kube/eksctl/clusters/first-cluster

export KUBECONFIG=~/.kube/eksctl/clusters/second-cluster

You have now setup the two clusters and pointing kubectl to respective clusters.
Now it is time to deploy App Mesh custom components
To automatically inject App Mesh components and proxies on pod creation, you need to create some custom resources on the clusters. Use  helm  for that. Install tiller on  both  the clusters and then use helm to run the following commands on both clusters for that.
Download App Mesh repo
>> git clone https://github.com/aws/aws-app-mesh-examples (https://github.com/aws/aws-app-mesh-examples).git
>> cd aws-app-mesh-examples/walkthroughs/howto-k8s-cross-cluster

Install Helm
>>brew install kubernetes-helm

Install tiller
Using helm requires a server-side component called tiller installed on the cluster. Follow the instructions in the  documentation  to install tiller on both the clusters.
Verify tiller installation
>>kubectl get po -n kube-system | grep -i tiller
tiller-deploy-6d65d78679-whwzn 1/1 Running 0 5h35m

Install App Mesh Components
Run the following set of commands to install the App Mesh controller and Injector components.
helm repo add eks https://aws.github.io/eks-charts
kubectl create ns appmesh-system
kubectl apply -f https://raw.githubusercontent.com/aws/eks-charts/master/stable/appmesh-controller/crds/crds.yaml
helm upgrade -i appmesh-controller eks/appmesh-controller --namespace appmesh-system
helm upgrade -i appmesh-inject eks/appmesh-inject --namespace appmesh-system --set mesh.create=true --set mesh.name=global

You are now ready to deploy example front and colorapp applications to respective clusters along with the App Mesh, which will span both clusters.
Deploy services and mesh constructs

*

*You should be in the walkthrough/howto-k8s-cross-cluster folder, all commands will be run from this location.

*Your account id:
export AWS_ACCOUNT_ID=<your_account_id>

*Region, e.g., us-east-1

export AWS_DEFAULT_REGION=us-east-1

*ENVOY_IMAGE environment variable is set to App Mesh Envoy, see  Envoy.

export ENVOY_IMAGE=...

*VPC_ID environment variable is set to the VPC where Kubernetes pods are launched. VPC will be used to set up
private DNS namespace in AWS using create-private-dns-namespace API. To find out VPC of EKS cluster, you can
use  aws eks describe-cluster. See below for reason why AWS Cloud Map PrivateDnsNamespace is required.

export VPC_ID=...

*CLUSTER environment variables to export kube configuration

export CLUSTER1=first-cluster
export CLUSTER2=second-cluster

Deploy
./deploy.sh

Finally remember to verify deployment.
More information you can find here: app-mesh-eks.

A: You can get aws IAM access key and id that has permission to access the cluster for both the cluster and set two aws profile and use the following command to access the cluster :
aws eks update-kubeconfig --name cluster-name --profile aws-profilename
above command will add the access details in the kubeconfig file and also set the current-context.
After that you can switch the context with kubectl commands:
kubectl config use-context arn-nameofeks-cluster
prerequisite to have:

*

*aws-cli installed

*kubectl installed


text:
Q: activerecord 3.2.13 query to use where with not nil I know there is Model.where.not for newer versions of activerecord. Is there a workaround for older version of activerecord?
I want to do something like Model.where.not(:completed_at => nil)
where completed_at is a timestamp value.

A: You can use arel but it's a bit verbose
Model.where(Model.arel_table[:completed_at].not_eq(nil))

Otherwise go for the raw SQL
Model.where('completed_at IS NOT NULL')

redpajama_set_name: RedPajamaStackExchange


text:
Q: PowerShell Scheduled task fails with error code: 0xFFFD0000 and 4294770688 if Run Hourly Every Day On a Windows Server 2012 R2 Build 9600, I have a Scheduled Task that runs successfully on demand.
I need it to run every hour every day.
if I change it to "Run Hourly, Every Day", it fails with error codes: 0xFFFD0000 and 4294770688, which stands for "The field "Add arguments (optional)" contains an invalid file name".
This is a bit odd, because everything is ok on that field and this only happens with that schedule combination.
As example, If I schedule it to run once a day at some time, it runs ok.
Best Regards to All

A: I got it to work.
I had to set it up to "Run Once, Every Hour, Indefinitely"
Like: Run "One time, Start at 0h00, Repeat Task Every 1 hour, Indefinitely"
Also do not use the trigger option Stop Task if it runs longer than because it will throw back the 0xFFFD0000 error. Use it on the Settings instead.

A: In my case, I had an action which called powershell. I had to quote the script file path in double quotes (") instead of single quotes (').
So, this error code may have different reasons.

A: I got the same error code and have fixed it by moving powershell script to a folder with no spaces in the file path.  In full, the Add arguments field is:
    -noprofile -ExecutionPolicy Bypass -File C:\users\myname\powershell_testing\my_powershell_script.ps1


text:
Q: How to set popup window style for responsive UI in android In My android app, I used popup window.
There is one issue regarding popup window.
In bigger device (height or width) It will show clearly and automatically set margin left or right.
In smaller device like nexus one , Popup window stick with device not set margin left or right.
Or another issue is that In lollipop or marshmallow there is one button look like floating button. You can view in screen shot which I attached below.
That button look good in marshmallow or higher version.
But in kitkat there is only look like a simple arrow how to resolved it.
Here i specified My popup window source code or screenshots of kitkat device UI and Marshmallow UI.
please any one let me know how to resolved it. In advance, Thank you for your support.
raw_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/demo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorWhite"
android:orientation="horizontal"
android:padding="16dp">

<TextView
    android:id="@+id/txtMainHeading"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="10dp"
    android:text="@string/headertext"
    android:textColor="@color/colorBlack"
    android:textSize="16sp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/txtText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:padding="10dp"
    android:text="@string/popupsubtext"
    android:textColor="@color/colorBlack" />

<View
    android:id="@+id/viewMain"
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:layout_below="@+id/txtText"
    android:background="@color/bg_border" />

<View
    android:id="@+id/view"
    android:layout_width="wrap_content"
    android:layout_height="2dp"
    android:layout_below="@+id/LayoutDetail"
    android:layout_marginLeft="95dp"
    android:layout_marginRight="10dp"
    android:background="@color/bg_border" />

<LinearLayout
    android:id="@+id/LayoutDetail1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/view"
    android:layout_gravity="center"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/txtLastNameText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:text="@string/puplastname"
        android:textColor="@color/colorBlack"
        android:textSize="15sp" />

    <TextView
        android:id="@+id/txtLastName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:focusableInTouchMode="true"
        android:text="@string/txtLastnametext"
        android:textColor="@color/button_text_dialog"
        android:textSize="16sp" />
</LinearLayout>

<View
    android:id="@+id/view1"
    android:layout_width="wrap_content"
    android:layout_height="2dp"
    android:layout_below="@+id/LayoutDetail1"
    android:layout_marginLeft="95dp"
    android:layout_marginRight="10dp"
    android:background="@color/bg_border" />

<LinearLayout
    android:id="@+id/LayoutDetail2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/view1"
    android:layout_gravity="center"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/txtEmailText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:text="@string/pupEmail"
        android:textColor="@color/colorBlack"
        android:textSize="15sp" />

    <TextView
        android:id="@+id/txtEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:text="@string/txtemailtext"
        android:textColor="@color/button_text_dialog"
        android:textSize="16sp" />

</LinearLayout>

<View
    android:id="@+id/view2"
    android:layout_width="wrap_content"
    android:layout_height="2dp"
    android:layout_below="@+id/LayoutDetail2"
    android:layout_marginBottom="10dp"
    android:layout_marginLeft="70dp"
    android:layout_marginRight="10dp"
    android:background="@color/bg_border" />

<ImageView
    android:id="@+id/btnNext"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/LayoutDetail2"
    android:layout_margin="@dimen/fab_margin"
    android:layout_marginLeft="10dp"
    android:layout_marginStart="10dp"
    android:layout_marginTop="14dp"
    android:background="@drawable/shape_oval"
    android:elevation="2dp"
    android:scaleType="center"
    android:src="@drawable/ic_icon_right_1" />

<LinearLayout
    android:id="@+id/LayoutDetail"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/txtText"
    android:layout_gravity="center"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/txtFirstNameText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:text="@string/pupfirstname"
        android:textColor="@color/colorBlack"
        android:textSize="15sp" />

    <TextView
        android:id="@+id/txtFirstName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:focusableInTouchMode="true"
        android:text="@string/txtFirstnametext"
        android:textColor="@color/button_text_dialog"
        android:textSize="16sp" />

</LinearLayout>

Popupwindow.java
private Context mContext;
private Activity mActivity;
private android.widget.PopupWindow mPopupWindow;
private RelativeLayout mRelativeLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_countrycode);

    mContext = getApplicationContext();

    // Get the activity
    mActivity = CountrycodeActivity.this;

    // Get the widgets reference from XML layout
    mRelativeLayout = (RelativeLayout) findViewById(R.id.mRelativeLayout);

    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);

    // Inflate the custom layout/view
    View customView = inflater.inflate(R.layout.raw_layout, null);

    mPopupWindow = new android.widget.PopupWindow(
            customView,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
    );
    //    mPopupWindow.setContentView(findViewById(R.id.activity_view_pager));
    mPopupWindow.setAnimationStyle(R.style.PopupAnimation);

    if (Build.VERSION.SDK_INT >= 21) {
        mPopupWindow.setElevation(24f);
    }

    new Handler().postDelayed(new Runnable() {

        public void run() {
            mPopupWindow.showAtLocation(mRelativeLayout, Gravity.CENTER, 0, 0);
        }

    }, 100L);

}

@Override
protected void onStop() {
    super.onStop();
    mPopupWindow.dismiss();
}

Screenshots of UI
In marshmallow as well as bigger device nexus 5.1
In nexus one as well as kitkat device or smaller

A: android:layout_width="fill_parent"

set RelativeLayout width property fill_parent


text:
Q: Android DownloadManager saving file to device and can't open it I'm trying to open a file I save to my device, but I can't open it. The device indicates, "This document cannot be opened".
Here's my code. The file is .ppt format.
Obviously I have these permissions in the manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Here's the code:
String fileName = doc.getName();

String packageName = fragment.getActivity().getPackageName();
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/Android/data/" + packageName + "/files/";

File saveFile = new File(path + fileName);

File parentDest = saveFile.getParentFile();
if (!parentDest.exists()) {
    parentDest.mkdirs(); //make all the directory structures needed
}
if (!saveFile.exists()) {

    try {
        saveFile.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Toast.makeText(getContext(), "Downloading...", Toast.LENGTH_SHORT).show();

    downloadingDocs.add(doc);

    final DownloadManager downloadManager;

    final long myDownloadReference;

    downloadManager = (DownloadManager) fragment.getActivity().getSystemService(Context.DOWNLOAD_SERVICE);

    Uri uri = Uri.parse(url);

    DownloadManager.Request request = new DownloadManager.Request(uri);

    request.addRequestHeader("Authorization", "Basic " + SharedPref.getAuthPrefValue());
    request.addRequestHeader("Device", BaseApplication.getCurrentDevice().getDevice().toString());
    request.addRequestHeader("DeviceId", BaseApplication.getCurrentDevice().getDeviceId());
    request.setDescription(fileName).setTitle("Downloading Document");
    request.setDestinationInExternalFilesDir(getContext(), path, fileName);
    request.setVisibleInDownloadsUi(true);
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);

    myDownloadReference = downloadManager.enqueue(request);

    finalHolder1.downloadProgress.setVisibility(View.VISIBLE);

    new Thread(new Runnable() {
        @Override
        public void run() {
            downloading = true;

            while (downloading) {
                DownloadManager.Query q = new DownloadManager.Query();
                q.setFilterById(myDownloadReference);
                Cursor cursor = downloadManager.query(q);
                cursor.moveToFirst();
                int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

                if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                    downloading = false;
                    downloadingDocs.remove(doc);
                }
                //final double dl_progress = (bytes_downloaded / bytes_total) * 100;
                final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
                fragment.getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    finalHolder2.downloadProgress.setProgress((int) dl_progress);
                }
            });
            cursor.close();
        }
    }}).start();
} else {
    Intent intent = new Intent();
    intent.setAction(android.content.Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(saveFile), "application/vnd.ms-powerpoint");

    fragment.getActivity().startActivity(intent);
}

A: ok so I found the solution, i'll post it here so maybe it will help anyone else in the future.
Basically, with the help of debugging and lots of logs.
I found out eventually that the DownloadManager saves the file automatically to this path :
"storage/emulated/0/Android/data/" + package name + "/files/".
after all that path that he creates for you, I added my own.
so the path I am looking for the file was not the correct one.
what I did is match my own file with the correct path of the download manager.


text:
Q: How to call Kotlin method with more than one similar signature with lambda? I am using some code from this library: https://github.com/Netflix-Skunkworks/rewrite
When I call one of its methods, I encounter an IDE error:

None of the following functions can be called with the arguments supplied.

The target method has two similar signatures:
data class CompilationUnit(...){

    fun refactor() = Refactor(this)

    fun refactor(ops: Refactor.() -> Unit): Refactor {
        val r = refactor()
        ops(r)
        return r
    }

    fun refactor(ops: Consumer<Refactor>): Refactor {
        val r = refactor()
        ops.accept(r)
        return r
    }
}

The calling code in Kotlin:
val unit: CompilationUnit =...
unit.refactor{ tx ->
   doSomeThing()
}

And this call with lambda is OK in Java:
CompilationUnit unit = ....
unit.refactor(tx -> {
    doSomeThing()
});

A: You can fix the calling code in Kotlin: you are passing a lambda with one argument { tx -> doSomething() }, but a lambda with receiver and no arguments is expected there.
Compare: (Refactor) -> Unit is the type for a function with one argument, while Refactor.() -> Unit means a function with receiver, which takes no arguments and instead is passed a receiver (this) of type Refactor. These types are sometimes interchangeable, but lambdas are not converted between them implicitly.
So, you can call refactor it as follows:
val unit: CompilationUnit = ...
unit.refactor {
   doSomeThing() // this code can also work with `this` of type `Refactor`
}

Alternatively, to call the overload with Consumer<Refactor>, you can explicitly specify that:
unit.refactor(Consumer { tx -> doSomething() })

Implicit SAM conversion is, apparently, not available because there are several overloads with functional parameters.


text:
Q: "exact" cause blank page production mode I'm new in ReactJS world, and I'm having a trouble with the production.
So, I'm learning about Router because I'm doing a sort of website with a login.
import React from 'react';
import ReactDOM from 'react-dom';
import IndexPage from './IndexPage/IndexPage';
import HomePage from './HomePage/HomePage';
import { Router, Route, Redirect, Switch } from 'react-router-dom'
import AuthService from './services/AuthService';
import History from './services/History';

const auth = new AuthService();

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={(props) => (
      auth.loggedIn() === true
        ? <Component {...props} />
        : <Redirect to={{
            pathname: '/',
            state: { from: props.location }
          }} />
    )} />
  )

ReactDOM.render(
    <Router history={History}>
        <Switch>
            <Route exact path="/" component={IndexPage}/>
            <PrivateRoute path="/home" component={HomePage}/>
        </Switch>
    </Router>,
    document.getElementById('root'),
);

This is my index.js file, as you can see I've
<Route exact path="/" component={IndexPage}/>

This line creates the problem. As you can see I'm using exact as param, if I don't use it I got "CANNOT GET /pagename" (for the other components). Now, if I build the website with this "exact" in the line, I've a blank page, else if I build without the exact it "works", but when I log-in I've the homepage behind the login form (I see both in the same page).
Someone could help me? I think that the webpack and the package are correct..
Thank you!
UPDATE, I SOLVED!
As Hassan said, I tried to change my route in this way (removing also the exact param):
<PrivateRoute path="/home" component={HomePage}/>
<Route path="/" component={IndexPage}/>

It worked :D!
Hope this is helpfull!

A: Try to change your code flow from
<Route exact path="/" component={IndexPage}/>
<PrivateRoute path="/home" component={HomePage}/>

To
<PrivateRoute path="/home" component={HomePage}/>
<Route path="/" exact component={IndexPage}/>

I had a problem like this. Hope this works for you too.
Let me know how it goes


text:
Q: Differential amplifier using LM741 I am trying to build a differential amplifier using the lm741 op amp, and simulate it in LTSpice. The dynamic range of the output is too small (about 20mV), I use a rectangular wave (3.3V) and 1.8V DC Input and want to amplify this input difference. Anybody knows the reason, why the output dynamic range is too small?
Thanks in advance,
Ahmed

A: From looking at the schematic, I'm assuming that vdd5 is 5V.
The amplifier has a gain of 7. So the difference between the vdd1.8 node (1.8V) and in- node will be multiplied by 7.
The signal coming to in- node is a pulse train. Let's analyse it:

*

*When the signal is zero the difference signal will be 1.8 - 0 = 1.8V. Expected output is 1.8 x 7 = 12.6V.

*When the signal is -3.3V the difference signal will be 1.8 - (-3.3) = 5V. Expected output is 5 x 7 = 35V.

As you can see, in either case, the output will exceed the supply voltage of op amp, which is presumably 5V. The LM741 is not a rail-to-rail op amp thus the output will be (probably a few hundreds of millivolts) less than 5V. So the circuit behaves as expected.
Decrease the pulse train's amplitude and increase the supply voltage because none of the 741's are supposed to be supplied from 5V.

A: You're using the poor 741 way beyond what it can do: switching at 1 MHz. If you'll go to My Documents/LTspiceXVII/examples/Educational/ you'll see LM741.asc. It's a transistor level representation. If you then change the input source to be PULSE(0 1 0 10n 10n 0.5u 1u) and simulate for .tran 10u, you'll see a more likely output of how the opamp should behave. Not only it's not a comparator, but it's a very fat and lazy opamp, too. What you have there is not a god model. Caveat emptor: always test your models.

A: Here is what the output should look like (roughly) with an LM741, but I've changed the supplies to +40/-4 and reduced the frequency to 1kHz, a more reasonable frequency for the LM741 and square waves.

simulate this circuit – Schematic created using CircuitLab

The peak output voltage is 7 * (1.8 + 3.25) = 35.35V. The minimum is 7 * 1.8 = 12.6V  (a popular vacuum tube heater voltage at one time).
A  741 will barely manage to output a sickly low-amplitude triangle wave if you feed it with a large square wave input at 1MHz. It's orders of magnitude away from being capable of handling that kind of frequency. In fact you'd need a very high frequency op-amp to amplify a 1MHz square wave x 7 and have it come out looking more or less like a square wave. Perhaps  70 MHz gain bandwidth, and adequate slew rate vs. about 1MHz GBW for the 741.
What you are seeing in the simulation is just some internal coupling at low amplitude. The op-amp is doing nothing of value (it's railed).


text:
Q: Delete record from many to many entity in Zend using Doctrine 2 I am working on Zend Doctrine. I have a many-to-many entity groups_contacts which has fields group_id and contact_id linked to relevant tables group and contact and created in group entity.
I am creating groups_contacts in group entity which is a many-to-many relationship.
Following is the code of delete action:
public function deleteGroupMemberAction() {
    $auth_service = $this->getServiceLocator()->get('doctrine.authenticationservice.orm_default');
    $objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
    $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
    $user = $auth_service->getIdentity();
    //die($_POST['g_id'] . ' removed');

    $query_deleteMember = $em->createQuery('delete from groups_contacts gc where gc.contact_id = 7 and gc.group_id = 1');

    $numDeleted = $query_deleteMember->execute();
    die($query_deleteMember. ' removed');

    $objectManager->flush();
    die($title . ' removed');
}

This function called on ajax call which is working perfectly.
I don't know why the delete query is not working, I tried other ways but get the same result. Does anyone have any ideas?

A: You have to specify the mapping to your entity
delete from MyMapping:groups_contacts gc where gc.contact_id = 7 and gc.group_id = 1

Or put your namespace:
delete from Your\Name\Space\groups_contacts gc where gc.contact_id = 7 and gc.group_id = 1

But that's not enough because you can not access these contact_id and group_id columns directly. So you would have to write:
delete from MyMapping:groups_contacts gc JOIN gc.contact c JOIN gc.group g where c.id = 7 and g.id = 1

Wow two joins .. this should be simpler in native SQL. Does it even execute those JOINS? Perhaps Doctrine will optimize it and not use the JOIN in the final query.
The use case is a bit weird though. Suppose you have a website which lists groups and their contacts. The relation is represented by groups_contacts (on a site note you should only make this a seperate entity when the relation needs to hold data itself). Then when the user wants to remove a relationship (disconnect a contact from a group) the relationship (represented by groups_contacts) can just be identified with it's own id. Then your query would become:
DELETE FROM MyMapping:groups_contacts gc WHERE gc.id = <user clicked relation>

A: Here is the solution
controller
$group = $em->find("Application\Entity\Group", $group_id);
        if ($group->getCreatedBy()->getId() == $user->getId()) {
            $contact = $em->find("Application\Entity\UserProfile", $contact_id);
            if (isset($contact)) {
                $group->getContacts()->removeElement($contact);
                $objectManager->persist($group);
                $objectManager->flush();

            }
Group Entity
/**
 *
 * @ORM\ManyToMany(targetEntity="UserProfile")
 * @ORM\JoinTable(name="groups_contacts",
 *      joinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="contact_id", referencedColumnName="id")}
 *      )
 */

    private $contacts;
It's better to handle many-to-many relationship this way, in which you have to get the group and the contact ids you want to remove from associative entity by usingthe removeElement and then persist with the relevant id of group


text:
Q: iOS Tests target cannot access target pods I made a test target for my app. It has dependencies like
import XCTest
import RxSwift
import RxCocoa
import RxBlocking
@testable import MyApp

And my Podfile looks like
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

def shared_pods
    pod 'RxSwift',          '~> 2.0'
    pod 'RxCocoa',          '~> 2.0'
end

target 'Mobium-ios' do
    shared_pods
end

target 'Mobium-ios-tests' do
    shared_pods
    pod 'RxBlocking',       '~> 2.0'
    pod 'RxTests',          '~> 2.0'
end

However, in my test I cannot import RxBlocking

A: 'Build for testing' solved the issue.


text:
Q: How to use etags for caching? Can anyone tell me how to pass etag correctly for this url?
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,id&playlistId=UUwpy_3CqtfwM7tg2JgQQQyA&maxResults=50&key={API_KEY}.
I was passing like this, but didn't work.
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,id&playlistId=UUwpy_3CqtfwM7tg2JgQQQyA&maxResults=50&key={API_KEY}&If-None-Match="p4VTdlkQv3HQeTEaXgvLePAydmU/vKZr9jiSytaO7UdTbhKbIrwbX20"

A: If-None-Match is request header, and not query param. Need set this header in headers of request. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader


text:
Q: MySQL junction table concatenation I have an requirement to return all educators associated with a session as a concatenated list, but to do it within a join (don't ask - I know there are multiple ways of doing it but I'm working with a library that won't accept those methods ;-))
I have a sessions table with session_id and session_name.
| session_id | session_name |
+------------+--------------+
| 1          | Swimming     |
| 2          | Chess        |

I have a session_educators table which is basically a junction table session_id and contact_id.
| session_id | contact_id |
+------------+------------+
| 1          | 1          |
| 1          | 2          |
| 2          | 3          |
| 2          | 4          |

I have a contacts table with contact_id and full_name
| contact_id | full_name    |
+------------+--------------+
| 1          | Fred Bloggs  |
| 2          | Mary Bloggs  |
| 3          | Mark Smith   |
| 4          | Shelly Smith |

So far this seems to be the closest I've come:
SELECT
    sessions.session_id,
    sessions.name,
    educators.names
FROM
    `sessions`
LEFT JOIN
    (
        SELECT
            GROUP_CONCAT(contacts.full_name SEPARATOR ', ') as names
        FROM
            `contacts`
        WHERE
            contact_id
        IN
            (
                SELECT
                    contact_id
                FROM
                    session_educator
                WHERE
                    session_educator.session_id = sessions.session_id
            )
    ) `educators`
USING
    (`session_id`)

But I'm really fumbling in the dark trying to figure it out, can anyone help?
What I'm wanting, as you can probably tell from the query, is a result like this:
| session_id | session_name | educators                |
+------------+--------------+--------------------------+
| 1          | Swimming     | Fred Bloggs, Mary Bloggs |
| 2          | Chess        | Mark Smith, Shelly Smith |

Any help greatly appreciated - even if it's just to say it can't be done!

A: You shouldn't need subqueries for this.  It is a few joins and an aggregation:
select s.session_id, s.session_name,
       group_concat(e.name separator ', ') as educators
from sessions s left join
     session_educators se
     on se.session_id = s.session_id left join
     educators e
     on e.educator_id = se.educator_id
group by s.session_id;

A: I do believe you're making it all a little more complex than needed (unless I've missed something in your requirements? I know how much of a pain libraries can be...)
This worked for me:
SELECT
    session_id,
    session_name,
    (
        SELECT
            GROUP_CONCAT(full_name SEPARATOR ', ') as names
        FROM
            contacts c,
            session_educators se
        WHERE
            c.contact_id = se.contact_id
        AND
            se.session_id = s.session_id
    )
FROM
    sessions s
;


text:
Q: Histogram tracking inventory levels in R I am looking for a way to visualize inventory throughout a day. The dataset looks as follows, with the summaries of the last two columns below:
                 Time  Price Inventory Duration
1 9/1/2016 9:25:06 AM 13.960    318        0
2 9/1/2016 9:36:42 AM 13.980    106      696
3 9/1/2016 9:40:52 AM 13.990   -599      250
4 9/1/2016 9:52:54 AM 14.015     68      722
5 9/1/2016 9:52:54 AM 14.015    321        0
6 9/1/2016 9:54:17 AM 14.010     74       83

Inventory
 Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
-1120.00   -98.75     9.00     0.00   100.00  1988.00

Duration
Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
 0.00     40.25    205.50   2100.00    529.00 272700.00

I want to visualize the data by showing how much time was spent on various inventory levels.  What would you recommend as a function for this? So far I found only histograms based on frequency, not time. My intended result would look similar to this:
https://postimg.org/image/z074waij1/
Thanks in advance

A: I wrote the following function for my needs. Hope it helps
inv.barplot.IDs <- function(inv.list, IDs = 1:1620)
  {
    # Subset according to the IDs
    myinvs <- as.data.frame(matrix(nrow = 0, ncol = 14))
    names(myinvs) <- inv.names
    Volume <- Duration <- vector("numeric")

    for (i in IDs)
    {
      #myinvs <- rbind(myinvs, inv.list[[i]])
      Volume <- c(Volume, as.numeric(inv.list[[i]]$Volume))
      Duration <- c(Duration, as.numeric(inv.list[[i]]$Duration))
    }

    # Design a sequence of skatules
    minimum <- min(Volume)
    maximum <- max(Volume)
    width <- (maximum + abs(minimum)) / 18
    width <- round(width, -1)
    seq.pos <- seq(width, maximum + width, by = width)
    seq.neg <- - seq(0, abs(minimum) + width, by = width)
    seq <- c(rev(seq.neg), seq.pos)

    # Categorize the dataframe (new column)
    Skatule <- numeric(length = length(Volume))
    for (i in 1:length(Volume))
    {
      Skatule[i] <- seq[head(which(seq > Volume[i]), 1) - 1]
    }

    barplot.data <- tapply(Duration, Skatule, sum)

    # Save the barplot
    #jpeg(filename = file.barplot, width = 480 * (16/9))
    inv.barplot <- barplot(barplot.data, border = NA, ylim = c(0, max(barplot.data)), main = "Total time spent on various inventory levels", xlab = "Inventory", ylab = "Log of Hours")
    #print(inv.barplot)
    #dev.off()
  }


text:
Q: Find the Key in map in javascript How to find the key from js map array of perticular value? For example:
var map = {'key1': 'value1', 'key2': 'value2'};

How I find the key of value1?

A: Object.prototype.getKeyByValue = function( value ) {
    for( var prop in this ) {
        if( this.hasOwnProperty( prop ) ) {
             if( this[ prop ] === value )
                 return prop;
        }
    }
}

var test = {
   key1: 42,
   key2: 'foo'
};

test.getKeyByValue( 42 );  // returns 'key1'

from: JavaScript object get key by value


text:
Q: Javascript: Is Javascript cached if invoked from the html's body? Problem!
I am calling a JS function inside the html's body section, the function's parameters are gathered by parsing the EL inside the function.
Eg:
<script type="text/javascript">
    jQuery(window).load(function() {
        loadImage("${expression_language_var_1}", "${expression_language_var2}");
    });
</script>

But it seems that sometimes both parameters are cached and I do receive old information.
Questions!

*

*Are the script tags inside the html structure being cached just the same way as the external javascript files that are included in the header?

Best Regards,

A: The issue is that the entire HTML page is being cached, including the script tags which contain your evaluated EL. If you serve the page with the following header tags the browser shouldn't cache it:
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />

For more details about how these headers disable caching refer to this answer: Using <meta> tags to turn off caching in all browsers?


text:
Q: How to change text in a button without affecting a button name? I have a trivial question hopefully. I create a button with CreateWindowEx where I specify a button name. Later in the application I need to change the button caption so I use a WM_SETTEXT message:
SendMessage(hStartBtn, WM_SETTEXT, 0, (LPARAM) _T("NewText"));

This works fine, it changes a button caption to "NewText". However it also have one drawback - it changes the button name specified during CreateWindowEx call. This messes few things in my app since I use FindWindowEx to find a handle of this button (Im trying to avoid using global variables thus I don't store handle returned by CreateWindowEx).
Is this really how buttons work or Im missing some other message/function that changes the caption but doesn't affect the control name?
Thanks,
Kra

A: Buttons are not identified by "name". The string passed to the button control is the text it displays.
Windows uses control IDs to identify controls. GetDlgItem is used to retrieve a window handle, given its parent window. All that is required is that windows are created with the correct control id (passed in via the HMENU parameter of CreateWindow) and the parent window does not have to be a dialog.

A: This MSDN article on WM_SETTEXT suggests that "For a button, the text is the button name".


text:
Q: Adding Qframes and Matplotlib In python PyQt5 I am trying to run a program with Python PyQt5 where I take ip's of 2 camera's and stream them live on my screen, but the stream is coming like so (check the 1st picture) like the one in the given picture both the steams are coming in the first half but What I really want them is to come in separate halves(check 2nd picture for better understanding) of the top layout of the code which is in horizontal layout, not together in just the 1st Half of the screen (also i am getting these black borders which I am not able to remove if anyone knows how it can be removed please do tell)
And after the video streams are in the top layout in the bottom layout I am trying to get a Graph and an empty widget which I could edit for later use.
Thanks in Advance

Click here to see my desired output(what i am actually trying to get)
#this is my main window code#
import sys
import vlc
import subprocess

from PyQt5 import QtCore, QtGui, QtWidgets

from PyQt5 import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import*
from PyQt5.QtWebEngineWidgets import*
from PyQt5.QtPrintSupport import*

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Final App")
        self.setGeometry(350,150,400,400)
        self.UI()

#calling the UI fucntion which contains the layouts
    def UI(self):
        self.mainLayout=QVBoxLayout()#main layout is in Vertical Layout
        self.topLayout=QHBoxLayout()#top layout is in Horizontal layout
        self.bottomLayout=QHBoxLayout()#btm layout is in also in horizontal layout
        self.topLayout.setContentsMargins(0, 0, 0, 0)
        #self.topLayout.setSpacing(0)

        #adding the top and bottom layout inside main layout
        self.mainLayout.addLayout(self.topLayout)
        self.mainLayout.addLayout(self.bottomLayout)

        #assigning variables to different widgets that can be added later
        self.videoFrame1 = QFrame()
        self.videoFrame2 = QFrame()
        #code here to add graph#
        #graphcode=graph#
        self.text=QLabel("A widget that I can Edit LATER ")

########################################################video player 1###################################################################################

        self.videoFrame1 = QFrame()
        #QWidget.setGeometry (self,100, 200, 1000, 500)
        self.videoFrame1.setGeometry(QtCore.QRect(100, 100, 100, 200))
        self.topLayout.addWidget(self.videoFrame1)
        self.vlcInstance = vlc.Instance(['--video-on-top'])
        self.videoPlayer = self.vlcInstance.media_player_new()
        self.videoPlayer = self.vlcInstance.media_player_new()
        self.videoPlayer.video_set_mouse_input(False)
        self.videoPlayer.video_set_key_input(False)
        #self.videoPlayer.set_mrl("rtsp://admin:admin123@192.168.1.250:554/cam/realmonitor?channel=1&subtype=0", "network-caching=300")
        self.videoPlayer.set_mrl("rtsp://admin:admin123@192.168.1.251:554/cam/realmonitor?channel=1&subtype=0", "network-caching=200")
        self.videoPlayer.audio_set_mute(True)
        if sys.platform.startswith('linux'): # for Linux using the X Server
            self.videoPlayer.set_xwindow(self.videoFrame1.winId())
        elif sys.platform == "win32": # for Windows
            self.videoPlayer.set_hwnd(self.videoFrame1.winId())
        elif sys.platform == "darwin": # for MacOS
            self.videoPlayer.set_nsobject(int(self.videoFrame1.winId()))

        self.videoPlayer.play()

        #########################################video player 2############################################################################################
        #frame2
        self.videoFrame2 = QFrame()
        self.topLayout.addWidget(self.videoFrame2)
        self.vlcInstance1 = vlc.Instance(['--video-on-top'])
        self.videoPlayer1 = self.vlcInstance1.media_player_new()
        self.videoPlayer1 = self.vlcInstance1.media_player_new()
        self.videoPlayer1.video_set_mouse_input(False)
        self.videoPlayer1.video_set_key_input(False)
        #self.videoPlayer1.set_mrl("rtsp://admin:admin123@192.168.1.251:554/cam/realmonitor?channel=1&subtype=0", "network-caching=300")
        self.videoPlayer1.set_mrl("rtsp://admin:admin123@192.168.1.250:554/cam/realmonitor?channel=1&subtype=0", "network-caching=200")
        self.videoPlayer1.audio_set_mute(True)
        if sys.platform.startswith('linux'): # for Linux using the X Server
            self.videoPlayer1.set_xwindow(self.videoFrame2.winId())
        elif sys.platform == "win32": # for Windows
            self.videoPlayer1.set_hwnd(self.videoFrame2.winId())
        elif sys.platform == "darwin": # for MacOS
            self.videoPlayer1.set_nsobject(int(self.videoFrame2.winId()))

        self.videoPlayer1.play()
        ###########################################################################################################

          #calling top layout
        self.toplayout()

        #calling bottom layout
        self.bottomlayout()

        #setting main layout
        self.setLayout(self.mainLayout)

        self.show()

    def toplayout(self):
        self.topLayout.setContentsMargins(10,10,20,20)
        self.topLayout.addWidget(self.
            videoFrame1)
        self.topLayout.addWidget(self.videoFrame2)

    def bottomlayout(self):
        self.bottomLayout.setContentsMargins(150,40,100,80)
        self.bottomLayout.addWidget(self.raddar)
        self.bottomLayout.addWidget(self.button2)

def main():
    App= QApplication(sys.argv)
    window=Window()
    sys.exit(App.exec())

if __name__ == '__main__':
    main()

this is my other folder having a matplotlib code:---
#this is another folder having my garph which i want to call in my main window#
import matplotlib.pyplot as plt

def UI():
    plt.figure()

    # Set x-axis range
    plt.xlim((-4,4))

    # Set y-axis range
    plt.ylim((0,8))

    #setting background color
    ax = plt.axes()
    ax.set_facecolor('black')

    # Draw lines to split quadrants
    plt.plot([0,0],[0,8], linewidth=3, color='blue' )
    plt.plot([-4,4],[4,4], linewidth=3, color='blue' )
    plt.title('Quadrant plot')

    plt.show()

UI()

A: hey so I was able to work something out with the code that I already had so I am going to stream the videos on pyqt only and use subprocess to call the .exe file which I made using MATLAB so here you go do have a look.(here I haven't called the Subprocess right now)
import sys
import vlc
from PyQt5 import QtCore, QtGui, QtWidgets

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtPrintSupport import *

class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        #this sets the size Maximum for the main Q Frame
        self.setWindowState(QtCore.Qt.WindowMaximized)
        #this removes the title bar of the window
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.move(0,0)

        #Main Q frame defined where the HBox layout is defined
        self.mainFrame = QFrame()
        #means defining it in central widget
        self.setCentralWidget(self.mainFrame)
        #HBox Layout
        t_lay_parent = QHBoxLayout()
        #used to move the frames inside to go more up down, right,left
        t_lay_parent.setContentsMargins(0, 0, 0, 315)
        #removes the spacing between the frames and makes it looks like that its just 1 stream
        t_lay_parent.setSpacing(0)

#########################################################Camera Frame 1###################################################################
        self.videoFrame = QFrame()
        QWidget.setGeometry (self, 100, 200, 1500, 1500)
        t_lay_parent.addWidget(self.videoFrame)
        self.vlcInstance = vlc.Instance(['--video-on-top'])
        self.videoPlayer = self.vlcInstance.media_player_new()
        self.videoPlayer = self.vlcInstance.media_player_new()
        self.videoPlayer.video_set_mouse_input(False)
        self.videoPlayer.video_set_key_input(False)
        #self.videoPlayer.set_mrl("rtsp://admin:admin123@192.168.1.250:554/cam/realmonitor?channel=1&subtype=0", "network-caching=300")
        self.videoPlayer.set_mrl("rtsp://admin:admin123@192.168.1.251:554/cam/realmonitor?channel=1&subtype=0", "network-caching=200")
        self.videoPlayer.audio_set_mute(True)
        if sys.platform.startswith('linux'): # for Linux using the X Server
            self.videoPlayer.set_xwindow(self.videoFrame.winId())
        elif sys.platform == "win32": # for Windows
            self.videoPlayer.set_hwnd(self.videoFrame.winId())
        elif sys.platform == "darwin": # for MacOS
            self.videoPlayer.set_nsobject(int(self.videoFrame.winId()))

        self.videoPlayer.play()
##########################################################Camera Frame 2#################################################################

        #frame2
        self.videoFrame1 = QFrame()
        t_lay_parent.addWidget(self.videoFrame1)
        self.vlcInstance1 = vlc.Instance(['--video-on-top'])
        self.videoPlayer1 = self.vlcInstance1.media_player_new()
        self.videoPlayer1 = self.vlcInstance1.media_player_new()
        self.videoPlayer1.video_set_mouse_input(False)
        self.videoPlayer1.video_set_key_input(False)
        #self.videoPlayer1.set_mrl("rtsp://admin:admin123@192.168.1.251:554/cam/realmonitor?channel=1&subtype=0", "network-caching=300")
        self.videoPlayer1.set_mrl("rtsp://admin:admin123@192.168.1.250:554/cam/realmonitor?channel=1&subtype=0", "network-caching=200")
        self.videoPlayer1.audio_set_mute(True)
        if sys.platform.startswith('linux'): # for Linux using the X Server
            self.videoPlayer1.set_xwindow(self.videoFrame1.winId())
        elif sys.platform == "win32": # for Windows
            self.videoPlayer1.set_hwnd(self.videoFrame1.winId())
        elif sys.platform == "darwin": # for MacOS
            self.videoPlayer1.set_nsobject(int(self.videoFrame1.winId()))

        self.videoPlayer1.play()
##########################################################################################################################################
        #adding layout inside Main Frame
        self.mainFrame.setLayout(t_lay_parent)

        #shows the Pyqt frame
        self.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setApplicationName("VLC Test")

    window = MainWindow()
    window.show()
    app.exec_()


text:
Q: How to make my welcome text appear? After login, I want the text "Welcome, Niklas" to display but after logging in I have to reload the page and I didn't understand how to make the page display the text from the server variable current_user. If I login and press reload then the correct welcome message appears. Can you help me achieve what I want? Why is there no simple working example for FB python + javascript? Can I implement facebook connect without javascript? If so, do I have to use and set the cookie myself? Thank you
{% load i18n %}
<!DOCTYPE html>

    <title>
      Test Facebook SDK
    </title>

<fb:login-button autologoutlink="true"></fb:login-button>
{% if current_user %}

{% trans "Welcome," %} {{ current_user.name|escape }}

{% endif %}

Here's how I get the variable current_user
@property
def current_user(self):
    if not hasattr(self, "_current_user"):
        self._current_user = None
        cookie = facebook.get_user_from_cookie(
            self.request.cookies, facebookconf.FACEBOOK_APP_ID, facebookconf.FACEBOOK_APP_SECRET)
        logging.debug("logging cookie"+str(cookie))
        if cookie:
            # Store a local instance of the user data so we don't need
            # a round-trip to Facebook on every request
            user = FBUser.get_by_key_name(cookie["uid"])
            logging.debug("user "+str(user))
            logging.debug("username "+str(user.name))

            if not user:
                graph = facebook.GraphAPI(cookie["access_token"])
                profile = graph.get_object("me")
                user = FBUser(key_name=str(profile["id"]),
                            id=str(profile["id"]),
                            name=profile["name"],
                            profile_url=profile["link"],
                            access_token=cookie["access_token"])
                user.put()
            elif user.access_token != cookie["access_token"]:
                user.access_token = cookie["access_token"]
                user.put()
            self._current_user = user
    return self._current_user

A: When using Oauth 2.0
FB.Init(...oauth=true)

the login button is setting a cookie into your domain named
fbsr_(appid)=....

which is encoded using the app secret key, and which do not contain the user token anymore.
If you really want to avoid the use of java script client side (which is the most simple way) you can leverage the presence of this cookie to know if the user is connected to facebook and then perform any authorization check or dynamically display a welcome message.
I do not use python, so i do not have working example, but this give you a way to search.
Hope this help.


text:
Q: Why in pyqt5 should I use pyuic5 and not uic.loadUi("my.ui")? I've been experimenting with QT5 for Python, using pyqt5.  I've noticed that most tutorials recommend using pyuic5 to convert the XML UI to Python code.  I've also seen a couple of tutorials where instead they use uic.loadUi("myui.ui") to dynamical load the XML UI.  This seems like a cleaner, more modular solution to me, but it appears to be an unpopular option.  Is there a reason converting your code with pyuic5 is a sounder solution?

A: The biggest reason to use pyuic5 is that IDEs (e.g. Visual Studio Code, PyCharm) do not understand .ui files, and therefore cannot provide code introspection (e.g. autocompletion of widget names) for your class unless you compile it to Python.

A: Having looked into this more, for me dynamically loading the form generated by QT Designer is the way to go.  You can get round the problems of not having access to the underlying widgets with commands like this (assuming you have a label called bob_label in your form):
self.bob_label: QLabel = self.findChild(QtWidgets.QLabel, 'bob_label')

In PyCharm, at any rate, this will automatically enable Intellisense (so the IDE now knows that there's a label in the window class called bob_label).  In Visual Studio Code despite great effort I couldn't find a way to get this to work easily, although I did manage it eventually.

A: Both solutions are good, they have advantages and disadvantages that have to be weighed with what you want to do, and many times it will depend on the taste of the programmer.
pyuic5:

*

*Allows inheritance [+]

*There is no additional load when running the application [+]

*Convert the .ui to .py every time the file is modified [-]
uic.loadUi():

*

*You do not have to modify anything when modifying the .ui [+]

*Compilation extra time [-]

*Does not allow inheritance (You could implement the inheritance using uic.loadUiType()) [-]

*Does not allow the use of inspect [-].


text:
Q: the field not updated trigger LeadStatusCheck on Lead ( before update)
{
      List<String> leadEmails = new List<String>();
    for(Lead lead:Trigger.new){
        leadEmails.add(lead.Email);
    }

    List<Contact> contacts = [ SELECT  Id, Email  FROM  Contact WHERE Email =:leadEmails ];

    Set<String> contactEmails = new Set<String>();
    for(Contact contact:contacts){
        contactEmails.add(contact.Email);
        system.debug('contact mail='+ contact.Email);
    }
    Contact con=new Contact();
    for(Lead lead:Trigger.new){
        if(contactEmails.contains(lead.Email))
           {
               system.debug('lead mail='+lead.Email);

                   con.Lead_Status__c =lead.Status;// here i'm assign the value of field ...but value not assign
               system.debug('lead status='+lead.Status);
                   try
                   {
                 update con;
                   }
                   catch(Exception e)
                   {
                       system.debug(con.Lead_Status__c);
                   }

        }
    }
}

A: You are trying to update a contact without giving it an id, there is no way Salesforce can understand which contact to Update.
Issues with the above code :

*

*You need to create a Map of Email to Contact record and in the for
loop if the contact email is equal to lead email, take the contact
record from the map and update its field, this will give reference to
the contact for which you want to update Lead_Status__c field.

*You are creating Contact instance outside of the loop, this will only
create one contact record. Needs bulkification to handle multple
records in trigger.

*Update con is inside a for loop, which can hit the governor limits,
need to be bulkified.
You code should be something like below :
Map<String,Contact> emailToContactMap = new Map<String,Contact>();
List<Contact> contactList = new List<Contact>();//Contacts to be updated
for(Contact contact:contacts){
    emailToContactMap.put(contact.Email,contact);
    system.debug('contact mail='+ contact.Email);
}
//Contact con=new Contact(); this line is not required, as you will get the contact record from map emailToContactMap
for(Lead lead:Trigger.new){
    if(emailToContactMap.contains(lead.Email))
       {
           system.debug('lead mail='+lead.Email);

            Contact contactRec = emailToContactMap.get(lead.Email);// here we are getting the contact record for the email and updating it in the next line
            contactRec.Lead_Status__c =lead.Status;

           system.debug('lead status='+lead.Status);

           contactList.add(contactRec);

    }
}
if(!contactList.isEmpty()){
    update contactList;
}


text:
Q: Displaying notification messages in angular2 app failes I want to implement notification messages for my simple angular 2 app. I decided to use ng2-toasty. My simple angular 2 app is based on ng2-admin theme.

*

*I installed package
npm install ng2-toasty --save

*Import and register ToastyModule in the AppModule

import { ToastyModule } from 'ng2-toasty';
...
 imports: [
    ToastyModule.forRoot(),
]

3. Inside Component I import again Toast service and injected inside constructor

import { ToastyService, ToastyConfig, ToastOptions, ToastData } from 'ng2-toasty';
constructor(private toastyService: ToastyService) { }
...
// This error is raised on purpose inside some method
this.toastyService.error({
      title: 'Error',
      msg: 'An unexpected error occured!',
      theme: 'default',
      showClose: true,
      timeout: 2000
});

Inside app.component.html
I added on top of the file
<ng2-toasty [position="'top-right'"]></ng2-toasty>

I don't get any errors inside console but still notification message is not shown.
  I've found several examples where I need to update systemjs.config.js or webpack.config.vendor.js files but inside this template I cannot find one. What I'm missing here?

A: Change this line of code Inside app.component.html
<ng2-toasty [position] ="'top-right'"></ng2-toasty>

A: Usually when you are trying to import a new module to your app, you just declare it in your app module (or any other module you wish to use it) and then use it.
In your case, ng toasty runs as a service as well, so you will need to import it as a provider too. In your app module providers[] array, add:
providers: [ToastyService] // add ToastyService


text:
Q: Iterating based on a variable number of inner loops In the below code I am trying to go through all possible combination of alphabets for number of characters which are runtime variable.
The purpose of this code is to build a kind of password cracker, which basically brute-force guess the string. I want to use loop, because I will be able to break the loop as soon as the correct combination is hit thus saving on time and resources which otherwise will be required if I try to build an array of all possible combinations in first step.
I have a static code which works for a string 5 characters long but in reality my string could be any length. How can I make my code work with any length of string?
let len = textField.text?.characters.count //Length of string
let charRange = "abcdefghijklmnopqrstuvwxyz" //Allowed characterset

for char1 in charRange.characters {
    for char2 in charRange.characters {
        for char3 in charRange.characters {
            for char4 in charRange.characters {
                for char5 in charRange.characters {
                     // Do whatever with all possible combinations
                }
            }
        }
    }
}

I think I have to utilize for totalChars in 1...len { somehow but can't figure out how the for loops are going to be created dynamically?

A: As suggested by Martin R, you can use recursion
This is the function
func visit(alphabet:[Character], combination:[Character], inout combinations:[String], length: Int) {
    guard length > 0 else {
        combinations.append(String(combination))
        return
    }

    alphabet.forEach {
        visit(alphabet, combination: combination + [$0], combinations: &combinations, length: length - 1)
    }
}

The helper function
func combinations(alphabet: String, length: Int) -> [String] {
    var combinations = [String]()
    visit([Character](alphabet.characters), combination: [Character](), combinations: &combinations, length: length)
    return combinations
}

Test
Now if you want every combination of 3 chars, and you want "ab" as alphabet then
combinations("ab", length: 3) // ["aaa", "aab", "aba", "abb", "baa", "bab", "bba", "bbb"]

Duplicates
Please note that if you insert duplicates into your alphabet, you'll get duplicate elements into the result.
Time complexity
The visit function is invoked as many times as the nodes into a perfect k-ary tree with height h where:

*

*k: the number of elements into the alphabet param

*h: the length param

Such a tree has

nodes. And this is the exact number of times the function will be invoked.
Space complexity
Theoretically The max number of stack frames allocated at the same time to execute visit is length.
However since the Swift compiler does implement the Tail Call Optimization the number of allocated stack frames is only 1.
Finally we must consider that combinations will be as big as the number of results: alphabet^length
So the time complexity is the max of length and elements into the result.
And it is O(length + alphabet^length)

Update
It turns out you want a brute force password breaker so.
func find(alphabet:[Character], combination:[Character] = [Character](), length: Int, check: (keyword:String) -> Bool) -> String? {
    guard length > 0 else {
        let keyword = String(combination)
        return check(keyword: keyword) ? keyword : nil
    }

    for char in alphabet {
        if let keyword = find(alphabet, combination: combination + [char], length: length - 1, check: check) {
            return keyword
        }
    }

    return nil
}

The last param check is a closure to verify if the current word is the correct password. You will put your logic here and the find will stop as soon as the password is found.
Example
find([Character]("tabcdefghil".characters), length: 3) { (keyword) -> Bool in
    return keyword == "cat" // write your code to verify the password here
}

A: Idea: form the string using an array of indices into your alphabet; each time increment the indices.
[0, 0, 0] -> [1, 0, 0] -> [2, 0, 0] ->
[0, 1, 0] -> [1, 1, 0] -> [2, 1, 0] ->
[0, 2, 0] -> [1, 2, 0] -> [2, 2, 0] ->
[0, 0, 1] ... [2, 2, 2]

Here's an example using a length of 3 and an alphabet of abcd
let len = 3
let alphabet = "abcd".characters.map({ String($0) })
var allStrings = [String]()
let maxIndex = alphabet.endIndex
var indicies = Array(count: len, repeatedValue: 0)

outerLoop: while (true) {
    // Generate string from indicies
    var string = ""
    for i in indicies {
        let letter = alphabet[i]
        string += letter
    }
    allStrings.append(string)
    print("Adding \(string)")

    // Increment the index
    indicies[0] += 1

    var idx = 0
    // If idx overflows then (idx) = 0 and (idx + 1) += 1 and try next
    while (indicies[idx] == maxIndex) {
        // Reset current
        indicies[idx] = 0
        // Increment next (as long as we haven't hit the end done)
        idx += 1
        if (idx >= alphabet.endIndex - 1) {
            print("Breaking outer loop")
            break outerLoop
        }
        indicies[idx] += 1
    }
}

print("All Strings: \(allStrings)")

A: Alternative to recursion; loop radix representation of incremental (repeated) traversing of your alphabet
An alternative to recursion is to loop over an numeral representation of your alphabet, using a radix representative for the different number of letters. A limitation with this method is that the String(_:,radix:) initializer allows at most base36 numbers (radix 36), i.e., you can at most perform your "password cracking" with a set of characters with a unique count <=36.

Help function
// help function to use to pad incremental alphabeth cycling to e.g. "aa..."
let padToTemplate: (str: String, withTemplate: String) -> String = {
    return $0.characters.count < $1.characters.count
        ? String($1.characters.suffixFrom($0.characters.endIndex)) + $0
        : $0
}

Main radix brute-force password checking method
// attempt brute-force attempts to crack isCorrectPassword closure
// for a given alphabet, suspected word length and for a maximum number of
// attempts, optionally with a set starting point
func bruteForce(isCorrectPassword: (String) -> Bool, forAlphabet alphabet: [Character], forWordLength wordLength: Int, forNumberOfAttempts numAttempts: Int, startingFrom start: Int = 0) -> (Int, String?) {

    // remove duplicate characters (but preserve order)
    var exists: [Character:Bool] = [:]
    let uniqueAlphabet = Array(alphabet.filter { return exists.updateValue(true, forKey: $0) == nil })

    // limitation: allows at most base36 radix
    guard case let radix = uniqueAlphabet.count
        where radix < 37 else {
        return (-1, nil)
    }

    // begin brute-force attempts
    for i in start..<start+numAttempts {
        let baseStr = String(i, radix: radix).characters
            .flatMap { Int(String($0), radix: radix) }
            .map { String(uniqueAlphabet[$0]) }
            .joinWithSeparator("")

        // construct attempt of correct length
        let attempt = padToTemplate(str: baseStr,
            withTemplate: String(count: wordLength, repeatedValue: alphabet.first!))

        // log
        //print(i, attempt)

        // test attempt
        if isCorrectPassword(attempt) { return (i, attempt) }
    }
    return (start+numAttempts, nil) // next to test
}

Example usage
Example usage #1
// unknown content closure
let someHashBashing : (String) -> Bool = {
    return $0 == "ask"
}

// setup alphabet
let alphabet = [Character]("abcdefghijklmnopqrstuvwxyz".characters)

// any success for 500 attempts?
if case (let i, .Some(let password)) =
    bruteForce(someHashBashing, forAlphabet: alphabet,
               forWordLength: 3, forNumberOfAttempts: 500) {
    print("Password cracked: \(password) (attempt \(i))")
} /* Password cracked: ask (attempt 478) */

Example usage #2 (picking up one failed "batch" with another)
// unknown content closure
let someHashBashing : (String) -> Bool = {
    return $0 == "axk"
}

// setup alphabet
let alphabet = [Character]("abcdefghijklmnopqrstuvwxyz".characters)

// any success for 500 attempts?
let firstAttempt = bruteForce(someHashBashing, forAlphabet: alphabet,
                              forWordLength: 3, forNumberOfAttempts: 500)
if let password = firstAttempt.1 {
    print("Password cracked: \(password) (attempt \(firstAttempt.0))")
}
// if not, try another 500?
else {
    if case (let i, .Some(let password)) =
        bruteForce(someHashBashing, forAlphabet: alphabet,
                   forWordLength: 3, forNumberOfAttempts: 500,
                   startingFrom: firstAttempt.0) {
        print("Password cracked: \(password) (attempt \(i))")
    } /* Password cracked: axk (attempt 608) */
}


text:
Q: Add wmts layer from Geoserver to ArcGIS viewer for Flex Is there anyone out there who has set wmts layer from Geoserver to ArcGIS viewer for flex?
I am trying to do that but without any luck.
<layer label="Sample WMTS layer" type="wmts" visible="true" useproxy="false" imageformat="gif" url="http://v2.suite.opengeo.org/geoserver/gwc/service/wmts" style="_null" servicemode="KVP" layerid="world" tilematrixsetid="EPSG:4326"/>

If I change the type to "wms" it works like a charm.
Anyone?

A: In my project I had to use proxy with WMTS layers, otherwise they would not work.
edit
As noted in the thread in the comment by @user28386:

The issue is likely that the server does have a crossdomain.xml but it
  only has "allow-http-request-headers-from" and does not have an entry
  for "allow-access-from".

and

Unlike  the WMS type, there is no skipgetcababilities attribute. Since
  this is  the case, if the WMTS service does not have a crosdomain file
  associated  with it, you will need to provide a proxy page URL.


text:
Q: Visual Studio debug information not being re-generated after code change I'm having a weird problem in Visual Studio 2008. Every once in a while, after adding/removing some members of a class, when examining the contents of an object of that class in the watch window the changes to that class don't appear to have been recognized. Instead, all of the old members are there, including anything that was removed, and nothing new shows up. Furthermore, the data of the members it shows is messed up, likely because the memory layout of the object has changed.
I've been using Visual Studio 2008 for years and encountered this problem for the first time about a month ago. Re-installing the program did the trick, but now it's cropped up again.
I've tried a full rebuild, deleting the .pdb file, deleting the .ncb file, deleting the .exe, the .obj files, the .sln file, etc. Nothing seems to solve it. Has anyone come across something like this before?
Thanks!
UPDATE
I realized it may not have been obvious from the initial post, so I wanted to clarify that the code behaves correctly, it's just the debugging information that's wrong.
UPDATE Number 2
Just tried downloading Visual Studio 2008 Express Edition, but it has the same problem.

A: So finally I was able to fix this just to moving around some variables in the header file. I'm quite sure I tried this the last time I encountered this problem, but to no avail then. This time, for whatever reason, it seemed to work. Thanks Joachim for your time in trying to help!


text:
Q: Assistance needed with Jquery if statement for calculated fields ow would I write a script that would allow the option of having the user enter a percentage and a dollar amount is calculated or a dollar amount and a percentage is calculated?  Currently my form only allows for the entry of a percentage and the dollar amount is calculated, but I need for the user to be able to enter either and have the form automatically calculate the missing element. Here is the code that I am using to calculate the dollar amount:
    script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  $(".TextBox").hover(function(){
    $(this).toggleClass('TextBoxSelected');
  },function(){
    $(this).toggleClass('TextBoxSelected');
  }).change(function(){
    calculate();
  });
});
function getFldValue(fldValue) {
  return isNaN(fldValue) ? 0 : parseFloat(fldValue);
}
function calculate() {
  var property_SPrice = getFldValue($('#property_SPrice').val());
  var price = getFldValue($('#price').val());

  var REO_sale_percentage    = getFldValue($('#REO_sale_percentage').val());
  var REO_sale_dollars       = getFldValue($('#REO_sale_dollars').val());
  var REO_sale_bonus_dollars = getFldValue($('#REO_sale_bonus_dollars').val());
  var REO_sale_fixed_dollars = getFldValue($('#REO_sale_fixed_dollars').val());
  var REO_sale_total_dollars = getFldValue($('#REO_sale_total_dollars').val());

  var REO_list_percentage    = getFldValue($('#REO_list_percentage').val());
  var REO_list_dollars       = getFldValue($('#REO_list_dollars').val());
  var REO_list_bonus_dollars = getFldValue($('#REO_list_bonus_dollars').val());
  var REO_list_fixed_dollars = getFldValue($('#REO_list_fixed_dollars').val());
  var REO_list_total_dollars = getFldValue($('#REO_list_total_dollars').val());

  var gr_comm_percentage     = getFldValue($('#gr_comm_percentage').val());
  var gr_comm_dollars        = getFldValue($('#gr_comm_dollars').val());
  var gr_bonus_dollars       = getFldValue($('#gr_bonus_dollars').val());
  var gr_fixed_dollars       = getFldValue($('#gr_fixed_dollars').val());
  var gr_total_dollars       = getFldValue($('#gr_total_dollars').val());

  $('#price').val(property_SPrice);
  $('#gr_comm_percentage').val(REO_list_percentage + REO_sale_percentage);

  $('#gr_comm_dollars').val(getFldValue(REO_list_dollars + REO_sale_dollars));
  $('#REO_list_dollars').val(getFldValue(REO_list_percentage/100*price));
  $('#REO_sale_dollars').val(getFldValue(REO_sale_percentage/100*price));
  $('#gr_fixed_dollars').val(getFldValue(REO_list_fixed_dollars + REO_sale_fixed_dollars));
  $('#gr_bonus_dollars').val(getFldValue(REO_list_bonus_dollars + REO_sale_bonus_dollars));
  $('#gr_total_dollars').val(getFldValue(REO_sale_total_dollars + REO_list_total_dollars));
  $('#REO_sale_total_dollars').val(getFldValue(REO_sale_dollars + REO_sale_fixed_dollars + REO_sale_bonus_dollars));
  $('#REO_list_total_dollars').val(getFldValue(REO_list_dollars + REO_list_fixed_dollars + REO_list_bonus_dollars));

}
</script>

A: you could try something like
var fieldvalue= //get the field value
if(fieldvalue.indexOf('%') != -1){
   var percentage = parseFloat(fieldvalue.replace('%',''));
   //do whatever you need with that value
}


text:
Q: Not able to lock orientation for 1 VC I am trying to get device rotation right.

*

*I am testing on iPad 8.x/9.x simulator

*I have 4 VCs

*

*VC1 - Both Portrait and Landscape

*VC2 - Both Portrait and Landscape

*VC3 - Only Portrait

*VC4 - Both Portrait and Landscape

Goal: to have VC3 display PortraitView at all times (same as if app orientation was fixed to portrait).
I tried
@implementation RotationAwareNavigationController

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    UIViewController *top = self.topViewController;
    return top.supportedInterfaceOrientations;
}

-(BOOL)shouldAutorotate {
    UIViewController *top = self.topViewController;
    return [top shouldAutorotate];
}

@end

In VC which is portrait
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

But it does not work meaning view not displayed in Portrait dimensions Am I missing something?
I am sure it can be done as when I use ImagePickerController provided my iOS, it is fixed to Portrait. I just dont know how to do it.

A: To support differing orientations in different view controllers, you will need to do a few things. First, you need to check all the checkboxes for orientations you want to support in your target's General settings tab.
Second, anytime you call presentViewController or dismissViewController in your app, the UIApplicationDelegate method application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask will be called. You can use this method to restrict (or allow) specific orientations each time a new view controller is presented or dismissed. Unfortunately, it isn't as simple as just returning a UIInterfaceOrientationMask here. You will need to find the view controller that is going to be showing on screen and return the orientations that it supports. Here is an example of this:
func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
    guard let window = window, let rootViewController = window.rootViewController else {
        return UIDevice.currentDevice().userInterfaceIdiom == .Pad ? .All : .AllButUpsideDown  // iOS defaults
    }

    // Let the view controller being shown decide what orientation it wants to support. This method will be called anytime a new view controller is presented on screen.
    return findVisibleViewController(rootViewController: rootViewController).supportedInterfaceOrientations()
}

/// Searches the view hierarchy recursively and finds the view controller that is currently showing.
private func findVisibleViewController(rootViewController rootViewController: UIViewController) -> UIViewController {
    if let presentedViewController = rootViewController.presentedViewController {
        // Search for a modal view first.
        return self.findVisibleViewController(rootViewController: presentedViewController)
    } else if
        let navigationController = rootViewController as? UINavigationController,
        let visibleViewController = navigationController.visibleViewController {
        // Then search navigation controller's views to find its visible controller.
        return self.findVisibleViewController(rootViewController: visibleViewController)
    } else if let splitViewController = rootViewController as? UISplitViewController {
        // Then try the split view controller. This will be the true root view controller. Use the master here since the detail just shows web views.
        return self.findVisibleViewController(rootViewController: splitViewController.viewControllers[0])
    } else {
        // Guess we found the visible view controller, because none of the other conditions were met.
        return rootViewController
    }
}

findVisibleViewController(_:) is an example from one of my projects and is tailored to the exact view controller hierarchy in my app. You will need to edit this for your own app in a way that makes sense for your hierarchy.
Third, you will need to implement supportedInterfaceOrientations() for most, if not all, of your view controllers.
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return // portrait, landscape, or combinations of those.
}

Finally, this only handles situations where you presented or dismissed something modally. For show (push) segues, the orientation of the navigation controller will be used for every new view controller pushed onto the stack. If you need more fine grained control here, you will need to force the orientation to happen. Here is an example of that:
// Some other view had the screen in landscape, so force the view to return to portrait
UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation")


text:
Q: Write docm files using Python win32com and python-docx Win32com only works on Windows operating systems and can process docm files.
However, python-docx works on all operating systems and cannot process docm files.
I want to process the docm file using the python-docx file on the Linux server. Is it possible?

A: You can use any third-party components designed for dealing with docm files on Linux. For docx file you may consider using the Open XML SDK as it now supports .NET Standard which is supported by .NET Core on various distros of Linux.


text:
Q: redundant openvpn configuration I have two openbsd nat/firewall boxes with carp for failover / high availability purposes. What would be the best possible practice to ensure that OpenVPN, which I plan on running on these boxes, fails over gracefully as well?

A: Without losing the current session?
Anyways you could always use ifstated(8) to sense the a CARP demotion and start the OpenVPN server.
Actually I don't know if there would be any issues with the MASTER and SLAVE running at the same time the OpenVPN server.

A: OpenVPN doesn't support any kind of state sharing between two different daemon instances, so no, you can't have seamless failover.
But, you can always configure your clients to handle a server failure gracefully. If this kind of redundancy meets your needs, you can achieve it by combining two features that OpenVPN does actually have:
1) automatically re-trying after getting disconnected from the server, AND
 2) connecting to a randomly-chosen server on each attempt, from a pre-defined list.
The basic idea is that you can run two (or three, or more) OpenVPN servers, and add all of their IP addresses or hostnames to your VPN client configurations. Also, the client should re-try quickly in order to minimize the downtime experienced by the user. When one server fails, the client rotates to the next address in its connect-to list, and the connection gets re-established in pretty short order.
The documentation is available at:

*

*http://openvpn.net/index.php/open-source/documentation/manuals/69-openvpn-21.html
In particular, you'll probably want to look at these configuration options:

*

*remote

*connect-retry

*connect-retry-max

*remote-random

*ifconfig-pool-persist

You should be able to add these options, client-side, on top of any combination of other client/server options you might already be using. Just remember to keep 'connect-retry' low, and 'connect-retry-max' high (possibly even infinite), and it should work pretty well.


text:
Q: why does linker have a tougher task in C++ compared to C? The interviewer asked me this question and not sure if my answer to it was good enough or not. Anyone has any ideas?

A: I can't say I understand this very well, but this blog entry by Ian Lance Taylor seems to have an answer.  Quoting from there:

There are some special challenges when using C++. Adding a new virtual method to a class can be an ABI change for any function which uses that class. Providing the backward compatible version of the class in such a situation is very awkward–there is no natural way to specify the name and version to use for the virtual table or the RTTI information for the old version.
Naturally, you must never delete any symbols.

Read the entry for some more context.  (ABI = Application Binary Interface)

A: The first thought that popped in my head was name mangling. In C++ but not in C, you can have two methods with the same name but different parameters. The compiler has to distinguish between the two methods and thus changes (mangles) the name internally.
Another thing that the C++ compiler must do that in not in C, is deal with the class inheritance. You have abstract classes, overridden methods and virtual methods. That takes a little more processing to sort out.


text:
Q: Gitlab CI cache update On GitlabCI I have caching setup and it is working properly:
  cache:
    key: gradle
    paths:
      - .gradle/caches
  before_script:
    - export GRADLE_USER_HOME=`pwd`/.gradle

In order to speed up the process of uploading my cache (<20s); and take advantage of this; I delete the "extra" files which have been updated during the build:
  after_script:
    - rm -rf .gradle/caches/$GRADLE_VERSION/
    - rm .gradle/caches/journal-1/file-access.bin
    - find .gradle/caches/ -name "*.lock" -type f -delete

I expect CI to skip uploading the cache, since none of the files have been updated anymore. i.e.
Result of
    - find .gradle/caches/ -mmin -5 -exec ls -la {} +

is an empty list as well.
But that is not the case and my cache is uploaded on every job.
Am I missing something else? Has anyone else ran into this?


text:
Q: parse cloud code afterSave returns error 107 cannot POST I have problems with afterSave implementing my signup logic.
What I have to do is to add a transaction in Wallet class when user makes the registration, giving him some credits. So i have my cloud code function:

// Add welcome bonus on signup
Parse.Cloud.afterSave(Parse.User, (request) => {
// commit transaction only on signup completed with phone number
  if (request.object.get('username')) {
    const wallet = new Parse.Object('Wallet')

    wallet.set('value', 100)
    wallet.set('action', '+')
    wallet.set('description', 'welcome bonus')
    wallet.set('user', {
       __type: 'Pointer',
       className: '_User',
       objectId: request.object.id
    })

    wallet.save(null,{useMasterKey: true}).then(
      (result) => console.log('objectId',result.id),
      (error) => console.log('code:',error.code,'message:',error.message)
    )
  }
})

Since Parse.Cloud.useMasterKey() is deprecated I follwed the Parse doc on how to use the useMasterKey option on save method, but i still got this error:

info: afterSave triggered for _User for user undefined:
  Input: {...} className=_User, triggerType=afterSave, user=undefined
code: 107 message: Received an error with invalid JSON from Parse: Cannot POST /classes/Wallet

And this is my Wallet table:

| value: Number | action: String | description: String | user: Pointer<_User> |

And the default columns createdAt, updatedAt, objectId and ACL
I'm working on localhost.
Any ideas on what's going on?

A: I would bet this is an issue with the way you're setting the User. If the field is set to be a pointer field to a user object, all you have to do is set wallet.set('user', request.object);  The rest of the request looks fine, so my gut tells me it just isn't liking that JSON format for your set. I.e. when I set a pointer on the dashboard, I just type in the object ID. I don't format it like a pointer.
Also, this is gonna get triggered any time you save a user, so it isn't going to do what you want beyond this issue anyway.


text:
Q: Insert multiple spans inside a shopify liquid template I want to add 3 spans at different places as placeholders inside sections/product-template.liquid template of Shopify using jquery in NodeJS.
The template looks like this.

 <meta itemprop="name" content="{{ product.title }}">
 <meta itemprop="url" content="{{ shop.url }}{{ product.url }}">

{% if collection %}

    {% include 'icon-arrow-left' %}
    {{ 'products.product.back_to_collection' | t: title: collection.title }}

{% endif %}

{% unless product == empty %}

  {{ product | json }}

{% endunless %}

I want to add one span each inside the div, p and span that are shown above.
When I convert the complete string above into jQuery, it gives me access to only the div with class 'product-template__container' but not the other elements which are rendered conditionally inside {%...%}.
How can I add span the conditional elements ?


text:
Q: Is the "Shine" in The Dark Tower related to "The Shining"? In the 2017 film The Dark Tower, Jake's psychic powers are referred to as "The Shine". This has a similar phrasing to "The Shining", which is a story about a boy with psychic powers. Given that both are novels written by Stephen King, and The Dark Tower has a multiple-worlds thing going on, is "The Shine" related to "The Shining"?
I am unfamiliar with Stephen King's works in general and have only seen these two films (and Maximum Overdrive), so I apologize if this is an obvious question.

A: Short Answer: Yes
The dark Tower is the work that connects all Stephen King works

I have written enough novels and short stories to fill a solar system of the imagination, but Roland's story is my Jupiter--a planet that dwarfs all the others . . . a place of strange atmosphere, crazy landscape, and savage gravitational pull. Dwarfs the others, did I say? I think there's more to it than that, actually. I am coming to understand that Roland's world (or worlds) actually contains all the others of my making...
Stephen King

Specifically about the relation between the shine and The Shinning: Jake Chambers (from the Dark Tower) has psychic powers, refered as the Shine, that are similar to those of Danny Torrance (the little fellow on the trycicle that found two charming sisters in a hotel hallway). Danny's powers are called in similar terms:

"You shine on boy, harder than anyone I ever met in my life. […]. You got a knack. […] Me I've always called it shining. That's what my grandmother called it, too. She had it. We used to sit in the kitchen when I was a boy and have long talks without even opening our mouths"

In other King's novel The Stand, prophetic visions are said to be

"the shining lamp of God… sometimes just the shine."

So it seems King is kind of using the shine as a common term for this psychic powers across his universe.
On anoteher note, Jake and Danny are possible twinners: different versions of the same person, living on different levels of the Tower.


text:
Q: Prove that there exist $\alpha < 0$ and $\beta > 0$ such that $Y = [\alpha, \beta]$ Let
$X = \{A = (a_{ij}) \in M_2(\mathbb R): tr(A) = 0 \text{and} |a_{ij}|\leq 2 \forall i,j \}$
Let $Y = \{\det(A) : A \in X\}\subset \mathbb R.$ Then, there exist $\alpha < 0$ and $\beta > 0$ such
that $Y = [\alpha, \beta]$
My attempt.
$M_2(\mathbb R)$~$ \mathbb R^4$
$\because tr(A) = 0$. We get $a_{11}=-a_{22}.$ I know that $f:M_2(\mathbb R) \to \mathbb R: f(A)=\det (A)$ is a continuous map. So, It is enough to prove that $X$ is compact. $O$ matrix is in $X$. So  matrix with $\det(A)=O$  exists.

A: I think it's easier to just break it down into the components.
We have $det(A) = a_{11}a_{22}-a_{12}a_{21}$. By the trace constraint we get that $det(A)=-a_{11}^2-a_{12}a_{21}$. We also know that each entry is smaller than $2$ in magnitude. Since $det(A)$ is a polynomial of these three variables (and hence continuous) and each variable lives in a compact set $[-2,2]$, the values of $det(A)$ form a compact set. More specifically, the image of the product of intervals $[-2,2]^3$ under a polynomial is an interval. Now just show that there is a matrix with $det(A)<0$ and another with $det(B)>0$ and you are done.


text:
Q: Apache .htaccess 301 permanent redirect How can I make it so that whenever a page on mydomain.com is accessed without www to go to www.mydomain.com, please?
Thank you.

A: Try this in your .htaccess file:
Options +FollowSymLinks
RewriteEngine on

# redirect for http
RewriteCond %{HTTP_HOST} ^mydomain\.com$ [NC]
RewriteCond %{SERVER_PORT} =80
RewriteRule ^/?(.*)$ http://www.mydomain.com/$1 [R=301,QSA,L,NE]

# redirect for https
RewriteCond %{HTTP_HOST} ^mydomain\.com$ [NC]
RewriteCond %{SERVER_PORT} =443
RewriteRule ^/?(.*)$ https://www.mydomain.com/$1 [R=301,QSA,L,NE]

R=301 will redirect with https status 301
L will make last rule
NE is for no escaping query string
QSA will append your existing query parameters
$1 is your REQUEST_URI


text:
Q: Python won't print expression So, I'm kind of new to programming and have been trying Python. I'm doing a really simple program that converts usd to euroes.
This is the text of the problem that I'm trying to solve

You are going to travel to France. You will need to convert dollars to euros (the
  currency of the European Union). There are two currency exchange booths. Each has
  a display that shows CR: their conversion rate as euros per dollar and their fee as a
  percentage. The fee is taken before your money is converted. Which booth will give
  you the most euros for your dollars, how many euros, and how much is the difference.
  Example 1:
  Dollars: 200
  CR1: 0.78
  Fee: 1 (amount 152.88 euros)
  CR2: 0.80
  Fee: 3 (amount 155.2 euros)
  Answer: 2 is the best; difference is 2.32 euros; 155.2 euros

And here is my code
    from __future__ import division

usd = int(input("How much in USD? "))
cr1 = int(input("What is the convertion rate of the first one? "))
fee1 = int(input("What is the fee of the first one? "))

cr2 = int(input("What is the convertion rate of the second one? "))
fee2 = int(input("What is the fee of the second one? "))

def convertion (usd, cr, fee):
    usdwfee = usd - fee
    convert = usdwfee * cr
    return convert

first = convertion(usd, cr1, fee1)
second = convertion(usd, cr2, fee2)

fs = first - second
sf = second - first

def ifstatements (first,second,fs,sf):
    if first < second:
        print "1 is the best; difference is ",fs," euroes. 2 converts to ",first," euroes."
    elif first > second:
        print "2 is the best; difference is",sf," euroes. 2 converts to", second," euroes."

ifstatements(first, second, fs, sf)

The problem is that when I run the program it won't print out. It just takes my input and doesn't output anything.

A: Check your logic more.
cr1 = int(input("What is the convertion rate of the first one? "))
Your conversion rate is in int. As in Integer which means it can't have a floating point (a decimal "CR1: 0.78" from your example). Your cr1 will become 0 if you cast it into an int. Also change your dollar and fees to accept floats too since I'm assuming you want to deal with cents too
So change:
usd = float(input("How much in USD? "))
cr1 = float(input("What is the convertion rate of the first one? "))
fee1 = float(input("What is the fee of the first one? "))

cr2 = float(input("What is the convertion rate of the second one? "))
fee2 = float(input("What is the fee of the second one? "))

And it should work.


text:
Q: MSPGCC error trying to use -mlarge flag, conflict with -msmall being default setting I am currently having an issue with trying to use the -mlarge flag with the MSPGCC compiler on an MSP430, its throwing the following error for all the generated objects in my code:
/user/local/ti/msp430-gcc/bin/../lib/gcc/msp430-elf/9.3.1/../../../../msp430-elf/bin/ld: error: /home/ewheatland/repos/Embedded/driverlib/MSP430FR2xx_4xx/lib/adc.o uses the small code model whereas /usr/local/ti/msp430-gcc/bin/../lib/gcc/msp430-elf/9.3.1/../../../../msp430-elf/lib/large/crt0.o uses the large code model
I believe this is due to -msmall being the default configuration however Im not sure how to change it to -mlarge when compiling.
Ive currently tried passing the flag -mlarge to the linker as well using: -Wl,-mlarge however that ended up not being a valid flag for the linker.


text:
Q: Wired connection recognized but no internet access Let me start by saying, I'm very new to all of this and not as tech savvy as I'd like to think. So,  if you ask me to show you specifics,  I may not immediately now how to show you.
Anyway, I built my very first computer yesterday. I had heard good things about Ubuntu from my friends that use Linux so I decided to give it a try. Besides,  a small donation versus $200 was no contest. The installation went fine but it wouldn't recognize my wired connection. After hours of going through forums I finally got it to connect. Although, if I mess with it at all, it disconnects and I have to restart my computer. I opened Firefox and there was no internet. I opened the other browser that comes pre-installed and nothing. I went through a few similar threads but didn't find anything that worked. Or maybe my brain was just exhausted.
Here's what I'm using:
Gigabyte 990FX-UD3 R5 motherboard
AMD FX 9590 Black Edition pcu
2 Sapphire Nitro R9 390 gpu's
16 GB RAM
Ubuntu 16.04 LTS
I didn't install a wireless card because I planned on using a wired connection
I would appreciate any help. I won't mind if you talk to me like a 3 yr old.