text:
Q: Why does this loop reverses a String in Java I'm trying to remove whitespaces in a given string, and, while I've achieved this, the returned String appears reversed. Can anyone please explain why?
public String removeSpaces(String cadena) {
    String noSpace="";
    for (int i = 0; i < cadena.length(); i++) {
        if (cadena.charAt(i) == ' ') {
            noSpace=noSpace;
        }else{
            noSpace=cadena.charAt(i)+noSpace;
        }
    }
    return noSpace;
}

A: To remove whitespace, you could have done something like the following:
str.replaceAll("\\s+","")

A: If you want to use this kind of method just change it slightly:
public String removeSpaces(String cadena) {
String noSpace="";
for (int i = 0; i < cadena.length(); i++) {
    if (cadena.charAt(i) != ' ') {
        noSpace+=cadena.charAt(i);
    }
}
return noSpace;
}


text:
Q: How to properly report aborted suites from SBT, Scalatest and Junit reporter I am running Bamboo, SBT (0.13.x) and Scalatest (2.x). I use the Junit reporter like
testOptions in Test += Tests.Argument("-u", "target/junit")

However, when a suite is aborted in Scalatest there is no indication (build not failing in Bamboo). Is there another Runner option which I should use to notify the Junit reporter of the aborted suite?
16-May-2014 16:29:55    [info] Total number of tests run: 8
16-May-2014 16:29:55    [info] Suites: completed 2, aborted 1
16-May-2014 16:29:55    [info] Tests: succeeded 8, failed 0, canceled 0, ignored 0, pending 0
16-May-2014 16:29:55    [info] *** 1 SUITE ABORTED **

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to download file in ASP.Net using Response.TransmitFile says "Could not find part of the path" I am using ASP.Net Webforms and C# to download a file which I stored at a physical path.
(C:\Users\Public\Temp). Since I did not store  the file on the server, I am using a physical location to download the file using the following code snippet from the .aspx handler
        HttpRequest request = System.Web.HttpContext.Current.Request;
        HttpResponse response = System.Web.HttpContext.Current.Response;
        String fileName = request.QueryString["fileName"];
        String storagePath = "C:/Users/Public/Temp/";
        String filePath = String.Format("{0}/{1}", storagePath, fileName);
        response.ClearContent();
        response.Clear();
        response.ContentType = "application/octet-stream";
        response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.TransmitFile(filePath);
        response.Flush();
        response.End();

I got the reference from the post here. But, when I initiate the download through a button click, I get the

"Could not find part of the part C:/Users/Public/Temp/"

message on the exception. I am not sure if this is because of the folder not being on the server. Is there anything I need to add to the file path? Please help me understand where I am going wrong. Please do suggest if there is a better way of doing the downloads.
(This is a prototype I am working on which I will extend to a network location)

A: I figured this was because of the fileName query string being empty (due to postbacks). Pretty lame I didn't find it before. In this case , the TransmitFile was getting a path to the "C:/Users/Public/Temp/" but not the actual file path and hence the error.
Now, I  persist the data for fileName using ViewState and TransmitFile gets the full path C:/Users/Public/Temp/fileName and it works fine.


text:
Q: Is the $n/2$-th heat kernel coefficient topological? Let $M$ be an $n$-dimensional manifold, with $n$ even and consider the heat kernel of the Laplacian on $M$:
$$K_M(t) := \mathrm{Tr}\Big(\mathrm{e}^{-t \Delta_M}\Big) \equiv \sum_{\lambda\in\mathrm{spec}(\Delta_M)} \mathrm{e}^{-t \lambda}.$$
The heat kernel admits an asympotic small-$t$ expansion as
$$K_M(t) = \frac{1}{(4\pi t)^{n/2}}\sum_{k=0}^\infty b_k(M) t^k,$$
where $b_k(M)$ are known as the heat kernel coefficients and are given by integrals of local geometric data of $M$.
I am particularly interested in what I'll call middle-dimensional heat kernel coefficient, namely
$$ b_{n/2}(M) = b_{\mathrm{dim}M/2}(M).$$
This coefficient is interesting because it is closely related to the value of the Minakshisundaram-Pleijel zeta function (i.e. the spectral zeta function for the Laplacian) at zero.
Is an explicit formula for the calculation of $b_{n/2}(M)$ known? In particular, is it a topological invariant? It seems to me that it wants to be related to the number of connected components of $M$ or to some sum of Betti numbers of $M$, but I haven't managed to show it.
(If anyone feels brave, I'd be curious about how it generalizes to $p$-forms; namely what's the middle-dimensional heat kernel coefficient associated with the Laplacian, $\Delta_p = \mathrm{d}\delta + \delta \mathrm{d}$, acting on $p$-forms on $M$)


text:
Q: bootstrap-select me devuelve el text pegado de lo que se selecciona tengo una duda..
Estoy trabajando con bootstrap-select por primera vez, al seleccionar mas de una opcion en pantalla me los muestra separados por coma, por ejemplo:
UNO, DOS, TRES, CUARTO
y al obtener el valor desde el archivo js con el comando
$("#combobox option:selected").text();  me devuelve el valor UNODOSTRESCUATRO, como puedo obtenerlo al igual como me lo muestra en pantalla?
Este es el codigo del select:
<select class="selectpicker" multiple name="combobox " id="combobox " >
                        <option value="1">UNO</option>
                        <option value="2">DOS</option>
                        <option value="3">TRES</option>
                        <option value="4">CUATRO</option>

                    </select>

A: Podrías utilizar la función change de JQuery para eso, de esta forma:
$('.selectpicker').on('change', function(){
   var selected = []
   selected = $(this).val()
})

$(document).ready(function(){
  $('.selectpicker').selectpicker();
  $('.selectpicker').on('change', function(){
    var selected = []
    selected = $(this).val()
    alert(selected);
  })
})
.dropdown:hover > .dropdown-menu {
display: block;
margin: 0px;
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.2/css/bootstrap-select.min.css" rel="stylesheet"/>

  <select class="selectpicker" multiple>
    <option>Mustard</option>
    <option>Ketchup</option>
    <option>Relish</option>
  </select>

A: Si haces $('#combobox').val() te va a devolver un vector con cada value de cada option seleccionado, pero si lo que necesitas son los textos de los ítems seleccionados podrías utilizar el map de jQuery para recorrerlos y obtener su texto, y después juntar todo con un join.
Acá te dejo un ejemplo que podés ejecutar y verlo.
¡Suerte!

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.2/css/bootstrap-select.min.css" rel="stylesheet"/>

<select class="selectpicker" multiple name="combobox" id="combobox">
  <option value="1">UNO</option>
  <option value="2">DOS</option>
  <option value="3">TRES</option>
  <option value="4">CUATRO</option>
</select>

<button onclick="verValor()">Prueba</button>

A: Tambien puedes poner la funcion onchange en el elemento:
<select class="selectpicker" multiple name="combobox " id="combobox " onchange="myfunction(this.value)" >
                    <option value="1">UNO</option>
                    <option value="2">DOS</option>
                    <option value="3">TRES</option>
                    <option value="4">CUATRO</option>

                </select>


text:
Q: Reference for a result in measure theory I'm studying the Aldous-Hoover Theorem and I've seen in many references that its analogous in dimension zero is a result of abstract measure theory:

Let $\nu:E\rightarrow [0,1]$ be a Borel probability measure on a standard Borel space $E$. Then there is a measurable $f:[0,1]\rightarrow E$ such that, given a random variable $U\sim U[0,1]$, \begin{equation*}f(U)=^d X,\end{equation*}where $X$ is a random variable with values in $E$ and law $\nu$.

I am interested in seeing the proof of this result. Can you tell me where to find it?
Thank you

A: You can find this result in Kallenberg's book Foundations of Modern Probability. It is Lemma 2.22 in the first edition and Lemma 3.22 in the second edition. Kallenberg states the result in a more general way involving a probability kernel $\mu\colon S\rightsquigarrow T$. But the result you want is the special case when $S$ is the one-point space, in which case $\mu$ is just a probability measure on $T$.


text:
Q: kryptonDataGridView.CellBorderStyle not working If I have a normal DataGridView and I want to show only the horizontal lines, I apply the following code:
dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal;

Using the UI template Krypton for WinFroms, it is not working for me. I use:
kryptonDataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal;

And the lines still appear!
Did anyone come across this problem and solve it?

A: I know this is an old question, but I hope you can still find this useful:
Why your code doesn't work:
Well, KryptonDataGridView inherits from the DataGridView WinForms control, and by looking at the source code, you'll find that KryptonDataGridView.CellBorderStyle simply gets or sets the value of base.CellBorderStyle which are not the same borders displayed by KryptonDataGridView.
A lot of the inherited properties doesn't have an effect on Krypton controls (the Font property, for example). But in most cases, Krypton provides an alternative (with more features usually).
Solution:
To replicate the behavior of DataGridView.CellBorderStyle, with KryptonDataGridView, you should use the DataCell.Border.DrawBorders property of the appropriate State:
using ComponentFactory.Krypton.Toolkit;
//

kryptonDataGridView1.StateCommon.DataCell.Border.DrawBorders =
    PaletteDrawBorders.TopBottom;

Result:

Hope that helps.


text:
Q: passing flatbuffers from C to duktape javascript Wondering if anyone out there has had any success or attempted to integrate flatbuffers with duktape, so far I can only get about 1/2 way there...
I can push a flatbuffer from C, and access it from JS with the following code, and it seems to work perfectly:
duk_push_heapptr(ctx, t->ptr);
duk_push_external_buffer(ctx);
duk_config_buffer(ctx, -1, d.data, d.length);
duk_call(ctx, 1);

However, i cant quite seem to achieve the same success passing a flatbuffer from JS to C (or C++ in my case):
void * buff;
duk_size_t sz;
buff = duk_require_buffer_data(ctx, 1, &sz);
if (VerifyLogEventBuffer(flatbuffers::Verifier((uint8_t *)buff, (unsigned int)sz))) {
    std::cout << "Buffer is good here!" << std::endl;
} else {
std::cout << "Buffer is broken here even" << std::endl;
}

Any ideas what i could be doing wrong here?  No issues compiling, but the the flatbuffer is unreadable.
Edit: I should also include the relevant JS --
        var fbb = new flatbuffers.Builder(1024);

    PGS.Buffers.LogEvent.startLogEvent(fbb);
    PGS.Buffers.LogEvent.addLevel(fbb,'WARN');
    PGS.Buffers.LogEvent.addSource(fbb,"js");
    PGS.Buffers.LogEvent.addText(fbb,"1 Event Emitted from JS now with a very long text string to make sure our buffer size increases.");
    var toEmit = PGS.Buffers.LogEvent.endLogEvent(fbb);
    PGS.Buffers.LogEvent.finishLogEventBuffer(fbb, toEmit);

   // var b = new Buffer(fbb.asUint8Array());
    print("1 Attempting to raise long log event using dataBuffer and Buffer");
    raise('log', new Buffer(fbb.asUint8Array()));


text:
Q: Display scatter3D above a surface (plot_trisurf), zorder doesn't work I am trying to add a point on a surface displayed with the function plot_trisurf. The point is present, but seems to be drawn before the surface, so that the only way to see it is to make the surface transparent. I would like this point to appear on the surface even if the surface is not transparent. Do you have any idea of how to do that ?
An example of the problem would be the following :
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt

Latitude = np.repeat(np.linspace(45.1525, 45.17, 1000), 15)
Longitude = np.array(list(np.linspace(5.9, 5.94, 1000))*15)
x = np.linspace(0,3,len(Latitude))
Altitude = np.sin(x)*np.cos(x**2)

fig = plt.figure(figsize=(15, 9))
ax = fig.gca(projection="3d")
ax.view_init(30, 250)
surf = ax.plot_trisurf(
    Latitude,
    Longitude,
    Altitude,
    cmap=plt.cm.jet,
    linewidth=0,
    alpha=0.2,
    edgecolor=None,
    antialiased=False,
)

s = ax.scatter(
    Latitude[10600],
    Longitude[10600],
    Altitude[10600],
    c="black",
    marker="*",
    s=100,
    depthshade=False,
)
plt.title((Latitude[10600], Longitude[10600], Altitude[10600]))
plt.show()

I also tried with scatter3D, and by increasing a little the altitude of the point with respect to the surface but nothing worked.
Thanks a lot for your help !


text:
Q: Writing to the Eclipse console My plugin has to write to the eclipse console - for testing purpose I simplified my code, so that I only have the following:
public void start(BundleContext context) throws Exception {
        super.start(context);
        plugin = this;
        System.out.println("Tecomp Plugin is running");

        MessageConsole myConsole = new MessageConsole("My Console", null);
        //myConsole.activate();
        ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[]{ myConsole });
        ConsolePlugin.getDefault().getConsoleManager().showConsoleView(myConsole);
        final MessageConsoleStream stream = myConsole.newMessageStream();
        stream.setActivateOnWrite(true);
        stream.println("Hi there!");
        stream.close();
    }

It's a simple plugin, the method start belogs to the class extending AbstractUIPlugin - it't no rcp application.
Code works fine inside the runtime workbench - once the plugin is installed, the output gets lost somewhere. The rest of the plugin is working properly.
Is there perhaps a problem with the ConsolePlugin? Or are streams handled differently in the runtime workbench and the development workbench?
I tried both - a feature project and directly copying the plugin jar to the eclipse directory - for installing the plugin - same result for both...
Any help is welcome, because I'm struggeling with that problem for a while now...
Regards, Kathi
Edit:
it doesn't seem to be a problem of the Console... I provided my own view for printing the output, but although declard in the plugin.xml there is no view after installing the plugin... here is what I did:
-export the plugin with the ExportWizard into a jar-archive
-copied this archive to /usr/share/eclipse/plugins
-restarted eclipse
or with a feature project:
-exported the feature-project containing my plugin with the ExportWizard
-removed the above jar archive from the eclipse dir
-installed the feature
-restarted eclipse
both didn't word - did I get something wrong with installing the plugin?
The jar-archive is ok, I checked it - it's the latest version. But somehow it seems that eclipse is still working with some older plugin without the changes I made
regards, Kathi
Edit:
I implemented the IStartup Interface end extended the org.eclipse.ui.startup point, but nothing changed... I really thinks it's an installation problem somehow. I commented out some output but it's still printed to the debug console.
Is there some sort of plugin cache in eclipse? So that the new code doesn't get read?
Edit:
Thanks for the suggestions, but starting eclipse with the -clean option didn't help - I'll try to install the plugin in some other environment next week - perhaps there is something wrong with mine...
Edit:
the code in the class calling the compilier looks as follows:
private MessageConsole findConsole(String name){
  ConsolePlugin plugin = ConsolePlugin.getDefault();
  IConsoleManager conMan = plugin.getConsoleManager();
  IConsole[] existing = conMan.getConsoles();
  for (int i = 0; i<existing.length; i++){
    if (name.equals(existing[i].getName())){
      return (MessageConsole)existing[i];
    }
  }
  //no console found -> create new one
  MessageConsole newConsole = new MessageConsole(name, null);
  conMan.addConsoles(new IConsole[]{newConsole});
  return newConsole;
}

public void run() {
  MessageConsole console = findConsole("tecompConsole");
  //display the tecomp Console
  IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
  String id = IConsoleConstants.ID_CONSOLE_VIEW;
  try {
    IConsoleView view = (IConsoleView) page.showView(id);
    view.display(console);
  } catch (PartInitException e) {
    e.printStackTrace();
  }
  MessageConsoleStream output = console.newMessageStream();
  String tecompPath = TecompPlugin.getDefault().getPreferenceStore().getString(IEiffelConstants.TECOMP_PATH);
  if (checkTecompPath(tecompPath)){
    String line;
    String[] cmd = {tecompPath, pathToAceFile};
    try{
      output.println("calling tecomp");
      Process tecomp = Runtime.getRuntime().exec(cmd);
      //capture stdout und stderr from tecomp
      BufferedReader input = new BufferedReader(
          new InputStreamReader(tecomp.getInputStream()));
      BufferedReader err = new BufferedReader(
          new InputStreamReader(tecomp.getErrorStream()));
      while ((line = input.readLine()) != null ){
        output.println(line);
      }
      input.close();
      while ((line = err.readLine()) != null){
        output.println(line);
      }
      err.close();
      output.close();
      tecomp.waitFor();
      //System.out.println(tecomp.exitValue());
    }catch (Exception err){
      err.printStackTrace();
    }
  } else {
    try{
    output.println("please specify a tecomp path");
    output.close();
    }catch (Exception err){}
  }
}

but the first test example should work, shouldn't it? I create a new MessageConsoleStream and write to it manually. Thats exactly like the examples I found.
Edit:
The code doesn't belog to an rcp application - it's just a plugin, extending the eclipse ide with support for the eiffel programming language. So I think your suggestion doesn't work for my plugin - VonC, at least I don't know where to put your code...
My first sample code in the initial question gets called inside the Plugin class extending AbstractUIPlugin within the start(BundleContext context) method. My plugin in running, so somewhere this method gets called. And as I mentioned - plugin works fine inside the runtime workbench...
I'm sorry if this is not the right place for an additional explanation of my question - but it seemed to be the only place the system allows me to post some further lines. Comments to your answers are not allowed for me, because I just signed in and for that I don't have enough reputation points... so, please correct me, if I'm using the system wrong :) thx

A: Did you check "Displaying the console in your RCP application" ?
Would the follwoing small code (done in the Application.java run() before creating and running the workbench) begin to at least behave like what you want ?
MessageConsole console = new MessageConsole("System Output", null);
ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { console });
ConsolePlugin.getDefault().getConsoleManager().showConsoleView(console);
MessageConsoleStream stream = console.newMessageStream();

System.setOut(new PrintStream(stream));
System.setErr(new PrintStream(stream));

logger = LoggerFactory.getLogger(Application.class); // Previously declared.

(I.e. does a console display itself when your plugin is installed in eclipse ?)

A: I think the problem is that your plugin is not being started.  The code you show won't be activated until some other plug-in tries to access something within your plugin.  It seems like this is the case with your debug launch configuration, but not with the packaged application.
You could try to implement the IStartup interface, and use the org.eclipse.ui.startup extension point in your plugin to force the initialization as soon as the UI is loaded.  This should activate your plugin and execute the console code that you have.
Can you maybe add some logging statement or breakpoint in the start() method to ensure that it is being invoked on your deployed application?

A: Sounds to me the eclipse application where you try to install your plugin into might not have the org.eclipse.ui.console plugin installed that you need to have as a plugin dependency. Did you check that your plugin has the correct plugin dependencies and that it is installed without a problem?

A: You probably have to clear the cached data used by OSGI and the eclipse runtime.  You can do that by adding the -clean argument to your eclipse command line.
Here is the relevant information from the Plug-in Dev Guide:

Cleans cached data used by the OSGi framework and Eclipse runtime. Try to run Eclipse once with this option if you observe startup errors after install, update, or using a shared configuration.

See the Eclipse runtime options for more information.
You might also want to check into using update sites.  I routinely use a local update site to install plugins while testing as it seems less error prone.  The Eclipse FAQ has a quick article on how to create an update site.

A: Another possibility then is that the plugin you are installed is cached in the installation.  You can start eclipse with the -clean option to remove all the cached plugins from the workspace


text:
Q: Lottery winner has brain uploaded, then travels in a starship I am looking for the title of a book / series i read many years ago, i have tried google but i just cant seem to get the search right so any help would be great.
The basis of the story is about a young guy who ends up winning the lotto which allows him to get the best health care and in the end transfer his mind to a computer and travel around on a star ship.  I cannot remember the characters name.  If i remember correctly it was a 2 or 3 book series.  If there are any other details that may help let me know what could be useful.
Again thank you.

A: There's a chance this might be the "Gateway" series by Frederik Pohl.  The first book came out in 1977.
The first book starts with the protagonist winning a lottery which puts the book's plot into motion. Healthcare is purchased, the best is called "Full Medical".
I don't remember the mind transfer into a computer, but IMHO the sequels weren't nearly as good as "Gateway" and I lost interest quickly, so could be a later book.
The series (at least the part I read) mostly deals with humanity's interactions with technology left scattered about the solar system by a race they call the "Heechee", maybe that rings a bell?


text:
Q: Using XSL to count the last number of nodes with a certain value I have XML like this:
<game id="1" result="W" />
<game id="2" result="T" />
<game id="3" result="L" />
<game id="4" result="W" />
<game id="5" result="W" />

I'm trying to count the number of nodes from the end that have the same result as the last node.  In this case it would be 2.  I've tried for-each, but can't exit the loop after the result changes.

A: Something like this should work:
<xsl:variable name="lastValue" select="game[last()]/@result"/>
<xsl:variable name="streak"
              select="count(game[@result = $lastValue and
                          not(following-sibling::game/@result != $lastValue)])" />


text:
Q: JETTY: Embedded JSP inside its jar I'm using Jetty 8.0. to create a simple web server (html/json/png) inside my java application.
I added an handler to use jsp pages positioned inside a package (as mentioned here:  http://docs.codehaus.org/display/JETTY/Embedding+Jetty):
        String WEBAPPDIR = "com/econorma/jsp/resources";
        String CONTEXTPATH = "/jsp";

        URL warUrl = WebApplication.class.getClassLoader().getResource(WEBAPPDIR);
        final String warUrlString = warUrl.toExternalForm();
        WebAppContext webapp = new WebAppContext(warUrlString, CONTEXTPATH);

I tested this code in Eclipse without any problems: html and jsp both work.

My problem come when I run my jar deployed. I get NULL POINTER exception in the getClassLoader line.
I try to put the slash at the end of WEBAPPDIR as mentioned in one StackOverflow post but, also if I solve the null pointer exception, I can't me it work.

A: You need to put the updated codes of jsp and html files back into the jar to work properly.
The local jsp pages in the package com.econorma.ui.resources will be available only for development process and when you export your project as a war file. The jars will not have the changes that you made in jsp pages which you had in com.econorma.ui.resources.
So you need to copy of jsp or html files from the package you created. And then put these files in the jar in the appropriate packages and update it.
Now you have to build your project again after installing the new jars files and restart your jetty server to see the changes and you should be able to run your server without errors. Hope this helps.

A: There was two problems for my embedded jetty and jsp:
1-Missing code before calling my webClass:
System.setProperty("org.apache.jasper.compiler.disablejsr199", "true");

2-The Eclipse export to prepare the jar: I used the EXTRACT method and non the PACKAGE one and so it wasn't possibile to find jsp inside the jar.


text:
Q: Bootstrap row custom height in percentage I'm developing a little website and I'm facing some troubles.
What I want is to resize a "row" div with a particular height, in percentage.
I've already searched on SO but nothing was good for me.
Here is my code:

      ...

class "row-first" for now has no rules so it not take effect.
I want that "row-first" div is 80% of the viewport's height, but the only way to resize it is by putting some content inside the div so that the div's height follows content height.
my CSS:
html {
    height: 100%;
}

body {
    height: 100%;
}

body {
    font-family: 'Muli', sans-serif;
}

.container-fluid {
    max-height: 100%;
    padding-left: 0px;
    padding-right: 0px;
}

.row {
    margin-left: 0px;
    margin-right: 0px;
    height:80%;
}

.row-first {

}

A: The height of the div is relative to the height of the parent. Therefor, to make the height of .row 80%, I first set the height of the parent. Here's the css:
.container-fluid {
  height: 100%;
  padding-left: 0px;
  padding-right: 0px;
}

.row-first {
  height:80%;
  overflow: hidden;
}

And the fiddle: http://jsfiddle.net/bmwoLkdr/
Feel free to play with the height and see for yourself!


text:
Q: What is the benefit of convoy-glusterfs over pure glusterfs I have a problem to see the benefit of glusterfs with convoy over pure glusterfs
Our starting position:

*

*we just use convoy of rancher, nothing else

*we have glusterfs setup for persistent data

Setup without convoy

*

*Mount glusterfs volume on each docker host

*create services with docker swarm and mount them to the right directory on the host, which hosts in the background to glusterfs

Setup with convoy

*

*Run the convoy deamon on ever dockerhost (which mounts the glusterfs volume in the background)

*create services with docker swarm and attach a volume to it over the convoy

*volume-driver, which is maped to a glusterfs directory in the background

So, what is the benefit of starting a deamon (convoy), which does the mounting in the background, when I can do the mounting myself over /etc/fstab

A: *

*snapshots

*described in the docker compose / stack yaml file of your project.


text:
Q: Is there a way to use aliases for Sass @use with Vite? This may be a fairly noob question, but I haven't yet been able to find a solution that works.
I am trying to use an alias for the @use/@forward methods with Sass in conjunction with Sass modules/CSS modules in a React project using Vite.
For example, I want to be able to use @use "@scss/styles" from the something.module.scss without the use of @use "../scss/styles"
Example folder structure below:
└── My-App/
    └── src/
        ├── scss/
        │   ├── styles.scss
        │   └── abstract/
        │       └── _colors.scss
        └── components/
            └── something.module.scss

My understanding is that aliases via the vite.config.ts don't apply to the Sass preprocessor as they currently work normally for everything else.
There is a sass-alias package on npm sass-alias, however I have not been able to make it work via the config file. From what I can understand, it also uses a non-current method to achieve.
Most of what I have seen apply mostly to Webpack, and don't seem to work in my case. Various iterations of filenames have been tried as well as putting aliases in the vite.config.ts and tsconfig.json files.
I have tried using the sass-alias package without too much success as well. I think I'm missing something really obvious, or that the solution will involve a combination of using path and resolving __dirname with a combination of other things I'm not familiar with.
Many thanks in advance.


text:
Q: Exibir numero de comentarios da tabela de um unico usuario Como contar as linhas de comentários na tabela de comentários que foram adicionados por um determinado  usuário.
a tabela é essa

id |post_body | posted_by | posted_to | date_added |removed   | post_id
1  |teste 1   |  joao     | maria     | 10-10-10   | no     | 23
2  |teste 2   |  carlos   | joao      | 10-10-10   | no     | 24
3  |teste 3   |  joao     | carlos    | 11-10-10   | no     | 25
4  |teste 4   |  joao     | maria     | 12-10-10   | no     | 26
4  |teste 4   |  maria    | joao      | 12-10-10   | no     | 27

quero exibir o numero de comentario só de joão.
ex: total comentarios 3

A: Select COUNT(ID) from usuario WHERE posted_by = 'joao'

A: Use o seguinte:
<?php
$query = mysqli_query($conn, "SELECT COUNT(*) as total FROM tabela_comentarios WHERE posted_by = 'joao';");
$row = mysqli_fetch_array($query);

echo "Joao comentou: ".$row['total']." vezes!";
?>

OBS: Eu não testei o código. Mas acredito que funcione. Abraços!


text:
Q: Links in Modal not working for Bootstrap This is a very puzzling issue, but all the links I have in the below modal do not work (clicking on the links, nothing happens). I just want it to open the href to the correct page.  Any help would be appreciated. The code is below:

                              Information

US Citizenship Quiz

                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                  ×
                                </button>

                                Small sampling of the US Citizenship Test built with HTML, CSS, and JavaScript.

                                        Go to Site
                                        Go to Code
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

EDIT: Added entire code

<!doctype html>

 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

 <title>Bedig Galladian</title>

 <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
 <link rel="stylesheet" href="fancybox/jquery.fancybox-v=2.1.5.css" type="text/css" media="screen">
    <link rel="stylesheet" href="css/font-awesome.min.css" rel="stylesheet">
  <link href="css/ihover.css" rel="stylesheet">

 <link rel="stylesheet" type="text/css" href="css/style.css">

 <link href='http://fonts.googleapis.com/css?family=Titillium+Web:400,600,300,200&subset=latin,latin-ext' rel='stylesheet' type='text/css'>

 <link rel="prefetch" href="images/zoom.png">

   <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">

   </button>

 HOME

 ABOUT ME

 PORTFOLIO

 SKILLS

 RESUME

 CONTACT

Bedig Galladian

I am a Full Stack Web Developer

PROFESSIONAL

PERSONABLE

About Me

Knower of useless facts

How I Was Educated

I graduated from Towson University in 2012 with my Masters in Student Affairs and Higher Education Administration. After many years of advising students, I decided to that one of my hobbies (web development) is something I would like to pursue.  Hence why enrolled in General Assemblys Web Immersive Program!

My Personal Skills

As a former Student Affairs professional, I have leadership and collaboration skills as well as creativity.  I also possess strong interpersonal and social communication skills and can interact with supervisors, coworkers, and clients alike to achieve a desired product.  I have a strong detail focus, and can work well under pressure.

What I Do For Fun

I love to learn and be creative, which is what web development has done for me. Other than coding, I love to research various historical events, and watch movies constantly.  Netflix is always on in my home. I hope to write sreenplay one day.  My perfect day is a set of Legos to build with and a good movie on the TV.  Avid sneakerhead.

My  Portfolio

Take a look at some of my work

US Citzenship Quiz

       <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
         Information
       </button>

US Citizenship Quiz

               <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                 ×
               </button>

               Small sampling of the US Citizenship Test built with HTML, CSS, and JavaScript.

           Go to Site
           Go to Code
               <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

Was It It Worth It?

        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal1">
          Information
        </button>

Was It Worth It?

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  ×
                </button>

            A movie review app with a "unique" ranking system.  Built with Ruby on Rails, with 3 models, a seach function, and user authentication.  Built over the course of 3 days.

            Go to Site
            Go to Code
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

oneShot

         <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal2">
          Information
         </button>

oneShot

             <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              ×
             </button>

             My first project with a team.  Built with a Rails backend with an Angular frontend.  It is an anonymous message board with no delete or edit function.  Hence the user only gets "one shot".

             Go to Site
             Go to Code
             <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

kickSStarter

        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal3">
         Information
        </button>

kickSStarter

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
             ×
            </button>

            A website where independent sneaker designers can submit custom designs to showcase their talents to other designers.  Built with Mongo, Express, ReactJS, and NodeJS.

            Go to Code
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

See what I can do

Most important skill is being able to learn Fast

Front End

HTML

CSS

JavaScript

jQuery

AngularJS

React

Bootstrap

Materialize

Back End

Ruby

Rails

Mongoose

Sinatra

NodeJS

Express

PostGresQL

Other

GitHub

Heroku

Windows

MacOS

Microsoft Office Suite

Google Docs

User Stories

Wire Framing

Take a look at my Resume

     <embed src="images/resume.pdf" width="100%" height="1000px"></embed>

Leave me a message

You can find me  anywhere, just push a button and I'm there

     (240)-200-2418

     Feel free to email me!

     Washington, DC

     Lets Connect on LinkedIn!

     Check out my work on Github!

 © Bedig Galladian 2017

A: Add this code:
<asp:UpdatePanel runat="server" >
     <ContentTemplate>
          ... your code here ...
     </ContentTemplate>
</asp:UpdatePanel>

inside
<div class="modal fade" ...

while wrapping

Result:

<asp:UpdatePanel runat="server" >
    <ContentTemplate>

US Citizenship Quiz

                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              ×
                            </button>

                            Small sampling of the US Citizenship Test built with HTML, CSS, and JavaScript.

                                    Go to Site
                                    Go to Code
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

     </ContentTemplate>
</asp:UpdatePanel>


text:
Q: How to map a property as NOT a column in EF 4.1 I have a class:
public class classParty
{
    private int _arrivedCount;

    public int PartyID {get; private set;}
    public DateTime PartyDate {get; private set;}
    public int ArrivedCount
    {
        get
        {
            return _arrivedCount;
        }

        set
        {
            _arrivedCount = value;
        }
    }
}

I can map the PartyId and the PartyDate but I don't have a column for ArrivedCount (it's a moment in time count, it doesn't persist).
How do I tell EF 4.1 to stop looking for a column named "ArrivedCount"? It's not in the table. It's not going to be in the table. It's simply a property of the object and that's all.
Thanks in advance.
EDIT:
Here's the Fluent API configuration for classParty.
public class PartyConfiguration : EntityTypeConfiguration<classParty>
{
    public PartyConfiguration()
        : base()
    {
        HasKey(p => p.PartyID);

        Property(p => p.PartyID)
            .HasColumnName("PartyID")
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
            .IsRequired();
        Property(p => p.PartyDate)
            .HasColumnName("PartyDate")
            .IsRequired();

        ToTable("Party");
    }
}

A: modelBuilder.Entity<classParty>().Ignore(x => x.ArrivedCount);

A: With data annotations:
[NotMapped]
public int ArrivedCount
//...

Or using Fluent API:
modelBuilder.Entity<classParty>()
    .Ignore(c => c.ArrivedCount);


text:
Q: sub graph after a spatial intersection in neo4j I recently started using neo4j db and its spatial plugin.
My data model consist of 4 different nodes: Building, Floor, Room and Device. All of them related by the relationship "HAS".
The node added to the spatial layer is Building.
This is how it looks at this moment:

To get all the Buildings that intersect in a given polygon I'm using the next cypher
WITH 'POLYGON((-6.342523097991944 39.47879396554205, -6.339948177337647
39.47879396554205, -6.339948177337647 39.478121118127696,
-6.342523097991944 39.478121118127696, -6.342523097991944
39.47879396554205))' as polygon
CALL spatial.intersects('geom',polygon) YIELD node
RETURN node

Particularity that returns one building:

Now, what I'm trying to do is to obtain the sub-graph holding from the intersected Building. Here is my try:
WITH 'POLYGON((-6.342523097991944 39.47879396554205, -6.339948177337647
39.47879396554205, -6.339948177337647 39.478121118127696, -6.342523097991944
39.478121118127696, -6.342523097991944 39.47879396554205))' as polygon
CALL spatial.intersects('geom',polygon) YIELD node
MATCH (node)-[:HAS]->(Floor)-[:HAS]->(Room)-[:HAS]->(Device)
RETURN *

That outputs the next graph:

That result is similar of what I want but not exactly. What I need is all the intersected building, all its floors, rooms and devices. This result is only giving my the floors that have rooms and the rooms that have devices. I don't know how to write the cypher to get what I need.
Apart from that, the previous cypher is taking around 7 seconds to output the results, is that time normal with the size of my actual graph? It seems a lot to me.
Thank you!

A: You can specify a variable length pattern:
...
CALL spatial.intersects('geom',polygon) YIELD node
MATCH (node)-[:HAS*0..3]->(Item)
RETURN Item


text:
Q: How to detect email addresses within arbitrary strings I'm using the following code to detect an email in the string. It works fine except dealing with email having pure number prefix, such as "536264846@gmail.com". Is it possible to overcome this bug of apple? Any help will be appreciated!
NSString *string = @"536264846@gmail.com";
NSError *error = NULL;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];
NSArray *matches = [detector matchesInString:string
                                     options:0
                                       range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
    if ([match.URL.scheme isEqualToString:@"mailto"]) {
        NSString *email = [match.URL.absoluteString substringFromIndex:match.URL.scheme.length + 1];
        NSLog(@"email :%@",email);

    }else{
        NSLog(@"[match URL] :%@",[match URL]);
    }

}

Edit:
log result is: [match URL] :http://gmail.com

A: What I did in the past:

*

*tokenize the input, e.g., separate tokens using spaces (since most other common separators may be valid within an email). However, this may not be necessary if the regular expression is not anchored - but not sure how it would work without the "^" and "$" anchors (which I added to what was shown on the web site).

*keep in mind that addresses may take the form '"string"' as well as just address

*in each token, look for '@', as it's probably the best indicator you have that its an email address

*run the token through the regular expression shown on this Email Detector comparison site (I found in testing that the one marked #1 as of 3/21/2013 worked best)
What I did was put the regular expression in a text file, so I didn't need to escape it:

^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}@)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))\x22))(?:.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))\x22)))@(?:(?:(?!.[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+).){1,126}){1,}(?:(?:[a-z][a-z0-9])|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+))|(?:[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.[a-f0-9][:]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))]))$

Defined an ivar:
NSRegularExpression *reg

Created the regular expression:
NSString *fullPath = [[NSBundle mainBundle] pathForResource:@"EMailRegExp" ofType:@"txt"];
NSString *pattern = [NSString stringWithContentsOfFile:fullPath encoding:NSUTF8StringEncoding error:NULL];
NSError *error = nil;
reg = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
assert(reg && !error);

Then wrote a method to do the comparison:
- (BOOL)isValidEmail:(NSString *)string
{
    NSTextCheckingResult *match = [reg firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
    return match ? YES : NO;
}

EDIT: I've turned the above into a project on github
EDIT2: for an alterate, less rigorous but faster, see the comment section of this question


text:
Q: Cannot find activate file in Python venv in Linux I am trying to install venv but getting this error:

name@malikov:~/Desktop/informtech$ python3 -m venv venv
Error: Command '['/home/name/Desktop/informtech/venv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1.

venv folder created but there is no activate file to activate venv

What should I do. Is there any solution. All problems started after upgrading python version from 3.8 to 3.10strong text

A: You can try installing venv for python3.10 via command:
sudo apt install python3.10-venv


text:
Q: Create night vision effect to Camera I know all other stuff about creating and handling camera.
I only want to know how to add a Night Vision effect to Camera View.
Or how could i create an effect ?
To support a night vision I have no clue from where to start.


text:
Q: VBS looping simple query helo please help this is the code
Option Explicit

Dim iim1, i, s , shell
dim iret
dim myname, mypath
dim pos

'initialize iMacros instance
set iim1= CreateObject ("iMacros")

'i = iim1.iimOpen ("-fx", false) 'Use open Firefox instance if available
i = iim1.iimOpen ("-fx", true) 'Always open new instance

pos = 2

Do while pos < 10

iret = iim1.iimSet("loopVar",Cstr(pos))
iret = iim1.iimPlay("ecc2.iim")

set shell=createobject("wscript.shell")
shell.Run "%comspec% /c C:\Users\SDFL\Desktop\dc1.bat"

pos = pos + 1
loop

After the line
iret = iim1.iimPlay("ecc2.iim")

I want it to check if iret < 0. If yes then I want it to repeat the step
iret = iim1.iimSet("loopVar",Cstr(pos))
iret = iim1.iimPlay("ecc2.iim")

in a loop until iret > 0 with same Pos value without disturbing the main loop, and if iret > 0 I want it to move it to the next lines of the code.
So this is a loop inside a loop how to do that? Please take care of Pos value, e.g. if Pos value was 6 when iret < 0, then repeat the step with pos = 6, if iret > 0 then move forward to next lines of code, so in last step pos = 7 and the whole code proceeds.
I hope you get it
Please give the code  thanks
ADDED
 >>pos = 2

iret = iim1.iimSet("loopVar",Cstr(pos))
iret = iim1.iimPlay("ecc2.iim")

Do

iret = iim1.iimSet("loopVar",Cstr(pos))
iret = iim1.iimPlay("ecc2.iim")
iret = Rnd() > .5
WScript.Echo pos, CStr(iret)
Loop Until iret

set shell=createobject("wscript.shell")
shell.Run "%comspec% /c C:\Users\SDFL\Desktop\dc1.bat"

pos = pos + 1

A: The method of choice for looping over a numerical range is For, not While:
>> For pos = 2 To 9
>>     WScript.Echo "pos", pos
>> Next
>>
pos 2
pos 3
pos 4
pos 5
pos 6
pos 7
pos 8
pos 9

To repeat an action at least once and until some condition is fullfilled, use Do ... Loop Until:
>> For pos = 2 To 9
>>     Do
>>        ret = Rnd() > .5
>>        WScript.Echo pos, CStr(ret)
>>     Loop Until ret
>> Next
>>
2 True
3 True
4 True
5 False
5 False
5 True
6 False
6 True
7 True
8 True
9 False
9 False
9 True

There should probably an upper limit (counter/timer?) on the Do loop to aviod endless loopings.
Added:
In my sample, the loop controlling boolean variable ret is set to True (= please stop looping) if the function Rnd() returns a value > .5. Given a function .iimSet() that returns some number indicating success or failure you surely can work out for yourself what number (..-1, 0, +1 ..) to compare how (=, <, >, <=, >=) with that return value to stop the looping in case of success. Hint: double check your tests "iret < 0" vs. "iret > 0" wrt .iimSet() delivering 0.

A: If you want an inner loop, just add an inner loop:
pos = 2

Do while pos < 10
  Do
    iret = iim1.iimSet("loopVar",Cstr(pos))
    iret = iim1.iimPlay("ecc2.iim")
  Loop Until iret > 0

  set shell=createobject("wscript.shell")
  shell.Run "%comspec% /c C:\Users\SDFL\Desktop\dc1.bat"

  pos = pos + 1
loop

Of course, since your outer loop is simply iterating over a sequence of numbers, you'd be better off using a For loop for that. And I'd move the creation of the WScript.Shell object outside the loop, so you don't waste system resources (re-)creating the object over and over again.
set shell=createobject("wscript.shell")

For pos = 2 To 9
  Do
    iret = iim1.iimSet("loopVar",Cstr(pos))
    iret = iim1.iimPlay("ecc2.iim")
  Loop Until iret > 0

  shell.Run "%comspec% /c C:\Users\SDFL\Desktop\dc1.bat"
Next


text:
Q: Mt.exe doesn't like absolute paths in the -dll option Is it just me, or does Mt.exe hate absolute paths in the -dll option?
I have a Visual C++ project in Visual Studio 2008 with a reference to an isolated (registration free) COM DLL. I copy the COM DLL into the project's output directory using a Pre-Build Event. In the project's properties, on the Configuration Properties > Manifest Tool > Isolated COM dialog I used the following settings:
Type Library File: $(OutDir)\MyCom.tlb
Registrar Script File:
Component File Name: $(OutDir)\MyCom.dll
Replacements File:

Visual Studio shows me the generated command line command:
mt.exe /nologo
    /tlb:"C:\[ ... snip ... ]\OtherProject\Release\MyCom.tlb"
    /dll:"C:\[ ... snip ... ]\OtherProject\Release\MyCom.dll"
    /outputresource:"..\Release\OtherProject.exe;#1"

It builds fine, but I get a runtime FileNotFound exception. The application can't find MyCom.dll! Changing Component File Name to the following relative path works fine:
Component File Name: ..\$(ConfigurationName)\MyCom.dll


text:
Q: Binding end node of known path to variable to use for CRUD operations I'm relatively new to neo4j and I'm not quite sure how to do more complex queries. I want to build a graph which in part is analogous to a file tree structure (but with some extra connections and special things happening at the leafs). Each node has a unique path in the file-like tree and the application code will have access to that node-path-id and perform CRUD operations on the node. For this reason, I would like to know what the best way of getting an identifier for the node that the node-path-id identifies in cypher.
You could obviously store the entire path in the node and search for the id as you normally would but that feels unnecessary when the path is already in the graph. The only way of utilizing this that I could figure out is by generating the query below dynamically. This creates lots of useless identifiers though (if scaled up). Is there a better way to localize a node when a path to it is already known?
Also, as the special root node will be accessed for each query I will want to make sure that the database can access it without searching the entire graph for it. How do you do that. Is it enough to give it a unique :root label for instance?
MATCH (:root)-[:child]->(A)
WHERE A.name = "myDir"
MATCH (A)-[:child]->(B)
WHERE B.name = "nestedDir"
MATCH (B)-[:child]->(C)
WHERE C.name = "deepDir"
CREATE (:leafNode {name:"myLeaf"})<-[:child]-(C) // or some other CRUD operation utilizing C node.

Other attempts:
apoc.path.subgraphNodes doesn't allow filtering on properties. Is pretty close to what I want to do though.
Using UNWIND is pretty complex and I couldn't find a solution.

A: The best way to do this in Neo4J would probably be variable length patterns. Assuming that your data is a directed acyclic graph of structure and you want to fetch the path for the node with name myDir you could do this
MATCH (node:Node) WHERE node.name = "myDir"
MATCH path=(:root)-[:child*]->(node)
RETURN reduce(s="", node IN nodes(path) | node.name + "/")

For your question regarding easily finding the root then giving it a unique label is a good solution.


text:
Q: Search by Name Category/SubCategory using Javascript on laravel view I had some problems with the task. I'm not very good with javascript. Please help.
I display categories as form and I want to when the form to be typed to display products that are set for each category and sub-category. In the next task I have to make sure that when the form is typed, the categories show up and, also without refreshing the page.
code on product_upload.blade.view

                                {{translate('Category')}}

                                    <select class="form-control aiz-selectpicker" name="category_id" id="category_id"  data-live-search="true" required>
                                        @foreach($categories as $category)
                                            <option value="{{$category->id}}">{{ $category->getTranslation('name') }}</option>
                                        @endforeach
                                    </select>

                                {{translate('Subcategory')}}

                                    <select class="form-control aiz-selectpicker" name="subcategory_id" id="subcategory_id"  data-live-search="true" required>

                                    </select>

My script :
       function get_subcategories_by_category(){
        var category_id = $('#category_id').val();
        $.post('{{ route('subcategories.get_subcategories_by_category') }}',{_token:'{{ csrf_token() }}', category_id:category_id}, function(data){
            $('#subcategory_id').html(null);
            for (var i = 0; i < data.length; i++) {
                $('#subcategory_id').append($('<option>', {
                    value: data[i].id,
                    text: data[i].name
                }));
                $(".aiz-selectpicker").selectpicker();
            }
            get_subsubcategories_by_subcategory();
        });
    }

        $('#category_id').on('change', function() {
        get_subcategories_by_category();
    });

    $('#subcategory_id').on('change', function() {
        get_subsubcategories_by_subcategory();
    });

and my controller :
    public function get_subcategories_by_category(Request $request)
{
    $subcategories = SubCategory::where('category_id', $request->category_id)->get();
    return $subcategories;
}

But that wont work.


text:
Q: Powershell - use CSV to create multiple text files I am trying to create a PS script that autogenerates txt files using a CSV file as an input.
The CSV file contains data such as this:

Category
Product
Priced

Bike
Red bike
Yes

Bike
Blue bike
Yes

Bike
Black bike
No

Car
Red car
No

Car
Blue car
Yes

The script should get a CSV as an input and generate 2 txt files (because we have 2 categories):
Example:
txt file 1: Bike.txt
Red bike - Yes
Blue bike - Yes
Black bike - No

I tried using this code, but it does not act the way I want it to:
$csv = Import-CSV -Path path.csv -Delimiter ";"

foreach($record in $csv){

    $cat_array += $record.Category

    foreach($Product in $cat_array){
        .....
    }
}

I think I am handling the logic wrong.

A: Here is a possible solution:
# Group CSV data by column Category and loop over groups
Import-CSV -Path path.csv -Delimiter ";" | Group-Object Category | ForEach-Object {

    # Create a text file from the current group
    $fileName = "$($_.Name).txt"
    Set-Content $fileName -Value "$($_.Name) file contains:"

    # Loop over the rows of the CSV and add the data to the txt file
    $_.Group | ForEach-Object {
        # Format one line of the current text file
        ($_.Product, $_.Priced) -join ' - '
    } | Add-Content $fileName
}

Output:
Bike.txt
Red bike - Yes
Blue bike - Yes
Black bike - No

Car.txt
Red car - No
Blue car - Yes

Detailed explanation:
The Group-Object command groups data by specified criteria, in this case the value of property (column) Category. To better understand how it works, it helps to remove the ForEach-Object command:
Import-CSV -Path path.csv -Delimiter ";" | Group-Object Category

This outputs:
Count Name Group
----- ---- -----
    3 Bike {@{Category=Bike; Product=Red bike; Priced=Yes}, @{Category=Bike; Product=Blue bike; Priced=Yes}, @{Category=Bike;…
    2 Car  {@{Category=Car; Product=Red car; Priced=No}, @{Category=Car; Product=Blue car; Priced=Yes}}

So for each group (Bike, Car), it outputs one object, which has the properties Count (number of grouped objects), Name (value of property by which it groups) and Group (an array of grouped objects).
So when iterating over the output of Group-Object, the ForEach-Object script block gets called one time per group. At this level the file will be created.
We then iterate over the elements of the Group array, which contains the rows of the CSV for the current category, to create the lines of the file, using the -join operator to format each line. This ends up in the file because it is implicit output, piped to the next command.
Finally output the file by piping to Set-Content. If necessary, use the -Encoding parameter to specify a non-default encoding (PS 5.x defaults to ANSI, while PS 7.x defaults to UTF-8).


text:
Q: How to compare two huge List in Java? My application generates 2 big lists (up to 3.5mill string records). I need the best and fastest way to compare it. Currently I am doing it like this:
List list1 = ListUtils.subtract(sourceDbResults, hiveResults);
List list2 = ListUtils.subtract(hiveResults, sourceDbResults);

But this method is really expensive on memory as i see from jconsole and sometimes process even stack on it. Any good solutions or ideas?
Element positions/order in the list are always the same, so I dont need to deal with it. After comparing I need to know if the list are the same and to get the differences from these list if they are not the same. Subtract works perfect for small lists.

A: Given that you've said your two lists are already sorted, they can be compared in O(N) time, which is much faster than your current solution that uses ListUtils. The following method does this using a similar algorithm to the one that merges two sorted lists that can be found in most textbooks.
import java.util.*;

public class CompareSortedLists {
    public static void main(String[] args) {
        List<Integer> sourceDbResults = Arrays.asList(1, 2, 3, 4, 5, 8);
        List<Integer> hiveResults = Arrays.asList(2, 3, 6, 7);
        List<Integer> inSourceDb_notInHive = new ArrayList<>();
        List<Integer> inHive_notInSourceDb = new ArrayList<>();

        compareSortedLists(
                sourceDbResults, hiveResults,
                inSourceDb_notInHive, inHive_notInSourceDb);

        assert inSourceDb_notInHive.equals(Arrays.asList(1, 4, 5, 8));
        assert inHive_notInSourceDb.equals(Arrays.asList(6, 7));
    }

    /**
     * Compares two sorted lists (or other iterable collections in ascending order).
     * Adds to onlyInList1 any and all elements in list1 that are not in list2; and
     * conversely to onlyInList2. The caller must ensure the two input lists are
     * already sorted and should initialize onlyInList1 and onlyInList2 to empty,
     * writable collections.
     */
    public static <T extends Comparable<? super T>> void compareSortedLists(
            Iterable<T> list1, Iterable<T> list2,
            Collection<T> onlyInList1, Collection<T> onlyInList2) {
        Iterator<T> it1 = list1.iterator();
        Iterator<T> it2 = list2.iterator();
        T e1 = it1.hasNext() ? it1.next() : null;
        T e2 = it2.hasNext() ? it2.next() : null;
        while (e1 != null || e2 != null) {
            if (e2 == null) {  // No more elements in list2, some remaining in list1
                onlyInList1.add(e1);
                e1 = it1.hasNext() ? it1.next() : null;
            }
            else if (e1 == null) {  // No more elements in list1, some remaining in list2
                onlyInList2.add(e2);
                e2 = it2.hasNext() ? it2.next() : null;
            }
            else {
                int comp = e1.compareTo(e2);
                if (comp < 0) {
                    onlyInList1.add(e1);
                    e1 = it1.hasNext() ? it1.next() : null;
                }
                else if (comp > 0) {
                    onlyInList2.add(e2);
                    e2 = it2.hasNext() ? it2.next() : null;
                }
                else /* comp == 0 */ {
                    e1 = it1.hasNext() ? it1.next() : null;
                    e2 = it2.hasNext() ? it2.next() : null;
                }
            }
        }
    }
}

The above method uses no external libraries, and can be used with any version of Java from 6 upwards. If you use a PeekingIterator, such as the one from Apache Commons Collections, or Guava, or write your own, then you can make the method simpler, especially if you also use Java 8:
public static <T extends Comparable<? super T>> void compareSortedLists(
        Iterable<T> list1, Iterable<T> list2,
        Collection<T> onlyInList1, Collection<T> onlyInList2) {
    PeekingIterator<T> it1 = new PeekingIterator<>(list1.iterator());
    PeekingIterator<T> it2 = new PeekingIterator<>(list2.iterator());
    while (it1.hasNext() && it2.hasNext()) {
        int comp = it1.peek().compareTo(it2.peek());
        if (comp < 0)
            onlyInList1.add(it1.next());
        else if (comp > 0)
            onlyInList2.add(it2.next());
        else /* comp == 0 */ {
            it1.next();
            it2.next();
        }
    }
    it1.forEachRemaining(onlyInList1::add);
    it2.forEachRemaining(onlyInList2::add);
}


text:
Q: Identification of packets in a byte stream I'm having a bit of a problem with the communication to an accelerometer sensor. The sensor puts out about 8000 readings/second continuously. The sensor is plugged in to a usb port with an adaper and shows up as com4. My problem is that I can't seem to pick out the sensor reading packets from the byte stream. The packets have the size of five bytes and have the following format:
            High nibble                     Low nibble

Byte 1      checksum, id for packet start   X high
Byte 2      X mid                           X low
Byte 3      Y high                          Y mid
Byte 4      Y low                           Z high
Byte 5      Y mid                           Y low

X, y, z is the acceleration.
In the documentation for the sensor it states that the high nibble in the first byte is the checksum (calculated Xhigh+Xlow+Yhigh+Ylow+Zhigh+Zlow) but also the identification of the packet start. I'm pretty new to programming against external devices and can't really grasp how the checksum can be used as an identifier for the start of the package (wouldn't the checksum change all the time?). Is this a common way for identifying the start of a packet? Does anyone have any idea how to solve this problem?
Any help would be greatly appreciated.

A:
... can't really grasp how the checksum can be used as an identifier for the start of the package (wouldn't the checksum change all the time?).

Yes, the checksum would change since it is derived from the data.
But even a fixed-value start-of-packet nibble would (by itself) not be sufficient to (initially) identify (or verify) data packets.  Since this is binary data (rather than text), the data can take on the same value as any fixed-value start-of-packet.  If you had a trivial scan for this start-nibble, that algorithm could easily misidentify a data nibble as the start-nibble.

Is this a common way for identifying the start of a packet?

No, but given the high data rate, it seems to be a scheme to minimize the packet size.

Does anyone have any idea how to solve this problem?

You probably have to initially scan every sequence of bytes five at a time (i.e. the length of a packet).
Calculate the checksum of this "packet", and compare it to the first nibble.
A match indicates that you (may) have packet alignment.
A mismatch means that you should toss the first byte, and test the next possible packet that would start with what was the second byte (i.e. shift the 4 remaining bytes and append a new 5th byte).
Once packet alignment has been achieved (or assumed), you need to continually verify the checksum of every packet in order to confirm data integrity and ensure packet data alignment.  Any checksum error should force another hunt for correct packet data alignment (starting at the 2nd byte of the current "packet").

A: What you need to do is get some free SerialPortTerminal in c# import in your project and first check all the data and packets you are getting, unless you have already done that. Than just to read you will need to do something like...
   using System;
   using System.IO.Ports;
   using System.Windows.Forms;

   namespace SPE
   {
     class SerialPortProgram
     {
       // Create the serial port with basic settings
       private SerialPort port = new SerialPort("COM4",      9600, Parity.None, 8, StopBits.One);

       [STAThread]
       static void Main(string[] args)
       {
         // Instatiate this class
         new SerialPortProgram();
       }

       private SerialPortProgram()
       {
         Console.WriteLine("Incoming Data:");

         // Attach a method to be called when there      // is data waiting in the port's buffer
         port.DataReceived += new         SerialDataReceivedEventHandler(port_DataReceived);

         // Begin communications
         port.Open();

         // Enter an application loop to keep this thread alive
         Application.Run();
       }

       private void port_DataReceived(object sender,      SerialDataReceivedEventArgs e)
       {
         // Show all the incoming data in the port's buffer
         Console.WriteLine(port.ReadExisting());
       }
     }
   }


text:
Q: How to add object in a list of object in ne04j I have 2 classes as following
class Organization{
    @GraphId
    private Long Id;

    @Relationship(type = "has", direction="Outgoing)
    private List<Person> personList;
}

and
class Person{
    @GraphId
    private Long Id;
    private String name;
}

and organization repo
interface OrganizationRepository extends GraphRepository<Organization> {}

I can Create organization and add list of person to it.
Now How can i add a new person to existing organization?
I can get all the person of a organization in a list and then add the new person to that list and then update the organization. but this does not seems the right way to do it.
So is there any other way to add a person to existing organization??

A: That's right, load the organization, add the person to the list, and save the organization.
Edit based on comments:
If the organization can contain 50,000 persons, then perhaps this is not the right model for you. How about a reference to the organization on the Person instead? Then, all you need to do is load the person, set his organization, and save the person.


text:
Q: How do I check for file encryption in VBA (MSAccess) I'm building a form that moves files from one location to another based on data within the DB, and it works as long as the source file is not encrypted (green filename in windows explorer) and as long as the destination file does not exist.
So I'm trying to create the following:
Public Function isEncrypted(file As String) As Boolean
    Dim info As System.IO.FileInfo
    info = My.Computer.FileSystem.GetFileInfo(file)

    Dim attr As System.IO.FileAttributes
    attr = info.Attributes

    isEncrypted = ((attr And System.IO.FileAttributes.Encrypted) > 0)
End Function

But it doesn't run at all. Anyone have experience with this, or is there an easier way to check for encryption? Access hangs and crashes if I try to rename & move an encrypted file.

A: As others have mentioned, there is no way that the vb.net code is going to compile in access.  You will most likely need to use a system call from win32 to get the file attributes.  The FileSystemObject (Scrrun.dll 'Windows Scripting Runtime') object will not work either as it's enumeration will not tell you if the file is encrypted.  Here is a windows API function you can use to determine if the file is encrypted or not.
Public Enum FileAttribute
'uses VBA Hex Notation
    FILE_ATTRIBUTE_READONLY = &H1
    FILE_ATTRIBUTE_HIDDEN = &H2
    FILE_ATTRIBUTE_SYSTEM = &H4
    FILE_ATTRIBUTE_DIRECTORY = &H10
    FILE_ATTRIBUTE_ARCHIVE = &H20
    FILE_ATTRIBUTE_DEVICE = &H40
    FILE_ATTRIBUTE_NORMAL = &H80
    FILE_ATTRIBUTE_TEMPORARY = &H100
    FILE_ATTRIBUTE_SPARSE_FILE = &H200
    FILE_ATTRIBUTE_REPARSE_POINT = &H400
    FILE_ATTRIBUTE_COMPRESSED = &H800
    FILE_ATTRIBUTE_OFFLINE = &H1000
    FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = &H2000
    FILE_ATTRIBUTE_ENCRYPTED = &H4000
    FILE_ATTRIBUTE_VIRTUAL = &H10000
End Enum

Private Declare Function GetFileAttributes Lib "kernel32.dll" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long

Public Sub Test()

    Dim fileTestPath As String
    Dim attributes As Long

    fileTestPath = "C:\yourfile.txt"

    attributes = GetFileAttributes(fileTestPath)

    'uses bitwise AND calculations to determine values
    If (attributes And FileAttribute.FILE_ATTRIBUTE_ARCHIVE) Then Debug.Print "Archive"
    If (attributes And FileAttribute.FILE_ATTRIBUTE_COMPRESSED) Then Debug.Print "Compressed"
    If (attributes And FileAttribute.FILE_ATTRIBUTE_DEVICE) Then Debug.Print "Device"
    If (attributes And FileAttribute.FILE_ATTRIBUTE_DIRECTORY) Then Debug.Print "Directory"
    If (attributes And FileAttribute.FILE_ATTRIBUTE_ENCRYPTED) Then Debug.Print "Encrypted"
    If (attributes And FileAttribute.FILE_ATTRIBUTE_HIDDEN) Then Debug.Print "Hidden"
    If (attributes And FileAttribute.FILE_ATTRIBUTE_NORMAL) Then Debug.Print "Normal"
    If (attributes And FileAttribute.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED) Then Debug.Print "Not Content Indexed"
    If (attributes And FileAttribute.FILE_ATTRIBUTE_OFFLINE) Then Debug.Print "Offline"
    If (attributes And FileAttribute.FILE_ATTRIBUTE_READONLY) Then Debug.Print "ReadOnly"
    If (attributes And FileAttribute.FILE_ATTRIBUTE_REPARSE_POINT) Then Debug.Print "ReparsePoint"
    If (attributes And FileAttribute.FILE_ATTRIBUTE_SPARSE_FILE) Then Debug.Print "SparseFile"
    If (attributes And FileAttribute.FILE_ATTRIBUTE_SYSTEM) Then Debug.Print "System"
    If (attributes And FileAttribute.FILE_ATTRIBUTE_TEMPORARY) Then Debug.Print "Temporary"
    If (attributes And FileAttribute.FILE_ATTRIBUTE_VIRTUAL) Then Debug.Print "Virtual"

End Sub


text:
Q: Changing the "day" contents in pgfgantt charts titles When generating a title with the days in a Gantt chart (package pgfgantt), the day number is generated by
\gantttitlecalendar{day}

and it will generate the day number in the form 01, 02, ... etc.
Is it possible to manipulate this format? For example, adding the initial of the weekday to it, like M01, T02, W03, ...? (this may seems strange but it is quite commonly used in school calendars in Spain).

A: This is a possible way to add a wday specifier:
\documentclass[border=10pt]{standalone}
\usepackage{pgfgantt}

\makeatletter
\def\pgfcalendarweekdayletter#1{%
\ifcase#1M\or T\or W\or T\or F\or S\or S\fi%
}
\ganttset{%
calendar/wday/.code={%
    \ifgtt@calendar@eol\ganttnewline\fi%
    \begingroup%
    \pgfcalendar{}{\gtt@calendar@startdate}{\gtt@calendar@enddate}{%
        \gantttitle{%
            \pgfcalendarweekdayletter{\pgfcalendarcurrentweekday}%
            \pgfcalendarcurrentday}{1}%
    }%
    \endgroup%
    \gtt@calendar@eoltrue%
    }%
}
\makeatother

\begin{document}
\begin{tikzpicture}
    \begin{ganttchart}[
        title/.append style={fill=black!10},
        x unit=10pt,
        time slot format=isodate,
        hgrid, vgrid,
        ]{2017-9-4}{2017-9-17}

        \gantttitlecalendar{year, month=name} \\
        \gantttitle{W1}{7}
        \gantttitle{W2}{7}
        \\
        \gantttitlecalendar[
            title label font=\ttfamily\tiny,
            title label node/.append style={rotate=90},
        ]{wday} \\

    \ganttbar[inline]{task}{2017-9-8}{2017-9-14}

    \end{ganttchart}
\end{tikzpicture}

\end{document}

Which will produce:


text:
Q: How can I get the instance that created another object's instance in php? I need to track which instance created another instance. It's an instancing hierarchy not a parent-child class hierarchy. Here's an example:
class Car{

    private var $engine;
    private var $id;

    public function __construct(){
        $this->id = nextId();
        $this->engine = new Engine(500);
    }
}

class Engine{

    private var $horsepower;
    private var $id;

    public function __construct($hp){
        $this->id = nextId();
        $this->horsepower = $hp;
    }
}

if I do:
$myCar1 = new Car();
$myEngine = new Engine(200);

I currently have 1 instance of Car and 2 of Engine. I need to know which instance created which instance. something like this:
$creator = instanceCreatorOf($myCar1->engine or $myCar1->engine->id);

would return: $myCar or $myCar->id;
but if I do:
$creator = instanceCreatorOf($myEngine or $myEngine->id);

would return: root or null or 0;
I need to track this but having a lot of dynamically created objects I need dynamic tracking of this hierarchy. Any ideas?
thanks!

A: Can you have an Car create its own engine and pass in a reference to itself:
class Car {
  function __construct() {
    myEngine = new Engine(this);
...

and
class Engine {
 var $creator;
 function __construct(Car $car, $horsepower) {
  $this->creator = $car;
...

A: You'd have to look at the debug_backtrace once the instance is created. From there you could store the creator in a variable, as there is no way to do that later. Thus, I'd also suggest passing the creating instance to the other instance if they are conceptually tied together. And Cars and their Engines are.


text:
Q: Prove/disprove statement about functions with special properties Suppose $H:\mathbb{R}^{2n}\to\mathbb{R}$ satisfies the following:

*

*$H\geq0$ everywhere and $H(x)=0\iff x=0$;

*$H\in\mathcal{C}^2(\mathbb{R}^{2n}\smallsetminus\{0\})$;

*$H$ is positively homogeneous of degree 2 (i.e. for all $x\in\mathbb{R}^{2n}\smallsetminus\{0\},\lambda>0$ we have $H(\lambda x)=\lambda^2H(x)$);

*The Hessian of $H$ is everywhere positive definite, except at most in the origin;

*The level sets of $H$ are all compact.

I know the gradient $\nabla H$ is therefore injective. But can it be proven (in general, for in some cases it is of course possible) it is surjective as well? And if not, can you provide a counterexample? Does this statement's truth depend on the dimension (i.e. on $n$)?

A: As said in the comments, $H(x)$ must be:
$$H(x)=\sum_{i\leq j}a_{ij}x_ix_j,$$
for $a_{ij}$ real coefficients, by positive homogeneity. Then its Hessian is precisely the matrix $A=(a_{ij})$, which is therefore invertible. But the gradient is:
$$\nabla H(x)=x\cdot A\cdot(e_1,\dotsc,e_{2n})^T,$$
so the equation $\nabla H(x)=y$ as solution $x=y\cdot A^{-1}$.
Actually, having only positive homogeneity those coefficients may depend on the half-line where $x$ lies. Still, the above should yield surjectivity.
Update
Here is how the comments continue in chat: 1, 2, 3, 4, 5.


text:
Q: Unity3D how to make an object start moving in an arc or circle using radius? Unity3D, C#
I would like to know how to move the object smoothly using radius, I want the object to start moving in a circle from the transform.position, like this:sample of what I want to do, and only using C# script, what I can think of is using transform like below.
timeCounter += Time.deltaTime * speed;
float x = Mathf.Cos(timeCounter) * width;
float z = Mathf.Sin(timeCounter) * height;
transform.position = new Vector3(x, 0, z);

I have tried this https://forum.unity.com/threads/how-to-make-an-object-move-in-a-circular-motion-at-constant-speed.526107/ but it is not what I wanted, the answer of mine (https://youtu.be/V2A-0yOUNwc) make the object quickly move to the right and it uses the middle location as the center then starts moving from the right, and I can't control which angle it will start.

A: Try Transform.RotateAround:
using UnityEngine;

public class RotateAround : MonoBehaviour
{
    public Vector3 rotatingPoint;
    private Vector3 rotAxis = new Vector3(0,1,0);
    void Start()
    {

    }
    void Update()
    {
        transform.RotateAround(rotatingPoint, rotAxis, 1f);
    }
}

Check the documentation. You set the rotation poiunt,the rotation axis and the angle and that is it.


text:
Q: How to eliminiate duplicates rows in table of sql server 2005 database? i am using sql server 2005. i have a table contains duplicated rows. how can i eliminated those duplicate rows in that table? for e.g., the table may contain 3 similar rows in which i want to delete 2 rows and keep the original

A: If you just want to eliminate duplicate records from your result set, you can use the DISTINCT command:
SELECT DISTINCTI field1, field2 FROM...

If you want to delete those duplicate records, you can use COUNT to detect which records have more than one instance, and then deleting them with a subquery

A: First you can copy duplicate record into another table like as following way
Select fieldnames into #temp from table1 group by fieldnames having count (*) > 1

then remove that record from original table
delete from table1 where fieldname in (select fieldnames from #temp)

and finally copy record from temporary table to original source table.
insert table1 select * from #temp

through above mentioned steps you can eliminate duplicate record from table.

A: For understanding purpose, lets take a simple table Employee with below schema
EmployeeId - int
EmployeeName    varchar(50)
Age int

Lets populate with duplicate values. Please note primary key is not duplicated in this case
INSERT INTO Employee(EmployeeId,EmployeeName,Age) VALUES (1,'Mark',20)
INSERT INTO Employee(EmployeeId,EmployeeName,Age) VALUES (2,'Tom',22)
INSERT INTO Employee(EmployeeId,EmployeeName,Age) VALUES (3,'Sam',24)
INSERT INTO Employee(EmployeeId,EmployeeName,Age) VALUES (4,'Mark',20)
INSERT INTO Employee(EmployeeId,EmployeeName,Age) VALUES (5,'Tom',22)
INSERT INTO Employee(EmployeeId,EmployeeName,Age) VALUES (6,'Tom',22)
GO

we can make use of CTE in finding the  duplicate rows.
Gather duplicate rows by using Group by/Count statement.
Once Duplicate rows are Identified, we select those rows from the main table using join condition.
Now rank those Rows and delete all the rows apart from the rows with rank 1.
I find this a lot more elegant.
WITH TotalDuplicates(EmployeeName,Age,Total) AS
(
    SELECT EmployeeName,Age,COUNT(employeeId)  AS Total  FROM Employee
    GROUP BY EmployeeName,Age
    HAVING COUNT(employeeId) > 1
)
,DistinctRows(EmployeeId,EmployeeName,Age) AS
(
    SELECT E.EmployeeId,E.EmployeeName,E.Age FROM Employee AS E
    INNER JOIN TotalDuplicates AS D
    ON (E.EmployeeName = D.EmployeeName AND E.Age = D.Age)
)
,OrderedDuplicateTables(EmployeeId,EmployeeName,Age,Ranking) AS
(
    SELECT
        EmployeeId,
        EmployeeName,
        Age,
        RANK() OVER (PARTITION BY EmployeeName, Age ORDER BY EmployeeId DESC)
    FROM DistinctRows
)

DELETE FROM Employee
WHERE EmployeeId IN (SELECT EmployeeId FROM OrderedDuplicateTables WHERE Ranking > 1)


text:
Q: How to add associated text for input text in Struts html?

Maximum Factory Year

*

<%-- 	 --%>

This is the code that is there. Now using Rational Policy Tester(RPT), I am getting an policy violation of "Each form control must have associated text."... Please an someone help me in sorting out this issue. Thanks in Advance

A: Try changing the id of , because it conflicts with id of your . That's probably why  is confused.


text:
Q: Extracting the closest Point to a Line within a Polygon using ArcGIS for Desktop I have the following shapefiles:

*

*Polyline: Detailing a road network.

*Polygon: Containing approx. 2000 polygons enclosing sections of that road network.

*Point: Containing numerous (OS Addressbase) points falling within each of the polygons.

Using ArcGIS for Desktop, I would like to identify and extract to a new shapefile the point within each polygon that is closest to the road network, and also calculate the distance that each closest point is from the road network.

A: Seems to me that you need to clip your road feature first using your polygons. Then begin the point selection process.
Other thing to consider is how the road feature is drawn. Is it a polyline? Is a single feature? If you're trying to get only 1 point that is closest then you need to make sure the individual roads are 1 feature too.
This would be so much easier if you knew the minimum distance for a point. My initial thought was to use a simple 'select by location' with a minimum distance to narrow down your selection. I will try and work on this and see what I come up with. This seems like a geoprocessing tool for spatial statistics.
I wanted to iron out some of the variables in your question first before I continue.


text:
Q: How to digitally sign PDF files with XFA forms using iText iText release notes mention that signing of PDFs with XFA forms is supported from iText versions 5.4.2 and 5.4.3:
http://itextpdf.com/history/?branch=54&node=542
http://itextpdf.com/history/?branch=54&node=543
Is there a documentation somewhere how to do the signing in Java?
I am specifically interested in signing PDFs with XFA where there is a prepared field for signature.

A: This is a small example showing how to sign using XmlDSig:
PdfReader reader =new  PdfReader(src);
FileOutputStream os =new  FileOutputStream(dest);
PdfStamper stamper = PdfStamper.createXmlSignature(reader, os);
XmlSignatureAppearance appearance = stamper.getXmlSignatureAppearance();
appearance.setXmlLocator(new  XfaXmlLocator(stamper));
appearance.setXpathConstructor(new XfaXpathConstructor(XfaXpathConstructor.XdpPackage.Datasets));
ExternalSignature signature =new  PrivateKeySignature(pk, digestAlgorithm,"BC");
//use signXmlDSig or signXades
MakeXmlSignature.signXmlDSig(appearance, signature, chain);

You can also sign using XAdES, but then you won't be able to validate the signature in Adobe software because I don't think Adobe already supports XAdES (please correct me if I'm wrong).


text:
Q: Liveweb Plugin for Powerpoint: Support for HTML5 Canvas? I'm thinking of using the Liveweb plugin for Powerpoint, to embed a web page in a Powerpoint presentation.
Does Liveweb support HTML5 Canvas? Does it support Javascript?
Thanks very much in advance to all for any info.

A: Shyam Pillai's LiveWeb?  It simply embeds an instance of the browser control into your presentation.  It doesn't support any web technologies ... just turns the browser loose on them, so it'll depend on the MSIE version in place and what it supports and your Internet settings (ie, whether javascript is disabled or not).
Or the short version:  Can't answer that.  Try it for yourself and see.  ;-)

A: So far it doesn't seem to be working.  I can access a web page from inside a PowerPoint slide show. I can use the navigation on the page and navigate around the site. But when I go to a page that uses HTML5 Canvas, the Canvas objects don't yet appear.


text:
Q: Get random text between two regexen I have a file of scraped posts that looks like this:
1 Name: foo

Hello, my name is foo.

2 Name: bar

Hello.
Multi
line
post.

3 Name: foo

Hello, bar!

I am capable of writing a regex that will match just the headers (because they have some HTML that's not allowed in posts).
How would I get a random post from this file? Just the text, no names or such.
EDIT: Note that some post numbers may be missing.

A: If you have Ruby(1.9+)
$ ruby -0777 -ne 'a=$_.split(/\d+\sName:.*/);puts a.reject(&:empty?).shuffle.first' file

Hello, my name is foo.

$ ruby -0777 -ne 'a=$_.split(/\d+\sName:.*/);puts a.reject(&:empty?).shuffle.first' file

Hello, bar!


text:
Q: How can I improve the performance of this jquery animation code I've written some code that when I hover over an element, adds four arrows around it and loops an animation so that they move back and forwards.
This is to visually show that the element is draggable. I am using the hoverIntent plugin to only draw the arrows when the user intends to hover over the element.  I am also using jQueryUI for the element positioning.
Appending an item to the document and then animating it is something I have never done before and I am certain that I have coded this poorly causing the performance to be less than optimal.
How could I go about making this code perform better?
jQuery.fx.interval = 1;

// Add Hover arrows
$('.table-row.songnamecolumn').livequery(function($songRow) {
    var $songRow = $(this).closest('tr').children('td');
    var $appenditem = $(this);
    var $this = $(this);

    var loop = function loop(){
        $('#toparrow').animate({ top:'-=15px'},500).animate({ top:'+=15px'},100);
        $('#bottomarrow').animate({ top:'+=15px'},500).animate({ top:'-=15px'},100);
        $('#leftarrow').animate({ left:'-=15px'},500).animate({ left:'+=15px'},100);
        $('#rightarrow').animate({ left:'+=15px'},500).animate({ left:'-=15px'},100);
    }

    $(this).hoverIntent({
        sensitivity: 3, // How sensitive the hoverIntent should be
        interval: 200, // How often in milliseconds the onmouseover should be checked
        over: slidedrag, // Function to call when mouseover is called
        timeout: 200, // How often in milliseconds the onmouseout should be checked
        out: slidedragback // Function to call when mouseout is called
    });

    function slidedrag() {
        $('

'
        +'

'
        +'

'
        +'

').appendTo($appenditem);

        $('#toparrow').position ({
            of: $this,
            my: 'center top',
            at: 'center top',
            offset: "0 -18"
        })

        $('#bottomarrow').position ({
            of: $(this),
            my: 'center bottom',
            at: 'center bottom',
            offset: "0 18"
        })

        $('#leftarrow').position ({
            of: $(this),
            my: 'left center',
            at: 'left center',
            offset: "-10 0"
        })

        $('#rightarrow').position ({
            of: $(this),
            my: 'right center',
            at: 'right center',
            offset: "10 0"
        })

        $('#toparrow, #bottomarrow, #leftarrow, #rightarrow').animate({opacity:'0.5'},600);
        setInterval(loop, 600);
    }

    function slidedragback() {
        clearInterval(loop);
        $('#toparrow, #bottomarrow, #leftarrow, #rightarrow').animate({opacity:'0'},600);
        $('#toparrow,#bottomarrow,#leftarrow,#rightarrow').remove();
    }
});

A: I see you're selecting the same elements more than once. I suggest you to store them as local variable and recall the variable:
var arrow_top = $('#toparrow');

Remove over white space in you code block:
out: slidedragback // Function to call when mouseout is called
});

function slidedrag() {

Last, avoid doing over animations.


text:
Q: sscanf for formatting string from file As part of a homework assignment I need to load a file with data in the following format:
R1  Fre     17/07/2015   18.00     FCN - SDR     0 - 2     3.211
R1  Lor     18/07/2015   16.00     FCM - VFF     2 - 0     7.232

For doing so I used fgets to store the string in a temporary string and after that sscanf to format the string while iterating through the file line by line.
while(fgets(temp, MAX_LINE_SIZE, input_file)!= NULL) {
  sscanf(temp,
    " %*s %3s %d / %d / %d %s %3s - %3s %d - %d %6s",

    round[i].match[j].weekday,
    &round[i].match[j].day,
    ..... And so on ....
  j++;
}

Current output is:
Weekday: Fre18.00FCNSDR3.211
Day: 17
Month: 7
Year: 2015
Start: 18.00FCNSDR3.211
Home team: FCNSDR3.211
Away team: SDR3.211
Score: 0 - 2
Viewers: 3.211

Expected output is:
Weekday: Fre
Day: 17
Month: 7
Year: 2015
Start: 18.00
Home team: FCN
Away team: SDR
Score: 0 - 2
Viewers: 3.211

The strings with %s placeholder in sscanf seems to putting themselves together for some reason.
All help is much appreciated.

A: Are you sure you're storing strings like Fre in a 4-byte character array?
%3s actually reads in 4 bytes.  F, r, e, and \0.  If you use an array too small then you overwrite the \0, causing the string to include whatever comes next in memory (in this case, more strings).


text:
Q: Put image in a text please could you tell me how can I put image in text from some position (not inline="left or right..."). I have to do this without tables.

A: Wrap (if not already) your paragraph in a div..
then wrap your image in a div, set that divs id  (i.e. 'id=my_img_div'), and make sure that this 'image div' is in the same wrapper div as your paragraph..
then add this rule to your css stylesheet:
#my_img_div {
float: right;
}

The image should now be positioned at the right with the paragraph's text wrapping around it nicely.

A: <hmtl>
<title>hello</title>

text on left
image inside (anchor)
text on right


text:
Q: Update LaTeX document content with the parameter values of a Matlab model I have a Matlab model with some parameters ( a=1, b=2, c=3, etc). I want this values to appear "automatically" in my LaTeX document and when they are changed in the Matlab code they are in the LaTeX document also.
I imagined something like storing the Matlab parameters values in a text file which is then used by the LaTeX document to be incorporated in the text or in a table. Updating the Matlab parameter values, running the code to update the value text file, and compiling the LaTeX document should then allow to have the values up to date in the LaTeX document.
I am pretty sure I am not the first one with this kind of question but I could not find the right keywords to get a solution.
Thank you in advance for your help.

A: Thanks to moewe, here the solution to my problem:
The Matlab code example:
clear all
close all
clc

%Parameters
a=3;
b=-2;
c=3;

% Model
y=a^3+2*b^2+c

%% Tex file writing

str = strcat(['\newcommand*{\parama}{',num2str(a),'}','\newcommand*{\paramb}{',num2str(b),'}','\newcommand*{\paramc}{',num2str(c),'}','\newcommand*{\paramy}{',num2str(y),'}']);

% To escape the backslashes and percent signs:
str = strrep(str,'\','\\');
str = strrep(str,'%','%%');
fileID = fopen('parameters.tex','w');

%Export values to use in LateX
fprintf(fileID,str);

This code produces the LaTeX file parameters.tex with the currently used parameter values.
The minimal LaTeX example using the parameter values:
\documentclass[12pt]{standalone}

\input{parameters.tex}

\begin{document}

The Matlab model uses $a=\parama$, $b=\paramb$ and $c=\paramc$ to calculate $y=a^3+2b^2+c=\paramy$

\end{document}

Which produces in LaTeX:

A similar example I just found trying to deal in Matlab with the special character used in LaTeX (\, %, etc) is here : https://stackoverflow.com/questions/11523555/write-string-as-it-is-to-a-file-in-matlab


text:
Q: IIS 7 Url Rewrite Not Working Inbound IIS7 Url Rewrite Rule not working
Below is the URL Rewrite rule I've defined.
    <rewrite>
        <rules>
            <rule name="Redirect domain.co.uk to www.domain.co.uk" enabled="true" stopProcessing="true">
                <match url="^domain\.co\.uk(.*)" />
                <action type="Redirect" url="http://www.domain.co.uk{R:1}" />
            </rule>
        </rules>
    </rewrite>

When I go to domain.co.uk it's not redirecting to www.domain.co.uk. Am I doing something wrong?

A: Had to add a condition to get it to work. Like so...
    <rewrite>
        <rules>
            <rule name="Redirect root to www" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="^domain\.co\.uk(.*)" />
                </conditions>
                <action type="Redirect" url="http://www.domain.co.uk/{R:1}" />
            </rule>
        </rules>
    </rewrite>

URL Rewrite Tips


text:
Q: Add fields to TYPO3 template for global site info? How can I add some fields to the TYPO3 template (or a better location) for general site info?
For example, a phone number field so that I can add it to the site header or other non content area.
In the past I have used content elements in a special folder to add something like this, but that's not very user friendly for site editors.

A: If you want it to be (relatively) easy for site editors to edit, without building a custom module or something like that, content elements in a special folder is your best bet. We often use custom content elements for this so the field are more logical, but you do need to do some programming for this. More on creating custom fields can be found at https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/ContentElements/AddingYourOwnContentElements.html
An alternative could be using a TypoScript constant. These are relatively easy to edit using the Constants editor in the Template module. Assuming you use Fluid templates, you can add it to your template with <f:cObject typoscriptObjectPath="lib.phoneNumber" /> In TypoScript you then add the following:
lib.phoneNumber = TEXT
lib.phoneNumber.value = {$phoneNumber}

More about the Constants editor can be found at https://docs.typo3.org/m/typo3/reference-typoscript/master/en-us/UsingSetting/TheConstantEditor.html

A: in both other answers I miss the simplest solution:
defining the value as a generic fluid variable
page {
    10 = FLUIDTEMPLATE
    10 {
        :
        variables {
            :
            phoneNumber = TEXT
            phoneNumber.value = {$phoneNumber}
        }
    }
}

You do not need to use settings as it is no setting.
or jumping back from fluid to typoscript with lib.anything and a call to f:cObject viewhelper.

Aside of that I would recommend to consider if it is ok to need an admin (or even a maintainer to deploy a new version) to change that phone number (all typoscript, setup and constants, belongs into the site-extensions which is provided in a repository).
you always could restrict normal editors from accessing special pages or even columns or special content elements, where an admin can change data without a deploy-process.
(example: How much hassle it is if you need to change the number in case of emergency because of a breakdown of phone lines?)

A: I think the easiest way is to add it with TS, something like that :
page {
   10 {
      settings {
         siteInfos {
            phone = 01 02 03 04 05
         }
      }
   }
}

And then , you can use this in you Fluid Templates :
{settings.siteInfos.phone}

Florian


text:
Q: Filter an ArrayList of Objects using Java Streams to return an ArrayList of type String I can't find an exact solution for this on SO. I have a Crowd class which consists of a Crowd object which is an arraylist of type People. People is a class with properties String name, Double bankBalance, Integer numberOfCarsOwned.
In my crowd class I have the following method whereby I seek to filter by names beginning with the letter P and return these an arraylist of type String:
  public ArrayList<String> filterByLetterP(){
       ArrayList<String> filteredNames =  this.crowd.stream()
               .filter(name -> name.getName().contains("P"));
               return filteredNames;
    }

My error is:
required type ArrayList<String> provided Stream<People>
Note: My solution must make use of streams. How can I correct my solution to get it to work?
Reference info below.
 People class definition:
public class People {

    private String name;
    private Double bankBalance;
    private Integer numberOfCarsOwned;

    public People(String name, Double bankBalance, Integer numberOfCarsOwned) {
        this.name = name;
        this.bankBalance = bankBalance;
        this.numberOfCarsOwned = numberOfCarsOwned;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getBankBalance() {
        return bankBalance;
    }

    public void setBankBalance(Double bankBalance) {
        this.bankBalance = bankBalance;
    }

    public Integer getNumberOfCarsOwned() {
        return numberOfCarsOwned;
    }

    public void setNumberOfCarsOwned(Integer numberOfCarsOwned) {
        this.numberOfCarsOwned = numberOfCarsOwned;
    }
}

Crowdclass definition:
public class Crowd {

    private ArrayList<People> crowd;

    public Crowd() {
        this.crowd = new ArrayList<>();
    }

    public ArrayList<People> getCrowd() {
        return crowd;
    }

    public void setCrowd(ArrayList<People> crowd) {
        this.crowd = crowd;
    }

    public void addPeopleToCrowd(People people){
        this.crowd.add(people);
    }

    public ArrayList<String> filterByLetterP(){
       ArrayList<String> filteredNames =  this.crowd.stream()
               .filter(name -> name.getName().contains("P"));
               return filteredNames;
    }
}

A: A couple of things needs to be addressed:

*

*You should use String#startsWith instead of String#contains.

*You have to map the Stream to People#name.

*You have missed collecting the Stream.

Do it as shown below:
public List<String> filterByLetterP() {
    List<String> filteredNames = this.crowd.stream()
            .map(p -> p.getName())
            .filter(s -> s.startsWith("P"))
            .collect(Collectors.toList());
    return filteredNames;
}

A: You should change your filter because it doesn't check names with beginning letter 'P':
public List<String> filterByLetterP(){
    return this.crowd.stream()
            .map(People::getName)
            .filter(name -> name.charAt(0) == 'P')
            .collect(Collectors.toList());
}


text:
Q: JS : endDate issue in viewmode "months" using bootstrap datepicker Using the following dates "2013,01,01" and "2015,09,28" and startdate and enddate,
bootstrap datepicker works perfectly in a daily viewmode,
but switching to monthly viewmode, the month of the endDate and the previous one (here September and August) are not clickable, regardless all the different date values and formats i have tried. (first/last day of month,
Some code :
                var params_datepicker = {
                    language : "fr-FR",
                    clearBtn : true,
                    autoclose : true,
                    todayHighlight : true,
                    format : 'dd/mm/yyyy',
                    startDate : new Date(limitesdates.min), // 2013,01,01
                    endDate : new Date(limitesdates.max)  // 2015,09,28
                };

Any idea?

A: After a whole day chasing this bug (thanks to acrobat, the fiddle made me figuring out where the bug was located), i finally found the bug.
My bootstrap-datepicker.min.js file was not up to date, (~ 2 weeks).
I noticed that as i joined the last bootstrap-datepicker.js to my project : the issue vanished as soon as i joined the latest files.
Have a nice day. ;)