text:
Q: Python module import - why are components only available when explicitly imported? I have recently installed scikit-image version 0.11.3. I am using python 2.7.10. When I import the entire module I cannot access the io module.
import skimage
img = skimage.io.imread(path_)

Gives error:
AttributeError: 'module' object has no attribute 'io'

However the following does not error.
from skimage import io
img = io.imread(path_)

Question: Why?

A: Quick answer: IO is a submodule. Submodules need to be imported from the parent module explicitly.
Long answer: From section 5.4.2 of the python docs:
When a submodule is loaded using any mechanism (e.g. importlib APIs, the import or import-from statements, or built-in import()) a binding is placed in the parent module's namespace to the submodule object. For example, if package spam has a submodule foo, after importing spam.foo, spam will have an attribute foo which is bound to the submodule. Let's say you have the following directory structure:
spam/
    __init__.py
    foo.py
    bar.py

and spam/init.py has the following lines in it:
from .foo import Foo
from .bar import Bar

then executing the following puts a name binding to foo and bar in the spam module:
>>>
>>> import spam
>>> spam.foo
<module 'spam.foo' from '/tmp/imports/spam/foo.py'>
>>> spam.bar
<module 'spam.bar' from '/tmp/imports/spam/bar.py'>

Given Python's familiar name binding rules this might seem surprising, but it's actually a fundamental feature of the import system. The invariant holding is that if you have sys.modules['spam'] and sys.modules['spam.foo'] (as you would after the above import), the latter must appear as the foo attribute of the former.

A: It's simply the way Python handles modules.
One reason is that it would make importing one module very slow if cpython needed to scan for submodules, import all of them and then import all of their submodules.
The other reason is "better be explicit than implicit". Why should Python import everything possible when you only need a small fraction of a package with a complex module hierarchy.
Instead of from skimage import io you can also write
import skimage.io

then skimage.io.imread will be found.


text:
Q: Re-apply layout of a dynamically added UserControl after calling ApplyResources In a WinForms application, a Panel is used as a placeholder to display a single User Control as a navigation strategy: whenever the user wishes to navigate to a given area, the respective User Control is added to the Panel. Simplified:
contentPanel.Controls.Clear();
userControl.Dock = DockStyle.Fill;
contentPanel.Controls.Add(userControl);

As a result of a requirement that is out of my control, the Form must support switching the language dynamically. This is implemented and working fine using Hans Passant's answer, with a modification to use the User Control's Resource Manager, which correctly gets and applies the localized text to controls.
After applying the resources from the User Control's respective resource file, however, the layout resulting from DockStyle.Fill is lost for the User Control's constituent controls that are not themselves set to have a DockStyle.Fill. This has the effect that controls no longer stretch to fill the available area, and are limited to the original size defined in the designer/resource file. Note that the Dock property of the User Control is still set correctly to DockStyle.Fill after applying the resources.
I created an example application which illustrates/reproduces the problem: the form below has a panel to which a user control is added dynamically and set to DockStyle.Fill. The user control has a label which is anchored top left on the Default locale and top right in the German locale. I would expect the form to snap the label which is anchored to the right against the right margin of the form, but the size of the user control is reset to the value at design time. View source code.

If I start the form on the German locale, the label is correctly laid out against the right edge of the form:

What I'd like to happen is that the layout is retained after calling ApplyResources. Of course I could simply make a copy of the controls' Location and Size properties (as suggested in another answer to the same question mentioned above) but unfortunately values of these properties differ between locales. So, after the localized string and positioning are applied, how can the User Control be directed to layout all its controls anew?
What I've tried

*

*By looking into InitializeComponent(), I've tried calling PerformLayout() to the Panel container, the User Control, and the Form to no avail.

*Adding SuspendLayout() and ResumeLayout(true) before and after the call to ApplyResources, also without success.

Additional implementation details

*

*References to instantiated User Controls are kept in a private dictionary in the Main Form. When navigation for that control is raised, the previous user control is removed and the existing reference added with the snippet above.

*Reacting to the user event of changing the language:
protected virtual void OnChangeCulture(CultureInfo newCulture)
{
    System.Threading.Thread.CurrentThread.CurrentCulture = newCulture;
    System.Threading.Thread.CurrentThread.CurrentUICulture = newCulture;

    SuspendLayout();
    ComponentResourceManager resources = new ComponentResourceManager(this.GetType());
    ApplyResources(resources, this, newCulture);
    ResumeLayout(true);
}

*Applying the resources to all controls in the form:
private void ApplyResources(ComponentResourceManager resourceMgr, Component target, CultureInfo culture)
{
    //Since target can be a Control or a Component, get their name and children (OMITTED) in order to apply the resources and recurse
    string name;
    IEnumerable<Component> children;

    //Have the resource manager apply the resources to the given target
    resourceMgr.ApplyResources(target, name, culture);

    //iterate through the collection of children and recursively apply resources
    foreach (Component c in children)
    {
        //In the case of user controls, they have their own ResourceManager with the translated strings, so get it and use it instead
        if (c is UserControl)
            resourceMgr = new ComponentResourceManager(c.GetType());

        //recursively apply resources to the child
        this.ApplyResources(resourceMgr, c, culture);
    }
}

Many thanks in advance for any pointers!

A: I can suggest the following custom extension method:
using System.ComponentModel;
using System.Globalization;

namespace System.Windows.Forms
{
    public static partial class Extensions
    {
        public static void ApplyResources(this Control target, CultureInfo culture = null)
        {
            ApplyResources(new ComponentResourceManager(target.GetType()), target, "$this", culture);
        }

        static void ApplyResources(ComponentResourceManager resourceManager, Control target, string name, CultureInfo culture = null)
        {
            // Preserve and reset Dock property
            var dock = target.Dock;
            target.Dock = DockStyle.None;
            // Reset Anchor property
            target.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            // Have the resource manager apply the resources to the given target
            resourceManager.ApplyResources(target, name, culture);
            // Iterate through the collection of children and recursively apply resources
            foreach (Control child in target.Controls)
            {
                if (child is UserControl)
                    ApplyResources(child, culture);
                else
                    ApplyResources(resourceManager, child, child.Name, culture);
            }
            // Restore Dock property
            target.Dock = dock;
        }
    }
}

The essential changes are two.
First, since the stored location/sizes are relative to the container design size (before being docked), we preserve the Dock property, reset it to None during the ApplyResources calls to the control and its children, and finally restore it to the current value.
This basically resolves the issue with right anchor. However, since Windows Forms designer doesn't save property values having default values, and the default value for Anchor property is AnchorStyles.Top | AnchorStyles.Left, it's not stored and hence is not set correctly (when going from German to English in your sample).
So the second fix is to simply reset it to its default value before ApplyResources call.
The usage is simple:
protected virtual void OnChangeCulture(CultureInfo newCulture)
{
    System.Threading.Thread.CurrentThread.CurrentCulture = newCulture;
    System.Threading.Thread.CurrentThread.CurrentUICulture = newCulture;

    SuspendLayout();
    this.ApplyResources(); // <--
    ResumeLayout(true);
}

Note that SuspendLayout and ResumeLayout calls are not essential - it works with or without them. They are used to eventually prevent flickering, which doesn't happen in your example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Allocate an ArrayList Values to Another I have many functions that take a global ArrayList as an argument, some of them don't make any change of this list, and others are need to remove some elements of this array while working, so i create a local tempArrays inside these function.
static ArrayList array1 = new ArrayList();

public fn1(ArrayList array1)
{
   ArrayList tempArray1 = new ArrayList();
   tempArray1 = array1;
   tempArray1.remove(elemnt);
}

The problem is the deleted elements is deleted also from original arrayList array1, i don't know why? .
Thanks..

A: In line :
tempArray1 = array1;

You are making the tempArray1 variable to refer the same object of ArrayList to which array1 is referencing. Hence both are referencing the same object of ArrayList. Any change made in ArrayList object using any of the variables, would be reflected by both variables. So when you removing an element using:
tempArray1.remove(elemnt);

array1 is also reflecting that removal of element.
You should use:
ArrayList tempArray1 = new ArrayList(array1);

As specified in official documentation : ArrayList(Collection<? extends E> c) :

Constructs a list containing the elements of the specified collection,
  in the order they are returned by the collection's iterator.
Parameters:
      c - the collection whose elements are to be placed into this list

A: The problem is that declaring tempArray1 = array1; simply makes tempArray1 a reference to array1.
To create a true copy, call this:
ArrayList tempArray1 = new ArrayList(array1);

A: try to do the following
List tempList = new ArrayList(oldArrayList);

A: The reason why the item is deleted from the original ArrayList is because, in Java, variables of reference types (arrays, Strings, and anything else which is a subclass of Object) hold references, not values. What that essentially means is that a variable of type ArrayList holds the memory address at which the data for the ArrayList is allocated. When you do tempArray1 = array1;, you're just giving tempArray1 the address of the same ArrayList. This all only applies to types that derive from Object in Java, which does happen to include String, if you didn't know. Primitive types (byte, short, int, long, char, float, double) are stored as values.
Now, onto your real problem; I must ask, why you don't just use the get(index) method to work with the item?
If you need to actually remove the element, use the copy constructor of ArrayList, like so:
ArrayList tempArray1 = new ArrayList(array1);

A: I think there are some fatures of Java that you have misunderstood:

*

*When you declare a Java variable, it is a refenrence for an object, like a pointer in C/C++. It can be a referance to previously created object or you can create a new object to referance.
//Created a new object instance on heap
ArrayList tempArray1 = new ArrayList();
//Both tempArray1 and tempArray2 will point to same object in memory
ArrayList tempArray2 = tempArray1;

In your code you first creating a new ArrayList object referance tempArray1 and creating an a new object for it ArrayList tempArray1 = new ArrayList(); and than assigning an other referance to this referance by tempArray1 = array1;. So first object you have created has no reference that point it and will be deleted. Now both tempArray1 and tempArray2 are pointing the same oject.

*In Java If you want to make a copy of an object you can use it's clone method if it has implemented the Clonable interface. Also look at this question for detailed answers about cloning How do I copy an object in Java?
So you want to make a copy of your array but you are doing it wrong.

A: You are replacing the instance you created with the global one. Try with this:
ArrayList tempArray1 = new ArrayList(array1);
tempArray1.remove(elemnt);

A: You can also use the addAll(Collection c) Method
static ArrayList array1 = new ArrayList();

public fn1(ArrayList array1)
{
   ArrayList tempArray1 = new ArrayList();
   tempArray1.addAll(array1);
   tempArray1.remove(elemnt);
}

A: A) tempArray1 is a variable that refers to the same instance as array1. To make a copy, use the copy constructor:
List tempArray1 = new ArrayList(tempArray1);

B) Remove the parameter from the method. There is no need to pass the list in - code in the method already has access to the list. In fact, by passing it in using a parameter with the same name, you are shadowing the original list - if a different list was passed in, you would be working with that instead of the list you think you're working with.
C) You should  type your list, for example:
static ArrayList<String> array1 = new ArrayList<String>();

D) Always use the abstract class: change it to List:
static List<String> array1 = new ArrayList<String>();

E) A list is not an array, so don't call the variable "array1" - its misleading:
static List<String> list1 = new ArrayList<String>();


text:
Q: android why sending information to server works with WIFI only? I am sending information to a server via WIFI and everything works great.Now i want to send information to a server with mobile data too, and i do not know why only works with WIFI, with mobile data trows an exception of failed to connect to server.
this is the part that fail with mobile data; with WIFI works perfectly:
int length=values.length();
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams,9000);
    HttpConnectionParams.setSoTimeout(httpParams, 9000);

    HttpClient client = new DefaultHttpClient(httpParams);

    String url = saveData+"?Length="+length+"&Table="+temp;
    HttpPost request = new HttpPost(url);
    request.setEntity(new ByteArrayEntity(values.toString().getBytes("UTF8")));
    request.setHeader("json", values.toString());
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    // If the response does not enclose an entity, there is no need
    Log.d("test 7","test 7 last");
    if (entity != null) {
        InputStream instream = entity.getContent();
        String result =  RestClient.convertStreamToString(instream);
        Log.d("here",""+result);
        if(result.equals("success")&& ReadyOff==false){
            Ready=true;
        }else{
            Ready=false;
            ReadyOff=true;
        }
        Log.d("sent","valor de ready"+Ready);
    }

so i am doing something wrong?
`

A: You cannot contact your server from the device's mobile network unless it is routable from the public Internet.
A server running on your development machine or otherwise behind a NAT/firewall would typically only be accessible from your local network / wifi.


text:
Q: Arranging the stacks in a stacked bargraph according to the value of one variable I am trying to write a function that outputs a stacked bar graph at the end, where the stacked bar graph has its' bars ordered going from the greatest percentage to the smallest percentage of one specific variable. I have not been able to find a general way to do this and my ultimate goal is to have this process done in a way where it requires the least amount of human input.
My data looks like this
 Swimming_style     Comfort_level_label    Comfort_level_scale    n     Total_n       Percentage
 Front Crawl        Excellent              3                     7       10          70
 Front Crawl        Good                   2                     3       10          30
 Backstroke         Excellent              3                     4       10          40
 Backstroke         Good                   2                     4       10          40
 Backstroke         Fair                   1                     1       10          10
 Backstroke         Poor                   0                     1       10          10
 Brest stroke       Excellent              3                     6       10          60
 Brest stroke       Fair                   1                     4       10          40
 Butterfly          Good                   2                     7       10          70
 Butterfly          Fair                   1                     1       10          10
 Butterfly          Poor                   0                     2       10          20

So far, this is my code:
 data <- arrange(data, Comfort_level_label, (Percentage))
 data$Swimming_style <- factor(data$Swimming_style, levels = unique(data$Swimming_style))

 ggplot(data, aes( x = Swimming_style, y = n, fill = Comfort_level_label)) +
      geom_bar(position = "fill",stat = "identity") +
      scale_y_continuous(labels = scales::percent_format())+
     coord_flip()

Which outputs this:

But what I need the graph to do is sort by the Excellent rating from most Excellent on top to least or no Excellent on the bottom, and I'm having trouble doing exactly that.

A: It can be a little ambiguous, but the important thing when prioritizing is to ensure you always have exactly one of each of the factors.
library(dplyr)
SS <- dat %>%
  arrange(-Comfort_level_scale, -n) %>%
  group_by(Swimming_style) %>%
  slice(1) %>%
  ungroup() %>%
  arrange(Comfort_level_scale, n) %>%
  pull(Swimming_style)

library(ggplot2)
dat %>%
  mutate(Swimming_style = factor(Swimming_style, levels = SS)) %>%
  ggplot(aes( x = Swimming_style, y = n, fill = Comfort_level_label)) +
  geom_bar(position = "fill",stat = "identity") +
  scale_y_continuous(labels = scales::percent_format()) +
  coord_flip()

BTW: should Brest stroke be Breast stroke?

library(dplyr)
dat <- read.table(header=TRUE, stringsAsFactors=FALSE, text="
 Swimming_style     Comfort_level_label    Comfort_level_scale    n     Total_n       Percentage
 Front_Crawl        Excellent              3                     7       10          70
 Front_Crawl        Good                   2                     3       10          30
 Backstroke         Excellent              3                     4       10          40
 Backstroke         Good                   2                     4       10          40
 Backstroke         Fair                   1                     1       10          10
 Backstroke         Poor                   0                     1       10          10
 Brest_stroke       Excellent              3                     6       10          60
 Brest_stroke       Fair                   1                     4       10          40
 Butterfly          Good                   2                     7       10          70
 Butterfly          Fair                   1                     1       10          10
 Butterfly          Poor                   0                     2       10          20") %>%
  mutate(Swimming_style = gsub("_", " ", Swimming_style))


text:
Q: A func in a Singleton does not works As the title suggest I'm occurred in a little problem with a fun in a singleton. this is my code:
    import UIKit

class InterfaceManager: NSObject
{
    class var sharedInstance: InterfaceManager
    {
        get
        {
            struct Static
            {
            static var instance: InterfaceManager? = nil
            static var token: dispatch_once_t = 0
            }
            dispatch_once(&Static.token) { Static.instance = InterfaceManager()
            }
            return Static.instance!
        }
    }

    func chooseAttributedString(string: NSString, font: UIFont, color: UIColor)
    {
        let string: NSString = string
        var stringMutable = NSMutableAttributedString()
        stringMutable = NSMutableAttributedString(string: string as String , attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color])
    }
}

but when I'm going to call the method in a class Xcode gives me an error "Extraneous argument label 'string' in call". following my lines code:
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CellSquadreController
        let squadra = DataManager.sharedInstance.arrayCori[indexPath.row]

        cell.backgroundColor = UIColor.clearColor()
        cell.nomeSquadra.attributedText = InterfaceManager.sharedInstance.chooseAttributedString(string: squadra.nome, font: UIFont(name: "Noteworthy-Light", size: 23)!, color: UIColor.whiteColor())
        return cell
    }

PS: I've just revised a little mistake, but but still it does not work...

A: You forgot to access the sharedInstance:
InterfaceManager.sharedInstance.chooseAttributedString(squadra.nome, font: UIFont(name: "Noteworthy-Light", size: 23)!, color: UIColor.whiteColor())


text:
Q: .Net equivalent of the vb6 Tab control paradigm My co-workers are used to using tab controls with the tab height set to zero in vb6 to allow multiple panels overlayed on one form and now want to do the same in .Net. Unfortunately they've been confused by the fact that there are some extra hoops you have to jump though to make it work the same way.
A bit of judicious googling solved the problem, but VB.net just doesn't seem geared towards this method of managing space on a form. Does anyone have any advice on the best way of arranging what used to be multiple layers of panels within one tab control in .net? (or is still widely accepted as a good way of doing things?)

A: You could make different user controls so to separate logic and decouple things if and as much as possible then in a tab control you display those user controls in the pages. But if you are making kind of wizard like interface there are specific and better approaches to use.

A: As Davide said, you can use different controls and load and unload via code.
You can also use layout panels with similar results, although that is more difficult to use (in the GUI editor.)
.Net also has a tab control which can provide multiple pages of controls on the same form, but I've never tried it without the tabs.  I have, in the past, disabled the tabs which do not have input focus, but that sort of defeats the purpose of tab controls.
I would tend to make a separate form for each user screen.  It's cleaner, easier, and more extensible.  Maintain the program state in a class and have the class invoke the forms.


text:
Q: Unable to see the value in output I have been trying to figure out why this is not visible in the output, most likely its something to do with asynchronous nature of react, which is good. But what do need to do to show the contents up?
The Description column is blank!
https://codesandbox.io/embed/vibrant-field-700k2?fontsize=14&hidenavigation=1&theme=dark
There is a usertable with master data:
{usrData.map((prop, key) => {
            return (

                {prop.id}
{/* Returns Data */}

                  {
                    selectTimeOptions.filter(
                      dealer => dealer.value === prop.time_slot
                    )[0].label
                  }

                {/* To double check data is present */}
                {prop.customergarage}

                  {/* Does not return or show data */}
                  {/* But data visible in console */}
                  {[...prop.customergarage].forEach(d => {
                    if (parseInt(d, 10) > 0) {
                      const retrs = sTypes.filter(st => st.value === d)[0];
                      console.log(retrs);
                      return retrs;
                    }
                  })}

            );
          })}

Any explanations and/or fixes? Specially how to use React.useEffect() here?

A: I don't know what you want to do with useEffect here, but I will try to explain why it is not rendering.
First of all, forEach does not work that way, so you cannot return from it.
Second, you can resolve all your issues with a function that builds the internal part.
buildCustomerData = (customergarage) => {
const good = [];
customergarage.forEach(d => {
                    if (parseInt(d, 10) > 0) {
                      const retrs = sTypes.filter(st => st.value === d)[0];
                      console.log(retrs);
                      good.push(retrs)
                    }
                  })
  return good;
}

{usrData.map((prop, key) => {
            return (

                {prop.id}
{/* Returns Data */}

                  {
                    selectTimeOptions.filter(
                      dealer => dealer.value === prop.time_slot
                    )[0].label
                  }

                {/* To double check data is present */}
                {prop.customergarage}

                  {/* Does not return or show data */}
                  {/* But data visible in console */}
                  {buildCustomerData(prop.customergarage)}

            );
          })}

Just a map wont do the work in the internal loop, because you will have cases where your conditions will not be met.


text:
Q: WampServer : Your Port 80 is actually used by Microsoft-HTTPAPI/2.0 I've uninstalled my WampServer 2.5 and installed version 3.0
But apache service isn't running and tray icon is orange...
Clicking on test port 80 gave me the following cmd output :
***** Test which uses port 80 *****
===== Tested by command netstat filtered on port 80 =====
Test for TCP
Your port 80 is used by a processus with PID = 4
The processus of PID 4 is 'System' Session: Services
The service of PID 4 for 'System' is 'N/A'
*** ERROR *** This service IS NOT from Wampserver - Should be: 'wampapache'
Test for TCPv6
Your port 80 is used by a processus with PID = 4
The processus of PID 4 is 'System' Session: Services
The service of PID 4 for 'System' is 'N/A'
*** ERROR *** This service IS NOT from Wampserver - Should be: 'wampapache'
===== Tested by attempting to open a socket on port 80 =====
Your port 80 is actually used by :
Server: Microsoft-HTTPAPI/2.0

Press Enter to exit...

ISS Service has been disabled before and the Activation Windows service process too by the wampserver forum.
What is the problem then ??

A: I had the same problem, and found out that the culprit was the BranchCache (PeerDistSvc) service.
After stopping that, WAMP starts up correctly on port 80.

A: Watch this Video on Youtube:
https://youtu.be/CMIC1UMONEk
the answer is when you install the SQL MANAGEMENT SERVER OF ANY VERSION
new SET OF SERVICES IS been added
WE HAVE TO STOP THE SERVICE SQL SERVER REPORTING SERVICES MSSQLSERVER
Step 1:
Normal process:
Control Panel.. All Control Panel Items...Administrative Tools
....Select Services
or for fast result
in run Type services.msc
Step 2
select show hidden icons
left click on wamp server icon
apache ....service ...install service

A: Update 2017- Wamp version 3.0.6
Right click on Wamp--> tool--> apache section-->use a port other than 80

Now listen to
http://localhost:7080/phpmyadmin/

A: There is more than one service that could be causing this. Try opening cmd or PowerShell (remember about administrator rights) and run:
NET stop HTTP

It will stop service that is running on port 80 and will display every service that was disabled to achieve that, simply disable that services for future and that should solve your issue.

A: Ok so that means your system has Microsoft IIS installed or one of the other bits of MS technology that reports that signature, they are doing that on later versions of Windows for some reason.
If you are not intending to use it you can uninstall it, it is not an integral part of windows so its being uninstalled wont effect normal operations of windows,
and if you need to install it again later, it comes as part of the standard OS so you wont need to do anything perticularly clever.
So go to Start -> Control Panel -> Programs and Features
Click the 'Turn windows features on and off' link in the left hand menu.
Wait for the list to load and then find 'Internet Information Services'
Un check the check boxes for the following items ( you may not see all of them ), and there may be others I done know about. You may have all of these or just some of these.

*

*IIS

*Web Deploy 2.0 (Web Deployment Agent Service)

*MS Sql Server Reporting service.

*BranchCache ( Windows 8.1 )

*SQL Server VSS Writer

List of possible service names not sure how up to date this is.
Tutorial on how to find what ports are in use on your system and what app is using them
Windows will then have a think for a while and then remove those applications, you will probably be asked to reboot to complete the uninstalls.
Reboot anyway when the uninstalls are complete.
Then try wamp again.
Alternativeley just disable it/them.
Start -> Control Panel -> Administrative Tools -> Services
Find IIS in the list of services.
Left Click that line and select Properties
Change the 'Startup Type' to disabled.
Ditto for the other possibilities if you see them.

A: The Microsoft Hyper-V creates tasks/services on port 80. I still dont know the exact name (and probably wont look out for it), but unnistalling the hyper-v worked just fine for me.
In case anyone else had the same problem, theres another tip.


text:
Q: how to read data from file line by line and storing each token in a line in vectors for further use(c++) I have data in the following format  (N  Snode Sterminal Dnode Dterminal):
5
4
1   2  3  4  5
6  7  8  9  10
11 12 13 14 15
...
For the first step, I am trying to read line by line but in my output I could only output the last line but not the rest. After reading line by line, I have to store each column into vectors.
my code:`
using namespace std;

int main(){
    int cell, con, N,Snode,Sterminal,Dnode,Dterminal;
    ifstream infile;
    infile.open("file");
    infile >>cell;
    cout<<cell<<endl;
    infile >>con;
    cout<<con<<endl;
    while(infile>>N>>Snode>>Sterminal>>Dnode>>Dterminal);
        {
            cout<< N <<"\t"<< Snode<<"\t" << Sterminal<<"\t" << Dnode<< "\t" << Dterminal <<endl;
        }
}

`
my output:
5
4
3  5  6  7  8 //last line in the file
I further want Snode, Dnode, Sterminal, Dterminal as vectors so that i can save the respective columns in it.


text:
Q: Find and replace text in array Using PHP I need to itinerate an array to remove the last two slash of every value from this:
$my_array = array(
     'http://apinmo.com/1/2/3.jpg',
     'http://apinmo.com/4/5/8.jpg',
     'http://apinmo.com/10/9/3.jpg',
     'http://apinmo.com/76/534535/6-1.jpg'
);

to this:
$my_new_array = array(
     'http://apinmo.com/123.jpg',
     'http://apinmo.com/458.jpg',
     'http://apinmo.com/1093.jpg',
     'http://apinmo.com/765345356-1.jpg'
);

How can get this?

A: You can try this with regex by removing / between the digits.
$my_array = array(
     'http://apinmo.com/1/2/3.jpg',
     'http://apinmo.com/4/5/8.jpg',
     'http://apinmo.com/10/9/3.jpg',
     'http://apinmo.com/76/534535/6-1.jpg'
);

$new = array_map(function($v) {
     return preg_replace('/(?<=\d)\/(?=\d)/', '', $v);
}, $my_array);

Output
array(4) {
  [0]=>
  string(25) "http://apinmo.com/123.jpg"
  [1]=>
  string(25) "http://apinmo.com/458.jpg"
  [2]=>
  string(26) "http://apinmo.com/1093.jpg"
  [3]=>
  string(33) "http://apinmo.com/765345356-1.jpg"
}

And also you can't have - in variable names.
Update
$new = array_map(function($v) {
     $temp = preg_replace('/(?<=\d)\/(?=\d)/', '', $v);
     return str_replace('http://', '', $temp);
}, $my_array);

echo implode(', ', $new);

Output
apinmo.com/123.jpg, apinmo.com/458.jpg, apinmo.com/1093.jpg, apinmo.com/765345356-1.jpg

A: $mya = array(
         'http://apinmo.com/1/2/3.jpg',
         'http://apinmo.com/4/5/8.jpg',
         'http://apinmo.com/10/9/3.jpg',
         'http://apinmo.com/76/534535/6-1.jpg'
    );

    foreach($mya as $my)
    {
        $myb[] = preg_replace("~\/(?!.*\/)~","",preg_replace("~\/(?!.*\/)~", "",$my));
    }

    print_r($myb);

A: You should use a regex replace like this:
preg_replace("#([0-9\-]+)/([0-9\-]+)/([0-9\-]+).([a-z]+)#", "$1$2$3.$4", $url);

A: simply use pathinfo like this..
$my_array = array(
     'http://apinmo.com/1/2/3.jpg',
     'http://apinmo.com/4/5/8.jpg',
     'http://apinmo.com/10/9/3.jpg',
     'http://apinmo.com/76/534535/6-1.jpg'
);
$tmp=array();
foreach( $my_array as $url ){
    $tmp[]= pathinfo( $url, PATHINFO_DIRNAME ).pathinfo( $url, PATHINFO_BASENAME );
}
print_r($tmp);


text:
Q: How to transform a vector using a dataframe(associate table) in R language? For example, I have a dataframe like this (the content of V1 is not the same as line number):
V1 V2 V3
1 cat animal
3 dog animal
4 apple fruit

And a vector like this:
c(4,1,3)

Is there an easy way to get a vector like this in R?
c("fruit:apple", "animal:cat", "animal:dog")

I tried ==(my_frame$V1==my_vector) but found that can't be used for two vectors..

A: Something like this works:
## my_dat <- read.table(text="V1 V2 V3
## 1 cat animal
## 2 dog animal
## 3 apple fruit", header=T)
##
## my_vect <- c(3,1,2)

library(qdap)  #for paste2 function
paste2(my_dat[sapply(my_vect, function(x) which(x == my_dat[, 1])), 3:2], sep=":")
## [1] "fruit:apple" "animal:cat"  "animal:dog"

First I match the my_vect with the column 1 of my_dat using sapply, which and ==.  This tells the order to grab in:
sapply(my_vect, function(x) which(x == my_dat[, 1]))
## [1] 3 1 2

Then I index and grab only the last two columns in the order you requested (3rd col. then 2nd)
my_dat[sapply(my_vect, function(x) which(x == my_dat[, 1])), 3:2]

##       V3    V2
## 3  fruit apple
## 1 animal   cat
## 2 animal   dog

Then I use paste2 from the qdap package to bind the columns together without specifying the specific columns (just being lazy; you could accomplish this with base paste by explicitly stating the vectors.

A: @Firegun,how about using 'merge', like so:
#original data frames
df1=data.frame(V1=c(1,3,4),V2=c("cat","dog","apple"),V3=c("animal","animal","fruit"))
df2=data.frame(V1=c(4,1,3))

# just merge and don't sort (which is the default)
df3=merge(df2,df1,by.x="V1",sort=FALSE)
vec=as.vector(paste0(df3$V3,":",df3$V2))

> vec
[1] "fruit:apple" "animal:cat"  "animal:dog"

A: A slightly more concise version:
my_charvec <- as.character(my_vector)
rownames(my_frame) <- my_frame$V1
apply(my_frame[my_charvec,c(3,2)],1,paste,collapse=":")

Here's the output:
            4             1             3
"fruit:apple"  "animal:cat"  "animal:dog"

The 4,1,3 on the output are just names; you can ignore them if you want to.

A: Another base R solution, using match and mapply
d <- read.table(text='V1 V2 V3
1 cat animal
3 dog animal
4 apple fruit', header=TRUE)
v <- c(4,1,3)

with(d[match(v, d$V1), ], paste(V3, V2, sep=':'))
# [1] "fruit:apple" "animal:cat"  "animal:dog"

A: Maybe something like this?
> df<-data.frame(V1=c(1,2,3), V2=c("a","b","c"), V3=c("v", "nv", "nv"))
> v <- c(3,1,2)
> df[v,]
##   V1 V2 V3
## 3  3  c nv
## 1  1  a  v
## 2  2  b nv
> res <- as.character(apply(df[v,], 1, function(r) paste(r[3],r[2],sep=":")))
> res
## [1] "nv:c" "v:a"  "nv:b"

A: Here is a base solution
a <- data.frame(c("cat", "dog", "apple"), c("animal", "animal", "fruit"))
v <- c(3,1,2)
apply(a[v,], 1, paste0, collapse=":")


text:
Q: How to Unit test Web API calling Method I am calling a Web Api method inside my Repository layer. Can anyone suggest how to test it using Mocking

A: If you want to mock the call to a Web API method you will have to abstract the code that is calling it.
So abstract it:
public interface IMyApi
{
    MyObject Get();
}

and then you could have a specific implementation of this interface that is using an HttpClient to call the actual API:
public class MyApiHttp: IMyApi
{
    private readonly string baseApiUrl;
    public MyApiHttp(string baseApiUrl)
    {
        this.baseApiUrl = baseApiUrl;
    }

    public MyObject Get()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = this.baseAddress;
            var response = client.GetAsync('/api/myobjects').Result;
            return response.Content.ReadAsAsync<MyObject>().Result;
        }
    }
}

Now your repository layer will simply take this abstraction as constructor argument:
public class Repository: IRepository
{
    private readonly IMyApi myApi;
    public Repository(IMyApi myApi)
    {
        this.myApi = myApi;
    }

    public void SomeMethodThatYouWantToTest()
    {
        var result = this.myApi.Get();
        ...
    }
}

Next in your unit test it's trivial to mock the access to the API using your favorite mocking framework. For example your the unit test with NSubstitute might look like this:
// arrange
var myApiMock = Substitute.For<IMyApi>();
var sut = new Repository(myApiMock);
var myObject = new MyObject { Foo = "bar", Bar = "baz" };
myApiMock.Get().Returns(myObject);

// act
sut.SomeMethodThatYouWantToTest();

// assert
...


text:
Q: set priorityclass by default for a namespace I would like to know how it's possible to set a priorityClass by default for all pods in a specific namespace without using a
globalvalue:  true
may be with admission controller but i don't know.
Do you have an concret example for that ?

A: PriorityClass : A PriorityClass is a non-namespaced object
PriorityClass also has two optional fields: globalDefault and description.
The globalDefault field indicates that the value of this PriorityClass should be used for Pods without a priorityClassName.
Only one PriorityClass with globalDefault set to true can exist in the system. If there is no PriorityClass with globalDefault set, the priority of Pods with no priorityClassName is zero.
Create Priority Class as using below yaml (no globalDefault flag is set)
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
  name: high-priority
value: 1000000
description: "This priority class should be used for pods."

$ kubectl get priorityclasses.scheduling.k8s.io
NAME                      VALUE        GLOBAL-DEFAULT   AGE
high-priority             1000000      false            10s

Now add priority class to pod manifest and schedule them in your namespace
$ kubectl create namespace priority-test
namespace/priority-test created

$ kubectl get namespaces
NAME              STATUS   AGE
default           Active   43m
kube-node-lease   Active   43m
kube-public       Active   43m
kube-system       Active   43m
priority-test     Active   5s

Example : pod.yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - name: nginx
    image: nginx
  priorityClassName: high-priority

$ kubectl apply -f pod.yaml -n priority-test
pod/nginx created

ubuntu@k8s-master-1:~$ kubectl get all -n priority-test
NAME        READY   STATUS    RESTARTS   AGE
pod/nginx   1/1     Running   0          25s

$ kubectl describe pod -n priority-test nginx  | grep -i priority
Namespace:            priority-test
Priority:             1000000
Priority Class Name:  high-priority
  Normal  Scheduled  <unknown>  default-scheduler      Successfully assigned priority-test/nginx to worker-1

A: Currently per namespace priorities are not possible.
But you can achieve similar result if instead you set default priorityClass with globalDefault: true and e.g. value: 1000. Next create another lower priority class and with e.g. value: 100 and add it to all dev/staging pods.
Btw. not directly related to the question but it would be much easier to accomplish what you need if you use nodeSelectors and schedule dev pods to separate nodes. This way production pods don't have to compete for resources with non-essential pods.


text:
Q: AWS lambda create cloudformation stack using java I am trying to create a cloudformation stack using java. I have created before using python, but trying to convert that to java
import boto3
import time

datetime = time.strftime("%Y%m%d%H%M%S")
stackname = 'abc'
client = boto3.client('cloudformation')
response = client.create_stack(
  StackName= (stackname+ '-' + datetime),
  TemplateURL='https://s3.amazonaws.com/abc/xyz.json',
  Parameters=[
    {
        'ParameterKey': 'Environment',
        'ParameterValue': 'dev',
        'UsePreviousValue': False
    }
  ]
)

def lambda_handler(event, context):
            return(response)


text: Q: How to get the thumbnail image for multi-selected files I can get the thumbnail image for a single file using StorageFile.GetThumbnailAsync Method. Is there a way to get a thumbnail for multiple file selections?  Similar to the one that is displayed in Window's Explorer when multi-selected files are dragged? like this one


text:
Q: What does this sum converge to (binomial theorem) Let $t, a \in \left(0,1\right)$ and $b \in \mathbb{N}$.
$$
\mbox{What is the limit of}\quad
s = \lim_{n \to \infty}\sum_{k = 0}^{an + b}
{n\choose k}t^{n - k}\,\,\left(\,{1 - t}\,\right)^{k}
\quad {\large ?}.
$$
We can assume that $s$ exists because $s \leq 1$ and this series is monotonic. I already know that
$$
s =
\left\{\begin{array}{ll}
0 & a \geq t
\\
1 & \, a < t
\end{array}
\right.
$$
because that would solve the actual exercise perfectly.
Thanks for reading and for the help.


text:
Q: d3 combine zoom and drag calls? Is it possible to conditionally ignore the drag function from eating an event? I have a pan/zoom canvas (as seen here: www.proofapp.io/workspace) and I'm trying to implement a shift+drag multi-selection lasso. The svg object already has the zoom function registered so when I put a drag function above it the zoom never gets called. Since call only runs once at the beginning I'm not sure how I can make this work. Any suggestions?
const zoom = d3.zoom()
                    .scaleExtent([0.25 ,5])
                    .on("zoom", function() {
                        root.attr('transform', d3.event.transform);
                    });

// THIS DOESNT WORK BECAUSE IT ONLY RUNS ONCE AT THE BEGINNING
const lasso = function() {
    if (d3.event.sourceEvent) {
        if (d3.event.sourceEvent.shiftKey) {
            d3.drag()
                .dragDisable() // maybe the answer is with this?
                .on("start", function() { console.log('lasso-start') })
                .on("drag", function() { console.log('lasso-drag') })
                .on("end", function() { console.log('lasso-end') });
        }
    }
}

var svg = d3.select("div#nodegraph")
                    .append("svg")
                        .attr("width", "100%")
                        .attr("height", "100%")
                        .on('click', Graph.setNodeInactive)
                        .call(lasso)
                        .call(zoom);

UPDATE
Trying to just use the mousedown.drag event instead so that I can control the event bubbling. Not quite there yet, but the behaviour is correct (only blocks zoom when shift is pressed).
const zoom = d3.zoom()
                    .scaleExtent([0.25 ,5])
                    .on("zoom", function() {
                        root.attr('transform', d3.event.transform);
                    });

function lasso() {
    if (d3.event.shiftKey) {
        // do stuff
        d3.event.stopImmediatePropagation();
    }
}

var svg = d3.select("div#nodegraph")
                    .append("svg")
                        .attr("width", "100%")
                        .attr("height", "100%")
                        .on('click', Graph.setNodeInactive)
                        .on('mousedown.drag', lasso)
                        .call(zoom);

A: If there's a d3 way to do this I'd still love to know how it works to take advantage of all the extra goodness d3.drag does. Until that happens, here is a fairly complete example that takes into account the zoomed canvas.
Selection = {};
Selection.DragLasso = {};
Selection.DragLasso.__lasso = null;
Selection.DragLasso.handler = function() {
    if (d3.event.shiftKey) {
        d3.event.stopImmediatePropagation();

        if (Selection.DragLasso.__lasso) {
            Selection.DragLasso.__lasso.remove();
            Selection.DragLasso.__lasso = null;
        }

        var m = d3.mouse(this);

        svg
            .on('mousemove.drag', Selection.DragLasso.drag)
            .on('mouseup.drag', Selection.DragLasso.end);

        var z = d3.zoomTransform(svg.node());
        var x = (z.x / z.k * -1) + (m[0] / z.k);
        var y = (z.y / z.k * -1) + (m[1] / z.k);

        Selection.DragLasso.__lasso = noderoot.append('rect')
                                                    .attr("fill", 'red')
                                                    .attr('x', x)
                                                    .attr('y', y)
                                                    .attr('width', 0)
                                                    .attr('height', 0)
                                                    .classed('selection-lasso', true);
    }
}
Selection.DragLasso.drag = function(e) {
    var m = d3.mouse(this);

    var z = d3.zoomTransform(svg.node());
    var x = (z.x / z.k * -1) + (m[0] / z.k);
    var y = (z.y / z.k * -1) + (m[1] / z.k);

    Selection.DragLasso.__lasso
        .attr("width", Math.max(0,  x - +Selection.DragLasso.__lasso.attr("x")))
        .attr("height", Math.max(0, y - +Selection.DragLasso.__lasso.attr("y")));

}
Selection.DragLasso.end = function() {
    svg.on('mousemove.drag', null).on('mouseup.drag', null);
    Selection.DragLasso.__lasso.remove();
    Selection.DragLasso.__lasso = null;
}

var svg = d3.select("div#nodegraph")
                    .append("svg")
                        .attr("width", "100%")
                        .attr("height", "100%")
                        .on('mousedown.drag', Selection.DragLasso.handler)
                        .call(zoom);


text:
Q: How to animate collection view layout change while using `layoutAttributesForElements`? I made a custom collection view flow layout that can toggle (with animation) between "film-strip" and "list" layouts. But after adding some fancy animations to the edge cells, the toggle animation broke. Here's what it looks like currently, without those changes:

The animation is nice and smooth, right? Here's the current, working code (full demo project here):
enum LayoutType {
    case strip
    case list
}

class FlowLayout: UICollectionViewFlowLayout {

    var layoutType: LayoutType
    var layoutAttributes = [UICollectionViewLayoutAttributes]() /// store the frame of each item
    var contentSize = CGSize.zero /// the scrollable content size of the collection view
    override var collectionViewContentSize: CGSize { return contentSize } /// pass scrollable content size back to the collection view

    /// pass attributes to the collection view flow layout
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        return layoutAttributes[indexPath.item]
    }

    // MARK: - Problem is here
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

        /// edge cells don't shrink, but the animation is perfect
        return layoutAttributes.filter { rect.intersects($0.frame) } /// try deleting this line

        /// edge cells shrink (yay!), but the animation glitches out
        return shrinkingEdgeCellAttributes(in: rect)
    }

    /// makes the edge cells slowly shrink as you scroll
    func shrinkingEdgeCellAttributes(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let collectionView = collectionView else { return nil }

        let rectAttributes = layoutAttributes.filter { rect.intersects($0.frame) }
        let visibleRect = CGRect(origin: collectionView.contentOffset, size: collectionView.frame.size) /// rect of the visible collection view cells

        let leadingCutoff: CGFloat = 50 /// once a cell reaches here, start shrinking it
        let trailingCutoff: CGFloat
        let paddingInsets: UIEdgeInsets /// apply shrinking even when cell has passed the screen's bounds

        if layoutType == .strip {
            trailingCutoff = CGFloat(collectionView.bounds.width - leadingCutoff)
            paddingInsets = UIEdgeInsets(top: 0, left: -50, bottom: 0, right: -50)
        } else {
            trailingCutoff = CGFloat(collectionView.bounds.height - leadingCutoff)
            paddingInsets = UIEdgeInsets(top: -50, left: 0, bottom: -50, right: 0)
        }

        for attributes in rectAttributes where visibleRect.inset(by: paddingInsets).contains(attributes.center) {
            /// center of each cell, converted to a point inside `visibleRect`
            let center = layoutType == .strip
                ? attributes.center.x - visibleRect.origin.x
                : attributes.center.y - visibleRect.origin.y

            var offset: CGFloat?
            if center <= leadingCutoff {
                offset = leadingCutoff - center /// distance from the cutoff, 0 if exactly on cutoff
            } else if center >= trailingCutoff {
                offset = center - trailingCutoff
            }

            if let offset = offset {
                let scale = 1 - (pow(offset, 1.1) / 200) /// gradually shrink the cell
                attributes.transform = CGAffineTransform(scaleX: scale, y: scale)
            }
        }
        return rectAttributes
    }

    /// initialize with a LayoutType
    init(layoutType: LayoutType) {
        self.layoutType = layoutType
        super.init()
    }

    /// make the layout (strip vs list) here
    override func prepare() { /// configure the cells' frames
        super.prepare()
        guard let collectionView = collectionView else { return }

        var offset: CGFloat = 0 /// origin for each cell
        let cellSize = layoutType == .strip ? CGSize(width: 100, height: 50) : CGSize(width: collectionView.frame.width, height: 50)

        for itemIndex in 0..<collectionView.numberOfItems(inSection: 0) {
            let indexPath = IndexPath(item: itemIndex, section: 0)
            let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)

            let origin: CGPoint
            let addedOffset: CGFloat
            if layoutType == .strip {
                origin = CGPoint(x: offset, y: 0)
                addedOffset = cellSize.width
            } else {
                origin = CGPoint(x: 0, y: offset)
                addedOffset = cellSize.height
            }

            attributes.frame = CGRect(origin: origin, size: cellSize)
            layoutAttributes.append(attributes)
            offset += addedOffset
        }

        self.contentSize = layoutType == .strip /// set the collection view's `collectionViewContentSize`
            ? CGSize(width: offset, height: cellSize.height) /// if strip, height is fixed
            : CGSize(width: cellSize.width, height: offset) /// if list, width is fixed
    }

    /// boilerplate code
    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true }
    override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
        let context = super.invalidationContext(forBoundsChange: newBounds) as! UICollectionViewFlowLayoutInvalidationContext
        context.invalidateFlowLayoutDelegateMetrics = newBounds.size != collectionView?.bounds.size
        return context
    }
}

class ViewController: UIViewController {

    var data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    var isExpanded = false
    lazy var listLayout = FlowLayout(layoutType: .list)
    lazy var stripLayout = FlowLayout(layoutType: .strip)

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!
    @IBAction func toggleExpandPressed(_ sender: Any) {
        isExpanded.toggle()
        if isExpanded {
            collectionView.setCollectionViewLayout(listLayout, animated: true)
        } else {
            collectionView.setCollectionViewLayout(stripLayout, animated: true)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.collectionViewLayout = stripLayout /// start with the strip layout
        collectionView.dataSource = self
        collectionViewHeightConstraint.constant = 300
    }
}

/// sample data source
extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ID", for: indexPath) as! Cell
        cell.label.text = "\(data[indexPath.item])"
        cell.contentView.layer.borderWidth = 5
        cell.contentView.layer.borderColor = UIColor.red.cgColor
        return cell
    }
}

class Cell: UICollectionViewCell {
    @IBOutlet weak var label: UILabel!
}

Again, everything works perfectly, including the animation. So then, I tried to make the cells shrink as they neared the screen's edge. I overrode layoutAttributesForElements to do this.
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    return layoutAttributes.filter { rect.intersects($0.frame) } /// delete this line
    return shrinkingEdgeCellAttributes(in: rect) /// replace with this
}

Film-strip
List

The scale/shrink animation is great. However, when I toggle between the layouts, the transition animation is broken.

Before (return layoutAttributes.filter...)
After (return shrinkingEdgeCellAttributes(in: rect))

How can I fix this animation? Should I be using a custom UICollectionViewTransitionLayout, and if so, how?

A: Thanks for your detailed investigation @Thisura Dodangoda
– it was instrumental in helping me solve a similar problem. For folks who end up here, I want to add a tiny detail in case you run into another issue that I did.
The UICollectionViewLayout API has 2 very similar methods:
func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint,  withScrollingVelocity velocity: CGPoint) -> CGPoint
This method Retrieves the point at which to stop scrolling
and
func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint
This method Retrieves the content offset to use after an animated layout update or change
I had already implemented the first for some custom behaviour during scrolling, and I was trying to implement the solution posted by @Thisura Dodangoda in that method.
However, these are used for completely different purposes. You need to use the second method (without the velocity parameter) to implement the solution for layout changes.

A: Whew! This was a workout. I was able to modify your FlowLayout so that there are no hiccups in animation. See below.
It works!

Problem
This is what was happening. When you change layouts, the layoutAttributesForElements method in FlowLayout is called twice if the content offset of the collection view is anything but (0, 0).
This is because you have overridden 'shouldInvalidateLayout' to return true regardless of whether it is actually needed. I believe the UICollectionView calls this method on the layout before and after the layout change (as per the observation).
The side effect of this is that your scale transform is applied twice - before and after the animations to the visible layout attributes.
Unfortunately, the scale transform is applied based on the contentOffset of the collection view (link)
let visibleRect = CGRect(
    origin: collectionView.contentOffset,
    size: collectionView.frame.size
)

During layout changes the contentOffset is not consistent. Before the animation starts contentOffset is applicable to the previous layout. After the animation, it is relative to the new layout. Here I also noticed that without a good reason, the contentOffset "jumps" around (see note 1)
Since you use the visibleRect to query the set of Layout Attributes to apply the scale on, it introduces further errors.
Solution
I was able to find a solution by applying these changes.

*

*Write helpers methods to transform the content offset (and dependent visibleRect) left by the previous layout to values meaningful for this layout.

*Prevent redundant layout attribute calculates in prepare method

*Track when and when not the layout is animating

// In Flow Layout

class FlowLayout: UICollectionViewFlowLayout {
    var animating: Bool = false
    // ...
}

// In View Controller,

isExpanded.toggle()

if isExpanded {
    listLayout.reset()
    listLayout.animating = true // <--
    // collectionView.setCollectionViewLayout(listLayout)
} else {
    stripLayout.reset()
    stripLayout.animating = true // <--
    // collectionView.setCollectionViewLayout(stripLayout)
}

*Override targetContentOffset method to handle content offset changes (prevent jumps)

// In Flow Layout

class FlowLayout: UICollectionViewFlowLayout {

    var animating: Bool = false
    var layoutType: LayoutType
    // ...

    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
        guard animating else {
            // return super
        }

        // Use our 'graceful' content content offset
        // instead of arbitrary "jump"

        switch(layoutType){
        case .list: return transformCurrentContentOffset(.fromStripToList)
        case .strip: return transformCurrentContentOffset(.fromListToStrip)
        }
    }

// ...

The implementation of content offset transforming is as follows.
/**
 Transforms this layouts content offset, to the other layout
 as specified in the layout transition parameter.
*/
private func transformCurrentContentOffset(_ transition: LayoutTransition) -> CGPoint{

    let stripItemWidth: CGFloat = 100.0
    let listItemHeight: CGFloat = 50.0

    switch(transition){
    case .fromStripToList:
        let numberOfItems = collectionView!.contentOffset.x / stripItemWidth  // from strip
        var newPoint = CGPoint(x: 0, y: numberOfItems * CGFloat(listItemHeight)) // to list

        if (newPoint.y + collectionView!.frame.height) >= contentSize.height{
            newPoint = CGPoint(x: 0, y: contentSize.height - collectionView!.frame.height)
        }

        return newPoint

    case .fromListToStrip:
        let numberOfItems = collectionView!.contentOffset.y / listItemHeight // from list
        var newPoint = CGPoint(x: numberOfItems * CGFloat(stripItemWidth), y: 0) // to strip

        if (newPoint.x + collectionView!.frame.width) >= contentSize.width{
            newPoint = CGPoint(x: contentSize.width - collectionView!.frame.width, y: 0)
        }

        return newPoint
    }
}

There are some minor details I left out in the comments and as a pull request to OP's demo project so anyone interested can study it.
The key take-aways are,

*

*Use targetContentOffset when arbitrary changes in content offset occur in response to layout changes.

*Be careful about incorrect query of layout attributes in layoutAttributesForElements. Debug your rects!

*Remember to clear your cached layout attributes on the prepare() method.
Notes

*

*The "jump" behavior is evident even before you introduced scale transforms as seen in your gif.

*I sincerely apologize if the answer is lengthy. Or, The solution is not quite what you wanted. The question was interesting which is why I spent the whole day trying to find a way to help.

*Fork and Pull request.


text:
Q: Emails from my custom enquiry form are marked as spam All emails from my custom module are marked as spam. Already put the necessary headers but still didnt work.
Anyone can help me to fix this?
Also, I have tried installing different modules for custom form but they're always have errors. Saying they cant find helper data file. argh!
Thanks in advance!

A: Send email to any of the spam detecting service like http://www.emailspamtest.com to check it spam rate and possible issues.
It can be wrong headers and encoding, stop words in the subject and the body, no text part in html emails, too many images comparing to the text size.
Also try to use smtp server instead of default mail function.
Edit:
Here is the full code to send transactional email in Magento:
public function sendTransactionalEmail()
{
    // Transactional Email Template's ID
    $templateId = 1;

    // Set sender information
    $senderName = Mage::getStoreConfig('trans_email/ident_support/name');
    $senderEmail = Mage::getStoreConfig('trans_email/ident_support/email');
    $sender = array('name' => $senderName,
                'email' => $senderEmail);

    // Set recepient information
    $recepientEmail = 'john@example.com';
    $recepientName = 'John Doe';

    // Get Store ID
    $store = Mage::app()->getStore()->getId();

    // Set variables that can be used in email template
    $vars = array('customerName' => 'customer@example.com',
              'customerEmail' => 'Mr. Nil Cust');

    $translate  = Mage::getSingleton('core/translate');

    // Send Transactional Email
    Mage::getModel('core/email_template')
        ->sendTransactional($templateId, $sender, $recepientEmail, $recepientName, $vars, $storeId);

    $translate->setTranslateInline(true);
}

Hope this helps.


text:
Q: setprecision equivalent in C#? In C++ I would do:
auto loadingTime = TimeUtilities::getDistance<milliseconds_t>(TimeUtilities::getNow(), startTime);
std::cout << "Reset all accounts and players in " << std::setprecision(3) << loadingTime / 1000.f << " seconds!" << std::endl << std::endl;

However in C# I tried to do something similar, but it failed:
double loadingTime = TimeUtil.GetDistanceInMilliseconds(DateTime.Now, startTime);

Console.WriteLine("Reset all accounts and characters in {0:0.000} seconds!", loadingTime);

The Method GetDistanceInMilliseconds just returns the TotalMilliseconds value of the TimeSpan between the two DateTime objects.
How can I do mimic the same behavior in C#?
EDIT: Dividing the value by 1000f will work if the loadingTime value is less than 1 second. If it's more than 1 second, the displayed value will be wrong.
My goal is to display a loading time from the start point to the end point (DateTime.Now is the start point and startTime is the end point) in milliseconds (up to 3 decimal points).

A: Use 0.### specifier:
7d.ToString("0.###", CultureInfo.InvariantCulture);

returns 7,
0.007d.ToString("0.###", CultureInfo.InvariantCulture);

returns 0.007


text:
Q: Does the main theorem of elimination theory with $\mathbb{Z}$-coefficients imply that projective varieties are complete? I have a question concerning the completeness of projective varieties.
Let $k$ be an algebraically closed field. By the "main theorem of elimination theory" I mean the following result:
Let $f_1,\ldots,f_r\in\mathbb{Z}[X_0,\ldots,X_n,Y_1,\ldots,Y_m]$ be homogeneous in $X_0,\ldots,X_n$. Then there exist polynomials $g_1,\ldots,g_s\in \mathbb{Z}[Y_1,\ldots,Y_n]$ such that for all $a\in k^m$ the system $f_1(X,a)=\cdots=f_r(X,a)=0$ has a nontrivial solution in $k$ if and only if $g_1(a)=\cdots=g_s(a)=0.$
I want to deduce that projective varieties over $k$ are complete. Since closed subvarieties of complete varieties are complete and every variety is a finite union of open affines, it suffices to prove that the projection $\mathbb{P}^n(k)\times \mathbb{A}^m(k)\to \mathbb{A}^m(k)$ to the second factor is closed. The above "main theorem of elimination theory" gives us that the image of a closed set defined by polynomials with integer coefficients is closed. Does it already follow somehow that the image of a closed set defined by polynomials with coefficients in $k$ is closed?
Context: In Exercise 3.4.22 of Marker's "Model Theory. An Introduction", part (a) asks for a nice model theoretic proof of the "main theorem" as stated above. The task in part (b) is to deduce that projective varieties are complete.
Thanks for your help!
Edit: Thanks for your answers! I have come up with this "elementary" solution, giving a little more details to the proof in the comment by Alex Kruckman. Please let me know when I did a mistake.
For the general case, now let $f_1,\ldots,f_r\in k[X_0,\ldots,X_n,Y_1,\ldots,Y_m]$ be homogeneous in the $X_0,\ldots,X_n$ and let $Z$ be their vanishing set in $\mathbb{P}^n(k)\times\mathbb{A}^m(k)$. We want to show that $\mathrm{pr}_2(Z)$ is closed in $\mathbb{A}^m(k)$. Let $(\mu_i)_{i=1}^N$ be the finitely many coefficients of $f_1,\ldots,f_r$. replacing each $\mu_i$ by a new variable $W_i$, we obtain polynomials
\begin{align*}
\tilde f_1,\ldots,\tilde f_r\in \mathbb{Z}[X_0,\ldots,X_n,Y_1,\ldots,Y_m,W_1,\ldots,W_N]
\end{align*}
that are homogeneous in the $X_0,\ldots,X_n$. Let $\tilde Z$ denote their vanishing set in $\mathbb{P}^n(k)\times\mathbb{A}^{m+N}(k)$. Consider the commutative diagram

where the vertical maps $p$ and $p'$ are also the obvious projection maps. By the statement for $\mathbb{Z}$-coefficients, the map $\mathrm{pr}_2\times\mathrm{id}$ is closed. The projection $p$ restricts to an isomorphism from the closed set $\tilde Z\cap V((W_i-\mu_i)_{i=1}^N)$ to $Y$ and we have
\begin{align*}
(\mathrm{pr}_2\times\mathrm{id})(\tilde Z\cap V((W_i-\mu_i)_{i=1}^N))=(\mathrm{pr}_2\times\mathrm{id})(\tilde Z)\cap  V((W_i-\mu_i)_{i=1}^N),
\end{align*}
which is closed because $(\mathrm{pr}_2\times\mathrm{id})(\tilde Z)$ is closed. We observe that $p'$ restricts to an isomorphism from $(\mathrm{pr}_2\times\mathrm{id})(\tilde Z)\cap  V((W_i-\mu_i)_{i=1}^N)$ to $\mathrm{pr}_2(Y)$, and we conclude that $\mathrm{pr}_2(Y)$ is closed.

A: One way to reduce completeness of projective space to $\mathbb{Z}$ is to use noetherian approximation techniques from scheme theory.
Def: Let $R$ be a ring. We say a $R$-scheme $X$ is universally closed if for every $R$-scheme $T$, the projection $X \times_R T \to T$ is closed in the Zariski topology.
It is not hard to see that it suffices to check the statement only on affine schemes $T = \mathrm{Spec}\ A$. Using the observation that $X \times_R T = (X \times_R R') \times_{R'} T$ for any ring homomorphism $R \to R'$ and $R'$-scheme $T$, we see that if $X/R$ is universally closed, then so is $X \times_R R'/R'$. The key approximation result is the following which is proved in Tag 05JW of the Stacks Project.
Lemma: Let $X/R$ be quasi-compact. Then $X$ is universally closed if and only if the projection $X \times \mathbb{A}^m \to \mathbb{A}^m_R$ is closed.
The hard part of the proof is to show that if $X/R$ is not universally closed, then there exists some finitely presented affine scheme $T$ such that $X \times_R T \to T$ is not closed. Since every finitely presented affine scheme $T$ embeds as a closed subscheme of $\mathbb{A}^m_R$ for some $m$, the reverse implication follows.
Prop: For any ring $R$, $\mathbb{P}^n_R$ is universally closed.
Proof. By the observation above, it suffices to show the claim for $R = \mathbb{Z}$. By the lemma, it suffices to show that the morphism of $\mathbb{Z}$-schemes $\pi : \mathbb{P}^n \times \mathbb{A}^m \to \mathbb{A}^m$ is closed in the Zariski topology. Every closed subscheme $Z \subset \mathbb{P}^n \times \mathbb{A}^m$ is given by the vanishing of $f_1, \ldots, f_r$ as in the hypothesis of the Main Theorem of Elimination Theory. Let $W \subset \mathbb{A}^m$ be the closed subscheme defined as the vanishing of $g_1, \ldots, g_s$. Then the projection of $Z$ is $W$ and thus $\pi$ is closed. Indeed every point $p \in Z$ is the image of some $k$-point $\bar{p} : \mathrm{Spec}\ k \to Z$ where $k$ is an algebraically closed field. Thus $\pi(p)$ is the image of $\pi \circ \bar{p} \in \mathbb{A}^m(k)$ which lies in $W(k)$ by the Main Theorem.
I think this argument, and in particular the key lemma above can be rephrased in a way that only makes reference to $k$-points. Namely one can try to show that any closed subvariety of $X(k) \times \mathbb{A}^m(k)$ which witnesses the failure of the projection to be closed is defined over some finitely generated ring extension $R/\mathbb{Z}$, and by writing $R = \mathbb{Z}[a_1, \ldots, a_s]/I$, produces a closed subvariety of $X(k) \times \mathbb{A}^{m+s}(k)$ defined over $\mathbb{Z}$ whose image under projection is not closed. While I was writing this answer Alex Kruckman suggested essentially this argument in the comments. I think there is something to be gained by thinking about schemes though so I'll leave the scheme theoretic argument too.


text:
Q: Importing data from server txt/xml I'm currently developing an app that will be used as track and trace app. This app will need data that is located on a server. Let's say, we create a file for each customer on the server. This file will contain the track and trace info. Would it be easier if this is a xml file or text file and how would the code look like?
Let's say we've already knew the customers number and the file has the same name as the customer number. The user tapped the button to get the data. Then the app contacts the server asking for the file that got the same customers number and reads it presenting the info in a label or something similar.
Any suggestions where to start?

A: If you dont have any other specific requirements fetching xml files from server will be good enough. For example if you have file at url www.test.com/user1.xml you can load into data
NSData *tmpData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"www.test.com/user1.xml"] ];
                    //convert data to string
NSString *tmpString = [[NSString alloc] initWithData:tmpData encoding:NSUTF8StringEncoding];
NSArray *piecesArray = [tmpString componentsSeparatedByString:@" "];
if(piecesArray.count==2)
{
   labelA.text = [piecesArray objectAtIndex:0];
   labelB.text = [piecesArray objectAtIndex:1];
}


text:
Q: How to use Struts2 iterator index in non struts tag I want to generate dynamic id for html anchor tag. However stat.index will work only if we are using tags defined by Struts.
<s:iterator value='environmentList' status="stat" var="env">

            <s:text value="#env.value" />
            <s:hidden id="environmentId[%{#stat.index}]" name="#env.name" />

</s:iterator>

In  the above example, I have a list of object environmentList which I am iterating. In anchor tag, I want to generate id's like environmentList[0], environmentList[1] etc.. But [%{#stat.index}] will work only in Struts tags(like it is working in s:hidden tag).
How can I generate dynamic id's in anchor tag?

A: I think I got the solution... using ${stat.index} has worked for me..
<s:iterator value='environmentList' status="stat" var="env">

            <s:text value="#env.value" />
            <s:hidden id="environmentId[%{#stat.index}]" name="#env.name" />

</s:iterator>


text: Q: Easiest way to install the Ubuntu Mysql Security Patch I am looking for a quick and easy way to install the security fix for CVE-2012-2122 on my Ubuntu boxes.  I don't want to risk installing any of the other updates and I just want to install the critical security updates.  When I built my boxes out I set them to install sec updates automatically but I want to make sure I have this vuln patched given the extreme nature of it.


text:
Q: Clustered stacked bar plot with error bars I am using the code (posted here: https://stackoverflow.com/a/22845857/6649485) below to generate a clustered stacked bar plot. Unfortunately the error bars are not shifted in the same way as the data bars. I am not sure how to adress them and set their x-value accordingly.

def plot_clustered_stacked(dfall, labels=None, title="SEC stress study",  H="/", **kwargs):
    """Given a list of dataframes, with identical columns and index, create a clustered stacked bar plot. labels is a list of the names of the dataframe, used for the legend title is a string for the title of the plot H is the hatch used for identification of the different dataframe"""

    n_df = len(dfall)
    n_col = len(dfall[0].columns)
    n_ind = len(dfall[0].index)
    axe = plt.subplot(111)

    for df in dfall : # for each data frame
        axe = df.plot(kind="bar",
                      linewidth=0,
                      stacked=True,
                      ax=axe,
                      legend=False,
                      grid=False,
                      yerr=0.1,
                      **kwargs)  # make bar plots

    h,l = axe.get_legend_handles_labels() # get the handles we want to modify
    for i in range(0, n_df * n_col, n_col): # len(h) = n_col * n_df
        for j, pa in enumerate(h[i:i+n_col]):
            for rect in pa.patches: # for each index
                rect.set_x(rect.get_x() + 1 / float(n_df + 1) * i / float(n_col))
                rect.set_hatch(H * int(i / n_col)) #edited part
                rect.set_width(1 / float(n_df + 1))

    axe.set_xticks((np.arange(0, 2 * n_ind, 2) + 1 / float(n_df + 1)) / 2.)
    axe.set_xticklabels(df.index, rotation = 0)
    axe.set_title(title)

    # Add invisible data to add another legend
    n=[]
    for i in range(n_df):
        n.append(axe.bar(0, 0, color="gray", hatch=H * i))

    l1 = axe.legend(h[:n_col], l[:n_col], loc=[1.01, 0.5])
    if labels is not None:
        l2 = plt.legend(n, labels, loc=[1.01, 0.1])
    axe.add_artist(l1)
    return axe

A: This is what I came up with by now.
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

def plot_clustered_stacked(dfall):

    for j, df in enumerate(dfall):
            set_count=1
            width = 0.2
            N=len(df.index)
            b_width = 0.2
            index=np.arange(N/set_count)
            labels=df.index
            p1 = plt.bar(index +j*b_width, df['Average Monomer Area'], width=width, yerr='0.5 Stdev Monomer Area', data=df)
            p2 = plt.bar(index +j*b_width, df['Average HMW Area'], bottom=df['Average Monomer Area'], width=width, yerr='0.5 Stdev HMW Area', data=df)
            plt.xticks(index+b_width, labels)
            plt.legend((p1[0], p2[0]), ('Average Monomer Area', 'Average

HMW Area'))
data=pd.read_csv("SEC.csv")

df1 = data[data['Time'].str.contains("0 weeks")].drop(['High/low', 'Time'], axis=1)
df1.set_index('Excipient Name', inplace=True)
df2 = data[data['Time'].str.contains("1 week")].drop(['High/low', 'Time'], axis=1)
df2.set_index('Excipient Name', inplace=True)
df3 = data[data['Time'].str.contains("3 weeks")].drop(['High/low', 'Time'], axis=1)
df3.set_index('Excipient Name', inplace=True)

plot_clustered_stacked([df1, df2, df3])

plt.show()


text:
Q: Top Performance PHP + HTTPD + OPCACHE I'm trying to figure out what would be the most performing configuration to host a PHP website on Amazon EC2.
Which webserver? (Apache, Lighttpd, nginx)?
Which PHP module? mod_php, FastCgi?
Which OpCache? (xcache, APC, eAccelerator, Varnish)
What would you recommended setup would look like?

A: *

*It depends on your application running on the server. Needs much more memory or cpu or both?

*Nginx + PHP-FPM + Varnish-Cache is a good solution if you can use them effectively.


text:
Q: If condition fail skip to end of file
for (( v=0; v<t ; v++ ))
  do
  awk '/TRAP-TYPE/{i++}i' $fname >tron
  if [ "$?" -eq 0 ]
  then
  echo "MIB file found"
  else
  t=$t-1
  fi
some other commands
  echo "MIB not in directory"
  done

When the awk '/TRAP-TYPE/{i++}i' $fname >tron fails I want it to skip some other commands and reach directly the end of the code and just print MIB not in directory.
What can I do to do this? Bash doesn't have goto.

A: I would just move some other commands between echo "MIB file found" and else.


text:
Q: laravelcollective: add extra attribute to each options(Form::Select) <select class="form-control" id="user" name="car">
  <option value="0" selected="selected">Select Cars</option>
  <option dta-img='1.jpg' value="134">Volvo</option>
  <option dta-img='2.jpg' value="135">Noah</option>
  <option dta-img='3.jpg' value="136">Marcidis</option>
  <option dta-img='4.jpg' value="143">London Express</option>
</select>

My array for options :
public function guardianList()
    {
      $list = ["Select Cars"];
        foreach ($carss->all() as $car) {
            $list[$car->id] =  $car->name;
        }
        return $list;
}

   Form::select('car',$list, null, null);

How can i add extra dynamic html attribute to all options?
I want to show image infront of every option in jquery select2. For that i need to send image from Form::Select(). I there any easy way to do that without using marcos?

A: Solved the issue:
Pass array in the 4th param.
$opt_attributes = collect($guardians->all())
        ->mapWithKeys(function ($item) {
            return [$item->id => ['data-img' => $item->photos->last()->name]];
        })->all();

make a array linke this and pass it as 4th parameter.

A: I don't know exactly since which version, but laravelcollective/html 5.8 version takes optionParameters as fifth parameter, not 4th


text:
Q: Static initializer block in derived nested class assuming the following example:
public abstract class A {

  public void readList() {
    for (Integer o : InnerA.INT_LIST) {
      System.out.println(o);
    }
  }

  public static class InnerA {

    protected static List<Integer> INT_LIST;

    static {
      INT_LIST = new ArrayList<Integer>();
      INT_LIST.add(1);
    }
  }
}

public class B extends A {

  public static class InnerB extends InnerA {
    static {
      INT_LIST.add(2);
    }
  }
}

My assumtion was, that when I call
new B().readList();

the output would be
1
2

but instead it is
1

Adding the constructor
public B() {
    new InnerB();
}

leads to the expected behaviour. I thought since the nested class is static, it gets initialized when a new B object is created (it obviously is when A is initialized).
Can someone please explain this to me?
Thanks.

A: Let's see the implementation of readList() first:
public void readList() {
  for (Integer o : InnerA.INT_LIST) {
    System.out.println(o);
  }
}

It is obviously that it print all elements in the InnerA.
Class B extends Class A and doesn't override readList() function. So the behavior of new B().readList() is print all elemtns in the InnerA, too.
Since the InnerA.INT_LIST only has a elements added in static block of InnerA, it only has 1 elements.
Actually, your code never use class InnerB. JVM do not load it so its static block is not executed.


text:
Q: Adding JxBrowser Content to JPanel Is it not possible to add jxbrowser contents to jpanel. When I add jxBrowser content to JFrame, it is seen very easily. But I am not able to add jxBrowser content to jpanel. I don't know if it is not possible or I am not able to add jxBrowser contents to jpanel.

A: Here's sample code that demonstrates how to embed JxBrowser Browser component into JPanel:
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

import javax.swing.*;
import java.awt.*;

/**
 * This sample demonstrates how to create Browser instance,
 * embed it into Swing BrowserView container, display it in JFrame and
 * navigate to the "www.google.com" web site.
 */
public class BrowserSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView view = new BrowserView(browser);

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(view, BorderLayout.CENTER);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(panel, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.loadURL("https://google.com");
    }
}

More samples you can find at https://jxbrowser.support.teamdev.com/support/solutions/9000049010

A: Actually jxbrowser is able to added into Jpanel.
I have met the same problem. It is just because I did not specify BorderLayout when initilize JPanel. The code blow is alright.
JPanel panel = new JPanel(new BorderLayout());


text:
Q: In general relativity, what makes an object released in a gravitational field START to fall? I understand why a released object moves as it does once it has started moving, and why all objects fall at the same speed, removing other effects. But I don't see why the curvature of space would make it start to move in the first place, thank you.

A: In the weak field limit (which applies near a planet) curvature of space is so small that its effect can be ignored completely; gravity is explained by looking only at time. We know that clocks on GPS satellites do not keep time with identical clocks on Earth, and we also know that energy is the time component of a 4-vector. It follows that energy is changed when an object moves up or down. We measure the energy change directly, as light is redshifted when it goes upwards, and we can calculate that the change is equivalent to potential energy in Newtonian gravity. The apparent force of gravity is minus the gradient of potential energy, so that the apparent change in the rate of clocks with height is directly responsible for the apparent force of gravity.


text:
Q: Tensorflow Hub module reuse Say I want to use a specific module (text embeddings) from TF Hub to create two distinct models, that I would then like to export and serve.
Option 1:
Import the module for each model, put each classifier on top, and export 2 models; serve each in its own docker container. These models contain both the underlying embedding module and the classifier.
Option 2:
Serve the module itself, and have its output go to 2 different served models, that themselves do not contain the embeddings. (Is this even possible?)
My computer science background tells me that option 2 is better, since we are re-using the original embeddings module for both models, also decoupling the models themselves from the embeddings module.
However, from a practical standpoint, when a data scientist is coding, they are importing the module and training with the classifier on top of it, so it becomes cumbersome having to export the model itself without the underlying embeddings.
Can anyone point me in the right direction? Hopefully my question makes sense, I am not a data scientist myself, I am coming more from a development background.
Thanks

A: Putting a classifier on top of an embedding module creates a fairly strong dependency: the classifier must be trained to the particular embedding space. Unless you make very special arrangements, just swapping in another embedding module won't work. So Option 1 is quite good: it yields two models that can be served and updated independently. They have some overlap, akin to two statically linked programs using the same library, but the source code is still modular: using Hub embedding modules through their common signature makes them interchangeable.
Option 2, by comparison, gives you three moving parts with non-trivial dependencies. If your goal is simplicity, I wouldn't go there.


text:
Q: How do I drag and copy a button to a container without completely transferring the button? I am developing a simple game (similar to Blockly and Scratch) that involves drag and drop. Currently, I am able to drag the button to a target container. However, the button gets completely transferred to another container. What I want to achieve is something like copy-pasting - from one container to another (basically drag-and-copy). I understand I have to clone it and give it a new ID but to no avail.
Here are the relevant codes:
HTML and JS
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Game</title>
    <link href="{{ url_for('static',filename='css/playmaze.css') }}" rel="stylesheet">

Directions

            <form action="/" method="post">

                    <input type="button" class="draggable" id="forward" value="Forward" draggable="true"></button>
                    <input type="button" class="draggable" id="backward" value="Backward" draggable="true"></button>
                    <input type="button" class="draggable" id="right" value="Right" draggable="true"></button>
                    <input type="button" class="draggable" id="left" value="Left" draggable="true"></button>
                    <input type="button" class="draggable" id="repeat" value="Repeat" draggable="true"></button>

            </form>

Maze

                                    <input type="reset" id="reset" class="btn btn-lg btn-primary" value="Reset"></button>
                                    <input type="submit" id="run" class="btn btn-lg btn-primary" value="Run"></button>

CSS:
.container
{
    background-color: #ffeaf0;
    padding: 1rem;
    flex-direction: column;
    display: flex;
    align-content: center;
}

.draggable
{
    padding: 1rem;
    margin-bottom: 1rem;
    background-color: white;
    border: 1px solid black;
    cursor: move;
    border-radius: 1rem;
}

.draggable.dragging
{
    opacity: .5;
}

.grid-wrapper
{
    display: grid;
    padding: 0px;
    margin: 0px;
    grid-template-columns: repeat(5, 100px);
    grid-template-rows: repeat(5, 100px);
}

.grid-item
{
    background-color: rgba(255, 255, 255, 0.8);
    border: 2px solid rgb(139,69,19);
    padding: 20px;
    font-size: 30px;
    text-align: center;
}

.directions {
    flex-direction: column;
    display: flex;
    align-content: center;
    padding: 0px;
    margin: 0px 20px 10px 20px;
}

.btn-lg {
    margin-bottom: 10px;
}

#forward {
    background-color: #98e690;
    border:#98e690;
    color: #404040;
}

#backward {
    background-color: #ff85a2;
    border: #ff85a2;
    color: #404040;
}

#right {
    background-color: #92dff3;
    border: #45b3e0;
    color: #404040;
}

#left {
    background-color: #fdfd96;
    border: #fdfd96;
    color: #404040;
}

#repeat {
    background-color: #CC99FF;
    border: #CC99FF;
    color: #202020;
}

#reset {
    background-color: black;
    border: #CC99FF;
    color: white;
    margin-top: 30px;
    margin-right: 10px;
    width: 6rem;
}

#run {
    background-color: #32CD32;
    border: #32CD32;
    color: white;
    margin-top: 30px;
    width: 6rem;
}

A: You need to clone the dragged html element:
So your code should be:
const draggables = document.querySelectorAll(".draggable");
const containers = document.querySelectorAll(".container");
let currentDraggableClone = null;
let currentAfterElement = null;
let currentContainer = null;
// loop through each of the draggables (aka buttons)
draggables.forEach((draggable) => {
  draggable.addEventListener("dragstart", () => {
    console.log("drag start");
    draggable.classList.add("dragging");
  });

  draggable.addEventListener("dragend", () => {
    if (currentContainer === null || currentDraggableClone === null) return;
    //Random ID
    currentDraggableClone.id =
      currentDraggableClone.id + Math.random() * 100000000;
    if (currentAfterElement == null) {
      // append the element that is currently being dragged
      currentContainer.appendChild(currentDraggableClone);
    } else {
      currentContainer.insertBefore(currentDraggableClone, currentAfterElement);
    }
    currentDraggableClone.classList.remove("dragging");
    draggable.classList.remove("dragging");
  });
});

containers.forEach((container) => {
  container.addEventListener("dragover", (e) => {
    // by default, dropping inside an element is disabled
    e.preventDefault();
    currentContainer = container;
    currentAfterElement = getDragAfterElement(container, e.clientY);
    const draggable = document.querySelector(".dragging");
    if (
      draggable !== null &&
      (currentDraggableClone === null ||
        currentDraggableClone.id !== draggable.id)
    ) {
      currentDraggableClone = draggable.cloneNode(true);
    }
  });
});

// determine the mouse position when dragging elements and
// return whichever element our mouse position is directly after
function getDragAfterElement(container, y) {
  // array
  const draggableElements = [
    ...container.querySelectorAll(".draggable:not(.dragging)")
  ];

  // reduce -> loop through the list of draggableElements and determine
  // which single element is directly after the mouse based on the y position (retrieved from the event)
  return draggableElements.reduce(
    (closest, child) => {
      const box = child.getBoundingClientRect();
      const offset = y - box.top - box.height / 2;
      if (offset < 0 && offset > closest.offset) {
        return { offset: offset, element: child };
      } else {
        return closest;
      }
    },
    { offset: Number.NEGATIVE_INFINITY }
  ).element;
}


text:
Q: Ubuntu 12.04 dropping LAN connection I have a Ubuntu 12.04 machine that has two Ethernet interfaces, both are static.
eth0 is sitting on a network like:
xxx.xxx.169.xxx with a 255.255.255.0 mask
It's static address is:
xxx.xxx.169.14
eth1 is the gateway to a sub network (also a dhcp server):
192.168.1.1
This network arrangement works fine when there is a direct lan connection from the xxx.xxx.169.14 managed switch.
I'm trying to introduce a client machine (Windows 7) that is also straddling both networks. To do this I've introduced a 4 port dumb switch between the xxx.xxx.169.14 managed switch and the two straddled computers.
The problem:
Windows doesn't have a problem (both machines are the exact same hardware), but Ubuntu get's intermittent connectivity to eventually no connectivity in a short period of time.
When I remove the dumb switch and direct connect the Ubuntu machine it's fine again.
I'm not sure what is going on here, can someone offer some assistance. My only thought (which I haven't tried) is maybe I need a better driver?
Thanks in advance.

A: The answered to the problem was changing out the dumb 5 port switch I was using.
Do not use this:
Cisco SF100D-05 if you are using a Linux machine with Realtek networking chipset.
https://supportforums.cisco.com/discussion/11874911/unstable-link-sf100d-05


text:
Q: Scale deployment with python client in Kubernetes I am trying to scale deployments using Kubernetes python client. The cluster is running on 3 nodes and I have remote access via kubectl. I need to scale my deployment based on a python script via Kubernetes python client. I am trying the following code but I get an error. I couldn't figure out the issue. Any suggestions ? Thank you.
from kubernetes import client, config

replicas=3

config.load_kube_config()
k8s_apps_v1 = client.AppsV1Api()

container = client.V1Container(
    name="trafficapp-deployment",
    image="traffic-app",#docker repository name?
    ports=[client.V1ContainerPort(container_port=5000)],
    )

template = client.V1PodTemplateSpec(
    metadata=client.V1ObjectMeta(labels={"app": "trafficapp"}),
    spec=client.V1PodSpec(containers=[container]))

spec = client.V1DeploymentSpec(
    replicas=replicas,
    template=template,
    selector={'matchLabels': {'app': 'trafficapp'}})

deployment = client.V1Deployment(
    api_version="apps/v1",
    kind="Deployment",
    metadata=client.V1ObjectMeta(name=DEPLOYMENT_NAME),
    spec=spec)
deployment.spec.replicas=replicas

api_response = k8s_apps_v1.patch_namespaced_deployment(
    name=DEPLOYMENT_NAME,
    namespace="default",
    body=deployment)

print("Deployment updated. status='%s'" % str(api_response.status))

Error I am getting -
Traceback (most recent call last):
File "/home/k8/Desktop/K8 Python client/test_pyclient.py", line 31, in <module>
api_response = k8s_apps_v1.patch_namespaced_deployment(
File "/home/k8/.local/lib/python3.10/site-packages/kubernetes/client
/api/apps_v1_api.py", line 4627, in patch_namespaced_deployment
return self.patch_namespaced_deployment_with_http_info(name, namespace, body, **kwargs)
 # noqa: E501
File "/home/k8/.local/lib/python3.10/site-packages/kubernetes/client
/api/apps_v1_api.py", line 4742, in patch_namespaced_deployment_with_http_info
return self.api_client.call_api(
File "/home/k8/.local/lib/python3.10/site-packages/kubernetes/client/api_client.py",
line 348, in call_api
return self.__call_api(resource_path, method,
File "/home/k8/.local/lib/python3.10/site-packages/kubernetes/client/api_client.py",
line 180, in __call_api
response_data = self.request(
File "/home/k8/.local/lib/python3.10/site-packages/kubernetes/client/api_client.py",
line 407, in request
return self.rest_client.PATCH(url,
File "/home/k8/.local/lib/python3.10/site-packages/kubernetes/client/rest.py", line
295, in PATCH
return self.request("PATCH", url,
File "/home/k8/.local/lib/python3.10/site-packages/kubernetes/client/rest.py", line
234, in request
raise ApiException(http_resp=r)
kubernetes.client.exceptions.ApiException: (404)
Reason: Not Found
HTTP response headers: HTTPHeaderDict({'Audit-Id': 'b4523864-3ea8-4857-
a1ac-59034d630644', 'Cache-Control': 'no-cache, private', 'Content-Type':
'application/json', 'X-Kubernetes-Pf-Flowschema-Uid': 'f90063cc-3ae9-45ed-aed6-
d6ea009c6b10', 'X-Kubernetes-Pf-Prioritylevel-Uid': 'cda270d5-00fc-4012-
bb7e-58a85a29842f', 'Date': 'Wed, 07 Sep 2022 14:20:23 GMT', 'Content-Length': '232'})
HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":
{},"status":"Failure","message":"deployments.apps \"DEPLOYMENT_NAME\" not
found","reason":"NotFound","details":
{"name":"DEPLOYMENT_NAME","group":"apps","kind":"deployments"},"code":404}

A: You did not specify variable DEPLOYMENT_NAME
Specify
DEPLOYMENT_NAME="your deployment name"
and try below snippet.
api_response= k8s_apps_v1.patch_namespaced_deployment_scale(name=DEPLOYMENT_NAME,
                                           namespace="default",
                                          {'spec': {'replicas': replicas}} )


text:
Q: Replicate Google spreadsheet array formula in Excel I've got  Google form survey data I'd like to analyse. In my example doc,
Sheet 1 contains the survey responses and sheet 2 references the data in sheet 1.   Sheet 2 is where I am using this array formula under the column called Behaviour:
=ArrayFormula(if(len(A3:A),if(Sheet1!Question3="Yes","Excluded ",)&if(Sheet1!Question5="Yes","Arrested ",)&if(Sheet1!Question6="Yes","Alcohol ",)))

The issue is that I need to be able to download this Google spreadsheet as a Microsoft Excel doc but whenever I do that, of course the Google spreadsheet =ArrayFormula() function is not supported in Microsoft Excel.
My question is how could I replicate this array function's behaviour using another method in Google spreadsheet so that I get the same result when it's downloaded to Microsoft Excel?
What I've been able to find in the forum so far are questions on how you can manually copy formulas to multiple rows in Excel. The trouble with these methods are that the user has to do it by either clicking and dragging the bottom right-hand corner of the cell or by using shortcuts. I'd like my process to work so that the user doesn't have to manually do anything.
Many thanks in advance.

A: Excel support array formulas but it does that in a different way than Google Sheets.
Instead of an ARRAYFORMULA function, Excel requires that the formula autor/editor, first selects the area to which the array formula result should be extended, then enter edit mode and press CTRL+SHIFT+ENTER. See Create an array formula that calculates multiple results on Create an array formula

A: It is possible to replicate the Google Sheet ArrayFormula in MS Excel using the OFFSET() formula even if it's not as simple as the ArrayFormula function.
The full documention of the function can be found here.
https://support.office.com/en-us/article/OFFSET-function-C8DE19AE-DD79-4B9B-A14E-B4D906D11B66
A quick example
Google Sheet
= ARRAYFORMULA(SQRT(Sheet2!A:A))

=> This will copy the full column A for the Sheet2 taking the square root of each value.
Excel Version
= SQRT(OFFSET(Sheet2!A1,0,0,COUNTA(Sheet2!A:A),1))

=> This will take a reference of the column, but we have to manually specify the height and width of the reference before taking the square root of each value.

A: You may very well discover that this is not possible; at least not in every case. There may be a few formulae which have the exact same definition in Google sheets and Excel. however, it's not guaranteed to work in general.
Some more detailed information here: Sheets vs Excel forumlae


text:
Q: How to highlight JSON block in Gitlab Wiki (Markdown)? I want to highlight & color the syntax for json data in GitLab Markdown.
Input Json
[
  {
    "id": 1,
    "first_name": "Jeanette",
    "last_name": "Penddreth",
    "gender": "Female"
  },
  {
    "id": 2,
    "first_name": "Giavani",
    "last_name": "Frediani",
    "gender": "Male"
  }
]

Expected Output

When I was copy paste the beautified json data in wiki it seems to be like paragraph, which leads to less readability .

A: Method1
Place three semicolons on the start and end of json data like below.
;;;

json data here

;;;

NB: When we are placing any text before leading three semicolons this method won't work.
Reference
Method2
```json

json data here

```

A: This is similar to How to style JSON block in Github Wiki?
Use a code fence:
```json

your JSON here

```

See https://docs.gitlab.com/ee/user/markdown.html#colored-code-and-syntax-highlighting
This will add color highlighting but won't beautify the code (change whitespace) -- you have to do that yourself which you can do with jq on the command line or using an external service such as https://beautifier.io/

A: GitLab 15.0 (May 2022) does include syntax highlighting

GitLab 15.0 includes a few exciting improvements to speed up your workflow in the WYSIWYG Markdown editor for your wikis.
You'll find no more un-styled, monochrome code blocks: choose from over 100 languages in the dropdown list above the code block so your CSS, YAML, and Python code are distinct from each other with accurate syntax highlighting.
The code blocks will even inherit your preferred syntax highlighting theme.
You can also quickly copy the code block to your clipboard for use in your code editor of choice.