text:
Q: Html tags are not rendering under if-else statements in Email Templates in kentico8 I have a requirement to generate e-mails based on conditions. Here is the e-mail template:

      This is an automatic notification sent by Kentico. The following document is waiting for your approval. Please sign in to the Kentico administration interface and approve it.

    {%if (2<3) { %}

      This is Sent By : {%SentBy%}

      SiteURL

    {% }else{%}

This is else Method

    {%}#%}

And here's the code behind:
EmailMessage msg = new CMS.EmailEngine.EmailMessage();
        EmailTemplateInfo etInfo = EmailTemplateProvider.GetEmailTemplate("Email", SiteContext.CurrentSiteID);
        if (etInfo != null)
        {
            MacroResolver mcr = MacroResolver.GetInstance();
            mcr.SetNamedSourceData("siteurl", "http://google.com/");
            mcr.SetNamedSourceData("SentBy", "admin");

            msg.EmailFormat = EmailFormatEnum.Both;
            msg.From = etInfo.TemplateFrom;
            msg.Recipients = "xyz@google.com";
            msg.Subject = etInfo.TemplateSubject;
            msg.Body = etInfo.TemplateText;
            msg.PlainTextBody = etInfo.TemplatePlainText;

            //Send Email..
            EmailSender.SendEmailWithTemplateText(SiteContext.CurrentSiteName, msg, etInfo, mcr, true);

        }

When I send the e-mail it gets rendered as follows:
This is an automatic notification sent by Kentico. The following document is waiting for your approval. Please sign in to the Kentico administration interface and approve it.

 This is Sent By : admin

 SiteURL

All HTML tags below the "if" condition are not being rendered.

A: In order to get text with resolved macros you also need to call ResolveMacros method.
In your case it could be something like this:
        EmailMessage msg = new CMS.EmailEngine.EmailMessage();
        EmailTemplateInfo etInfo = EmailTemplateProvider.GetEmailTemplate("Email", SiteContext.CurrentSiteID);
        if (etInfo != null)
        {
            MacroResolver mcr = MacroResolver.GetInstance();
            mcr.SetNamedSourceData("siteurl", "http://google.com/");
            mcr.SetNamedSourceData("SentBy", "admin");

            msg.EmailFormat = EmailFormatEnum.Both;
            msg.From = etInfo.TemplateFrom;
            msg.Recipients = "xyz@google.com";
            msg.Subject = etInfo.TemplateSubject;
            msg.Body = mcr.ResolveMacros(etInfo.TemplateText);
            msg.PlainTextBody = mcr.ResolveMacros(etInfo.TemplatePlainText);

            //Send Email..
            EmailSender.SendEmailWithTemplateText(SiteContext.CurrentSiteName, msg, etInfo, mcr, true);
        }

Notice the mcr.ResolveMacros(etInfo.TemplateText) code that I'm using.

A: Normally I'd add encode parameter to the macro:
{% some_macro_with_html_output|(encode)false %}

I'm not sure if it works with your type of record. Try to add it right before closing tag of else statement.


text:
Q: Some Technical Problem with my Blog Post ! I recently posted a article in my blog site which uses Wordpress for CMS and after posting the article i noticed a set of dots appearing after the post .
I'm not able to remove it .. Can anyone help me ? and explain me what's wrong with it ?!

A: Are you seeing the dots in your list of posts?  If yes, you're looking at the list of post excerpts.  Once you click one of the title links, you'll see the post text without trailing dots.
Alternatively you can add this method to your theme's functions.php file to remove the dots for you.

A: Do you see the whole post or just part of the post? Do you user the  tag in your post? It could be that it is just showing part of the post if you do use the , What theme are you using? It could be the lots of it ...
Looks like we cannot connect the dots :-) yet!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Solr Spell Check result based filter query I implemented Solr SpellCheck Component based on the document from http://wiki.apache.org/solr/SpellCheckComponent , it works good. But i am trying to filter the   spell check result based on some other filter. Consider the following schema
product_name
product_text
product_category
product_spell -> copy string from product_name and product_text . And tokenized using white space analyzer

For the above schema, i am trying to filter the spell check result based on provided category.  I tried querying like http://127.0.0.1:8080/solr/colr1/myspellcheck/?q=product_category:160%20appl&spellcheck=true&spellcheck.extendedResults=true&spellcheck.collate=true . Spellcheck results does not consider the product_category:160
Is it because the dictionary was build for all the categories? If so is it a good idea to create the dictionary for every category?
Is it not possible to have another filter condition in spellcheck component?
I am using solr 3.5

A: I previously understood from the SOLR-2010 issue that filtering through the fq parameter should be possible using collation, but it isn't, I think I misunderstood.
In fact, the SpellCheckComponent has most likely a separate index, except for the DirectoSolrSpellChecker implementation. It means the field you select is indexed in a different index, which contains only the information about that specific field you chose to make spelling corrections.
If you're curious, you can also have a look how that additional index looks like using luke, since it's of course a lucene index. Unfortunately filtering using other fields isn't an option there, simply because there is only one field there, the one you use to make spelling corrections.


text:
Q: Untar *tar.gz files in s3, then compress them as *.gz and finally move those new compressed files to a new location in s3 As the noted title I'm trying to untar/uncompress several tar.gz files for a given path in s3 (those are JSON files) and then (in memory) compress them as .gz and finally move to another location in s3 again.
This is the code I've tried so far.
`
s3_resource = resource('s3')

tar_file = s3_resource.Object(bucket_name=bucketname, key=key_path)
file_object = BytesIO(tar_file.get()["Body"].read())

with tarfile.open(fileobj=file_object, mode=('r:gz')) as z:
    for filename in z.getmembers():
        #print(filename)

        if (filename.isfile()):
            logger.info(f'current file in zipfile: {filename.name}')
            final_file_path = f"{filename.name}.gzip"

            #print(final_file_path)

            gzipped_content = gzip.compress(z.extractfile(filename))

            s3_resource.meta.client.upload_fileobj(
                io.BytesIO(gzipped_content),
                Bucket=bucket_name,
                Key=f'{key_path_untar}/{final_file_path}'
            )

`
The problem specifically is with the gzipped_content = gzip.compress(z.extractfile(filename)) part.
But I'm receiving the error
a bytes-like object is required, not 'ExFileObject'


text:
Q: How to pass a function as predicate to another function, When name of the predicate function is received at RunTime? I receive the name of the function to be used as biPredicate at runtime. I want to pass around this biPredicate and evaluate, basically filter to get results.
Following is my utility that defines biPredicates. I tried utilizing MethodHandle and Lambda Functions. When I use
new FilterUtility().execute("genericFilter");

I get java.lang.AbstractMethodError

public class FilterUtility {

public void execute(String filterName) throws Throwable {
    ActualBean beanObject = ActualBean.builder().param1("true").param2("false").build();

    MethodType methodType = MethodType.methodType(boolean.class, Object.class, Object.class);
    MethodHandles.Lookup lookup = MethodHandles.lookup();
    MethodHandle handle = lookup.findStatic(FilterUtility.class, filterName, methodType);
    BiPredicate<Object, Object> f = (BiPredicate<Object, Object>) LambdaMetafactory.metafactory(lookup,
            "test",
            MethodType.methodType(BiPredicate.class),
            methodType.generic(),
            handle,
            methodType)
            .getTarget()
            .invokeExact();

    resolve(beanObject, new HashMap<>(), f);
}

public static <SourceObject, TemplateObject> Map<String, String> resolve(SourceObject src,
        TemplateObject template,
        BiPredicate<SourceObject, TemplateObject> p) {
    if (p.test(src, template))
        return new HashMap<>();

    return null;
}

public static <SourceObject, TemplateObject> boolean genericFilter(SourceObject x, TemplateObject y) {
    ObjectMapper ob = new ObjectMapper();
    Map<String, Object> source = ob.convertValue(x, Map.class);
    Map<String, Object> template = ob.convertValue(y, Map.class);

    for (Map.Entry<String, Object> entry : template.entrySet()) {
        if (!source.get(entry.getKey()).equals(entry.getValue()))
            return false;
    }
    return true;
}
}

When I change implementation of execute to following, I dont get exceptions.
public void execute(String filterName) throws Throwable {
    ActualBean beanObject = ActualBean.builder().param1("true").param2("false").build();
    resolve(beanObject, new HashMap<>(), FilterUtility::genericFilter); }

This makes me believe that there is something wrong with the way I am trying to find the function with name and send it as a biPredicate.

A: You are calling the method methodType.generic() which will replace all parameter types and the return type with java.lang.Object, including primitive types. So you are transforming the target method's signature (Object,Object)->boolean to (Object,Object)->Object, effectively creating a class with a method Object test(Object,Object) which will invoke your target method and box the result.
Such type mismatches are not checked by the lambda metafactory. So when you try to invoke BiPredicate's method boolean test(Object,Object) on that generated class, an error will be thrown.
The correct method to use is methodType.erase(), which will replace all reference types with java.lang.Object but keep primitive types as-is. Though, in this specific case, you don't need to transform the method type at all, as the target method's type is already (Object,Object)->boolean, so just replacing methodType.generic() with methodType would work too.


text:
Q: How to Search and Retrieve Image/Picture that was converted into bytes and saved in local database I have a program here that saves an image in a local database with an Image data type in visual studio 2010 using a these codes:
    private void button10_Click(object sender, EventArgs e)
    {
        try
        {
            if (pictureBox1.ImageLocation == "" || textBox13.Text == "")
            {
                MessageBox.Show("No Filename or No Picture Selected!","Warning!".ToUpper(), MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
            }
            else
            {
                byte[] imgData;
                imgData = File.ReadAllBytes(pictureBox1.ImageLocation);

                Database1DataSet2TableAdapters.tblPictureTableAdapter photos = new Database1DataSet2TableAdapters.tblPictureTableAdapter();
                photos.InsertQuery(this.textBox13.Text.Trim(), imgData);

                MessageBox.Show("Saved");
            }
        }
        catch
        {
            MessageBox.Show("Duplication!");
        }
    }

then i insert these codes to search the ID of the image and display the image on a picture box:
    public Database1DataSet2.tblPictureDataTable GetDataRegpic(String data)
    {
        Database1DataSet2TableAdapters.tblPictureTableAdapter ret = new Database1DataSet2TableAdapters.tblPictureTableAdapter();
        return ret.GetDataBy2(this.textBox3.Text.Trim());
    }

    private void button11_Click(object sender, EventArgs e)
    {
        try
        {
                Database1DataSet2.tblPictureDataTable getregA = GetDataRegpic(this.textBox3.Text);
                Database1DataSet2.tblPictureRow getregA1 = (Database1DataSet2.tblPictureRow)getregA.Rows[0];
                byte[] imgData = (byte[])(getregA1["Image"]);
                MemoryStream ms = new MemoryStream(imgData);
                this.pictureBox1.Image = Image.FromStream(ms);
                this.textBox14.Text = getregA1.abc.Trim();
        }
        catch
        {
            MessageBox.Show("Member Does not Exist");
        }
    }

but it seems that it doesn't work.
Can anyone help me?


text:
Q: How can I pull data from a webpage and store it google sheets? Trending data from enviormental monitor I have this environmental monitor from a company that went out of business but it's useful, it has an NDIR co2 sensor, tempature and RH. It has an ethernet port and webserver.
You can go to different urls such as 127.0.0.1/setget?%sen-3
and it outputs:
handler.setget(%sen-3)
500

where 500 would be the current room co2 concentration in ppm. Can someone point me in the direction to go about scraping this into a database and charting it to see trends in co2. Ex: how much does co2 rise while sleeping, how much does it change with occupancy, etc. I was thinking Google Sheets and Google Charts would be a good start. How can I scrape this page and store it in Google Sheets? Python? I only have experience with HTML, PHP but don't mind learning python if it isn't too complicated of a project.
Thanks

A: got a lead! Need to setup a rasberry pi with home assistant. then use sensor scrape to scarpe the data and define it as a sensor. Home assistant is a power interface!
https://www.home-assistant.io/components/sensor.scrape/


text:
Q: Why is AjaxForm in jQuery UI Dialog accumulating posts? I have a AjaxForm in a modalDialog that is accumulating posts. The first time it posts OK, then the second time it posts twice, then posts three times and so on...
I have found several people with the same problem, but none of their solutions worked for me. The click event and the GET are always called once, but the POST and success function are called several times.
This is my form in a partial view:
@using (Ajax.BeginForm(new AjaxOptions { OnSuccess = "handleModalSubmit"})) {
    @Html.ValidationSummary(true)
        @*FORM FIELDS*@

            <input type="submit" class="medium buttons" value="Save" />

}

On the main view this is how it (supposed to) works:

And the controller:
public ActionResult AddLine()
{
    //Add some stuff to ViewBag
    return PartialView();
}

[HttpPost]
public ActionResult AddLine(Fatura fatura)
{
    if (ModelState.IsValid)
    {
        db.Faturas.Add(fatura);
        db.SaveChanges();
        return Json(new
        {
            value = true,
            tabelaID = "idx",
            linha = new object[] {"1", 2, 3, 4, 5, 6}
        });
    }
    //Add some stuff to ViewBag
    return PartialView(fatura);
}

Why am I getting repeated posts?

A: I found out what I was doing wrong. I was loading JqueryVal on the partial view of the modal. Change it to the main view and it worked.


text:
Q: Can I control function inlining? Babel is causing "Cannot access [variable] before initialization" Babel is causing me to have a "Cannot access [variable] before initialization" error that is being caused by how babel is transpiling the following two functions:
function dangerousStyleValue(name: string, value: Value) {
  if (value == null || typeof value === 'boolean' || value === '') return ''
  if (
    typeof value === 'number' &&
    value !== 0 &&
    !isCustomPropRE.test(name) &&
    !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])
  )
    return value + 'px'
  // Presumes implicit 'px' suffix for unitless numbers
  return ('' + value).trim()
}

export function applyAnimatedValues(instance: Instance, props: Lookup) {
  if (!instance.nodeType || !instance.setAttribute) {
    return false
  }

  const isFilterElement =
    instance.nodeName === 'filter' ||
    (instance.parentNode && instance.parentNode.nodeName === 'filter')

  const { style, children, scrollTop, scrollLeft, ...attributes } = props!

  const values = Object.values(attributes)
  const names = Object.keys(attributes).map(name =>
    isFilterElement || instance.hasAttribute(name)
      ? name
      : attributeCache[name] ||
        (attributeCache[name] = name.replace(
          /([A-Z])/g,
          // Attributes are written in dash case
          n => '-' + n.toLowerCase()
        ))
  )

  if (children !== void 0) {
    instance.textContent = children
  }

  // Apply CSS styles
  for (let name in style) {
    if (style.hasOwnProperty(name)) {
      const value = dangerousStyleValue(name, style[name])
      if (name === 'float') name = 'cssFloat'
      else if (isCustomPropRE.test(name)) {
        instance.style.setProperty(name, value)
      } else {
        instance.style[name] = value
      }
    }
  }

  // Apply DOM attributes
  names.forEach((name, i) => {
    instance.setAttribute(name, values[i])
  })

  if (scrollTop !== void 0) {
    instance.scrollTop = scrollTop
  }
  if (scrollLeft !== void 0) {
    instance.scrollLeft = scrollLeft
  }
}

The transpiled output is:
applyAnimatedValues: function(e, t) {
        if (!e.nodeType || !e.setAttribute) return !1;
        const n = "filter" === e.nodeName || e.parentNode && "filter" === e.parentNode.nodeName,
            r = t,
            {
                style: o,
                children: i,
                scrollTop: a,
                scrollLeft: d
            } = r,
            p = u(r, s),
            h = Object.values(p),
            v = Object.keys(p).map(t => n || e.hasAttribute(t) ? t : c[t] || (c[t] = t.replace(/([A-Z])/g, e => "-" + e.toLowerCase())));
        void 0 !== i && (e.textContent = i);
        for (let u in o)
            if (o.hasOwnProperty(u)) {
                const t = null == (t = o[u = u]) || "boolean" === typeof t || "" === t ? "" : "number" !== typeof t || 0 === t || l.test(u) || f.hasOwnProperty(u) && f[u] ? ("" + t).trim() : t + "px";
                "float" === u ? u = "cssFloat" : l.test(u) ? e.style.setProperty(u, t) : e.style[u] = t
            }
        var m, g;
        v.forEach((t, n) => {
            e.setAttribute(t, h[n])
        }), void 0 !== a && (e.scrollTop = a), void 0 !== d && (e.scrollLeft = d)

I'm getting this error:

As far as I can tell, it is coming from the inlined version of the dangerousStyleValue function:
const t = null == (t = o[u = u]) || "boolean" === typeof t || "" === t ? "" : "number" !== typeof t || 0 === t || l.test(u) || f.hasOwnProperty(u) && f[u] ? ("" + t).trim() : t + "px";
                "float" === u ? u = "cssFloat" : l.test(u) ? e.style.setProperty(u, t) : e.style[u] = t

I believe this is being caused by my babel configuration, which is:
{
    const babelLoader = environment.loaders.get('babel');
    const babelLoaderUsed = babelLoader.use.find(
      (el) => el.loader === 'babel-loader'
    );

    babelLoader.test = /\.(js|jsx|ts|tsx)?(\.erb)?$/;

    babelLoader.exclude = /node_modules\/(?!(recoil)\/).*/;
    babelLoaderUsed.options = merge({}, babelLoaderUsed.options, {
      presets: [
        [
          '@babel/preset-env',
          {
            modules: false,
            targets: {
              browsers: ['> 1%', 'IE 11']
            },
            forceAllTransforms: true,
            useBuiltIns: 'entry',
            corejs: {
              version: 2,
              proposals: true
            }
          }
        ],
        '@babel/preset-react',
        '@babel/preset-typescript'
      ],
      plugins: [
        '@babel/plugin-transform-typescript',
        '@babel/plugin-syntax-dynamic-import',
        '@babel/plugin-proposal-object-rest-spread',
        '@babel/plugin-transform-modules-commonjs',
        [
          '@babel/plugin-proposal-class-properties',
          {
            spec: true
          }
        ],
        [
          'module-resolver',
          {
            root: ['./app'],
            alias: {
              assets: './assets'
            }
          }
        ],
        '@babel/plugin-syntax-import-meta',
        '@babel/plugin-proposal-json-strings',
        [
          '@babel/plugin-proposal-decorators',
          {
            legacy: true
          }
        ],
        '@babel/plugin-proposal-function-sent',
        '@babel/plugin-proposal-export-namespace-from',
        '@babel/plugin-proposal-numeric-separator',
        '@babel/plugin-proposal-throw-expressions'
      ]
    });
  }

I don't know what setting I need to change in order to fix how the function is being inlined (or to disable inlining if that is necessary). I do need to support IE11 still, that is very important.

A: I finally figured out that it was coming from uglifyjs. I turned off inlining and the problem was resolved.


text:
Q: Use of "up" in "back up", to mean going in reverse Why do we use the term "back up" when we are going in reverse? This is sometimes confusing for young English Language learners.  Going backwards is understandable, where does the word "up" fit in? Are we moving in two directions?

A: The word up can have literal spatial meaning with respect to a vertical or horizontal axis.  To climb up a ladder. To walk up a ramp. To take the elevator or lift up to the 10th floor. We're going up to London (destination).
But it also has a more abstract figurative meaning, originating in the semantic realm of motion, specifically as it relates to the commencement or initiation of actions.  The actor moves from a state of inaction, understood (at some deep metaphorical level) figuratively as a kind of recumbency, to a state of action.

He said, "I told you to back up, motherf_cker !"  So I backed down and backed up.

P.S. Compare German auf, e.g.  Hör auf !  (i.e. "desist!").

A:
Why do we say "back up" when we are going in reverse?

The word up has many definitions, but here it means to a source or origin. The word back here is acting as shorthand for backwards or drive in reverse. Thus putting the two together, we get the following statement:

Drive in reverse toward your point of origin

But that's a mouthful; saying, "Back up," is so much easier.

A: Of course, you are right, it is difficult to find the logic behind "up". My guess would be "to back" is derived from "to go back(wards)" and "up" is just an enforcing element as in to finish sth up.

A: As noted "back" in the phrase "back up" or "backing up" as used to describe going in reverse is easy to understand.  For me the connection to up was made when I drove a 1960s era column shift vehicle.  What is often referred to as a "three on the tree" to describe a three speed manual shift with shifter on the column.  To place the car in reverse one had to pull the shift lever back and then push up.  Thus "back and up" was the action taken to go in reverse.  For me I equate "backing up" to the "back and up" shifter movement.
I can't say with any authority if that contributed to the term or if that shifter movement was some automotive engineers idea of a bad pun.  Seems reasonable that in future times people may believe up in "backup" as applied to data storage comes from the concept of "the cloud" being up.

A: When it comes to verb-particle phrases, it is often not possible to give a generally applicable rule. It's just important to be aware that English as many of these, and learn them individually. Other "up" verb phrases where the "up" seems arbitrary include "shut up" (stop talking), "hook up", "look up" [a word in the dictionary], "catch up", "put up" (as in to put someone up at your house = to let someone stay at your house overnight), and "lock up".

A: Yall are focused on the words too much. It comes from the old manual transmissions that had "3 on the tree" or a manual shift lever on the steering column. To put the vehicle in reverse you had to pull the shifter back and up

A: This phrase doesn't actually make a lot of sense literally, especially pertaining to the word "up" in the sentence. This is because this is an inseparable phrasal verb, which means that the part with meaning (back) cannot be separated from the part that doesn't have meaning (up).
You can think about it this way in order to separate the lexical part:

To back something up

You can also understand this is through context:

I am backing up by 10 meters.

The opposite would simply be:

I am walking forward by 10 meters.

In both of these examples, movement is happening in only one direction.
If you are interested in a very helpful list of phrasal verbs including this one, you can find one here.
Also see
Omnidisciplinarianist's answer for another great way to understand this.


text:
Q: Resources for Understanding C++ Performance? I'm looking for resources (ideally a book) that will help me gain an in-depth understanding of C++ performance. Here's a little more background:
I write server software with very high throughput requirements and/or low latency requirements. We write in C++; it's not really up for debate at this time. Most of my colleagues seem to have a much better understanding of C++ performance. They have better mental models, so they can tell when a certain bit of code will perform poorly at scale. I lack this understanding, and so I'm looking to improve my mental model.
I am specifically interested in:

*

*Understanding cache effects, and how cache locality due to object layout affects my code's performance. This is the number one issue that seems to be brought up by other members of my team.

*Understanding how memory allocation otherwise affects performance. Should I be using TCMalloc (or other mallocs), and how should I know? How should I tune the various allocation and deallocation parameters?

*How do I know when the overhead from object copying will matter (and therefore should switch to pointers, for example)?

*I'm also generally interested in "optimizations" as long as I have the knowledge as to when to use them.

Things I'm not really interested in:

*

*"High Performance Computing," a term which seems indicate more math/simulation-oriented applications.

*Discussions of C++ performance relative to other languages, since I'm stuck with C++.

As a starting point, anyone know if this book, Efficient C++, would fit the bill?

A: Let me split my recommendations into several sections.
C++ Optimization
As a starting point, I would highly recommend Agner Fog's Optimizing software in C++. This manual gives an excellent overview of the common C++ optimization topics.
Understanding Hardware in General
To have a good mental model of the C++ performance, you also need to understand the underlying hardware. Consider this statement:
a[7] = 5;

On the C++ language side, the line of code is boring from the performance perspective: it's just one memory write. But, on real hardware, the performance of that memory write can vary by orders of magnitude. To understand what's going on at that level, you need to learn about concepts such as caches, processor pipeline, TLB, branch prediction, and so on.
As a quick introduction to processor caches, I'd recommend my article Gallery of Processor Cache Effects. A much deeper and longer (>100 pages) discussion of caches and computer memory is What Every Programmer Should Know About Memory.
To get an overall understanding of modern computer hardware, Computer Architecture: A Quantitative Approach is the commonly recommended book. I didn't read the book myself, but instead learned by reading blogs and experimentation. However, others have apparently found the book to be very useful.
Understanding Specific Processors
At one point in your journey to improve your optimization skills, you'll find it useful to recognize specifics of different processors. As one example of many, different Intel and AMD processors have very different penalties for using unaligned SSE instructions, such as the _mm_storeu_ps C++ intrinsic.
To learn the specifics of different processors, I'd recommend The microarchitecture of Intel, AMD and VIA CPUs: An optimization guide for assembly programmers and compiler makers. In fact, I'm just going to go ahead and recommend all of the optimization manuals from Agner Fog. Also, hardware vendors provide documentation for their particular hardware.
Learning to Use Tools
Having a good mental model of C++ and hardware performance is very useful when optimizing code. But, learning to use the right tools is at least as useful. Arguably the best advice for optimization is "Measure first!". It is extremely difficult to understand the performance of even a simple block of code just by thinking about it. You'll gain a lot of information by running the code and measuring it in various ways.
These are some of the common useful measurements:

*

*Timing: just run the code and measure the time

*Sampling profilers

*Instrumentation profilers

*Processor counters

I won't get into recommendations for specific tools, since I am arguably getting out of scope of your original question. And, tooling is a big topic by itself: tools vary for different hardware platforms, software platforms, and by cost (some are free, some are expensive).
But, you certainly need to be aware that to optimize C++ code, you need to know and use appropriate tools.

A: Valgrind should be your first tool.
Valgrind has a lot of tools, but cachegrind is a great way to see whether your algorithm has good data locality. This will identify memory bottlenecks. Callgrind is another valgrind module that will help you identify processing bottlenecks.
References:
Cachegrind:
http://valgrind.org/docs/manual/cg-manual.html
Callgrind:
http://valgrind.org/docs/manual/cl-manual.html

A: Previous responses gave the most important thinks.
Just one warning : do some profiling (valgrind), that's where you'll get the quick win. After that, trying to get cache optimizations, looking at SSE… will require a lot more effort, for (at least at the begining) little improvement.
Also, C++ is a huge language, and the compilers does magic. Templates, inlining, and so forth allow the compiler to do great optimisations that are not possible in other languages like C.
So be very carefull when thinking about using lowlevel data structures. It might result in a loss of performances (and more bugs and more headaches in memory management).
Using the STL and BOOST will probably help avoiding some mistakes.

A:
To understand what's going on at that level, you need to learn about concepts such as caches, processor pipeline, TLB, branch prediction, and so on.

I would like to discuss these further in a very casual manner.

*

*Cache - Basically, if you can try to fit your work set inside of cache, your application can see enormous speed gains.

*Branches - Branches take a VERY long time because they require a block on a memory read. For instance, x=1 can be faster than if (needWrite) x=1; even if you end up doing unnecessary writes.

*branch prediction - Because of the previous, the CPU attempts to try to 'guess' what the result of a branch is using pattern matching algorithms. Making this trival to guess can give you speed gains.

*As far as processor pipelines, Instruction Level Parallelism, superscalars, register renaming and others - These mostly have to be optimized by the compiler, I think.


text:
Q: Where does android camera determine immediate preview frame? I am trying to ensure that the preview frame which is displayed briefly after snapping a picture in Camera corresponds closely to the captured image.  There is a bit of delay between the preview image and the captured image, and when capturing subjects in motion, that's a problem.
In the Camera code are these comments:
// If postview callback has arrived, the captured image is displayed
// in postview callback. If not, the captured image is displayed in
// raw picture callback.

But I don't see it.  I see that at the end of capture(), mPreviewing is set to false, and the JpegPictureCallback resumes previewing after a little bit.  This suggests to me that the frozen image is the one from the moment mPreviewing is switched off - I don't see any code that would replace that image with anything fresher.  Are the comments correct?  If so, where is the image updated?


text:
Q: Build Docker image in privileged mode How to build a Docker image with privileged capabilities, like when running docker run -ti --privileged?
So I can mount a device while building my Dockerfile without getting an automount error?

A: It's not possible to build Docker images in a privileged mode as you do when you run a container. [1]
root is already the default user when building or running your Docker container, although as you pointed out, some commands will fail, like mount a partition for example. [2] [3]


text:
Q: How to extract some row in vertical condition in pandas dataframe Now I have dataframe below
    A B C
1   a 0 6
1   b 1 5
1   c 0 8
1   d 0 9
2   e 0 1
2   f 1 2
2   g 0 3
3   h 0 4
3   i 0 5
3   j 0 6

first, I would like to extract df.B==1
   A B C
1  b 1 5
2  f 1 2

second,I would like to extract the row around the number of Column C (+ -1, in this case the row c 0 8 is next to b 1 5,but the number of df.C=8 so this column would be dropped.If df.C=4or6 this row will be added) It does not matter whether they are next to each other or not.
  A B C
1 a 0 6
1 b 1 5
2 e 0 1
2 f 1 2
2 g 0 3

I want to get the dataframe above. How can I do this?
First I tried
df[df.B==1]

But,I couldn't figure out next step..

A: # find where `B` is one
bs = np.where(df.B.values == 1)[0]

# union `bs` with + 1 and - 1
idx = np.unique(np.concatenate([bs - 1, bs, bs + 1]))

# don't go below zero or above last row
idx = idx[(0 <= idx) & (idx < len(df))]

# use `iloc` to index correct rows
df.iloc[idx]

   A  B  C
1  a  0  6
1  b  1  5
1  c  0  8
2  e  0  1
2  f  1  2
2  g  0  3

A: okay its a bit confusing (specially because u changed the numbers from first example to second to third) but from what i understood you want to get all rows with:
B==1

and from those rows, you want to get the rows with equal index value and C+-1 from the C of the one with B==1 (please correct me if i got that wrong)
I would do that the following way:
being df = your original dataframe
DF = pd.DataFrame([], columns=['A','B','C'])

index_list = []

for i in np.arange(len(df)):

    ref_index = df.index[i]

    if df.iloc[i]['B'] == 1:

        DF.loc[len(DF)] = df.iloc[i]
        index_list.append(df.index[i])

    if df.iloc[i]['B'] == 0:

        try:

            ref_C = df[df['B']==1].loc[ df.index[i]]['C']

        except:

            ref_C = np.nan

        if ((df.iloc[i]['C'] == ref_C + 1)|(df.iloc[i]['C'] == ref_C - 1)):

        DF.loc[len(DF)] = df.iloc[i]
        index_list.append(df.index[i])

DF.index = index_list

hope that is it, if it helps upvote/check answer, peace mate!


text:
Q: Possible performance issues implementing multi-tenant database? I would like to design and develop school application using PHP and MYSQL as backend. The frontend - a combination of HTML, JS and CSS - has a registration form for every school.
Every school has its own students, classes, teachers and the like.
I would like to use a single database with one students table having a client column that refers to the owner of every record.
e'g: sutd_id, client_id, first_name, last_name......
e'g: class_id, client_id, description, blahblah....
Question 1
Will a WHERE clause with too many parameters  affect performance? I mean thinks like WHERE id='blah' AND class_ID='blah' AND client_id='blah' AND enroll_date between 'time' AND 'AGO'.
If the case that affects performance, I've thought of creating views for every new client, example: When new successful registration takes place, I will create some extra views to the database by using new client's unique name.
e'g: new client which is abc is registered than automatically i will create these views: (abc_students, abc_classes....)
Question 2
Would this approach (the one with the views) affect the performance or accuracy of results?
Question 3
Is there another way to increase the performance, other that creating views?

A: Views will not help with performance; they are effectively just queries with a Name.  Indeed, they may actually make things worse and, IIRC, MySQL does suffer from this "View overhead".
Indexes are what you're looking for.
Sensible indexing can make millions of rows just as responsive as a handful of them.
Don't get carried away, though.  Whilst well-chosen indexes will speed up selects, they need to be amended by every insert and delete (and, possibly, update) so the more of them that you have, the slower your update traffic might become.
Indexing, like most things database-y, is a "balancing act".  You need to try things out and see what's "best" for your needs.

A: If you want to partition the data by school/client, you'll probably want to look at schemas instead of views. A schema will put the tables (and indexes, triggers, etc) in a separate namespace. Depending on the database you use, you may be able to put individual schemas in separate files, which should give you the ability to put individual schools/clients on separate drives if one or more of them grows large enough to require that. Note, however, that while you can use the same data model in your application for all schemas, if you change a table definition you will have to change the table in each schema individually.


text:
Q: Is malloc thread-safe? Is the malloc() function re-entrant?

A: Here is an excerpt from malloc.c of glibc :
Thread-safety: thread-safe unless NO_THREADS is defined
assuming NO_THREADS is not defined by default, malloc is thread safe at least on linux.

A: If you are working with GLIBC, the answer is: Yes, BUT.
Specifically, yes, BUT, please, please be aware that while malloc and free are thread-safe, the debugging functions are not.
Specifically, the extremely useful mtrace(), mcheck(), and mprobe() functions are not thread-safe.  In one of the shortest, straightest answers you will ever see from a GNU project, this is explained here:
https://sourceware.org/bugzilla/show_bug.cgi?id=9939
You will need to consider alternate techniques, such as ElectricFence, valgrind, dmalloc, etc.
So, if you mean, "are the malloc() and free() functions threadsafe", the answer is yes.  But if you mean, "is the entire malloc/free suite threadsafe", the answer is NO.

A: Short answer: yes, as of C11, which is the first version of the C standard that includes the concept of threads, malloc and friends are required to be thread-safe.  Many operating systems that included both threads and a C runtime made this guarantee long before the C standard did, but I'm not prepared to swear to all.  However, malloc and friends are not and never have been required to be reentrant.
That means, it is safe to call malloc and free from multiple threads simultaneously and not worry about locking, as long as you aren't breaking any of the other rules of memory allocation (e.g. call free once and only once on each pointer returned by malloc).  But it is not safe to call these functions from a signal handler that might have interrupted a call to malloc or free in the thread handling the signal.  Sometimes, using functionality beyond ISO C, you can guarantee that the thread handling the signal did not interrupt a call to malloc or free, e.g. with sigprocmask and sigpause, but try not to do that unless you have no other option, because it's hard to get perfectly right.

Long answer with citations: The C standard added a concept of threads in the 2011 revision (link is to document N1570, which is the closest approximation to the official text of the 2011 standard that is publicly available at no charge).  In that revision, section 7.1.4 paragraph 5 states:

Unless explicitly stated otherwise in the detailed descriptions that follow, library functions shall prevent data races as follows: A library function shall not directly or indirectly access objects accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function's arguments. A library function shall not directly or indirectly modify objects accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function's non-const arguments. Implementations may share their own internal objects between threads if the objects are not visible to users and are protected against data races.
[footnote: This means, for example, that an implementation is not permitted to use a static object for internal purposes without synchronization because it could cause a data race even in programs that do not explicitly share objects between threads. Similarly, an implementation of memcpy is not permitted to copy bytes beyond the specified length of the destination object and then restore the original values because it could cause a data race if the program shared those bytes between threads.]

As I understand it, this is a long-winded way of saying that the library functions defined by the C standard are required to be thread-safe (in the usual sense: you can call them from multiple threads simultaneously, without doing any locking yourself, as long as they don't end up clashing on the data passed as arguments) unless the documentation for a specific function specifically says it isn't.
Then, 7.22.3p2 confirms that malloc, calloc, realloc, aligned_alloc, and free in particular are thread-safe:

For purposes of determining the existence of a data race, memory allocation functions behave as though they accessed only memory locations accessible through their arguments and not other static duration storage. These functions may, however, visibly modify the storage that they allocate or deallocate. A call to free or realloc that deallocates a region p of memory synchronizes with any allocation call that allocates all or part of the region p. This synchronization occurs after any access of p by the deallocating function, and before any such access by the allocating function.

Contrast what it says about strtok, which is not and never has been thread-safe, in 7.24.5.8p6:

The strtok function is not required to avoid data races with other calls to the strtok function.
[footnote: The strtok_s function can be used instead to avoid data races.]

(comment on the footnote: don't use strtok_s, use strsep.)
Older versions of the C standard said nothing whatsoever about thread safety.  However, they did say something about reentrancy, because signals have always been part of the C standard.  And this is what they said, going back to the original 1989 ANSI C standard (this document has nigh-identical wording to, but very different section numbering from, the ISO C standard that came out the following year):

If [a] signal occurs other than as the result of calling the abort
or raise function, the behavior is undefined if the signal handler
calls any function in the standard library other than the signal
function itself or refers to any object with static storage duration
other than by assigning a value to a static storage duration variable
of type volatile sig_atomic_t .  Furthermore, if such a call to the
signal function results in a SIG_ERR return, the value of errno is
indeterminate.

Which is a long-winded way of saying that C library functions are not required to be reentrant as a general rule.  Very similar wording still appears in C11, 7.14.1.1p5:

If [a] signal occurs other than as the result of calling the abort or raise function, the behavior is undefined if the signal handler refers to any object with static or thread storage duration that is not a lock-free atomic object other than by assigning a value to an object declared as volatile sig_atomic_t, or the signal handler calls any function in the standard library other than the abort function, the _Exit function, the quick_exit function, or the signal function with the first argument equal to the signal number corresponding to the signal that caused the invocation of the handler. Furthermore, if such a call to the signal function results in a SIG_ERR return, the value of errno is indeterminate.
[footnote: If any signal is generated by an asynchronous signal handler, the behavior is undefined.]

POSIX requires a much longer, but still short compared to the overall size of the C library, list of functions to be safely callable from an "asynchronous signal handler", and also defines in more detail the circumstances under which a signal might "occur other than as the result of calling the abort or raise function."  If you're doing anything nontrivial with signals, you are probably writing code intended to be run on an OS with the Unix nature (as opposed to Windows, MVS, or something embedded that probably doesn't have a complete hosted implementation of C in the first place), and you should familiarize yourself with the POSIX requirements for them, as well as the ISO C requirements.

A: I read somewhere that if you compile with -pthread, malloc becomes thread safe. I´m pretty sure its implementation dependant though, since malloc is ANSI C and threads are not.
If we are talking gcc:

Compile and link with -pthread and
  malloc() will be thread-safe, on x86
  and AMD64.

http://groups.google.com/group/comp.lang.c.moderated/browse_thread/thread/2431a99b9bdcef11/ea800579e40f7fa4
Another opinion, more insightful

{malloc, calloc, realloc, free,
  posix_memalign} of glibc-2.2+ are
  thread safe

http://linux.derkeiler.com/Newsgroups/comp.os.linux.development.apps/2005-07/0323.html

A: I suggest reading

§31.1 Thread Safety (and Reentrancy Revisited)

of the book The Linux Programming Interface, it explains the difference between thread safety and reentrancy, as well as malloc.
Excerpt:

A function is said to be thread-safe if it can safely be invoked by
  multiple threads at the same time; put conversely, if a function is
  not thread-safe, then we can't call it from one thread while it is
  being executed in another thread.
....
   This function illustrates the typical reason that a function is not
  thread-safe: it employs global or static variables that are shared by all threads.
...
  Although the use of critical sections to implement thread safety is a significant
  improvement over the use of per-function mutexes, it is still somewhat inefficient
  because there is a cost to locking and unlocking a mutex. A reentrant function
  achieves thread safety without the use of mutexes. It does this by avoiding the use
  of global and static variables.
...
  However, not all functions can
  be made reentrant. The usual reasons are the following:

*

*By their nature, some functions must access global data structures. The functions in the malloc library provide a good example. These functions maintain a
  global linked list of free blocks on the heap. The functions of the malloc library
  are made thread-safe through the use of mutexes.

  ....

Definitely worth a read.
And to answer your question, malloc is thread safe but not reentrant.

A: This is quite old question and I want to bring freshness according current state of things.
Yes, currently malloc() is thread-safe.
From the GNU C Library Reference Manual of glibc-2.20 [released 2014-09-07]:

void * malloc (size_t size)
Preliminary: MT-Safe | ...
...
  1.2.2.1 POSIX Safety Concepts:
... MT-Safe or Thread-Safe functions are safe to call in the presence
  of other threads. MT, in MT-Safe, stands for Multi Thread.
Being MT-Safe does not imply a function is atomic, nor that it uses
  any of the memory synchronization mechanisms POSIX exposes to users.
  It is even possible that calling MT-Safe functions in sequence does
  not yield an MT-Safe combination. For example, having a thread call
  two MT-Safe functions one right after the other does not guarantee
  behavior equivalent to atomic execution of a combination of both
  functions, since concurrent calls in other threads may interfere in a
  destructive way.
Whole-program optimizations that could inline functions across library
  interfaces may expose unsafe reordering, and so performing inlining
  across the GNU C Library interface is not recommended. The documented
  MT-Safety status is not guaranteed underwhole-program optimization.
  However, functions defined in user-visible headers are designed to be
  safe for inlining.

A: Question: "is malloc reentrant"?
Answer: no, it is not. Here is one definition of what makes a routine reentrant.
None of the common versions of malloc allow you to re-enter it (e.g. from a signal handler). Note that a reentrant routine may not use locks, and almost all malloc versions in existence do use locks (which makes them thread-safe), or global/static variables (which makes them thread-unsafe and non-reentrant).
All the answers so far answer "is malloc thread-safe?", which is an entirely different question. To that question the answer is it depends on your runtime library, and possibly on the compiler flags you use. On any modern UNIX, you'll get a thread-safe malloc by default. On Windows, use /MT, /MTd, /MD or /MDd flags to get thread-safe runtime library.

A: Yes, under POSIX.1-2008 malloc is thread-safe.

2.9.1 Thread-Safety
All functions defined by this volume of POSIX.1-2008 shall be thread-safe, except that the following functions1 need not be thread-safe.
[ a list of functions that does not contain malloc ]

A: It depends on which implementation of the C runtime library you're using. If you're using MSVC for example then there's a compiler option which lets you specify which version of the library you want to build with (i.e. a run-time library that supports multi-threading by being tread-safe, or not).

A: No, it is not thread-safe. There may actually be a malloc_lock() and malloc_unlock() function available in your C library. I know that these exist for the Newlib library. I had to use this to implement a mutex for my processor, which is multi-threaded in hardware.

A: malloc and free are not reentrant, because they use a static data structure which records what memory blocks are free. As a result, no library functions that allocate or free memory are reentrant.

A: No, it is not.
Web archive link (original has gone dead)


text:
Q: Four particles are situated at the corners of a square of side 'a' and move at a constant speed v.
Each particle maintains a direction towards the particle at the next corner. Time when particles will meet each other will be $\frac{2a}{\sqrt n v}$. Find the value of n

MY SOLUTION
The particles at adjacent corners will move with speed Vi and Vj. Therefore, relative velocity of first particle wrt second will be
$$V_r=\sqrt{V^2+V^2}$$
$$=\sqrt 2 V$$
Distance to be covered is 'a'
Time=$$\frac{a}{\sqrt 2 V}$$
Equating this with the original given expression
$$\frac{a}{\sqrt 2 v}=\frac{2a}{\sqrt n V}$$$$n=8$$
Answer given is 4, what have I don't wrong?

A: Consider what has happened after a small interval of time, $\delta t$. The first particle will have travelled a distance of $v \delta t$ towards the second particle whereas the second particle has travelled
a distance of $v \delta t$ perpendicular to the line joining them.
The distance between them is the hypotenuse of a right-angled triangle with the other sides having lengths $a-v \delta t$ and $v \delta t$. Ignoring distances as small as $ (\delta t)^2$,  the distance between the two particles is just $a-v \delta t$.
Therefore the distance between two particles will have decreased by $v \delta t$. This will be the same throughout the motion and so the particles will meet when $a=vt$, i.e. after time $\frac {a}{v}$.
In your solution, the relative velocity should just be $v$ along the line joining the particles since the second particle is moving at right angles to the first at every instant.


text:
Q: prove that $g$ is a function of $(x_1-x_2,x_2-x_3,\dots,x_{n-1}-x_n)$ $g$ is a function of $(x_1-x_2,x_2-x_3,\dots,x_{n-1}-x_n)$ iff $$g(x_1+a,x_2+a,\dots,x_n+a)=g(x_1,x_2,\dots,x_n)\forall a \in \mathbb R$$
Trial: Only if part : Consider $g$ is a function of $(x_1-x_2,x_2-x_3,\dots,x_{n-1}-x_n)$
i.e. $g(x_1,x_2,\dots,x_n)=f(x_1-x_2,x_2-x_3,\dots,x_{n-1}-x_n)$.
So, we have
\begin{align}
g(x_1+a,x_2+a,\dots,x_n+a) &= f(x_1+a-x_2-a,x_2+a-x_3-a,\dots,x_{n-1}+a-x_n-a)\\&=f(x_1-x_2,x_2-x_3,\dots,x_{n-1}-x_n)\\&=g(x_1,x_2,\dots,x_n)
\end{align}
Help me to prove the if part. Thanks in advance

A: Suppose $g(x_1, ..., x_n) = g(x_1 + a, ..., x_n + a)$ for all $a \in \mathbb{R}$ (1).
Then define $f(y_1, ..., y_{n-1}) := g(y_1 + ... + y_{n-1}, y_2 + ... + y_{n-1}, ..., y_{n-1}, 0)$
Then $f(x_1 - x_2, ..., x_{n-1} - x_n) = g(x_1 - x_n, x_2 - x_n, ..., x_{n-1} - x_n, x_n - x_n) = g(x_1, x_2, .., x_{n-1}, x_n)$
(the last equality taking $a = x_n$ in (1))


text:
Q: Does $ f(pq)\times f((1-p)(1-q))=f(p(1-q))\times f(q(1-p))$ imply $f(pq)=f(p)\times f(q)$ over $[0,1]$? Let $f(x)$ be a non-negative Lebesgue measurable (or continuous, or differentiable, or strictly monotone, as needed) function defined on $[0,1]$.
Condition A: $f(x)$ satisfies
$$ f(pq)\times f((1-p)(1-q))=f(p(1-q))\times f(q(1-p))$$ for all $p,q\in [0,1]$.
Condition B: $f(x)$ satisfies
$$ f(pq)=k \times f(p)\times f(q)$$ where $k$ is a constant, for all $p,q\in [0,1]$.
Condition B obviously implies Condition A.
Question: Does Condition A imply Condition B?

A: No: $f(x)=2x$ satisfies Condition A but not Condition B.
Condition A is a homogeneous identity (both sides are the product of the same number of $f$-values), while Condition B is a non-homogeneous identity (the two sides are products of different numbers of $f$-values). Therefore even if one function $f$ satisfies both conditions, then any nontrivial multiple of $f$ will still satisfy Condition A but will no longer satisfy Condition B.
Edited to add: $f(x)=x^2$ also satisfies Condition A but not the new Condition B when $k\ne0,1$. Homogeneity also means that we can raise a solution to a power and get a new solution.


text:
Q: Microsoft Office Interop Assembly references I have an application developed in Visual Studio 2005 which I am deploying using ClickOnce. My solution contains two projects - a user interface layer coded in VB, and a class library coded in C#.  My C# class library has some code that uses the Outlook and Excel Interop Assemblies (Microsoft.Office.Interop.Outlook and Microsoft.Office.Interop.Excel, both version 11). Here are my questions.

*

*Although I haven't found where this is stated as an absolute, my understanding is that you MUST have the appropriate versions of the Office applications (Outlook/Excel) in order to install an application that uses the Interop assemblies. Is this correct?

If (1. = Yes) Then
How would you handle the situation in which your application uses the Interop assemblies for only a couple of features that will be utilized by only a select few of the total user base? Why must I require every user of my application to install Microsoft Office if only some users will need to use those features? These Interop assemblies are just .dll files, so what makes them so different from others in that you can't just publish the file with your project and have that satisfy the reference regardless of what software is installed at the client? (Clearly I have a poor understanding of the GAC and it's effect on Visual Studio's behavior.) I would be happy to write my own code to check for the existence of the required Office software for the few features that use them. No Office, no access to feature...
Else
If my understanding on this is incorrect, then HOW do I setup my references and ClickOnce settings so that users don't encounter the following error upon installation attempt?
"Unable to install or run the application. The application requires that assembly office Version 11.0.0.0 be installed in the Global Assembly Cache (GAC) first.
Please Contact your system administrator."

*

*I have tried setting my Interop references CopyLocal property to both True and False.

*In my ClickOnce Application Files list, I have tried setting these assemblies to Include, Exclude and Prerequisite.

*In my research I have seen where some people have these references pointing to *C:\WINDOWS\assembly\GAC*, mine points to *C:\Program Files\Microsoft Visual Studio 9.0\Visual Studio Tools for Office\PIA\Office11* but I haven't found a way to change the reference path.  According to http://msdn.microsoft.com/en-us/library/ez524kew(VS.80).aspx you CAN'T add references from the GAC, so how did other people manage it?

*I have tried copying the references from *C:\Program Files\Microsoft Visual Studio 9.0\Visual Studio Tools for Office\PIA\Office11* to my project directory and referencing them there.

End If
I suppose the main thing I need to know is how/if I can include these assemblies in my publication and satisfy or bypass the GAC requirement.
Where possible, please try to answer my specific questions as directly as possible. While articles are helpful, I have already read A LOT of articles and tried A LOT of suggested solutions and have found no success. Keep in mind my lack of understanding of the logistics of how this all works to begin with.
Forgive me for my lack of understanding, and thank you for any help you can offer. It is much appreciated!

A: You might like to have a look at the NetOffice project: http://netoffice.codeplex.com/.
It is a free (MIT License) and complete (all the versions 2000-2010 and all the Office apps) set of version-independent interop assemblies. The assemblies are generated from the actual PIAs with a tool, so they are correct, complete and up-to-date, and likely to be be updated quickly for future versions.
Another nice feature is that the IntelliSense for each member displays which Office versions implement that member.
For deployment, you can copy or install the assemblies with your app.

A: In my experience, trying to manage office interop assemblies in a broad deployment scenario is a nightmare.  If you are deploying via ClickOnce,  even if you get around the GAC issue you note above (perhaps by having your IT department push out a GAC registration of the interop assemblies, if this is a corporate environment), you will need to handle situations where users have a different version of Office than the standard -- and heaven help you when Office 13 comes out and users start to upgrade and it breaks your application.
In order to get around using the version-tied interop assemblies, it is possible to do office automation using pinvoke directly to the Office COM wrappers, which are version-independent (they pull the current office version on the client out of the registry).  This will have its own deployment challenges, though (you may need to update the registry to handle machines that have the PIAs installed, for example, which could be very challenging when using ClickOnce for deployment), and is a lot harder to develop against.
If I were in your shoes, I would start out by taking a long hard look at the interop functionality you are using in your class library -- is there another way to provide the functionality you need, outside of office interop on the client machine?  Perhaps a service-oriented solution where clients submit a request a server to generate a customized office doc and provide it for download...

A: Here is what I know from experience (I should point out that we did not use ClickOnce but I'm not sure why that would matter):
If you write to the Excel 2003 APIs and deploy to a machine with Excel 2007 it will work because Excel 2007 essentially impersonates Excel 2003. The problem is that some APIs have changed and their are a few which have even been removed. You'll have to try it yourself to see if your application is affected.
In fact, it's slightly worse than that. If you run your application on a machine with Excel 2003 and Excel 2007 installed, your use of Interop will still use Excel 2007.
One possibility is to use SpreadsheetGear for .NET which gives you an Excel compatible Windows Forms control implemented entirely in one .NET assembly which you can deploy with your application - so your application will not depend on Office.
You can download a free trial here if you want to try it out.
Disclaimer: I own SpreadsheetGear LLC

A: The best way is to use late binding library
https://sourceforge.net/projects/exceldata/

*

*no nigthmare with iterops and tlbs with different office versions

*support of various offices

*easy to make modificate

However:

*

*its hard to support this library

A: Use the COM interface and late-binding. VB.NET has always supported late-binding. Just use Marshal.GetActiveObject() and set the type of your variable to Object. You can make a VB.NET object that does this and call it from C#.
With C# you get late-binding if you use the reflection API but it's pretty painful to write code using this. In C# 4 you can also get late binding via the dynamic type.
If you do this you don't need to distribute any Office assemblies and your code will work as long as the attributes on the objects in the Office API don't change.
Late binding code is slower than early binding code but for many purposes this is not a problem.


text:
Q: Rails NoMethodError in Classified#show I'm following along with a book called Rails Solutions: Rails Made Easy, its written for rails 2 but I'm using rails 3 which is making things very interesting and making me learn a lot which is good, but I'm stuck with the above problem. I've read around on Stack and other websites I think it could be a routes issue but the book so far hasn't mentioned anything about routes.
routes.rb
List::Application.routes.draw do
  match ':controller(/:action(/:id))(.:format)'
end

app/views/classified/show.html.erb

    Title:  <%= @classified.title %>

app/controllers/classified_controller.rb
class ClassifiedController < ApplicationController
  def list
    @classifieds = Classified.find(:all)
  end
  def show
     @classifieds = Classified.find(params[:id])
  end
   def new
@classified = Classified.new
  end
  def create
    @classified = Classified.new(params[:classified])
    if @classified.save
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end
  def edit

  end
  def update

  end
  def delete

  end
end

NoMethodError in Classified#show
Showing /home/mark/Documents/RoR/list/app/views/classified/show.html.erb where line #3 raised:
undefined method `title' for nil:NilClass
Extracted source (around line #3):
1:
2:
3:     Title:  <%= @classified.title %>
4:

A: In your controller you used @classifieds but in your view you use @classified. Change one to match the other.


text:
Q: How to change default flask logger output to an json logging handler i need to change flask default logging handler to a custom JSON logging text, i can change handler before app.run() but flask set a default handler when I don't a standard handler (clear() logging handlers)

A: Just stumbled over a very convenient way to solve this challenge.
Go for json-logging package (https://github.com/bobbui/json-logging-python)
With that package installed, it's as easy as that:
import datetime, logging, sys, json_logging, flask

app = flask.Flask(__name__)
json_logging.init_flask(enable_json=True)
json_logging.init_request_instrument(app)

And proceed as usual in your Flask app.

A: import logging
from pythonjsonlogger.jsonlogger import JsonFormatter

def get_logger(module_name):
    """Generate a logger."""
    logger = logging.getLogger(module_name)
    # logger.setLevel(logging.CRITICAL)
    logger.setLevel(logging.DEBUG)
    logger.propagate = False    # reset handler to avoid duplicates
    logger.handlers = [get_json_handler()]
    return logger

def get_json_handler():
    """Generate a JsonFormatter"""
    formatter = JsonFormatter("(asctime) (levelname) (module) (funcName) (lineno) (message)")
    log_handler = logging.StreamHandler()
    log_handler.setFormatter(formatter)
    return log_handler

# Example:
log = get_logger()

flask_log = logging.getLogger('werkzeug')
flask_log.setLevel(logging.DEBUG)
flask_log.addHandler(log)


text:
Q: How to close a database used within a ContentProvider in Android I'm loading the contents of a database into a GridView using a CursorLoader and a ContentProvider.
The application is working but in the log is written several times "close() was never explicitly called on database.
I found some topics about this issue and the response to "close database in ContentProvider is": "A content provider is created when its hosting process is created, and remains around for as long as the process does, so there is no need to close the database".
So, whats going wrong?
As the database is opened within the ContentProvider, if I close it the cursor returned will be empty, how I resolve this issue?

A: That message is printed when the db is garbage collected before being closed.  There is a lot of discussion about the issue here:
Closing the database in a ContentProvider
tl;dr: don't worry about it.  It is, in general, actually counter-productive to close the db.  Close your transactions and your cursors and let android manage the DB.
BTW, take care opening the DB in onCreate.  If you open your DB using a SQLiteDatabaseHelper, the onUpdate method might be called.  There isn't too much that could be worse than having your program killed by an ANR, in the middle of updating the DB.


text:
Q: Enable HTTP context in WCF service i added
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

but it's giving me an error"
The service cannot be activated because it requires ASP.NET compatibility. ASP.NET compatibility is not enabled for this application

it seems like the WCF service has no HTTP context related to it? please help

A: It has check out the following link
http://msdn.microsoft.com/en-us/library/aa702682.aspx
and make sure you have added this tag in your web config


text:
Q: How can I save table data ex: Min,max,avg,90%,throughput,etc How can I save table data(ex: min, max,avg,90%, throughput,etc..) for an aggregate report or summary report while running through command prompt in JMeter.

A: You need to add a csv/jtl/xml file in your Summary Report or Aggregate Report.

Save your Jmeter script and execute it through cmd. Your results will be saved in the .csv file.
You can follow this Save Response Data in JMeter

A: If you want a text representation of the table data of the Aggregate Report listener you can use JMeterPluginsCMD Command Line Graph Plotting Tool, the relevant command would be something like:
JMeterPluginsCMD.bat --generate-csv aggregatereport.csv --input-jtl /path/to/your/test/result.jtl --plugin-type AggregateReport

You can install JMeter Plugins Command Line Tool using JMeter Plugins Manager


text:
Q: Showing Bayes Estimator is Consistent $X_1, X_2, ... , X_n$ are iid $N(0, \theta)$ random variables with $\theta$ in $(0, \infty)$. With the prior distribution $\pi(\theta)$=$\frac{4e^\frac{-2}{\theta}}{\theta^3}$, I calculated the posterior distribution and used the squared error loss function to obtain the Bayes estimator for $\theta$ (the mean of the posterior distribution). I found the Bayes estimator to be $\frac{4 + \sum x_i^2}{n+2}$.  How do I show that this estimator is consistent?
I know showing the estimator is consistent has something to do with showing convergence in probability, however, I am completely lost on where to start.

A: You generally use the law of large numbers(https://en.wikipedia.org/wiki/Law_of_large_numbers) to prove consistency. The LLN
gives convergence in probability, and if you can use it to show convergence in
probability to what you want ($\theta$ here) then you're basically done.
Here, as $X_i \sim \mathcal{N}(0,\theta)$ are all iid the law of large numbers will apply. In particular, it tells you
$$
\frac{1}{n}\sum_{i=1}^{n} X_i \overset{P}{\rightarrow} \mathbb{E}(X)=0,
$$
and also
$$
\frac{1}{n}\sum_{i=1}^{n} X_i^2 \overset{P}{\rightarrow} \mathbb{E}(X^2)=\theta.
$$
This is almost exactly what you want. You just need to take care of the other terms in the Bayes estimator as $n\rightarrow \infty$.


text:
Q: R{ff}- use apply in ffdf I'm interested on using apply on a ffdf. I think I can't use ffdfdply because I'm not interested on splitting columns, because I have to use all components of the row, formed by 4 components("identifier1" "identifier2" "value" and "condition"), to fill 2 matrix depending on a condition.
As this prior thread proposes (How to use apply or sapply or lapply with ffdf?) I've tried this:
apply(physical(myffdf),1,function(x){

  if( x["condition"]=="A"){
        matrix1[x["indentifier1"],x["identifier2"]] <<- x["value"]
  } ifelse( x["condition"]=="B") {
        matrix1[x["indentifier1"],x["identifier2"]] <<- x["value"]

  }
})

but I've read that physical() returns a list with atomic ff objects, so logically I can't use apply.
Any suggestion?

A: It seems, you want to apply a function over the rows. You can use chunk for that. Get you chunk in RAM and use apply and store it where you want (in RAM or in ff).
require(ff)
ffiris <- as.ffdf(iris)
for(i in chunk(ffiris)){
  x <- ffiris[i, ]
  apply(x, MARGIN=1, FUN=yourfunction)
}


text:
Q: NSURLConnection and connectionDidFinishLoading sharing between multiple functions This is a simplification, but I have an app that has the following methods:
//This is a common function that is used by various functions in my app to send a HTTP Post via NSURLConnection
- (void)sendPostWithURL:(NSString*)url

//This is the NSURLConnection function that has the response data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection

//myFunction1: send a HTTP Post and receive response1.json
-(void)myFunction1{
 [self sendPostWithURL:@"http://www.somesite.com/response1.json"];
 }

//myFunction2: send a HTTP Post and receive response2.json
-(void)myFunction2{
 [self sendPostWithURL:@"http://www.somesite.com/response2.json"];
}

So as you can see, I have two functions (myFunction1 and myFunction2) that share a common NSURLConnection for sending and receiving data.
In the connectionDidFinishLoading() function, how can I tell whether the response is for myFunction1 or myFunction2?
I have one possibility, such as requesting that within the json response data, there is one key/value pair that allows me to see which response it is.  However, I have a feeling that there is a more elegant way for me to do this within the code itself.
Any advice would be great!  Thank you!

A: You are calling them "functions".  If you start thinking of them as "methods" in a class, a lot of this will make more sense.
You need to encapsulate all of the NSURLConnection stuff in a class (called, say, Downloader.m).
Downloader.m will have methods: sendPostWithUrl and connectionDidFinishLoading.
Then, when you need to download something, instantiate a new instance of downloader, and call it's sendPost method.  You will have a specific class instance for each download operation and those should be easy enough to keep track of.


text:
Q: Generating random IV for AES in Java I'm implementing and AES encryption engine for PBE in android, and I've found two ways to implement the creation of the IV and I would like to know which one is better and more secure for getting IvParameterSpec:
Method #1:
SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
byte[] iv = new byte[cipher.getBlockSize()];
randomSecureRandom.nextBytes(iv);

IvParameterSpec ivParams = new IvParameterSpec(iv);

Method #2:
AlgorithmParameters params = cipher.getParameters();
byte[] iv2 = params.getParameterSpec(IvParameterSpec.class).getIV();

ivParams = new IvParameterSpec(iv2);

A: I'd use method #1, because the Java API specifies the following for the Cipher.init() API that just takes the encryption/decryption mode and key:

If this cipher instance needs any algorithm parameters or random values that the specified key can not provide, the underlying implementation of this cipher is supposed to generate the required parameters (using its provider or random values).

(emphasis mine).
So it is not clear what different providers will do when method 2 is chosen. Looking at the Android source code, it seems that at least some versions (including version 21?) will not create a random IV - the random IV creation seems commented out.
Method 1 is also more transparent and it is - in my opinion - easier on the eyes.

Note that it is generally better to use new SecureRandom() and let the system figure out which RNG is best. "SHA1PRNG" is not well defined, may differ across implementations and is known to have had implementation weaknesses, especially on Android.

So the end result should be something like:
SecureRandom randomSecureRandom = new SecureRandom();
byte[] iv = new byte[cipher.getBlockSize()];
randomSecureRandom.nextBytes(iv);
IvParameterSpec ivParams = new IvParameterSpec(iv);

Beware that GCM mode works best with a 12 byte IV instead of the 16 byte IV  - the block size of AES.


text:
Q: Nested square root recursion Let's assume you have the following numerical output pattern for a function
(function 0) = sqrt(6)

(function 1) = sqrt(6 + (2 * sqrt(7)))

(function 2) = sqrt(6 + (2 * sqrt(7 + (3 * sqrt(8)))))

etc...

In scheme I have the following recursive function to calculate this pattern
(define (function depth)
    (cond
        ((= depth 0) (sqrt 6))
        (else (+ (function (- depth 1)) (* (+ depth 1) (sqrt (+ depth 6)))))
        )
    )

I can't figure out how to write the else case so that the square root is nested. Can someone give me a suggestion?

A: The formula is a bit tricky to implement, but this should work using a named let (this is just for avoiding the creation of another procedure):
(define (function n)
  (let helper ((a 2))
    (if (= (- a 2) n)
        (sqrt (+ a 4))
        (sqrt (+ a 4 (* a (helper (+ a 1))))))))

If the named let bothers you, here's a completely equivalent solution, using a nested helper procedure:
(define (function n)
  (define (helper a)
    (if (= (- a 2) n)
        (sqrt (+ a 4))
        (sqrt (+ a 4 (* a (helper (+ a 1)))))))
  (helper 2))

If nested procedures are also a problem, then extract the helper as a completely independent procedure:
(define (helper a n)
  (if (= (- a 2) n)
      (sqrt (+ a 4))
      (sqrt (+ a 4 (* a (helper (+ a 1) n))))))

(define (function n)
  (helper 2 n))

Anyway, the results are as expected:
(function 0)
=> 2.449489742783178

(function 1)
=> 3.360283116365224

(function 2)
=> 3.724280930782559

A: Here's how I would implement it. Compared to @Oscar's version

*

*it covers erroneous input values of n (Oscar's solution will loop indefinitely for negative values)

*has no redundant expression

Code:
(define (function n)
  (if (negative? n)
      (error "n is negative")
      (let recur ((n n) (a 1))
        (if (= -1 n)
            0
            (* a (sqrt (+ a 5 (recur (sub1 n) (add1 a)))))))))

Testing:
> (for ((i (in-range 10))) (printf "~a ~a\n" i (function i)))
0 2.449489742783178
1 3.360283116365224
2 3.7242809307825593
3 3.8777446879222386
4 3.9447403174010236
5 3.9746786776817733
6 3.988278318778271
7 3.994530823306873
8 3.997431999017166
9 3.998787961199304

> (function -2)
n is negative


text:
Q: CustomSortOrder for Taxonomy Term (Sharepoint 2010) I'm trying to set a custom order for my term set "Cities" using the Term store management tool.
When the user creates a new content type which has the column "City", the cities from the term store are displayed in the correct order. But when I'm looking at the term store from code, the order is not correct at all. To get the term set I'm using this:
 TermCollection myTermCollection = term.Groups[taxonomyGroupName].TermSets[taxonomyListName].GetAllTerms();

The default order in the 'myTermCollection' is the creation order of the taxonomies. The order listed in the property "CustomSortOrder" is alphabeticall. None of them are the correct one set using the term store management tool.
I ran manually the Taxonomy Update Scheduler, and the job works fine since I saw taxonomy names being updated correctly after running this, but the order is still not right.
Any ideas are very much appreciated!

A: It was so simple!
In order to get the custom order, I was doing:
TermCollection myTermCollection = term.Groups[taxonomyGroupName].TermSets[taxonomyListName].GetAllTerms();
orderList = myTermCollection[0].CustomSortOrder;

Instead, I had to do
TermCollection myTermCollection = term.Groups[taxonomyGroupName].TermSets[taxonomyListName].GetAllTerms();
orderList = myTermCollection[0].TermSet.CustomSortOrder;

I'm not sure for what myTermCollection[0].CustomSortOrder stands for, but it's not what I need. What I need is myTermCollection[0].TermSet.CustomSortOrder.


text:
Q: Could not find schema information for the element 'setting' VS 2015 ASP.Net When building my web app, I get the following message (amongst 77 others, all similar, just for different elements in my web.config)
Could not find schema information for the element 'setting' VS 2015 ASP.Net

I have looked at the schema for the config,

looks Ok to me?
I have also other weird stuff going on, like When I add a new webpage, I get an HRESULT FAIL COM error. Ditto with trying to install NuGet packages.
This only started happening yesterday, on a large solution. I had reference errors after a merge, which I have now fixed. All projects target the same  .NET version (4.5).
I have no build errors and everything works, except my recent work - a page that uses partials (worked fine until yesterday!). My colleagues are beginning to doubt me!
Does anyone have any ideas?

A: Deleting the 'bin' folder, then rebuilding seems to have cleared the messages.


text:
Q: Calculate Grand Total from my total of Each Group in my SSRS Report
I want Grand Total of Each Group total as shown in image, but i dont want to repeat my grand total so i have placed it outside of my Group1. How to calculate Grand Total outside of my Group1.
My Report Structure is as Below -

In Quantity Field which is showing -86 , expression i wrote is as follows -
    =Last(SUM(Fields!BalanceQty.Value,"Group1"))
In the image - result of Quantity is -86 , but my required Output is 41 i.e. 26 + 16 + 30 -31 .
Any help would be appreciated.

A: So if I understand correctly, you want to sum the values shown in the cell directly above the grand total cell (in your design).
If that's the case then get the textbox name from the 'cell' you want to sum and then do
=SUM(ReportItems!myTextBoxName.Value)

A: dont you have on grouping "add totals after" or "add totals before" option. This will show you a grand total; plus and sub-totals for each category.


text:
Q: How to add an ad using document.getElementById()? I have a  with an id of "ad". I am trying to put in an adsense ad in there using JavaScript when a user meets a condition. Basically when a user meets a certain condition, ads will be shown.
This is my code:
if ($resultTot = $db->query($queryTot))
    {
        $data = $resultTot->fetch_assoc();

     if($data["total"]>1)
        {
                echo "";

     }
  }

When I use document.getElementId() to change let's say a p tag, it works. I just can't get the adsense to display. Any ideas on how I can add it in there and why my code isn't working?

A: You just need to print regular AdSense JS code. No need to get any elements with JS.
Currently you are just editing contents of #ad DOM element. This dosen't work, because it has to be

So, use this:
if ($resultTot = $db->query($queryTot))
{
  $data = $resultTot->fetch_assoc();

  if($data["total"]>1)
  {
    echo "

    ";
  }
}


text:
Q: MarkLogic Query By Example - underscore in JSON key not working? I have the following entry in MarkLogic in JSON format:
{
   "identifier":"user1",
   "attributesList": [
      {
        "firstName": "James",
        "address_1": "Farcity"
      }
   ]
 }

If, I'm going to query that using the below format:
{
 $query:
 {
   "identifier":"user1",
   "attributesList": [
      {
        "firstName": "James"
      }
   ]
 }
}

this will match and return back the expected result with a count of 1 because "firstName" is equal to "James".
However, if I do the following:
{
 $query:
 {
   "identifier":"user1",
   "attributesList": [
      {
        "address_1": "Farcity"
      }
   ]
 }
}

it will not give back any result even if "address_1" exactly matches which is "Farcity". I already tried this on other JSON key as well, it works fine with all except those with underscores in the key.. Is this a reserved character? If so, is there a way to escape this so that the key "address_1" or "county_state" can still be matched?

A: It looks like the Json object converts the underscores to a double underscore
running this:
xquery version "1.0-ml";

import module namespace json="http://marklogic.com/xdmp/json"
 at "/MarkLogic/json/json.xqy";

let $j :=
 '{
   "identifier":"user1",
   "attributesList": [
      {
        "firstName": "James",
        "address_1": "Farcity"
      }
   ]
}'
return
 json:transform-from-json( $j)

you will get this out put
<json type="object" xmlns="http://marklogic.com/xdmp/json/basic">
  <identifier type="string">user1</identifier>
  <attributesList type="array">
    <json type="object">
      <firstName type="string">James</firstName>
      <address__1 type="string">Farcity</address__1>
    </json>
  </attributesList>
</json>

So try querying with a double underscores. Also If you are using Marklogic 6 or 7 it converts the Json to xml. so you could just try to query by example using the XML format.

A: See http://docs.marklogic.com/xdmp:encode-for-NCName for the exact algorithm and function used to map JSON field names to QNames


text:
Q: Multiple returning Could anyone help me.
I need to return multiple img's, but with this code, only one of two is returning.
What is the solution.
Thank you in advance.
$test = "/claim/img/box.png, /claim/img/box.png";

function test($test)
{
            $photo = explode(',', $test);
            for ($i = 0; $i < count($photo); $i++)
                {

                    $returnas = "";
                    return $returnas;
                }

}

A: This might be a good opportunity to learn about array_map.
function test($test) {
    return implode("",array_map(function($img) {
        return "";
    },explode(",",$test)));
}

Many functions make writing code a lot simpler, and it's also faster because it uses lower-level code.

While we're on the subject of learning things, PHP 5.5 gives us generators. You could potentially use one here. For example:
function test($test) {
    $pieces = explode(",",$test);
    foreach($pieces as $img) {
        yield "";
    }
}

That yield is where the magic happens. This makes your function behave like a generator. You can then do this:
$images = test($test);
foreach($images as $image) echo $image;

Personally, I think this generator solution is a lot cleaner than the array_map one I gave earlier, which in turn is tidier than manually iterating.

A: Modify your code that way
function test($test)
{
    $returnas = '';
    $photo = explode(',', $test);
    for ($i = 0; $i < count($photo); $i++)
    {
        $returnas .= "";
    }
    return $returnas;
}

Your code didn't work since you were returning inside the loop immediatly. Every programming language support "only a return for call". In my solution you're appendig a string that has an img tag each time you enter the loop and return it after every photo is "passed" into the loop
You could even use the foreach() construct, of course
Bonus answer
If you don't know the difference between ...
for ($i = 0; $i < count($photo); $i++)
and
for ($i = 0, $count = count($photo); $i < $<; $i++)
Well, in first case you'll evaluate count($photo) every single time the for is called whereas the second time, it is evaluated only once.
This could be used for optimization porpuses (even if php, internally, stores the length of an array so it is accesible in O(1))

A: The function breaks after the first return statement. You need to save what you want to return in some structure, an array eg, and return this.
function test($test)
{
    $result = array();
    $photo = explode(',', $test);
    for ($i = 0; $i < count($photo); $i++)
    {
        $returnas = "";
        $result[] = $returnas;
    }
    return $result;
}


text:
Q: Running a python script on start-up/background in Ubuntu Linux - Failed to start service, Unit Not Found I wrote a python script and need this to be running 24/7. Haven't really done this before and I decided to use upstart in my Digital Ocean cloud running Ubuntu, and followed the below tutorial.
https://www.digitalocean.com/community/tutorials/the-upstart-event-system-what-it-is-and-how-to-use-it
Below is my conf file pdlb.conf located in /etc/init
description "A basic bot to get fixture information"
author "abcuser"

start on runlevel [2345]
exec python3 /home/abcuser/bot/pdlb.py >> /var/log/pdlb.log

I checked the syntax using init-checkconf and it showed syntaxOK
On running this (sudo service pdlb start), I got the following error and I don't know how to fix it. The pdlb.py file is in the correct location and log file isn't created yet.
Failed to start pdlb.service: Unit pdlb.service not found.

Do you have idea where I went wrong with this process? Any help will be appreciated, thanks.


text:
Q: How should I start Java-based web development? I have been using java as my main language for 3 years while developing college assignments, and now I plan to learn the web programming aspect of it. I see there are lots of different "stuff" going on such as JSP, JSF, Spring, etc.
Previous topics suggest that Head First Servlets and JSP is a good book to start with, but what do you think about that? After that, what route I should be following in order, at least to be able to write my own blog site app from scratch?

A: Use the first few lessons from the Spring step-by-step tutorial: http://static.springsource.org/docs/Spring-MVC-step-by-step/
Although the latter lessons are cover advanced Spring functionality the first couple of lessons are about setting up a simple, Tomcat-based web-app.

A: I would say:

*

*Install Java.

*Install Tomcat.

*Build a servlet, make it do stuff. Play with Requests and Responses. Get to grips with GET and POST requests, the HTTP protocol, why many web applications need RDBMSs, etc.

*If you get stuck on anything, use google, or this site to figure it out.

*Get your hands dirty!

*Get your hands dirty!

A: Be a bit careful.  Most solutions to doing web development have a tendency to be very large and hard to get around and learn.
I would suggest getting the basics right since you WILL eventually need to know them.  The Head First series are well written and a good start.
This will teach you JSP's and servlets which is what most of the frameworks build on top of.

A: I had the same question and read this thread and started with Head First. Have read 5 chapters but then I started to search for new resources and found Core Servlets and JavaServer Pages (JSP) from http://pdf.coreservlets.com/ and I think this book is much better in many ways.

*

*First of all it is not objected to an exam.

*Includes much more example with codes.

*There is many ways to implement a web application in Java. You can use just Servlets, just JSPs or combinations with/without beans etc. This book explains advantages and disadvantages of each very well.

*Explains MVC from scratch much better. (chapter 15)

*And it is free.

Update after almost seven years: I highly recommend to take a look at Spark Framework.

A: Just start with your project with the book of your choice by your side.
Lots of resources about good books can be found here on stackoverflow.
My advice is to start with making a page to communicate with the server, at least post some data and act depending on the response.
At the beginning stick with base scriplets, don't go straight to jsf tag libraries (or whatever else of that kind), understand what is a session, a request, a response and so on.

A: First it's important to understand the web languages, html, css, javascript. A good resource would be http://www.alistapart.com/
Then understand how http works, and how servlets are modeling http requests/response cycles. This is a good book: Head First Servlets and JSP.
Then try out the first java web framework that captures your attention. A good one is Spring Framework.
Good luck!

A: I kinda had a similar route, although not because I was in college, but because my career of many years involved standalone application development using Java, with no web component involved. Java-based web development basically seemed to pass me by, and I didn't find it easy when I tried to move into the mainstream.
Recognize first that web-based development is a pretty large field. From an employment point of view, opportunities tend to drift towards one or other subsections of the field in general. Roughly speaking, front-end and back-end development tend to be viewed as specific enough skills that you might be expected to have expertise in one versus the other, more so now that JavaScript is more central to frontend development.
And the surfeit of frameworks in Java makes it difficult for the newcomer to choose what to begin out with. There's just way too many JavaScript libraries, Web frameworks and application servers or frameworks. Even though your background is in Java, I'd still suggest you try out Rails or maybe Grails to get a better idea of the entire stack, as they have a more coherent story. In Java, there's dominant libraries for sure, but you'll still find your efforts to master them interrupted by constant comparisons to other competing frameworks or so. Or GWT and Wicket, being more based on the Java development style, may mean an easier transition to web technologies. Spring framework is also a good starting point as it has a more or less consistent story from the back- to the front-end, although it is still overwhelming.

A: Check  JavaPassion.com
It has an online course for java and other related technologies like ajax, jruby, webservices etc.  And the coverage is pretty decent.
Hope this will be beneficial to you.


text:
Q: Why is my dropzone javascript form not working? HELP!
I'm building the front end of a website and I'm using dropzone.js for image uploads. Now I've included the dropzone.min.js and the dropzone.css in the head and I asigned the dropzone class to the  tag i wanted to convert. Despite this the form field isn't made into a dropzone field. Dropping images on the field results in the browser just showing only the image like it would usually do. I use a lot of different jquery or javascript plug ins so maybe there's something causing a conflict?
Firebug console says: Uncaught Error: No URL provided.
If you guys could help me out on this one it would be great!
Thanks in advance
Here is the complete HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <link rel="stylesheet" media="screen" type="text/css" href="css/dropzone.css" />

    <link rel="stylesheet" media="screen" type="text/css" href="css/colorpicker.css" />

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

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

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

    <title>AppXelerator</title>

    Apps

Crawler

Builder

Publish

Finish

Pages

        <button class="md-trigger bluebutton" data-modal="modal-9">+ Add new page</button>

Home (locked)

Shop

Saved products

About us

Store locator

Home

                <button class="md-close">Remove page</button>

Content

Design

Header

            <form>

                     Background color:
                    <input id="colorpickerField1" class="input_color" value="#">

                     Button color:
                    <input  id="colorpickerField2" class="input_color" value="#"/>

                     Lettertype:
                    <select class="chosen-select input_text" tabindex="1" style="width:360px;" data-placeholder="Select font">
                    <option value=""></option>
                    <option value="Arial" class="font-arial">Arial</option>
                        <option value="Arial black" class="font-arial-black">Arial Black</option>
                    <option value="Comic sans" class="font-comicsans">Comic sans</option>
                    <option value="Courier new" class="font-courier">Courier new</option>
                    <option value="Georgia" class="font-georgia">Georgia</option>
                    <option value="Helvetica" class="font-helvetica">Helvetica</option>
                    <option value="Impact" class="font-impact">Impact</option>
                    <option value="Lucida" class="font-lucida">Lucida</option>
                    <option value="Palatino" class="font-palatino">Palatino</option>
                    <option value="Tahoma" class="font-tahoma">Tahoma</option>
                    <option value="Times new roman" class="font-times">Times New Roman</option>
                    <option value="Trebuchet" class="font-helvetica">Trebuchet</option>
                    <option value="Verdana" class="font-verdana">Verdana</option>
                    <option value="MS Sans serif" class="font-mssansserif">MS Sans serif</option>
                  </select>

                     Header logo:
                    <input class="input_image" value="Select image"/>

            </form>

Menu

            <form class="dropzone"></form>

        <button class="md-trigger bluebutton_radius4 phonepreview_positionfix" data-modal="modal-10">Set up phone view</button>

Add new page

Every page has it's own base functionality, please select the kind of page that you want to add to your app. Select a page and start customizing the design.

                Shop pagina
                Store locator
                Facebook
                Contact page
                Saved products
                About us
                <button class="md-close">Close</button>

Set up live phone view

Besides the preview in the browser we offer you the ability to view your app live on your smartphone while building it.
                    Follow the instructions below to link up your smartphone to AppXelerator.

1. Connect your smartphone to the same network as your computer

2. Download the AppXelerator app from AppStore for iOs devices or Google Play for Android.

3. Log in to the app with your provided username and password.

4. Enjoy your live app view!

                <button class="md-close">Close</button>

A: <form class="dropzone" id="myDropzone" action="url.php"> in HTML code (or even without specifying any id) is good. That said :
Url can be specified in javascript in options - Ways of doing it :
1)
if autodiscover is let to true (default)
Dropzone.options.myDropzone = { url : "url.php",...
With JS the id of the form must be declared in form : id="mydropzone" or #my-dropzoneHaving class="dropzone" is not enough.
Note : autodiscover must be declared just after  and before dom ready.
2)
if Dropzone.autoDiscover = false :
var myDropzone = new Dropzone("#myDropzone", { url: "url.php",... // JS : Dropzone class
or
$("#myDropzone").dropzone({ url: "url.php",... // JS : jquery style

Note : you can of course use another id, code will be Dropzone.options.myOtherId =... , $("#myOtherId").dropzone... etc.

warning :  jQuery document ready callback function and JQUERY 3 :
"Uncaught Error: No URL provided." can happen still happen in one condition (wich brought me here) :

Scenario 1 :
loading dropzone.js and jQuery 2 in
autodiscover let to true
then, in jQuery document ready : Dropzone.options.myDropzone = { url : "url.php",...
--> all is fine
Scenario 2 :
Switching to jQuery 3 without any other change : "Uncaught Error: No URL provided."
--> nothing work
It seems to be because of the new way jQuery handle doc ready :
https://jquery.com/upgrade-guide/3.0/#breaking-change-document-ready-handlers-are-now-asynchronous

Solution with jQuery 3 :
  1) let autodiscover to true and put ALL code OUTSIDE jQuery doc ready
  or
  2) set autodiscover to false BEFORE doc ready and declare options (url among others) via Javascript IN doc ready

INFOS :
https://github.com/enyo/dropzone/issues/1423

A: Even I faced the same problem. After some minutes of research, I found that we need to specify url for elements when not using form. But in your case you have used form tag for implementing dropzone, so it requires an action like..
<form action="some_target_url" class="dropzone"></form>

this worked for me..try this.
I found this in the website of dropzone.js in options table(scroll down)

A: Same problem - easy solution -> I did not specify dropzone URL in his configuration.
        $("#dZUpload").dropzone({
            url: "my-upload-url",
        });

A: <form action="files" class="dropzone">

        <input type="file" name="file" multiple />

</form>