text:
Q: Python one line if else with function def test(x):
  print("in test")
  if x >0:
    return 1
  else:
    None
def whennegative():
  return 6
myval =test(3) if test(3) else whennegative()

Is there anyway do this one-line if-else without execute test twice? thanks

A: What you're writing can be summarized as "Do test(3) if it works, and if it doesn't, then here's a fallback". Put another way, that can be summarized as "Do test(3), or else do the fallback".
myval = test(3) or whennegative()

If test(3) is truthy, it'll short circuit out. Otherwise, it'll evaluate whennegative().
There are people who will argue that this is too short and clever, and it can certainly be overused (if you ever see a = (b and c) or d then you've gone too far). But a single or in assignment to mean "here's a fallback" or a single and to mean "here's a point of failure" is pretty well understood by folks and is, indeed, more concise than the ternary alternative.


text:
Q: Enum: interfaces cannot declare types From one class, I'm trying to call an enum from another class.  According to some solution that I found on this site, I had to create the enum inside an interface and then create a property from the class.  That works perfectly for me, but when I try to compile the project, I receive the error message:  "enum_Name:  'interfaces cannot declare types'.
Here is the code for the interface:
public interface IEnums
{

public enum enum_SomeName
{
    firstenumname = 1,
    secondenumname = 2,
    thirdenumname = 3,
    forthenumname = 4,
    fifthenumname = 5
}

Here is the class the property:
  public class Whatever
 {
   public IEnums.SomeName wtf {get; set; }
 }

As I mentioned, I'm able to call the enum on the other class on 40 different methods, but I receive the error message on line:
    public enum enum_SomeName.

A: Either you misunderstood that advice or it was wrong. It is legal, but rare to put an enum declaration inside a class or struct declaration. It is not necessary and you should not do so without good reason. It is not legal to put an enum deck in an interface. Put it outside.

A: You're trying to define the enum WITHIN the interface.  You can't do that.
You can have the interface have a scalar value of the enum.
public interface IEmployee
{

  Enums.EmployeeStatusEnum EmpStatus {get;set;}
}

public enum EmployeeStatusEnum
{
    Unknown = 0,
    Hired= 1,
    Fired= 2
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kafka Spark Streaming json file with varying schema I have created a pipeline to consume streaming data from kafka topic which is in json format. But the problem is the jsons files with varying schema. so when I apply schema on the dataframe, it produces corrupted record.
How can I handle the varying schema in kafka streaming in Databricks using Pyspark

A: There are several approaches here, depending on what kind of schema variation is in your topic:

*

*if all schemas have the compatible data types (no columns with the same name but with different types), then you can just create a schema that is superset of all schemas, and apply that schema when performing from_json.

*if your schemas are incompatible, for example, you have fields that have the same name but different data types, then you can read data as text lines first, and then decode with different schemas depending on the row type - suppose that all JSONs have the type field with string type (not tested):
import pyspark.sql.functions as F
df = spark.readStream.format("kafka")....load().withColumn("value")\
  .withColumn("value", col("value").cast("string"))
df_typed = df.withColumn("jsn", F.from_json(F.col("value"), "type string"))\
  .select("value", "jsn.*")
df1 = df_typed.filter("type == some_value)\
  .withColumn("jsn", F.from_json(F.col("value"), schema1)).select("jsn.*")
# process df1


text:
Q: Linker error in recursive union Given an extrimely simplificated code (I don't know how to reduce it even more):
#include <type_traits>
#include <iostream>

#include <cstdlib>

#define PP { std::cout << __PRETTY_FUNCTION__ << std::endl; }

struct descriptor
{
    std::size_t const s;
    bool const * c;
    bool const * d;
};

template< descriptor const & x, bool c, bool d, typename ...types >
union U;

template< descriptor const & x, bool c, bool d >
union U< x, c, d >
{
    static_assert(c);
    static_assert(d);

    U() PP
    ~U() PP
};

template< descriptor const & x, bool c, bool d, typename first, typename ...rest >
union U< x, c, d, first, rest... > // specialize against c and/or d values
{
    static constexpr std::size_t s = x.s - sizeof...(rest);
    using tail = U< x, x.c[s], x.d[s], rest... >;

    first head_;
    tail tail_{};

    U() PP
    ~U() { PP; /*tail_.~tail();*/ } // !!!!!!!
};

template< typename ...types >
struct V
{
    static constexpr bool c[sizeof...(types) + 1] = {std::is_trivially_constructible< types >{}..., true};
    static constexpr bool d[sizeof...(types) + 1] = {std::is_trivially_destructible< types >{}..., true};
    static constexpr descriptor x{sizeof...(types), c, d};
    U< x, x.c[0], x.d[0], types... > storage_;

    V() PP
    ~V() PP
};

template< typename ...types >
constexpr bool V< types... >::c[sizeof...(types) + 1];
template< typename ...types >
constexpr bool V< types... >::d[sizeof...(types) + 1];
template< typename ...types >
constexpr descriptor V< types... >::x;

int
main()
{
    struct S { S() { ; } ~S() { ; } };
    V< int, S, double > v;
    (void)v;
    S s;
    (void)s;
    return EXIT_SUCCESS;
}

LIVE EXAMPLE
What it do is propagation of type traits through recursive union to use them somewhere in depth of recursion.
Currently the code gives linker error:
/tmp/main-ecd8fb.o: In function `main':
main.cpp:(.text+0x2fa): undefined reference to `_ZN1UIL_ZN1VIJiZ4mainE1SdEE1xEELb1ELb1EJEED1Ev'
main.cpp:(.text+0x318): undefined reference to `_ZN1UIL_ZN1VIJiZ4mainE1SdEE1xEELb1ELb1EJdEED1Ev'
main.cpp:(.text+0x336): undefined reference to `_ZN1UIL_ZN1VIJiZ4mainE1SdEE1xEELb0ELb0EJS1_dEED1Ev'
clang: error: linker command failed with exit code 1 (use -v to see invocation)

But if I uncomment the line marked by exclamation marks, then liker error ceased to exist. It strange, because doing so I begin to use more symbols, then previously. | c++filt -t cant demangle this symbols and I can't infer what is wrong. Is it clang (version 3.7.0) bug or ld (GNU ld v2.22) bug or something else? How to detect the source of such errors in general? Which tools do you use?


text:
Q: Bind a list of objects into a Grails command? I have 2 command objects, one of them contained List of other
@grails.validation.Validateable
class SongCommand {

    String title
    List<CoupletCommand> coupletCommandList = [].withLazyDefault {new CoupletCommand()}
    Boolean isChorusRepeat

    static constraints = {
        title blank: false, size: 1..129
        coupletCommandList validator: { couplets, obj ->
            def isValid = true
            couplets.each {
                isValid = isValid && it.validate()
            }
            return isValid
        }
    }
}
class CoupletCommand {

    Integer coupletPosition
    String coupletText
    Boolean isChorus

    static constraints = {
        coupletText blank: false, size:20..700
        isChorus nullable: true
    }
}

From front end to controller I passed something like this
[coupletText:2342342352342, coupletPosition:1, isChorus:false]
[coupletText:frfsdfsdf, coupletPosition:2, isChorus:true]
......
[coupletText:sd9f9s9df9, coupletPosition:n, isChorus:false]

when try save list of couplets on controller
def saveCouplets() {
        def songCommand = new SongCommand()
        // bad, but not necessary now
        def count = session['songId'] as Integer
        def bindingMap
        for (int i = 1; i <= count; i++) {
            bindingMap = [coupletText: params['coupletText-' + i],
                          coupletPosition: params['coupletPosition-' + i],
                          isChorus: (params['isChorus-' + i]) ? params['isChorus-' + i] : false]
            songCommand.coupletCommandList.add(bindingMap)
        }

        //Validate it
        //if valid
        if (songCommand.validate()) {
            coupletService.addCouplets(bindingMap, params)
        } else {
            render model: [command: songCommand]
        }
        //else render view show model [command: command]
    }

I receive error message

groovy.lang.MissingMethodException
  Message
  No signature of method: java.util.LinkedHashMap.validate() is applicable for argument types: () values: [] Possible solutions: wait(), values(), values()

A: CoupletCommand needs to implement Validateable or requires the annotation as well. Everything else seems to be fine


text:
Q: how to move a postgres schema via file operations? I have a schema schema1 in a postgres database A. I want to have a duplicate of this schema (model + data) in database B under the name schema2.
What are my options ?
I currently :
 * dump schema1 from database A
 * sed my way through schema renaming in the dump : schema1 becomes schema2
 * restore schema2 in database B
but I am looking for a more efficient procedure. For instance, via direct file operations on postgres binary files.
Thanks for your help
Jerome Wagner

A: First, be aware (as others have commented) that Postgresql and Mysql have different ideas on what is a SCHEMA. In Postgresql (and in the SQL standard) a schema is just a namespace inside a database, which you can use to qualify object names (analogous to directories and files; and there is a 'public' schema whichs is used as default for unqualified names). Schemas, then, are related to organization of names, not isolation: as long as we are inside a database, objects (tables, views...) from different schemas are mutually visible; so that, for example, a view can mix tables of different schemas, or a FK can refer to other schema. On the contrary, objects in different databases are isolated (they only share users and groups), you can't join tables of different databases.
A dump-restore is the only sane way I can think of, for copying a schema from one database to another. Even so, from the above, it might not be safe/possible if the schema depends on other schemas of the database (it's like you are copying the classes of a Java package from one project to another). I would not dream on attempting a copy of the binary files.


text:
Q: Why sinon.assert.match(actual, expected) would throw AssertError when both actual and expected are identical string values? I have mocha, chai and sinon Javascript testing framework and library are availabe on an application I inherited. I am new to all ^ of them and I've been reading their APIs to learn how to use them properly.
Here is Javascript object I want to validate. If expected name property is missing, validator would throw UsageError: name property is missing.
// person object
const person = { name: 'peter' }

// validate method of exported validator JS component
async validate(person) {
    const { name } = person;
    const promises = [];
    if (typeof name !== object) { throw new UsageError('name property is missing'); }
    ...
    else { promises.push(fooService(name)); }
    try {
        await Promise.all(promises);
    } catch (error) { throw (error); }
}

// unit test in sinon
describe('Validate person', async function() {
it('should throw error not find name property', async function() {
  const person = { 'foo': '1234 somewhere' };
 try {
  await validator.validate(person);
 } catch(error) {
  sinon.assert.match(error, 'name property is missing');
 }
});

This is async + await code so little I know sinon would be a fit then when I executed the unit test, I am even puzzled with following error msg:
AssertError: expected value to match
expected = UsageError: name property is missing
actual = UsageError: name property is missing

Both actual and expected come out same in string I think but I don't understand why I got AssertError. I'd appreciate if someone can explain to me what I am doing wrong and guide me the right way to implement this unit test. Ty!
[update]
My apology, I realized that I gave a wrong example within the sample test I have posted. I corrected it by having person object does not contain name property.

A: it is failed because the test compares the reference. The code creates new reference by using new statement e.g new UsageError.
An example:
let expect = require('chai').expect;

it('checks equality' ,function() {
  const actual = new Error('name property is missing');
  const expected = new Error('name property is missing');

  expect(actual).to.equal(expected);
})

The code above will give output
// output
AssertionError: expected [Error: name property is missing] to equal [Error: name property is missing]
      + expected - actual

The solution maybe you could compare the message by accessing message property
it('checks equality' ,function() {
  ...

  expect(actual.message).to.equal(expected.message);
})

Hope it helps


text:
Q: Add a new element with node childs in a XML file in c# I have a xml that is something like this:
<Servers>
  <MyNewServer>
    <Host>10.10.10.2</Host>
    <Port>12</Port>
    <User>MyUser</User>
    <Password>NkbgKnF9g96EYgxG3qRdCNY2KR6Xd5+0uqpY9KOCl4k=</Password>
  </MyNewServer>
</Servers>

I'm trying to add a new server below of "NyNewServer" label and add the same child elements in blank (Host, Port, User and Password).
I'm adding now a new element of server but is not with the correct format is displayed horizontal  instead of vertically, and I'm not sure how to add the child elements in blank.
Any idea? I have this:
public void XmlNewInterface(string Server)
{
    //Temporal Solution
    xmldoc.Load(XMLInterfacesFile);
    XmlElement record = xmldoc.CreateElement(Server);
    record.InnerText = Guid.NewGuid().ToString();
    xmldoc.DocumentElement.AppendChild(record);

    xmldoc.Save(XMLInterfacesFile);
}

Thanks

A: I prefer Linq to Xml, it simplifies building/constructing Xml. You just need these lines.
var doc = XDocument.load(inputfile);

doc.Descendants("Servers").First()
    .Add( new XElement("OneMoreServer",  new [] {
        new XElement("Host"),
        new XElement("Port"),
        new XElement("MyUser"),
        new XElement("Password")
    }));

Output
<Servers>
    <MyNewServer>
        <Host>10.10.10.2</Host>
        <Port>12</Port>
        <User>MyUser</User>
        <Password>NkbgKnF9g96EYgxG3qRdCNY2KR6Xd5+0uqpY9KOCl4k=</Password>
    </MyNewServer>
    <OneMoreServer>
        <Host />
        <Port />
        <MyUser />
        <Password />
    </OneMoreServer>
</Servers>

Working Demo


text:
Q: Reflect data quality in Kalman filter In a single stream of observations, I have some prior knowledge about the level of noiseness of the data that get feed into my Kalman filter. Some points are more noisy than the others.
To make use of this knowledge, I have two thoughts
(1) partition the data into two streams: low confidence and high confidence
(2) scale my confidence in data to a factor b/w 0 and 1, and multiply the kalman gain with this factor.
Can someone shed some light on this problem with some new thoughts or comment on my thoughts. Any comments would be appreciated.

A: Kalman filter in principle supports variable noisiness of data, so you are good. Just encode the noisiness info as a sequence of observational (co)variance matrices, $\mathbf{R}_k$ in wikipedia notation.
It might be that the implementation of the Kalman filter that you use does not support it, then either hack it (like I did with pykalman for myself), or find one that does.
Also, you will have to translate the "level of noiseness" to variance, which might involve some thinking if you get that level in some crazy form (like the binary form that you were contemplating, bad idea btw).


text:
Q: Give file link in place of absolute path in fs.createReadStream(); I've a code like this
const fileData = fs.createReadStream('Google Sheet Link');

The error I am getting is this.
This is probably due to fs trying to read from an absolute path, rather than directly from the URL.
The path, it is taking is "Directory to which file is located" + "Google sheet link"
I only want to open google sheet link in the createReaderStream Path.
I've hidden the google sheet path due to privacy reasons.

A: The createReadStream() method is an inbuilt application programming interface of fs module which allow you to open up a file/stream and read the data present in it.
fs.createReadStream( path, options )

Parameters: This method accept two parameters as mentioned above and described below:

*

*path: This parameter holds the path of the file where to read the file. It can be string, buffer or URL.

*options: It is an optional parameter that holds string or object.

Now, To avoid paths issues, it's recommended to use path.join, like:
const path = require('path');

const pathGoogleSheet = path.join(__dirname, 'Sheet name');
const readableStream = fs.createReadStream(pathGoogleSheet);

Here, you're creating a path to the google sheet referring to the current directory of the script stored in global variable called __dirname.


text:
Q: Using C Header in C++ Program I have a C header file which contains an enum
typedef enum {leaf, operator} my_type;

Now when I try to include this header in my C++ program I get error
"expected identifier before 'operator'"
How can I get rid of it.

A: Operator is a reserved word in C++. Name that part of your enum something else.

A: Perhaps a dirty trick like this might work?
#define operator operator_
extern "C" {
    #include "library.h"
}
#undef operator

Make sure that operator_ doesn't clash with anything in that header though.

A: Even if it's a third party library, you should be able to just change the header. It's not likely to break anything if you compiled the library with a C compiler beforehand.
If you don't wanna do that, you can write a wrapper, compile that with a C compiler and use the wrapper from C++ instead of using the library directly. Annoying, but the only way I can think of right now that's definitely going to work.
I'm not sure if this would work, but I suppose you could also try something like
#define operator OPERATOR
#include <thelibrary>
#undef operator

Normally the preprocessor doesn't care too much about what you do with it, but I'm not sure if this'll work considering operator is a keyword.


text:
Q: Is $(T,\omega) \mapsto \int_0^T f(t,\omega)\ dt$ measurable? Let $(\Omega, \mathcal{A}, P)$ be a probability space. Denote by $\mathcal{B}$ the Borel space on the real line and denote by $\mathcal{B}_{[0, \infty)}$ the Borel space on the interval $[0, \infty)$. Denote by $\mu$ the Lebesgue measure on $\mathcal{B}_{[0,\infty)}$.
Let $f:[0,\infty)\times\Omega\rightarrow\mathbb{R}$ be a $(\mathcal{B}_{[0,\infty)}\otimes\mathcal{A})/\mathcal{B}$-measurable function such that for every $T \in [0,\infty)$, $f\mathbb{1}_{[0, T]\times\Omega} \in L_1(\mu \otimes P)$. For every $T \in [0,\infty)$ define $X_T : \Omega \rightarrow \mathbb{R}$ as follows:
$$
X_T(\omega) := \int_0^T f(t, \omega)\ dt
$$
as long as the (Lebesgue) integral on the right is defined and finite. Otherwise, set $X_T(\omega) := 0$. From Fubini's theorem we know that, w.l.g., we may assume that $X_T$ is $\mathcal{A}/\mathcal{B}$-measurable.
Consider the stochastic process $X := (X_T)_{T \in [0,\infty)}$. As a function from $[0,\infty)\times \Omega$ to $\mathbb{R}$, is $X$ $(\mathcal{B}_{[0,\infty)}\otimes \mathcal{A})/\mathcal{B}$-measurable?

A: Yes, it is. This follows from the fact that $(X_t)_{t \geq 0}$ has continuous sample paths.

Lemma: Let $(X_t)_{t \geq 0}$ be a stochastic process with continuous sample paths such that $X_t$ is $\mathcal{A}$-measurable for each $t \geq 0$. Then $X: [0,\infty) \times \Omega \to \mathbb{R}$ is measurable.

For the proof show first that
$$X^n(t,\omega) := \sum_{j \geq 0} X_{\frac{j}{n}}(\omega) 1_{[\frac{j}{n},\frac{j+1}{n})}(t)$$
is $\mathcal{B}[0,\infty) \otimes \mathcal{A}$-measurable for each $n$ and then use that $X^n(t,\omega) \to X(t,\omega)$ as $n \to \infty$.


text:
Q: Fix my (short) Python to C# Algorithm Port Writing a sorting algorithm based off of Reddit's here: http://amix.dk/blog/post/19588
I'm having a little trouble getting it all to fit together because some of the System.Math signatures differ in their application.
public class Calculation
{
    protected DateTime Epoch = new DateTime(1970,1,1);

    protected int EpochSeconds(DateTime date)
    {
        var td = date - Epoch;
        return td.Days*86400 + td.Seconds + ((td.Milliseconds)/1000000);
    }

    protected int Score(int upVotes,int downVotes)
    {
        return upVotes - downVotes;
    }

    public int HotScore(int upVotes,int downVotes,DateTime date)
    {
        var s = Score(upVotes, downVotes);
        var order = Math.Log(Math.Max(Math.Abs(s), 1), 10);
        var sign = Math.Sign(s); //Edit from Jonathon Reinhart
        var seconds = EpochSeconds(date) - 1134028003;
        return Math.Round(order + sign + *seconds/45000, 7);
    }
}

Edits for more information
Specifically I'm getting an error on the last line
return Math.Round(order + sign + *seconds/45000, 7);
//error "The * or -> operator must be applied to a pointer"

"
The closest match I can find in the method signature is this:
http://msdn.microsoft.com/en-us/library/f5898377

A: One recommendation I would make is to use Math.Sign(Int32). So:
var sign = new int();
if (s > 0) { sign = 1; }
else if (s < 0) { sign = -1; }
else { sign = 0; }

Becomes:
var sign = Math.Sign(s);

Ok, so you're having problems with this line:
return Math.Round(order + sign + *seconds/45000, 7);

Well for one, you're probably losing the fractional part in seconds/45000, because they are both int. Cast one to double first:  ((double)seconds / 45000).
For two, you've likely got a syntactical error sign + *seconds.  Do you mean + or *? It thinks you're using seconds like a pointer.
Finally, Math.Round returns a double, but your HotScore method is returning an int. I'm guessing you want that to return a double.
My guess is that this is what you want:
public double HotScore(int upVotes,int downVotes,DateTime date)
{
    var score = Score(upVotes, downVotes);
    var order = Math.Log(Math.Max(Math.Abs(score), 1), 10);
    var sign = Math.Sign(score);
    var seconds = EpochSeconds(date) - 1134028003;
    return Math.Round(order + sign * ((double)seconds/45000), 7);
}

Also, I don't think your EpochSeconds() is correct. I adapted this from here:
public long GetEpochTime(DateTime dt)
{
    var ts = dt.Subtract(Convert.ToDateTime("1/1/1970 8:00:00 AM"));

    return ((((((ts.Days * 24) + ts.Hours) * 60) + ts.Minutes) * 60) + ts.Seconds);
}

A: You have a syntax error on the last line - the sequence of + * isn't valid. I think what you want for the last line is this (using this Math.Round overload):
return Math.Round(order + sign * ((double)seconds / 45000), 7);


text:
Q: Animated mobile animation with vanilia js and css I would like to make animated show and hide navigation menu like in this webiste
I tried to do it with JS
const body = document.getElementsByTagName("body")[0];
let element = document.querySelector(".navigation");
let button = document.querySelector(".menu-button");

 button.addEventListener("click", function() {
  button.classList.toggle("menu-button--changed");
  element.classList.toggle("navigation--show");
});

And width scss
.navigation {
  background-color: rgb(14, 14, 23);
  width: 250px;
  height: 100vh;
  position: fixed;
  right: 0;
  top: 0;
  z-index: 3;
  padding: 6rem 0 2rem 0rem;
  transition: transform 0.3s ease-out;
  transform: translateX(30rem);
  &--show {
    transform: translateX(0rem);
  }

 &__item {
    list-style: none;
    border-top: 1px solid rgba(255, 255, 255, 0.03);

    &:last-child {
      border-bottom: 1px solid rgba(255, 255, 255, 0.03);
    }
  }
  &__link {
    color: #fff;
    text-decoration: none;
    display: block;
    padding: 11px 5px 10px 20px;
    font-size: 1.4rem;

    &:hover {
      text-transform: uppercase;
    }
  }
}

HTML

Home

Contact

Group

But it doesn't work correctly. I don't know how to move body to left, when I show menu, and change it to more darkly.
I tried to add, but animation doesn't work.

A: This is a very basic one I made for another question a while ago, it's similar to what you're asking. Basically, the navigation bar changes colour when the user reaches a certain scroll point. Should hopefully be a starting point to actually getting you on your way with making it disappear and then reappear.
HTML

            <button type="button" class="navbar-toggle" id="nav-icon" data-toggle="collapse" data-target=".navbar-collapse">

            </button>

HOME

COURSES

PRICING

ACCOUNT

CONTACT

CSS
.navbar {
  background-color:#101010;
  border:none;
  height: 200vh;
}
#logo {
  width:45px;
  height:auto;
 }
.navbar-right li a {
  color:#e5e5e5;
  font-size:14px;
}
ul.navbar-right li a:hover {
  color:#e5e5e5;
  text-decoration: none;
  background-color:transparent;
}
ul.navbar-right li a:visited {
  color:#e5e5e5;
  text-decoration:none;
}
/* Transitions */
.navbar { background-color: transparent; border:none; transition:0.8s; }
.nav-scrolled { background-color:#181818; transition:0.8s; }
.navbar-right li a { letter-spacing:3px; }

JS
// Change nav on scroll
$(function() {
    var header = $(".navbar");

    $(window).scroll(function() {
        var scroll = $(window).scrollTop();
        if (scroll >= 200) {
            header.addClass("nav-scrolled");
        } else {
            header.removeClass("nav-scrolled");
        }
    })
});

ALT:
https://jsfiddle.net/vtqeuzf5/

A: Treat the main page as a element and use overflow hidden.
lets say that main column is 100% on mobile when you click the menu button it changes to 60% and the menu to 40%.
Bootstrap has a basic turotial about this


text:
Q: Java how to update a JSON object value and send it as a body to PUT request I am trying to automate my REST service's PUT request and I am completely new to JAva. Here I am passing a PUT  body(in JSON format)  along with other headers.
I had created a Java class for PUT in which I have getters and setters and I am assigning values using setter and creating my PUT body and sending this PUT body in my PUT request.
My PUT body is something like this .  I am able to update "id" and "name" and create my body object but I am not sure how do I update the "versionname" and"number" under "versions" path?
{
    "versions": [
        {
            "versionname": "Test",
            "number": 1

        }
    ],
    "id": 89960004,
    "name": "TEST CES LIST4",

}

The class for PUT body is as below:

public class putBody {

public String id;
public String name;
public String versionName;
public String number;

public String getId() {
    return id;
}

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

public String getversionName() {
    return versionName;
}

public void setversionName(String versionName) {
    this.versionName = versionName;
}

My question is how to update the "versionname" and "number" and create my putBody object. Any help much appreciated.

A: First, your PutBody class must have a collection to keep your version data, according to the JSON output that you provided.
For this purpose, just create a Version class that will be used for every single version information:
public class Version {

    public String versionName;
    public String number;

    public String getVersionName() {
        return versionName;
    }

    public void setVersionName(String versionName) {
        this.versionName = versionName;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

}

Then, here is your PutBody class should be look like
public class PutBody {

    public String id;
    public String name;
    public List<Version> versions;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public List<Version> getVersions() {
        return versions;
    }

    public void setVersions(List<Version> versions) {
        this.versions = versions;
    }

}

And here is how to fill it with data according to your example values :
List<Version> versions = new ArrayList<Version>();
    Version version = new Version();
    version.setVersionName("Test");
    version.setNumber("1");
    versions.add(version);

    PutBody putBody = new PutBody();

    putBody.setName("TEST CES LIST4");
    putBody.setId("89960004");
    putBody.setVersions(versions);

And the JSON Output :
{
  "id": "89960004",
  "name": "TEST CES LIST4",
  "versions": [
    {
      "versionName": "Test",
      "number": "1"
    }
  ]
}

UPDATE
Google's Gson has great features for this purpose. You can easily convert Java instances to JSON and convert JSON strings back to Java instances.
Please check that


text:
Q: simple node client server communication not working using express and socket.io I'm trying to write a simple client server application.
That's the HTML:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    <script src="client.js"></script>
</body>

</html>

server.js file:
const express = require('express');
const app = express();
const port = 3000;
const server = app.listen(port);
const io = require('socket.io')(server);

app.get('/', (req, res) => {
  res.send('Hello World!');
});

io.on('connection', (socket) => {
    console.log('a user connected');
});

client.js file:
const socket = io('https://localhost:3000/');

At this moment if I start the server by typing node server on the terminal and I open the HTML file using the LiveServer vs extension, the console doesn't show the text a user connected, it also returns an error which is:

GET
https://localhost:3000/socket.io/?EIO=4&transport=polling&t=NdZ4wOd
net::ERR_SSL_PROTOCOL_ERROR

I don't know what I'm doing wrong.

A: In the client.js file you could try const socket = io.connect(); and I'm not sure but i think <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script> Should be in the header but i could be wrong about that.

A: **Make Changes In Your Server File **
const express = require('express');
const cors = require('cors');
const app = express();
const port = 3000;
app.use(cors());
const server = app.listen(port);
const io = require('socket.io')(server);

app.get('/', (req, res) => {
  res.send('Hello World!');
});

io.on('connection', (socket) => {
    console.log('a user connected');
});

Install cors npm package before starting your server using npm i cors


text:
Q: Entrust laravel hasRole function was not working I am using laravel 5 and using entrust for permissions. I have a username called admin. And i have a Role named admin. I have assigned the role to user id. But the below command not working.
Route::get('/secret', function()
{
    $user = Auth::user();
    if (Entrust::hasRole('admin'))
    {
        print_r($user);
        return 'True';
    }

    return 'Not ok';
});

A: You'd have to do (if everything is setup properly):
Route::get('/secret', function()
{
    $user = Auth::user();
    if ($user->hasRole('admin'))
    {
        print_r($user);
        return 'True';
    }

    return 'Not ok';
});

More info in the Documentation under 'Checking for Roles & Permissions'
.


text:
Q: Array.concat() returns separate arrays in typescript(Angular) I am trying to apply a filter on a JSON array using multiple input parameters from a checkbox and concatenate the results into a single array.
stats = {
    All : {value: 'All', prop: 'All', checked: true, disabled: false},
    Open : {value: 'Open', prop: 'Open', checked: false, disabled: false},
    Registered: {value: 'Registered', prop: 'In Progress', checked: false,
                 disabled: false},
    Admitted: {value: 'Admitted', prop: 'Student Admitted', checked: false,
                   disabled: false},
    Inactive: {value: 'Inactive', prop: 'Converted', checked: false,
                   disabled: false},
         };
    check: boolean = true; disable: boolean = true;
    checkedStatus =[];
    filtered = [];

//inside function//

if(checkerObj.checked === true){
    this.checkedStatus.push(checkerObj.prop);
    this.checkedStatus.forEach(el => {
     var temp = [];
     let temp2 = [];
     temp = this.rows.filter(row => {
      if(row.statusValue === el){
        temp = [];
        //console.log(typeof row);
        return row;
      }
      });
      //console.log(temp);
      var arr3 = temp2.concat(temp);
     //this.source = new LocalDataSource(temp2);
     console.log(arr3);
    })
  }

The code prints multiple array declarations on screen, which would have been fine if every consecutive declaration had the value of previous concatenated into it.
enquiry-manage.component.ts:131
 (17) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},
      {…}, {…}, {…}]
enquiry-manage.component.ts:131
 (6) [{…}, {…}, {…}, {…}, {…}, {…}]
enquiry-manage.component.ts:131
 (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

I have fetched data into the array by use of a service:
this.enquire.getAllEnquiry().map(data => {
  this.rows = data;
 }).subscribe(data => {
  this.source = new LocalDataSource(this.rows);
  this.source.refresh();
})

then only checkbox check event
  statusFilter(checkerObj){
   if(this.stats.Open.checked === true || this.stats.Registered.checked ===
   true || this.stats.Admitted.checked === true ||
   this.stats.Inactive.checked === true){
   this.stats.All.checked = false;
   this.stats.All.disabled = true;
   if(checkerObj.checked === true){
    this.checkedStatus.push(checkerObj.prop);
    this.checkedStatus.forEach(el => {
     var temp = [];
     let temp2 = [];
     temp = this.rows.filter(row => {
      if(row.statusValue === el){
        temp = [];
        return row;
      }
      });
      //console.log(temp);
      temp2 = temp.concat(temp2);
     //this.source = new LocalDataSource(temp2);
     console.log(temp);
    })
  }
  else if(checkerObj.checked === false){
    var index = this.checkedStatus.indexOf(checkerObj.prop);
    if (index > -1){
      this.checkedStatus.splice(index, 1);
    }
    this.checkedStatus.forEach(el => {
    //          this.customFilterStatus(el);
    })
    //      console.log(this.checkedStatus);
  }
  }

A: Well tried the suggestion provided by @Satpal and modified the code a bit inside the function.
    if(checkerObj.checked === true){
    this.checkedStatus.push(checkerObj.prop);
    let temp2 = [];
    let temp = [];
    let arr = [];
    this.checkedStatus.forEach(el => {
      temp2 = this.rows.filter(row => {
        return row.statusValue === el });
        temp = temp2;
        arr = arr.concat(temp);
      });
      this.source = new LocalDataSource(arr);
      console.log(arr);
  }


text:
Q: Code conversion from MVC to C# asp.net webforms I found a nice code to down size image on server, to avoid bad image rendering by different browser. This code is for MVC application.
I have no experience in C# would like to know what do I need to change to make this code work in webforms.
<img src="@Url.Action("ResizeImage", "Controller", new { urlImage = "<url_image>", width = 35 })" />

public ActionResult ResizeImage(string imageUrl, int width)
{
    WebImage wImage = new WebImage(imageUrl);
    wImage = WebImageExtension.Resize(wImage, width);
    return File(wImage.GetBytes(), "image/png");
}

public static class WebImageExtension
{
    private static readonly IDictionary<string, ImageFormat> TransparencyFormats =
        new Dictionary<string, ImageFormat>(StringComparer.OrdinalIgnoreCase) { { "png", ImageFormat.Png }, { "gif", ImageFormat.Gif } };

    public static WebImage Resize(this WebImage image, int width)
    {
        double aspectRatio = (double)image.Width / image.Height;
        var height = Convert.ToInt32(width / aspectRatio);

        ImageFormat format;

        if (!TransparencyFormats.TryGetValue(image.ImageFormat.ToLower(), out format))
        {
            return image.Resize(width, height);
        }

        using (Image resizedImage = new Bitmap(width, height))
        {
            using (var source = new Bitmap(new MemoryStream(image.GetBytes())))
            {
                using (Graphics g = Graphics.FromImage(resizedImage))
                {
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.DrawImage(source, 0, 0, width, height);
                }
            }

            using (var ms = new MemoryStream())
            {
                resizedImage.Save(ms, format);
                return new WebImage(ms.ToArray());
            }
        }
    }
}

UPDATE:
I use this code to resize images
public static void ResizeImageFreeSize(string OriginalFile, string NewFile, int MinWidth, int MinHeight, string FileExtension)
{
var NewHeight = MinHeight;
var NewWidth = MinWidth;
// var OriginalImage = System.Drawing.Image.FromFile(OriginalFile); // THis statlement alon with generate error as file is locked so -->GDI+ keeps a lock on files from which an image was contructed.  To avoid the lock, construct the image from a MemorySteam:

MemoryStream ms = new MemoryStream(File.ReadAllBytes(OriginalFile));
var OriginalImage = System.Drawing.Image.FromStream(ms);

if (OriginalImage.Width < MinWidth || OriginalImage.Height < MinHeight)
    throw new Exception(String.Format("Invalid Image Dimensions, please upload an image with minmum dimensions of {0}x{1}px", MinWidth.ToString(), MinHeight.ToString()));

// If the image dimensions are the same then make the new dimensions the largest of the two mins.
if (OriginalImage.Height == OriginalImage.Width)
    NewWidth = NewHeight = (MinWidth > MinHeight) ? MinWidth : MinHeight;
else
{
    if (MinWidth > MinHeight)
        NewHeight = (int)(OriginalImage.Height * ((float)MinWidth / (float)OriginalImage.Width));
    else
        NewWidth = (int)(OriginalImage.Width * ((float)MinHeight / (float)OriginalImage.Height));
}

// Just resample the Original Image into a new Bitmap
var ResizedBitmap = new System.Drawing.Bitmap(OriginalImage, NewWidth, NewHeight);

// Saves the new bitmap in the same format as it's source image
FileExtension = FileExtension.ToLower().Replace(".", "");

ImageFormat Format = null;
switch (FileExtension)
{
    case "jpg":
        Format = ImageFormat.Jpeg;

        Encoder quality = Encoder.Quality;
        var ratio = new EncoderParameter(quality, 100L);
        var codecParams = new EncoderParameters(1);
        codecParams.Param[0] = ratio;
        // NewImage.Save(NewFile, GetEncoder(ImageFormat.Jpeg), codecParams);
        ResizedBitmap.Save(NewFile, GetEncoder(ImageFormat.Jpeg), codecParams);
        break;
    case "gif":
        Format = ImageFormat.Gif;
        ResizedBitmap.Save(NewFile, Format);
        break;
    case "png":
        Format = ImageFormat.Png;
        ResizedBitmap.Save(NewFile, Format);
        break;
    default:
        Format = ImageFormat.Png;
        ResizedBitmap.Save(NewFile, Format);
        break;
}

//  ResizedBitmap.Save(NewFile, Format);

// Clear handle to original file so that we can overwrite it if necessary
OriginalImage.Dispose();
ResizedBitmap.Dispose();
}

A: You can have a HttpHandler for this in C#,
namespace CMSN.Software.Tutorials.HowToDynamicallyResizeImages
{
    public class DynamicImage : IHttpHandler
    {
        /// <summary>
        /// Default cache duration
        /// </summary>
        private static readonly TimeSpan CacheDuration = TimeSpan.FromDays(30);

        /// <summary>
        /// Gets a value indicating whether another request can use the
        /// <see cref="T:System.Web.IHttpHandler"/> instance.
        /// </summary>
        /// <returns>
        /// true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
        /// </returns>
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the
        /// <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the

        /// intrinsic server objects (for example, Request, Response, Session, and Server)
        /// used to service HTTP requests.
        /// </param>
        public void ProcessRequest(HttpContext context)
        {
            string cacheKeyName = context.Request.Url.PathAndQuery;
            string imagePath = context.Server.MapPath(context.Request.Url.LocalPath);
            string imageExtention = Path.GetExtension(imagePath);
            string contentType = string.Empty;
            byte[] imageFileContent;
            ImageFormat imageFormat = null;

            switch (imageExtention)
            {
                case ".png":
                    imageFormat = ImageFormat.Png;
                    contentType = "image/png";
                    break;
                case ".jpg":
                case ".jpeg":
                case ".jpe":
                    imageFormat = ImageFormat.Jpeg;
                    contentType = "image/jpeg";
                    break;
                case ".bmp":
                    imageFormat = ImageFormat.Bmp;
                    contentType = "image/bmp";
                    break;
                case ".gif":
                    imageFormat = ImageFormat.Gif;
                    contentType = "image/gif";
                    break;
                default:
                    break;
            }

            context.Response.ContentType = contentType;

            if (context.Cache[CacheKey(cacheKeyName)] != null)
            {
                imageFileContent = context.Cache[CacheKey(cacheKeyName)] as byte[];
            }
            else
            {
                int imageWidth = 0;
                int imageHeight = 0;

                if (!string.IsNullOrEmpty(context.Request["w"]))
                {
                    if (!int.TryParse(context.Request["w"], out imageWidth))
                    {
                        imageWidth = 0;
                    }
                }

                if (!string.IsNullOrEmpty(context.Request["h"]))
                {
                    if (!int.TryParse(context.Request["h"], out imageHeight))
                    {
                        imageHeight = 0;
                    }
                }

                Image originalImage;

                if (File.Exists(imagePath))
                {
                    originalImage = Image.FromFile(imagePath);
                }
                else
                {
                    originalImage = new Bitmap(100, 100);
                }

                if (imageWidth > 0 || imageHeight > 0)
                {
                    if (imageHeight == 0 && imageWidth > 0)
                    {
                        imageHeight = originalImage.Height * imageWidth / originalImage.Width;
                    }

                    if (imageWidth == 0 && imageHeight > 0)
                    {
                        imageWidth = originalImage.Width * imageHeight / originalImage.Height;
                    }
                }
                else
                {
                    imageHeight = originalImage.Height;
                    imageWidth = originalImage.Width;
                }

                using (Bitmap newImage = new Bitmap(originalImage, imageWidth, imageHeight))
                {
                    Graphics generatedImage = Graphics.FromImage(newImage);
                    generatedImage.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    generatedImage.SmoothingMode = SmoothingMode.AntiAlias;
                    generatedImage.CompositingQuality = CompositingQuality.HighQuality;
                    generatedImage.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);

                    // make a memory stream to work with the image bytes
                    using (MemoryStream imageStream = new MemoryStream())
                    {
                        // put the image into the memory stream
                        newImage.Save(imageStream, imageFormat);

                        // make byte array the same size as the image
                        byte[] imageContent = new byte[imageStream.Length];

                        // rewind the memory stream
                        imageStream.Position = 0;

                        // load the byte array with the image
                        imageStream.Read(imageContent, 0, (int)imageStream.Length);

                        // return byte array to caller with image type
                        imageFileContent = imageContent;

                        using (CacheDependency dependency = new CacheDependency(imagePath))
                        {
                            context.Cache.Insert(
                            CacheKey(cacheKeyName),
                            imageContent,
                            dependency,
                            System.Web.Caching.Cache.NoAbsoluteExpiration,
                            CacheDuration);
                        }
                    }
                }

                originalImage.Dispose();
            }

            SetResponseCache(context.Response, new string[1] { imagePath });
            context.Response.BinaryWrite(imageFileContent);
        }

        /// <summary>
        /// Generate unique Cache key.
        /// </summary>
        /// <param name="key">The cache key.</param>
        /// <returns>Generated unique Cache key</returns>
        protected static string CacheKey(string key)
        {
            return "DynamicImage." + key;
        }

        /// <summary>
        /// Sets the response cache.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="files">The files.</param>
        protected static void SetResponseCache(HttpResponse response, string[] files)
        {
            response.AddFileDependencies(files);
            HttpCachePolicy browserCache = response.Cache;
            DateTime modifiedTime = DateTime.Now;
            browserCache.SetCacheability(HttpCacheability.ServerAndPrivate);
            browserCache.VaryByParams["w"] = true;
            browserCache.VaryByParams["h"] = true;
            browserCache.VaryByParams["v"] = true;
            browserCache.SetOmitVaryStar(true);
            browserCache.SetExpires(modifiedTime.AddDays(7));
            browserCache.SetValidUntilExpires(true);
            browserCache.SetLastModified(modifiedTime);
            browserCache.SetETagFromFileDependencies();
            browserCache.SetLastModifiedFromFileDependencies();
        }
    }
}

Web.config
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpHandlers>
      <add verb="*" path="*.png,*.jpg,*.jpeg,*.gif,*.bmp" type="CMSN.Software.Tutorials.HowToDynamicallyResizeImages.DynamicImage,HowToDynamicallyResizeImages"/>
    </httpHandlers>
  </system.web>
  <system.webServer>
    <handlers>
      <add verb="*" path="*.png,*.jpg,*.jpeg,*.gif,*.bmp" name="DynamicImage" type="CMSN.Software.Tutorials.HowToDynamicallyResizeImages.DynamicImage,HowToDynamicallyResizeImages"/>
    </handlers>
    <validation validateIntegratedModeConfiguration="false"/>
  </system.webServer>
</configuration>

Usage,
http://localhost/Images/xxxxxxxx.png?w=300&h=149

If you want to see the complete guide for this, please follow the following URL.
http://tutorials.cmsnsoftware.com/2011/09/how-to-dynamically-resize-images.html


text:
Q: speeding up finding changes in list of dictionaries I have a question on how to speed up my code.
From a api request I retrieve a huge table that I convert into a list of dictionaries.
I do this every X minutes to keep up to date.
Now I want to upload this to firebase firestore to use in my web app.
To limit the amount of reads and writes to firebase I only want to send the changes in the table.
I use this function to calculate the differences (added, changed and deleted).
def getDifferences(table, tableInfo):
    tableName = tableInfo[0]
    tableNumber = tableInfo[1]
    ID = tableInfo[2]
    tableOld = []

    if os.path.isfile('/home/bellboy/Python/history/' + tableName + '.txt'):
        with open('/home/bellboy/Python/history/' + tableName + '.txt', 'rb') as f:
            tableOld = pickle.load(f)

    with open('/home/bellboy/Python/history/' + tableName + '.txt', 'wb') as f:
        pickle.dump(table, f)

    i = {}
    added = [i for i in table if i not in tableOld and not any(
        d[ID] == i[ID] for d in tableOld)]
    changed = [i for i in table if i not in tableOld and any(
        d[ID] == i[ID] for d in tableOld)]
    deleted = [i for i in tableOld if i not in table and not any(
        d[ID] == i[ID] for d in table)]

    return [added, changed, deleted]

How can I speed up this function, the lists can be 40,000 dictionaries long?
The ID checking is necessary because there can be changes within the dictionaries values.
Sample data:
[
    {'volgnummer': u'001', 'naam': u'xxxxxx', 'telefoonnummer': u'0311-xxxxxxx', 'emailadres': u'xxxxxxx@xxxxxx.nl', 'klantnummer': u'204829'},
    {'volgnummer': u'001', 'naam': u'xxxxxx', 'telefoonnummer': u'0311-xxxxxxx', 'emailadres': u'xxxxxxx@xxxxxx.nl', 'klantnummer': u'204830'},
    {'volgnummer': u'001', 'naam': u'xxxxxx', 'telefoonnummer': u'0311-xxxxxxx', 'emailadres': u'xxxxxxx@xxxxxx.nl', 'klantnummer': u'204831'},
    {'volgnummer': u'001', 'naam': u'xxxxxx', 'telefoonnummer': u'0311-xxxxxxx', 'emailadres': u'xxxxxxx@xxxxxx.nl', 'klantnummer': u'204832'},
    {'volgnummer': u'001', 'naam': u'xxxxxx', 'telefoonnummer': u'0311-xxxxxxx', 'emailadres': u'xxxxxxx@xxxxxx.nl', 'klantnummer': u'204833'},
    {'volgnummer': u'001', 'naam': u'xxxxxx', 'telefoonnummer': u'0311-xxxxxxx', 'emailadres': u'xxxxxxx@xxxxxx.nl', 'klantnummer': u'204834'},
    {'volgnummer': u'001', 'naam': u'xxxxxx', 'telefoonnummer': u'0311-xxxxxxx', 'emailadres': u'xxxxxxx@xxxxxx.nl', 'klantnummer': u'204835'},
 ]


text:
Q: How does Angular Component be rendered in HTML?Or in what form does angular component template exist in dom? I'm new to angular, and WEB to be honest.Now I am doing some experiments with angular and Chrome dev tools.I created a quite simple component.
@Component({
  selector: 'fa-input',
  templateUrl: './fa-input.component.html',
  styleUrls: ['./fa-input.component.css']
})

whose template is just a input wrapped in div
<div>
  <input>
</div>

In chrome element inspector, I saw
this
Then I got confused with some basic concepts.Are app-root and fa-input real elements in the html? If so, are they so-called custom elements? If angular components are represented as custom elements, why there is another concept called Angular elements? And do they have relationship with
a concept called web components? Are they rendered in dom as shadow dom? Are all custom elements rendered in the form of shadow dom?
I also tried to add css style to the template.
:host {
  border: 1px solid grey;
}
input {
  border: none;
  outline: none;
}

In chrome dev tools I saw
this
It seems :host get the component shadow root(does it?).But the style didn't apply.I can't see the border as the css described.Can someone explain how angular components be attached to html and rendered in dom? How can I use chrome dev tools more effectivly? Many many thanks!


text:
Q: Jquery pass parameter from script tag Hi guys I just want to know is there any possibility to pass variables from
<script src="js/scripts.js"></script>

this tag? I mean something like this:
<script src="js/scripts.js">$par = "hello world"</script>
or
<script src="js/scripts.js" par="hello world"></script>

A: You can definitely do both (why you would want this is another question).
Regarding the first option, you'll find a more detailed explanation in this article from John Resig.
As for the second option, take a look at the dojo toolkit, they use it a lot (they call it the declarative approach).

A: There is no need to or use of defining a variable like you do.
Try this:
<script>var par = "<?php echo $par; ?>"</script>

A: <script type="text/javascript">
    /* <![CDATA[ */
    var par = "<?php echo $par; ?>";
    /* ]]> */
</script>
<script src="js/scripts.js"></script>

The variable "par" is then accessible inside the script.


text:
Q: Create View with STUFF function using two tables I have a create view and I am using the STUFF function. I have it working where it takes one field from one table and stuffs it. However those values are int's and they have corresponding descriptions in another table. So I would have "4, 5" in my stuff field and I would like it to be "this is #4 description, this is #5 description". My create view and STUFF function is the following and the tables are linked by ConditionsReasonsID however I need the RequestedBurnsID for the original stuff and to be used in my create view.
CREATE VIEW [AQB_OB].[GISREQUESTEDBURNS]
AS

with conditions as
(SELECT DISTINCT BD.[RequestedBurnsID]
,[ConditionsReasonsID] = STUFF((SELECT ', ' + CONVERT(VARCHAR(20),[ConditionsReasonsID])
FROM [AQB_OB].[BurnDecisions] WHERE [RequestedBurnsID]= BD.[RequestedBurnsID]
ORDER BY [RequestedBurnsID] ASC
FOR XML PATH ('')) , 1 , 1, '') FROM
[AQB_OB].[BurnDecisions] BD)

SELECT RB.[RequestedBurnsID] AS REQUESTEDBURNID
  ,BUY.[BurnYear] AS BURNYEAR
  ,CY.[CurrentYear] AS CURRENTYEAR
  ,RB.[BurnSitesID] AS BURNSITESID
  ,[BurnerID] AS BURNERID
  ,[BurnStartDate] AS BURNSTARTDATE
  ,[BurnEndDate] AS BURNENDDATE
  ,[BurnDecision] AS BURNDECISION
  ,RB.[Comment] AS COMMENT
  ,CC.ConditionsReasonsID AS CONDITIONS

  FROM [AQB_MON].[AQB_OB].[RequestedBurns] RB
 inner join AQB_MON.[AQB_OB].[BurnSites] BS on RB.BurnSitesID = BS.BurnSitesID
full outer join  conditions CC on CC.RequestedBurnsID = RB.RequestedBurnsID
INNER JOIN [AQB_OB].[ConditionsReasons] CR ON CR.ConditionsReasonsID = CC.ConditionsReasonsID
GO

Update - My table structure for the two table - BurnDecision and ConditionsReasons. I need the SELECT DISTINCT as it ties to RequestedBurnes as that is the table the view is created around.

Update - Result with original sql statement. I would like the integers in the Conditions column to be string descriptions from the ConditionsReasons table.


text:
Q: Pyomo constraints and using pandas I am using Pyomo to optimize a cashflow matching problem using bonds.
I also want to have a detailed constraint that does looks at the cashflows I am expecting to get from my portfolio versus fixed requirements and conduct a number of calculations on the differences:

*

*Calculate difference (wanted minus expected to receive or "in - out" in the picture)

*Calculate the accumulation of these differences to the last end point using accumulation factors (multiply difference with accumulation factors - which are stored as a model.AccumFactors)

*Sum these year-on-year accumulation factors (cumsum(axis=1))

*Find the minimum

[Excel description of process][1]
Now Panda commands don't work in this situation. Is there anything I can do to fix this? Alternative approaches?

A: Thanks gmavrom.
Trying to think a different formulation. The code below has Multipliers as the model variable and everything else as parameters.
Unfortunately the below doesn't work and just prints out strings of:
54993.219033692505*Multipliers[Bond1] + 63662.18895851663*Multipliers[Bond2] + 64451.10079031628*Multipliers[Bond3] + … etc
def Test1_Constraint(model, TimeIndex):
   SumAccumulatedShortfall=0
   for TimeCount in range(0,TimeIndex+1):
         AccumulatedShortfall = (model.Liabilities[TimeCount] - \
                    sum(model.BondPayment[BondIndex, TimeCount] *model.Multipliers[BondIndex] for BondIndex in model.Bonds))* \
                                  model.AccumulationFactor[TimeCount]

         SumAccumulatedShortfall = SumAccumulatedShortfall + AccumulatedShortfall
         print('SumAccum',SumAccumulatedShortfall)
    return (SumAccumulatedShortfall/model.TotalLiabilityValue <= 0.03)


text:
Q: can more than 2 users connect Remotely using Remote Desktop connection in Windows server 2008 R2 can  more than 2 users connect at same time using Remote Desktop connection  (RDC) in Windows server 2008?
If yes, please guide me.

A: Since you used the Windows Server R2 tag, I assume you use the R2 version:

*

*On the RD Session Host server, open Remote Desktop Session Host Configuration. To open Remote Desktop Session Host Configuration, click Start, point to Administrative Tools, point to Remote Desktop Services, and then click Remote Desktop Session Host Configuration.

*Under Connections, right-click the name of the connection, and then click Properties.

*In the Properties dialog box for the connection, on the Network Adapter tab, click Maximum connections, enter the number of simultaneous remote connections that you want to allow for the connection, and then click OK.
If the Maximum connections option is selected and dimmed, the Limit number of connections Group Policy setting has been enabled and has been applied to the RD Session Host server.
copy & pasted from source: http://technet.microsoft.com/en-us/library/cc753380.aspx


text:
Q: problem with NHibernate one-to-many relationship Collection with cascade I have AssetGroup entity with has a one-to-many relation with Asset entity. There is a Entity base class which overrides Equals and GetHashCode . I am following the example of ch 20 parent child
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="TestNHibernate"
                   namespace="TestNHibernate.Models" auto-import="true">
  <class name="AssetGroup">
    <id name="Id" column="Id" type="guid">
      <generator class="guid"></generator>
    </id>
    <property name="Name" type="string" not-null="true"/>
    <set name="Assets" cascade="all" inverse="true" access="field.camelcase-underscore" lazy="true">
      <key column="AssetGroupID"/>
      <one-to-many class="Asset"/>
    </set>
  </class>
</hibernate-mapping>

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="TestNHibernate"
                   namespace="TestNHibernate.Models" auto-import="true">
  <class name="Asset">
    <id name="Id" column="Id" type="guid">
      <generator class="guid"></generator>
    </id>
    <property name="Name" type="string" not-null="true"/>
    <many-to-one name="AssetGroup" column="AssetGroupID" cascade="all" lazy="false"/>

  </class>
</hibernate-mapping>

the code as folloow:
public class AssetGroup : Entity<Guid>
{
    public AssetGroup()
    {
        this._assets = new HashedSet<Asset>();
    }

    virtual public string Name { get; set; }

    private ISet<Asset> _assets;
    virtual public ISet<Asset> Assets
    {
        get { return _assets; }
        protected set { _assets = value; }
    }

    virtual public bool AddAsset(Asset asset)
    {
        if (asset != null && _assets.Add(asset))
        {
            asset.SetAssetGroup(this);
            return true;
        }
        return false;
    }

    virtual public bool RemoveAsset(Asset asset)
    {
        if (asset != null && _assets.Remove(asset))
        {
            asset.SetAssetGroup(null);
            return true;
        }
        return false;
    }
 }

public class AssetGroup : Entity<Guid>
{
    public AssetGroup()
    {
        this._assets = new HashedSet<Asset>();
    }

    virtual public string Name { get; set; }

    private ISet<Asset> _assets;
    virtual public ISet<Asset> Assets
    {
        get { return _assets; }
        protected set { _assets = value; }
    }

    virtual public bool AddAsset(Asset asset)
    {
        if (asset != null && _assets.Add(asset))
        {
            asset.SetAssetGroup(this);
            return true;
        }
        return false;
    }

    virtual public bool RemoveAsset(Asset asset)
    {
        if (asset != null && _assets.Remove(asset))
        {
            asset.SetAssetGroup(null);
            return true;
        }
        return false;
    }
}

My TestCode is as follow :
[TestMethod]
public void Can_Use_ISession()
{
    ISession session = TestConfig.SessionFactory.GetCurrentSession();
    var ag = new AssetGroup { Name = "NHSession" };
    session.Save(ag);

    var a1 = new Asset { Name = "s1" };
    var a2 = new Asset { Name = "s2" };

    a1.SetAssetGroup(ag);
    a2.SetAssetGroup(ag);

    session.Flush();

    Assert.IsTrue(a1.Id != default(Guid)); // ok
    Assert.IsTrue(a2.Id != default(Guid)); // ok

    var enumerator = ag.Assets.GetEnumerator();
    enumerator.MoveNext();
    Assert.IsTrue(ag.Assets.Contains(enumerator.Current));  // failed

    Assert.IsTrue(ag.Assets.Contains(a1));  // failed
    Assert.IsTrue(ag.Assets.Contains(a2));  // failed

    var agRepo2 = new NHibernateRepository<AssetGroup>(TestConfig.SessionFactory, new QueryFactory(TestConfig.Locator));
    Assert.IsTrue(agRepo2.Contains(ag)); // ok
    var ag2 = agRepo2.FirstOrDefault(x => x.Id == ag.Id);
    Assert.IsTrue(ag2.Assets.FirstOrDefault(x => x.Id == a1.Id) != null); // ok
    Assert.IsTrue(ag2.Assets.FirstOrDefault(x => x.Id == a2.Id) != null); // ok

    var aa1 = session.Get<Asset>(a1.Id);
    var aa2 = session.Get<Asset>(a2.Id);
    Assert.IsTrue(ag2.Assets.Contains(aa1));  // failed
    Assert.IsTrue(ag2.Assets.Contains(aa2));  // failed

}

My Entity base class is here:
public abstract class Entity<Tid> : IEquatable<Entity<Tid>>
{
    [HiddenInput(DisplayValue = false)]
    public virtual Tid Id { get; protected set; }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return base.Equals(obj);
        return Equals(obj as Entity<Tid>);
    }

    public static bool IsTransient(Entity<Tid> obj)
    {
        return obj != null && Equals(obj.Id, default(Tid));
    }

    private Type GetUnproxiedType()
    {
        return GetType();
    }

    public virtual bool Equals(Entity<Tid> other)
    {
        if (ReferenceEquals(this, other))
            return true;
        if (!IsTransient(this) && !IsTransient(other) && Equals(Id, other.Id))
        {
            var otherType = other.GetUnproxiedType();
            var thisType = GetUnproxiedType();
            return thisType.IsAssignableFrom(otherType) || otherType.IsAssignableFrom(thisType);
        }
        return false;
    }

    public override int GetHashCode()
    {
        if (Equals(Id, default(Tid)))
        {
            return base.GetHashCode();
        }
        else
        {
            return Id.GetHashCode();
        }
    }

}

I have commented which parts have failed in the code . Please help. It seems entities which are saved by cascading is not compatible with ICollection Contains/Remove . Asset a1 a2 are saved and they are inside the parent's Collection . For example I can find them by Linq FirstOrDefault . But the Collection's Contains and Remove will fail to find them . I notice the Collection use GetHashCode while Contains() or Remove() are called.

A: Assert.IsTrue(ag.Assets.Contains(a1));  // failed

This could would indeed fail. You have to manage the bi-directional relationship. By this I mean,
In AssetGroup:
virtual public bool AddAsset(Asset asset)
{
    if (asset != null && _assets.Add(asset))
    {
        asset.AssetGroup = this;
        return true;
    }
    return false;
}

... and a corresponding remove

In Asset:
virtual public bool SetAssetGroup(AssetGroup group)
{
    this.AssetGroup = group;
    group.Assets.Add(this);
}

Note the difference between your code and the one above.
This is not the only way of doing it, but it's the most mapping-agnostic, safe way of doing it... so whether you set inverse=true on your mapping or not, it'll work. I do it by default without even thinking about it too much.
When working with the model from the outside, you use AddXXX, RemoveXXX, SetXXX. When working with the model from the inside you reference the properties and collections directly. Adopt this as a convention, and you'll be ok for most of the common bi-directional mapping scenarios.
Having said this, I'm not sure why this code fails:
Assert.IsTrue(ag2.Assets.Contains(aa1));

ag2 is from a new query, so that should be ok ... unless the session cached the object, which I don't think it does... but I'm not sure.

A: I added session.Refresh(ag) and then it works .  Is session Refresh an expensive operation ? Is there any alternative
[TestMethod]
public void Can_Use_ISession()
{
    ISession session = TestConfig.SessionFactory.GetCurrentSession();
    var ag = new AssetGroup { Name = "NHSession" };
    session.Save(ag);

    var a1 = new Asset { Name = "s1" };
    var a2 = new Asset { Name = "s2" };

    a1.SetAssetGroup(ag);
    a2.SetAssetGroup(ag);

    session.Flush();
    session.Refresh(ag);

    Assert.IsTrue(a1.Id != default(Guid)); // ok
    Assert.IsTrue(a2.Id != default(Guid)); // ok

    var enumerator = ag.Assets.GetEnumerator();
    enumerator.MoveNext();
    Assert.IsTrue(ag.Assets.Contains(enumerator.Current));  // failed

    Assert.IsTrue(ag.Assets.Contains(a1));  // failed
    Assert.IsTrue(ag.Assets.Contains(a2));  // failed

    var agRepo2 = new NHibernateRepository<AssetGroup>(TestConfig.SessionFactory, new QueryFactory(TestConfig.Locator));
    Assert.IsTrue(agRepo2.Contains(ag)); // ok
    var ag2 = agRepo2.FirstOrDefault(x => x.Id == ag.Id);
    Assert.IsTrue(ag2.Assets.FirstOrDefault(x => x.Id == a1.Id) != null); // ok
    Assert.IsTrue(ag2.Assets.FirstOrDefault(x => x.Id == a2.Id) != null); // ok

    var aa1 = session.Get<Asset>(a1.Id);
    var aa2 = session.Get<Asset>(a2.Id);
    Assert.IsTrue(ag2.Assets.Contains(aa1));  // failed
    Assert.IsTrue(ag2.Assets.Contains(aa2));  // failed

}


text:
Q: MY SQL Partition by order by and percents
Can anyone explain each step in more detail of the attached syntax.  I can gather somewhat what the query and subquery is trying to find half the p1s when length is less then half and then when it is more. I just cant decipher understand the why and how. Is this similar to rank()OVER but using values inputted like length instead also not sure where the x1 and x2 come into play is that what its being called or its alias. Is the first query pulling the p1 from the subquery I get confused when and when you can not use aliases as well.  I apologize for the rambling the more coherent and detailed in layman terms the better.  Thank you in advance for your knowledge its much obliged!


text:
Q: how to change the output encoding, while displaying a file through php how to change the output encoding, while displaying a file through php

A: Use header('Content-type: text/foo; charset=bar'); to set the appropriate encoding, and use iconv to change the actual encoding of the file you are displaying if it does not match.


text:
Q: Create http request with WebWorker I'm trying to use nativescript web worker and i'm having a problem .
i want to make the http request in the webWorker.ts using http angular service
i need to import the http angular servie to the worker.ts and use it there
I've tried to send the http service as a parameter to the worker.ts but its do not works because its Initializing the service
I was hoping that the code will look something like that
worker.ts
require("globals");
(<any>global).onmessage = (msg: any) => {
       (make the httpRequest..... ).subscribe(response=>{
          (<any>global).postMessage(response);
        })

}

did you have any idea how can i do it ?


text: Q: jquery toggleClass without animation I want toggleClass to have the effect of hide and show, which is an abrupt showing and hiding of an element without any sign of a fade. In other words, I do not want any fade in or fade out animation which seems to come baked with toggleClass and removeClass and addClass. Does anyone know how to use jQuery's toggleClass without the fading animation?


text:
Q: Flask Upload with no Content-Type or Form Data at All I'm attempting to get around this WebDAV POST issue with Python3 Flask using WSGI on Apache2.4 by proxying all POST requests to a script.
I've been able to successfully upload PUT to create a file using CURL which looks like this:

But when I trigger the intended service to upload, the PUT is missing Content-Type and form data:

This fails all Flask upload examples which contain a conditional for request.files:
@app.route('/<path:fullpath>', methods = ['POST', 'PUT'])
def upload_files(fullpath):
    if not request.files:
        abort(400, "File not found")

Despite my searching I have no idea how to proceed with such an upload (raw?) type.
I believe I need to work with streams, but even those examples work off request.files().
Does anyone recognize how I might be able to upload these files?

A: The solution is to use file streaming. After many days of searching I finally found this blog post which mentions the specific problem of using the Flask/Requests file call:

The trick seems to be that you shouldn't use other request attributes like request.form or request.file because this will materialize the stream into memory/file. Flask by default saves files to disk if they exceed 500Kb, so don't touch file.

Running the attached method immediately solved the issue of upload without multipart-form:
from flask import Flask
import requests
from flask import request

app = Flask(__name__)

# Upload file as stream to a file.
@app.route("/upload", methods=["POST"])
def upload():
    with open("/tmp/output_file", "bw") as f:
        chunk_size = 4096
        while True:
            chunk = request.stream.read(chunk_size)
            if len(chunk) == 0:
                return
            f.write(chunk)
    return 'created', 201

(Full credit to @izmailoff, but I added the final line or else there would be a timeout issue on the receivers side)


text:
Q: Calculating weighted score of test I have a test containing questions with 3 levels of difficulty:
+------------+------------+-------+
| Question   | Difficulty | Score |
+------------+------------+-------+
| Question 1 | 1          | 100%  |
+------------+------------+-------+
| Question 2 | 1          | 100%  |
+------------+------------+-------+
| Question 3 | 2          |  25%  |
+------------+------------+-------+
| Question 4 | 2          |  75%  |
+------------+------------+-------+
| Question 5 | 3          |  25%  |
+------------+------------+-------+
| Question 6 | 3          |   0%  |
+------------+------------+-------+

Difficulty could mean something like

*

*Beginner

*Normal

*Expert

The average of the scores is ~54%, but this does not seem fair, because the candidate only answered the easy questions well.
What is the best formula to calculate the final score to reflect the knowledge level of the candidate for 3 difficulty levels?
Can we extend this formula to n difficulty levels?
What is the method used in education?

A: I was wondering that how did u rank  the difficulty level of the question?
I would suggest to make it an inverse function of average score for that question. for example :-
if a question was answered by 4 test takers correctly(100%) and 3 others scored 50% and rest did not attempt then for 10 test taker  its weigtage can be 10/(4 + 3*1.5 +0)
if all answered it correctly it should be 10/(10) =1
Its just a suggestion , i am not an expert in this field.
Here in my country many national level exams are conducted by third party vendors such as prometric , pearson. and most of them do not disclose their algorithm. so i am not really sure what scaling method is used in education


text:
Q: not able to cross compile openvpn in arm64 docker container in ubuntu 20.04 focal distribution
*

*Able to enter arm64 enviorntment by "docker run --rm -it arm64v8/ubuntu" in ubuntu Ubuntu 20.04.4 LTS focal distribution

*git clone https://github.com/mattock/sbuild_wrapper.git

*added arm64 content in ./config/variant.conf and mentioned openvpn version as 2.4.11 in c
config/version.conf

*when i ran sudo scripts/install-build-deps.sh i am getting below error,
E: 10mount: mount: /run/schroot/mount/bionic-arm64-sbuild-a9a9d57c-d683-4ea5-901b-dde2f81b960f:
permission denied.
E: bionic-arm64-sbuild-a9a9d57c-d683-4ea5-901b-dde2f81b960f: Chroot setup failed: stage=setup-
start
Chroot setup failed
Error setting up bionic-arm64 chroot
Chroot setup failed at /usr/bin/sbuild-apt line 52.**
May i know how to resolve this and compile successfuly?


text:
Q: Cannot use JSP tag or Servlet when HTML is generated from XML My web pages are rendered from XML.
It is dynamic without to create HTML pages or JSP.
The source code is described as follows
@RequestMapping(value = "/{templateid}", produces = "text/html; charset=UTF-8", method = RequestMethod.GET)
@ResponseBody
public String get(@PathVariable final String templateid) {
    //render from xml to html as string
    return string;
}

But, I can not use JSP tags or Servlet since it is not a JSP pages (the string returned above is html).
I want to use JSP tags when these pages are generated
Do you have any way to solve my problem I'm having?
Thanks,


text:
Q: Decimal type in Go and Postgresql with gorm So i'm creating an API and I needed to store the price of something.
I'm using gorm and gormigrate for my database migration.
I'm just wondering what proper type should I use for storing decimals. I've red somewhere that I shouldn't use floats when storing currencies.
type MyStruct struct {
    Name        string `json:"name" gorm:"not null"`
    Description string `json:"description" gorm:"null"`
    Price <what type should be here> `json:"price"`
}

A: So, based on the suggestion of @ain, I used shopspring/decimal. But it's giving me an error when I do automigrate.
It turns out that I only needed to set the type to numeric using a gorm tag to make it work:
type MyStruct struct {
    Name        string `json:"name" gorm:"not null"`
    Description string `json:"description" gorm:"null"`
    Price decimal.Decimal `json:"price" gorm:"type:numeric"`
}


text:
Q: Publish graphic icon into geoserver from QGIS I want to publish graphic icon (point) into geoserver by using maki style. Below is the coding,
<UserStyle>
  <se:Name>streetlight_u4</se:Name>
  <se:FeatureTypeStyle>
    <se:Rule>
      <se:Name>Single symbol</se:Name>
      <se:PointSymbolizer>
        <se:Graphic>
          <se:ExternalGraphic>
            <se:OnlineResource xlink:type="simple" xlink:href="file:///maki/park-alt1-15.svg"/>
            <se:Format>image/svg+xml</se:Format>
          </se:ExternalGraphic>

But, the result turns like below:-

Which is the actual graphic point is like below :-

Can anyone help?

A: Your url file:///maki/park-alt1-15.svg starts with a / so GeoServer is searching in the root of the file system. If you want it to look in the styles folder then you should just use the file name as shown here. If for neatness you chose to use a sub directory just use the sub directory name followed by the file name subdir/file.png


text:
Q: Looping through all sheets, getting error at end So I have a workbook with a master sheet and subordinate sheets and among other things (hence the choice = 7 thing) it calculates the totals for every row and every column of the data portion of the sheet as well as the total for all data. I have this part working but then when I went on to the next step/option of comparing the total of the master sheet to the sum of the totals of the subordinate sheets (with the addition of recalculating the totals of each sheet in case of changes or one wasn't filled out etc) I run into an error.
It executes the totals functionality well on every sheet and then it seems to run into an issue at the end of the loop. Not every sheet in this workbook is a data sheet and thus does not adhere to the specific layout the others are. Since these are not in any particular order, I have in my code to just skip them. It does this by intentionally catching the error that arises from working with something not adhering to the layout of the others and then skipping to the bottom of the loop.
At the moment I only have one of these extra sheets and I tried taking it out but it still gets an error near the end of the loop. The weird thing is that even though I have an error handling, it doesn't seem to be caught by it. k here is the sum of the subordinate totals, Position is just a max value (I wanted to make use of all my variables even if they weren't important in other functionalities), any odd numbers like MastLastRow - 6 is to account for the labels and other parts of the sheet that are not the data portion, and the flag part is making sure that someone didn't accidentally delete data. While I have multiple lines where I GoTo ErrCatch7: these just help me skip to the bottom and the only error that should come up anywhere in the code is when hitting an extra sheet. If you need any more possible clarification as to what in the code is doing what or need me to post a picture showing the spreadsheet let me know
ElseIf Fchoice = "7" Then
                k = 0
                Application.Calculation = xlCalculationManual
                Application.ScreenUpdating = False
                Application.DisplayStatusBar = False
                On Error GoTo ErrCatch7:
                MastLastRow = Sheets("Master").Range("A7").CurrentRegion.Rows.Count
                For Each WSCount In Worksheets
                    If WSCount.Name = "Master" Then
                        MastLastCol = Sheets("Master").Range("A5").CurrentRegion.Columns.Count
                        If Sheets("Master").Range("C7").Offset(MastLastRow - 7, 0) = "" Then
                            Sheets("Master").Range("C7").Offset(MastLastRow - 7, 0).EntireRow.ClearContents
                        End If
                        MastLastRow = Sheets("Master").Range("A7").CurrentRegion.Rows.Count
                        j = -1
                        i = 0
                        Set TempM = Range("H7")
                        Do While i < MastLastRow - 6
                            Set TempP = Range(TempM.Offset(0, 1), TempM.Offset(0, MastLastCol))
                            TempM.Value = Application.Sum(TempP)
                            Set TempM = TempM.Offset(1, 0)
                            i = i + 1
                        Loop

                        Do While j < MastLastCol - 8
                            Set TempP = Sheets("Master").Range(TempM.Offset(-1, 0), Sheets("Master").Range("I7").Offset(0, j))
                            TempM.Value = Application.Sum(TempP)
                            Set TempM = TempM.Offset(0, 1)
                            j = j + 1
                        Loop

                        Sheets("Master").Range("H7").Offset(MastLastRow - 6, 0).Font.ColorIndex = 6
                        Sheets("Master").Range("H7").Offset(MastLastRow - 6, 0).Interior.Color = RGB(0, 0, 255)
                        Sheets("Master").Range("H7").Offset(MastLastRow - 6, -1).Value = "Sheet Total"
                        GoTo ErrCatch7:
                    Else
                        Set MastData = Sheets("Master").Range("A7")
                        Set SubordData = WSCount.Range("A7")
                        SubordLastRow = WSCount.Range("A7").CurrentRegion.Rows.Count
                        SubordLastCol = WSCount.Range("A5").CurrentRegion.Columns.Count
                        If WSCount.Range("C7").Offset(SubordLastRow - 7, 0) = "" Then
                            WSCount.Range("C7").Offset(SubordLastRow - 7, 0).EntireRow.ClearContents
                        End If
                        SubordLastRow = WSCount.Range("A7").CurrentRegion.Rows.Count
                        Flag = True
                        If MastLastRow > SubordLastRow Then
                            Position = MastLastRow
                        Else
                            Position = SubordLastRow
                        End If

                        'Check if tasks in subordinate sheet have been mistakenly erased or misformated
                        Do While i < Position And j < Position
                            If MastData.Offset(i, 0).Value = SubordData.Offset(j, 0).Value Then
                                i = i + 1
                                j = j + 1
                            ElseIf MastData.Offset(i, 0).Value = SubordData.Offset(j, 0).Value And MastData.Offset(i, 0).Value = vbNullString Then
                                i = i + 1
                                j = j + 1
                            ElseIf MastData.Offset(i, 0).Value = vbNullString And SubordData.Offset(j, 0).Value <> vbNullString Then
                                i = i + 1
                            ElseIf SubordData.Offset(j, 0).Value = vbNullString And MastData.Offset(i, 0).Value <> vbNullString Then
                                j = j + 1
                            Else
                                Flag = False
                                Exit Do
                            End If
                        Loop
                        If Flag = False Then
                            MsgBox (OrgName + " appears to be missing tasks. This sheet will be ignored. Check for mistakes and compare totals later")
                            GoTo ErrCatch7:
                        End If
                        j = -1
                        i = 0
                        Set TempM = WSCount.Range("H7")
                        Do While i < SubordLastRow - 6
                            Set TempP = WSCount.Range(TempM.Offset(0, 1), TempM.Offset(0, SubordLastCol))
                            TempM.Value = Application.Sum(TempP)
                            Set TempM = TempM.Offset(1, 0)
                            i = i + 1
                        Loop

                        Do While j < SubordLastCol - 8
                            Set TempP = WSCount.Range(TempM.Offset(-1, 0), WSCount.Range("I7").Offset(0, j))
                            TempM.Value = Application.Sum(TempP)
                            Set TempM = TempM.Offset(0, 1)
                            j = j + 1
                        Loop

                        WSCount.Range("H7").Offset(SubordLastRow - 6, 0).Font.ColorIndex = 6
                        WSCount.Range("H7").Offset(SubordLastRow - 6, 0).Interior.Color = RGB(0, 0, 255)
                        WSCount.Range("H7").Offset(SubordLastRow - 6, -1).Value = "Sheet Total"
                    End If
                    k = k + WSCount.Range("H7").Offset(SubordLastRow - 6, 0).Value
    ErrCatch7:
                Next
                Application.Calculation = xlCalculationAutomatic
                Application.ScreenUpdating = True
                Application.DisplayStatusBar = True
                MsgBox ("Master sheet hourly total = " + Sheets("Master").Range("H7").Offset(SubordLastRow - 6, 0).Value + ": Sum of subordinate sheets = " + k)

A: I believe your problem might be because you are trying to use ErrCatch7 as an error handler.
I suggest you replace "On Error GoTo ErrCatch7" with "On Error GoTo ErrCatch7Err", then include a section at the very end of your procedure (after an Exit Sub or Exit Function) which says:
ErrCatch7Err:
    Resume ErrCatch7

Edit:  Based on what Maciej Los just said, it is also a problem that your error handler is enabled while outside the For Next loop as well as inside it.  I would recommend that you use
    ...
    For Each WSCount In Worksheets
        On Error GoTo ErrCatch7Err
        ...
        ... (other code, including "GoTo ErrCatch7" statements if needed)
        ...
ErrCatch7:
    Next
    On Error GoTo 0
    ...
    Exit Sub
ErrCatch7Err:
    Resume ErrCatch7

If you want an error handler to cover errors in the
MastLastRow = Sheets("Master").Range("A7").CurrentRegion.Rows.Count

statement which occurs before your loop starts, use a different handler.  (You would want different actions to be performed in that case anyway, so using the same handler makes no real sense.)
As an example of the difference between using ErrCatch7 as the target of the On Error condition, and using a separate label as the target, consider the following two code samples:
Sample 1:
Sub TestMe()
    On Error GoTo ErrCatch7
    For i = 1 To 10
        MsgBox i
        j = i / 0
        MsgBox j
ErrCatch7:
    Next i
End Sub

Sample 2:
Sub TestMe()
    On Error GoTo ErrCatch7
    For i = 1 To 10
        MsgBox i
        j = i / 0
        MsgBox j
ErrCatch7:
    Next i
    Exit Sub
ErrCatch7Err:
    Resume ErrCatch7
End Sub

Sample 1 will display the number 1, then (while still handling the "1 / 0" error) 2, then (while attempting "2 / 0") give a division by zero error.
Sample 2 will display all the numbers from 1 to 10.

A: MSDN documentation states:

You jumped into the middle of a For...Next loop. Remove the jump into the loop. Placing labels inside a For...Next loop isn't recommended.

The issue is here:

           'before loop
            On Error GoTo ErrCatch7:
            MastLastRow = Sheets("Master").Range("A7").CurrentRegion.Rows.Count
            For Each WSCount In Worksheets
            ....
            'jump into the loop is here
       ErrCatch7:
            Next

The simplest way to resolve your problem is to debug programme using F8 key.

A: As answered here and here:

With the code as shown, you're actually still considered to be within
  the error handling routine when you strike the next statement.
That means that subsequent error handlers are not allowed until you
  resume from the current one.

A better architecture in your case would be something like:
        'before loop
        On Error GoTo ErrCatch7
        MastLastRow = Sheets("Master").Range("A7").CurrentRegion.Rows.Count
        For Each WSCount In Worksheets
        ....
   NextWorksheet:
        Next
        ' the rest of your code

   ErrCatch7:
        Resume NextWorksheet

As also already mentioned in the answers above, you can find a great explanation about the problem in this site


text:
Q: achieving fast performance using polymorphism and functors in c++ I am currently writing a Maya 2013 plugin in c++ that optimizes the geometry of given mesh for specific constraints. i need to achieve maximum performance. for now i only implemented an hard-coded version of the algorithm for a specific constraint and it's very fast, but i need achieve some king of generic implementation of the algorithm for any given constraint (thus i need some kind of polymorphism).
a pseudo code for the general structure of the algorithm is:
(1) do k times:
(2)      for every face fj in the mesh do:
(3)            some manipulation on the vertices qi incident to the face fj
(4)      for every vertex  vi in the mesh do:
(5)            some manipulation  on the faces fj incident to the vertex vi

the problem is that in my specific implementation there is no function calls for the calculations in steps 3 and 5 in the pseudo code, when i tried calculating those steps with auxiliary functions there was a big reduction on performance.
for a generic implementation i need to make function calls in steps 3 and 5 for every constraint.
i thought of two kinds of solutions:

*

*write a generic class for constraints. derive classes for every constraint i need with methods for calculaing steps 3 and 5 in the algorithm.

*write a general functor (class with only the () operator) and derive from it functors for calculating steps 3 and 5. the reason for this idea is that the call for the () operator in a functor is inlined (answer about reusable code in this link).

first question:

is there any way to reduce the overhead for the function calls?

second question:

is there any way to make the compiler always inline the functions in
  the two solutions above? from this question i know that virtual
  functions called from pointers to objects can't be inlined.

third question:

is there a more efficient way then the solutions i proposed?

A: I would recommend you take look at templates and pass a template function/functor as a parameter.
With dynamic polymorphism you almost always have indirect call to function, ie the body of the function isn't known to compiler - hence optimization options are limited.
Templates allow you to do what is called a static polymorphism.
see these links for more info:
Static polymorphism definition and implementation
C++ templates for performance?


text:
Q: How to show that $\left \| AB \right \|_F \leq \min (\left \| A \right \|_F \left \| B \right \|_2 , \left \| A \right \|_2 \left \| B \right \|_F)$? For any matrices $A \in \mathbb{C}^{m \times k}$ and $B \in \mathbb{C}^{k \times n}$, show that $\left \| AB \right \|_F \leq \min (\left \| A \right \|_F \left \| B \right \|_2 , \left \| A \right \|_2 \left \| B \right \|_F)$ where $\left \| \cdot \right \|_F$ and $\left \| \cdot \right \|_2$ are the Frobenius-norm and 2-norm, respectively, defined as:
$\left \| A \right \|_F = \sqrt{\mathrm{trace} \left ( A^H A \right )}$,
$\left \| A \right \|_2 = \sqrt{\lambda_{max} \left ( A^H A \right )}$

A: For sake of having an answer, let us turn cardinal's comment into one. By definition, $\|AB\|_F^2 = \operatorname{tr}\left((AB)^\ast(AB)\right) = \operatorname{tr}\left(B^\ast A^\ast AB\right)$. Since $A^\ast A$ is positive semidefinite, it has nonnegative eigenvalues and can be unitarily diagonalized as $A^\ast A=U^\ast\Lambda U$, where $\Lambda$ is a nonnegative diagonal matrix containing the squared singular values of $A$. Using the property $\operatorname{tr}(XY)=\operatorname{tr}(YX)$, we get $\|AB\|_F^2 = \operatorname{tr}(\Lambda UBB^\ast U^\ast)$. As the diagonal entries of both $\Lambda$ and $UBB^\ast U^\ast$ are nonnegative, we have
$$
\|AB\|_F^2 = \operatorname{tr}(\Lambda UBB^\ast U^\ast)\le(\max_i\Lambda_{ii})\operatorname{tr}(UBB^\ast U^\ast)
=\|A\|_2^2\|B\|_F^2.
$$
Hence $\|AB\|_F\le\|A\|_2\|B\|_F$. The counterpart inequality can be proved by unitarily diagonalizing $BB^\ast$.


text:
Q: VueJs: Using component inside another component I'm trying to make use of the main component inside another with pre-defined properties.
Here's what I'm trying to achieve, but I'm just getting an empty div as a result.
<template>
    <call-dialog-link
        :id="id"
        :url=url"
        message="Are you sure you wish to remove this record?"
        label="Remove"
        css-classes="alert"
    ></call-dialog-link>
</template>

Here's the CallDialogLink component
<template>

</template>

Any idea what I'm doing wrong?

A: I believe there is typo in your code.
<template>
    <call-dialog-link
        :id="id"
        :url="url" // didn't open the double quote here
        message="Are you sure you wish to remove this record?"
        label="Remove"
        css-classes="alert"
    ></call-dialog-link>
</template>


text:
Q: How to Extract zip file I am working on WPF application using framework 4.0 . I am downloading Zip file using following code
 public void DownloadZip(string _URL, string zip_local_path)
    {

        try
        {

            WebClient webClient = new WebClient();
            webClient.Headers.Add(HttpRequestHeader.UserAgent, "blah");
            webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(webClient_DownloadDataCompleted);
            // Specify a progress notification handler.
            webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
           // isDownloading = true;
            this.zip_local_path = zip_local_path + "/" + _URL.Substring(_URL.LastIndexOf("/") + 1);
            webClient.DownloadDataAsync(new Uri(_URL));

        }
        catch (WebException ex)
        {

        }
    }

 void webClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
    {
      zipData=  e.Result;
   //Save Zip file in local drive.
      File.WriteAllBytes(this.zip_local_path, zipData);
      FileInfo fi = new FileInfo(this.zip_local_path);
      DirectoryPath=  Decompress(fi, this.img_isometric);
      //isDownloading = false;
      //isDownloaded = true;
     }

here zipData variable hods holds all bites of zip file .
      Now my question is : Is it possible to extract zip file directly from from bites & save the extracted file only .


text:
Q: drag drop between Swing & JavaFX I want to do drag/drop from swing component to JavaFX 2 component is that posible?
My application is swing and use a JFXPanel to display a LineChart, i want to drop data from a Jtable to the chart.
I try to set the transfer handler on the JFXPanel but that doesn't seems to work.
Clarification:
setTransferHandler(new TransferHandler());

I just do that on the main JFrame to intsall a custom transfer handler, in the frame there a table and a JFXPanel with the LineChart, i can drop objects onto the table but not onto the chart.
Not sure if i need to implement something on JavaFX side, so that the chart in the JFXPanel also accept the drop.
Basically i just want to drop on any place of my window, the result will be the same in my case, the drooped object will be added to the underlying model.


text:
Q: Alfresco and Google chart I use alfresco 5.2 and I install google graphs using instruction
https://code.google.com/archive/p/statistics-and-graphs/downloads
First I add in alfresco-global.properties
## AUDIT
audit.enabled=true
audit.alfresco-access.enabled=true

than

*

*
*

*Put the provided AMP, 'Statistics.amp', into /amps_share .

*
*

*Run /apply_amps

*
*

*Restart Alfresco

I got in admin console statistics&graphs and when clik on statistics&graphs i got error

The Web Script /share/service/extras/components/console/statistics has    responded with a status of 500 - Internal Error.

500 Description:    An error inside the HTTP server which prevented it from fulfilling the request.

Message:    01180016 Failed to execute script 'classpath*:alfresco/site-webscripts/com/devcom/components/console/statistics.get.js': 01180015 ReferenceError: "response" is not defined. (file:/C:/alfresco-community/tomcat/webapps/share/WEB-INF/classes/alfresco/site-webscripts/com/devcom/components/console/statistics.get.js#2104)
Server: Spring WebScripts - v6.11.0 schema 1.000
Time:   18.02.2017. 23.30.54

Diagnostics:    Inspect Web Script (com/devcom/components/console/statistics.get)

A: I tried to install it in my local Alfresco too. But this module is quite old, and don't seem to be maintained anymore. I had to do minor changes to be able to see something:

*

*In the file Statistics_project/config/alfresco/site-webscripts/com/devcom/components/console/statistics.get.js:

*

*Line 5 and 147: I deleted the variable site

*Line 6: In the URL, I removed the parameter &limit=0
Then, I was able to open the page. But I had an error message. I had to change the file Statistics_project/source/web/scripts/statistics.js:

*

*Line 114: In the URL, I removed the parameter &limit=0.

Then I was able to open the page, and select a site but nothing is displayed:
Screenshot
I recommend you to look at this plugin:
https://addons.alfresco.com/addons/alfresco-audit-analysis-and-reporting-aaar


text:
Q: Kontsevich's lecture at Rutgers (1996) Reading some papers about (homological) mirror symmetry I have found the reference to the unpublished Kontsevich's lecture at Rutgers University (Nov 11, 1996). I would like to know if someone has some notes of this lecture. I really want to know in some detail (as far as possible) what Kontsevich said in that talk. I think it is not easy to find notes of the talk (15 years after!) but I would also appreciate comments about it (for example, the main ideas presented, etc)
Thanks in advance


text:
Q: Can't Update Dijit Widget copied into a Dialog I'm slowly building up the functionality of a popup dialog containing a form. It works with one exception. In the onClick event on the button, I want to update a value in the form. It updates the value, but only in the div (emailForm) that was input into the form. I have the div set to display so I can see the update. How do I update it in the myDialog object?

Contact Form

Feel free to drop us a line.

<form id="contact-form" action="confirmation.php" method="post">
    <fieldset class="contact-fieldset">

                To:
                <input id="to" name="to" type="text" size="40" value="Staff" disabled>

                Message:
                <textarea id="message" name="message"></textarea>

        <input type="submit" class="contact-submit" value="Send">
    </fieldset>
</form>

Update
Based on tik27's description of the problem, I tried the following test:

This fixes the problem. The html shown is only a small test of the complete form. How can I keep the html separate from the script and then bring it in without duplicating the id's? I looked into templates, but that seems overkill.
Update 2
Again, based on some Tik27 suggested, I tried this:

The browser ignores anything in the text/template script so the id's only added once to the DOM. Do a search on this site for more information on the script type.

A: The problem here with the way you are doing this, is that there ends up being to inputs with the id="to".  Ids are supposed to be unique in html.  If you want to do it this way, i suggest that you put your form info into a script tag with type="text/template".
But is there a reason you just don't create it declaratively?

Contact Form

Feel free to drop us a line.

<form id="contact-form" action="confirmation.php" method="post">
    <fieldset class="contact-fieldset">

                To:
                <input data-dojo-type="dijit.form.TextBox" data-dojo-props="readOnly: 'readOnly' , value:'Staff'" id="to" name="to" type="text" size="40">

                Message:
<textarea id="message" name="message" data-dojo-type="dijit.form.Textarea" data-dojo-props="placeholder: 'Your message'"></textarea>

        <input type="submit" class="contact-submit" value="Send">
    </fieldset>
</form>

Show

Fiddle:: http://jsfiddle.net/ZJ735/