text:
Q: Talend greenplumRow error handling I want to create views in greenplum HAWQ using a simple talend job, that would basically have a fileinput that contains all the views then I need to execute the CREATE VIEW script.
Since these views (50-60.000) come from an oracle system I need to find the ones that we were unable to create.
Here's a mock up for my problem:

I have a view already in the DB, and I want to create it 3 more times. This would obviously fail.
Here's the output:
Exception in component tGreenplumRow_2
org.postgresql.util.PSQLException: ERROR: relation "ad_apps_dependencies" already exists
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:1592)
.--------------.
|  tLogRow_4   |
|=------------=|
|componenterror|
|=------------=|
|componenterror|
'--------------'

.-----------------------------------------------------+-------------------------------------------------------------.
|                                                                                tLogRow_5                        |
|=----------------------------------------------------+------------------------------------------------------------=|
|result                                               |result1                                                      |
|=----------------------------------------------------+------------------------------------------------------------=|
|ERROR: relation "ad_apps_dependencies" already exists|CREATE VIEW SYSTEM.AD_APPS   AS SELECT * FROM APPLSYS.AD_APPS|
'-----------------------------------------------------+-------------------------------------------------------------'

.------------.
| tLogRow_6  |
|=----------=|
|subjobError |
|=----------=|
|Subjob Error|
'------------'

I want to have this output 3 times, as I try to run 3 times the query. (In the final version I'd create another file that contains only the queries that failed, so we can fix it later, but this is a crucial point.)
As a workaround:
I could move this tRow -> OnError -> FixedFlow -> FailedViews part into a different job, but thats not an elegant solution.

A: Do it with tJavaFlex. It works for Greenplumrow as well!!! In the below exmaple I execute a query in tOracleInput_6:
"SELECT count(*) FROM "+((String)globalMap.get("ora_sch.SCHEMA_NAME")) + "." + ((String)globalMap.get("ora_tab.TABLE_NAME"))

I am not sure about query result. It might fail (eg:someone just dropped the table) therefore i use tJavaFlex+iterate connection! The resulting code generated try {...} catch block.
In below case i iterate over tables of a schema and count the rows in every table. I collect the exceptions into a java hashmap. (the hashmap is in the context, but that's another story)

tJavaFlex Begin code:
try{

tJavaflex main code:
// here is the main part of the component,
// a piece of code executed in the row
// loop
System.out.println(((String)globalMap.get("TYPE"))+" SELECT count(*) FROM "+((String)globalMap.get("ora_sch.SCHEMA_NAME")) + "." + ((String)globalMap.get("ora_tab.TABLE_NAME")));

tJavaFlex1 End code:
// end of the component, outside/closing the loop
} catch (Exception e) {
//put
((Map<String, String>)context.EXCEPTIONS).put(
  ((String)globalMap.get("TYPE"))+((String)globalMap.get("ora_sch.SCHEMA_NAME"))+"_"
  +((Integer)globalMap.get("tFlowToIterate_8_CURRENT_ITERATION")).toString(),
((String)globalMap.get("ora_sch.SCHEMA_NAME"))+","
+ ((String)globalMap.get("ora_tab.TABLE_NAME")));

//print some debug message
System.out.print(((String)globalMap.get("TYPE"))+" ### SQL Exception at ");
System.out.print("Iteration Number: "+((Integer)globalMap.get("tFlowToIterate_8_CURRENT_ITERATION")).toString()+","+((String)globalMap.get("ora_sch.SCHEMA_NAME"))+","+ ((String)globalMap.get("ora_tab.TABLE_NAME")));
System.out.println(" ###");
//e.printStackTrace();
}


text:
Q: set and reset index in pandas dataframe not working import numpy as np
import pandas as pd
np.random.seed(121)
randArr =np.random.randint(0,100,20).reshape(5,4)
df =pd.DataFrame(randArr,np.arange(101,106,1),['PDS','Algo','SE','INS'])
df.index.name='RollNo'
print(df)
print("")
df.reset_index()
print(df)
print("")
df.set_index('PDS')
print(df)
print("")

Output:(not coming as expected)
        PDS  Algo  SE  INS
RollNo
101      66    85   8   95
102      65    52  83   96
103      46    34  52   60
104      54     3  94   52
105      57    75  88   39

        PDS  Algo  SE  INS
RollNo
101      66    85   8   95
102      65    52  83   96
103      46    34  52   60
104      54     3  94   52
105      57    75  88   39

        PDS  Algo  SE  INS
RollNo
101      66    85   8   95
102      65    52  83   96
103      46    34  52   60
104      54     3  94   52
105      57    75  88   39

A: You need assign the result back
df = df.reset_index()

df = df.set_index('PDS')

Or you can use inplace argument
df.reset_index(inplace=True)

df.set_index('PDS', inplace=True)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I add quotes, commas, and spaces after each word in a ms-word list? I am trying to add quotes and a comma after each word in a word document.
For example:

apple
banana
carrot

Goes into:

"apple",
"banana",
"carrot",

What should I put in the find section and replace section to arrive at this outcome?

A: On LibreOffice Writer you can press CTRL + H to open the find and replace tool.
You must enable regular expression and configure as following:
Find: (\w+)
Replace: "$1"
And then press replace all.
I am sure you can do it on ms-word as well.

A: Not sure why you have both JavaScript and Java tags in your question, but I will assume you meant Java. A possible solution to what you want to do using Java:
1) Lets first read in the file with the words and create a way to write out the result:
String contents = new String(Files.readAllBytes(Paths.get("path-to-input"))); // input
BufferedWriter writer = new BufferedWriter(new FileWriter("path-to-output")); // output

2) We've read the contents of the file as a single String, lets split it now into individual words. We will do this by splitting by carriage return and newline (depending on your file, only newline may be sufficient):
String[] splitContents = contents.split("\r\n");

3) Let's change the Strings in the array above to the ones that we want to see in our file. Then output them to file:
    for(int i = 0; i < splitContents.length; i++) {
        splitContents[i] = "\"" + splitContents[i] + "\","; //create new string
        writer.write(splitContents[i]); //write new string to file
        writer.newLine(); //append newline
    }

4) And don't forget to flush() and close() the writer:
writer.flush();
writer.close();


text:
Q: OpenCV: The result of findContours cannot be filled I use the OpenCV and findContours method to find the contour of the polygon that can be filled.   Basically the result image should look the same as an input. The image I provide is already black and white, so it doesn't need to be converted to grayscale.
The issue I'm having is that the result of findContours cannot always be filled. The drawContours can draw nice contours, but the thickness = FILLED works only sometimes (meaning it doesn't work in the presented example, but it can work on similar input). Initially blurring the image, increases the chance of success, but it's still not a very reliable solution.

// blur( src_gray, src_gray, Size(2,2) ); - blurring an image with different kernel sizes might help sometimes

Canny( src_gray, canny_output, thresh, thresh*2, 3 );
findContours( canny_output, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );

Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );
for(int i = 0; i <contours.size(); i++ ) {
    drawContours( drawing, contours, i, Scalar(255, 255, 255), FILLED, 8);
}

I tried to verify what's wrong with result contours after converting it to a polygon with BOOST library and it tells me that the Geometry has invalid self-intersections or it has spikes. In this case it's unable to correct it.
Is there any better solution that can give me filled shape, assuming that drawing just contours works really well?

A: If you replace the i variable in the drawContours() function with -1, you can get a filled polygon. you must delete for cycle.
Canny( src_gray, canny_output, thresh, thresh*2, 3 );
findContours( canny_output, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );

Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );
drawContours( drawing, contours, -1, Scalar(255, 255, 255), FILLED, 8);


text:
Q: std::function works beautifully with std::bind - but why? I was using a std::uniform_int_distribution to generate primes (p). I put the distribution object in an anonymous namespace - which seems like C++ 'static linkage' for grown-ups...
namespace
{
    // a more pedantic range: [2, 18446744073709551557]
    std::uniform_int_distribution<uint64_t> p_dist {2};

    std::mt19937 rng; // (sufficient IV states for uniqueness)
}

Note, that I seed the Mersenne Twister as thoroughly as portable code will allow. This isn't really important to the question though. It's just to assure the reader I'm using the random facilities properly:
std::seed_seq::result_type data[rng.state_size];
std::random_device rdev;

std::generate_n(data, rng.state_size, std::ref(rdev));
std::seed_seq rng_seed (data, data + rng.state_size);
rng.seed(rng_seed);

This is very convenient, as I have a deterministic u64_prime(p) function, using (7) bases, that can determine if (p) is prime:
uint64_t p;
while (!u64_prime(p = p_dist(rng)))
    ;

Now I create a std::function object:
std::function<uint64_t()> zp_rng = std::bind(
    decltype(p_dist){0, p - 1}, std::ref(rng));

This function: zp_rng() can be invoked to return a random number in Z(p). That is, using the distribution object for: [0, p - 1] from the results of the referenced rng.

Now this is very impressive - but I've effectively adopted it by cut-and-paste with little understanding of the interaction between std::function and the interaction of the parameters given to std::bind.
I'm not confused by decltype(p_dist){0, p - 1} - that's just a way to specify we still want to use a std::uniform_int_distribution. My understanding of std::ref(rng) is that it prevents a local copy of the rng being instantiated, and forces the use of reference instead... so:

Q: What are the basic rules that effectively determine: dist(rng) being used - I don't see why std::bind would enforce this interaction. A lot of interactions seem based around operator () methods.
Q: std::function is helpfully referred to as 'a general-purpose polymorphic function wrapper' on cppreference.com. So is it a function that encapsulates a uint64_t return type? Or again, making use of operator () syntax to drive the notion of a function?
As incredibly useful as these constructs are, I feel like I'm cargo-cult programming to a degree here. I'm looking for an answer which resolves any ambiguities in a concrete way, and adds insight to similar questions - how are bind arguments expected to interact, and how does the function signature reflect that?

I'm not getting any positive feedback about the use of std::bind. Plenty on the superior results (and code generation) of simply using lambda functions, even in such a simple case. My own tests validate this.

A: std::bind is kind of irrelevant to std::function, all it does is wrap something callable so that a certain set of parameters is always passed, see https://en.cppreference.com/w/cpp/utility/functional/bind
std::function just takes anything callable which fits the function signature that you specify as its template arguments.
std::uniform_int_distribution is callable because it has a operator() specified, see https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution/operator() . That specifically takes a Generator. We use bind to create a wrapper around that so that we don't always have to pass the generator explicitly. The result is then stored in the std::function matching the uint64_t return type and no arguments (as the generator argument is bound).
If this concept is foreign to you, you should read up on operator overloading, see https://en.cppreference.com/w/cpp/language/operators (specifically Function call operator).

A: There is no need to use std::bind in modern C++ - use a lambda instead:
// NOTE: p and rng are captured by reference and must outlive zp_rng!
std::function<uint64_t()> zp_rng = [&]() { return decltype(p_dist){0, p - 1}(rng); };

As for std::bind and std::function instances, they are callable function objects, i.e. they have operator().

A:
Q: What are the basic rules that effectively determine: dist(rng) being used - I don't see why std::bind would enforce this interaction. A lot of interactions seem based around operator () methods.

std::bind performs function composition. The first argument must be a function object, i.e. something callable like a function (e.g. a normal function, or a class with an overloaded operator()).
A call to std::bind makes copies of its arguments, "binds" the copies of the arguments to the first argument (the function object), and returns a new function object that will invoke the copy of the function object.
So in a simple case:
int f(int i) { return i; }
auto f1 = std::bind(f, 1);

this binds the value 1 to the function f, creating a new function object that can be called with no arguments. When you invoke f1() it will invoke f with the argument 1, i.e. it will call f(1), and return whatever that returns (which in this case is just 1).
The actual type of the thing returned by std::bind(f, 1) is some implementation-specific class type, maybe called something like std::__detail::__bind_type<void(*)(int), int>. You're not meant to refer to that type directly, you would either capture the object using auto or store it in something else that doesn't care about the precise type, so either:
auto f1 = std::bind(f, 1);

or:
std::function<int()> f1 = std::bind(f, 1);

In your more complex case, when you call std::bind(decltype(p_dist){0, p - 1}, std::ref(rng))) you get a new function object that contains a copy of the temporary decltype(p_dist){0, p - 1} and a copy of the reference_wrapper<std::mt19937> created by std::ref(rng). When you invoke that new function object it will call the contained distribution, passing it a reference to rng.
That means it is callable with no arguments, and it will call the contained random number distribution with the contained random engine, and return the result.

Q: std::function is helpfully referred to as 'a general-purpose polymorphic function wrapper' on cppreference.com. So is it a function that encapsulates a uint64_t return type?

A std::function<uint64_t()> is a wrapper for a function object that is callable with no arguments and that returns a uint64_t (or something implicitly convertible to uint64_t). It can be used to store a copy of an arbitrary function object that is copy constructible, and callable with no arguments, and returns something convertible to uint64_t.
(And more generally, a std::function<R(A1, A2 ... AN)> is a wrapper for a function object that returns R when called with N arguments, of types A1, A2 ... AN.)
Since the result of your std::bind call is a copy constructible function object that is callable with no arguments and returns a uint64_t, you can store the result of that std::bind call in a std::function<uint64_t()>, and when you invoke the function it will invoke the result of the bind call, which will invoke the contained distribution, and return the result.

Or again, making use of operator () syntax to drive the notion of a function?

I'm not sure what this means, but in general it's true that in C++ we often talk about "function objects" or "callables" which are generalisations of functions, i.e. something that can be invoked using function call syntax, e.g. a(b, c)

A: I'm quoting from A Tour of C++
what is bind():

A function adaptor takes a function as argument and returns a function
  object that can be used to invoke the original function. The standard
  library provides bind() and mem_fn() adaptors to do argument
  binding, also called Currying or partial evaluation. Binders were
  heavily used in the past, but most uses seem to be more easily
  expressed using lambdas.
double cube(double);
auto cube2 = bind(cube,2);

A call cube2() will invoke cube with the argument 2, that is,
  cube(2)
A bind() can be used directly, and it can be used to initialize an
  auto variable. In that, bind() resembles a lambda.
If we want to assign the result of bind() to a variable with a
  specific type, we can use the standard library type function. A
  function is specified with a specific return type and a specific
  argument type.
The standard library function is a type that can hold any object you
  can invoke using the call operator (). That is, an object of type
  function is a function object.

So std::function is a function object. A function object is used to define objects that can be called like functions.
and this is an example of function object:
template<typename T>
class Cube2 {
const T val; // value to compare against
public:
Cube2 (const T& v) :val(v) { }
double operator()(const T& x) const { return pow(x,3); } // call operator
};

And
auto cube2 = bind(cube,2); is like saying Cube2<int> cube2{2};


text:
Q: How to remove or include errorbar plot from matplotlib axes? This code shows an Attribute error:
I am plotting errorbar plot for let's say 10 different datasets (huge datasets) from a file containing multiple datasets (let's say for different days), and I am showing the user an option (Checkbox) to remove or include a plot of the particular dataset (through GUI).
So for this, I just want to erase the current axes and at a later time want to redraw it again.
How can I do this?
Below is a simplified example to show what I need.
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1)
x, y, yerr = np.random.rand(3,10)
l  = ax.errorbar(x, y, yerr, marker='s', mfc='red', mec='green', ms=20, mew=4)

canvas = fig.canvas
canvas.draw()
bkg = canvas.copy_from_bbox(ax.bbox)

plt.show()
plt.pause(1)

ax.clear()
canvas.restore_region(bkg)
ax.draw_artist(l)

# here it throws an AttributeError: 'ErrorbarContainer'
#object has no attribute 'draw'


text:
Q: Is there a technical reason not to use a TWebBrowser in Delphi to view Google Earth? I do hope that this is not deleted as subjective. The only subjective part might be that 1) my Delphi is better than my PHP and 2) I prefer compiled to interpreted programming languages.
However, the actual (non-subjective) question is - if I choose Delphi and use a TWebBrowser (or similar mechanism) to view/manipulate Google Earth, will I be restricting my available functionality in any way?
Are there some things that I can only do "in a browser" that I can't do "in a VCL browser component"?
[Update] I forgot to say that 1) I am comfortable with Windows only and, 2) the Google Earth functionality is only one part of a larger APP (for me, it is easier to implement that app as a Delphi program than something browser based, but that sounds subjective again, which is why I never mentioned it. I'll just stick with "if I choose Delphi and use a TWebBrowser will I be restricting my available functionality in any way?" as the question, since that can be answered.

A: There is no technical reason why not to use the TWebBrowser to display maps, or anything for that matter. In fact, this is a matter of opinion, and most likely you have heard people's opinions telling you not to do so. Unfortunately, Stack Overflow is a Question/Answer site, so a question like this isn't necessarily feasible.
The TWebBrowser wraps an Internet Explorer browser window, and relies on whatever version of IE is installed. Anything which you can open in Internet Explorer can also be opened in the TWebBrowser, Google Earth included. It's a matter of pointing it to a page and loading it. As for technical reasons, there may be some glitches here and there, but I don't see why not.

A:
Are there some things that I can only do "in a browser" that I can't do "in a VCL browser component"?

The short answer is, that if you know the TWebBrowser (IE based) / DelphiChromiumEmbedded (Webkit) inside-out you are not limited.
Two major browsers I know of, are based on TWebBrowser/IE control - Avant Browser (written in Delphi) and
Maxthon (I have used both, and they served me very well, until I completely switched to FF) - never had any compatibility issues with them (compared to IE application).
A good starting point will be the TEmbeddedWB -  This package wraps the IWebBrowser interface  and Control Library (SHDOCVW.DLL) to allow you to create a customized Web browsing application.
One very important issue, the Web Browser Control has, that it uses IE 7 rendering mode by default. so you will need to specify the IE rendering mode for your own application (see this article). There are other issues but most of them could be configured and customized via the registry FeatureControl keys:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl

A: Yes, there is one - Chromium Embedded Framework (CEF) is much high performance than IE, especially in the case where your end user's using an earlier version of IE.
CEF is based on Google's open source project Chromium.
I'm using CEF in LIVEditor (my new live html editor) and the result is very very good!.
But note that you'll have to distribute an additional 20 MB files when compressed.


text:
Q: Create DataFrame from Loop with Bloomberg function I have a list of company ticker's:
df = {'Ticker': ['AVON LN EQUITY', 'GFS LN EQUITY'], 'Value': [1., 2.]}
df = pd.DataFrame(df)

I am using the BLPAPI wrapper, https://github.com/alex314159/blpapiwrapper
Using this i would like to get a DataFrame, of all the prices over on a monthly basis. For this i am using the BLP class and BDH function. Settings below (the longer version is in the link):
def bdh(self, strSecurity='SPX Index', strData='PX_LAST', startdate=datetime.date(2013, 1, 1), enddate=datetime.date(2016, 9, 6),
        adjustmentSplit=False, periodicity='MONTHLY', strOverrideField='', strOverrideValue=''):

for simplicity i created a mini function:
def bloom_func(x, func):
    bloomberg = BLP()
    return bloomberg.bdh(x, func, strOverrideField='BEST_FPERIOD_OVERRIDE', strOverrideValue='1GY' )
    bloomberg.closeSession()

Using these i can get a DataFrame for one equity.
Price = bloom_func('VOD LN EQUITY', 'PX_LAST')
print (c)

which works.
However, when i try to run this in a across the 2 companies using:
df1 = pd.concat([df.apply(lambda x: bloom_func(x)) for p in df['Ticker']])

i get ValueError: Shape of passed values is (2, 0), indices imply (2, 2).

A: Was simpler than I thought
for d in df['Ticker']:
    x[d] = bloom_func(d)


text:
Q: State machine spring I need to create StateMachine to manage quests. I know how to create a state machine, but I can not use it. It's my first state machine and first project with the MongoDB.
My state machine:
@Configuration
@EnableStateMachine
class QuestStateMachineConfig : EnumStateMachineConfigurerAdapter<QuestState, QuestEvent>() {

    @Throws(Exception::class)
    override fun configure(states: StateMachineStateConfigurer<QuestState, QuestEvent>) {
        states.withStates()
                .initial(QuestState.AWAITING)

                .state(QuestState.ASSIGNED)
                .state(QuestState.MARKED_TO_REJECT)
                .state(QuestState.IN_PROGRESS)

                .end(QuestState.DONE)
                .end(QuestState.REJECTED)
    }

@Throws(Exception::class)
override fun configure(transitions: StateMachineTransitionConfigurer<QuestState, QuestEvent>) {
    transitions.withExternal()
            .source(QuestState.AWAITING).target(QuestState.ASSIGNED).event(QuestEvent.ASSIGN)
            .and()
            ...
   }

I need to create a quest with state AWAITING, next I have to modify and save it in a database when a user uses update action. How to do it? And how can I listen to onSuccess callback of this operation?

A:
I need to create a quest with state AWAITING

This normally should be an Entity created in the DB.
You probably want to manage this Entity's State using the state machine.
To get an instance of the SM you only need to inject it - you have already defined an instance because of @EnableStateMachine - upon starting your application an SM will be created and you can inject it where you need it.

"I have to modify and save it in a database when a user uses update
action. How to do it?"

At some point the "update action" needs to translate to "update event".
There's a lot of options here, depending on your needs:

*

*update the quest in the DB the normal way (e.g. repository) and then move the state token in the SM to the correct state, for that user's quest (you will need some way to correlate the user, the quest and the SM instance).

*upon "update action" - send event to the SM and let the SM update the quest in the DB and transition to a new state. This can be achieved using "actions" or listening to specific event and reacting on it using SM "listener".

how can I listen to onSuccess callback of this operation?

See StateMachineListener for starting point, also check out this answer.


text:
Q: simple function which should close the tab doesn't work (not a function) I have a simple function, which should close the tab if a user clicks a button. For some reason, I keep getting an error that it is not a function.
It's a simple function, and I have no idea why it wouldn't work...

Uncaught TypeError: deny is not a function at HTMLButtonElement.onclick (login.html:183)

Any help would be welcome
EDIT: Thanks for pointing to other threads. It might be true that it wouldn't close the window. BUT why does it say that deny is not a function?

function deny(){
  console.log("deny function executed.. :D ");
 window.close();
};
<button id="deny" onclick="deny()">
 Close
</button>

A: window.close() will not work on windows that weren't opened with the window.open() method

A: Scripts may close only the windows that were opened by it. So you cannot close the current window by window.close() method.
Please refer this link.
window.close and self.close do not close the window in Chrome


text:
Q: Why is this algorithm for bracket balancing wrong? I wrote a PHP function that counts whether a string contains the right numbers of pairs of brackets. I tested it and it works properly, but the website I'm answering says that this is wrong. Help me debug why?
function bracketBalancer ($string) {
  for ($i=0; $i<strlen($string); $i++) {
    if ($string[$i] == '(') {
      $parentheses++;
    } elseif ($string[$i] == '{') {
        $curly++;
    } elseif ($string[$i] == '[') {
        $square++;
    } elseif ($string[$i] == ')') {
        $parentheses--;
    } elseif ($string[$i] == '}') {
        $curly--;
    } elseif ($string[$i] == ']') {
        $square--;
    }
  }
  if (!$parentheses && !$curly
      && !$square) {
     return true;
  }
  return false;
}

A: Personally, I would have probably used some of the built in string functions to do comparisons with like this:
function bracketBalancer ($string)
{
    $ret=true;
    if(substr_count($string, '(') != substr_count($string, ')'))
    {
        echo "Parentheses don't match...\r\n";
        $ret=false;
    }
    if(substr_count($string, '{') != substr_count($string, '}'))
    {
        echo "Curlies don't match...\r\n";
        $ret=false;
    }
    if(substr_count($string, '[') != substr_count($string, ']'))
    {
        echo "Squares don't match...\r\n";
        $ret=false;
    }
    return $ret;
}

But as I said, there are a hundred ways to write code that does the same thing.
And on that note, looking at the code, it's bloody horrible, so here is a somewhat cleaner function:
<?php
    function bracketBalancer ($string)
    {
        $match=array(
            'Parentheses' => array('(', ')'),
            'Squares' => array('[', ']'),
            'Curlies' => array('{', '}')
             );
        $ret=true;
        foreach($match as $key=>$val)
        {
            if(substr_count($string, $val[0]) != substr_count($string, $val[1]))
            {
                echo $key." don't match.\r\n";
                $ret=false;
            }
        }
        return $ret;
    }

    $string='[{][)}[[}}[][))(())';
    echo (bracketBalancer($string))?"Everything matches nicely. Yay!":"Oh noes, there isn't matches!";
?>

We have an array that matches left and right brackets of sorts (or anything else for that matter) and a foreach statement that does the comparison for each pair spitting out the name of problem bracket/thing and returning a fail.
Output:
Parentheses don't match.
Squares don't match.
Curlies don't match.
Oh noes, there isn't matches!

A: Your answer would not detect if the brackets are nested properly [(]) or if they occur in the correct sequence )(. The following should work:
function bracketBalancer ($string) {
  $brkt = [];
  for ($i=0; $i<strlen($string); $i++) {
    if ($string[$i] == '(') {
      array_push($brkt, '(');
    } elseif ($string[$i] == '{') {
      array_push($brkt, '{');
    } elseif ($string[$i] == '[') {
      array_push($brkt, '[');
    } elseif ($string[$i] == ')') {
      if (empty($brkt)) {return false;}
      $c = array_pop($brkt);
      if ($c != '(') {return false;}
    } elseif ($string[$i] == '}') {
      if (empty($brkt)) {return false;}
      $c = array_pop($brkt);
      if ($c != '{') {return false;}
    } elseif ($string[$i] == ']') {
      if (empty($brkt)) {return false;}
      $c = array_pop($brkt);
      if ($c != '[') {return false;}
    }
  }
  if (empty($brkt)) {
    return true;
  }
  return false;
}


text:
Q: array is not a function in react native in sub map array this is my code to call arrays of object
 {data.map((item, index ) =>
        <View>
        <Text key={index}>{item.type}</Text>

        {item.resultlist((sub,index)=>

            <Text key={index}>{sub.name}</Text>

          )}
            </View>
    )}

and this is my response of json array
 {
"status": "success",
"message": "Home page Response",
"response": [
    {
        "type": "product",
        "status": true,
        "sort_order": 0,
        "resultlist": [
            {
                "name": "Mifa F1",
                "img": "https://www.achhacart.com/image/cache/catalog/new%20thumbnails/Mifa%20A1BlacjkThumbnail-600x600.jpg",
                "type": "product",
                "product_id": 87
            },
            {
                "name": "Earphone",
                "img": "https://www.achhacart.com/image/catalog/cmsblock/hgb5.png",
                "type": "category",
                "category_id": 20
            },
            {
                "name": "Air Purifier",
                "img": "https://www.achhacart.com/image/catalog/cmsblock/air.gif",
                "type": "product",
                "product_id": 87
            },
            {
                "name": "Powerbank",
                "img": "https://www.achhacart.com/image/catalog/cmsblock/Powerbank10.jpg",
                "type": "product",
                "product_id": 87
            }
        ]
    },
    {
        "type": "middleimage",
        "status": true,
        "sort_order": 1,
        "img": "https://www.achhacart.com/image/catalog/cmsblock/Powerbank10.jpg",
        "product_id": 187
    },
    {
        "type": "product",
        "status": true,
        "sort_order": 2,
        "resultlist": [
            {
                "name": "Mifa A1 Black",
                "img": "https://www.achhacart.com/image/cache/catalog/new%20thumbnails/Mifa%20A1BlacjkThumbnail-600x600.jpg",
                "type": "product",
                "product_id": 87
            },
            {
                "name": "Earphones",
                "img": "https://www.achhacart.com/image/catalog/cmsblock/hgb5.png",
                "type": "category",
                "category_id": 20
            },
            {
                "name": "Air Purifiers",
                "img": "https://www.achhacart.com/image/catalog/cmsblock/air.gif",
                "type": "product",
                "product_id": 87
            },
            {
                "name": "Powerbanks",
                "img": "https://www.achhacart.com/image/catalog/cmsblock/Powerbank10.jpg",
                "type": "product",
                "product_id": 87
            }
        ]
    },
    {
        "type": "slider",
        "status": true,
        "sort_order": 3,
        "resultlist": [
            {
                "title": "slider1",
                "link": "",
                "image": "https://www.achhamall.com/staging-achhamall.com/image/catalog/1AA/WeChatImage_20191228151402.jpg"
            },
            {
                "title": "slider2",
                "link": "",
                "image": "https://www.achhamall.com/staging-achhamall.com/image/catalog/1accc/WeChatImage_20191231125513.jpg"
            }
        ]
    }
]

}
how should i call the sub array inside the whole array function in react native i am using the map function but still the error is same
and when i call the array object outside the array object then its render
suggest me where i am wrong

A: You are missing map by the looks of it when you are trying to iterate over resultlist.
item.resultlist -> item.resultlist.map((sub, index) => { ... }
It also looks like not every item in data contains a resultlist so maybe check if it exists also.

A: There are two things
1) First, Yoo have to apply map in your child array also
2) You are not returning the tag elements.
Use below code
{data.map((item, index ) =>
    return (
        <View>
            <Text key={index}>{item.type}</Text>
            {item.resultlist.map((sub,index)=>
       return (
                    <Text key={index}>{sub.name}</Text>
                )
            )}
        </View>
    );
)}


text:
Q: How do the particles in a rigid body "know" when to accelerate? In many cases, a force is applied to only a small part of a rigid body, yet all the particles of the body accelerate immediately. How do particles on which the force does not act directly "know" that they are supposed to accelerate?
I know the answer probably involves the transmission of the applied force in some way but I'll appreciate a good explanation. Furthermore, the acceleration of the particles on which the force acts directly depends on the mass of the entire body and not the masses of those particles themselves. Why is this the case?

A: Exactly because all portions of the body don't move instantaneously according to an applied force at a given point, that most of the noises of everyday life are produced.
The disturbance propagates as an elastic wave through the body as explained here
If the body will only vibrate for a fraction of second, but stay at rest, or will also move as a rigid body, it depends on the boundary conditions (static friction forces for example).
The cause of the vibration are atomic/molecular interactions in the solid. In a metal for example, the cloud of electrons hold the nuclei at its positions. Any attempt to increase or decrease the interatomic distance generates a restoring force as in a spring-mass system.
The vibration effect is normally only a transient that vanishes very quickly by damping, if the final effect in the rigid body is a translation, or a rotation around one of the axis of inertia.

A: "Rigid body" is an idealization.
Bodies that are well approximated as "rigid" have high tensile strength, high elastic modulus and high speed of sound. In this construct, "high" relates to the scale and forces of the system in question.
In reality, there is no absolutely rigid bodies. The acceleration propagates by acoustic waves with the speed of sound.
A certain body may be regarder both as rigid and as non-rigid. Imagine a church bell - you may consider it rigid when planning on how to transport it from the bell workshop to the church tower top. You have to assume it is pretty much elastic and non-rigid when you have to understand how it rings.
(There is a traditional physics practice experiment where you hit two metal cylinders together at their bases and use an electronic timer connected to them in order to determine the speed of sound in the metal. Cylinders stay connected together for the duration of the impact and the impact duration is the time the acoustic wave travels to the free ends and returns back to the impact side.)


text:
Q: SignalR IIS With React - "Server returned handshake error: Handshake was canceled." I am developing a .Net Core (3.1) web application hosted with IIS 10. When I am trying to use SignalR on localhost, I am able to connect totally fine and receive messages from the backend, but after I publish it to IIS, I get the error: "Server returned handshake error: Handshake was canceled." In the client logs on Chrome's console, I get the message: "Information: SSE connected to http://myserver.com/MyApplication/output" before I get the error described above (which you would think means that I connected successfully)...
I have seen other posts where people have suggested that I have to enable webSockets on IIS, and I have already checked the my site has this enabled.
I have also seen people suggest to try using the longPolling argument in the withUrl function when creating the connection, and this has not helped either.
I have also added SignalR Event Log Trace Listeners to my web.config file, and the only warning I get that might be related to this issue is that I get a warning from the .NET runtime that reads "Failed to determine the https port for redirect." I am not sure what this means or if it would be related to SignalR, but as this also appears to deal with Middleware, it might be significant.
One thing that I thought might be related is that my site is just one of multiple hosted on this server, so that when I am running locally, I can use the following to connect to SignalR:
hubConnection = new signalR.HubConnectionBuilder().withUrl("/output").build();
But because of the way this site is deployed on my server, I have to use this:
hubConnection = new signalR.HubConnectionBuilder().withUrl("/MyApplication/output").build();
when I deploy the site or else I get a 404 error...
Would there be any issue there? I noticed when inspecting the network requests that on localhost, the URL to connect with the socket is "wss://localhost:44315/output?id=..." and I get the "Status Code: 101 Switching Protocols", but after I deploy, the url that is used is "http://myserver.com/MyApplication/output?id=..." and I get a "200 OK" just before receiving the error described at the top. Why does wss get used on localhost but http is requested from my client when I deploy?

A: FINALLY discovered the issue after days of debugging... The reason I was getting a "101" response on localhost and not when published is because 101 is basically the server (IIS in my case) saying "I support web sockets". I realized that because I wasn't getting this when published, web sockets were probably not enabled in IIS. It was weird, however, because I went into IIS manager and it said that web sockets were enabled, but after much more research, I found that you also have to go into "Server Manager" and enable it as well (see here https://learn.microsoft.com/en-us/iis/get-started/whats-new-in-iis-8/iis-80-websocket-protocol-support and follow step by step instructions). I did not realize both were required.


text:
Q: Anti-reflection thin films When you put an anti-reflective thin film on a lens of sunglasses for example, how do they account for all of the wavelengths within the visible spectrum?
In order to counter reflection, you would need destructive interference of the waves reflected back into the eyes of the wearer.
We know that
$$L = \frac{\lambda}{4n_2}$$ for destuctive interference where $L$ is the width of the thin lens and $n_2$ is the refraction index of the sunglasses' lens.
How do they account for the entire range of 700-400nm of wavelengths for visible light? Do they stack a few of these layers on each other? Do they just take the average wavelength in that range?

A: In the case where we have an anti reflective coating with a thickness $L_{layer}=\frac{\lambda_{medium}}{4}$ and with a layer refractive index of $n=\sqrt{n_0n_1}$ where $n_0$ is the refractive index of the glass and $n_1$ is the refractive index of air the glasses will be reflective for, as you know, a very narrow set of wavelengths.
By instead doing similar coatings but with alternating refractive indexes, the freflectivity can be minimzed over a set of wavelengths. Given enough layers, the visible spectrum will be covered.


text:
Q: PowerQuery Transformation Fails for "Current State of Object" Background
A vendor periodically sends me an Excel workbook with a varying set of worksheets, where each sheet holds both a dataset and its metadata: the pricing for products in various groups.  I have written a function Parse_Sheet() to extract and standardize both the data and the metadata, and Parse_Sheet() works perfectly on a single table with the contents of a worksheet.
Instead of hard-coding every sheet on an individual basis, I wish to automatically format and consolidate the data from all sheets in the workbook—any arbitrary set of sheets.  While a simple List.Transform(..., Parse_Sheet) and Table.Combine() should suffice — to transform each in a list of sheet tables and then "stack" them into a single table — I unfortunately encounter an error.
While Parse_Sheet() will work on one table, it crashes when I use it to .Transform() each table in a list.  PowerQuery indicates that this error involves objects and their states, but I lack the expertise to decipher these particular diagnostics.
Error Message
Here is the error message displayed in the PowerQuery editor within Excel:
Unexpected error: Operation is not valid due to the current state of the object.
Details:
    Microsoft.Mashup.Evaluator.Interface.ErrorException: Operation is not valid due to the current state of the object. ---> Microsoft.Mashup.Evaluator.Interface.ErrorException: Operation is not valid due to the current state of the object. ---> Microsoft.Mashup.Evaluator.Interface.ErrorException: Operation is not valid due to the current state of the object. ---> Microsoft.Mashup.Evaluator.Interface.ErrorException: Operation is not valid due to the current state of the object. ---> Microsoft.Mashup.Evaluator.Interface.ErrorException: Operation is not valid due to the current state of the object. ---> System.InvalidOperationException: Operation is not valid due to the current state of the object. ---> System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at Microsoft.Mashup.Engine1.Language.Compiler.ToFunction(IFunctionExpression expression)
   at Microsoft.Mashup.Engine1.Runtime.CollapseNestedFunctionsVisitor.VisitFunction(IFunctionExpression node)
   at Microsoft.Mashup.Engine.Ast.AstVisitor2.VisitExpression(IExpression expression)
   at Microsoft.Mashup.Engine.Ast.AstVisitor2.VisitInvocation(IInvocationExpression invocation)
   at Microsoft.Mashup.Engine.Ast.AstVisitor2.VisitExpression(IExpression expression)
   at Microsoft.Mashup.Engine.Ast.AstVisitor2.VisitListElements(IExpression[] list)
   at Microsoft.Mashup.Engine.Ast.AstVisitor2.VisitInvocation(IInvocationExpression invocation)
   at Microsoft.Mashup.Engine.Ast.AstVisitor2.VisitExpression(IExpression expression)
   at Microsoft.Mashup.Engine.Ast.LogicalAstVisitor2`1.VisitFunction(IFunctionExpression function, IList`1 bindings)
   at Microsoft.Mashup.Engine1.Runtime.CollapseNestedFunctionsVisitor.VisitFunction(IFunctionExpression node)
   at Microsoft.Mashup.Engine.Ast.AstVisitor2.VisitExpression(IExpression expression)
   at Microsoft.Mashup.Engine1.Language.Query.NormalizationVisitor.Normalize(IExpression node, TypeValue[] parameterTypes, Boolean normalizeInvocation)
   at Microsoft.Mashup.Engine1.Language.Query.QueryExpressionBuilder.TryToQueryExpression(TypeValue type, IFunctionExpression functionExpression, QueryExpression& queryExpression)
   at Microsoft.Mashup.Engine1.Language.Query.AddColumnsQuery.CreateQueryExpressions(FunctionValue columnGeneratorFunction, RecordTypeValue rowType)
   at Microsoft.Mashup.Engine1.Language.Query.AddColumnsQuery.get_QueryExpressions()
   at Microsoft.Mashup.Engine1.Language.Query.AddColumnsQuery.SelectColumns(ColumnSelection columnSelection)
   at Microsoft.Mashup.Engine1.Language.Query.Query.ProjectColumns(ColumnSelection columnSelection)
   at Microsoft.Mashup.Engine1.Runtime.TableValue.SelectColumns(ColumnSelection columnSelection)
   at Microsoft.Mashup.Engine1.Runtime.TableValue.ReorderColumns(ListValue columnOrder, Boolean ignoreMissing)
   at Microsoft.Mashup.Engine1.Runtime.TableValue.ReplaceColumns(ColumnsConstructor columnConstructor)
   at Microsoft.Mashup.Engine1.Runtime.TableValue.TransformColumns(Dictionary`2 transforms, MissingFieldMode missingField)
   at Microsoft.Mashup.Engine1.Runtime.TableValue.TransformColumns(ListValue transformOperations, Value defaultTransformation, Value missingField)
   at Microsoft.Mashup.Engine1.Runtime.ColumnReferenceListValue.Transform(FunctionValue transform)
   at Microsoft.Mashup.Engine1.Runtime.NativeFunctionValue2`3.Invoke(Value arg0, Value arg1)
   at Microsoft.Mashup.Engine1.Language.DebugInstruction.Execute(MembersFrame1& frame)
   at Microsoft.Mashup.Engine1.Language.MembersFunctionValue1.Invoke(Value arg0)
   at Microsoft.Mashup.Engine1.Language.RecordInstruction.RuntimeRecordValue.Force(Int32 index)
   at Microsoft.Mashup.Engine1.Language.RecordInstruction.RuntimeRecordValue.get_Item(Int32 index)
   at Microsoft.Mashup.Engine1.Language.InstructionInvocationInstruction1.Execute(MembersFrame1& frame)
   at Microsoft.Mashup.Engine1.Language.DebugInstruction.Execute(MembersFrame1& frame)
   at Microsoft.Mashup.Engine1.Language.MembersFunctionValue1.Invoke(Value arg0)
   at Microsoft.Mashup.Engine1.Language.RecordInstruction.RuntimeRecordValue.Force(Int32 index)
   at Microsoft.Mashup.Engine1.Language.RecordInstruction.RuntimeRecordValue.get_Item(Int32 index)
   at Microsoft.Mashup.Engine1.Language.MembersFunctionValue1.Invoke(Value arg0)
   at Microsoft.Mashup.Engine1.Language.FunctionInvocationInstruction2.Execute(MembersFrame1& frame)
   at Microsoft.Mashup.Engine1.Language.MembersFunctionValue1.Invoke(Value arg0)
   at Microsoft.Mashup.Engine1.Language.DebugInstruction.Execute(MembersFrame1& frame)
   at Microsoft.Mashup.Engine1.Language.FunctionInvocationInstruction2.Execute(MembersFrame1& frame)
   at Microsoft.Mashup.Engine1.Language.DebugInstruction.Execute(MembersFrame1& frame)
   at Microsoft.Mashup.Engine1.Language.InstructionInvocationInstruction2.Execute(MembersFrame1& frame)
   at Microsoft.Mashup.Engine1.Language.DebugInstruction.Execute(MembersFrame1& frame)
   at Microsoft.Mashup.Engine1.Language.MembersFunctionValue1.Invoke(Value arg0)
   at Microsoft.Mashup.Engine1.Language.RecordInstruction.RuntimeRecordValue.Force(Int32 index)
   at Microsoft.Mashup.Engine1.Language.RecordInstruction.RuntimeRecordValue.get_Item(Int32 index)
   at Microsoft.Mashup.Engine1.Language.MembersFunctionValue1.Invoke(Value arg0)
   at Microsoft.Mashup.Engine1.Language.RecordInstruction.RuntimeRecordValue.Force(Int32 index)
   at Microsoft.Mashup.Engine1.Language.RecordInstruction.RuntimeRecordValue.get_Item(Int32 index)
   at Microsoft.Mashup.Engine1.Runtime.Library.Linker.BindFunctionValue.TypedInvoke(RecordValue environment, Value section, TextValue name)
   at Microsoft.Mashup.Engine1.Runtime.NativeFunctionValue3`4.Invoke(Value arg0, Value arg1, Value arg2)
   at Microsoft.Mashup.Engine1.Language.MembersFunctionValue0.Invoke()
   at Microsoft.Mashup.Engine1.Language.ListInstruction.RuntimeListValue.Force(Int32 index)
   at Microsoft.Mashup.Engine1.Language.ListInstruction.RuntimeListValue.get_Item(Int32 index)
   at Microsoft.Mashup.Engine1.Language.MembersFunctionValue1.Invoke(Value arg0)
   at Microsoft.Mashup.Engine1.Language.RecordInstruction.RuntimeRecordValue.Force(Int32 index)
   at Microsoft.Mashup.Engine1.Language.RecordInstruction.RuntimeRecordValue.get_Item(Int32 index)
   at Microsoft.Mashup.Engine1.Language.FunctionInvocationInstruction2.Execute(MembersFrame1& frame)
   at Microsoft.Mashup.Engine1.Language.Instruction.ExecuteCondition(MembersFrame1& frame)
   at Microsoft.Mashup.Engine1.Language.DebugInstruction.ExecuteCondition(MembersFrame1& frame)
   at Microsoft.Mashup.Engine1.Language.IfInstruction.Execute(MembersFrame1& frame)
   at Microsoft.Mashup.Engine1.Language.DebugInstruction.Execute(MembersFrame1& frame)
   at Microsoft.Mashup.Engine1.Language.MembersFunctionValue1.Invoke(Value arg0)
   at Microsoft.Mashup.Engine1.Language.RecordInstruction.RuntimeRecordValue.Force(Int32 index)
   at Microsoft.Mashup.Engine1.Language.RecordInstruction.RuntimeRecordValue.get_Item(Int32 index)
   at Microsoft.Mashup.Engine1.Language.MembersFunctionValue0.Invoke()
   at Microsoft.Mashup.Evaluator.SimpleDocumentEvaluator.BeginGetResult(DocumentEvaluationParameters parameters, Action`1 callback)
   --- End of inner exception stack trace ---
   at Microsoft.Mashup.Evaluator.SimpleDocumentEvaluator.BeginGetResult(DocumentEvaluationParameters parameters, Action`1 callback)
   at Microsoft.Mashup.Evaluator.SimpleDocumentEvaluator.BeginGetResult(DocumentEvaluationParameters parameters, Action`1 callback)
   at Microsoft.Mashup.Evaluator.Interface.IDocumentEvaluatorExtensions.GetResult[T](IDocumentEvaluator`1 evaluator, DocumentEvaluationParameters parameters)
   at Microsoft.Mashup.Evaluator.RemoteDocumentEvaluator.Service.OnBeginGetResult[T](IMessageChannel channel, BeginGetResultMessage message, Action`1 action)
   at Microsoft.Mashup.Evaluator.RemoteDocumentEvaluator.Service.OnBeginGetPreviewValueSource(IMessageChannel channel, BeginGetPreviewValueSourceMessage message)
   at Microsoft.Mashup.Evaluator.MessageHandlers.TryDispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.ChannelMessenger.ChannelMessageHandlers.TryDispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.MessageHandlers.Dispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.ChannelMessenger.OnMessageWithUnknownChannel(IMessageChannel baseChannel, MessageWithUnknownChannel messageWithUnknownChannel)
   at Microsoft.Mashup.Evaluator.MessageHandlers.TryDispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.ChannelMessenger.ChannelMessageHandlers.TryDispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.MessageHandlers.Dispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.EvaluationHost.Run()
   at Microsoft.Mashup.Container.EvaluationContainerMain.Run(Object args)
   at Microsoft.Mashup.Evaluator.SafeThread2.<>c__DisplayClass9_0.<CreateAction>b__0(Object o)
   at Microsoft.Mashup.Container.EvaluationContainerMain.SafeRun(String[] args)
   at Microsoft.Mashup.Container.BootstrapAppDomainManager.Execute(String[] argv)
   --- End of inner exception stack trace ---
   at Microsoft.Mashup.Evaluator.SimpleDocumentEvaluator.<>c__DisplayClass3_0.<BeginGetResult>b__0(EvaluationResult2`1 result)
   --- End of inner exception stack trace ---
   at Microsoft.Mashup.Evaluator.SimpleDocumentEvaluator.<>c__DisplayClass3_0.<BeginGetResult>b__0(EvaluationResult2`1 result)
   at Microsoft.Mashup.Evaluator.SimpleDocumentEvaluator.BeginGetResult(DocumentEvaluationParameters parameters, Action`1 callback)
   at Microsoft.Mashup.Evaluator.SimpleDocumentEvaluator.BeginGetResult(DocumentEvaluationParameters parameters, Action`1 callback)
   at Microsoft.Mashup.Evaluator.Interface.IDocumentEvaluatorExtensions.GetResult[T](IDocumentEvaluator`1 evaluator, DocumentEvaluationParameters parameters)
   at Microsoft.Mashup.Evaluator.RemoteDocumentEvaluator.Service.OnBeginGetResult[T](IMessageChannel channel, BeginGetResultMessage message, Action`1 action)
   at Microsoft.Mashup.Evaluator.RemoteDocumentEvaluator.Service.OnBeginGetPreviewValueSource(IMessageChannel channel, BeginGetPreviewValueSourceMessage message)
   at Microsoft.Mashup.Evaluator.MessageHandlers.TryDispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.ChannelMessenger.ChannelMessageHandlers.TryDispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.MessageHandlers.Dispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.ChannelMessenger.OnMessageWithUnknownChannel(IMessageChannel baseChannel, MessageWithUnknownChannel messageWithUnknownChannel)
   at Microsoft.Mashup.Evaluator.MessageHandlers.TryDispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.ChannelMessenger.ChannelMessageHandlers.TryDispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.MessageHandlers.Dispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.EvaluationHost.Run()
   at Microsoft.Mashup.Container.EvaluationContainerMain.Run(Object args)
   at Microsoft.Mashup.Evaluator.SafeThread2.<>c__DisplayClass9_0.<CreateAction>b__0(Object o)
   at Microsoft.Mashup.Container.EvaluationContainerMain.SafeRun(String[] args)
   at Microsoft.Mashup.Container.BootstrapAppDomainManager.Execute(String[] argv)
   --- End of inner exception stack trace ---
   at Microsoft.Mashup.Evaluator.RemoteDocumentEvaluator.Service.<>c__DisplayClass9_1.<OnBeginGetPreviewValueSource>b__1()
   at Microsoft.Mashup.Evaluator.RemotePreviewValueSource.<>c__DisplayClass0_0.<RunStub>b__0()
   at Microsoft.Mashup.Evaluator.EvaluationHost.ReportExceptions(String entryName, IEngineHost engineHost, IMessageChannel channel, Action action)
   --- End of inner exception stack trace ---
   at Microsoft.Mashup.Evaluator.EvaluationHost.<>c__DisplayClass17_0.<TryReportException>b__1()
   at Microsoft.Mashup.Common.SafeExceptions.IgnoreSafeExceptions(IEngineHost host, IHostTrace trace, Action action)
   at Microsoft.Mashup.Evaluator.EvaluationHost.TryReportException(IHostTrace trace, IEngineHost engineHost, IMessageChannel channel, Exception exception)
   at Microsoft.Mashup.Evaluator.EvaluationHost.ReportExceptions(String entryName, IEngineHost engineHost, IMessageChannel channel, Action action)
   at Microsoft.Mashup.Evaluator.RemoteDocumentEvaluator.Service.<>c__DisplayClass12_1`1.<OnBeginGetResult>b__0()
   at Microsoft.Mashup.Evaluator.EvaluationHost.ReportExceptions(IHostTrace trace, IEngineHost engineHost, IMessageChannel channel, Action action)
   at Microsoft.Mashup.Evaluator.RemoteDocumentEvaluator.Service.OnBeginGetResult[T](IMessageChannel channel, BeginGetResultMessage message, Action`1 action)
   at Microsoft.Mashup.Evaluator.RemoteDocumentEvaluator.Service.OnBeginGetPreviewValueSource(IMessageChannel channel, BeginGetPreviewValueSourceMessage message)
   at Microsoft.Mashup.Evaluator.MessageHandlers.TryDispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.ChannelMessenger.ChannelMessageHandlers.TryDispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.MessageHandlers.Dispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.ChannelMessenger.OnMessageWithUnknownChannel(IMessageChannel baseChannel, MessageWithUnknownChannel messageWithUnknownChannel)
   at Microsoft.Mashup.Evaluator.MessageHandlers.TryDispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.ChannelMessenger.ChannelMessageHandlers.TryDispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.MessageHandlers.Dispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.EvaluationHost.Run()
   at Microsoft.Mashup.Container.EvaluationContainerMain.Run(Object args)
   at Microsoft.Mashup.Evaluator.SafeThread2.<>c__DisplayClass9_0.<CreateAction>b__0(Object o)
   at Microsoft.Mashup.Container.EvaluationContainerMain.SafeRun(String[] args)
   at Microsoft.Mashup.Container.BootstrapAppDomainManager.Execute(String[] argv)
   --- End of inner exception stack trace ---
   at Microsoft.Mashup.Evaluator.EvaluationHost.OnException(IEngineHost engineHost, IMessageChannel channel, ExceptionMessage message)
   at Microsoft.Mashup.Evaluator.MessageHandlers.TryDispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.MessageHandlers.Dispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.ChannelMessenger.ChannelMessageHandlers.TryDispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.MessageHandlers.Dispatch(IMessageChannel channel, Message message)
   at Microsoft.Mashup.Evaluator.Interface.IMessageChannelExtensions.WaitFor[T](IMessageChannel channel)
   at Microsoft.Mashup.Evaluator.RemotePreviewValueSource.PreviewValueSource.WaitFor(Func`1 condition, Boolean disposing)
   at Microsoft.Mashup.Evaluator.RemotePreviewValueSource.PreviewValueSource.get_TableSource()
   at Microsoft.Mashup.Evaluator.Interface.TracingPreviewValueSource.get_TableSource()
   at Microsoft.Mashup.Host.Document.Analysis.PackageDocumentAnalysisInfo.PackagePartitionAnalysisInfo.SetPreviewValue(EvaluationResult2`1 result, Func`1 getStaleSince, Func`1 getSampled)

Code
Parse_Sheet()
The standard worksheet has the following form:

A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P

Title for the Worksheet

Multipliers

Multiplier

Multiplier
...

PROD_LINE-0422

Total
$0.00

A1
0.123
D4
0.456
G7
0.789
...

Prices effective April 15, 2022

B2
0.234
E5
0.567
H8
0.890
...

File updated April 15, 2022

C3
0.345
F6
0.678
I9
0.901
...

Fld 1
Grp
Fld 3
Fld 4
Fld 5
Fld 6
Fld 7
Fld 8
Fld 9
Fld 10
Fld 11

...
A1
...
...
...
...
...
...
...
...
...

...
A1
...
...
...
...
...
...
...
...
...

...
...
...
...
...
...
...
...
...
...
...

...
B2
...
...
...
...
...
...
...
...
...

...
...
...
...
...
...
...
...
...
...
...

The Parse_Sheet() function accepts this (table) worksheet and returns a record with the following fields:

*

*Data: a table with the dataset from the sheet, having the form below.

Fld 1
Grp
Fld 3
Fld 4
Fld 5
Fld 6
Fld 7
Fld 8
Fld 9
Fld 10
Fld 11

...
A1
...
...
...
...
...
...
...
...
...

...
A1
...
...
...
...
...
...
...
...
...

...
...
...
...
...
...
...
...
...
...
...

...
B2
...
...
...
...
...
...
...
...
...

...
...
...
...
...
...
...
...
...
...
...

*Info: a record with the following fields:

*

*Metadata: a record with the following fields:

*

*Title: the (text) title describing the sheet.
"Title for the Worksheet"

*Abbreviation: The (text) label ("[Product Line]-MMyy") abbreviating the sheet and resembling the worksheet name itself.
"PROD_LINE-0422"

*Date Effective: The (date) date on which the pricing becomes effective.
2022-04-15

*Date Updated: The (date) date on which the pricing was last updated.
2022-04-15

*Date: The (date) month for which the pricing applies, extracted as MMyy from the end of the Abbreviation.
2022-04-01

*Code: The (text) code for the product line, extracted from the start of the Abbreviation.
"PROD_LINE"

*Total: The (number) value of some "Total" listed separately on the worksheet, unclear in purpose and nearly always 0.
0.0

*Multipliers: a table of pricing multipliers, having the form below.

Group
Multiplier

A1
0.123

B2
0.234

...
...

I9
0.901

...
...

Unfortunately, the code for Parse_Sheet() is too long to include, as it violates the character limit.  So I have removed it here, where it is still visible in the timeline.
Suffice it to say, the function works perfectly when called on a single table object, with the contents of one worksheet.
let Parse_Sheet = (
    sheet as table
) as record =>
    // ...
in
    Parse_Sheet

Format_Sheet()
This function accepts a (table) sheet and returns its (table) dataset, in standardized form and "fortified" with metadata.  This output table has the following form: [Sheet] | Line | Field One | Grp | Field Three | ... | Field Eleven | Multiplier | Effective Date.
let Format_Sheet = (
    sheet as table,
    optional sheetName as nullable any
) as table =>
    let
        // Parse the sheet to extract data and info.
        sheet_parsed = Parse_Sheet(sheet),

        // // Record important metadata.
        // dateEff = sheet_parsed[Info][Metadata][Date Effective],
        // abbrev = sheet_parsed[Info][Metadata][Abbreviation],
        // code = sheet_parsed[Info][Metadata][Code],

        // Sheet name defaults to abbreviation in metadata.
        sheetName = if sheetName = null then
            sheet_parsed[Info][Metadata][Abbreviation]
        else
            sheetName,

        // // Record the names of the original columns in the data.
        // dataNames = Table.ColumnNames(sheet_parsed[Data]),

        // Filter the multipliers for mapping.
        multipliers = Table.SelectRows(
            sheet_parsed[Info][Multipliers],
            each [Multiplier] <> null
        ),

        // Format the data and augment it with multipliers.
        data = Table.ExpandTableColumn(
            Table.NestedJoin(
                Table.RenameColumns(

                    // (1) For clarity, rename the data columns...
                    sheet_parsed[Data], List.Transform({
                    {"Fld 1",  "Field One"   },
                    {"Grp",    "Group"       },
                    {"Fld 3",  "Field Three" },
                    {"Fld 4",  "Field Four"  },
                    {"Fld 5",  "Field Five"  },
                    {"Fld 6",  "Field Six"   },
                    {"Fld 7",  "Field Seven" },
                    {"Fld 8",  "Field Eight" },
                    {"Fld 9",  "Field Nine"  },
                    {"Fld 10", "Field Ten"   },
                    {"Fld 11", "Field Eleven"}
                }, each
                    // ...from their original (cleaned) state.
                    {Text.Upper(Text.Trim(_{0})),  _{1}                }
                )),

                // (2) Map each data record to its group multiplier...
                {"Group"}, multipliers, {"Group"}, "Multipliers", JoinKind.Inner
            ),

            // (3) ...and expand the value of that multiplier.
            "Multipliers", {"Multiplier"}, {"Multiplier"}
        ),

        // Fortify it with further metadata.
        data_fortified = Table.ReorderColumns(
            Table.AddColumn(
                // (1) Add a column with the line code from the sheet abbreviation...
                Table.AddColumn(data, "Line", each sheet_parsed[Info][Metadata][Code], type text),

                // (2) ...and add a column with the effective date.
                "Effective Date", each sheet_parsed[Info][Metadata][Date Effective], type date
            ),

            // (3) Move the line code to the start, and the date to the end.
            List.Combine({{"Line"}, Table.ColumnNames(data), {"Effective Date"}})
        ),

        // Optionally include the sheet name.
        result = if sheetName = false then
            data_fortified
        else
            Table.ReorderColumns(
                // (1) Add a column with the sheet abbreviation itself...
                Table.AddColumn(data_fortified, "Sheet", each sheet_parsed[Info][Metadata][Abbreviation], type text),

                // (2) ...and move it to the start of the table.
                List.Combine({{"Sheet"}, Table.ColumnNames(data_fortified)})
            )
    in
        result
in
    Format_Sheet

Format_File
This function accepts the (text) filepath of the original workbook, and it returns a table: the "fortified" datasets from each worksheet, "stacked" into a single table and distinguished by the Sheet (and Line) field(s).
This output table has the following form: Sheet | Line | Field One | Grp | Field Three | ... | Field Eleven | Multiplier | Effective Date.
let Format_File = (
    file_path as text
) as table =>
    Table.Combine(
        List.Transform(
            Table.SelectRows(
                // (1) Tabulate the contents of the workbook...
                Excel.Workbook(File.Contents(file_path), null, true),

                // (2) ...and use only its sheets.
                each ([Kind] = "Sheet")

            // (3) Extract those sheets as a list of tables...
            )[Data],

            // (4) ...and format each table into a fortified result.
            Format_Sheet
        )

        // (5) "Stack" those fortified tables into a single table.
    )
in
    Format_File

Note
For Format_File() I have tried both List.Transform(..., Format_Sheet), and also List.Transform(..., each Format_Sheet(_)) with the each _ convention.  Unfortunately, neither convention resolved the state error.


text:
Q: "If/as/when necessary" Is there any difference between the following sentences?

*

*Please press the bell if necessary.

*Please press the bell as necessary.

*Please press the bell when necessary.

A: All three read roughly the same to me but if I were to divide them I would do along a spectrum of how often it may be necessary to press the bell. 3 implies (very weakly) pressing once, otherwise whenever would be there in formal language. 2 Implies several presses to my mind. 1 Seems very neutral. Alas I have no source or proof for these gut reactions so don't base any importance on my musings!

A: One can review use of if necessary, as necessary, and when necessary via examples drawn from links at ngrams.  Some sets of examples are given below, with a summary after each set.

So check all cylinder fins periodically and clean them if necessary. - Townsend
  ...be willing to see several therapists if necessary in order to find one who is right for you - Norwood
  Then take your complaint to the bully's parents and school authorities, and to the police if necessary. - L.H.D.

The above are typical examples of use of if necessary in explaining what action to take if certain conditions arise.  It is supposed that the action might or might not be needed, depending on conditions.  While as necessary could be used in these examples without particular change in their meanings, such use happens to be rare.

Repair or replace timer as necessary - Powell
  Lubricate or replace heat valve as necessary. - Motor

These two examples illustrate use of as necessary in cases where neither of if necessary or when necessary are quite right; specifically, where multiple actions may or may not be done, each dependent on conditions.  Note that among numerous surveyed examples for as necessary, it is far more frequently used in a way not of interest here, in sentences like "skilled employees ... should be regarded as necessary employees" (Railway news).

When necessary, the investigator may engage an appropriate specialist - RSFSR codes
  The rope is held in the hands to give the critter slack to play on and is dallied around the saddle-horn when necessary to stop the animal when he goes wrong. - Ward
  ...consideration and approval by the relevant bodies as and when necessary. - Kenya Gazette

In these and other examples, use of when necessary may be prompted by a sense that conditions will arise to make an action necessary; except that in the Kenya Gazette example, as and when necessary is, more or less, a verbose set phrase that could be adequately replaced by any of the simpler if, as or when phrases.


text:
Q: How to access value from Firebase Realtime Database in React-native? (android)
On the left my database schema, on the right is my react-native code.
I followed this documentation to get started with Realtime Database for Android.
I am trying to get the value "Lesson" from key "Category".
none of the commands I tried work. How I can get Lesson value?
I tried test.parent but I got the correct location in my database but I want the values.
thanks!

A:
Documentation is your Friend!

The answer to your question is in the document you attached!
If you scroll a bit down there's a section One-time read
To read the value once, call the once method on a reference:
import database from '@react-native-firebase/database';

database()
  .ref('/users/123')
  .once('value')
  .then(snapshot => {
    console.log('User data: ', snapshot.val());
  });

So just replace the ref path '/users/123' with your path 'Lesson 1/1 Introduction/Category'
You can also listen for changes in the document in real-time. Check out Real-Time Changes
import database from '@react-native-firebase/database';

database()
  .ref('/users/123')
  .on('value', snapshot => {
    console.log('User data: ', snapshot.val());
  });


text:
Q: Save firefox profile generated by Selenuim Web Driver I use Selenium WebDriver with firefox. Every time selenium generates new anoniumus profile for firefox in temp folder and after exit, removes it. I need this profile. How can I get it?
F.e. profile stored in
C:\Documents and Settings\Developer\Local Settings\Temp\anonymous5583304190515426768webdriver-profile

After shutting down WebDriver with
driver.quit();

profile will be removed, but it is already logged and I want to use it in next iteration, by initing WebDriver with it:
FirefoxDriver driver = new FirefoxDriver(new FirefoxProfile(profileFolder));

Is it possible to save profile without dirty hacks like coping whole folder while driver works (I'm not sure even it works, because in windows, folder is locked while firefox launched)? Maybe exists some API in Selenium for it?

A: Why dont you just change approach?

*

*Create firefox profile which will be clean and name it somehow you know what it is. e.g. SELENIUM

*When initializing the Webdriver:
 ProfilesIni allProfiles = new ProfilesIni();
 FirefoxProfile desiredProfile = allProfiles.getProfile("SELENIUM");
 WebDriver driver = new FirefoxDriver(desiredProfile);

That way, you assure that this profile will be used anytime you do the tests...


text:
Q: Dexie.js getting results in a proper way My question is regarding approach of data.
Lets say i have table of 700 records of files and some data to them like date, name etc.
Example:
{
blob:....,
name:'Name',
date:'13-11-2020',
type:'text/html'
....
}

Now i want to do some sorting, filtering and pagination in spa app like vue.
Is it better to do db.files.toArray(COSTOMFILTER,PAGINATION,SORTINNG function) and return to view or get all data to array and sort them there ? list = await db.files.toArray().
Also is it possible to limit return elements ? for example I don`t want blob in my return elements.
NO Blob
{
name:'Name',
date:'13-11-2020',
type:'text/html'
....
}
Or return answer just pointing to blob in memory ? I ask because files can be large.
Thanks for answer.

A: Regarding the combination of sorting and filtering and pagination, there is no silver bullet on how to approach it. Generally:

*

*try to squeeze out what you can by using a compound index to combine filtering of multiple fields and ordering.

*In case dataset is huge and pages are small but not possible to combine filtering and order in an index, consider using the index for sorting only and do the filtering on top of that. See some hints on this page.

Regarding your other question about selecting fields: In IndexedDB it's only possible to select whole objects (Collection.toArray()) or just the primary keys (Collection.primaryKeys()) - not certain properties. Blobs are a bit special though: They are (or should be at least) lazy loaded anyway so they should not starve memory until you start reading from them.


text:
Q: Current core technologies for AJAX w/ Java? Looking to implement a RIA using AJAX with Java on the backend.
I was looking at DWR for an RPC style approach, but the project hasn't been updated since 2008.
I was also looking at DOJO and GWT.
Can anyone recommend a core set of technologies that works best for a Java based back end, that contains a rich set of client side widgets and backend integration with Spring WebFlow/MVC?
thanks

A: I would recommend Spring 3.0.  It's up to date, lightweight, easily configurable, supports dependency injection, annotated classes, and is a great framework.
It supports REST, so it's easy to implement classes  that return JSON to your HTML pages.  This will help keep your content, behavior, and presentation all separate while still enabling you to build a Rich Internet Application.
Although outside the scope of your question, I'd suggest you use JQuery on the frontend as I've had really good results using it to transfer JSON back and forth from the server.
I would stay away from DWR.  They merged with Dojo, which in my opinion is a better choice than DWR.  DWR sounded good, but in practice it was buggy and difficult to use.  Dojo was much cleaner and more modular.  But unless you're using Comet (aka Reverse Ajax) just stick with Spring and JQuery.
Spring 3.0 is also supported on Google App Engine... just worth mentioning as Platform as a Service is in our future.

A: My recommendation is a RIA framework like SmartClient or ExtJS + a REST-based backend (built on Jersey, for example).  I have also found JQuery to be extremely helpful when combined with these frameworks.  Together. this allows you to build your GUI right on top of a REST API, which itself could be reusable for programmatic integration.
These kinds of questions are always religious ones, but FWIW I am personally not a massive fan of GWT, for multiple reasons. One of those reasons is because I don't want server side folks constructing GUI-targeted data structures (I'd rather have them stick to pure data and let me GUI folks handle the GUI stuff).  So I actually don't appreciate that capability of GWT, but obviously many other people welcome that aspect, so again it's a religious choice.

A: you can try GWT.That supports Spring well.
http://www.springbyexample.org/examples/simple-gwt-spring-webapp.html

A: If you use a Spring MVC back end, you can use any AJAX frontend there is.
And if you are going to develop a RIA, I would suggest either Prototype with Script.Aculo.Us (Killer GUI effect library) or MooTools (which is either an extension or a re-write of prototype, that also includes many GUI tools).
The great thing about both ProtoType and Mootools is their Object-Oriented methodology (MooTools Class() docs, Prototype Class.create() docs), but the extension mechanism that gives additional methods and properties to DOM elements (How Prototype extends the DOM, MooTools Element reference). Of course this mechanism is exactly what the JQuery guys loathe about these libraries. But the nice thing is that because of these extensions, you hardly ever have to resort to browser-specific programming, the abstraction handles that for you.

A: I choose JSF for RIA applications.

*

*It is J2EE 6 standard

*it built-in in J2EE application servers (glassfish, jboss),

*it has several implementations - if you have problem with one, you can switch to another

*I has at least 4 (richfaces, myfaces, icefaces, primefaces) independent, big components libraries.

A: Spring can work well, but my personal preference is for simplicity, and Spring is bit heavy platform. So I prefer deploying services on JAX-RS containers (like Jersey); Guice for wiring things together, and in case I want to override or change data bindings, Jackson for JSON handling.
Other useful pieces would be jDBI for database access (much simpler than hibernate or other full ORMs), async-httpclient for doing calls to other web services.
Best of all, these all work nicely for many other kinds of uses.


text:
Q: GUI for a new cmake I installed Cmake 3.5 and I want to have a GUI for it, as I had before with cmake-qt-gui. But what was installed is only cmake itself. I expected cmake-gui to come with the source of cmake, maybe I just don't see it? If not, any chance getting a GUI for it? I use Ubuntu.

A: Cmake code for Linux comes with cmake-gui, but it is not built by default. One can open bootstrap file, scroll down and set:
cmake_bootstrap_qt_gui="1"

After that run bootstrap, make and make install again.


text:
Q: Keep type information after hydrating a function So, I have a bunch (hundreds) od dbMethods that are basically methods that take "db" as the first argument and then only turn to real methods. Later they are "hydrated" (the db is supplied), thus new methods are created.
My main problem is that I want the "hydrated" to be properly typed. Currently it's not, because reduce() loses type information. Do you have any suggestion? I'm sharing my attempts, but "RemoveFirstArgument" doesn't seem to be working.
const dbMethods = { // db is always the first argument
    getModerators: (db: any) => (chatId: string) => Promise.resolve([111]),
    getRooms: (db: any) => (accountId: string) => Promise.resolve([222])
}

type dbkeys = keyof typeof dbMethods

type WithDb = (db: any) => (...args: any) => any

type DbMethodContainer = {
  [key in dbkeys]: WithDb;
};

type RemoveFirstArgument<T = DbMethodContainer> = {
    [P in keyof T]: ReturnType<T[P]>;
};

// ultimately I want "hydrated" to have the right type
const hydrated: RemoveFirstArgument<typeof dbMethods> = Object.keys(dbMethods)
    .reduce((acc, method) => ({ ...acc, [method]: dbMethods[method](db) }), {})

// this is how I want to use it
const rooms = hydrated.getRooms('some accountId')

Here's the playground


text:
Q: Stored proc with 11+ dynamic parameters I know this question has been asked and debated before. The answers I have read are mostly opinion, so I am looking for something more technical. More "under the hood".
I'm using SQL Server 2008. I am about to write a query that will need to accept at least 11 inputs. The user could specify 1 to 11(+) of these. They are of various types (IDs, text matching, geography, full text matches, record sets, etc.). It's as dynamic as you can get with SQL.
I know how to do this without using dynamic SQL:
/*for simple match*/ WHERE @Input IS NOT NULL OR t.col = @Input

This has drawbacks because of joins etc. I don't ever use dynamic SQL. But from what I've read, it seems this may be a case for dynamic SQL.
Can anyone give some technical pointers please?

A: http://www.sommarskog.se/index.html
Look at the curse and blessing of Dynamic SQl and the Dynamic Search Conditions links

A: You need to remember that if you don't want to use dynamic SQL (and I wouldn't either) then the DRY principle is sorta out-the-window.
Make effective use of TVP's and accept the fact that you will have somewhat high cyclomatic complexity (for a SQL statement)
If you want everything cacheable and sargable, you should consider how to design it in multiple procedures and then break out your conditions as needed.
Another very common approach is to include conditions such as:
WHERE (@pParam IS NULL OR ~condition~)

If your parameter is NULL then SQL will not bother resolving the other half of the condition.
EDIT: This last part only applies in SQL2008R2 and only if using the OPTION(RECOMPILE) command


text:
Q: RoR + IIS. What kind of problems I would run into? It looks like that most of the time people are running RoR behind nginx/Apache web servers. Right now our workshop uses only Microsoft's products. So most natural move would be to try and run RoR using IIS 7.5.
It does look that setting up RoR and IIS is a quite a pain. However, besides problems setting up IIS I could not find anyone pointing out problems with RoR behind IIS.
Are there any issues I would definitely run into if I would choose this "lovely" path of IIS?

A: Sure, it's possible, but you are setting yourself up for trouble. Configuration, deployment, and troubleshooting will be constant hassles under IIS. If you really want to host internally, I'd setup an Ubuntu server in Hyper-V, use Nginx, and be done with it. On the other hand, if your shop isn't built to deal with managing a Linux server or hosting a Rails app internally, I think it would be more reasonable to consider Heroku or another PaaS before dealing with IIS.
EDIT: Coming from a background in Windows IT, I know that setting up a Linux server and managing it isn't always as easy as "do it and be done with it," so don't think I'm not sympathetic to where you're coming from. The thing is, while the "natural move" might seem like trying to do it in IIS, it is an unnatural move as far as Rails is concerned. My suggestion to anyone who isn't ready to make the plunge into both Linux and hosting their own Rails apps really is Heroku. Even with the know-how to configure Linux for Rails, I still use Heroku for all of my Ruby MRI apps.


text:
Q: Change an error message, returned by SharePoint 2007 I would like to change an error message returned by SharePoint 2007
"An error occurred copying some or all of the selected files"
So that it is more informative to end users.
Is this possible? If so how?

A: I don't believe this error message is actually generated by SharePoint. SharePoint is simply displaying the error that it encountered from another system component. I don't think you'll have much chance of changing it without doing crazy stuff.
Out of curiosity, how informative were you going to be? Compared to some of the generic errors that SharePoint returns, the one you're looking at isn't that bad.  :)


text:
Q: How to group elements effectively in a huge list by their first character in python I am following the answer of the following stackoverflow question to accomplish my task as follows. python list group by first character
import json
from itertools import groupby

#Load data
with open('input.txt', 'r') as f:
    concepts = []
    for concept in f:
        concepts.append(concept.strip())

print(len(concepts))

concepts_list = [list(g) for k, g in groupby(concepts, key=lambda x: x[0])]

concepts_dict = {}
for item in concepts_list:
    concepts_dict[item[0][0]] = item

with open("concepts_preprocessed_dictionary.txt", "w") as fw:
    fw.write(json.dumps(concepts_dict))

However, I am wondering why this code is not working when there are huge number of concepts in the list (aproximately 13,000,000 concepts). Surprisingly the program executes in seconds and when I check the dictionary it contains wrong results (in other words the dictionary file is only 1KB in size and contain mostly one or two elements per grouped lists).
Unfortunately, I am not in a position to share my concept list as it violates some privacy issues.
But I found a long word list in the following github page: https://raw.githubusercontent.com/dwyl/english-words/master/words.txt
However, unlike the above mentioned dataset my current dataset is only àlphabetically ordered by first character` (i.e. as follows)
My dataset: Only first letter is m, but the remaining words are not albetically ordered

*

*methods

*machine learning

*mic

Dataset I have mentioned: Nicely ordered based on characters

*

*machine learning

*methods

*mic

Please let me know if there is any further details needed.

A: You don't really need to use groupby to do this.
Consider your linked example:
list1=['hello','hope','hate','hack','bit','basket','code','come','chess']

You can create the groups described with a native Python dict:
groups={}
for word in list1:
    groups.setdefault(word[0],[]).append(word)

>>> groups
{'h': ['hello', 'hope', 'hate', 'hack'], 'b': ['bit', 'basket'], 'c': ['code', 'come', 'chess']}

Or, with defaultdict if your prefer:
from collections import defaultdict
groups=defaultdict(list)
for word in list1:
    groups[word[0]].append(word)

>>> groups
defaultdict(<class 'list'>, {'h': ['hello', 'hope', 'hate', 'hack'], 'b': ['bit', 'basket'], 'c': ['code', 'come', 'chess']})

Both of these methods will work with completely unsorted data and gather the words based on the first letter. You are then free to use the values of that dict to make a list of lists if desired:
>>> sorted(groups.values(), key=lambda s: s[0])
[['bit', 'basket'], ['code', 'come', 'chess'], ['hello', 'hope', 'hate', 'hack']]

Now if you still want to use groupby for some reason, you would likely do something like this:
groups={}
for k,v in groupby(list1, key=lambda s: s[0]):
    groups.setdefault(k,[]).extend(v)


text:
Q: Why it is UDP, not RTP in Wireshark when I stream using jmf? I want to capture and stream audio using JMF 2.1.1e in RTP format. I wrote a simple transmitter, I can transmit and receive the audio. But when I saw in Wireshark, I saw the packets as UDP. Can anyone point me out the problem, please.
And here is my function responsible for audio capture and transmit.
public void captureAudio(){

    // Get the device list for ULAW
    Vector devices = captureDevices();

    CaptureDeviceInfo captureDeviceInfo = null;

    if (devices.size() > 0) {
         //get the first device from the list and cast it as CaptureDeviceInfo
         captureDeviceInfo = (CaptureDeviceInfo) devices.firstElement();
    }
    else {
        // exit if we could not find the relevant capturedevice.
        System.out.println("No such device found");
        System.exit(-1);
    }

    Processor processor = null;
    try {
        //Create a Processor for the specified media.
        processor = Manager.createProcessor(captureDeviceInfo.getLocator());
    } catch (IOException ex) {
        System.err.println(ex);
    } catch (NoProcessorException ex) {
        System.err.println(ex);
    }
    //Prepares the Processor to be programmed.
    //puts the Processor into the Configuring state.
    processor.configure();

    //Wait till the Processor configured.
    while (processor.getState() != Processor.Configured){
       try {
           Thread.sleep(100);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }

    //Sets the output content-type for this Processor
    processor.setContentDescriptor(CONTENT_DESCRIPTOR);
    /**
         ContentDescriptor CONTENT_DESCRIPTOR
                = new ContentDescriptor(ContentDescriptor.RAW_RTP);
      */

    //Gets a TrackControl for each track in the media stream.
    TrackControl track[] = processor.getTrackControls();

    boolean encodingOk = false;

    //searching through tracks to get a supported audio format track.
    for (int i = 0; i < track.length; i++) {
        if (!encodingOk && track[i] instanceof FormatControl) {
            if (((FormatControl)
                    track[i]).setFormat( new AudioFormat(AudioFormat.ULAW_RTP, 8000, 8, 1) ) == null)
            {
               track[i].setEnabled(false);
            }
            else {
                encodingOk = true;
                track[i].setEnabled(encodingOk);
                System.out.println("enc: " + i);
            }
        } else {
            // we could not set this track to ULAW, so disable it
            track[i].setEnabled(false);
        }
    }

    //If we could set this track to ULAW we proceed
    if (encodingOk){
        processor.realize();
        while (processor.getState() != Processor.Realized){
           try {
               Thread.sleep(100);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
        }

        DataSource dataSource = null;
        try {
            dataSource = processor.getDataOutput();
        } catch (NotRealizedError e) {
            e.printStackTrace();
        }

        try {

            String url= "rtp://192.168.1.99:49150/audio/1";
            MediaLocator m = new MediaLocator(url);
            DataSink d = Manager.createDataSink(dataSource, m);
            d.open();
            d.start();
            System.out.println("transmitting...");
            processor.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

And please ask, if you find anything improper or vague.
Thanks in advance. :)
Clarification: I have a peice of C# code for RTP streaming. And when I capture the data using wireshark, I can see them as RTP, but the problem is when I capture the data stream from JMF wireshark show them as UDP. And my question is, why?
I know the difference between UDP and RTP.

A: RTP is the Application layer,
UDP is the Transport Layer,
that is not the same level!
Wikipedia helps to explain that in detail.
So your data is send as a RTP stream within a UDP "Frame"
A small overview...
Application layers:
* DHCP
* DHCPv6
* DNS
* FTP
* HTTP
* IMAP
* IRC
* LDAP
* MGCP
* NNTP
* BGP
* NTP
* POP
* RPC
* RTP
* RTSP
* RIP
* SIP
* SMTP
* SNMP
* SOCKS
* SSH
* Telnet
* TLS/SSL
* XMPP
* (more)

Transport layer
* TCP
* UDP
* DCCP
* SCTP
* RSVP
* (more)

Internet layer
* IP
      o IPv4
      o IPv6
* ICMP
* ICMPv6
* ECN
* IGMP
* IPsec
* (more)

Link layer
* ARP/InARP
* NDP
* OSPF
* Tunnels
      o L2TP
* PPP
* Media access control
      o Ethernet
      o DSL
      o ISDN
      o FDDI
* (more)

A: If I understand your question correctly you want to know why the RTP packets are not recognised as RTP packets in wireshark. In my experience this can be the case if wireshark does not have enough information about the RTP session.
For example: 1) if I sniff an RTP session that has been setup using RTSP or SIP and SDP, then wireshark will show detect RTP. 2) However in another application in which I was setting up the session using local SDP descriptions, the packets show up as UDP. In the second scenario wireshark sees the RTP packets but lacks the information to classify them as RTP. Since RTP usually sits on top of UDP and wireshark can classify UDP packets, they are classified as such.
FYI, you can then select a packet from stream that you know is RTP, and select "Decode as". Then select RTP from the protocol list for the appropriate stream (and RTCP for the other one if applicable), and then wireshark will show the packets as being RTP and you'll be able to see the packet info.
I'm not sure if this is the reason in your specific case, but perhaps there is a signaling difference between your JMF and your C# example? It sounds like you might be using SIP for the C# application, and nothing for the JMF one?


text:
Q: Partition a list into sublists by percentage I have a large list containing values.
I would like to partition the list into sublists whose size is given in percentage, like 25%, 10%, 10%, 5%, %5, ..., %1% (these should add up to 100%), with respect to the size of the big list.
It seems there is no function like this.

A: You can use np.split like this:
import numpy as np

def splitPerc(l, perc):
    # Turn percentages into values between 0 and 1
    splits = np.cumsum(perc)/100.

    if splits[-1] != 1:
        raise ValueError("percents don't add up to 100")

    # Split doesn't need last percent, it will just take what is left
    splits = splits[:-1]

    # Turn values into indices
    splits *= len(l)

    # Turn double indices into integers.
    # CAUTION: numpy rounds to closest EVEN number when a number is halfway
    # between two integers. So 0.5 will become 0 and 1.5 will become 2!
    # If you want to round up in all those cases, do
    # splits += 0.5 instead of round() before casting to int
    splits = splits.round().astype(np.int)

    return np.split(l, splits)

list = np.arange(100)
percents = np.array([25, 10, 15,  5,  5,  5, 10, 25])
# 100 elements -> lengths of sublists should equal their percents
assert all(percents == map(len, splitPerc(list, percents)))


text:
Q: I have a dictionary & the values are also a dictionary itself- how do I write the values to a CSV, with the key in the values being the column name? Writing this out is a little confusing but it'll be easier to see with my code.I'm not sure if my title accurately describes my issue, I'm a newbie and I'm struggling to wrap my head around this.
main.py (part 1)
new_dict = {}
for ip, host, os, vuln_title, vuln_id, cvss2, cvss3, descr, proof, solu, cves in data[1:]:
    vuln_data = new_dict.setdefault(vuln_id, {"Vulnerability ID": vuln_id, "Name": host, "Affected IP Address": [], "Risk Exposure": cvss3})
    vuln_data["Affected IP Address"].append(ip)

print(new_dict)

Output
{
'202845': {'Vulnerability ID': '202845', 'Name': 'dsm1', 'Affected IP Address': ['10.0.7.2', '10.0.8.1'], 'Risk Exposure': '5.30000019'},
'149055': {'Vulnerability ID': '149055', 'Name': 'bitbucket', 'Affected IP Address': ['10.0.6.4', '10.0.5.9'], 'Risk Exposure': '7.5'},
'201637': {'Vulnerability ID': '201637', 'Name': 'logstash1', 'Affected IP Address': ['10.0.9.12', '10.0.7.24', '10.0.8.5'], 'Risk Exposure': '7.80000019'},
'151610': {'Vulnerability ID': '151610', 'Name': 'bitbucket2', 'Affected IP Address': ['10.0.6.7', '10.0.5.4'], 'Risk Exposure': '5.30000019'}
    }

When I ran

vuln_data = new_dict.setdefault(vuln_id, {"Vulnerability ID": vuln_id,
"Name": host, "Affected IP Address": [], "Risk Exposure": cvss3})

It obviously sets the key to be vuln_id which I would prefer not to, I want the key value pairs, I just don't want to have the vuln_id in front as well. This output below is what I really need:
main.py (part 2)
new_list = new_dict.values()
print(new_list)

Output
[
{'Vulnerability ID': '202845', 'Name': 'dsm1', 'Affected IP Address': ['10.0.7.2', '10.0.8.1'], 'Risk Exposure': '5.30000019'},
{'Vulnerability ID': '149055', 'Name': 'bitbucket', 'Affected IP Address': ['10.0.6.4', '10.0.5.9'], 'Risk Exposure': '7.5'}, '201637':
{'Vulnerability ID': '201637', 'Name': 'logstash1', 'Affected IP Address': ['10.0.9.12', '10.0.7.24', '10.0.8.5'], 'Risk Exposure': '7.80000019'},
{'Vulnerability ID': '151610', 'Name': 'bitbucket2', 'Affected IP Address': ['10.0.6.7', '10.0.5.4'], 'Risk Exposure': '5.30000019'}
]

Now I have a list of these dictionaries and this is all the relevant info that I need, but I'm running into an error when trying to write all of this to a CSV file like-so:
main.py (part 3)
keys = new_list[0].keys()

with open('output.csv', 'w', newline='') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(new_list)

Error
line 16, in <module>
    keys = new_list[0].keys()
TypeError: 'dict_values' object is not subscriptable

I'm really not sure how to get this to work correctly- but with I just want to write to a cdv file with the keys as the column names/header (ie. Vulnerability ID, Name, etc.) and the values to get written as a row

A: I'm just mentioning my way to do it.
l = [
{'Vulnerability ID': '202845', 'Name': 'dsm1', 'Affected IP Address': ['10.0.7.2', '10.0.8.1'], 'Risk Exposure': '5.30000019'},
{'Vulnerability ID': '149055', 'Name': 'bitbucket', 'Affected IP Address': ['10.0.6.4', '10.0.5.9'], 'Risk Exposure': '7.5'},
{'Vulnerability ID': '201637', 'Name': 'logstash1', 'Affected IP Address': ['10.0.9.12', '10.0.7.24', '10.0.8.5'], 'Risk Exposure': '7.80000019'},
{'Vulnerability ID': '151610', 'Name': 'bitbucket2', 'Affected IP Address': ['10.0.6.7', '10.0.5.4'], 'Risk Exposure': '5.30000019'}
]

import pandas as pd
df=pd.DataFrame(l)
print(df)
df.to_csv("outputs.csv", index=False)

output column names as keys


text:
Q: Time Series analysis ARIMA I am trying to predict "daily_cases" using time series analysis.
The time series plot looks like -

The ACF plot of original series is given below-

The above ACF plot suggests that trend is present which needs to be removed using  appropriate differencing.
The ACF and PACF plots of 1-differenced series are given below-

The above plots suggest an ARMA(1,1) process which was also validated by "arma_order_select_ic()" function in python on the basis of "aic" and "bic" scores.
But, after fitting the model I get weird fitted values ,which were way different from observed values(differing by 10000!).
Please help.
Thanks in advance

A: I would recommend using a unit root test like Augmented Dicky Fuller Test to check if your time series is really stationary after differencing, if not you might need to do a second differentiation.


text:
Q: Where are latex macros such as `\@nx` defined? I was looking into the amsmath documentation, particularly the implementation of \genfrac. I find it is difficult to understand because I don't know what commands such as \@nx do.
Where is this stuff defined? Is there a list of commands commonly used in core packages, that one should be aware of to understand their implementation?

A: amsgen.dtx source file has
% \begin{macro}{\@xp}
% \begin{macro}{\@nx}
%    Shorthands for long command names.
%    \begin{macrocode}
\let\@xp=\expandafter
\let\@nx=\noexpand
%    \end{macrocode}
%    \end{macro}
%    \end{macro}
%


text:
Q: Creating a virtual X11 output with Nvidia driver I'm attempting to follow this guide to extend the desktop on computer A to computer B by creating a virtual output on computer A and using vnc to display the virtual output on computer B.
The problem I'm having is that the Nvidia driver does not allow screens that are not connected to be used neither does it create any virtual outputs.
Is it possible to create virtual outputs with the Nvidia (or even Nouveau) drivers?

A: I'm using this on a daily basis. You need an xorg.conf file, in your Device section you need the following:
Option      "nopowerconnectorcheck"
Option      "ExactModeTimingsDVI" "ON"

Then in your Monitor section place your HorizSync, VertRefresh, and ModeLine
Finally in your Screen section add this:
Option "AllowEmptyInitialConfiguration" "True"
Option "ConnectedMonitor" "DFP"
Option "UseDisplayDevice" "DFP-0"
Option "ModeValidation" "AllowNonEdidModes"
SubSection     "Display"
        Depth       24
        Modes       "<Resolution and Refresh from your modeline>"
EndSubSection

What this does is tells the Nvidia driver that there is a monitor attached, and gives it the information required to start drawing to the frame buffer. No monitor required. I do recommend using x11vnc to do your viewing because it polls the screen and is much more responsive to screen changes than any other linux vncserver.


text:
Q: Flat extension of local domains Let $(R,m)$, $(S,n)$ be two local Noetherian domains, $R \subseteq S$ is flat,
and $m \subseteq n$.
Question 1:
If $R$ is regular and $S$ is Cohen-Macaulay,
is $S$ also regular?
Question 2:
If $R$ is Cohen-Macaulay and $S$ is regular,
is $R$ also regular?
My favorite examples:
$R=k[x(x-1)]_{(x(x-1))}$, $S=k[x]_{(x)}$, $R \subseteq S$ is flat (as a localization of a free extension)
and both local domains are regular (localization of a polynomial ring).
$R=k[x^2,x^3]_{(x^2,x^3)}$, $S=k[x]_{(x)}$, but the extension is not flat.
Notice that $R=k[x^2]_{(x^2)}$, $S=k[x^2,x^3]_{(x^2,x^3)}$ is flat,
$R$ is regular, $S$ is CM, but not regular.
I guess that in some special cases one can apply the miracle flatness theorem.
I do not want to assume that $mS$ is a prime ideal in $S$.
I do not mind to assume that $\dim(R)=\dim(S)$.
Thank you very much!
Edit: Perhaps the second answer to this question may help. It says:
"If $f: A \to B$ is flat, then obviously the image of any $A$-regular sequence under $f$ is a $B$-regular sequence." (Does it answer Question 1?).


text:
Q: Upload Encrypted Image on disk in C# ASP.NET C# Application is uploading Signature images of Employees on server, now we want to these signature image is encrypted format for security reason, and when we use these signature in Application then decrypted these signature images for them.
How we can upload image in encrypted format on server and then later on decrypted image also when ever application use?