text:
Q: FTP connection (Java) when I connected to a FTP-Server with sockets how can I send username and password?
thank you for your answers.

A: FTP sends username and password in plain text, so you should be able to just invoke the commands and send them that way (at your own risk).

See also

*

*List of FTP commands

*

*USER - Authentication username.

*PASS - Authentication password.

A: Why not just use Jakarta Commons Net to handle this?
http://commons.apache.org/net/

A: You might want to have a look at FTPClient's source code.


text:
Q: Static electricity—electron donor/acceptor At school, we were taught that in a situation where one material gets rubbed with another, there's a transfer of electrons. This is because the electrons (or charges) jump from one material to the other due to friction.
And we were also told that one of the materials tends to be the giving one in the exchange, which we call the electron donor. And the electron acceptor is the one that takes in the electrons offered by the corresponding electron donor.
And we were given a table with examples of electron donors and acceptors along with that, of the classic hair/comb sort.
When our teacher helpfully added that whether a material acts as an electron donor or acceptor depends on the material it is being rubbed with, it got me thinking.
I was wondering if there were certain pairs of electron donor/acceptor. Pairs of specific materials that synchronise with each other. In the sense that one material in the pair exhibits either of these behaviours only in case of the other material in the pair.
Say, you've got material X which you rub with material Y. It acts as a electron donor perhaps. But it doesn't always behave like an electron donor. You see that it acts as an electron donor only upon friction with that specific material Y.
Do such pairs exist? Hope I had been able to express my question clearly enough.

A: I am not sure if your teacher has mentioned the triboelectric series, which basically lists various materials according to their tendency to accept or donate electrons. Here is a link to one of many pages on this topic.
If you take two materials at the opposite side of this series, the outcome would be predictable. If the materials are close to each other - not so much, i.e., the outcome could be affected by the state of their surfaces or other factors and, in general, the effect won't be significant.
I have not heard of anomalies, though, where two materials on the opposite sides of the triboelectric series, would switch their personalities when paired together.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Any Marketing Cloud SDK Resource for Objective - C (Not Swift) Code? Currently, I am developing the Marketing Cloud function from React Native using MC SDK, and want to implement push handling Url - Open Direct.
However, documentation to Handling URL using Objective C in Xcode (Not Swift) is already gone and redirected to new documentation
Are there any other docs that I can refer to besides the current one? Because right now codes in the new documentation for iOS are using Swift, and I'm not familiar with that. It's also not the basic language from iOS in React Native.
Thank you very much for your help.

A: You can see an old snippet from docs/code here:
    // Framework import
#import <MarketingCloudSDK/MarketingCloudSDK.h>

// Make sure your class adopts the protocol
@implementation AppDelegate <MarketingCloudSDKURLHandlingDelegate>

...
// Set the delegate somewhere in your application code (after configuring the SDK)
[[MarketingCloudSDK sharedInstance] sfmc_setURLHandlingDelegate:<set the delegate to
                                                               be the class implementing
                                                               the protocol method - example:> self];
...
// EXAMPLE IMPLEMENTATIONS

// Implement the protocol method and have iOS handle the URL itself
- (void) sfmc_handleURL:(NSURL *) url type:(NSString *) type
{
    if ([[UIApplication sharedApplication] canOpenURL:url] == YES) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                if (success) {
                  NSLog(@"url %@ opened successfully", url);
                }
                else {
                  NSLog(@"url %@ could not be opened", url);
                }
            }];
        }
        else {
            if ([[UIApplication sharedApplication] openURL:url] == YES) {
                if (url != nil && type != nil) {
                  NSLog(@"url %@ opened successfully", url);
                }
            }
            else
            {
              NSLog(@"url %@ could not be opened", url);
            }
        }
    }
}

// Implement the protocol method and use SFSafariViewController to present the URL within your application
- (void) sfmc_handleURL:(NSURL *) url type:(NSString *) type
{
  UIViewController *topViewController = ... // obtain your app's topmost view controller
  SFSafariViewController *safariViewController = [[SFSafariViewController alloc] initWithURL:url];
  [topController presentViewController:safariViewController animated:YES completion:^{
  }];
}

// Implement the protocol method and take application-specific actions based on the URL itself
- (void) sfmc_handleURL:(NSURL *) url type:(NSString *) type
{
  NSArray *queryItems = url.queryItems;
  for (NSURLQueryItem *item in queryItems) {
    // do something interesting in your application based on the pararmeters in the URL
  }
}

ref. https://gist.github.com/sfmc-mobilepushsdk/d9f3ef00c2678aced1d4e19acbc66b02.  If that does not provide enough guidance then I suggest you seek professional implementation assistance.


text:
Q: Cron: Permission denied on everything As a regular user I can't edit my cron settings.
I get a "permission denied" for everything: listing the cron commands or editing them.
Example:
cron -l
cron: can't open or create /var/run/crond.pid: Permission denied

crontab -e
/var/spool/cron/crontabs/skerit: Permission denied

These are the permissions of /var/run/crond.pid:
-rwxr-Sr-- 1 root root 5 2011-05-27 12:44 crond.pid
---------- 1 root root 0 2011-03-23 21:13 crond.reboot

And the permissions of /var/spool/cron/:
drwxr-sr-x  5 root root     4,0K 2009-12-23 23:01 cron

All users are also added to the /etc/groups file:
crontab:x:102:skerit,www-data

A: This was a messy problem.
I ended up adding all the users to the crontab group, and setting the group ownership of all needed files to that crontab group.
A lot of permissions were messed up. Changing the group ownership to something else first "resets" those permissions.
The crontab executable:
sudo chgrp crontab /usr/bin/crontab
sudo chmod g+s /usr/bin/crontab
Result: -rwxrwsr-x 1 root crontab 37K 2010-04-15 08:51 /usr/bin/crontab
The cron spool files:
sudo chmod 4774 -R /var/spool/cron
Result: drwsrwsr--  5 root crontab  4,0K 2009-12-23 23:01 cron
The cron files in these spool directories need to be READ AND WRITE only. Otherwise they won't run.
sudo chmod 600 /var/spool/cron/crontabs/*
The cron pid file:
sudo chmod 744 /var/run/crond.pid
I think that should cover it.

A: The permissions for the CRON files are set to user root group root, so you'll need to be root to modify or run CRON files. Alternatively you can log in as root and change the groups to something else so you can edit it.

A: What linux distro is this? Is there an /etc/cron.allow or /etc/cron.deny file? If so, what are their contents?
What are the permissions on
/var/spool/cron/crontabs/skerit
Any user should be able to edit their own crontab.


text:
Q: Code times out Ruby According as the number of elements in a set of numbers is odd or even, median of that set is defined respectively as the middle value or the average of the two middle values in the list that results when the set is sorted.
Below is code for calculating the "running" median of a list of numbers. "Running" median is a dynamic median which is re-calculated with the appearance of a new number as the list is scanned for all numbers that have appeared thus far. Input is an integer n followed by a list of n integers, and output should be the "running" median of the list as the list is scanned.  For example,
3
4
1
5

should yield
4
2.5
4

because 4 is the median of [4], 2.5 ((1+4)/2)is the median of [4,1] and 4 again is the median of [4,1,5].
My program works correctly, but it times out on a certain test on very large inputs. I suspect that this copying step is the problem.
a=(a[0,(k=a.index(a.bsearch{|x|x>=t}))].push(t) + a[k,a.length-k])

But I am not sure because this copy is meant to be a shallow copy as far as I know. Also, I am not doing a regular insert anywhere, which would involved shifting elements and thus result in slowing down the code, into the array that contains the numbers.
n=gets.chomp.to_i
a=[]
n.times do
    t=gets.chomp.to_i

    a==[]||(t<=a.first) ? a.unshift(t): t>=a.last ? a.push(t) : a=(a[0,(k=a.index(a.bsearch{|x|x>=t}))].push(t) + a[k,a.length-k])

    p (l=a.count)%2==0 ? ((a[l/2] + a[l/2-1])/2.0).round(1):a[(l-1)/2].round(1)
end

Can anybody point out where the problem could be? Thank you.
Here is a less obfuscated version.
n=gets.chomp.to_i
a=[]
n.times do
    t=gets.chomp.to_i

    if a==[]||(t<=a.first)
        a.unshift(t)
    else
        k=a.index(a.bsearch{|x|x>=t})
        if k.nil? == true
            k=a.length
        end
        a=a[0,k].push(t)+ a[k,a.length-k]
    end
    p (l=a.count)%2==0 ? ((a[l/2] + a[l/2-1])/2.0).round(1):a[(l-1)/2].round(1)
end

A: I think...
a=(a[0,(k=a.index(a.bsearch{|x|x>=t}))].push(t) + a[k,a.length-k])

...because it's creating a new array every time, is likely an expensive operation as the array gets bigger.
Better might actually be something that mutates the original array.
a.insert((a.index{|x|x>t} || -1), t)

It also handles the edge cases of less than first or greater than last, so you can remove those tests. Also works on first pass (empty array a)


text:
Q: Performance impact of stacking multiple Vue components I am building an application that uses Vue to display most of the data that my users will see (charts, tables, etc.)
Now, imagine I have a table built with Vue with a list of actions performed by each user. Now, the user name cell will be especially formatted with the user's picture, social handle, etc. The way the user is presented in this table is the same as it will be in other components. It will also contain some especific functionality (e.g. hovering over the picture will provide expanded information about the user; but this functionality is only planned).
My objective is to reuse as much code as possible. This is why I was planning to have a small UserProfile.vue component inside my Table.vue component. Using this logic, I may repeat this for other information as well (think CompanyProfile.vue, ProjectDetail.vue, etc.).
Is this a good idea? Will it have cause significant performance issues to have multiple vue components inside one and other?

A: Vue has optimized the result of rendered html as far as possible. You don't need to worry a lot about it. Child components only update when their respective data has changed, that is usually quite cheap.
Good to keep in mind:

When authoring components, it's good to keep in mind whether you intend to reuse it somewhere else later. It's OK for one-off components to be tightly coupled, but reusable components should define a clean public interface and make no assumptions about the context it's used in.

For larger applications, you may use Async Components

Vue will only trigger the factory function when the component actually needs to be rendered and will cache the result for future re-renders. For example:

Vue.component('async-example', function (resolve, reject) {
  setTimeout(function () {
    // Pass the component definition to the resolve callback
    resolve({
      template: '
I am async!
'
    })
  }, 1000)
})

I found some interesting topics that you might want to look:
Performance for large number of components
Performance degradation when using components
Unlock performance tracing in vue
Analyze runtime performance
So now, you know what to do. Hope, it helps.


text:
Q: JavaScript injected form field does not appear in POST data I have a form that generates new input fields via JavaScript on click.
the inputs are successfully added to the FORM with the desired naming convention.
<input type="text" name="util_name0" id="util_name0" value="" />

<input type="button" onClick="newUtil(this)" value="Add New" />

newUtil() adds:
<input type="text" name="util_name1" id="util_name1" value="" />

however after posting, print_r($_POST) only lists 'util_name0'.
Normally i'd paste some code, but that's all i really need to do at this point...
form is in an include called from parent.php.
Javascript is called in parent.php
JS:
function newUtil(el) {
    var newval = util_count++;
    $('#qty').attr('value', newval);
    $(el).before('-------------

       Type (i.e. gas, electric...) '+newval+'

       <input type="text" name="util_type'+newval+'" id="util_type'+newval+'" value="" />

       Company Name

       <input type="text" name="util_name'+newval+'" id="util_name'+newval+'" value="" />

       Company Number

       <input type="text" name="util_number'+newval+'" id="util_number'+newval+'" value="" />

');
}

A: Would recommend creating proper objects rather than creating the elements like that.
Create elements and inject them one by one.
EDIT : check link http://domscripting.com/blog/display/99

A: After execute the js code that adding the new field, inspect the new element using Firebug (in Firefox) or Web Inspector (in safari and google chrome). If the new field is outside the form tag, then it will not be included to form submit.
If you can, please provide the structure of form and it's fields. Also, make sure that the page contain no other error, and the tag is well balanced, all open tag have been closed in the right place. Misplace closing tag might yield error and unexpected behaviour.

A: Is this behaving differently in IE than it is in Firefox? Run an HTTP sniffer (like Fiddler) on it check the HTTP post headers carefully.


text:
Q: ClassCastException in karaf only after restart I have a two Bundles A of version 05.18.000  which uses B of 05.18.000 used in Bundle C.
and I have same bundles A and B of different version 05.20.000 used in Bundle D.
Bundle A is trying to cast a concrete class to an interface. Both the interface and implementation classes are in Bundle B.
When I am using both C and D both at runtime they are working fine.
But when I restart the karaf container, a class cast Exception is thrown in Bundle A.
@Override
public String parse(DeviceMessageEnvelope deviceMessageEnvelope) {

    String result = "NO RESULTS";
    LOGGER.debug("HL7MinaServerParserControllerBase.parse called.");
    try {
        HL7MinaServerCommunicationObject commObject = getHL7MinaServerCommunicationObject();

        commObject.initObject((MinaServerCom) getDeviceCom(), deviceMessageEnvelope, getParser());

        LOGGER.debug("HL7MinaServerParserControllerBase: Attempted to connect device com");
        boolean connected = getDeviceCom().connect();

        if (connected) {
            while (commObject.isRunning()) {
                LOGGER.debug("HL7MinaServerParserControllerBase.parse : In Loop isRunning() : " + commObject.isRunning());
                Thread.sleep(getWaitTime());
            }
            LOGGER.debug("HL7MinaServerParserControllerBase.parse : Exit from while commObject.isRunning()");
            result = commObject.getResult();
        }
    } catch (InterruptedException e) {
        LOGGER.warn("HL7MinaServerParserControllerBase.parse :  Error in HL7MinaServerParserControllerBase", e);
    } catch (CommunicationException e) {
        LOGGER.warn("HL7MinaServerParserControllerBase.parse :  Error in HL7MinaServerParserControllerBase", e);
    } catch (MinaSupportConfigurationException e) {
        LOGGER.warn("HL7MinaServerParserControllerBase.parse :  Error in HL7MinaServerParserControllerBase", e);
    } finally {
        try {
            getDeviceCom().release();
        } catch (CommunicationException e) {
            LOGGER.warn("HL7MinaServerParserControllerBase : Error trying to release the com", e);
        }
    }

    return result;
}

Below is the error:
[2018-03-01 22:46:38.287] [Device Id: 10237 Device Name : WA_CMS_GW] ERROR com.company.driver.factory.DeviceTask                            com.company.drvs.sdk.mina.com.server.types.MinaServerComImpl cannot be cast to com.company.drvs.sdk.mina.com.server.MinaServerCom
java.lang.ClassCastException: com.company.drvs.sdk.mina.com.server.types.MinaServerComImpl cannot be cast to com.company.drvs.sdk.mina.com.server.MinaServerCom
    at com.company.drvs.sdk.mina.com.server.types.parser.HL7MinaServerParserControllerBase.parse(HL7MinaServerParserControllerBase.java:43)[411:com.company.drvs.sdk.company-sdk-mina-support-hl7:5.20.0]
    at com.company.drvs.welchallyn.nce.parser.NCEParserController.getResult(NCEParserController.java:57)[412:com.company.drvs.welchallyn-nce.core:1.0.1]
    at com.company.drvs.welchallyn.nce.parser.NCEParserController.parse(NCEParserController.java:45)[412:com.company.drvs.welchallyn-nce.core:1.0.1]
    at com.company.drvs.welchallyn.nce.driver.Driver.execute(Driver.java:67)[412:com.company.drvs.welchallyn-nce.core:1.0.1]
    at com.company.driver.factory.DeviceTask.execute(DeviceTask.java:46)[321:com.company.dxc.DriverHarness:1.10.1.GA]
    at com.company.task.CycleTaskHarness.run(CycleTaskHarness.java:88)[312:com.company.dxc.TaskRunner:1.10.1.GA]
    at java.lang.Thread.run(Thread.java:748)[:1.8.0_161]
[2018-03-01 22:46:38.287] [Device Id: 10237 Device Name : WA_CMS_GW] WARN  com.company.task.CycleTaskHarness                                Task retry: Device Id: 10237 Device Name : WA_CMS_GW, com.company.task.TaskException: com.company.drvs.sdk.mina.com.server.types.MinaServerComImpl cannot be cast to com.company.drvs.sdk.mina.com.server.MinaServerCom
[2018-03-01 22:46:38.287] [Device Id: 10237 Device Name : WA_CMS_GW] ERROR com.company.task.CycleTaskHarness                                Task error:
com.company.task.TaskException: com.company.drvs.sdk.mina.com.server.types.MinaServerComImpl cannot be cast to com.company.drvs.sdk.mina.com.server.MinaServerCom
    at com.company.driver.factory.DeviceTask.execute(DeviceTask.java:54)[321:com.company.dxc.DriverHarness:1.10.1.GA]
    at com.company.task.CycleTaskHarness.run(CycleTaskHarness.java:88)[312:com.company.dxc.TaskRunner:1.10.1.GA]
    at java.lang.Thread.run(Thread.java:748)[:1.8.0_161]
Caused by: java.lang.ClassCastException: com.company.drvs.sdk.mina.com.server.types.MinaServerComImpl cannot be cast to com.company.drvs.sdk.mina.com.server.MinaServerCom
    at com.company.drvs.sdk.mina.com.server.types.parser.HL7MinaServerParserControllerBase.parse(HL7MinaServerParserControllerBase.java:43)[411:com.company.drvs.sdk.company-sdk-mina-support-hl7:5.20.0]
    at com.company.drvs.welchallyn.nce.parser.NCEParserController.getResult(NCEParserController.java:57)[412:com.company.drvs.welchallyn-nce.core:1.0.1]
    at com.company.drvs.welchallyn.nce.parser.NCEParserController.parse(NCEParserController.java:45)[412:com.company.drvs.welchallyn-nce.core:1.0.1]
    at com.company.drvs.welchallyn.nce.driver.Driver.execute(Driver.java:67)[412:com.company.drvs.welchallyn-nce.core:1.0.1]
    at com.company.driver.factory.DeviceTask.execute(DeviceTask.java:46)[321:com.company.dxc.DriverHarness:1.10.1.GA]
    ... 2 more

company-sdk-mina-support-hl7:5.20.0 is the Mentioned Bundle A.
MinaServerComImpl and MinaServerCom are implementations and interface in Bundle B.
The error is happening in this line
commObject.initObject((MinaServerCom) getDeviceCom(), deviceMessageEnvelope, getParser());

MinsServerComImpl is injected through spring and getDeviceCom() returns the instance of MinaServerComImpl.
Please help. Thanks.

A: The usual cause of this is having multiple definitions of the same class(es).
In Java, the identity of a class is the combination of its fully-qualified name AND the ClassLoader that defined it. If two classloaders define a class -- even using the same class data in terms of bytes on the disk -- they will be considered different classes in the JVM. Any subclass that inherits from one of those class definitions will not be considered a subtype of the other definition.
In your case it is likely that you have copied the MinaServerCom class in multiple bundles. Instead ensure that the definition is in only one bundle, from where its package should be exported. Other bundles should import that package.

A: ClassCastException came due to any object of one class cannot convert to the another one only because they are not in relationship 'parent-child'.
As you said.. Problem with this line..
commObject.initObject((MinaServerCom) getDeviceCom(), deviceMessageEnvelope, getParser());

Here getDeviceCom() returns the object of  MinsServerComImpl and you try to cast it into MinaServerCom. then please make sure is there any Is-A relationship in between these two class.
It should be either
class MinsServerComImpl extends MinaServerCom

or
class MinsServerComImpl implements MinaServerCom


text:
Q: hide an image in javascript using its src I have an image defined as following:

I want with a javascript get the image by its src and hide it.
function hideImage() {
  if (document.getElementById()
  {
    if (document.getElementById('logo').getElementsByClassName('wrapper').src=="path/to/the/image/logo.png")
    {
      document.style.visibility = 'hidden';
    }
  }
};

hideImage();

But the code didn't work!! any idea?

A: With jQuery you could write
$('img[src="path/to/the/image/logo.png"]').hide();

A: You have to make sure you have a link to jquery library in your header using this code

You could diplay:none in css if you wanted it not to render on the screen, just pass the image source into the function
function hideImage(imageSrc) {
$('img[src=" + imageSrc + "]').css("display","none");

}

and turn it back on using
$('img[src="path/to/the/image/logo.png"]').css("display","block");

A: You can try this:-
$('img[src="path/to/the/image/logo.png"]').css("display","none");

or try this:-
    this.style.display = "none";

A: getElementsByClassName('wrapper') is an array, which is why you have to access the src-attribute of the first element - at least in your case.
if (document.getElementById('logo').getElementsByClassName('wrapper')[0].src=="path/to/the/image/logo.png")

A: Try this script:
function hideImage() {
    var path = 'path/to/the/image/logo.png';
    var img = document.getElementById('logo').getElementsByTagName('img')[0];
    if (img && img.getAttribute('src').indexOf(path) > -1) {
        img.style.visibility = 'hidden';
    }
}

if (window.addEventListener) {
    window.addEventListener('load', hideImage, false);
} else if (window.attachEvent) { // for older IE8-6 compatibility
    window.attachEvent('onload', hideImage);
}

JSFiddle


text:
Q: Removing arguments from python/argparse (without using parse_known_args) I have two programs, one is a wrapper of the other.
Main program has args order-arg-one, --arg1, --arg2
Wrapper program has all the args of main program, and additional args --arg3 , --arg4
I want to be able to pass the arguments from the wrapper to the main program without getting an 'argument not recognized' error. However, I do not want to use parse_known_args, because then the user receives zero feedback if they made a typo or used a nonsensical argument. (I have already seen this question)
Other than manually searching for every single argument name, and then any value coming immediately after that name if the name is present and its an argument that expects a parameter after is, is there a more elegant way of cleaning my arguments of some set of values in order to pass them on to another parser?

A: An example of mixing various partial parsings:
import argparse

def foo(parser, alist):
   for arg in alist:
        parser.add_argument('--'+arg, action='store_true')

parser1 = argparse.ArgumentParser()
foo(parser1, ['arg1','arg2'])

parser2 = argparse.ArgumentParser()
foo(parser2, ['arg3','arg4'])

parser12 = argparse.ArgumentParser()
foo(parser12, ['arg1','arg2','arg3','arg4'])

args = parser12.parse_args()
print('p12', args)

args, extras = parser2.parse_known_args()
print('p2',args, extras)

args = parser1.parse_args(extras)
print('p1',args)

args, extras = parser1.parse_known_args()
print('p1p',args, extras)

None:
1714:~/mypy$ python3 stack47866170.py
p12 Namespace(arg1=False, arg2=False, arg3=False, arg4=False)
p2 Namespace(arg3=False, arg4=False) []
p1 Namespace(arg1=False, arg2=False)
p1p Namespace(arg1=False, arg2=False) []

all:
1722:~/mypy$ python3 stack47866170.py --arg1 --arg2 --arg3 --arg4
p12 Namespace(arg1=True, arg2=True, arg3=True, arg4=True)
p2 Namespace(arg3=True, arg4=True) ['--arg1', '--arg2']
p1 Namespace(arg1=True, arg2=True)
p1p Namespace(arg1=True, arg2=True) ['--arg3', '--arg4']

subsets
1723:~/mypy$ python3 stack47866170.py --arg1 --arg2
p12 Namespace(arg1=True, arg2=True, arg3=False, arg4=False)
p2 Namespace(arg3=False, arg4=False) ['--arg1', '--arg2']
p1 Namespace(arg1=True, arg2=True)
p1p Namespace(arg1=True, arg2=True) []
1723:~/mypy$ python3 stack47866170.py --arg1 --arg3
p12 Namespace(arg1=True, arg2=False, arg3=True, arg4=False)
p2 Namespace(arg3=True, arg4=False) ['--arg1']
p1 Namespace(arg1=True, arg2=False)
p1p Namespace(arg1=True, arg2=False) ['--arg3']

error - caught by parser12:
1724:~/mypy$ python3 stack47866170.py --arg1 --foo
usage: stack47866170.py [-h] [--arg1] [--arg2] [--arg3] [--arg4]
stack47866170.py: error: unrecognized arguments: --foo


text:
Q: Static to Dynamic nature in C I have implemented naive Bayes but I did it in static memory allocation.
I wanted to convert into dynamic but my small brain is not able to do that.
#define COLS 4 //including class label
#define BINS 100
#define CLASS_COL 0
#define CLASS 2

The idea is to fetch above value from a configuration file and then set it.
struct each_col //Probability for each feature based on classes
{
    double col_PB[BINS][CLASS];
};
struct NB_Class_Map
{
    char label[250];
    unsigned int label_value;
    double class_PB;
};
struct NB //Proabability for entire feature
{
    struct NB_Class_Map classes[CLASS];
    struct each_col cols[COLS];
};
NB nb = {0}; //gloabal value

The function to train NB:
long strhash(const char *str)
{
    long hash = 5381;
    int c;
    printf("IN: %s ",str);
    while (c = *str++)
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

     printf("OUT: %ld  ||",hash);
    return hash;
}

int setup_train_NB(vector<vector<string> > &data)
{
    //Finding the feature count
    static int class_label = -1;
    for(unsigned int i=0;i<data.size();i++)
    {
        unsigned int Class;
        printf("\n===========New ROW==============\n");
        int k;
        for(k=0;k<CLASS;k++)
        {
            if(strcmp(data[i][CLASS_COL].c_str(), nb.classes[k].label) == 0)
            {
                printf("MATCHED\n");
                Class = nb.classes[k].label_value;
                break;
            }
        }
        if(k==CLASS)
        {
            printf("NOT MATCHED\n");
            class_label++;
            nb.classes[class_label].label_value = class_label;
            strcpy( nb.classes[class_label].label, data[i][CLASS_COL].c_str());
            Class = nb.classes[class_label].label_value;
        }

        printf("Class: %d  ||\n", Class);

        for(unsigned j=0;j<data[0].size();j++)
        {
            printf("\n===========New COLUMN==============\n");
            if(j == CLASS_COL)
            {
                nb.classes[Class].class_PB++;
                continue;
            }
            unsigned int bin = strhash((data[i][j].c_str()))%BINS;

            printf("Bin: %d  ||", bin);
            printf("Class: %d  ||\n", Class);
            nb.cols[j].col_PB[bin][Class]++; //[feature][BINS][CLASS]
        }
    }

    //Finding the feature PB
    for(unsigned int i=0;i<COLS;i++)
    {
        if(i==CLASS_COL)
            continue;
        for(unsigned j=0;j<BINS;j++)
        {
            for(unsigned k=0;k<CLASS;k++)
            {
//              nb.cols[i].col_PB[j][k] /= nb.classes[k].class_PB; //without laplacian smoothing
                nb.cols[i].col_PB[j][k] = (nb.cols[i].col_PB[j][k] + 1) / (nb.classes[k].class_PB + COLS - 1); //with laplace smoothing
            }
        }
    }

    int k = 0;
    int sum = 0;
    while(k<CLASS)
    {
        sum += nb.classes[k].class_PB;
        k++;
    }

//Finding the class PB
    k = 0;
    while(k<CLASS)
    {
        nb.classes[k].class_PB /= sum;
        k++;
    }
return 0;
}

The program is supposed to be written in C but for the moment, I use vector to fetched the data from a CSV file. Please ignore that for the moment. The actual question is how I can remove those hardcoded define value and still declare my structs.
Although it does not matter but the CSV file look like this and it may change in terms of no of cols and labels. The first line is ignored and not put into data.
Person,height,weight,foot
male,654,180,12
female,5,100,6
female,55,150,8
female,542,130,7
female,575,150,9

What actually I am doing is, for each value is put into a bin, then for each of those value, I am finding proabability for the CLASS/label i.e male = 0, female = 1

A: Basically:

*

*Define variables instead of preprocessor macro constants: size_t cols; size_t bins; etc.

*Replace your 1-dimensional fixed-size arrays with pointers (initialized to NULL!) and length variables. Alternatively, you could use a struct mytype_span { size_t length; mytype* data; }

*Replace your 2-dimensional fixes-size arrays with "1-dimensional" pointers (also initialized to NULL of course) and pairs off dimension variables. Again, you could use a struct.

*Replace your 2-d array accesses a[x][y] with a "linearized" access, i.e. a[x * row_length_of_a + y] (or you could do this in an inline function which takes the relevant arguments, or a struct mytype_span)

*When you've read your configuration values from, um, wherever - set the relevant length variables (see above).

*use the malloc() library function to allocate the correct amount of space; remember to check the malloc() return value to make sure it's not null, before using the pointer values!

A: Your use of struct, is probably wrong, except for struct NB_Class_Map. You shouldn't use struct in the goal of puting big arrays in the same variable. Instead of this, you should define of variable for each array, not putting it inside a struct, and instead of using array, replace it by a pointer. Then you can allocate memory to your pointer. e.g. :
struct mydata {
    type1 field1;
    type2 field2;
    etc...
    } *myarray;
myarray = calloc(number_of_record_you_need, sizeof(struct mydata));
// here, error checking code, etc.

Now, having done that, if you really want, you may put your different pointers into a global structure, but each of your table should be allocated separately.

Edit (about your variables) :
NB has no real interest as a structure. It's just 2 variables you glued together:
struct NB_Class_Map classes[CLASS];
struct each_col cols[COLS];

NB.Cols is not really a structure. It's just a three dimensional array
double cols[COLS][BINS][CLASS];

The only real structure is
struct NB_Class_Map
{
    char label[250];
    unsigned int label_value;
    double class_PB;
};

So you just have to replace
struct NB_Class_Map classes[CLASS];

with
struct NB_Class_Map *classes;

and
double cols[COLS][BINS][CLASS];

with
double *cols[BINS][CLASS];

Or if you want a type name :
typedef double each_col[BINS][CLASS];
each_cols *cols;

and allocate memory space for classes and colls with calloc.
Now, if you really want this struct NB :
typedef double each_col[BINS][CLASS];

struct NB
{
    struct NB_Class_Map *classes;
    each_col *cols;
};


text:
Q: NTP bufferoverflow in ctl_putdata() After reading this:
http://googleprojectzero.blogspot.de/2015/01/finding-and-exploiting-ntpd.html
The Bug
The most severe bug that turned out to be exploitable on OS X Mavericks is a buffer overflow in the code which handles control packets. Control mode responses are fragmented if they exceed the size of the buffer used to store them, as implemented in the following function:
static void
ctl_putdata(
  const char *dp,
  unsigned int dlen,
  int bin   /* set to 1 when data is binary */
  )
{
  //[...]

   /*
    * Save room for trailing junk
    */
   if (dlen + overhead + datapt > dataend) {
     /*
      * Not enough room in this one, flush it out.
      */
    ctl_flushpkt(CTL_MORE);
   }
   memmove((char *)datapt, dp, (unsigned)dlen);
   datapt += dlen;
   datalinelen += dlen;
}

As you can see, if the data to be written doesn't fit into the remaining buffer space ctl_flushpkt() is called, which will send out the current packet and reset the datapt to point to the beginning of the buffer. However, memmove will be called in any case and if dlen is bigger than the total buffer size it will overflow the buffer.

Some basics:
I spent long time to understand it, so here are my findings.
To overflow a buffer a long var needs to be set and than read, in my tests around 1000 chars did the trick. I did set it in a file config and than read:
/etc/ntp.conf
setvar a = AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
:rv 0 a
It overflows.
(gdb) x/400x 0x684b0c
0x684b0c <rpkt+12>: 0x41413d61  0x41414141  0x41414141  0x41414141
0x684b1c <rpkt+28>: 0x41414141  0x41414141  0x41414141  0x41414141
0x684b2c <rpkt+44>: 0x41414141  0x41414141  0x41414141  0x41414141
0x684b3c <rpkt+60>: 0x41414141  0x41414141  0x41414141  0x41414141
0x684b4c <rpkt+76>: 0x41414141  0x41414141  0x41414141  0x41414141
0x684b5c <rpkt+92>: 0x41414141  0x41414141  0x41414141  0x41414141
0x684b6c <rpkt+108>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684b7c <rpkt+124>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684b8c <rpkt+140>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684b9c <rpkt+156>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684bac <rpkt+172>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684bbc <rpkt+188>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684bcc <rpkt+204>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684bdc <rpkt+220>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684bec <rpkt+236>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684bfc <rpkt+252>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684c0c <rpkt+268>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684c1c <rpkt+284>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684c2c <rpkt+300>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684c3c <rpkt+316>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684c4c <rpkt+332>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684c5c <rpkt+348>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684c6c <rpkt+364>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684c7c <rpkt+380>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684c8c <rpkt+396>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684c9c <rpkt+412>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684cac <rpkt+428>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684cbc <rpkt+444>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684ccc <rpkt+460>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684cdc <rpkt+476>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684cec <rpkt+492>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684cfc <rpkt+508>:    0x41414141  0x41414141  0x41414141  0x41414141
0x684d0c:   0x41414141  0x41414141  0x41414141  0x41414141
0x684d1c:   0x41414141  0x41414141  0x41414141  0x41414141
0x684d2c <utsnamebuf+12>:   0x41414141  0x41414141  0x41414141  0x41414141
0x684d3c <utsnamebuf+28>:   0x41414141  0x41414141  0x41414141  0x41414141
0x684d4c <utsnamebuf+44>:   0x41414141  0x41414141  0x41414141  0x41414141
0x684d5c <utsnamebuf+60>:   0x41414141  0x41414141  0x41414141  0x41414141
0x684d6c <utsnamebuf+76>:   0x41414141  0x41414141  0x41414141  0x41414141
0x684d7c <utsnamebuf+92>:   0x41414141  0x41414141  0x41414141  0x41414141
---Type <return> to continue, or q <return> to quit---
0x684d8c <utsnamebuf+108>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684d9c <utsnamebuf+124>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684dac <utsnamebuf+140>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684dbc <utsnamebuf+156>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684dcc <utsnamebuf+172>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684ddc <utsnamebuf+188>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684dec <utsnamebuf+204>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684dfc <utsnamebuf+220>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684e0c <utsnamebuf+236>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684e1c <utsnamebuf+252>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684e2c <utsnamebuf+268>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684e3c <utsnamebuf+284>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684e4c <utsnamebuf+300>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684e5c <utsnamebuf+316>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684e6c <utsnamebuf+332>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684e7c <utsnamebuf+348>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684e8c <utsnamebuf+364>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684e9c <utsnamebuf+380>:  0x41414141  0x41414141  0x41414141  0x41414141
0x684eac <ext_sys_var+4>:   0x41414141  0x41414141  0x41414141  0x41414141
0x684ebc <filegen_registry+4>:  0x00000000  0x00000000  0x00000000  0x00000000
0x684ecc <config_timer>:    0x00000000  0x00000000  0x00000000  0x00000000
0x684edc:   0x00000000  0x00000000  0x00000000  0x00000000
0x684eec:   0x00000000  0x00000000  0x00000000  0x00000000
0x684efc:   0x00000000  0x00000001  0x00000000  0x8749597e

Program received signal SIGSEGV, Segmentation fault.
read_variables (rbufp=<optimized out>, restrict_mask=<optimized out>) at ntp_control.c:2300
2300                for (i = 0; ext_sys_var &&

However I want to set it via control packet
:config setvar var = AAAAAAA
Setting long value doesn't help, since Control Packets requests cannot be fragmented. But setting long name and reading all variables on the server, you can make a Control Packet response big enough to be fragmented.
You can read all variables on the server with
:rv 0 sys_var_list
I tried to set a long variable name in order to trigger overflow.
:config setvar bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb = 1
Than read it via
:rv 0 sys_var_list
(gdb) x/400x  0x684b0c
0x684b0c <rpkt+12>: 0x5f737973  0x5f726176  0x7473696c  0x656c223d
0x684b1c <rpkt+28>: 0x732c7061  0x74617274  0x702c6d75  0x69636572
0x684b2c <rpkt+44>: 0x6e6f6973  0x6f6f722c  0x6c656474  0x722c7961
0x684b3c <rpkt+60>: 0x64746f6f  0x2c707369  0x69666572  0x65722c64
0x684b4c <rpkt+76>: 0x6d697466  0x63742c65  0x6565702c  0x666f2c72
0x684b5c <rpkt+92>: 0x74657366  0x6572662c  0x6e657571  0x732c7963
0x684b6c <rpkt+108>:    0x6a5f7379  0x65747469  0x6c632c72  0x696a5f6b
0x684b7c <rpkt+124>:    0x72657474  0x6f6c632c  0x702c6b63  0x65636f72
0x684b8c <rpkt+140>:    0x726f7373  0x7379732c  0x2c6d6574  0x73726576
0x684b9c <rpkt+156>:    0x2c6e6f69  0x5f6b6c63  0x646e6177  0x732c7265
0x684bac <rpkt+172>:    0x765f7379  0x6c5f7261  0x2c747369  0x2c696174
0x684bbc <rpkt+188>:    0x7061656c  0x2c636573  0x69707865  0x6d2c65---Type <return> to continue, or q <return> to quit---
72
0x684bcc <rpkt+204>:    0x63746e69  0x6561642c  0x5f6e6f6d  0x73726576
0x684bdc <rpkt+220>:    0x2c6e6f69  0x74746573  0x6f656d69  0x79616466
0x684bec <rpkt+236>:    0x6363612c  0x5f737365  0x696c6f70  0x612c7963
0x684bfc <rpkt+252>:    0x6262622c  0x62626262  0x62626262  0x62626262
0x684c0c <rpkt+268>:    0x62626262  0x62626262  0x62626262  0x62626262
0x684c1c <rpkt+284>:    0x62626262  0x62626262  0x62626262  0x62626262
0x684c2c <rpkt+300>:    0x62626262  0x62626262  0x62626262  0x62626262
0x684c3c <rpkt+316>:    0x62626262  0x62626262  0x62626262  0x62626262
0x684c4c <rpkt+332>:    0x62626262  0x62626262  0x62626262  0x62626262
0x684c5c <rpkt+348>:    0x62626262  0x62626262  0x62626262  0x62626262
0x684c6c <rpkt+364>:    0x62626262  0x62626262  0x62626262  0x62626262
---Type <return> to continue, or q <return> to quit---
0x684c7c <rpkt+380>:    0x62626262  0x62626262  0x62626262  0x62626262
0x684c8c <rpkt+396>:    0x62626262  0x62626262  0x62626262  0x62626262
0x684c9c <rpkt+412>:    0x62626262  0x62626262  0x62626262  0x62626262
0x684cac <rpkt+428>:    0x62626262  0x62626262  0x62626262  0x62626262
0x684cbc <rpkt+444>:    0x62626262  0x62626262  0x62626262  0x62626262
0x684ccc <rpkt+460>:    0x62626262  0x62626262  0x62626262  0x62626262
0x684cdc <rpkt+476>:    0x0a0d2262  0x00000000  0x00000000  0x00000000
0x684cec <rpkt+492>:    0x00000000  0x00000000  0x00000000  0x00000000
0x684cfc <rpkt+508>:    0x00000000  0x00000000  0x00000401  0x00000000
0x684d0c:   0x00000000  0x00000000  0x00000000  0x00000000
0x684d1c:   0x00000000  0x756e694c  0x00000078  0x00000000
0x684d2c <utsnamebuf+12>:   0x00000000  0x00000000  0x00000000  0x00000000
0x684d3c <utsnamebuf+28>:   0x00000000  0x00000000  0x00000000  ---Type <return> to continue, or q <return> to quit---
0x00000000
0x684d4c <utsnamebuf+44>:   0x00000000  0x00000000  0x00000000  0x00000000

I managed to get the biggest packet to be of dlen 466, but the buffer is 504 bytes
My question is:

*

*How did the author overflow this buffer?

It is hard to explain it here, but I hope you got the point.
Thanks,

A: It's size is as the size of u_char pointer. But it is pointing to an array of size 480 + MAX_MAC_LEN = 480+(6 * sizeof(u_int32)) = 480+6*4=504 bytes as it is assigned with the address of the data field of ntp_control struct.


text:
Q: copy paste not working in windows 10 office 365 while splitting word document using VBA The following code split the document by section breaks. however it is working correctly in windows 7 but not in windows 10 office 365, having "run time error 4605 : the command is not available." on windows 10? while I try to paste the copied content using oNewDoc.Range.Paste. I came to know it was due to oNewDoc windows not activate or pasting take place without waiting to oNewDoc to be created. because when I press debug and wait for 1 second then run again it executes correctly.
Private Sub GenerateFiles_Click()

    'Pages Update 1.0 By M.B.A.

    Dim oNewDoc As Document
    Dim oDoc As Document
    Dim CR As Range

    Dim firstLine As String
    Dim strLine As String
    Dim DocName As String
    Dim pdfName As String

    Dim arrSplit As Variant
    Dim Counter As Integer
    Dim i As Integer

    Dim PS As String

    PS = Application.PathSeparator

    'Progress
    pBarCurrent 0

    If pdfCheck.Value = False And docCheck.Value = False Then
        PagesLB = "**Please Select at least one check boxes!"
        Beep
        Exit Sub
    End If

        Set oDoc = ActiveDocument
        Set CR = oDoc.Range
        Letters = oDoc.Range.Information(wdActiveEndSectionNumber)
        Counter = 1

    While Counter < Letters + 1

        With oDoc.Sections.First.Range
                .MoveEnd wdSection, 0
                .MoveEnd wdCharacter, -1
                .Copy
                '.Select
            Set oNewDoc = Documents.Add(Visible:=True)

                oNewDoc.Range.Paste 'Run-time error '4605': This command is not available

        End With

        firstLine = oNewDoc.Paragraphs(1).Range.Text
        For i = 1 To 2
            strLine = oNewDoc.Paragraphs(i).Range.Text
            If InStr(strLine, ".pdf") > 0 Then
                arrSplit = Split(strLine, ".pdf")
                DocName = arrSplit(0) & ".pdf"
                Exit For
            End If
        Next i

        If i = 3 Then

            DocName = Left(firstLine, 45)
            DocName = Replace(DocName, vbCr, "")

        End If

        DocName = Replace(DocName, Chr(11), "")

        pdfName = Counter & " - " & DocName & IIf(i = 3, ".pdf", "")
        DocName = Counter & " - " & IIf(i < 2, Replace(DocName, ".pdf", ""), DocName) & ".docx"

        'Debug.Print pdfName; vbNewLine; DocName

        If docCheck Then
            oNewDoc.SaveAs FileName:=oDoc.Path & PS & ValidWBName(DocName), AddToRecentFiles:=False
        End If

        If pdfCheck Then
            oNewDoc.SaveAs FileName:=oDoc.Path & PS & ValidWBName(pdfName), FileFormat:=wdFormatPDF
        End If

        oDoc.Sections.First.Range.Cut

        '== Progress Bar =='
        DoEvents
        PagesLB = " Letter " & Counter & " of " & Letters & vbCr & " " & Int((Counter / (Letters)) * 100) & "% Completed..."
        pBarCurrent Int((Counter / (Letters)) * 100)
        oNewDoc.Close False
        Counter = Counter + 1

    Wend

    PagesLB = Letters & " Letters has been Created..."
    oDoc.Close wdDoNotSaveChanges
    Beep

End Sub

A: You can avoid using the clipboard by using the FormattedText property
    With oDoc.Sections.First.Range
        .MoveEnd wdSection, 0
        .MoveEnd wdCharacter, -1
        Set oNewDoc = Documents.Add(Visible:=True)
        oNewDoc.Range.FormattedText = .FormattedText
    End With


text:
Q: SciPy integrate ode doesnt' work after cythonized I wrote a simple script. It integrates a DE:
from scipy import integrate

def rhs(t, x):
    return x

solver = integrate.ode(rhs)
solver.set_integrator('dopri5')
solver.set_initial_value(1.0, 0.0)
solver.integrate(0.2)
print solver.y

It works correct. But if I cythonize it and load from another python script, I get the error:
capi_return is NULL
Call-back cb_fcn_in___user__routines failed.
Traceback (most recent call last):
  File "...\tmp\build\lib.win-amd64-2.7\test2.py", line 1, in <module>
    import test
  File "test.py", line 9, in init test (test.c:1113)
  File "...\Anaconda\lib\site-packages\scipy\integrate\_ode.py", line 408, in integrate
    self.f_params, self.jac_params)
  File "...\Anaconda\lib\site-packages\scipy\integrate\_ode.py", line 1032, in run
    tuple(self.call_args) + (f_params,)))
  File "test.py", line 3, in test.rhs (test.c:748)
TypeError: rhs() takes exactly 2 positional arguments (1 given)

The setup.py script contains:
from distutils.core import setup
from Cython.Build import cythonize

ext_modules = cythonize(['*.py'], exclude=['setup.py'])
setup(name='some_module', version='1.0', description='bla bla', ext_modules=ext_modules)

In the second script I just call
import test

P.S. I use anaconda python-2.7 for windows7, x64. I've got the latest version of scipy. I created the testproject gitlab.


text:
Q: inject into before serialization wcf I want to use IDispatchMessageInspector and BeforeSendReply method to change replay before return to client but it is too late cause message are serialized then.
It is another wcf interface or other way to change data returned by service but not serialized yet?
I want to use data return by service to generate new data and do my own serialization when accept type is text/html

A: The component which converts between the return object and the outgoing message is the IDispatchMessageFormatter. Content negotiation (changing the response format depending on the incoming Accept header) is doable in the "classic" WCF, but you'll need to write your own formatter to deal with it - on incoming requests it would check what's the accept header and store it somewhere (such as the operation context), and on outgoing responses it would get the value of that header and decide how to format the outgoing response.
With the WCF Web APIs, however, content negotiation is a lot easier, and there are indeed many samples that do exactly that. Check it out at http://wcf.codeplex.com - the Content Manager sample has some content negotiation capabilities.


text:
Q: Multiple selec2.js file loaded by several plugins Since upgrading to WP 4.2.2, I have the following error in one of my js file :
Uncaught TypeError: jQuery(...).select2 is not a function
I google the issue and it seems that this can happen when several jquery are loaded.
However, looking in the different plugins, and in my theme, I found out that several plugins (and my theme) do wp_enqueue_script of select2.js, none of them with the same version (3.1 to 3.5.2).
So my questions :

*

*is this normal that each plugins has its own version ?

*what could be the issue for the original error : Uncaught TypeError: jQuery(...).select2 is not a function ?

Thanks for your help

A:
is this normal that each plugins has its own version ?

If the script isn't registered by Core there isn't much else a plugin/theme can do but register the script itself. If would be nice if there were some standardization, but that would be a tricky problem to solve.

what could be the issue for the original error : Uncaught TypeError:
  jQuery(...).select2 is not a function ?

This is not likely to be directly WordPress related and I'd be guessing but see: https://stackoverflow.com/q/29968409/1735890


text:
Q: Entry and Exit points on times series chart data Is the following actually possible in SQL?
I have some time-series data and I want to extract some entry and exit points based on prices.
Desired output:

Example Data:

SQL Data:
CREATE TABLE Control
    ([PKey] int, [TimeStamp] datetime, [Name] varchar(10), [Price1] float, [Price2] float);

INSERT INTO Control ([PKey], [TimeStamp], [Name], [Price1], [Price2])
VALUES
    (1,'2018-10-01 09:00:00', 'Name1',120, 125),
    (2,'2018-10-01 09:10:00', 'Name1',110, 115),
    (3,'2018-10-01 09:20:00', 'Name1',101, 106),
    (4,'2018-10-01 09:30:00', 'Name1',105, 110),
    (5,'2018-10-01 09:40:00', 'Name1',106, 111),
    (6,'2018-10-01 09:50:00', 'Name1',108, 113),
    (7,'2018-10-01 10:00:00', 'Name1',110, 115),
    (8,'2018-10-01 10:10:00', 'Name1',104, 109),
    (9,'2018-10-01 10:20:00', 'Name1',101, 106),
    (10,'2018-10-01 10:30:00', 'Name1',99, 104),
    (11,'2018-10-01 10:40:00', 'Name1',95, 100),
    (12,'2018-10-01 10:50:00', 'Name1',101, 106),
    (13,'2018-10-01 11:00:00', 'Name1',102, 107),
    (14,'2018-10-01 11:10:00', 'Name1',101, 106),
    (15,'2018-10-01 11:20:00', 'Name1',99, 104),
    (16,'2018-10-01 11:30:00', 'Name1',105, 110),
    (17,'2018-10-01 11:40:00', 'Name1',108, 113),
    (18,'2018-10-01 11:50:00', 'Name1',108, 113),
    (19,'2018-10-01 12:00:00', 'Name1',109, 114),
    (20,'2018-10-01 12:10:00', 'Name1',108, 113),
    (21,'2018-10-01 12:20:00', 'Name1',105, 110),
    (22,'2018-10-01 12:30:00', 'Name1',101, 106),
    (23,'2018-10-01 12:40:00', 'Name1',102, 107),
    (24,'2018-10-01 09:00:00', 'Name2',103, 108),
    (25,'2018-10-01 09:10:00', 'Name2',101, 106),
    (26,'2018-10-01 09:20:00', 'Name2',104, 109),
    (27,'2018-10-01 09:30:00', 'Name2',106, 111),
    (28,'2018-10-01 09:40:00', 'Name2',108, 113),
    (29,'2018-10-01 09:50:00', 'Name2',108, 113),
    (30,'2018-10-01 10:00:00', 'Name2',105, 110),
    (31,'2018-10-01 10:10:00', 'Name2',103, 108),
    (32,'2018-10-01 10:20:00', 'Name2',101, 106),
    (33,'2018-10-01 10:30:00', 'Name2',99, 104),
    (34,'2018-10-01 10:40:00', 'Name2',101, 106),
    (35,'2018-10-01 10:50:00', 'Name2',104, 109),
    (36,'2018-10-01 11:00:00', 'Name2',101, 106),
    (37,'2018-10-01 11:10:00', 'Name2',99, 104),
    (38,'2018-10-01 11:20:00', 'Name2',106, 111),
    (39,'2018-10-01 11:30:00', 'Name2',103, 108),
    (40,'2018-10-01 11:40:00', 'Name2',105, 110),
    (41,'2018-10-01 11:50:00', 'Name2',108, 113),
    (42,'2018-10-01 12:00:00', 'Name2',105, 110),
    (43,'2018-10-01 12:10:00', 'Name2',104, 109),
    (44,'2018-10-01 12:20:00', 'Name2',108, 113),
    (45,'2018-10-01 12:30:00', 'Name2',110, 115),
    (46,'2018-10-01 12:40:00', 'Name2',105, 110)
;

What have I tried:
I am able to get the first instance of an entry and exit point using the following query which finds the first entry point PKey and then finds the first exit point after the entry point PKey
declare @EntryPrice1 float = 101.0; -- Entry when Price1 <= 101.0 (when not already Entered)
declare @ExitPrice2 float = 113.0; -- Exit when Price2 >= 113.0 (after Entry only)

select
 t1.[Name]
,t2.[Entry PKey]
,min(case when t1.[Price2] >= @ExitPrice2 and t1.[PKey] > t2.[Entry PKey] then t1.[PKey] else null end) as [Exit PKey]
from [dbo].[Control] t1
left outer join
(select min(case when [Price1] <= @EntryPrice1 then [PKey] else null end) as [Entry PKey]
,[Name]
from [dbo].[Control]
group by [Name]) t2
on t1.[Name] = t2.[Name]
group by t1.[Name],t2.[Entry PKey]

--Name  Entry PKey  Exit PKey
--Name1     3       6
--Name2     25      28

I'm stuck on the approach to use that will allow multiple entry/exit points to be returned and not sure if it's even possible in SQL.
The logic for entry an exit points are
Entry - when price1 <= 101.0 and not already in an entry that has not exited.
Exit - when price2 >= 113.0 and inside an entry.

A: It's a kind of gaps and islands problem, this is a generic solution using Windowed Aggregates (should work for most DBMSes):
declare @EntryPrice1 float = 101.0; -- Entry when Price1 <= 101.0 (when not already Entered)
declare @ExitPrice2 float = 113.0; -- Exit when Price2 >= 113.0 (after Entry only)

WITH cte AS
 ( -- apply your logic to mark potential entry and exit rows
   SELECT *
     ,CASE WHEN Price1 <= @EntryPrice1 THEN Timestamp END AS possibleEntry
     ,CASE WHEN Price2 >= @ExitPrice2  THEN Timestamp END AS possibleExit
     ,Max(CASE WHEN Price1 <= @EntryPrice1 THEN Timestamp END) -- most recent possibleEntry
      Over (PARTITION BY Name
            ORDER BY Timestamp
            ROWS Unbounded Preceding) AS lastEntry
     ,Max(CASE WHEN Price2 >= @ExitPrice2 THEN Timestamp END) -- most recent possibleExit
      Over (PARTITION BY Name
            ORDER BY Timestamp
            ROWS BETWEEN Unbounded Preceding AND 1 Preceding) AS lastExit
   FROM [dbo].[Control]
 )
-- SELECT * FROM cte ORDER BY Name, PKey
,groupRows AS
 ( -- mark rows from the 1st entry to the exit row
   SELECT *
     -- if lastEntry <= lastExit we're after an exit and before an entry -> don't return this row
     ,CASE WHEN lastEntry <= lastExit THEN 0 ELSE 1 END AS returnFlag
     -- assign the same group number to consecutive rows in group
     ,Sum(CASE WHEN lastEntry <= lastExit THEN 1 ELSE 0 END)
      Over (PARTITION BY Name
            ORDER BY Timestamp
            ROWS Unbounded Preceding) AS grp
   FROM cte
   WHERE (possibleEntry IS NOT NULL OR possibleExit IS NOT NULL)
     AND lastEntry IS NOT NULL
 )
-- SELECT * FROM groupRows ORDER BY  Name, PKey
,rowNum AS
 ( -- get the data from the first and last row of an entry/exit group
   SELECT *
     -- to get the values of the 1st row in a group
     ,Row_Number() Over (PARTITION BY Name, grp ORDER BY Timestamp) AS rn
     -- to get the values of the last row in a group
     ,Last_Value(Price2)
      Over (PARTITION BY Name, grp
            ORDER BY Timestamp
            ROWS BETWEEN Unbounded Preceding AND Unbounded Following) AS ExitPrice
     ,Last_Value(possibleExit)
      Over (PARTITION BY Name, grp
            ORDER BY Timestamp
            ROWS BETWEEN Unbounded Preceding AND Unbounded Following) AS ExitTimestamp
     ,Last_Value(CASE WHEN possibleExit IS NOT NULL THEN PKey END)
      Over (PARTITION BY Name, grp
            ORDER BY Timestamp
            ROWS BETWEEN Unbounded Preceding AND Unbounded Following) AS ExitPKey
   FROM groupRows
   WHERE returnFlag = 1
 )
SELECT Name
  ,Price1 AS EntryPrice
  ,ExitPrice
  ,Timestamp AS EntryTimestamp
  ,ExitTimestamp
  ,PKey AS EntryPKey
  ,ExitPKey
FROM rowNum
WHERE rn = 1 -- return 1st row of each group
ORDER BY Name, Timestamp

See dbfiddle
Of course it might be possible to simplify the logic or apply some proprietary SQL Server syntax...

A: This is a weird form of gaps-and-islands.  Start with the very basic definitions of entry and exit:
  select c.*,
         (case when [Price1] <= @EntryPrice1 then 1 else 0 end) as is_entry,
         (case when [Price2] >= @ExitPrice2 then 1 else 0 end) as is_exit
  from control c;

This doesn't quite work because two adjacent "entries" count only as a single entry.  We can get the information we need by looking at the previous entry/exit time.  With that logic, we can determine which entries are "real".  We might as well get the next exit time as well:
with cee as (
      select c.*,
             (case when [Price1] <= @EntryPrice1 then 1 else 0 end) as is_entry,
             (case when [Price2] >= @ExitPrice2 then 1 else 0 end) as is_exit
      from control c
     ),
     cp as (
      select cee.*,
             max(case when is_entry = 1 then pkey end) over (partition by name order by timestamp rows between unbounded preceding and 1 preceding) as prev_entry,
             max(case when is_exit = 1 then pkey end) over (partition by name order by timestamp) as prev_exit,
             min(case when is_exit = 1 then pkey end) over (partition by name order by timestamp desc) as next_exit
      from cee
     )

Next, use this logic to generate a cumulative sum of real entries, and then do some fancy filtering:
with cee as (
      select c.*,
             (case when [Price1] <= @EntryPrice1 then 1 else 0 end) as is_entry,
             (case when [Price1] >= @ExitPrice1 then 1 else 0 end) as is_exit
      from control c
     ),
     cp as (
      select cee.*,
             max(case when is_entry = 1 then pkey end) over (partition by name order by timestamp rows between unbounded preceding and 1 preceding) as prev_entry,
             max(case when is_exit = 1 then pkey end) over (partition by name order by timestamp) as prev_exit,
             min(case when is_exit = 1 then pkey end) over (partition by name order by timestamp desc) as next_exit
      from cee
     )
select *
from cp
where cp.is_entry = 1 and
      (prev_entry is null or prev_exit > prev_entry)

This gives you the rows where the entry starts.  You can join in to get the additional information you want.


text:
Q: Android - Sinch get push from own server with ManagedPush I'm using Sinch for App-to-App messaging with ManagedPush set to true which states that

NOTE: Using setSupportManagedPush(true) will register a token with Google Cloud Messaging using a Sender ID connected to Sinch, which will implicitly unregister your own token. You should not register any token with GCM if using Sinch push notifications.

Now beside push notifications from Sinch for Instant messaging, There are also other notifications i want to receive from my own server like general Ad etc for all users, I done some R&D but not able to figure out following

*

*As Sinch registers GCM token itself so can i use the same token to send push notification from my own server?

*If Answer for 1 is yes then how can i get Sinch registered token to send to my own server to receive notifications from my own server too along with one's sent via Sinch?

*Or is there any way to get GCM token registered via Sinch from Google server?

A: If you already have your infrastrucutre to send push, I would use that instead of managed push. So instead of setSupportManagedPush(true) set setSupportPush(true) and then send the push to your server in onShouldSendPush event


text:
Q: Как получить доступ к содержиому HTML-тега с помощью Jsoup Не могу получить доступ к содержимому тега datetime(получить дату "12 апреля 2017"). Как это сделать при помощи Jsoup?

    Екатеринбург

    <time datetime="2017-04-12T11:26:36Z">12 Апреля 2017 16:26</time>

      <svg viewBox="0 0 16 16">

        <path d="M13.8 1.4c.4 0 .7.3.7.7v8c0 .4-.3.7-.7.7H7.5l-3.2 2.3v-2.2H2.2c-.4 0-.7-.3-.7-.7v-8c0-.4.3-.7.7-.7l11.6-.1m0-1.4H2.2C1 0 0 1 0 2.2v8c0 1.2 1 2.2 2.2 2.2h.7V16L8 12.4h5.8c1.2 0 2.2-1 2.2-2.2v-8C16 1 15 0 13.8 0z"></path></svg>

      <svg viewBox="0 0 24 24">

        <path d="M12 9.229c.234-1.12 1.547-6.229 5.382-6.229 2.22 0 4.618 1.551 4.618 5.003 0 3.907-3.627 8.47-10 12.629-6.373-4.159-10-8.722-10-12.629 0-3.484 2.369-5.005 4.577-5.005 3.923 0 5.145 5.126 5.423 6.231zm-12-1.226c0 4.068 3.06 9.481 12 14.997 8.94-5.516 12-10.929 12-14.997 0-7.962-9.648-9.028-12-3.737-2.338-5.262-12-4.27-12 3.737z"></path></svg>

Музей истории Екатеринбурга ищет «око Саурона» для Водонапорной башни на Плотинке


text:
Q: how to add quotation one in jquery append i want to change format onclick from SendLowongan(000031) to SendLowongan('000031')
this is my code
var html = '
<button type="button" class="btn btn-success" id="send" onclick="SendLowongan(' + getdata.IDLowongan + ')"> Kirim Lowongan</button> <button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button>
';
        $("#footermodal").append(html);

A: You need to change this part:
...."SendLowongan(' + getdata.IDLowongan + ')"....

with:
..."SendLowongan(\'' + getdata.IDLowongan.trim() + '\')"....
                 ^^                      ^^^^^^^    ^^

function SendLowongan(d) {
    console.log('--->' + d + '<----');
}

var getdata = {};
getdata["IDLowongan"] = " 000035";

var html = '
<button type="button" class="btn btn-success" id="send" onclick="SendLowongan(\'' + getdata.IDLowongan.trim() + '\')"> Kirim Lowongan</button> <button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button>
';
$("#footermodal").append(html);

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" >


text:
Q: How to create NetworkCredentials for AuthType.Kerberos LdapConnection? In the case of AuthType.Basic this works in my server component:
// Provided by client
string username = "ou=user,uid=bob";
string password = "secr3t";

// Server side code that authenticates client at an LDAP server
string ldapServer = "my.server.org";
var credential = new NetworkCredential(username, password);
var connection = new LdapConnection(new LdapDirectoryIdentifier(ldapServer),
                                    credential,
                                    AuthType.Basic);
connection.Bind();

My next task is to use AuthType.Kerberos instead. As far I understood, the client sends a Kerberos ticket instead of its username and password to the server.
I imagine the result to look something like this:
// Provided by client
var kerberosTicket = /*???*/;

// Server side code that authenticates client at an LDAP server
string ldapServer = "my.server.org";
var credential = new NetworkCredential(/*kerberosTicket ???*/);
var connection = new LdapConnection(new LdapDirectoryIdentifier(ldapServer),
                                    credential,
                                    AuthType.Kerberos);
connection.Bind();

What data type contains a Kerberos ticket and how can I convert it into a NetworkCredential?


text:
Q: Progress Bar while sending ByteArray to Server through Action Method in MVC 3 I have a byte-array that i upload to the server through action method from javascript (MVC3):
      $.ajax({
        url: '@Url.Action("Upload")',
        type: 'POST',
        contentType: 'application/x-amf',
        processData: false,
        data: ByteArrayData,
        success: function (result) {
            alert(result);
        }

    });

I was wondering what is the easiest way to make a percentage progress bar while the bytes are getting sent to the server?

A: Easiest way would be to Mask the content using javascript or show Javascript progress bar on view, until you get the response back from Server.

A: My initial (and boring) response is that this would be hard to do, but I'm not wise enough with the HTTP post request to completely be sure if it is or isn't possible. Essentially though you'd have to either know:

*

*Size of posted data

*Upload speed

OR

*

*Size of posted data

*Data sent each interval (if such a thing even exists?)

I'm not sure you can access either of these combinations with JavaScript. You'd probably need to use some sort of flash uploader for this.


text:
Q: Why is the number Pi more popular than any other constant? What is so special about the number $\pi$? There are many more interesting constants,
such as
e, $\gamma, \sqrt{2}$ or the catalanian number.
$\pi$ has been calculated to more digits than any other irrational number.
$\pi$ is the only number used in memory contests. There is even a pi-day, the
14th March.
Is there any reason for that ?

A: Apparently because is the oldest one! It is 2500 years old!


text:
Q: Updating Power Query Source I have a 'Master' sheet that are made up of multiple sheets within the same workbook. I have combined the data from all the sheets to the 'Master' sheet using Power Query. However, I have to repeat a couple of steps(create connection, update source, etc) to include any newly created sheet into the 'Master' sheet.
I am looking at options to automate this process using VBA. Not sure how to start. Thanks!


text:
Q: Error installing MoveIt 2 from source on Ubuntu 20.04 VM I'm trying to get involved in open source and also am quite interested in robotics, so I thought about contributing to MoveIt 2. As a first step, I'm installing MoveIt 2 from source on my Ubuntu 20.04 VM in VirtualBox.
I've run through all the instructions here: https://moveit.ros.org/install-moveit2/source/#:~:text=colcon%20build%20%2D%2Devent%2Dhandlers%20desktop_notification%2D%20status%2D%20%2D%2Dcmake%2Dargs%20%2DDCMAKE_BUILD_TYPE%3DRelease
However, the build is failing on the highlighted part. The error message is as follows:
Starting >>> geometric_shapes
--- stderr: geometric_shapes
CMake Error at CMakeLists.txt:47 (find_package):
  By not providing "Findeigen3_cmake_module.cmake" in CMAKE_MODULE_PATH this
  project has asked CMake to find a package configuration file provided by
  "eigen3_cmake_module", but CMake did not find one.

  Could not find a package configuration file provided by
  "eigen3_cmake_module" with any of the following names:

    eigen3_cmake_moduleConfig.cmake
    eigen3_cmake_module-config.cmake

  Add the installation prefix of "eigen3_cmake_module" to CMAKE_PREFIX_PATH
  or set "eigen3_cmake_module_DIR" to a directory containing one of the above
  files.  If "eigen3_cmake_module" provides a separate development package or
  SDK, be sure it has been installed.

---
Failed   <<< geometric_shapes [1.20s, exited with code 1]

Summary: 0 packages finished [1.46s]
  1 package failed: geometric_shapes
  1 package had stderr output: geometric_shapes
  33 packages not processed

Any help is really appreciated. Thanks!

A: You have to install ROS2 before building Move It 2. After installing the ROS2 binaries, the error doesn't occur.


text:
Q: Fluid Dynamics Problem A vertical circular stack 100 ft high converges uniformly from a diameter of 20 ft at the bottom to 16 ft at the top. Coal gas with a unit weight of 0.030 pcf enters the bottom of the stack with a velocity of 10 fps. The unit weight of the gas increases uniformly to 0.042 pcf at the top. What is the mean velocity 25 ft above the bottom of the stack?

A: Converting velocity in to volumetric flow rate
At the bottom of stack:$$v_1 = \frac{Q_1}{A_1}$$
From this find $Q_1$
Thus $$Q_1 = 10\times \pi\times 10^2 = 1000\pi$$
Now since the unit weight changes, equate the mass flow rate such as below:
$$\rho_1\times Q_1 = \rho_2\times Q_2$$
Unit weight changes uniformly down the stack at the rate of $\frac{(.042-.030)}{100} = 0.00012$
At the stack height of 25 ft , the unit weight $= .03+0.00012*25 = 0.033$
Thus $\rho_2 = 0.033$.  Apply this in the equation above to get $Q_2$
$$Q_2 = \frac{0.03*1000\pi}{0.033} = 909.09\pi$$
Now $$V_2 = \frac{Q_2}{A_2} = \frac{909.09\pi}{9.5^2\pi}$$
If you solve this you get $v_2 = 10.07$ fps


text:
Q: C: split string to string array with delimiter "&&" I'm kinda new in C so i need help.
I need to split a string to string array with the delimiter "&&",
the thing is that i tried to use strtok, but when i use it, it looks like that the strtok can't handle correctly if the is '&' some where in the string.
I know that each part between the && is at max 256 chars and that there are at most 16 parts.
so i need to create an array arr[16][256] or an array of size 16*256.
in any case each time i try my code fail on the different between & and &&
example:
    char arr[16][255];
    char stringToSplit = "Hello World && How are u doing && more words & bla &";

output:
    arr[0] = "Hello World ";
    arr[1] = " How are u doing ";
    arr[2] = " more words & bla &";

Thanks ahead!
This is what i tried:
  int i;
  char *p;
  i = 0;
  p = strtok (stringToSplit ,"&&");
  while (p != NULL)
  {
    arr[i++] = p;
    p = strtok (NULL, "&&");
  }
  for (i=0;i<16; ++i)
    printf("%s\n", arr[i]);

A: strtok() splits the string on characters.
You need strstr() to find a string inside a string then copy the relevant characters to the destination. Keep doing this until the source string is exhausted.

A: A simple double nested loop will do.  check for "&&" and watch out for long sub-strings and too many sub-strings.
void  tubu13(void) {
  #define NUM (16)
  #define SIZ (255+1)

  char arr[NUM][SIZ];
  const char *stringToSplit = "Hello World && How are u doing && more words & bla &";

  const char *p = stringToSplit;
  int n, len;
  for (n = 0; n < NUM; n++) {
    for (len=0; len < SIZ-1; len++) {
      if (p[0] == '\0') {
        break;
      }
      if (p[0] == '&' && p[1] == '&') {
        p += 2;
        break;
      }
      arr[n][len] = *p;
      p++;
    }
    arr[n][len] = '\0';
    printf("  arr[%d] = \"%s\";\n", n, arr[n]);
  }
}

arr[0] = "Hello World ";
arr[1] = " How are u doing ";
arr[2] = " more words & bla &";
arr[3] = "";
...
arr[15] = "";

A: #include <stdio.h>
#include <string.h>

char *strtokByWord_r(char *str, const char *word, char **store){
    char *p, *ret;
    if(str != NULL){
        *store = str;
    }
    if(*store == NULL) return NULL;
    p = strstr(ret=*store, word);
    if(p){
        *p='\0';
        *store = p + strlen(word);
    } else {
        *store = NULL;
    }
    return ret;
}
char *strtokByWord(char *str, const char *word){
    static char *store = NULL;
    return strtokByWord_r(str, word, &store);
}

int main(){
    char arr[16][255];
    char stringToSplit[] = "Hello World && How are u doing && more words & bla &";
    int i, n;
    char *p;
    i = 0;
    p = strtokByWord(stringToSplit, "&&");
    while (p != NULL){
        strcpy(arr[i++], p);
        p = strtokByWord(NULL, "&&");
    }
    n = i;
    for (i=0;i<n; ++i)
        printf("%s\n", arr[i]);
    return 0;
}


text:
Q: How shall I understand this simple example of No Free Lunch theorem? I have trouble in understanding a simple example following No Free Lunch theorem in James Spall's Introduction to stochastic search and optimization:
My understanding  is that a cost function is a mapping from a finite set $\{\theta_i\}$ to a finite set $\{L_j\}$. A search algorithm, when applied to a cost function, is to search for a $\theta_i$ such that the value of the cost function at it is the least.

If there are $N_\theta$ possible values in $\{\theta_i\}$  and $N_L$
  possible values in $\{L_j\}$, then by direct enumeration there are
  $N_L^{N_\theta}$ possible mappings from $\{\theta_i\}$ to $\{L_j\}$.
The NFL theorems indicate that: When averaging over all $N_L^{N_\theta}$ possible mappings from from $\{\theta_i\}$ to
  $\{L_j\}$, all algorithms work the same (i.e., none can work better
  than a blind random search).
Example 1.7—NFL implications in a small problem. Suppose that $\Theta = \{\theta_i, \theta_2, \theta_3\}$ and that there are two
  possible outcomes for the noise-free loss measurements, $\{L_1,
 L_2\}$. Hence, $N_L^{N_\theta} =2^3 =8$. Table 1.1 summarizes the
  eight possible mappings.
Note that all rows in Table 1.1 have the same number of $L_1$ and
  $L_2$ values. Hence, the mean loss value across all eight possible
  problems is the same regardless of which $\theta_i$ is chosen. Because
  the algorithm chooses the $\theta_i$, all algorithms produce the same
  mean loss value when averaging across all possible problems. As a
  specific instance of the implication of the NFL theorems, suppose that
  $L_1 < L_2$. Then, an algorithm that puts priority on picking $\theta$
  will work well on problems 1, 2, 3, and 7, but poorly on problems 4,
  5, 6, and 8. The average performance is the same as an algorithm that
  puts priority on picking $\theta_2$ or $\theta_3$.

My questions are:

*Does the example assume that an algorithm will always output the
same element in $\Theta$, regardless of which of the eight loss
function it is applied to? (This is the only way that I can make sense out of the example. Otherwise, how shall I understand it?)
If yes, isn't it contrary to what an algorithm is in reality? For
example, for minimizing different cost functions, the gradient descent algorithm outputs different solutions instead of a fixed solution.
If no, I can construct an algorithm that outputs $\theta_1$ for cost function 1, 2, 3, 7 and 8, $\theta_2$ for cost function 4 and 5, and $\theta_3$ for cost function 6. This algorithm outputs the best solution for each cost function, so when considering its average performance over all cost functions, it is obviously better than many other algorithms. This violates NFL theorem. What is going wrong?

*What exactly is a search algorithm? Is it a mapping from some set to another set?
.
Thanks and regards!

A: I think the answer to 2 will guide you a little better on 1.  First off, you should probably read the Wolpert and McReady 1997 paper for a more precise definition than what I'm stating here.
[1] There are only 8 possible mappings between the inputs and the outcomes, each of which is enumerated as a column of the table. Your constructed example assumes that you have more information about the problem (in this case, that you know the cost functions). NFL is restricted to cases where you have no a priori knowledge of the domain, which is not strictly true in many practical applications.
[2] A search algorithm (using the terms defined in your question), is an ordered sequence of the inputs (a tuple in computer science terms).

A: Question 2, first. In NFL analysis, optimization (search) is decomposed into sampling of the objective function (mapping), and use of the sample to generate an output. It is tacitly assumed that all optimizers under comparison process samples identically. The NFL literature uses the terms search algorithm and optimization algorithm to refer to the sampler alone. When the codomain of the mapping (set of loss values) is finite, the most intuitive representation of a deterministic (non-random) sampler is as a decision tree. I provide one that is a fairly good match for Spall's example in Figure 1 of my 2004 paper on NFL.
Back to Question 1. You can know quite a bit about the mapping, and still not know how to go about optimizing it. For instance, I can tell you that two elements of the domain map to $L_1,$ and that the other maps to $L_2.$ This how many information takes you from eight possible mappings to just three: those in columns 2, 4, and 7. But you are still totally lacking in information as to which inputs are associated with which outputs. That is because the set of remaining functions $F^\prime = \{f_2, f_4, f_7\}$ is closed under permutation. For each $f$ in $F^\prime$,
$$F^\prime = \{f \circ \sigma \mid \sigma \mathrm{~is~a~permutation~of~}\Theta\}.$$
(A permutation is a 1-to-1 correspondence on a set.) The condition under which you cannot justify a choice of sampler is that the set of mappings is, as far as you know, closed under permutation. A good way to understand why things work this way is to scrutinize the decision tree.


text:
Q: Feedback Notification (iOS) One of my application have 70k+ users and I am sending notifications to them but it is taking more than 7 hours to send a notification to all users.
So, I want to check out of them how many users have installed my application and how many users have to remove it from the mobile.
For that, I research some things and find out Feedback Notification will use for that.
But I don't know how it works and implements in iOS.
Could anyone please suggest me some details for the same or also suggest any other way how I can find users who have removed my app from the mobile.


text:
Q: Tensorflow object detection next steps Im trying to train a model to check images, identify specified objects and tell me its coodinates (i dont even need to see an square around the object).
For this im using Tensorflow's object detection and most of what I did was looking this tutorial:
How To Train an Object Detection Classifier for Multiple Objects Using TensorFlow (GPU) on Windows 10
But some things changed, probably because of updates, and then I had to do somethings on my own. I can actually train the model (I guess) but I don't understand the evaluation results. Im used to see loss and current step but this output is unusual for me. Also I don't think the training is being saved.
Training command line:
model_main.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_coco.config

Config file:
model {
  faster_rcnn {
    num_classes: 9
    image_resizer {
      keep_aspect_ratio_resizer {
        min_dimension: 600
        max_dimension: 1024
      }
    }
    feature_extractor {
      type: 'faster_rcnn_inception_v2'
      first_stage_features_stride: 16
    }
    first_stage_anchor_generator {
      grid_anchor_generator {
        scales: [0.25, 0.5, 1.0, 2.0]
        aspect_ratios: [0.5, 1.0, 2.0]
        height_stride: 16
        width_stride: 16
      }
    }
    first_stage_box_predictor_conv_hyperparams {
      op: CONV
      regularizer {
        l2_regularizer {
          weight: 0.0
        }
      }
      initializer {
        truncated_normal_initializer {
          stddev: 0.01
        }
      }
    }
    first_stage_nms_score_threshold: 0.0
    first_stage_nms_iou_threshold: 0.7
    first_stage_max_proposals: 300
    first_stage_localization_loss_weight: 2.0
    first_stage_objectness_loss_weight: 1.0
    initial_crop_size: 14
    maxpool_kernel_size: 2
    maxpool_stride: 2
    second_stage_box_predictor {
      mask_rcnn_box_predictor {
        use_dropout: false
        dropout_keep_probability: 1.0
        fc_hyperparams {
          op: FC
          regularizer {
            l2_regularizer {
              weight: 0.0
            }
          }
          initializer {
            variance_scaling_initializer {
              factor: 1.0
              uniform: true
              mode: FAN_AVG
            }
          }
        }
      }
    }
    second_stage_post_processing {
      batch_non_max_suppression {
        score_threshold: 0.0
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 300
      }
      score_converter: SOFTMAX
    }
    second_stage_localization_loss_weight: 2.0
    second_stage_classification_loss_weight: 1.0
  }
}

train_config: {
  batch_size: 5
  optimizer {
    momentum_optimizer: {
      learning_rate: {
        manual_step_learning_rate {
          initial_learning_rate: 0.0002
          schedule {
            step: 900000
            learning_rate: .00002
          }
          schedule {
            step: 1200000
            learning_rate: .000002
          }
        }
      }
      momentum_optimizer_value: 0.9
    }
    use_moving_average: false
  }
  gradient_clipping_by_norm: 10.0
  fine_tune_checkpoint: "faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt"
  from_detection_checkpoint: true
  num_steps: 50000
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
}

train_input_reader: {
  tf_record_input_reader {
    input_path: "C:/tensorflow1/models/research/object_detection/images/train.record"
  }
  label_map_path: "C:/tensorflow1/models/research/object_detection/training/object-detection.pbtxt"
}

eval_config: {
  num_examples: 67
  max_evals: 10
}

eval_input_reader: {
  tf_record_input_reader {
    input_path: "C:/tensorflow1/models/research/object_detection/images/test.record"
  }
  label_map_path: "C:/tensorflow1/models/research/object_detection/training/object-detection.pbtxt"
  shuffle: false
  num_readers: 1
}

Output:
2019-03-16 01:05:23.842424: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512] Adding visible gpu devices: 0
2019-03-16 01:05:23.842528: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-03-16 01:05:23.845561: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990]      0
2019-03-16 01:05:23.845777: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003] 0:   N
2019-03-16 01:05:23.847854: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 6390 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1070, pci bus id: 0000:01:00.0, compute capability: 6.1)
creating index...
index created!
creating index...
index created!
Running per image evaluation...
Evaluate annotation type *bbox*
DONE (t=0.05s).
Accumulating evaluation results...
DONE (t=0.04s).
 Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.681
 Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 1.000
 Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.670
 Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.542
 Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.825
 Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = -1.000
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.682
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.689
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.689
 Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.556
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.825
 Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = -1.000

Also the models inside faster_rcnn_inception_v2_coco_2018_01_28 have not been changed since Jan 2018, which probably means that even if it's training, it's not saving the progress.
My questions are:

*

*Am I doing something wrong with the config or something else?

*Is the training progress being saved ?

*How can I understand this output? (IoU? maxDets? area? negative
precision? is it for a single batch or what?)

*Should I wait for this stops by itself eventually? I cant see at
which step I am at and just this piece of output that I used as
example here took almost 15 minutes to appear.

A: Wow, a lot of questions to answer here.
1 .I think your config file is correct, usually the fields that need to be carefully configured are:

*

*num_classes: the number of classes of your dataset

*fine_tune_checkpoint: the checkpoint to start the training with if you adopt tansfer learning, this should be provided if from_detection_checkpoint is set true.

*label_map_path: path to your label file, the number of classes should be equal to num_classes

*input_path in both train_input_reader and eval_input_reader

*num_examples in eval_config, this is your validation dataset size, e.g. the number of examples in your validation dataset.

*num_steps: this is the total number of training steps to reach before the model stops training.

2 Yes, your training process is being saved, it is saved at train_dir (if you are using the older version api, but model_dir if you are using the latest version), the official description is here. You can use tensorbard to visualize your training process.
3 The output if of COCO evaluation format as this is the default evalution metric option. But you can try other evalution metrics by setting metrics_set : in eval_config in the config file, other options are available here. For coco metrics, specifically:

*

*IoU is Intersection over Union, this defines how much your detection bounding box overlaps with your groundtruth box. This answer provides more details for you to understand how the precision is calculated on different IoUs.

*maxDets is thresholds on max detections per image (see here for better discussion)

*area, there are three categories of area, it depends the number of pixels the area takes, small, medium and large are all defined here.

*As for negative precision for category 'large', I think this is because this is the default value if no detections are categorized as 'large' (But I cannot confirm this, you may refer to the official coco website http://cocodataset.org/#home)

*The evaluation is performed on the whole validation dataset, so all images in your validation set.

*This file provides more details on coco metrics

4 The training will stop once the total number of training step is reached to num_steps as set in your cofig file. In your case, every 15 minutes an evaluation session is performed. Also how often each evaluation is performed can also be configured in the config file.
5 Although you followed the tutorial above, but I suggest follow the official API documentation https://github.com/tensorflow/models/tree/master/research/object_detection.
PS: Indeed I can confirm the negative precision score is because of the absence of corresponding category. See reference in the cocoapi.


text:
Q: How to stop rotation on `willRotateToInterfaceOrientation:` I need a way to force the orientation back to portrait on rotate.
The problem is that I have a Tab bar controller, but only want one of the tabs to autorotate.
So I have allowed rotation on all tabs and now I need a way to intercept a rotation on a tab where I don't want to allow rotation.
I'm guessing I can do this on - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration?
Thanks
Tom

A: There is no way to force rotation. In case of a UITabBarController you are out of luck. It is an all or nothing situation wrt interface rotation. If one of your tabs cannot rotate then the whole UITabBarController stays in portrait mode fixed.

A: Maybe this would even work if implemented in all your viewControllers:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return (return ([[self.tabBarController.selectedViewController class] isSubclassOfClass:[TurnableViewController class]]) || UIInterfaceOrientationIsPortrait(toInterfaceOrientation);
}

This will, however, not turn back your view if you switch back to a non-turnable, until you tilt your device...


text:
Q: Count number of left nodes of a tree in mysql Following is my table structure
*id name parent *
1 King  0

2 Scott 1

3 Tiger 1

4 Oracle 2

5 MSSql  2

6 MySQL  3

I wish to count the number of child nodes under King
In MSSQL i was able to do it using WITH for recursion. How to do the same using MYSQL


text:
Q: Unity: How to get the size of a prefab, (2d polygoncollider) I got a prefab and and want to spawn it in the scene, but without it spawning in the ground.
my idea was, that i get the size (which doesnt work) and try setting it in the scene with some basic maths and look if it overlaps with my ground.
how do i tackle this problem? any answer is appreciated
(btw the collider.size doensnt work with a polygon collider)


text:
Q: What could be the cause for Socket errors reported by JMeter I am running a test with 350 users at peak. I have split the tests in two machine with one machine running 220 users and rest on the other machine. On both the machines after a few minutes of run I start seeing socket exception, socket time-out exception and HTTP host exception.
I have tried to find any error that correlates to this exception in the load-balancer (software), IIS logs, application logs and environment monitoring system but I have not found them any where.
I read a lot of blogs and answers on SO that have had the same problem and were able to solve it through changing JMeter settings. I have attempted all of these settings but none have helped.
I am running my test on
Windows Server 2012 R2/ 6 GB RAM/ 64 Bit OS/ 64 bit Java/ Intel Xeon CPU E5-46170 @ 2.90 GHz processor/ JMeter 2.13

My JMeter.bat setting are:
set HEAP=-Xms1536m -Xmx2048m
set NEW=-XX:NewSize=128m -XX:MaxNewSize=1024m -XX:+UseConcMarkSweepGC
set SURVIVOR=-XX:SurvivorRatio=3 -XX:TargetSurvivorRatio=50%
set TENURING=-XX:MaxTenuringThreshold=12
rem Java 8 remove Permanent generation, don't settings the PermSize
if %current_minor% LEQ "8" (
    rem Increase MaxPermSize if you use a lot of Javascript in your Test Plan :
    set PERM=-XX:PermSize=64m -XX:MaxPermSize=128m
)

set IPV4=-Djava.net.preferIPv4Stack=true
set ARGS=%DUMP% %HEAP% %NEW% %SURVIVOR% %TENURING% %RMIGC% %PERM% %DDRAW% %IPV4%

My HC.Parameter settings are:
http.connection.stalecheck$Boolean=true

My user.properties settings are:
jmeter.save.saveservice.output_format=csv
jmeter.save.saveservice.data_type=false
jmeter.save.saveservice.label=true
jmeter.save.saveservice.response_code=true
jmeter.save.saveservice.response_data.on_error=false
jmeter.save.saveservice.response_message=false
jmeter.save.saveservice.successful=true
jmeter.save.saveservice.thread_name=true
jmeter.save.saveservice.time=true
jmeter.save.saveservice.subresults=false
jmeter.save.saveservice.assertions=false
jmeter.save.saveservice.latency=true
jmeter.save.saveservice.bytes=true
jmeter.save.saveservice.hostname=true
jmeter.save.saveservice.thread_counts=true
jmeter.save.saveservice.sample_count=true
jmeter.save.saveservice.response_message=false
jmeter.save.saveservice.assertion_results_failure_message=false
jmeter.save.saveservice.timestamp_format=yyyy/MM/dd HH:mm:ss.SSS
jmeter.save.saveservice.default_delimiter=,
jmeter.save.saveservice.print_field_names=true
jmeter.save.saveservice.autoflush=true

httpclient4.retrycount=1
hc.parameters.file=hc.parameters

I am running my test for 2 hours and my test have been set to loop forever, Stop Thread on error (also run using: start next thread loop on error). I have checked Download Embedded resources and have set the connection Pool as 6(also run with 4).
I have run the tests using default HTTP client and HTTPClient 4.
As of now I can think of 3 other things to try but I am pretty much at the end of my wits and could use a few suggestions.

*

*IP Spoofing,

*Run with Java Client

*Run in Server client mode.

If you need additional information i'll provide as much as I can but please help!
Additional information:
Socket errors I am getting
org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl$6: I/O exception (java.net.SocketException) caught when processing request: Connection reset
org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl$6: I/O exception (java.net.SocketException) caught when processing request: Connection reset by peer: socket write error

Directly hitting IIS
I ran some tests by directly hitting one server with Failed request logging turned on and noticed the below errors.
A process serving application pool 'XXXXXXXXX' failed to respond to a ping.
The process was terminated due to an internal error in the .NET Runtime at IP XXXXXXXXXXXXXX with exit code 80131506.

A: When you load test, it happens very often that application under test cannot handle the load which will manifest as socket rest, socket timeout...
In your case the server is closing the connection, this means it's probably overloaded.
You need to check the components on server side:

*

*Firewall

*Load Balancer

*Apache or IIS or any other webserver

*J2EE server like tomcat or jboss or other similar


text:
Q: Bash script throws "assignment to invalid subscript range" when running from zsh Update
Looking through this link, I updated the array subscript to start with 1 instead of 0 and seems like the array variable is read properly.
#!/bin/bash

#Root folders for Git update.
    ROOT[1]="/Users/ayusman/dev/repos1"
    ROOT[2]="/Users/ayusman/dev/repos2"

#do some things with the ROOT variable.

But I start seeing errors else where for my previously declared shell functions not being recognized.

command not found: git

So I think the generalized question is:
How do I port my perfectly running shell scripts written to run in bash shell to zsh shell?
I recently upgraded my Mac to macOs Catalina 10.15.2
One of my shell scripts that looks like this:
#!/bin/bash

#Root folders for Git update.
    ROOT[0]="/Users/ayusman/dev/repos1"
    ROOT[1]="/Users/ayusman/dev/repos2"

#do some things with the ROOT variable.

This used to work fine when my default shell was a bash shell.
All I am doing here is adding a few folders to an array variable that I am going to use in the shell script.
Post the upgrade and making my default shell as zsh, I see the following error when I start the script (through an alias in my .zsrc file)
[ayusman@~10:39AM]$updateExpediaGitRepos
/Users/ayusman/scripts/updateGitRepos.sh:250: ROOT: assignment to invalid subscript range
[ayusman@~10:39AM]$

I verified that when I change my shell back to bash (by doing chsh like below), the same script runs as expected.
chsh -s /bin/bash

So essentially the question is can I not use my existing bash scripts as it is and run from a zsh shell?
Thanks,
Ayusman

A: It sounds like you're asking zsh to interpret that script. You don't say what updateExpediaGitRepos is, but I suppose that alias sources that script, using the . or source builtin command. Those are the commands to tell the current shell interpreter to interpret code in a file, so the shebang (#! /bin/bash) is not relevant. The shebang is only used by the kernel when you try to execute a script.
Presumably, that updateGitRepos.sh is used to customize the user's environment by modifying attributes of the user's shell (like setting environment variables, defining functions, aliases...), in which case executing it would not help.
bash and zsh are interpreters for two different and incompatible languages (though they have things in common as they both took a lot of inspiration from the Bourne shell, Korn shell and C shell). You can't generally expect one to be able to interpret code written for the other.
In particular, array implementations are very different.
zsh arrays are really arrays, whose indices start at 1 like in most other shells and tools typically used from the shell (more on that at Is there a reason why the first element of a Zsh array is indexed by 1 instead of 0?).
bash arrays are copied from the Korn shell. They are sparse arrays (more like associative array with keys limited to positive integers) and indices start at 0.
zsh supports a number of emulations which can be used to interpret code written for other shells. In particular, it's got a ksh emulation mode which could be useful for parsing bash scripts using arrays here.
emulate ksh

to start it.
Or:
emulate ksh -c 'some code'

To evaluate code in that emulation mode. Functions declared in that mode inherit the emulation mode.
Among other things, in the ksh emulation mode, the KSH_ARRAYS option is turned on which makes array indices start at 0 (but are still not sparse).
So here, you could try to modify your alias so that it does:
emulate ksh -c '. /Users/ayusman/scripts/updateGitRepos.sh'

instead of
. /Users/ayusman/scripts/updateGitRepos.sh

That may or may not be enough in your case. That emulation mode only improves compatibility with ksh, it doesn't make zsh a ksh clone. And ksh is not bash.
If updateGitRepos.sh is indeed intended to be sourced into the user's shell, then you should have different versions of the script for each of the supported shell each written in the corresponding language, or use a syntax that is compatible to all the supported shells, which generally precludes arrays (but see Test for array support by shell for possible approaches).
If that script is only meant to be executed, not interpreted by the user's interactive shell, then make sure you execute it, as /path/to/the/script which thanks to the shebang will make sure the right interpreter is started to interpret it, not source /path/to/the/script, not zsh /path/to/the/script (bash /path/to/the/script would also work here since it's a bash script (despite the misleading .sh extension)).

A: The behavior is because of how arrays work in zsh shell, their indices start at 1 and not at 0. So any access to elements at index 0 will throw the error you are seeing.
From the zsh manual - 15.2.1 Array Subscripts

15.2.1 Array Subscripts
Individual elements of an array may be selected using a subscript. A subscript of the form [exp] selects the single element exp, where exp is an arithmetic expression which will be subject to arithmetic expansion as if it were surrounded by $((...)). The elements are numbered beginning with 1, unless the KSH_ARRAYS option is set in which case they are numbered from zero
If the KSH_ARRAYS option is not set, then by default accesses to an array element with a subscript that evaluates to zero return an empty string, while an attempt to write such an element is treated as an error. For backward compatibility the KSH_ZERO_SUBSCRIPT option can be set to cause subscript values 0 and 1 to be equivalent; see the description of the option in Description of Options.

So, to emulate the behavior of arrays starting with index 0, set this option at the top of the script
setopt ksh_arrays

To clarify why the script was exhibiting zsh behavior, even when the she-bang interpreter was set to #!/bin/bash. Possibly the script was ran with an explicit invocation as zsh <script> in which case the OS does not recognize the interpreter line at the top of the script. Once the script is made itself an executable (chmod +x) and ran with ./<script>, the interpreter provided in the top of the script would be honoured.