text:
Q: how to save and post JS code result in Webgl within ruby on rails Currently I have two input text area for users to write the Javascript and JS Library on the browser and run it with a run button. Here is the view html:
<textarea id="scriptJS" rows="20" style="width:100%;">
</textarea>
<textarea id="libsJS" rows="20" style="width:100%;">
</textarea>

<button id="btn-run">Run</button>

<canvas id='your_canvas'></canvas> </br>

By clicking Run, the Canvas will render the image as the result of the code (Webgl). Below is the Javascript I have in order to make this possible:
$(window).load(function(){
  $("#btn-run").on('click', function(){
    scriptJS = $("#scriptJS").val();
    libsJS = $("#libsJS").val();
    eval(libsJS);
    eval(scriptJS);
    main();
  });
});

Now what I need to know in Ruby on Rails is how do I write this so that when the user click run, the result image in the Canvas (webgl) is saved and automatically rendered on the users profile. I need the 3d webgl image result be saved and posted with the code so that you can still interact with the image in the canvas after it is saved and posted. Any help would be great.

A: Cant see any ruby code there but i guess you want to transfer the rendered image to the server, doing so requires you to create the webgl context with 'preserveDrawingbuffer'. When enabled you can call toDataURL on the canvas element and get a jpg/png whatever base64 string you can send to your server using ajax.
Oh and take some of this while you're at it: eval is evil


text:
Q: Hover effects ends before mouse is moved Does anyone have idea why hover effects ends before mouse is moved off an element?
I applied hover effect on before pseudo element.

A: The :hover selector will complete once you hover over an element. Moving the mouse off of the element will stop/remove the effect. You should post in JSFiddle for more help. That way we can see what's going on.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamically add columns in SSRS I am tasked with creating a report in SSRS that can display data covering anywhere from 1 week up to 52 weeks.
What I am trying to avoid is writing a huge query that will pull all 52 weeks worth of data and have it show on the report, unless the user wants that data to appear.
So if the user wants January 1st - February 1st it will only show 6 columns of data instead of all 52 columns.  How would I do something like that?

A: Easy - you need to use a Matrix.
A grid gives you a fixed number of columns and many rows.
A matrix gives you many columns and many rows.

A: Try this How to Create SSRS Report with Dynamic Columns

A: Create column grouping on your tablix, for example you have column WEEK and you are bringing data from 1st Jan to 1st Feb.
Column grouping on column WEEK will generate only 5 columns if you have data for every week.


text:
Q: I can't change the text of one button, it changes for all of them in map (ReactJS) i try to do a map in React js with button, if i click on a buton, it would change the text of it, but when i click on the button, it changes all the button.
I know the problem is i don't specific the button_id but i don't have any idea to get this.
There is my code:
 const assignTutorToChildFunction = (id_child) => {
        setText("Cet enfant est déja ajouté")
    }

    const [text, setText] = useState("Ajouter cet enfant")
    return children.map((element, index) => (

    ))

}

when i click on a button, all my "Ajouter cet enfant" are replaced by "Cet enfant est deja ajouté")
Thanks for your help

A: I think this might work. Essentially, you need to save each text separately, instead of just having one text.
const [texts, setTexts] = useState({});

const assignTutorToChildFunction = (id_child) => {
    setText({...texts, [id_child]: "Cet enfant est déja ajouté"});
};

React.useEffect(
    () => {
        let temp_texts = {};
        children.map((element, index) => temp_texts[index] = "Ajouter cet enfant");
        setTexts(temp_texts);
    },
    []
);

A: You are using a state variable. Once you change it, it will cause a re-render and all of your references will be updated.
Better to try to have 2 separate variables containing texts.
const tutorUnassignedText = "Ajouter cet enfant";
const tutorAssignedText = "Cet enfant est déja ajouté";

then you need a state variable to track where to show which text.
You could try something like this:
const [tutorsAssigned, setTutorsAssigned] = useState(Array.from({length: children.length}).fill(false))

and then inside your map use:
<Inner>
  <button
onClick={() => setTutorsAssigned(prevState => {
  const tutorsArr = [...prevState];
  tutorsArr[index] = !tutorsArr[index]
  return tutorsArr;
})>
    {tutorsAssigned[index] ? tutorAssignedText : tutorUnassignedText}
  </button>
</Inner>

A: Each child component must have own state:
Const ChildComponent = () => {
    const assignTutorToChildFunction = (id_child) => {
      setText("Cet enfant est déja ajouté")
    }
    const [text, setText] = useState("Ajouter cet enfant");
    return (

  ) ;
} ;

Const ParentComponent = () =>  {
  return children.map((element, index) => (
    <ChildComponent />
  ))
 }

A: You declared state, which is used by ALL of your buttons in the loop.
You have 2 options:

*

*Extract a brand new component where you'll put the button and where you'll be able to use local state
or

*Change state to an array of strings. When you'll be able to manipulate the array depending on the index (or key):

const [text, setText] = useState([
  "Ajouter cet enfant",
  "Ajouter cet enfant"
  [...etc]
])

Then your callback function will look like that:
  const assignTutorToChildFunction = (index) => {
    setText(prevState => {
      const array = [...prevState];
      array[index] = "Ajouter cet enfant"
      return array
    });
  }

and the fragment with button:
<button
  key={`button-${index}`}
  onClick={() => assignTutorToChildFunction(index)} //You're passing index to you callback function.
>
  {text[index]}{" "}
</button>

Edit:
Few things I found in your code:

*

*For iterations over children you should use the Children.map from React:

return Children.map(children, (element, index) => (

*The assignTutorToChildFunction functions should use the useCallback from React:

const assignTutorToChildFunction = useCallback((index) => {
  setText(prevState => {
    const array = [...prevState];
    array[index] = "Ajouter cet enfant"
    return array
  });
})


text:
Q: Como achar um número dentro de uma lista HTML Estou tentando achar o número que a pessoa escreveu na box, no document.getElementByID no site, porém não sei fazer em c#, ou tentei pelo menos:
private void btnvalidar_Click(object sender, EventArgs e)
        {
            if (webrequestNumero.Document.GetElementById("Numero").InnerText.IndexOf(txtNumero.Text) == -1)
            {
                MessageBox.Show("O número está na lista");
            }
            else
            {
                MessageBox.Show("O número não está na lista");
            }
        }

Alguém poderia explicar oque há de errado no código?

A: Por favor, Você teria um exemplo do fonte da página?
tem várias forma de você identificar se o texto esta ou não no site.
A box se encontra dentro de alguma tag, um exemplo TD ou TR
caso esteja, faça esse código abaixo!

foreach (HtmlElement Html in WebBrowser.Document.Body.GetElementsByTagName("tr"))
              {
                  MessageBox.Show(Html2.InnerText);
              }

ao fazer essa função o C# vai lhe mostrar uma msgbox informando o conteúdo da tag, ai caso você queira você pode fazer um If para identificar se o valor da box corresponde ao que você procura.
ou melhor
caso a box esteja em um input com a ID ou name você pode fazer desta outra forma

string = WebBrowser.Documento.GetelementByID("BoxDoConteudo").innertext;

Como havia dito a inúmeras forma de você trazer o valor da box, caso esse exemplo tenha ajudado ficarei mto feliz, se não me informa qualquer duvida?
Atte!


text:
Q: Entity Framework modeling with .NET4, Data Annotations issue I am trying to use Entity Framework on my web site. I followed tutorials and Visual Studio (2010) does not complain. However, when I add a ForeignKey data annotation, I get an error when I run on the web site that the Namespace does not exist.
CS0246: The type or namespace name 'ForeignKey' could not be found (are you missing a using directive or an assembly reference?)
After doing some searching, it appears that the ForeignKey data annotation does not exist in .NET 4.
If that is the case, is there a way to add at foreign key to the model in .NET 4?

A: Correct, System.ComponentModel.DataAnnotations.Schema is part of .NET 4.5.
Have you instead looked at the Fluent API?
Here's a video for VS 2010 specifically. http://msdn.microsoft.com/en-ca/data/gg194009.aspx


text:
Q: maven goal doesn't execute properly if plugins are defined under pluginManagement I have maven-jaxb2-plugin. I generate jaxb objects and refer it in other classes of project.I've put jaxb plugin and compiler plugin under pluginManagement tag. Maven is executing compile phase first than generate phase where as if i remove pluginManagement tag, it works fine, first generate phase gets executed and all jaxb object gets generated and then compile phase gets executed. Due to pluginManagement tag, my project doesn't compile. Is pluginManagement tag used only for defining all the plugins in parent pom so that child pom can refer to these plugins ? My project is not a multi-module project.
   <pluginManagement>
      <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.jvnet.jaxb2.maven2</groupId>
            <artifactId>maven-jaxb2-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <schemaDirectory>${basedir}/src/main/resources/schema</schemaDirectory>
                <generatePackage>com.common.dto</generatePackage>
                <schemaIncludes>
                    <include>*.xsd</include>
                </schemaIncludes>
                <removeOldOutput>false</removeOldOutput>
                <strict>false</strict>
                <verbose>true</verbose>
                <forceRegenerate>true</forceRegenerate>
                <extension>true</extension>
            </configuration>
        </plugin>
    </plugins>
 </pluginManagement>

A: Yes, <pluginManagement> is used to create ready-to-use configurations, but does not automatically activate your plugins - you still need to include them.
So in effect you are right, <pluginManagement>, just like <dependencyManagement> are very useful in the parent pom to centralize plugin configurations and dependency management.
Effectively, 'declaring' your plugins in the right module benefits from a much more compact syntax:
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
    </plugin>

    <plugin>
        <groupId>org.jvnet.jaxb2.maven2</groupId>
        <artifactId>maven-jaxb2-plugin</artifactId>
    </plugin>
</plugins>


text:
Q: Log Viewers for Database-based Logs I'm writing a distributed system which logs directly to database (actual log files are only used when there's no database connection). There are plenty of tools for parsing traditional log files but are there any general tools for parsing log data from the database? I use MS SQL Server 2008 R2.

A: What format are you logging in? It doesn't matter if you log to a database table or a text file, the parser still needs to understand the message format and - as far as I know - there is no well-known standard for storing log messages in a database table.
For example, will you store the message as one string in a (N)VARCHAR column, or will you store individual values such as EventDate, EventMessage, EventSource etc. in different columns with different data types?
Perhaps you're asking if there are tools to visualize and analyze logged data stored in a database table, in which case you should look for generic reporting tools.


text:
Q: OPENCV bitwise_and operator I am learning OpenCV library in python following the tutorials and examples. I arrived to bitwise operations.
In this typical example:
   # Load two images
img1 = cv2.imread('messi5.jpg')
img2 = cv2.imread('opencv_logo.png')

# I want to put logo on top-left corner, So I create a ROI
rows,cols,channels = img2.shape
roi = img1[0:rows, 0:cols ]

# Now create a mask of logo and create its inverse mask also
img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)

# Now black-out the area of logo in ROI
img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)

# Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(img2,img2,mask = mask)

# Put logo in ROI and modify the main image
dst = cv2.add(img1_bg,img2_fg)
img1[0:rows, 0:cols ] = dst

cv2.imshow('res',img1)
cv2.waitKey(0)
cv2.destroyAllWindows()

When bitwise_and is used I don't understand what makes each parameter, and I've checked a hundred tutorials and no one clarifies it. What I don't understand is why we use twice roi in the parameters because "anyArray AND anyArray = anyArray".
Thanks you in advance.


text:
Q: dismissModalViewControllerAnimated function not dismissing the view I am trying to use dismissModalViewController:Animated: to dismiss my view, but it is not dismissing it, no matter what I try. You can see my attempts to release the view in the hideSplash method at the bottom. Please, if anyone can help it would be greatly appreciated. My code posted below:
#import "SplashViewController.h"

@implementation SplashViewController

- (void) didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void) viewDidUnload {

}

- (void) dealloc {
    [super dealloc];
}

-(void) showSplash {
    modalViewController = [[UIViewController alloc] init];
    modalViewController.view = modelView;
    [self presentModalViewController:modalViewController animated:NO];
    [activityIndicator startAnimating ];
    //[self bigcalculation];
    //[self performSelector:@selector(hideSplash) withObject:nil afterDelay:2.0];
}

- (void) viewDidAppear:(BOOL)animated {
    NSLog(@"View Did Appear");
    [self bigcalculation];
}

- (void) bigcalculation {
    NSLog(@"Big Calc Start");
    for (int i = 0; i <= 648230; i++) {
        for (int j = 0; j <= 1200; j++) {

        }
    }
    NSLog(@"Big Calc End");
    [self performSelector:@selector(hideSplash) withObject:nil];
}

- (void) hideSplash {
    NSLog(@"Hide");
    //[self dismissModalViewControllerAnimated:NO];
    //[[self parentViewController] dismissModalViewControllerAnimated:YES];
    [[self modalViewController] dismissModalViewControllerAnimated:YES];
    NSLog(@"End Hide");
}

@end

A: The modal view controller is not responsible for dismissal. That burden is placed on the view controller that called the modalViewController.
Try replacing:
[[self modalviewController] dismissModalViewControllerAnimated:YES];

with
[self dismissModalViewControllerAnimated:YES];

A: Try to use this:
[self.parentViewController dismissModalViewControllerAnimated:NO];

A: I found the solution in case anyone else has this issue the line
[self performSelector:@selector(hideSplash) withObject:nil];

Should be
[self performSelector:@selector(hideSplash) withObject:nil afterDelay:0.0];


text:
Q: Spring Integration Multiplexing correlation I am new to SI. I am using the code from the SI TCP Multiplexing example as a starting point for an app server I am writing. The caller of the service already exists and will be sending the payload prefixed by a byte length header. I am having a bit of trouble with the correlation of the response. As you can see below, I changed the Multiplexing example to first add a correlation id header to the incoming request before pushing on to the publish-subscribe-channel. The rest of the code is pretty much the same as the example.
So, the problem. The correlation id header is not available on the call to MessageController from the TcpSendingMessageHandler which serializes the message payload and sends it. Should I enrich the payload to include the correlation id (no correlation header) or is there a simpler way of doing all of this?  Any guidance would be greatly appreciated.
<gateway id="gw"
      service-interface="is.point.tokens.server.MessageGateway"
      default-request-channel="input">
</gateway>

<ip:tcp-connection-factory id="client"
            type="client"
            host="${tcpClientServer.address}"
            port="${tcpClientServer.port}"
            single-use="false"
            serializer="bigEndianFormatSerializer"
            deserializer="bigEndianFormatSerializer"
            so-timeout="10000"/>

<channel id="input" datatype="java.lang.String"/>

<header-enricher input-channel="input" output-channel="enriched.input">
     <correlation-id expression="headers['id']"/>
</header-enricher>

<publish-subscribe-channel id="enriched.input"/>

<ip:tcp-outbound-channel-adapter id="outAdapter.client"
                                     order="2"
                                     channel="enriched.input"
                                     connection-factory="client"/>
<!-- Collaborator -->

<!-- Also send a copy to the custom aggregator for correlation and
     so this message's replyChannel will be transferred to the
     aggregated message. The order ensures this gets to the aggregator first -->
    <bridge input-channel="enriched.input" output-channel="toAggregator.client" order="1"/>

    <!-- Asynchronously receive reply. -->
    <ip:tcp-inbound-channel-adapter id="inAdapter.client"
                                    channel="toAggregator.client"
                                    connection-factory="client"/>

<!-- Collaborator -->

<channel id="toAggregator.client" datatype="java.lang.String"/>

<aggregator input-channel="toAggregator.client"
                output-channel="toTransformer.client"
                correlation-strategy-expression="headers.get('correlationId')"
                release-strategy-expression="size() == 2">
</aggregator>

<!-- The response is always second -->
<transformer input-channel="toTransformer.client" expression="payload.get(1)"/>

    <!-- Server side -->

    <ip:tcp-connection-factory id="server"
                               type="server"
                               port="${tcpClientServer.port}"
                               using-nio="true"
                               serializer="bigEndianFormatSerializer"
                               deserializer="bigEndianFormatSerializer"/>

    <ip:tcp-inbound-channel-adapter id="inAdapter.server"
                                    channel="toSA"
                                    connection-factory="server" />

    <channel id="toSA" datatype="java.lang.String"/>

    <service-activator input-channel="toSA"
                       output-channel="toObAdapter"
                       ref="messageController"
                       method="handleMessage"/>

    <beans:bean id="messageController"
                class="example.server.MessageController"/>

    <channel id="toObAdapter"/>

    <ip:tcp-outbound-channel-adapter id="outAdapter.server"
                                     channel="toObAdapter"
                                     connection-factory="server"/>

A: Yes, you need something in the data so the reply can be correlated.
But I am confused. If you are the server side for an existing application, then you can simply use an inbound gateway.
If you really are providing the client and server side, we did add a mechanism in 3.0 to selectively add headers (to the tcp message), for example, using JSON.
EDIT:
From your comments, you only need the server side. All you need is this...
<int-ip:tcp-connection-factory id="server"
    type="server"
    serializer="serializer"
    deserializer="serializer"
    port="${port}"/>

<int-ip:tcp-inbound-gateway id="gateway"
    connection-factory="crLfServer"
    request-channel="toSA"
    error-channel="errorChannel"/>

<int:channel id="toSA" />

<int:service-activator input-channel="toSA"
    ref="messageController"
    method="handleMessage"/>

<bean id="serializer" class="org.springframework.integration.ip.tcp.serializer.ByteArrayLengthHeaderSerializer" />

The fact that the service-activator has no output-channel means the framework will send the reply to the gateway automatically.
This assumes the service can handle a byte[]; if you need a String, you'll need a transformer like in the sample. Either way, the payload will not include the length header; it is stripped off (inbound) and added (outbound).
This also assumes the length header is 4 bytes (default); the serializer takes a size in a constructor...
<bean id="serializer" class="org.springframework.integration.ip.tcp.serializer.ByteArrayLengthHeaderSerializer">
    <constructor-arg value="2" />
</bean>


text:
Q: No option to switch from xorg to Wayland on Ubuntu 17.10 login I don't see the gear button next to the Sign in button at the login screen. I have Nvidia drivers installed (for Nvidia 730 GT card). Ubuntu boots into Xorg as seen from the terminal with echo $XDG_SESSION_TYPE which outputs x11.
How do I switch to Wayland?

A: That means Wayland is disabled by your hardware and choice of drivers for it. You need to switch to nouveau to get Wayland working.
You might face this issue once you do it: GNOME has grey bar on top and bottom after upgrade from 17.04 to 17.10, how do I fix it to how it's supposed to look?

A:
That means Wayland is disabled by your hardware.
Thanks, I did read on Didier Rocks that Wayland is disabled and falls
  back by default when proprietary Nvidia drivers are used.
                                                 – user299070 yesterday

I am not a huge fan of the Linux Nvidia drivers*, but once in a while I try them to check the performance of the machine. More often than not, I end up in a console and no X/Wayland.
I have seen some Ubuntu users reinstalling their machine after this f* up, so here's how to fix it (I always forget the initramfs step and end up wasting a lot of time):
$ sudo apt-get remove --purge nvidia-*
$ sudo mv /etc/X11/xorg.conf /etc/X11/xorg.conf_pre-nvidia
$ sudo update-initramfs -u
$ reboot


text:
Q: How do I drown Whorls? There is an achievement (and item unlock) in Risk of Rain with the requirement "Drown 20 Whorls". How do I accomplish this? I would guess it has something to do with the "Sunken Tomb" level, but the Whorls survive just fine underwater.

A: You can "drown" the whorls by making them fall off the bottom of the screen on the Sunken Tomb level.


text:
Q: schema privilege 'createin' cannot be revoked I need to revoke CREATEIN privilege for PUBLIC in a schema named THOMAS.XXXXXXX@XXX.XXX.XXX, I connected to the database and typed the following commands
this one to verify PUBLIC has createin permissions in the schema
db2 "select schemaname,CREATEINAUTH from SYSCAT.SCHEMAAUTH where GRANTEE= 'PUBLIC'"

SCHEMANAME                                              CREATEINAUTH
THOMAS.XXXXXXX@XXX.XXX.XXX                                   Y

db2 revoke CREATEIN ON SCHEMA 'THOMAS.XXXXXXX@XXX.XXX.XXX' FROM PUBLIC
DB21034E  The command was processed as an SQL statement because it was not a
valid Command Line Processor command.  During SQL processing it returned:
SQL0108N  The name "COM" has the wrong number of qualifiers.  SQLSTATE=42601

i also tried with "" but got the same result
db2 "revoke CREATEIN ON SCHEMA THOMAS.XXXXXXX@XXX.XXX.XXX FROM PUBLIC"
DB21034E  The command was processed as an SQL statement because it was not a
valid Command Line Processor command.  During SQL processing it returned:
SQL0108N  The name "COM" has the wrong number of qualifiers.  SQLSTATE=42601

A: Try this:
db2 "revoke CREATEIN ON SCHEMA \"THOMAS.XXXXXXX@XXX.XXX.XXX\" FROM PUBLIC"

A: If there is any special character in db2 command that is not accepted by OS command line, you may keep the command in file with some delimiter and run the file from OS command line.
For eg. create a file with name say revoke.sql and keep following statement in it:
revoke CREATEIN ON SCHEMA THOMAS.XXXXXXX@XXX.XXX.XXX FROM PUBLIC;
Then you can execute this file as follows:
db2 -tvf revoke.sql


text:
Q: Swift Decode Array Custom Class Memory Leak I'm saving my app config using NSCoding and am getting a leak in Instruments when using DecodeWithKey.
Settings has a property stsSettings
stsSettings = (aDecoder.decodeObjectForKey("stsSettings") as! StsSettings)

stsSettings has a property array of StsVariables
stsVariables = (aDecoder.decodeObjectForKey("stsVariables") as! [StsVariable])

Leaked Object   #   Address Size    Responsible Library Responsible Frame
StsVariable 1   0x7fe182d494f0  192 Bytes   Foundation  _decodeObjectBinary
Settings also has a property conversions which is an array of Conversion objects and this doesn't leak, so I can't work out what's going on.

A: I experienced a memory leak in a similar situation. I resolved the issue by assigning the decoded array to a local variable and copy the elements to the property. However, I don't know why the memory leak was there in the first place.
let variables = (aDecoder.decodeObjectForKey("stsVariables") as! [StsVariable])
stsVariables = [StsVariable]()
for variable in variables {
    stsVariables += [variable]
}


text:
Q: Java best way to sort a list by another list with different objects Lets say I have a list with objects, lets call it listA which is unordered, and it has objects of type A. type A has a field called name.
now, I have another list, which is ordered. let's call it listB and it is ordered. the objects in this list are of type B and they also had a field name.
Now, I want listA to be ordered as listB, and the only thing that is the same in those two lists is the field name which is the same in both objects.
what is the most efficient way to do so?

A: I hope I'm understanding your problem.
Is the field 'name' a common field shared by the two types of Object (A and B)?
In other words, do the two types (A and B) extend the same Class C that contains the field 'name'? If so you could implement the Comparable in Class C and then Collections.sort() would do the trick for you. All you have to do, while implementing the comparable, would be to 'teach' it how to compare the field 'name' so that it orders, in the same manner, the list of type B objects, you specify, are ordered.
Another way to do this, in case your classes don't have anything in common, therefore not making sense of having a superclass C, would be to create a Comparator interface, where you could specify the fields that can be used to compare two distinct objects and then do the sorting using those fields, in other words:

*

*Create a Interface with the method getCompareFields() returns String[]; (for example)

*Implement interface of point 1. in objects A and B

*Implement a sorting algorithm that uses this interface's getCompareFields() method for sorting.

And, another way even, for you to do this, but, in my opinion, would be more complicated, would be to use reflection to get the field 'name' of both objects, in case they are not related in any kind.
I hope this helps you.
EDIT
Example of reflection:
Class TypeA (Example)
public class TypeA {
private String name;
private String id;

public TypeA() {
    this(null, null);
}

public TypeA(String name, String id) {
    this.name = name;
    this.id = id;
}

public String getName() {
    return this.name;
}

public String getId() {
    return this.id;
}

@Override
public String toString() {
    return "(" + name + ", " + id + ")";
}

}
Class TypeB (Example)
public class TypeB {
private String name;
private List<Integer> numbers;

public TypeB() {
    this(null);
}

public TypeB(String name, int ... numbers) {
    this.name = name;

    this.numbers = new LinkedList<Integer>();
    if (numbers != null) {
        for (int i : numbers) {
            this.numbers.add(i);
        }
    }
}

public String getName() {
    return this.name;
}

public List<Integer> getANumber() {
    return this.numbers;
}

@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("(").append(name).append(", [");

    Iterator<Integer> i = this.numbers.iterator();

    if (i.hasNext()) {
        builder.append(i.next());

        while (i.hasNext()) {
            builder.append(", ").append(i.next());
        }
    }

    builder.append("])");
    return builder.toString();
}

}
Reflection Name Comparator:
public class NameReflectionComparator implements Comparator<Object> {

@Override
public int compare(Object o1, Object o2) {
    if (o1 != null && o2 != null) {
        try {
            Method obj1_getNameMethod = o1.getClass().getMethod("getName");
            Method obj2_getNameMethod = o2.getClass().getMethod("getName");

            String obj1_name = (String) obj1_getNameMethod.invoke(o1);
            String obj2_name = (String) obj2_getNameMethod.invoke(o2);

            if (obj1_name != null) {
                return obj1_name.compareTo(obj2_name);
            } else if (obj2_name != null) {
                return obj2_name.compareTo(obj1_name);
            }
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }

    } else if (o1 != null && o2 == null) {
        return 1;
    } else if (o1 == null && o2 != null) {
        return -1;
    }

    return 0;
}

}
Main:
public class Main {
public static void main(String[] args) {

    // both TypeA and TypeB have field name and method getName()
    // unsorted list
    List<TypeA> typeAList = new LinkedList<TypeA>();
    typeAList.add(new TypeA("Yves Larock", UUID.randomUUID().toString()));
    typeAList.add(new TypeA("I'm ok", UUID.randomUUID().toString()));
    typeAList.add(new TypeA("Aaah", UUID.randomUUID().toString()));
    typeAList.add(new TypeA("Noooh", UUID.randomUUID().toString()));

    // sorted list
    List<TypeB> typeBList = new LinkedList<TypeB>();
    typeBList.add(new TypeB("Aaah", 1, 2, 3));
    typeBList.add(new TypeB("I'm ok", 1));
    typeBList.add(new TypeB("Noooh", 34, 3));
    typeBList.add(new TypeB("Yves Larock", 4, 5, 3, 9));

    System.out.println("ListA:\n" + typeAList);
    System.out.println("ListB:\n" + typeBList);

    NameReflectionComparator comparator = new NameReflectionComparator();
    Collections.sort(typeAList, comparator);

    System.out.println("=== AFTER SORT ====\nListA:\n" + typeAList);
    System.out.println("ListB:\n" + typeBList);
}

}
Result:
ListA:
[(Yves Larock, f40cb523-58e8-4ee2-aa4f-991ce7e7cdd5), (I'm ok, 5a66b9d9-7a27-4529-ab64-c893291bd9b0), (Aaah, 4842fd55-47e5-48ac-b7b6-ebc7acf7023c), (Noooh, 8dc89675-bc28-4374-aff2-0c5d0ae6dd9d)]
ListB:
[(Aaah, [1, 2, 3]), (I'm ok, 1), (Noooh, [34, 3]), (Yves Larock, [4, 5, 3, 9])]
=== AFTER SORT ====
ListA:
[(Aaah, 4842fd55-47e5-48ac-b7b6-ebc7acf7023c), (I'm ok, 5a66b9d9-7a27-4529-ab64-c893291bd9b0), (Noooh, 8dc89675-bc28-4374-aff2-0c5d0ae6dd9d), (Yves Larock, f40cb523-58e8-4ee2-aa4f-991ce7e7cdd5)]
ListB:
[(Aaah, [1, 2, 3]), (I'm ok, 1), (Noooh, [34, 3]), (Yves Larock, [4, 5, 3, 9])]


text:
Q: Python while loop (range) enter image description here
I dont know what's went wrong in the 1st one when I type 5 it suppose to stop
just like in the second one
thanks for your help.

A: You need to convert the str returned by input() to an int using
a = int(input("Enter number: "))


text:
Q: Suddenly new URLs with "table/"? I'm running a simple site based on Joomla. The SEF URLs are defined by SH404SEF and look like https://[domain]/[category]/[sub category]/[article title alias].html. In some cases there is a 1-to-1 relationship between category and article but in some cases one category has several articles.
Suddenly I have URLs requested following https://[domain]/table/[category]/[sub category]/. Not only does these new URLs in some cases create 404s, they also view my articles in the wrong way and when there is not a 1-to-1 relationship between category and article the link adds several articles on one page.
The correct non-SEF URL ends with &view=article and the new, uncorrect non-SEF URL ends with &view=category. I have no table/ in my correct URLs, neither in any internal link, in the articles' html code, in menu items nor in my sitemap.xml. I've discussed this with the few extension providers I am using and none of them see their extension as doing this request new.

*

*Is there any way to find out what is making these requests?

*I cannot make a redirect for these URLs since all of them do not
correspond to one article, but several. Can you see any risk with
making a rewrite rule that puts a 410 on all URLs that starts with
table/?

A: This is actually a misconfiugration in sh404SEF. Here's what to do:

*

*Login to the backend of your Joomla site

*Go to the sh404SEF configuration

*Set the field "Insert Content Table Name" to "No"

*Flush all URLs and clear your Joomla cache

This should do it.


text:
Q: Getting System.InvalidOperationException: 'Collection was modified error when taking ownership of files In in the process of making an application that gets executed as an Administrator user. The application copies and overwrites files if the said file exists to certain locations on C:\, If the Administrator does not have access  to perform the operation on the requested file then the application will take ownership and assign full control permission to the administrator user so that they can overwrite the said file.
however I am getting the following error when it tries to do this:
System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'

I have been reading that Foreach loops can't be modified during the iteration process.  So I converted my code to use a For loop but the issue still persists! I've spent many hours trying to get this to work and research but I have ended up going in circles, any help would be appreciated.  Below is my code:

    string[] lines = File.ReadAllLines(@"C:\Temp2\BarsInstaller\FilesToInstall.txt");
    string sourcePath = @"C:\Temp2\BarsInstaller\";

            for (int i = 0; i <= lines.Length; i++)
            {

                string[] col = lines[i].Split('=');
                string fileName = col[0];
                string pathName = col[1];

                string fullDestPath = pathName + fileName;
                string fileCopyToLocation = pathName;
                string fulleSourcePath = sourcePath + fileName;

                copyFilesToInstall(fulleSourcePath, fullDestPath, fileCopyToLocation);

}

void copyFilesToInstall(string sourceFile, string destFile, string target)

        {
            if (Directory.Exists(target) == false)
            {
                Directory.CreateDirectory(target);
            }

            //1 check if we have permissions to overrite the file or copy file to directory
            //if we dont then give us permisison

            string fileName = destFile;

            Console.WriteLine("Adding access control entry for "
                + fileName);

            // Get a FileSecurity object that represents the
            // current security settings.
 if (File.Exists(destFile))
{
                FileSecurity fSecurity = File.GetAccessControl(destFile);

  // Add the FileSystemAccessRule to the security settings.
 fSecurity.AddAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().User,
FileSystemRights.FullControl, AccessControlType.Allow));
fSecurity.SetOwner(WindowsIdentity.GetCurrent().User);

 using (new ProcessPrivileges.PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))
                {
                    fSecurity.SetOwner(WindowsIdentity.GetCurrent().User); //ERROR OCCURS HERE
                }

                // Set the new access settings.
                File.SetAccessControl(destFile, fSecurity);

}

}

Full Stack trace
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)\r\n
at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()\r\n
at ProcessPrivileges.PrivilegeEnabler.InternalDispose()
in C:\\Users\\bazile\\source\\repos\\ProcessPrivileges\\src\\ProcessPrivileges.Shared\\PrivilegeEnabler.cs:line 191\r\n
at ProcessPrivileges.PrivilegeEnabler.Dispose() in C:\\Users\\bazile\\source\\repos\\ProcessPrivileges\\src\\ProcessPrivileges.Shared\\PrivilegeEnabler.cs:line 149\r\n
 at BarsInstaller.Form1.copyFilesToInstall(String sourceFile, String destFile, String target) in D:\\SourceControl\\BarsInstaller\\BarsInstaller\\Form1.cs:line 224

A: I have now resolved this with the help from @OguzOzgul the issue was that the Nuget Package I was using had a bug version 1.5.7 so I downloaded the source code from this site: https://archive.codeplex.com/?p=processprivileges built it and added the DLL as a reference and this error is now gone.


text:
Q: How do I determine what programs are running with root privileges? Is there a way to check via terminal which programs are currently running and by which privileges they run?

A: ps -elf|grep root

Try this. Third field shows the process is running with root privileges


text:
Q: Why do Beckett Mariner and Captain Freeman have different last names? Beckett Mariner is Captain Freeman's daughter. Why do they have different last names?

A: No canon reason has been given yet.

Various theories abound, but the most likely is that Mariner is her middle name, one that she's adopted as her surname in order to avoid people realising that she's related to the various Starfleet officers under whom she's served; her mother Captain Carol Freeman of the Cerritos and Admiral Alonzo Freeman.
Adding weight to this theory is that the show's writer, Mike McMahan revealed in an interview that this character's name is based on his sister's name, and that Mariner is her middle name.

I don't know if you guys can say this —  I'm actually not sure if
we're allowed to say this — but my sister's name is Beckett Mariner
McMahan, and so I was able to use her name as the lead character on
the show, which I've always wanted to do. I don't think that's ever
been publicly out there. My mom loves to watch the show when the
captain goes, "Beckett!" because she thinks it's so awesome.
Below Deck With Lower Decks: Mike McMahan Breaks Down Season One


text:
Q: How to declare type of multiple variables in same line Suppose my Haskell file contains following declarations.
a :: Integer
b :: Double
c :: String

a = 10
b = 12.34
c = "Abcd"

I am able to assign values to variables in same line like below.
 (a, b, c) = (10, 12.34, "Abcd")

My question is, how can I define the type signature in same line?
When I used following statement.
  (a, b, c) :: (Integer, Double, String)

I am getting following error.
Invalid type signature: (a, b, c) :: (Integer, Double, String)
    Should be of form <variable> :: <type>

A: If you really have to do this, you can:
a :: Integer; b :: Double; c :: String
(a, b, c) = (10, 12.34, "Abcd")

Though I'd recommend you learn to like multiple lines, since that's generally better style.

A: (a :: Integer, b :: Double, c :: String) = ...`

should work, but probably requires the ScopedTypeVariables extension.

A: If they form a structure (that makes sense as a composite), structuring them first might be an option:
vals :: (Integer, Double, String)
vals = (10, 12.34, "Abcd")

(a, b, c) = vals

I don't see a reason to not put them on separate lines otherwise.

A: You can combine the binding and the type declaration in one line.
a = 10     :: Int
b = 12.34  :: Double
c = "Abcd" :: String

There's not much value in separating the two, since you can't really assign a different value to any of these names later.


text:
Q: If $K = F(\alpha)$ is a non separable and finite extension, then $T^K_F = 0$ I am trying to prove that if $K = F(\alpha)$ is a non separable and finite extension then $T^K_F = 0$. Now, I looked at a solution and it goes as follows: Suppose the minimal polynomial of $\alpha$ is $f=x^n+a_{n-1}x^{n-1}+...+a_0$, then $\{1, \alpha, ... \alpha^{n-1}\}$ is a basis for $K$. Now, consider the linear transformation $x \to \alpha \cdot x$. It is easy to check that the trace of the matrix which represents this linear transformation with respect to the above basis is exactly $-a_{n-1}$. But since the extension is not seperable, $f$ must be a polynomial in $x^p$ (where $p=char(F)$) and therefore $a_{n-1}=0$. Now, I understand that it proves that $T^{K}_F (\alpha) = 0$, but why does it prove that $T^K_F =0$? Say, I don't understand why for example $T^K_F(\alpha^2)=0$. Why is that?

A: Since you have $T^K_F=T^M_F\circ T^K_M$ for any intermediate field $M$, it follows that
$$
T^K_F(\alpha^2)=T^{F(\alpha^2)}_F\circ T^K_{F(\alpha^2)}(\alpha^2)=[K:F(\alpha^2)]T^{F(\alpha^2)}_F(\alpha^2)=0.
$$
In the same way, $T_F^K(\alpha^i)=0$ for all $i$. Then by the $F$-linearity of the trace you get $T_F^K=0$.


text:
Q: Str is already defined as a global variable I noticed something really strange while working with functions. It looks like the variable name 'str' is already defined as a global variable. Take a look:
def Example(x):
   str = input()
   return str

print (Example(str))
#When typing 'Hello!' Output --> Hello!

The variable str is defined in the function Example. So why is there no NameError: name 'str' is not defined?
When I call the variable x or something else ( In this case 'bar'):
def Example(x):
   bar = input()
   return bar

print (Example(bar))
#Output: NameError: name 'bar'is not defined

Why does a variable with the name 'str' act as a global variable?

A: In python, str() is the string constructor. It is used to cast an object to a string.
You can use it locally, but it will override the access to the function. You will not be able to use str() anymore.
for reference:
https://docs.python.org/2/library/functions.html#str

class str(object='')
Return a string containing a nicely printable representation of an
  object. For strings, this returns the string itself. The difference
  with repr(object) is that str(object) does not always attempt to
  return a string that is acceptable to eval(); its goal is to return a
  printable string. If no argument is given, returns the empty string,
  ''.

For general knowledge purpose, you can get back you constructor if you delete your variable. For example:
test = 1
str(test)
>>>'1'

str = 2
str(test)
>>>TypeError: 'int' object is not callable

del str

str(test)
>>>'1'

A: The reason this fails:
def Example(x):
   bar = input()
   return bar

print (Example(bar))
#Output: NameError: name 'bar'is not defined

Is because you're attempting to pass the variable bar to the Example() method, but bar was never defined anywhere prior to the call.
I'm not really sure what it is you want to accomplish with this method anyhow, since you pass a variable but don't use it at all.
Comment Response:
str is not a built-in function (albeit listed on the page), but rather it is the constructor for the built-in type str. To show that you are simply reassigning the method associated with the keyword (not necessarily reserved, but it is a keyword nonetheless), consider the following:
>>> str
<class 'str'>
>>> abs
<built-in function abs>
>>> str = abs
>>> str
<built-in function abs>

Thus you've essentially overwritten the assignment to the str class constructor. I used abs in this example, but the same applies (with a twist) for input:
>>> str
<class 'str'>
>>> input
<built-in function input>
>>> str = input
>>> str
<built-in function input>
>>> str = input()
hello world
>>> str
'hello world'

Difference here is you assign a string (of type str) to the keyword str. So you can never use str(10) to get '10' because that would now be like calling hello world(10) which fails.

A: If you want to use a keyword as a variable name, by convention a single trailing underscore is used to avoid conflicts with Python keywords, like so:
single_trailing_underscore_

Cf. PEP 8 -- Style Guide for Python Codes


text:
Q: How to find an unknown pattern, that is present in multiple strings? I'm trying to find a part in multiple strings, that all strings share in common. For example:
const string1 = '.bold[_ngcontent="_kjhafh-asda-qw"] {background:black;}';
const string2 = '[_ngcontent="_kjhafh-asda-qw"] {background-color:hotpink;}';
const string3 = 'div > p > span[_ngcontent="_kjhafh-asda-qw"] {background:hotpink;}'

I don't know in advance what exactly the string is that I'm looking for, so I have to loop over the strings and find out. In the example above, the pattern would be [_ngcontent="_kjhafh-asda-qw"].
Is this even possible? Also, it would have to understand that maybe no such pattern exists. And are there methods for that or do I need to implement such an algorithm myself?
EDIT (context): We are building a validator, that checks a micro-frontend for global CSS rules (not prefixed and outside a shadow-dom), by loading it in isolation in a headless browser (within a jenkins pipeline) and validate, that it should not break any other stuff by global rules, that might be outside the context of the micro-frontend, on the same page. Using a headless browser, we can make use of the document.styleSheets property and not miss any styles that are being loaded. This will find <style> tags and its contents, aswell as content of external stylesheets.

A: Leveraging the BLAST algorithm, the following code snippet seeks successively matching substrings.

//
// See https://stackoverflow.com/questions/13006556/check-if-two-strings-share-a-common-substring-in-javascript/13007065#13007065
// for the following function...
//

String.prototype.subCompare = function(needle, haystack, minLength) {
    var i,j;
    haystack = haystack || this.toLowerCase();
    minLength = minLength || 5;

    for (i=needle.length; i>=minLength; i--) {
        for (j=0; j <= (needle.length - i); j++) {
            var substring = needle.substr(j,i);
            var k = haystack.indexOf(substring);
            if (k !== -1) {
                return {
                    found : 1,
                    substring : substring,
                    needleIndex : j,
                    haystackIndex : k
                };
            }
        }
    }
    return {
        found : 0
    }
}

//
// Iterate through the array of strings, seeking successive matching substrings...
//

strings = [
  '.bold[_ngcontent="_kjhafh-asda-qw"] {background:black;}',
  '[_ngcontent="_kjhafh-asda-qw"] {background-color:hotpink;}',
  'div > p > span[_ngcontent="_kjhafh-asda-qw"] {background:hotpink;}'
]

check = { found: 1, substring: strings[ 0 ] }
i = 1;
while ( check.found && i < strings.length ) {
  check = check.substring.subCompare( strings[ i++ ] );
}

console.log( check );

Note that without seeing a larger sampling of string data, it's not clear whether this algorithm satisfies the objective...

A: Thanks to Trentium's answer, I was able to do it. I adapted the code a little bit, as it was doing too much and also, the substr didn't yield a consistent result (it depended on the order of input strings).
The code could obviously be further minified/simplified.
const findCommonPattern = (base, needle, minLength = 5) => {
  const haystack = base.toLowerCase();

  for (let i = needle.length; i >= minLength; i--) {
    for (let j = 0; j <= needle.length - i; j++) {
      let prefix = needle.substr(j, i);
      let k = haystack.indexOf(prefix);
      if (k !== -1) {
        return {
          found: true,
          prefix,
        };
      }
    }
  }
  return {
    found: false,
  };
};

const checkIfCssIsPrefixed = (strings) => {
  let check = { found: true };

  let matchingStrings = [];

  for (let i = 1; check.found && i < strings.length; ++i) {
    check = findCommonPattern(strings[0], strings[i]);
    matchingStrings.push(check.prefix);
  }

  // Sort by length and take the shortest string, which will be the pattern that all of the strings share in common.
  check.prefix = matchingStrings.sort((a, b) => a.length - b.length)[0];
  return check;
};

console.log(
  checkIfCssIsPrefixed([
    ".spacer[_ngcontent-wdy-c0]",
    "[_nghost-wdy-c0]",
    ".toolbar[_ngcontent-wdy-c0]",
    "p[_ngcontent-wdy-c0]",
    ".spacer[_ngcontent-wdy-c0]",
    ".toolbar[_ngcontent-wdy-c0] img[_ngcontent-wdy-c0]",
    "h1[_ngcontent-wdy-c0], h2[_ngcontent-wdy-c0], h3[_ngcontent-wdy-c0], h4[_ngcontent-wdy-c0], h5[_ngcontent-wdy-c0], h6[_ngcontent-wdy-c0]",
    ".toolbar[_ngcontent-wdy-c0] #twitter-logo[_ngcontent-wdy-c0]",
    ".toolbar[_ngcontent-wdy-c0] #youtube-logo[_ngcontent-wdy-c0]",
    ".toolbar[_ngcontent-wdy-c0] #twitter-logo[_ngcontent-wdy-c0]:hover, .toolbar[_ngcontent-wdy-c0] #youtube-logo[_ngcontent-wdy-c0]:hover",
  ])
);


text:
Q: why my timer component is not working as a timer its time is not reducing i have a timer which shows the timer based on the time left by comparing it from now to the time received from server and shows timer what i have done is below, received time is the string like "2020-09-02T05:09:56.119Z" now i want the time to be the difference between time received from server and the time now but my timer is showing two times only as shown in the below gif
Link to the problem timer
 import React, {useState, useEffect} from 'react';
    import {Box, Message, Video, Timer, BlueScreen, Emoji, Heading, SubHeading, WaitingImage} from './styled' ;
    import Button from 'Components/Button';
    import { getAPatient } from '../api';
    import moment from 'moment';

    export default function WaitingRoom(){

        const { t } = useTranslation();
        const [timeLeft, setTimeLeft] = useState();

        const url = window.location.href.split('?id=');
        const id = url[1];

        const geTimerTime = async () => {
            await getAPatient(id)
            .then((info) => {
                const datetime = info && info.data.datetime;
                const currentTime = moment().toISOString()
                const d1 = new Date(currentTime);
                const d2 = new Date(datetime);
                const difference = d1 - d2;
                if (difference > 60e3){
                   const minutes = Math.floor(difference / 60e3);
                   const seconds = minutes * 60;
                   setTimeLeft(seconds)
                }
                else {
                   const seconds =  Math.floor(difference / 1e3);
                   setTimeLeft(seconds)
                }
                console.log(currentTime, datetime,difference,"infopoooo")
            })
            .catch((err) => {
               console.log(err)
            });
        }

        useEffect(() => {
             geTimerTime()

            if (!timeLeft) return;
      }, [timeLeft]);

        return(
         timeLeft === 0 ?
        <BlueScreen>
            <Emoji>
                <Smiley />
            </Emoji>
            <Heading>
                {t('turnMessageHeading')}
            </Heading>
            <SubHeading>
                {t('turnMessageSubHeading')}
            </SubHeading>
            <SubHeading>
            {t('turnMessageSubHeadingDoctor')}
            </SubHeading>
            <Button
              themeWhite
            >
                {t('commingMessage')}
            </Button>
         </BlueScreen>
         :
           <Box>
               <Button
                themeBlue
                width={'100%'}
                textAlign={'left'}
               >
                {t('Virtual_waiting_room')}
               </Button>
               <Message>
                    {t('waiting_message')}
               </Message>
               <Timer>
                    <div>{Math.floor(timeLeft/60) + ':' + ('0' + Math.floor(timeLeft % 60)).slice(-2)}</div> minutes
               </Timer>
               <WaitingImage>
                <Waiting />
               </WaitingImage>
               <Video>
                <iframe src='https://www.youtube.com/embed/gaka1vqYFNs'
                    frameborder='0'
                    allow='autoplay; encrypted-media'
                    allowfullscreen
                    title='video'
                    width={"100%"}
                />
               </Video>

           </Box>
        )
    }

A: It is simply because you call setTimeLeft, which sets the state for timeLeft, which in react triggers a re-render, during which all the useEffect() hooks will run, except for those that are not listening to changes on a state variable.
Furthermore, you have timeLeft in the dependency array (the second parameter in the hook), which means this useEffect() will run on every re-render where timeLeft state was set, thus running on each iteration.
If you need your useEffect() to run like componentDidMount, you need to keep an empty dependency array, thus ensuring the hook only runs on initial render
useEffect(() => {
         geTimerTime()

        if (!timeLeft) return;
  }, []);//empty dependency array to mimic componentDidMount

A: useEffect's set state Function should not match the second parameter. The useEffects is run whenever any data inside the second parameter's array is changed. Since you are changing the timeLeft inside the useEffects it will run infinitely. If you want to do geTimerTime anyway and have the timeLeft inside the dependency array(second parameter to useEffect) then you can do like below
useEffect(() => {
    if (timeLeft) {
        geTimerTime();
    }
}, [timeLeft])


text:
Q: Drag event on MS Edge duplicating the "preview content" on 2nd/n drag Hopefully someone can help, the following snippet word on chrome/FF/IE11 fine.
On edge, the 1st one is fine, the second (or sometimes third) on the drag preview still has the previous words in it which where dragged?
https://www.w3schools.com/code/tryit.asp?filename=FU78JD0SFVQM
Any help would be much appreciated
Thanks


text:
Q: Customer group price I want to make a customer group in magento where the customers in that group will have to pay 10% extra on top of the product price, is there a simple way (like adding discounts for customer groups) to do this?

A: You can accomplish this by setting the following:

*

*Regular pricing is 100% and that customer group gets regular price

*All other customer groups get special pricing at 10% off

You could do this with either the product pricing or with catalog price rules. The former is preferable as catalog price rules present the prices as a strikethrough discount.


text:
Q: How would I make it so that props.match.params.id can be accessed to any of the children Components? I'm currently trying to wrap my head around how to structure a ReactJS application. Here's the relevant information:
Dev Environment: npm, webpack
Dependencies: React, ReactDOM, React Router, React Router DOM
Code: (Cleaned up a bit as to not reveal more sensitive information.)
/***********
TABLE OF CONTENTS
01.0.0 - Imports
02.0.0 - Data
03.0.0 - Components
03.1.0 -- Base
03.2.0 -- Location
03.3.0 -- Main
03.3.2 --- Map
04.0.0 - Render
***********/

/* 01.0 Imports */
import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import {
  HashRouter,
  Route,
  Switch,
  Link
} from 'react-router-dom';

console.log("Set-up successful");
/* 02.0 Data */
const locationDataArray = {
  locations: [
    {
      "location": "Scenario A",
      "slug": "lipsum",
      "googleUrl": "https://www.google.com/maps/place/Central+Park/@40.7828687,-73.9675438,17z/data=!3m1!4b1!4m5!3m4!1s0x89c2589a018531e3:0xb9df1f7387a94119!8m2!3d40.7828647!4d-73.9653551",
      "mapUrl": "locations/scenA/main-map.png",
      "areaMaps": [
        {
          "name": "Overall",
          "url": "inner/map-overall.html"
        }, {
          "name": "A",
          "url": "inner/map-a.html"
        }, {
          "name": "B",
          "url": "inner/map-b.html"
        }
      ],
      "overallPDF": "diagram.pdf",
      "mapKey": "mapkey.txt",
      "mapImagemap": "imagemap.txt"
    } // list truncated for your convenience.
  ],
  all: function() {return this.locations},
  get: function(id) {
    const isLocation = q => q.slug === id
    return this.locations.find(isLocation)
  }
}

/* 03.0 Components */
/* 03.1 Base */
class App extends React.Component {
  constructor() {
    super();
    console.log("<App /> constructor locationDataArray: " + locationDataArray);
    this.state = {
      locationData: locationDataArray,
      test: 'testing!'
    };
  }
  render() {
    console.log("<App /> locationDataArray: " + locationDataArray);
    console.log("<App /> state, testing: " + this.state.test);
    return(

        <Switch>
          <Route exact path='/' component={LocationGrid} />
          <Route path='/locations/:id' component={MainMap}/>
        </Switch>

    );
  }
}

/* 03.2.0 -- Location */

class LocationGrid extends React.Component {
  constructor() {
    super();
  }
  render() {
    return(

Location Grid

          <Link to="/locations">Main Map</Link>

            { // this part works with extra items in locationDataArray.
              locationDataArray.all().map(q => (

                  <Link to={`locations/${q.slug}`}>{q.location}</Link>

              ))
            }

    );
  }
}

/* 03.3.0 -- Main */

class MainMap extends React.Component {
  constructor(props) {
    super();
    console.log("Main map is on");
    const location = locationDataArray.get(
      props.match.params.id
    );
    if (!location) {
      console.log("No such location!");
    }
    if (location) {
      console.log("These tests show that the locationDataArray is accessible from this component.");
      console.log("A: props.match.params.id is: " + props.match.params.id);
      console.log("B: Location is: " + location.location);
      console.log("C: Map URL: " + location.mapUrl);
      console.log("State is: " + location);
    }
  }
  render() {
    return (

        <MapHolder />

    );
  }
}

/* 03.3.2 --- Map */
//var mapUrl = require(location.mapUrl);
class MapHolder extends React.Component {
  render() {
    console.log("And these tests show that the locationDataArray is NOT accessible from this component.");
    console.log("1. Map location test, mapUrl: " + location.mapUrl);
    console.log("2. Map location test, slug: " + location.slug);
    return

      <map name="samplemap" id="mapofimage">
         <area target="" alt="1" title="1" href="inner/01.html" coords="288,356,320,344,347,403,315,420" shape="poly"></area>
         {/* Additional imagemap areas. Truncated for your conveinence.*/}
      </map>

A map would be here if I could figure out the bug.

  }
}

/* 04.0.0 -- Render */

ReactDOM.render((
  <HashRouter>
    <App />
  </HashRouter>
), document.getElementById('container'));

package.json and webpack.config.js are all in a git repository, if needed.
Overall Goal: I want to dynamically serve information to a main component and children components via a React Router route param and JSON object. Essentially, I want to be able to associate a param with an item in the object, so that the component can just refer to something like arrayItem.itemProperty and it can work dynamically.
I am trying to stay away from Redux as much as possible, since I'm already slightly overwhelmed by React now.
The Current Problem:
The array (on lines 26-55) is in the code, but anything outside of 1 component (<MainMap />, lines 113-138) can't access it.
An example of one of these child Components would be <MapHolder />, which is on lines 142-156. (I get ReferenceError: props is not defined in those cases.)
How would I make it so that props.match.params.id (or any other thing that would make this work) can be accessed to any of the children Components?
(Note: I'm well aware that the code isn't perfect. But this is still in early production stages, so I'd like to just resolve that one issue and hopefully the rest will clear up as a result of that.)

A: When you're using import/export, global variables aren't shared between modules. This is a good thing, but you can export multiple variables from a module. For example, you can export locationDataArray; in your App.js to access it from other modules without breaking the existing exports and imports for that module. That being said you almost never want to share global data in React like this. As a general rule of thumb you should "lift" data that components depend on to the highest component in the tree that needs in (you can even make an extra parent component to make this composition easier if you'd like).
When child components rely on data from part of a parent component's data, you should generally pass in subsets of data from parent components via props. Add a location prop to MapHolder with the actual map data for the given id, instead of making the component look up the id itself. Then in MapHolder's parent, render it like this:
<MapHolder
  location={locationDataArray.locations.find(location => location.slug === ID)}
  />

A: What you're looking for is React's Context feature. It's pretty low-level, and is an unstable API likely to change at any point. Meaning: use with caution.

In some cases, you want to pass data through the component tree without having to pass the props down manually at every level. You can do this directly in React with the powerful "context" API.

TL;DR:
First, declare the shape of the context object you will be making accessible to children, and implement getChildChildContext to actually return it:
class MyComponent extends React.Component {
  ...
  static childContextTypes = {
    foo: PropTypes.string // or whatever you have
  };

  getChildContext() {
    return {foo: "some value"};
  }
  ...
}

Then, when you want to access that context in a child component, declare that you wish to do so by declaring contextTypes on your child component:
class SomeChildComponent extends React.Component {
  static childContextTypes = {
    foo: PropTypes.string
  };

  render() {
    // use in your component by accessing this.context.foo
  }
}

If it feels klunky, that's because it's meant to be:

The vast majority of applications do not need to use context.
If you want your application to be stable, don't use context. It is an experimental API and it is likely to break in future releases of React.

You will probably get much better results from using a state management library such as redux or mobx to manage state that should be accessible from arbitrary components.


text:
Q: In a parent window, how do I know which button is clicked in a child window? In JS ...
In a parent window, how do I know which (or if a) button is clicked in a child window?
I have a node function which builds the HTML page and creates the buttons as such:
    tosend += "
   <button id='abort' onclick='window.close() '>Cancel/Abort</button> " +
              "<button id='acceptid' type='button' " + "onclick='window.close();'>Accept & Close</button>   ";

Node sends the HTML back to the parent client which creates the child and
waits for the user response like so:
ws.onmessage = function(e) {
    const w = window.open('about:blank');
    w.document.open();
    w.document.write(e.data);
    w.document.close();

    /* wait for user to confirm */
    const timer = setInterval(() => {
        tosend = "";

        if (w.document.getElementById("acceptid").clicked == true) {    /* placeholder, see note below */
            tosend = "acceptid button clicked";
        } else {
            tosend = "none";
        }

        if (w.closed) {
            clearInterval(timer);

            ...
            ...

        }
    }, 500);
}

Note - I realize that ".clicked" is not valid.  It's just there as a
placeholder.

A: You won't really need an interval for that. You could just attach a click event handler to the document and that should do it.

function onUserSelection(event) {
  let tosend = '';

  if (event.target.id === 'acceptid') {
    tosend = 'acceptid button clicked';
  } else if (event.target.id === 'abort') {
    tosend = 'none';
  }

  console.log(tosend);
}

ws.onmessage = function (e) {
  const w = window.open('about:blank');
  w.document.open();
  w.document.addEventListener('click', onUserSelection, { once: true });
  w.document.write(e.data);
  w.document.close();
};

A: I got this working by changing:
tosend += "
   <button id='abort' onclick='window.close() '>Cancel/Abort</button> " +
  "<button id='acceptid' type='button' " + "onclick='window.close();'>Accept & Close</button>   ";

to
tosend += "
   <button id='abort' onclick='window.close();'>Cancel/Abort</button> " +
  "<button id='acceptid' type='button' " +
  "onclick='window.opener.setValue(true);window.close();'>Accept & Close</button>   ";

In the client parent I added:
var usedconfirm;

function setValue(val1) {
  usedconfirm = 1;
}

Just before the timer in the parent client added:
usedconfirm = 0;

And replaced:
if (w.document.getElementById("acceptid").clicked == true) {

with:
if (usedconfirm) {


text:
Q: Using a Class Library for ASP.NET Membership Provider with MySQL I am attempting to use the ASP.NET Membership Provider with a MySQL database with mixed success. My solution currently contains an ASP.NET MVC project that has been configured to use MySQL and another project that handles all calls to the database in which I also want to handle membership functions such as creating and validating users.
Both projects have MS .NET EnityFramework v6.1.3, Microsoft.AspNet.Identity.EntityFramework v2.2.1 and MySql.Data.Entity v6.9.7 installed.
I configured the ASP.NET project as per the instructions at http://k16c.eu/2014/10/12/asp-net-identity-2-0-mariadb/. My "web.config" is configured as follows;
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </configSections>
    <connectionStrings>
        <remove name="LocalMySqlServer" />
        <add name="LocalMySqlServer"
            connectionString="Server=localhost; Database=rb-web; Uid=root; Pwd=password; Convert Zero Datetime=True; Allow User Variables=True;"
            providerName="MySql.Data.MySqlClient" />
    </connectionStrings>
    <system.web>
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5" />
    </system.web>
    <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
            <parameter value="mssqllocaldb" />
        </parameters>
        </defaultConnectionFactory>
        <providers>
            <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
            <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
        </providers>
    </entityFramework>
    <system.data>
        <DbProviderFactories>
            <remove invariant="MySql.Data.MySqlClient" />
            <add name="MySQL Data Provider"
                invariant="MySql.Data.MySqlClient"
                description=".Net Framework Data Provider for MySQL"
                type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
        </DbProviderFactories>
    </system.data>
</configuration>

The instructions at http://k16c.eu/2014/10/12/asp-net-identity-2-0-mariadb/ required creating two new classes, ApplicationUser.cs and ApplicationContext.cs however these were basically replicating the code in IdentityModels.cs which was already included in my project. The identity model code is;
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using MySql.Data.Entity;

namespace RB.Client.Models
{
    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            return userIdentity;
        }
    }

    [DbConfigurationType(typeof(MySqlEFConfiguration))]
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext() : base("LocalMySqlServer", throwIfV1Schema: false) { }
        public ApplicationDbContext(string connStringName) : base(connStringName, throwIfV1Schema: false) { }
        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // Primary keys can easily get too long for MySQL's (InnoDB's) stupid 767 bytes limit.
            // The following lines rewrite the generation to keep those columns "short" enough.
            modelBuilder.Entity<IdentityRole>()
                .Property(c => c.Name)
                .HasMaxLength(128)
                .IsRequired();

            // Declare the table name here, otherwise IdentityUser will be created.
            modelBuilder.Entity<ApplicationUser>()
                .ToTable("AspNetUsers")
                .Property(c => c.UserName)
                .HasMaxLength(128)
                .IsRequired();
        }
    }
}

Once these changes were made I ran the Enable-Migrations from Package Manager Console and modified the Configuration.cs class as follows;
namespace RB.Client.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<RB.Client.Models.ApplicationDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
            SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
        }

        protected override void Seed(RB.Client.Models.ApplicationDbContext context)
        {
        }
    }
}

I then ran the Add-Migration "Initial" and Update-Database command from the Package Manager Console which created the aspnetroles, aspnetuserclaims, aspnetuiserlogins, aspnetuserroles and aspnetusers tables in MySQL.
I then use the following code in my persistence project;
public UserDto RegisterUser(UserDto user)
{
    var appUser = Membership.CreateUser(user.Email, user.Password);
}

Which raises the exception;
"Unable to initialize provider. Missing or incorrect schema."
"MySql.Web at MySql.Web.Common.SchemaManager.CheckSchema(String connectionString, NameValueCollection config)
at MySql.Web.Security.MySQLMembershipProvider.Initialize(String name, NameValueCollection config)
at System.Web.Configuration.ProvidersHelper.InstantiateProvider(ProviderSettings providerSettings, Type providerType)"
However, if I add the following entries to the "web.config";
<system.web>
    <roleManager defaultProvider="MySQLRoleProvider">
        <providers>
            <remove name="MySQLRoleProvider" />
            <add name="MySQLRoleProvider"
                 type="MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"
                 applicationName="/RBWeb"
                 description="RB Role Provider"
                 connectionStringName="LocalMySqlServer"
                 writeExceptionsToEventLog="True"
                 autogenerateschema="True"
                 enableExpireCallback="False" />
        </providers>
    </roleManager>

    <membership defaultProvider="MySQLMembershipProvider">
        <providers>
            <remove name="MySQLMembershipProvider" />
            <add name="MySQLMembershipProvider"
                 type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"
                 applicationName="/RbWeb"
                 description="RB Membership Provider"
                 connectionStringName="LocalMySqlServer"
                 writeExceptionsToEventLog="True"
                 autogenerateschema="True"
                 enableExpireCallback="False"
                 enablePasswordRetrieval="False"
                 enablePasswordReset="True"
                 requiresQuestionAndAnswer="False"
                 requiresUniqueEmail="True"
                 passwordFormat="Hashed"
                 maxInvalidPasswordAttempts="5"
                 minRequiredPasswordLength="6"
                 minRequiredNonalphanumericCharacters="1"
                 passwordAttemptWindow="10"
                 passwordStrengthRegularExpression="" />
        </providers>
    </membership>

    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
</system.web>

The user is successfully created and a System.Web.Security.MembershipUser object is returned. However the call has now generated a number of new tables in the database, my_aspnet_users, my_aspnet_roles, etc along with all of the tables for profiles, personalisation, and session management even though these options weren't included in the web.config settings and the user record was created in these tables. There seems to be a disconnect between my web and persistence projects.
I have reviewed all of the articles I could find in MySQL however these all appear to be out of date and were of no help. At this point I am now writing a custom membership provider to try and get around these problems but to be honest I'm also considering ditching MySQL due to the problems I have faced trying to get this to work.


text:
Q: draw network topology (php/jquery) I work for the small ISP.
We need to draw network topology in our project for network management.
I usually have this data:

"cisco"
      | => "d-link"
      | => "d-link"

and so on...
So. Using PHP and jQuery how can i draw simple but nice topology picture?
Thanks in advance! Appreciate your support.

A: In PHP, you could call out to Graphviz to make the images. There's probably a PHP wrapper for Graphviz already written out there, but it's pretty easy to call it yourself.
For example, this input file (in example.dot):
digraph example {
    dlink1 [label="d-link"];
    dlink2 [label="d-link"];
    cisco -> dlink1;
    cisco -> dlink2;
}

Can be converted into an image:
$ dot -Tpng -o example.png example.dot

Here's the result:


text:
Q: Perl cross compilation issue I am newbie to perl cross compilation.
I'm trying to install perl from source as given in www.perl.org.
Commands followed are ./Configure, Make, Make test.
To find the path for specific installation, the CLI "perl -V" shows error as follows.
# ./perl -V
Can't locate Config.pm in @INC (@INC contains: /usr/local/lib/perl5/5.9 .).
BEGIN failed--compilation aborted.

I think i have done some mistake in path inclusions.
Please let me know the reason and solution for successfull cross compilation.
Thanks in advance.

A: It's probably possible to cross-compile Perl (building on Linux and targeting for BSD), but there's not much point in doing so.  NetBSD is as capable as Linux of building Perl locally, and that's almost certainly what you should do.
You can build it from source, following the installation instructions, or better yet you can install a binary package, since somebody else has already done the work of building Perl from source for you.
Unless you have a very specific requirement for an old version, you should install the most recent production version, which I believe is 5.14.2.
You mentioned in a comment that when you build Perl from source on your target BSD machine, Make test had 2 failures.  You had a 99.86% success rate.  Surely that's good enough -- and you're not likely to do any better by cross-compiling.  You might want to look into those failures and the LD_LIBRARY_PATH issue (I don't know what it should be set to for NetBSD), but those issues aren't so serious that you should give up and use a radically different approach.


text:
Q: Computing S-Matrix Elements from Feynman Diagrams In Peskin and Schroeder (PS), the Feynman rules for calculating correlation functions are first presented. Only terms involving all field contractions need to be considered.
In Section 4.6, this is then extended towards calculating S-matrix elements. Now terms that aren't fully contracted may contribute.
For example, consider $$\langle p_{1}p_{2}|T\left(-i\frac{\lambda}{4!}\int d^4{x}\phi^{4}(x)\right)|p_{A}p_{B}\rangle=\langle p_{1}p_{2}|N\left(-i\frac{\lambda}{4!}\int d^4{x}\phi^{4}(x)+\textrm{contractions}\right)|p_{A}p_{B}\rangle$$
as in Equation 4.92 of PS. If we contract only two field operators, clearly terms including $a^{\dagger}a$ will still contribute. We need a way to deal with this.
Given that $\phi(x)=\phi^{+}(x)+\phi^{-}(x)$ PS shows that $\phi^{+}(x)|p\rangle=e^{-ipx}|0\rangle$, before stating
'An uncontracted $\phi$ operator inside the N-product of (4.92) has two terms: $\phi^{+}$ on the far right and $\phi^{-}$ on the far left.'
This is just the definition of normal ordering, I believe.
'We get one contribution to the S-matrix element for each way of commuting the $a$ of $\phi^{+}$ past an initial-state $a^{\dagger}$, and one contribution for each way of commuting the $a^{\dagger}$ of $\phi^{-}$ past a final state $a$.'
I don't think I get this. What does it mean by 'way of commuting'? Does it mean that, because $|p_{A}p_{B}\rangle=a^{\dagger}(p_{A})a^{\dagger}(p_{B})|0\rangle=a^{\dagger}(p_{B})a^{\dagger}(p_{A})|0\rangle$ there are two 'ways' - either past $a^{\dagger}(p_{A})$ or $a^{\dagger}(p_{B})$?
It is natural, then, to define the contractions of field operators with external states as follows: $$C(\phi(x)|p\rangle)=e^{-ipx}|0\rangle$$ $$C(\langle p|\phi(x))=\langle 0|e^{ipx}$$ I have denoted a contraction using $C()$. I don't really see how this follows from the above, assuming my interpretation so far is correct.
Could anybody possibly give a bit more detail as to what is being explained here? Thank you!

A: This business of "contractions" is just an overly formal way of saying the following: "commute all ladder operators until they annihilate the vacuum; your matrix element is given by whatever delta functions you pick up along the way."
Commuting the $a$ in $\phi(x)$ with $a^\dagger$ in $| p \rangle$ produces a delta function, but $\phi$ integrates over the momentum, so you pick up the coefficient $e^{-ip\cdot x}$ of $a$. (The factor $1/\sqrt{2 \omega_p} $ is cancelled by that in $| p \rangle$).

A: If you are looking for a painstaking walk-through of the procedure @rwold described, you can check this link out: https://physics.stackexchange.com/a/695210/303868


text:
Q: Mongodb and Express deleting an item from _id I'm new to Express and databases. I'm trying to create a simple CRUD todo list by following several tutorials using Mongo DB (not Mongoose), Express, Node, and Handlebars.
I can create items from an input form and have them successfully save to the Mongo database and the page. I can't figure out how to delete each item based on a button click both on the page and from the database. Ideally, I want to target them based on the _id that Mongo creates.
I think the issue might be having something to do with the way I'm trying to select each item. Any suggestions or easier ways to implement this would be great!
Here is my code for Express:
// Connecting Mongo DB
MongoClient.connect(url, (err, client) => {
  if (err) return console.log(err)
  db = client.db('todoitems')
})

 // Save items to DB from form
app.post('/items', (req, res) => {
  db.collection('items').save(req.body, (err, result) => {
    if (err) return console.log(err)
    console.log(req.body, {_id: req.body._id})
    res.redirect('/')
  })
})

// Delete item on click from DB
app.delete('/items/:id', (req, res) => {
  db.collection('items').remove({_id: req.body.id}, (err, result) => {
    if (err) return console.log(err)
    console.log(req.body)
    res.redirect('/')
  })
})

// Get items from DB to page
app.get('/', (req, res) => {
  db.collection('items').find().toArray((err, result) => {
    if (err) return console.log(err)
    res.render('index', {
      layout: false,
      items: result
    });
  })
})

And here is my code from the Handlebars file:
  <form action="/items" method="POST">
    <input type="text" placeholder="item" name="item">
    <input type="hidden" id="date" name="date" value="CurrentDate">
  </form>

    {{#each items}}

        {{item}} |
        {{date}}
        <button id={{_id}}>x</button>

    {{/each}}

A: If you are removing by _id, you need to pass an ObjectID(id) not a "string" id, something like:
remove({_id: mongodb.ObjectID( req.params.id)} ...

So, your code should be like:
app.delete('/items/:id', (req, res) => {
  db.collection('items').remove({_id: mongodb.ObjectID( req.params.id)}, (err, result) => {
    if (err) return console.log(err)
    console.log(req.body)
    res.redirect('/')
  })
})


text:
Q: Add folders in ubuntuone with kubuntu 11.04 I've installed the client for ubuntuone in my kubuntu 11.04 desktop but I'd like to add and sync some other folders of my home dir except the standard one, is it possible?
Thank you all.

A: You will find almost everything you need here:
https://wiki.kubuntu.org/UbuntuOne/Tutorials/Files


text:
Q: How can I make my embedded svg image stetch to fill a container? I have an embedded svg that is will only stretch to about 2/3 of it's container size. I would like to get it to fill the entire container.
Here's how it currently looks:

I have a plunker here showing the embedded svg: http://plnkr.co/edit/5PbBmhV6aBiAtanXTVgM
The simplified svg structure is like this:
    <svg id="approach_shot" viewBox="0 0 360 360" preserveAspectRatio="xMinYMin meet" class="content">
        <rect fill="#FFFFFF" stroke="#000000" stroke-width="0.5" width="360" height="360"></rect>
        <g id="green">
          <defs>
            <circle id="ball" r="6" stroke="#000000" fill="#FFFFFF" stroke-width="0.5"></circle>
          </defs>
          <g>
              <path fill="#005C1F" stroke="#005C1F" stroke-width="0.75" stroke-miterlimit="10" d="M42.09 171.26c-10.48-25.3-9.77-52.43-0.17-75.92l-18.48-7.65c-11.56 28.22-12.42 60.83 0.17 91.23 0.08 0.2 0.17 0.4 0.25 0.6l18.48-7.65C42.26 171.65 42.17 171.46 42.09 171.26z"/>
              more paths...
          </g>
          <g id="shots">
            <use xlink:href="#ball" transform="translate(150,150) scale(1.0)" />
          </g>
        </g>
    </svg>

I've been hacking on this for a few hours, and nothing I do impacts that green image. The outer rectangle fills the container just fine.
Thanks for your help!

A: The simplest way is to fix your viewBox attribute.  You currently have it set to a width and height of 360, when your circle is only about 247 in diameter.
The top-left of the circle is at roughly (11, 9.5), so changing your viewBox to:
viewBox="11 9.5 247 247"

will cause it to fill your viewport.
How did I determine the dimensions of the circle?  I used a little bit of javascript and called the getBBox() function on the element with id="green".
var b = document.getElementById("green").getBBox();
alert(b.x+" "+b.y+" "+b.width+" "+b.height);

Demo here


text:
Q: I do not want my VBA code to change sheets So, I'm trying to use the code to simply refresh a Pivot Table every time an alteration is made in the main sheet (dashboard).
As I need to keep it clean, I have another sheet, where all infos are, named historic_var.
The problem is, when I run the code, it works well, but it changes to the sheet that has no use (unless keep the infos safe). What can I do? Already tried application.ScreenUpdating = False
The current code is:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column <= 14 Then
        Sheets("historic_var").Select
        ActiveSheet.PivotTables("Tabela dinâmica1").PivotCache.Refresh
    End If
End Sub

A: YOu can update the table without changing the sheet. Try this out...
Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Column <= 14 Then

    Sheets("historic_var").PivotTables("Tabela dinâmica1").PivotCache.Refresh
    End If

End Sub


text:
Q: Moving files with bash scripts I have a bash script that watches a folder, if something is added to the folder, the script will move all contents withing the monitored folder to the defined destination.
THE ISSUE:
             - The script fails to move the files in the monitored folder to the destination folder through FileZilla (FTP). The script does work if you move the file to the monitored folder manually through a shell prompt. FTP is the only format not working properly.
Any Ideas what the issue may be?
Here is the script:
inotifywait -m ~/folderA/fileA -e moved_to |
    while read path action file; do
        #echo "The file '$file' appeared in directory '$path' via '$action'"
        # do something with the file
    mv ~/folderA/fileA/* "/folderB/myNewDest"
    done

A: First, by having inotifywait -e moved_to only monitor for files moved to the target directory, you omit monitoring for files that were written or overwritten there, by, for example Filezilla. Add -e modify -e create to your command, or, unless you have a convincing reason to ignore some inotifywait events, discard all the -e whatever options.
Second, by not quoting the from files in your mv ~/folderA/fileA/* "/folderB/myNewDest" command you run the risk of being caught by silly filenames, e.g. foo;rm -rf *. I would suggest
find ~/folderA/fileA/ -maxdepth 0 -type f -print0 | \
xargs -0 mv --target-directory=/folderB/myNewDest --

which does the same thing, but more safely.


text:
Q: Splitting domain name over two hosts I want to make the move to Webflow for a client project that require a CMS. I would like some more information about the logistics and best practices of adding domains though.
Say for instance I have a client's home page and a blog hosted on Webflow and this is accessed by their custom domain. what if I still need to host additonal files, and other pages on a traditional hosting platform with cPanel?
Would it be best to point the www.clientwebsite.com to Webfllow and keep the clientwebsite.com pointing at traditional host with a 301 redirect to the www.clientwebsite.com
I could still have pages on the traditional host for example clientwebsite.com/page.html while being able to add additional pages to Webflow e.g. www.clientwebsite.com/page.html
Basically I want to be able to use the same domain name on both Webflow and traditional hosting with cPanel, I just want to know what the best way to do this is, is there a better way to achieve this, is there anything to be careful of/ or would be considered bad practice?
Thanks in advance

A: Typically, one hostname will resolve to one IP address, so one hosting platform has to be the entry point. If the sites can be logically separated, you should probably just use different hostname (blog.example.com, www.example.com, something.example.com) and point them to different hosting platforms.
If you need to have content from the 2 platforms served under the same hostname, then one platform will be the entry point and there it will have some internal rewrite/proxy rules to fetch and serve content from somewhere else. This is easily doable in all modern webservers (nginx, apache..) but I am not sure your CMS platform will allow it.


text:
Q: Linux: Recursively find all .txt files that don't have a matching .tif I am using Debian Linux. I'm a newbie. I'll do my best to ask in the simplest way I know.
I have a pretty deep tree of directories on a drive that contain thousands of .tif files and .txt files. I'd like to recursively find (list) all .txt files that do not have a matching .tif file (basename). The .tif files and .txt files are also located in separate directories throughout the tree.
In simple form it could look like this...
directory1: hf-770.tif, hf-771.tif, hf-772.tif
directory2: hf-770.txt, hf-771.txt, hf-771.txt, hr-001.txt, tb-789.txt
I need to find (list) hr-001.txt and tb-789.txt as they do not have a matching .tif file. Again the directory tree is quite deep with multiple sub-directories throughout.
I researched and experimented with variations of the following commands but cannot seem to make it work. Thank you so much.
find -name "*.tif" -name "*.txt" | ls -1 | sed 's/\([^.]*\).*/\1/' | uniq

A: You can write a shell script for this:
#!/bin/bash
set -ue
while IFS= read -r -d '' txt
do
    tif=$(basename "$txt" | sed s/\.txt$/.tif/)
    found=$(find . -name "$tif")
    if [ -z "$found" ]
    then
        echo "$txt has no tif"
    fi
done < <(find . -name \*.txt -print0)

This has a loop over all .txt files it finds in the current directory or below. For each found file, it replaces the .txt extension with .tif, then tries to find that file. If it cannot find it (returned text is empty), it prints the .txt file name.
robert@saaz:$ tree
.
├── bar
│   └── a.txt
├── foo
│   ├── a.tif
│   ├── b.tif
│   ├── c.tif
│   └── d.txt
└── txt-without-tif

2 directories, 6 files
robert@saaz:$ bash txt-without-tif
./foo/d.txt has no tif


text:
Q: I gonna vs. I'm gonna I live in Germany where I often hear 'I gonna' or 'you gonna', in effect treating 'gonna' as a main verb and missing out the copula 'to be'. AAE also has a 'zero' copula. Perhaps this clitic will be dropped in all spoken Englishes in the future. For the moment, I was wondering where the confusion might lie.
1) Is there a phonological reason behind dropping the clitic?
2) Is this a German-speakers' phenomenon?
3) Are some forms (e.g. questions, 'you gonna come?') closer to a standard?

A: I don't have answers to your specific questions, but I think it might be useful to point out that the phenomenon you describe differs in important ways from 'zero copula' (more precisely, 'zero auxilliary') phenomenon in African American Vernacular English (AAVE). According to an "Our Living Language" note in the American Heritage Dictionary, which I will reproduce below, in AAEV

only is and are are deleted; am is frequently contracted but never deleted.

But in your case, it is am that is deleted.
Here is the note in full:

A widely known feature of African American Vernacular English (AAVE) and some varieties of Southern American English spoken by working-class white people is the absence of a form of be in situations where Standard English would normally require one. In these varieties of English, one can say He working, where Standard English has He is working, meaning "He is working right now." Linguists frequently describe this zero usage as zero copula, although strictly speaking the term zero copula should be used for missing inflected forms of be before nouns, adjectives, and constructions indicating place or time (as in She the leader, John nice, and He at home), and we should use the term zero auxiliary for progressive verb forms that have no form of be (as in He working) and when a form of be is missing before going to or gon(na) (as in He gon do it). The use of zero copula and zero auxiliary is perhaps even more characteristic of AAVE than is invariant habitual be. For some AAVE speakers, zero copula occurs 80 to 90 percent of the time where Standard English requires is or are. No other varieties of American English use zero copula as often.
As with all dialectal features, zero copula use is more systematic than it might at first appear. As the examples above indicate, only present tense inflected forms of be can be deleted (was and were cannot be deleted), and even among present forms, only is and are are deleted; am is frequently contracted but never deleted. Invariant or non-finite forms, such as be in You have to be good can't be deleted, nor can forms that come at the end of a clause (That's what he is). In the late 1960s, linguist William Labov summarized most of these generalizations by stating that wherever Standard English can contract is or are, AAVE can delete it. (Note that Standard English does not tolerate contractions in sentences such as That's what he's.) Equally systematic are the quantitative regularities of the zero copula. Throughout the United States, zero copula is less frequent when followed by a noun (He a man) than when followed by an adjective (He happy). It is most frequent when followed by progressives and gon(na), as exemplified above.
This pattern of be-deletion is also found in Gullah and Caribbean Creole varieties of English. Since zero copula is not a feature of the British dialects of English that colonial settlers brought to the United States, it is one of the strongest indicators that the development of AAVE may have been influenced by Caribbean English creoles or that AAVE itself may have evolved from an American Creole-like ancestor.
(American Heritage Dictionary)

A: Let's break down the sentences:
I gonna is I going to, which doesn't really sound correct.
I'm gonna is I am going to, which sounds more gramatical.
This is from an English Speaker's point of view, so I don't know about Germany.

A: This is just a conjecture, but in the German language present continuous doesn't exist, so it could be a "germanification" of the present continuous. It could be that they use "gonna" as "will", since they always use "will" ("werde" in German) for future references.

A: I'm gonna is correct. Seeing that "I'm" means I am. So it would be I gonna V.S. I am gonna (the latter is correct).


text:
Q: How do you get descriptions of the available `shopt` options? What is the canonical way for accessing the local documentation on any available Shell Options builtin with shopt?
I'm using Ubuntu 12.04 and can run help shopt to get a description of what shopt does:
shopt: shopt [-pqsu] [-o] [optname ...]
    Set and unset shell options.
    ...

I can list the various Shell Options and their values (shopt or shopt -p). But how do I find out what each one actually does without leaving the comfort of my Linux box? I'm not looking for the descriptions online. Is there a man page or something I'm missing?

A: You can find the list of options in the man page under the description of the shopt builtin. To open the man page at the list of options, you can use the less feature that lets you run a command such as a search when it starts:
PAGER='less "+/^ *The list of shopt"' man bash

To view this documentation in Info:
info --index shopt bash

If you want to extract the relevant part of the man page:
man bash | sed '/^ *The list of shopt/, /^ *suspend / p' | sed '$d'

or (nicer, as it removes the indentation)
man bash | awk '
    /^ *The list of shopt/ {indent=match($0, /[^ ]/)}
    /^ *suspend / && RSTART==indent {exit}
    indent {print substr($0, indent)}'

If you want to extract the description of one option (e.g. sourcepath):
man bash | awk -v target=sourcepath '
    /^ *The list of shopt/ {shopt=1}
    shopt && $1==target {getline; indent=match($0, /[^ ]/)}
    indent {if (match($0, /[^ ]/)>=indent) print substr($0, indent); else exit}'

A: See the "shell builtin commands" section of man bash; it has an entry for shopt that describes all of the available shell options. Here is an excerpt:
   shopt [-pqsu] [-o] [optname ...]

   [...]

          autocd  If  set,  a command name that is the name of a directory
                  is executed as if it were the argument to  the  cd  com-
                  mand.  This option is only used by interactive shells.
          cdable_vars
                  If  set,  an  argument to the cd builtin command that is
                  not a directory is assumed to be the name of a  variable
                  whose value is the directory to change to.
          cdspell If set, minor errors in the spelling of a directory com-
                  ponent in a cd command will be  corrected.   The  errors
                  checked for are transposed characters, a missing charac-
                  ter, and one character too many.   If  a  correction  is
                  found,  the corrected file name is printed, and the com-
                  mand proceeds.  This option is only used by  interactive
                  shells.

          [...]