text:
Q: Git empty response from server over https vpn after upgrade to sierra I've been facing this weird issue ever since i upgraded osx to Sierra,
all pulls/push fail with the following error for a remote repo over client vpn (Theres a VPN + firewall over browser).Its been failing for everyone who has updated to osx sierra on my team and works for people who are still on El Capitan...
GIT_CURL_VERBOS=1 GIT_TRACE=1 git pull origin master
16:52:02.657710 git.c:350               trace: built-in: git 'pull' 'origin' 'master'
16:52:02.660782 run-command.c:336       trace: run_command: 'fetch' '--update-head-ok' 'origin' 'master'
16:52:02.661465 exec_cmd.c:120          trace: exec: 'git' 'fetch' '--update-head-ok' 'origin' 'master'
16:52:02.665573 git.c:350               trace: built-in: git 'fetch' '--update-head-ok' 'origin' 'master'
16:52:02.671371 run-command.c:336       trace: run_command: 'git-remote-https' 'origin' 'https://<URL>/repo.git'
fatal: unable to access 'https://<URL>/repo.git': Empty reply from server

My git config looks like below-:
http.sslverify=false
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true
core.ignorecase=true
core.precomposeunicode=true

The repo is hosted on a gitlab server,i've already updated git and everything else to the latest version.One more thing i've noticed is that accessing the gitlab repo over chrome seems to work but not over Safari(It takes a long long time and sometimes fails).
I'd like some help trying to debug whats happening?Is there any more level of logging i can get to see what headers are going and what the response is?


text:
Q: How to change the input values, min value and max value in the input type=range using jquery? I'm  new to jquery and html5.
My jquery is:
var A_Route=['A1','A2','A3',.....'A50'];
var counter=0;
$("input[name='radio-choice']").change(function(){
    if ($(this).val() == "on")
    {
        $('#slider').val(A_Route[counter]);

    }

When I select a radio button whose value is ON the min and max value for the slider should automatically become A1 and A50 respectively. And as I slide through the slider my values should change from A1 to A50.
My Html Is:

                <fieldset data-role="controlgroup" data-type="horizontal">
                    <legend>Layout view:</legend>
                          <input type="radio" name="radio-choice" id="radio-choice-c" value="on" checked="checked" />
                          List
                          <input type="radio" name="radio-choice" id="radio-choice-d" value="off" />
                          Grid
                          <input type="radio" name="radio-choice" id="radio-choice-e" value="other" />
                          Gallery
                            </fieldset>

        Room:
        <input type="range" name="slider" id="slider" value="--------" min=? max=? data-highlight="true"  />

What do you think the min and max code should be? and
How can I change the input values from A1 to A50?

A: The value of the input slider should only be any valid floating point number. So I don't think it is going to work with the min max values you want to use.
With regards to the jQuery code to set min and max attributes, you should use the attribute method:
    $('#slider').attr('min', A_Route[0]);
    $('#slider').attr('max', A_Route[3]);

See it working here

redpajama_set_name: RedPajamaStackExchange


text:
Q: get before and after days based on 2 dataframes (date time ) i have a data frame which is of format(date range from start="2018-09-09",end="2020-02-02") with values from 1 to 513

I have another data frame with the format(only 3 dates)

based on second data frame i want 2 dates before and 1 date after what I mean is this

A: Edited: Corrected answer as per the question
If you do this:
keep = []
for val in df2['value']:
    keep += [val-3, val-2, val-1, val]
df_final = df1.take(keep)

Assumption: Your value columns always starts from 1 and is sequential. Also, its datatype is integer not string.
What it does:
The row numbers (indices) of every date = value of that row - 1, since indices start from 0.
So this keeps only the value-3 (2 days before), value-2 (1 day before), value-1 (that day present in df2) and value (1 day after) indices in the keep list.
Then DataFrame.take(indices) does the work for us, by only taking from the mentioned DataFrame df1 the rows with indices mentioned in the argument indices, a list.


text:
Q: Store properties in database, but override locally Currently, we store our application's environment properties in a .properties file in the WEB-INF.  We want to move them to a database table.  But we still want to specify the jndi name, and when running in our test environment locally, we want to be able to override certain properties just for our workspace for test and development.
Apache commons' DatabaseConfigurator seemed nice, but wouldn't play nice with the jndi name being defined as a property in the file.  Nothing I did to ask it to look at the property file first worked.
I decided to subclass apache commons' AbstractConfiguration to try to create a single configurator that would check the file and database as I wished, but again, it didn't really work.  Spring wants that jndi name absolutely first, probably because the data source has to be passed into the configurator as a parameter.
How can I get what I am after here?  Mostly properties in the database, but those that are in the file override them.  And jndi name for the datasource should not have to be hardcoded in the spring config.

A: Why don't you write a ApplicationContext listener that will read the configuration from your DB and inject them in the JNDI? Then you can override the configuration in the JNDI with a context.xml file that will be placed in the src/local/webapp/META-INF/.
This is how we get this working in our webapp.


text:
Q: Aligning  next to eachother in full width dropdown menu So I'm having a bit of a problem. I've created a fullwidth dropdown menu that contains a few li's with menu-items in them. I made it fullwidth with the padding: 0 1000em; margin: 0 -1000em; trick but now the li's are being placed under each other.
The goal is to place the li's next to each other and I'm getting stuck here. Any solutions? Below is the code being used.
To make it a bit clear I've made a image to show what I mean. The first one is how it displays now and the second one is how I'd like it to be displayed: http://imgur.com/a/09r6t
HTML:

                   Men

                                Shoes

                                        Slippers

And the CSS:
.header-container .navigation-container {width: 100%; padding: 0; margin:0 auto; clear: both; }
.header-container .main-navigation {}

.header-container .main-navigation ul{float: left;  margin: 3px 0 0 0; padding:0; list-style-type:none}
.header-container .main-navigation ul li{float:left; margin: 0; font-family: 'NewCenturySchlbkLTPro-Roman', Georgia, Times New Roman, serif; text-transform: uppercase; font-size: 12px; position:relative; }
.header-container .main-navigation ul li a{letter-spacing: .2em; color: #000; display: block; padding: 10px 10px 10px 10px; outline-style: none;}
.header-container .main-navigation ul li a:hover,
.header-container .main-navigation ul li.active a{color: #7b4a59; box-shadow: 0 14px 0px 0px white, 135px -8px 0px 0px white, 1px 0 9px 0px #cccccc, -2px 0 6px -3px #cccccc}

.header-container .main-navigation ul.submenu{margin:0;}
.header-container .main-navigation ul li ul.submenu{position:absolute; width:250px; padding-top:15px; }
.header-container .main-navigation ul li ul.submenu li{display:none; position: relative; left: 0; top: 100%; padding: 0 1000em; margin: 0 -1000em; z-index: 101;     -o-box-shadow: 0 5px 10px 0 rgba(0,0,0,0.5);
    -webkit-box-shadow: 0 5px 10px 0 rgba(0,0,0,0.5);
    -moz-box-shadow: 0 5px 10px 0 rgba(0,0,0,0.5);
    box-shadow: 0 5px 10px 0 rgba(0,0,0,0.5);}

.header-container .main-navigation ul li ul.submenu li a{letter-spacing: .2em; color: #000; display: block; padding: 0; outline-style: none;}
.header-container .main-navigation ul li ul.submenu li a:hover,
.header-container .main-navigation ul li ul.submenu li.active a{color: #7b4a59;}

.header-container .main-navigation ul li:hover ul.submenu li{display:block; z-index:999; background-color:white; float:none; overflow:auto; padding-bottom:25px;}

.header-container .main-navigation ul li ul.subsubmenu li{box-shadow:none;}
.header-container .main-navigation ul li ul.subsubmenu li a{color:red;}

A: You can make the ul display as inline-block

ul.menu {
  display: inline-block;
}
ul.menu li {
  list-style: none;
}
ul.menu li:hover {
  cursor: pointer;
  background-color: goldenrod;
}

One-1

One-2

One-3

Two-1

Two-2

Two-3

A: If anyone is still looking for something like this, it's like this:
/*Main menu*/
.header-container .navigation-container {width: 100%; padding: 0; margin:0 auto; clear: both; }
.header-container .main-navigation {}

.header-container .main-navigation ul{float: left; padding:0; list-style-type:none; margin:0;}
.header-container .main-navigation ul li{float:left; margin: 0; margin-left:-10px; margin-right:10px; font-family: 'NewCenturySchlbkLTPro-Roman', Georgia, Times New Roman, serif; text-transform: uppercase; font-size: 12px; position:relative; }
.header-container .main-navigation ul li a{letter-spacing: .2em; color: #000; display: block; padding: 16px 10px 15px 10px; outline-style: none;}
.header-container .main-navigation ul li a:hover{color: #7b4a59; }
.header-container .main-navigation ul li.menu-list:hover > ul{visibility: visible; opacity: 1; border-top:1px solid #cccccc;}
.header-container .main-navigation ul li.menu-list:hover:after{content:""; position:relative; display:block; width:100%; height:1px; background: #FFF; z-index:1000;}

.header-container .main-navigation ul li.menu-list{border-left:1px solid transparent ;border-top:1px solid transparent;border-right:1px solid transparent}
.header-container .main-navigation ul li.menu-list:hover,
.header-container .main-navigation ul li.menu-list.active a{color: #7b4a59; border-left:1px solid #cccccc;border-top:1px solid #cccccc;border-right:1px solid #cccccc}

/*Sub menu*/
.featured-menu{background-color:#e3e2e5;}
.header-container .main-navigation ul.submenu{margin:0;}
.header-container .main-navigation ul li ul.submenu{position: absolute; left: 0;  padding-left: 100em; padding-right: 100em; margin: 0px -1034em 0 -100em; z-index: 101;
    visibility: hidden; opacity: 0; background: #ffffff;)
    -o-box-shadow: 0 5px 10px 0 rgba(0,0,0,0.5);
    -webkit-box-shadow: 0 5px 10px 0 rgba(0,0,0,0.5);
    -moz-box-shadow: 0 5px 10px 0 rgba(0,0,0,0.5);
    box-shadow: 0 5px 10px 0 rgba(0,0,0,0.5);;
}

.header-container .main-navigation ul li ul.submenu li{display:none; position: relative; left: 0; top: 100%; z-index: 101;}
.header-container .main-navigation ul li ul.submenu li:last-child{}

.header-container .main-navigation ul li ul.submenu li a{padding-top:15px; text-transform:uppercase; font-size:12px; letter-spacing: .2em; color: #000; display: block;  outline-style: none; }
.header-container .main-navigation ul li ul.submenu li a:hover,
.header-container .main-navigation ul li ul.submenu li.active a{color: #7b4a59; box-shadow:none!important}

.header-container .main-navigation ul li:hover ul.submenu li{display: block; z-index:999; background-color:transparent; float:left; padding:25px 15px 25px 10px; overflow:auto;}
.header-container .main-navigation ul li:hover ul.submenu li:first-child{}

/*Sub sub menu*/
.header-container .main-navigation ul li ul.subsubmenu li{box-shadow:none!important; float:none!important; padding-bottom:0!important; padding-top:0!important; padding-left:0!important;}
.header-container .main-navigation ul li ul.subsubmenu li a{margin-left:5px; font-family: 'Swiss721BT-Light',"Helvetica Neue",Helvetica,Arial,sans-serif; text-transform: uppercase;
    font-size: 12px; letter-spacing: .1em; color: #000; padding-bottom:0px;}
.header-container .main-navigation ul li ul.subsubmenu li a:last-child{padding-bottom:15px; padding-top:0px; margin-left:15px;}


text:
Q: TypeError: A sparse matrix was passed, but dense data is required (multilabel K nearest neighbours) I'm having trouble with fitting an instance of an MLkNN model (from scikit-multilearn) after doing GridSearchCV (from scikit-learn). I am getting an error. Here is the appropriate code:
#From MachineLearningMastery: https://machinelearningmastery.com/multivariate-time-series-forecasting-lstms-keras/

def series_to_supervised(n_lags, n_vars, data, n_out=1, dropnan=True):
    n_vars = 1 if type(data) is list else data.shape[1]
    df = DataFrame(data)
    cols, names = list(), list()

    #input sequence t-n, ..., t-1
    for i in range(n_lags, 0, -1): #for i in 3 to 0 not including 0
        cols.append(df.shift(i))
        names += [('var%d(t-%d)' % (j+1, i)) for j in range (n_vars)]

    #forecast sequence t, t+1, ..., t+n
    for i in range(0, n_out):
        cols.append(df.shift(-i))
        if i==0:
            names += [('var%d(t)' % (j+1)) for j in range(n_vars)]
        else:
            names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]

    agg = concat(cols, axis=1)
    agg.columns = names
    if dropnan:
        agg.dropna(inplace=True)

    return agg

def testexamples():

    def average_precision_wrapper(estimator, X, y):
        if X.ndim == 2:
            X = X.reshape((-1)) #[1, 1497] becomes [1497,], needed for average_precision
        if y.ndim == 2:
            y = y.reshape((-1)) #[1, 1497] ... as above
        y_pred = estimator.predict(X).toarray()
        return average_precision_score(y, y_pred)

    true_values = np.random.choice([0,1], size=(500, 1497), p=[0.99, 0.01])

    #Need to convert this to supervised learning. Use previous 2 days to predict (lag=2)
    n_lags = 2
    n_vars = true_values.shape[1]
    all_data = np.asarray(series_to_supervised(n_lags, n_vars, data=true_values))

    train_x = all_data[:400, :int(n_vars*n_lags)]
    train_y = all_data[:400, int(n_vars*n_lags):]

    test_x = all_data[-100:, :int(n_vars*n_lags)]
    test_y = all_data[-100:, int(n_vars*n_lags):]

    parameters = {'k': range(1,5), 's': [0.5, 0.75, 1]}
    checked_model = GridSearchCV(MLkNN(), parameters, scoring='average_precision')
    print('type: train_x: ', type(train_x), ' type: train_y: ', type(train_y))
    checked_model.fit(train_x, train_y)

Full trace:
user@GPU8:~/path/to/dir$ python May15_mlknn.py
    type: train_x:  <type 'numpy.ndarray'>  type: train_y:  <type 'numpy.ndarray'>

Traceback (most recent call last):
  File "May15_mlknn.py", line 380, in <module>
    testexamples()
  File "May15_mlknn.py", line 340, in testexamples
    checked_model.fit(train_x, train_y)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/model_selection/_search.py", line 945, in fit
    return self._fit(X, y, groups, ParameterGrid(self.param_grid))
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/model_selection/_search.py", line 564, in _fit
    for parameters in parameter_iterable
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 758, in __call__
    while self.dispatch_one_batch(iterator):
  File "user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 608, in dispatch_one_batch
    self._dispatch(tasks)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 571, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/_parallel_backends.py", line 109, in apply_async
    result = ImmediateResult(func)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/_parallel_backends.py", line 326, in __init__
    self.results = batch()
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 131, in __call__
    return [func(*args, **kwargs) for func, args, kwargs in self.items]
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/model_selection/_validation.py", line 260, in _fit_and_score
    test_score = _score(estimator, X_test, y_test, scorer)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/model_selection/_validation.py", line 288, in _score
    score = scorer(estimator, X_test, y_test)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/metrics/scorer.py", line 196, in __call__
    return self._sign * self._score_func(y, y_pred, **self._kwargs)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/metrics/ranking.py", line 184, in average_precision_score
    average, sample_weight=sample_weight)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/metrics/base.py", line 88, in _average_binary_score
    y_score = check_array(y_score)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/utils/validation.py", line 380, in check_array
    force_all_finite)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/utils/validation.py", line 243, in _ensure_sparse_format
    raise TypeError('A sparse matrix was passed, but dense '
TypeError: A sparse matrix was passed, but dense data is required. Use X.toarray() to convert to a dense numpy array.

I have already seen this and this and this. My question is different because I checked the types of train_x and train_y, and both are dense numpy arrays.
What am I doing wrong and how can I fix it?
EDIT:
I'm now trying the answer provided below, but with a modification due to the error I got (answer here):
def average_precision_wrapper(estimator, X, y):
    if X.ndim == 2:
        X = X.reshape((-1)) #(1, 1497) becomes (1497,), needed for average_precision
    if y.ndim == 2:
        y = y.reshape((-1)) #(1, 1497) ... as above
    y_pred = estimator.predict(X).toarray()
    return average_precision_score(y, y_pred)

EDIT 2: That was no good after all. I get ValueError: query data dimension must match training data dimension . Here's the trace:
/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/utils/validation.py:395: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
  DeprecationWarning)
Traceback (most recent call last):
  File "May15_mlknn_to_so.py", line 393, in <module>
    testexamples()
  File "May15_mlknn_to_so.py", line 353, in testexamples
    checked_model.fit(train_x, train_y)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/model_selection/_search.py", line 945, in fit
    return self._fit(X, y, groups, ParameterGrid(self.param_grid))
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/model_selection/_search.py", line 564, in _fit
    for parameters in parameter_iterable
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 758, in __call__
    while self.dispatch_one_batch(iterator):
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 608, in dispatch_one_batch
    self._dispatch(tasks)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 571, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/_parallel_backends.py", line 109, in apply_async
    result = ImmediateResult(func)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/_parallel_backends.py", line 326, in __init__
    self.results = batch()
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 131, in __call__
    return [func(*args, **kwargs) for func, args, kwargs in self.items]
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/model_selection/_validation.py", line 260, in _fit_and_score
    test_score = _score(estimator, X_test, y_test, scorer)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/model_selection/_validation.py", line 288, in _score
    score = scorer(estimator, X_test, y_test)
  File "May15_mlknn_to_so.py", line 307, in average_precision_wrapper
    y_pred = estimator.predict(X).toarray()
  File "May15_mlknn_to_so.py", line 237, in predict
    self.knn_.kneighbors(X, self.k + self.ignore_first_neighbours, return_distance=False)]
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/neighbors/base.py", line 381, in kneighbors
    for s in gen_even_slices(X.shape[0], n_jobs)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 758, in __call__
    while self.dispatch_one_batch(iterator):
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 608, in dispatch_one_batch
    self._dispatch(tasks)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 571, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/_parallel_backends.py", line 109, in apply_async
    result = ImmediateResult(func)
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/_parallel_backends.py", line 326, in __init__
    self.results = batch()
  File "/user/pkgs/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 131, in __call__
    return [func(*args, **kwargs) for func, args, kwargs in self.items]
  File "sklearn/neighbors/binary_tree.pxi", line 1294, in sklearn.neighbors.kd_tree.BinaryTree.query (sklearn/neighbors/kd_tree.c:11337)
ValueError: query data dimension must match training data dimension

A: The MLkNN.predict method returns a scipy.sparse array. The scorer 'average_precision' expects a numpy array. You can write a small wrapper that makes this conversion yourself:
from sklearn.model_selection import GridSearchCV
from skmultilearn.adapt import MLkNN
from sklearn.metrics import average_precision_score

def average_precision_wrapper(estimator, X, y):
    y_pred = estimator.predict(X).toarray()
    return average_precision_score(y, y_pred)

# Make dummy features of shape (100,5)
train_x = np.random.random((100,5))
# Make dummy one-hot encoded labels of shape (100,4)
train_y = np.zeros((100,4), dtype=int)
for i in range(100):
    train_y[i, i%4] = 1

parameters = {'k': range(1,5), 's': [0.5, 0.75, 1]}
checked_model = GridSearchCV(MLkNN(), parameters, scoring=average_precision_wrapper)
checked_model.fit(train_x, train_y)

A: Solved, with help from user2653663: I changed the metric to the Hamming loss, but had to create a scorer to do that using make_scorer from sklearn.metrics.
parameters = {'k': range(1,5), 's': [0.5, 0.75, 1]}
#checked_model = GridSearchCV(MLkNN(), parameters, scoring='f1_samples')
start = time.time()
#checked_model = GridSearchCV(MLkNN(), parameters, scoring='average_precision')
hloss_scorer = make_scorer(hamming_loss, greater_is_better=False)
checked_model = GridSearchCV(MLkNN(), parameters, scoring=hloss_scorer)

checked_model.fit(train_x, train_y)
end = time.time()
print('best parameters: ', checked_model.best_params_, 'best Hamming loss: ', checked_model.best_score_)

best_model = MLkNN(k=checked_model.best_params_['k'], s=checked_model.best_params_['s'])
best_model.fit(train_x, train_y)
pred_values = best_model.predict(test_x) #returns 0/1 classes, not probabilities
pred_values = np.array(pred_values.todense())

true_values = test_y

#Metrics

bincross = []
ap = []
ap_weighted = []
h_loss = []

for i in range(1, pred_values.shape[0]):
    true_vals = true_values[i,:]
    pred_vals = pred_values[i,:]
    pred_vals = np.squeeze(pred_vals)
    h_loss.append(hamming_loss(true_vals, pred_vals))

print("***********************")
print("MLKNN with k=best")
print("***********************")

print("Hamming loss: ", h_loss)

h_loss = np.asarray(h_loss)

print("total Hamming loss: ", np.sum(h_loss))


text:
Q: Connect to COM events in C# - support both managed and unmanaged servers I'm writing C# code that needs to connect to COM events. I implemented the use of
IConnectionPointContainer and IConnectionPoint thus:
      IConnectionPointContainer connectionPointContainer = internalGenerator as IConnectionPointContainer;
      if (connectionPointContainer == null)
      {
        Debug.Fail("The script generator doesn't support the required interface - IConnectionPointContainer");
        throw new InvalidCastException("The script generator doesn't support the required interface - IConnectionPointContainer");
      }
      Guid IID_IScriptGeneratorEvents = typeof(IScriptGeneratorCallback).GUID;
      connectionPointContainer.FindConnectionPoint(ref IID_IScriptGeneratorEvents, out m_connectionPoint);
      m_connectionPoint.Advise(this, out m_cookie);

The problem is that when the COM server is actually implemented in .Net (say, C#), after .Net creates it, it handles it as a .Net object, not a COM object. Since the .Net object doesn't implement the IConnectionPointContainer interface, I get null when trying to cast the object to that interface.
Any idea how can i workaround this?
I can of course implement IConnectionPointContainer by myself in the C# COM server, however I would like a simpler solution, which I can easily explain to other developers which need to implement the COM server.
P.S I must use IConnectionPointContainer as the COM server may be implemented in non-.Net (C++, Java).
Thanks,
Inbar

A: IConnectionPointContainer is implemented on the CCW (COM callable wrapper) that .NET automatically generates when exposing your .NET object as a COM object externally.
Try calling Marshal.GetComInterfaceForObject on the .NET object to get a COM interface for IConnectionPointContainer rather than just casting it.
update ... and if that doesn't work Marshal.GetIUnknownForObject must return something, and maybe that will then support a Marshal.QueryInterface call.

A: I didn't find a way to do this.
Eventually I will define another interface in .Net and will write 2 code paths, one for .Net objects and one for real COM objects.

A: The problem is that doing a GetIUnknownForObject call returns a pointer which you can then successfully call to attain IConnectionPointContainer for the object using its GUID. But, that call to QueryInterface then simply returns the original .NET object, not an IConnectionPointContainer interface.
I'm also stuck with this, and if anyone has any further insights please do share. My scenario is that I'm exposing a .NET control as an ActiveX using COM interop. I have a ComSourceInterface defined for the event sink, but in a VB6 host, the events are not being hooked up as expected. I'm therefore trying to get the IConnectionPointContainer interface for my exposed .NET control in order to hook up the events manually, but cannot get to this interface, if indeed it is implemented - or perhaps I am simply looking at the wrong object?

A: I got a little further, as I have been having the same problem manually connecting events when exposing a .NET control as an ActiveX using COM interop.
If you dig a little into the UserControl class using Reflector (e.g. Redgate Reflector), you'll see an 'ActiveXImpl' nested class member, which contains another nested static class called 'AdviseHelper', which has members ComConnectionPointContainer and ComConnectionPoint. It also has helper functions to connect points as you require.
There's a problem. When an event is hooked up by COM interop from your control (the event source) to the connection point container (which contains the event sink for your control's events), the IQuickActivate.QuickActivate function gets called, which then calls AdviseHelper class' 'AdviseConnectionPoint' function.
An IUnknown interface pointer to the event sink, on your client (i.e. not your control, the thing containing it) is passed to this QuickActivate function (parameter 'pUnkEventSink'. In reflector this function looks like this, and I've highlighted where it does the actual event hookup:
internal void QuickActivate(UnsafeNativeMethods.tagQACONTAINER pQaContainer, UnsafeNativeMethods.tagQACONTROL pQaControl)
{
    int num;
    this.LookupAmbient(-701).Value = ColorTranslator.FromOle((int) pQaContainer.colorBack);
    this.LookupAmbient(-704).Value = ColorTranslator.FromOle((int) pQaContainer.colorFore);
    if (pQaContainer.pFont != null)
    {
        Control.AmbientProperty ambient = this.LookupAmbient(-703);
        IntSecurity.UnmanagedCode.Assert();
        try
        {
            Font font2 = Font.FromHfont(((UnsafeNativeMethods.IFont) pQaContainer.pFont).GetHFont());
            ambient.Value = font2;
        }
        catch (Exception exception)
        {
            if (ClientUtils.IsSecurityOrCriticalException(exception))
            {
                throw;
            }
            ambient.Value = null;
        }
        finally
        {
            CodeAccessPermission.RevertAssert();
        }
    }
    pQaControl.cbSize = UnsafeNativeMethods.SizeOf(typeof(UnsafeNativeMethods.tagQACONTROL));
    this.SetClientSite(pQaContainer.pClientSite);
    if (pQaContainer.pAdviseSink != null)
    {
        this.SetAdvise(1, 0, (IAdviseSink) pQaContainer.pAdviseSink);
    }
    IntSecurity.UnmanagedCode.Assert();
    try
    {
        ((UnsafeNativeMethods.IOleObject) this.control).GetMiscStatus(1, out num);
    }
    finally
    {
        CodeAccessPermission.RevertAssert();
    }
    pQaControl.dwMiscStatus = num;
    if ((pQaContainer.pUnkEventSink != null) && (this.control is UserControl))
    {
        Type defaultEventsInterface = GetDefaultEventsInterface(this.control.GetType());
        if (defaultEventsInterface != null)
        {
            IntSecurity.UnmanagedCode.Assert();
            try
            {
                **AdviseHelper.AdviseConnectionPoint(this.control, pQaContainer.pUnkEventSink, defaultEventsInterface, out pQaControl.dwEventCookie);**
            }
            catch (Exception exception2)
            {
                if (ClientUtils.IsSecurityOrCriticalException(exception2))
                {
                    throw;
                }
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
        }
    }
    if ((pQaContainer.pPropertyNotifySink != null) && UnsafeNativeMethods.IsComObject(pQaContainer.pPropertyNotifySink))
    {
        UnsafeNativeMethods.ReleaseComObject(pQaContainer.pPropertyNotifySink);
    }
    if ((pQaContainer.pUnkEventSink != null) && UnsafeNativeMethods.IsComObject(pQaContainer.pUnkEventSink))
    {
        UnsafeNativeMethods.ReleaseComObject(pQaContainer.pUnkEventSink);
    }
}

The 'pUnkEventSink' variable is passed in to this function via the tagQACONTROL structure, but as you can see, unlike the IAdviseSink, control container, font style etc., this variable is not set to any member of the 'ActiveXImpl' class, and hence you cannot get to it after this function has initially been called by the framework.
You need to get this IUnknown pUnkEventSink variable to call AdviseHelper.AdviseConnectionPoint() function, which will do the manual event hookup. And this is the problem I've had - sadly you simply can't seem to get hold of it.
Anyone else had any further developments with this do let me know!

A: I know I'm a little late to this, but I was able to get sink events to work using IConnectionPoint. See my answer here. Specifically check out the MyAppDotNetWrapper class and how it is used the the test.
Ultimately I think your m_connectionPoint.Advise(this, out m_cookie); fails because this must be [ComVisible(true)], [ClassInterface(ClassInterfaceType.None)] and public.


text:
Q: cypher assign group of nodes to a relation i'm working with Users assigned to a Grid location
(User)-[:PICK_UP]->(Grid)

With the query
 MATCH (u:User)-[:PICK_UP]->(g:Grid)-[:TO]-(g2:Grid)<-[:PICK_UP]-(u2:User)
    RETURN g,g2,u,u2

I have the result
In the image i have two groups of nodes, that represent the grid and its neighbors with users (red node). I would like to 'group'/create relations between the users nearby to a Spot node.
E.g. with the first group: grids 34, 40, 41, with the users 1,4,5,9. I would like to group the users in my query so i can get the result [user1, u4, u5, u9] and then those users i can assign them to a Spot, like this

Any suggestions??
Thank you !!

A: The thing to keep in mind is that your (u:User)-[:PICK_UP]->(g:Grid)-[:TO]-(g2:Grid)<-[:PICK_UP]-(u2:User) is matching a specific path, and while you see two groups in the graphical display, there are actually overlapping paths there.  Viewing your result in table mode might be helpful.
So onto answering your question!  Firstly, this was a tricky one, but a really cool one.  I think I've got a good solution:
MATCH path=(grid:Grid)-[:TO]-(other_grid:Grid)
WITH CASE WHEN ID(grid) < ID(other_grid) THEN ID(other_grid) ELSE ID(grid) END AS id_to_reject
WITH collect(DISTINCT id_to_reject) AS ids_to_reject

MATCH (grid:Grid)
WHERE NOT(ID(grid) IN ids_to_reject)

CREATE (spot:Spot)
WITH grid, spot

MATCH (grid)-[:TO|PICK_UP*1..6]-(user:User)

MERGE (user)-[:AT_SPOT]->(spot)

The first thing that the query does it to compare all Grid nodes which are related to each other.  For each of these pairs it passes on the ID() of the Grid node which is greater.  The IDs which aren't in the list are therefore the smallest in the group and can act as a representative of the group.  For each one of these representative Grid nodes we create a Spot node.
Using that node, it finds all User nodes within six hops via both TO and PICK_UP relationships.  That should give all users in the group (both the users of our representative grid as well as the users of the other grids).
Then it's a simple matter to MERGE a relationship from each user to the Spot.


text:
Q: Quiz scoring algorithm for how close an answer is I am trying to generate a small algorithm that will give a user a decimal score out of 1 based on how close their answer is to a true answer. These answers will always be numeric and be things like 'How many x did this?'
I will be setting a sensible maximum and minimum value for each answer where if a users answer exceeds this, they will score nothing though am a bit stuck on getting an equation created ...
As an example, a correct answer could be 100 and a sensible minimum could be set as 50. A user specifying 75 would thus be given a score of 0.5
Perhaps getting a bit complicated now but it would also be nice to allocate the score on a curve so the result is not linear and thus weighting is higher the nearer you are to the correct answer
Any help or better ideas for this scoring would be much appreciated

A: A formula code could be like this :

score = abs(input - answer) / (answer - min)

for your example we have input = 75 , answer = 100 and min = 50 so:

score = abs(75 - 100) / (100 - 50) = 25 / 50 = 0.5

A: If you wanted the scoring to be non-linear (to reward closeness to the answer) you could try a 'squared difference' formula. E.g.
score = 1 - (abs((answer - input)/(answer - minimum)))^2

e.g. with correct = 100, minimum = 60, answer = 70 you would get:
score = 1 - (abs((100 - 70)/(100 - 60)))^2 = 0.4375

If you want to give a greater reward for closeness, you could use a higher power. Note that division by zero will occur if answer = minimum.

A: I implemented the algorithm in Java and made a small test case.
public class Quiz{

    public static double calculateScore(int input,
                                        int correctAnswer,
                                        int minimumAnswer){

        if(input == correctAnswer){
            return 1;
        }

        double correctInterval = Math.abs(correctAnswer - minimumAnswer);
        double relativeAnswer = Math.abs(correctAnswer - input);

        if(relativeAnswer > correctInterval){
            return 0;
        }else{
            double score = relativeAnswer/correctInterval;

            score *= score;// make ^2 to avoid a linear progression

            return 1.0 - score;
        }
    }
}

public class QuizTest{

    @Test
    public void testCalculateScore() {

        assertTrue(0 == Quiz.calculateScore(5, 20, 15));
        assertTrue(0 == Quiz.calculateScore(30, 20, 15));
        assertTrue(1 == Quiz.calculateScore(20, 20, 15));
        assertTrue(0 < Quiz.calculateScore(17, 20, 15));
        assertTrue(0 < Quiz.calculateScore(22, 20, 15));
        assertTrue(Quiz.calculateScore(18, 20, 15) == Quiz.calculateScore(22, 20, 15));

        assertTrue(Quiz.calculateScore(17, 20, 15) < Quiz.calculateScore(22, 20, 15));
    }
}

The test run is successful


text:
Q: Trace of the identity map in a projective module Let $A$ be a commutative algebra (over the complex numbers, with a unit) and let $M$ be a finitely generated projective $A$-module, and let $m_1,\ldots,m_n$ be a set of generators of $M$. The Dual Basis Theorem states that there exists $m_1^\ast,\ldots,m_n^\ast\in M^\ast$ such that $x=\sum m_i^\ast(x)m_i$ for all $x\in M$. This implies that one can write the identity map on $M$ as the tensor $\mathbf{1}=\sum m_i^\ast\otimes m_i$ and one defines $\operatorname{tr}\mathbf{1}=\sum m_i^\ast(m_i)$. What are the properties of $\operatorname{tr}\mathbf{1}$? Is there any relation to, for instance, the rank of $M$? When is it proportional to the unit element in $A$?

A: More abstractly:  Let $A$ be a commutative unital ring and let $M$ be a f.g. projective $A$-module. The rank $rk_P(M)$ of $M$ at a prime ideal may be defined as the vector space dimension of $K\otimes_A M$ where $K$ is the residue field. Because projective modules of local rings are free, this is a locally constant function of the prime (so a constant if $A$ is a domain). The trace of the identity of $M$ is the unique element of $A$ such that in every local ring $A_P$ it goes to $rk_P(M)1$.

A: For any homomorphism $\varphi : A \to \mathbb C$, $\varphi({\rm tr}({\bf 1}))$ will be the corresponding trace for the finite-dimensional vector space $M \otimes_A \mathbb C$, and hence be equal to the rank of $M$ at $\varphi$.
So, if $A$ is some algebra of continuous functions on a connected space, then the trace ${\rm tr}({\bf 1})$ is a constant function, equal to the rank of $M$. In general, ${\rm tr}({\bf 1})$ is integer-valued locally constant.

A: Let $A$ be the matrix with entries $m_i^*(m_j)$, and put $B(x)=xA+I-A$ and $f(x)=\det(B(x))$.  We find that $A^2=A$, and $B(xy)=B(x)B(y)$, and $f(xy)=f(x)f(y)\in R[x,y]$.  We also have $f(1)=1$.  It follows that $f(x)=\sum_{i=0}^ne_ix^i$ for some elements $e_i\in R$ which are orthogonal idempotents, ie $e_ie_j=\delta_{ij}e_i$ and $\sum_ie_i=1$.  If we put $R_i=R/(1-e_i)\simeq Re_i$ and $M=M/(1-e_i)M\simeq e_iM$ we see that $R=\prod_iR_i$ as rings and $M=\prod_iM_i$ as modules.  Moreover, $M_i$ is locally free of rank $i$ over $R_i$.
We also have $\text{tr}(1)=\text{tr}(A)=f'(1)=\sum_iie_i$, so $\text{tr}(1)$ maps to $i$ in $R_i$.  It is cleaner to work with the elements $e_i$ because they distinguish the different $R_i$ even in a finite characteristic situation, which is not true for $\text{tr}(1)$.


text:
Q: how to write a query in prepared statement i am writing a query  with inner join involved in it but having an doubt on how to write it using prepared statement here is my query
$query = "SELECT * FROM detail INNER JOIN shortlisted ON detail.id = shortlisted.shortlisted_id";
$result = mysqli_query($conn, $query);
if(mysqli_affected_rows($conn)>0){
if($row = mysqli_fetch_assoc($result))
{
//html part
}

also what should we pass in bind param if we have no particular condition to satisfy for our select query like
$query = "select * from details";
 $stmt = $conn->prepare($sql);
   //$stmt->bind_param();
   $stmt->execute();
   $stmt->bind_result($full_name);

   while ($stmt->fetch()) {

//html code
}


text:
Q: $C_p(\omega_1)$ is a Lindelöf space From time to time I come across the following statement:

$C_p(\omega_1)$ is a Lindelöf space.

Where can I find a proof of this?

A: I finally found it.
Problem 316 (and its solution) in Tkachuk's "A Cp-theory problem book" (2011), page 280.


text:
Q: What does mean connection in jmeter ? Can we get the details of how many connections were made (not the user sample but the connections) What does mean connection in jmeter ?  Can we get the details of how many connections were made (not the user sample but the connections)

A: You can monitor the number of the TCP connections open by JMeter by invoking netstat command in the OS Process Sampler
If you're testing a web application the number of connections will vary from 1 to 6 (or whatever you specify under HTTP Request Defaults)

However normally you should not be very interested in this form of information. My expectation is that you should rather be looking for Server Hits Per Second custom chart which reports how many "hits" were generated by JMeter during the test execution time frame. The listener is available via 5 Additional Graphs bundle and can be installed using JMeter Plugins Manager


text:
Q: Why am I getting this error when trying to push to github after committing? I'm working on a Javascript project using parcel as a bundler, whenever I try to push to the repo I get the following error in the terminal.
Counting objects: 40, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (40/40), done.
Writing objects: 100% (40/40), 1.45 MiB | 198.00 KiB/s, done.
Total 40 (delta 26), reused 0 (delta 0)
remote: Resolving deltas: 100% (26/26), completed with 12 local objects.
remote: error: Trace: 13191e15dbdeb1dcd7186474dd8ff7cf93ebf2c7d42752d4fd9a2e73f37fa5eb
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File .parcel-cache/data.mdb is 116.10 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File .parcel-cache/data.mdb is 106.80 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
To https://github.com/nezmustafa123/recipe_app.git
 ! [remote rejected] main -> main (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/nezmustafa123/recipe_app.git'

There was a caching folder that was created by parcel that I deleted but it still comes out with the same error.
Does anyone have any idea as to what I can do?
Thanks.

A: .parcel-cache/data.mb is larger then 100 mb's.
check if you need to push this file to your github otherwise put it in a .gitignore file


text:
Q: Excluir ImageButton num ScrollView no Android Estamos desenvolvendo uma prancha de comunicação para pessoas com certo grau de dificiência, poder se comunicar através de uma prancha de comunicação. No caso pode ser que sem querer, adicione mais de uma imagem ( ficar duplicado ), então eu precisaria excluir este último botão.
Como o uso é para quem tem certo grau de dificuldade, pensamos em deixar a função de excluir em um botão ( conforme indica na imagem circulado em vermelho ), que ao ser pressionado, excluir o último ImageButton adicionado.
Alguma idéia de como fazer isso? Ele está adicionado num LinearLayout, numa ScroolView.
Abaixo está o código para adicionar o botão
//Função para Criar Botões
    protected void criaBotoes(final int idBotao, final int posicaoX, final int posicaoY, final int altura, final int largura, int tipoLayout, int tipoBotao, String pathArquivo, final int tagBotao) {
        AssetManager manager = getAssets(); //Pasta onde ficam os arquivos a serem carregados ( Imagens )

        //Carrega Imagens dinamicamente
        InputStream open = null;
        try {
            open = manager.open(pathArquivo);                 //Seta nome para carregar o arquivo
            Bitmap bitmap = BitmapFactory.decodeStream(open); //Seta objeto para controle de imagem

            //Cria Layout Params ( "Fatias no layout para adiocionar cada botão )
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            //Seta posições e tamanho do Botão
            params.leftMargin = posicaoX;
            params.topMargin  = posicaoY;
            params.width      = altura;
            params.height     = largura;

            ImageButton botaoImg = new ImageButton(this); //Cria Botão Dinamicamente
            botaoImg.setId(idBotao);                      //Seta propriedade ID para cada usuário, para ser usado no "Click"
            botaoImg.setTag(tagBotao);                    //**
            botaoImg.setBackgroundResource(0);            //Deixa botão sem bordas

            botaoImg.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    int id  = v.getId();
                    int tag = (int) v.getTag();
                    //...
                }
            });

            botaoImg.setImageBitmap(bitmap);  //Seta objeto de imagem para o Botão
            botaoImg.setLayoutParams(params); //Seta layout para o botão ( "Fatias"  para cada botão )

            ll.addView(botaoImg); //Adiciona Botão no Layout (Linear)
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

criaBotoes(seqBotoesSel, posX, posY, altura, largura, 1, 1, pathAquivo, 0);
sv.addView(ll); //adiciona botão na ScrollView


text:
Q: Let $P(t)$ be a Bézier curve of degree $N$ with control points $P_0, \ldots, P_N$ . Show that $P'(0) = N(P_1−P_0)$ and $P'(1) = N(P_N − P_{N−1})$ I am trying to learn more about Bézier Curves and I am following an old professor's course online, and I can't seem to see how to go about this problem. I understand the format of finding $x(t)$ and $y(t)$ given control points. It's something along the lines of:
\begin{align}
x(t) &= x0(1-t)^3 + x1 * 3t(1-t)^2 + x2 * 3t^2 (1-t) + x3 * t^3  \\
y(t) &= y0(1-t)^3 + y1 * 3t(1-t)^2 + y2 * 3t^2 (1-t) + 3 * t^3
\end{align}
assuming there are 4 control points of course.
Any help at all would be appreciated!

A: You seem to know already that the curve equation is
$$
P(t) = (1-t)^3P_0 + 3t(1-t)^2P_1 + 3t^2(1-t)P_2 + t^3P_3
$$
Differentiate this with respect to $t$, and set $t=0$, and you will get
$P'(0) = 3(P_1 - P_0)$.
Similarly, setting $t=1$ will give you $P'(1) = 3(P_3 - P_2)$.
To get the more general result (rather than the case $N=3$ that I outlined above), you have to start with the general equation of a Bézier curve of degree $N$.


text:
Q: splitdexfile causes crash : Facebook SDK Parcelable encounteredClassNotFoundException reading a Serializable object I tried to apply splitdexfile option to split Facebook's sdk as a separate dex file.
What I've done so far:

1) I've added below line to my dexguard-project.txt file:
-splitdexfile com.facebook.**

2) And below line to my project.properties file:
proguard.config=dexguard-project.txt

3) I've exported a signed apk with Export Optimized and Obfuscated Application Package... (DexGuard) option successfully.

4) I checked and confirmed that the apk is splitted to 2 dex files:

Then I installed the apk to a device, and tried facebook connect and got;
java.lang.RuntimeException: Parcelable encounteredClassNotFoundException reading a Serializable object (name = o.?$?)

I couldn't find the o.?$?class at generated mapping.txt file.
DexGuard Version: 6.1
Facebook SDK Version: 3.22.0
Full Stacktrace:
04-10 10:12:55.727: E/ActivityThread(15362): Failed to find provider info for com.facebook.katana.provider.AttributionIdProvider
04-10 10:12:58.039: E/AndroidRuntime(15362): FATAL EXCEPTION: main
04-10 10:12:58.039: E/AndroidRuntime(15362): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.devrim/com.facebook.LoginActivity}: java.lang.RuntimeException: Parcelable encounteredClassNotFoundException reading a Serializable object (name = o.?$?)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.os.Looper.loop(Looper.java:137)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.app.ActivityThread.main(ActivityThread.java:5103)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at java.lang.reflect.Method.invokeNative(Native Method)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at java.lang.reflect.Method.invoke(Method.java:525)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at dalvik.system.NativeStart.main(Native Method)
04-10 10:12:58.039: E/AndroidRuntime(15362): Caused by: java.lang.RuntimeException: Parcelable encounteredClassNotFoundException reading a Serializable object (name = o.?$?)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.os.Parcel.readSerializable(Parcel.java:2177)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.os.Parcel.readValue(Parcel.java:2022)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.os.Parcel.readMapInternal(Parcel.java:2255)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.os.Bundle.unparcel(Bundle.java:223)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.os.Bundle.getSerializable(Bundle.java:1259)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.content.Intent.getSerializableExtra(Intent.java:4543)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at com.facebook.LoginActivity.onCreate(SourceFile:65)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.app.Activity.performCreate(Activity.java:5133)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
04-10 10:12:58.039: E/AndroidRuntime(15362):    ... 11 more
04-10 10:12:58.039: E/AndroidRuntime(15362): Caused by: java.lang.ClassNotFoundException: o.?$?
04-10 10:12:58.039: E/AndroidRuntime(15362):    at java.lang.Class.classForName(Native Method)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at java.lang.Class.forName(Class.java:204)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:2304)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at java.io.ObjectInputStream.readNewClassDesc(ObjectInputStream.java:1663)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:683)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at java.io.ObjectInputStream.readNewObject(ObjectInputStream.java:1806)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:787)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2006)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:1963)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at android.os.Parcel.readSerializable(Parcel.java:2171)
04-10 10:12:58.039: E/AndroidRuntime(15362):    ... 20 more
04-10 10:12:58.039: E/AndroidRuntime(15362): Caused by: java.lang.NoClassDefFoundError: o/?$?
04-10 10:12:58.039: E/AndroidRuntime(15362):    ... 30 more
04-10 10:12:58.039: E/AndroidRuntime(15362): Caused by: java.lang.ClassNotFoundException: Didn't find class "o.?$?" on path: DexPathList[[zip file "/data/app/com.devrim-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.devrim-1, /vendor/lib, /system/lib]]
04-10 10:12:58.039: E/AndroidRuntime(15362):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
04-10 10:12:58.039: E/AndroidRuntime(15362):    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
04-10 10:12:58.039: E/AndroidRuntime(15362):    ... 30 more

A: This is solved by adding below lines to dexguard-project.txt file:
-keep class * implements java.io.Serializable { *;}
-keepclassmembers class * implements java.io.Serializable { *;}


text:
Q: Boundedness of Union in Time of Semigroup Acting on a Bounded Set I'm studying some introductory material on the $C^0$ semigroup of solution operators S(t). I'm reading through a textbook and in one place, they state that $\bigcup\limits_{0\leq t\leq t_0}S(t) B$ is clearly bounded if $B$ is bounded, and also clearly closed if $B$ is compact. However, I'm not finding this obvious. I think all we need is the continuity of $S$ in both time and with respect to the initial data and the boundedness/closedness of B, but I'm not sure exactly how to flesh out the details. Any help would be appreciated. Thanks!

A: Partial answer: boundedness in the case where $\{S(t)\}_{t\geq 0}$ is a semigroup of linear operators.
Since $B$ is bounded, there exists $C>0$ such that
$$\|b\|\leq C,\quad\forall\ b\in B.$$
Take $x\in\bigcup\limits_{0\leq t\leq t_0}S(t) B$. Then there exist $t_x\in[0,t_0]$ and $b_x\in B$ such that
$$x=S(t_x)b_x.$$
From the joint continuity of  $S$ (see equation (10.2) in the said book), there exists a constant $M$ (which depends only on $t_0$ and $C$) such that
$$\|S(t)b_x\|\leq M,\quad\forall \ t\in[0,t_0].$$
Therefore,
$$\|x\|=\|S(t_x)b_x\|\leq M,\quad\forall \ x\in \bigcup\limits_{0\leq t\leq t_0}S(t) B$$
which shows that the union is bounded.
Partial answer 2: closedness in the case where $B\subset\mathbb R^n$ (as in the book).
Take $x\in\overline{\bigcup\limits_{0\leq t\leq t_0}S(t) B}$. Then there exists a sequence $(x_n)$ in $\bigcup\limits_{0\leq t\leq t_0}S(t) B$ such that
$$x_n\overset{n\to\infty}{\longrightarrow} x\tag{1}.$$
For each $n$, there exist $t_n\in[0,t_0]$ and $b_n\in B$ such that $x_n=S(t_n)b_n$. From the Bolzano-Weierstrass theorem:

*

*$(t_n)$ has a subsequence $(t_{n'})$ such that $t_{n'}\overset{n'\to\infty}{\longrightarrow} t^*\in [0,t_0]$.

*$(b_{n'})$ has a subsequence $(b_{n''})$ such that $b_{n''}\overset{n''\to\infty}{\longrightarrow} b^*\in B$.
Then
$$x_{n''}=S(t_{n''})b_{n''}\overset{n''\to\infty}{\longrightarrow} S(t^*)b^*\tag{2}$$
because
$$\|S(t_{n''})b_{n''}-S(t^*)b^*\|\leq \|S(t_{n''})b_{n''}-S(t_{n''})b^*\|+\|S(t_{n''})b^*-S(t^*)b^*\|.$$
From $(1)$ and $(2)$,
$$x=S(t^*)b^*\in \bigcup\limits_{0\leq t\leq t_0}S(t) B.$$


text:
Q: How do I use my secondary GPU for display output and primary only for computation? I have two GPU's, GTX 1070 and GT 710. I have only one display and I would like this display to run off of the GT710 so that I can continue to work when I am training models using CUDA. I have been at this for quite a few hours and the furthest I have been able to get is to boot into Mint in "fallback mode" with the monitor connected to the GT 710.
I have been following the instructions here:
https://forums.developer.nvidia.com/t/how-do-i-set-one-gpu-for-display-and-the-other-two-gpus-for-cuda-computing/49113
My system information is as follows

I have tried two methods
1)First Attempt: As suggested by user "birdie" the link above, I created the file nvidia.conf in directory /etc/X11/xorg.conf.d, with the following content
    Section "Device"
        Identifier      "GT710"
        BusID           "PCI:5:0:0" # my Bus ID for gt710
        Driver          "nvidia"
        VendorName      "NVIDIA"
    EndSection

Then I went to xorg.conf in /etc/X11/ and modified the entry for screen as follows
Section "Screen"
    Identifier     "Screen0"
    Device         "GT710" #modified here
    Monitor        "Monitor0"
    DefaultDepth    24
    Option         "Stereo" "0"
    Option         "nvidiaXineramaInfoOrder" "DFP-6"
    Option         "metamodes" "2560x1440_75 +0+0"
    Option         "SLI" "Off"
    Option         "MultiGPU" "Off"
    Option         "BaseMosaic" "off"
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

By doing this I was able to boot into mint in fallback mode with my display connected to the GT710.
2)Second Attempt: I created a second device entry in /etc/X11/xorg.conf
    Section "Device"
        Identifier     "Device1"
        Driver         "nvidia"
        VendorName     "NVIDIA Corporation"
        BusID           "PCI:5:0:0"
        BoardName      "GeForce GT 710"
        option          "AllowEmptyInitialConfiguration"
    EndSection

Then I edited the Screen entry in /etc/X11/xorg.conf as follows:
Section "Screen"
    Identifier     "Screen0"
    Device         "Device1" #edited here
    Monitor        "Monitor0"
    DefaultDepth    24
    Option         "Stereo" "0"
    Option         "nvidiaXineramaInfoOrder" "DFP-6"
    Option         "metamodes" "2560x1440_75 +0+0"
    Option         "SLI" "Off"
    Option         "MultiGPU" "Off"
    Option         "BaseMosaic" "off"
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

Again I was able to boot into mint but only in fallback mode when connected to the GT710.
I would appreciate any help in making this work.
thank you

A: I solved the problem. The solution is to use approach #2 and edit /etc/X11/xorg.conf/ to add second GPU as shown above. Then under Section "screen" change "MultiGPU" to "on"
more details can be seen hereenter link description here
I will post my new xorg.con in case it helps anyone in the future
# nvidia-settings: X configuration file generated by nvidia-settings
# nvidia-settings:  version 440.82

Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen0" 0 0
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
    Option         "Xinerama" "0"
EndSection

Section "Files"
    EndSection

Section "Module"
    Load           "dbe"
    Load           "extmod"
    Load           "type1"
    Load           "freetype"
    Load           "glx"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Mouse0"
    Driver         "mouse"
    Option         "Protocol" "auto"
    Option         "Device" "/dev/psaux"
    Option         "Emulate3Buttons" "no"
    Option         "ZAxisMapping" "4 5"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Keyboard0"
    Driver         "kbd"
EndSection

Section "Monitor"
    # HorizSync source: edid, VertRefresh source: edid
    Identifier     "Monitor0"
    VendorName     "Unknown"
    ModelName      "Philips PHL 325E1"
    HorizSync       114.0 - 114.0
    VertRefresh     48.0 - 75.0
    Option         "DPMS"
EndSection

#makes gtx 1070 work on display

Section "Device"
    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    BoardName      "GeForce GTX 1070"
EndSection

#added to make GT710 run my Display doesnt work
Section "Device"
    Identifier     "Device1"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
BusID           "PCI:5:0:0"
option          "AllowEmptyInitialConfiguration"
EndSection

Section "Screen"
    Identifier     "Screen0"
    Device         "Device1"
    Monitor        "Monitor0"
    DefaultDepth    24
    Option         "Stereo" "0"
    Option         "nvidiaXineramaInfoOrder" "DFP-6"
    Option         "metamodes" "2560x1440_75 +0+0"
    Option         "SLI" "Off"
    Option         "MultiGPU" "on" #"Off" #CHANGE APPLIED HERE
    Option         "BaseMosaic" "off"
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection


text:
Q: Crash connection to FTP using CFNetwork I want to download a file from my FTP using CFNetwork.
The following code crashes allmost everytime i run my iOS Application (iOS 6.0 SDK).
The debugger just says "(lldb)"
http://pastebin.com/5XQD9ih1
I figured out that the App just crashed if i set the Delegate for the inputStream or the outputStream. So it have something to do with the delegate. But without any error message i dont know how to start searching the issue ? any ideas ?


text:
Q: Writing a Matlab script to implement a changing sum I am trying to implement this computation in Matlab, but I don't know how.
I want to compute the following:
$$p(k,j) = \frac{\sum\limits_{i=j+1}^{k} x_{i-1}}{\sum\limits_{i=j+1}^{k}(y_{i-1} - y_i)}$$ where $j = 0,\ldots,k-1$. For example for $k = 2$, $j = 0,1$. Thus,
$$ p(2,0) =  \frac{\sum\limits_{i=1}^{2}x_{i-1}z_{i-1}}{\sum\limits_{i=1}^2 (y_{i-1}-y_i)} \quad \text{and} \quad p(2,1)  = \frac{\sum\limits_{i=2}^{2}x_{i-1}z_{i-1}}{\sum\limits_{i=2}^2 (y_{i-1}-y_i)} $$
For $k=3$, $j=0,1,2$ and
$$p(3,0) = \frac{\sum\limits_{i=1}^{3}x_{i-1}z_{i-1}}{\sum\limits_{i=1}^3 (y_{i-1}-y_i)}\,,p(3,1) =\frac{\sum\limits_{i=2}^{3}x_{i-1}z_{i-1}}{\sum\limits_{i=2}^3 (y_{i-1}-y_i)} \,, p(3,2) =\frac{\sum\limits_{i=3}^{3}x_{i-1}z_{i-1}}{\sum\limits_{i=3}^3 (y_{i-1}-y_i)} ~.$$
I have the values of $x$ and $y$ but I only have the initial value of $z$, $z_0$. The next value of $z$ is found iteratively: $$z_i = z_{i-1} - 1/p(k,j). $$

A: Matlab has one-based array indexing: x(1), x(2) and so on. You need to take it into account. If p(k,j) is two-dimensional array, then you need to change indexing too.
Let:
x_(i+1) = x(i), y_(i+1) = y(i), z_(i+1) = z(i), p_(k+1,j+1) = p(k,j)
So, $p(k,j)$ is calulated, using element-wise multiplication .*, difference and vector sum operations, with this code:
p_(k+1,j+1) = sum(x_(j+1:k).*z_(j+1:k))/sum(y_(j+1:k)-y_(j+2:k+1))

One more hint, MATLAB has built-in function diff, calculating difference of neighbour elements. diff(X), for a vector X, is [X(2)-X(1)  X(3)-X(2) ... X(n)-X(n-1)]. So we can write:
p_(k+1,j+1) = sum(x_(j+1:k).*z_(j+1:k))/sum(-diff(y_(j+1:k+1)))


text:
Q: How to search contacts by name and phone number? I am using Contacts.CONTENT_FILTER_URI to search for contacts.
Uri contentUri = Uri.withAppendedPath(
                ContactsContract.Contacts.CONTENT_FILTER_URI,
                Uri.encode(searchString));

The searchstring can be either a number or a name. That works great.
My only problem is that the result does not contain a contact phone number.
I know that I can get it by querying ContactsContract.Data.CONTENT_URI. However, I would like to find a solution that will give me a contact name and phone number with a single query.

A: You should use Phone.CONTENT_FILTER_URI instead of Contacts.CONTENT_FILTER_URI
Docs say:

The filter is applied to display names as well as phone numbers.

Try this:
Uri filterUri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(searchString));
String[] projection = new String[]{ Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER };
Cursor cur = getContentResolver().query(filterUri, projection, null, null, null);


text:
Q: Defining a stride of (2, 2) in Keras -- what is the second value? I'm a bit confused by the idea of a stride that is, say, (2, 2) in keras.
What is the second 2 in the tuple (2,2) doing?
I'd understand if the stride was (2), because then we'd be moving a filter across an image by 2 pixels.
If we are striding by 2 along x and 2 along y, then we'd be running diagonally across an image. That doesn't make much sense.
The Keras documentation is not clear.
Thanks.

A: Indeed the two values are related to the two dimensions x and y along which we move the filters.
You will move the filters along both dimensions, so you will need to know the strides that you want to use. The thing you are misinterpreting is that the filters won't move by increasing both x and y values at the same time. They will be incremented one by one, so first you will go along the x axis 2 by 2, without changing y, the you will go down y by one step of 2 and start over along x, and so on...
So it just gives you flexibility on the steps sizes you want to make vertically and horizontally. In cases where you are working with simple pictures it makes sense to use the sames steps (2,2) or (3,3) for example. But you never know what this tool can be used for so they made it general in case someone wants to subsample more on one axis or the other.
Does that answer your question?


text: Q: Cannot start and re-register ECS container in Task Definitions I have AWS ECS Container service configured along with ALB. After I configured, committed and restarted Nginx, I cannot start or re-register the Nginx container back to ECS Task Definitions or Service.


text:
Q: EntityExistsException when using @EmbeddedId with dual-side bidirectional association
javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session

This exception's answers are flooded over Stackoverflow but have not a single matching my problem case. I have two entities Post and User which are having ManyToMany relationship but the relationship table has two extra fields: voted_at and vote.
So, I need to have an additional entity class PostVote which would have EmbeddedId. PostVote table is the table which would hold the user who voted for the post
public class PostVote implements Serializable {

    @EmbeddedId
    private PostVoteId id;

    @ManyToOne(fetch = FetchType.LAZY)
    @MapsId("postId")
    @JoinColumn(name = "post_id")
    private Post post;

    @ManyToOne(fetch = FetchType.LAZY)
    @MapsId("userId")
    @JoinColumn(name = "user_id")
    private User user;

    @NotNull
    @CreationTimestamp
    private LocalDateTime votedAt;

    @NotNull
    private Boolean vote = true;

    public PostVote() {
    }

    PostVote(Post post, User user) {
        this.post = post;
        this.user = user;
        this.id = new PostVoteId(post.getPostId(), user.getUserId());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PostVote that = (PostVote) o;
        return Objects.equals(post, that.post) &&
                Objects.equals(user, that.user);
    }
    @Override
    public int hashCode() {
        return Objects.hash(post, user);
    }
}

The PostVoteId entity
@Embeddable
public class PostVoteId implements Serializable {

    @Column(name = "post_id")
    private Integer postId;

    @Column(name = "user_id")
    private Integer userId;

    PostVoteId(Integer postId, Integer userId) {
        this.postId = postId;
        this.userId = userId;
    }

    public PostVoteId() {
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PostVoteId that = (PostVoteId) o;
        return Objects.equals(postId, that.postId) &&
                Objects.equals(userId, that.userId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(postId, userId);
    }
}

I am following Vlad Mihalcea article. Now, to add votes to the post, I have addVote method in Post.
public class Post implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
    @GenericGenerator(name = "native", strategy = "native")
    @Column(name = "post_id", unique = true, nullable = false)
    private Integer postId;

    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<PostVote> voters = new ArrayList<>();

    public void addVote(User user){
        PostVote postVote = new PostVote(this, user);
        voters.add(postVote);
        user.getVotedPosts().add(postVote); //problem here
    }
}

The service method which is voting for the post is:
Post post = postRepository.findById(postId);
final User user = userRepository.findById(123);
post.addVote(user);

postRepository.save(post);

The above code gives the error

javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [com.sample.entities.PostVote#com.sample.entities.PostVoteId@4ba].

But if I remove user.getVotedPosts().add(postVote)(keep single-side bidirectional association) then it works fine.
The existing solutions didn't help. Maximum says to check the GenerationType strategy and the implementation of equals and hashcode. But in my case, both are set fine.


text:
Q: Google Cloud Platform SDK network issues I have been trying to upload a local folder to a bucket on GCP.
I have Windows 7 Pro and no proxy server.
When running gcloud init I got a network diagnostic error.
Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.
ERROR: Reachability Check failed.
    Cannot reach https://www.googleapis.com/auth/cloud-platform (error)
Network connection problems may be due to proxy or firewall settings.

I am still able to select a user and project thereafter.
So I turned my anti-virus, windows firewall and router firewall off, and run gsutil ls and gsutil cp ... as a test, and get the same error for both.
INFO 1002 22:35:04.327000 util.py] Retrying request, attempt #3...
INFO 1002 22:35:11.644000 util.py] Retrying request, attempt #4...
INFO 1002 22:35:26.417000 util.py] Retrying request, attempt #5...
INFO 1002 22:35:51.611000 util.py] Retrying request, attempt #6...

I am able to ping www.googleapis.com.
Pinging www.googleapis.com [127.0.0.1] with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms

And when I tested it on another computer it worked perfectly - so proves that its not a configuration issue on GCP Console.
I often use WinSCP in command prompt for SFTP transfers. Why will this one thing not work? Is this a OS or GCP SDK issue?


text:
Q: DetectChanges: No entry for relationships if key property present I have two classes with an parent-child (1:n) relationship and want to detect when the parent has been changed by adding a child to it.
I have overriden the SaveChanges method of the context:
public override int SaveChanges()
{
    var ctx = ((IObjectContextAdapter)this).ObjectContext;

    ctx.DetectChanges();
    var entries = ctx.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified);
    foreach (var entry in entries)
    {
        if (entry.IsRelationship)
        {
            Console.WriteLine("Relationship");
        }
        else
        {
            Console.WriteLine("Entity");
        }
    }

    return base.SaveChanges();
}

As expected, when adding a child to the parent I get an entity entry for the child and a relationship entry for the parent-child relationship. But as soon as the child class contains a key property for the parent, I no longer get any relationship entries for this relationship.
class Class1
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; }
    public ICollection<Class2> Class2s { get; set; }
}

class Class2
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; }
    public Class1 Parent { get; set; }
    public int ParentId { get; set; } // <-- no relationship entries if present
}

Is this expected behavior? How can I detect relationship changes when the id column is present?


text:
Q: get_permalink and get_the_category return empty After saving/updating a custom wordpress posttype i'm calling a script:
function update_save_post( $post_id, $post, $update ){

    if ($post->post_type == 'my_custom_posttype')
    {
      include 'api/index.php';
    }

}
add_action( 'save_post', 'update_save_post', 10, 3);

In the index.php i retrieve all the posts of the my_custom_posttype and loop throught them. Inside the loop 'get_permalink' and 'get_the_category' return empty (empty string and empty array). The $post and $acf arrays contain the fields as expected. Permalink and get_the_category work normal when used inside the archive page.
$posts = get_posts([
  'post_type' => 'my_custom_posttype',
  'post_status' => 'publish',
  'numberposts' => -1,
  'order'    => 'ASC'
]);

foreach ($posts as $post) {
  print_r($post);
  echo get_permalink($post->ID); //empty string!?
  $acf = get_fields($post->ID);
  print_r($acf);
  $cats = get_the_category($post->ID);
  print_r($cats); //empty array!?
}

Any ideas?

A: Remove $post->ID and add only $post and it will work as you are using foreach
$posts = get_posts(array(
  'post_type' => 'my_custom_posttype',
  'post_status' => 'publish',
  'numberposts' => -1,
  'order'    => 'ASC'
));

foreach ($posts as $post) {
  print_r($post);
  echo get_permalink($post->ID); //empty string!?
  $acf = get_fields($post->ID);
  print_r($acf);
  $cats = get_the_category($post->ID);
  print_r($cats); //empty array!?
}


text:
Q: How can I get all the property names from a javascript object literal that contains nested objects? For example, if I have this javascript object literal:
var foo = {
    a: '1',
    b: {
        doit: function toit(){},
        c: true,
        d: {
          x: true,
          y: true
        }
    }
}

How can I get an array of all the property names? Such as:
['a', 'b', 'doit', 'c', 'd', 'x', 'y']

A: You can use this recursive function
function recursiveKeyFinder(object, result) {
    for (var key in object) {
        result.push(key);
        if (Object(object[key]).toString() === "[object Object]") {
            recursiveKeyFinder(object[key], result);
        }
    }
    return result;
}

console.log(recursiveKeyFinder(foo, []));
# [ 'a', 'b', 'doit', 'c', 'd', 'x', 'y' ]

A: You can loop over all the properties using the for in loop and push them to an array.
>
for (var key in foo) {
   var obj = foo[key];
   for (var prop in obj) {
      // important check that this is objects own property
      // not from prototype prop inherited
      if(obj.hasOwnProperty(prop)){
        arr.push(prop);
      }
   }
}

A: Try this: (Recursive function )
var foo = {
    a: '1',
    b: {
        doit: function toit(){},
        c: true,
        d: {
          x: true,
          y: true
        }
    }
};

var getKeys = function ( foo ) {
    var bar = [];

    for ( var key in foo ) {
        var _foo = foo [ key ];
        bar.push ( key );
        if ( typeof _foo === 'object') {
            var _bar = getKeys ( foo [key] );
            for (var _key in _bar ) {
                bar.push ( _bar[_key] );
            }

        }
    }

    return bar;
};

var bar = getKeys ( foo );

alert ( bar );

Demo Here : JSFiddle

A: A function such as this would do the job:
function getKeysRecursive(obj)
{
  var keys = [];

  (function r(obj) {
    Object.keys(obj).forEach(function(key) {
      keys.push(key);
      if (obj[key] instanceof Object) {
        r(obj[key]);
      }
    });
  }(obj));

  return keys;
}

Demo


text:
Q: How to load a custom config file in a Bundleless application with Treebuilder? I'm trying to import a custom config file called test.yaml.
I put the test.yaml in the config/packages/local folder and in config/packages folder.
The test.yaml file looks like this:
# config/packages/test.yaml
test1: 'hello'

When I compile the application I get this error: "There is no extension able to load the configuration for "test1"
Now You're gonna to tell me that i need to create and extension and blabla. But I cannot figure out. Is there a way to create an extension without creating a Bundle. I cannot find any example on the documentation that talks about Extension outside a Bundle scope. I mean I want to create it in the src folder ?
A related question is: If I setup a TreeBuilder like in this example:
https://symfony.com/doc/current/components/config/definition.html
is it possible to avoid to create an Extension ?
The Symfony version is 5.1.

A: Seems like I saw a similar question a few months ago but can't find it.  The src/Kernel class acts as a AppBundle class and allows you to do things like register extensions.
# src/Kernel.php
class Kernel extends BaseKernel
{
    use MicroKernelTrait;

    protected function prepareContainer(ContainerBuilder $container)
    {
        $container->registerExtension(new TestExtension());
        parent::prepareContainer($container);
    }
...
# src/TestExtension.php
class TestExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        // TODO: Implement load() method.
        dump($configs);
    }
}

As far as processing a tree builder without an extension, I don't know if that is possible.  The config stuff is already complicated enough so I would not go there myself.
Bit off-topic, I could not find an actual documented case of using prepareContainer in Kernel.  The source code makes it clear that the approach shown above will work.
Most of the time app specific configurations are just done in the config directory.  The main point of the bundle configuration system is to allow the app to override default bundle configurations.  I'm not really seeing the point of an app level extension.  What would override it? Maybe some sort of sophisticated database driven tree builder? Seems unlikely.
This could be a case of just because you can do something does not mean you should.

A: For custom config files, I think you might need to add parameters: at the top like this
# config/packages/test.yaml
parameters:
  test1: hello

https://symfony.com/doc/current/configuration.html#configuration-parameters


text:
Q: Get the size of an Android file resource? I have a video file in the raw folder in my resources. I want to find the size of the file.
I have this piece of code:
Uri filePath = Uri.parse("android.resource://com.android.FileTransfer/" + R.raw.video);
                File videoFile = new File(filePath.getPath());
                Log.v("LOG", "FILE SIZE "+videoFile.length());

But it always gives me that the size is 0. What am I doing wrong?

A: Try this lines:
InputStream ins = context.getResources().openRawResource (R.raw.video)
int videoSize = ins.available();

A: Try this:
AssetFileDescriptor sampleFD = getResources().openRawResourceFd(R.raw.video);
long size = sampleFD.getLength()

A: Reuseable Kotlin Extensions
You can call these on a context or activity. They are exception safe
fun Context.assetSize(resourceId: Int): Long =
    try {
        resources.openRawResourceFd(resourceId).length
    } catch (e: Resources.NotFoundException) {
        0
    }

This one is not as good as the first, but may be required in certain cases
fun Context.assetSize(resourceUri: Uri): Long {
    try {
        val descriptor = contentResolver.openAssetFileDescriptor(resourceUri, "r")
        val size = descriptor?.length ?: return 0
        descriptor.close()
        return size
    } catch (e: Resources.NotFoundException) {
        return 0
    }
}

If you'd like a simple way to get a different byte representation, you can use these
val Long.asKb get() = this.toFloat() / 1024
val Long.asMb get() = asKb / 1024
val Long.asGb get() = asMb / 1024

A: You can't use File for resources. Use Resources or AssetManager to get an InputStream to the resource, then call the available() method on it.
Like this:
InputStream is = context.getResources().openRawResource(R.raw.nameOfFile);
int sizeOfInputStram = is.available(); // Get the size of the stream

A: Slight variation to the answer by @shem
AssetFileDescriptor afd = contentResolver.openAssetFileDescriptor(fileUri,"r");
long fileSize = afd.getLength();
afd.close();

Where fileUri is of type Android Uri


text:
Q: ¿Como poner dos tipografias diferentes en flutter? Como puedo hacer un salto de linea en flutter y que en el mismo parafo halla dos tipografías diferentes...
Ejemplo:
child: Center(
              child: Text(
                "Regalate un momento,"
                    "Viví Carhué",

              ),
            ),

"Regalate un momento" sea una tipografia y "vivi carhue" otra...

A: El widget RichText muestra texto que usa múltiples estilos diferentes. El texto a mostrar se describe utilizando un árbol de objetos TextSpan, cada uno de los cuales tiene un estilo asociado que se usa para ese subárbol. El texto puede dividirse en varias líneas o puede mostrarse en la misma línea dependiendo de las restricciones de diseño.
Aquí esta mi fuente
https://docs.flutter.io/flutter/widgets/RichText-class.html


text:
Q: How to cancel io_service object in a thread? My understanding is that to end this timer thread, I need to call stop() on the io_service object. I'm doing this so that the MyClass object (also running as a thread) doesn't end in an active exception when it's thread ends.
How does one cancel an io_service object in a standard thread using a lambda?
class MyClass
{
    private:
        boost::asio::io_service io;

    // ...
}

void MyClass::operator()()
{
    boost::asio::deadline_timer my_timer(io,
        boost::posix_time::seconds(300));

    my_timer.async_wait(boost::bind(&MyTest::pump, this,
        boost::asio::placeholders::error, &my_timer));

    std::unique_ptr<std::thread> io_thread(
        std::make_unique<std::thread>([&] { io.run(); }));

    // ...

    // cancel here.

}

A: First of all, I wouldn't usually call io_service::stop. Instead I'd cancel all pending work and wait for the service to gracefully return.
Only if that fails I'll fall back to io_service::stop.
Secondly, the io_service is one of the few Asio objects that's documented to be thread-safe (except for construction/destruction). So you can just call io_service::stop from anywhere, as long as you can be sure the object is alive (not destructed).


text:
Q: SQL - Patient with an office visit one year before the most recent one I'm trying to write a query that brings back patients who have had an office visit at least a year before the most recent one. The various ways I'm thinking of get all twisted up in my head, so I was wondering if anyone out there can see an obvious way to write it that I'm missing. Don't worry too much about the exact syntax and naming -- I should be able to translate it. :-)
Thanks!

A: Use:
SELECT ph.*
  FROM PATIENT_HISTORY ph
 WHERE ph.visit_date >= (SYSDATE - 365)

...or:
SELECT ph.*
  FROM PATIENT_HISTORY ph
 WHERE ph.visit_date >= ADD_MONTHS(SYSDATE, -12)

ADD_MONTHS is self-explanatory.  In Oracle, SYSDATE returns the current date and time, and you can manipulate Oracle DATE (includes time) by adding/subtracting a number (which is interpreted as the number of days).
For patients with a record that is a year or more in the past:
SELECT a.*
  FROM PATIENT_HISTORY a
 WHERE EXISTS(SELECT NULL
                FROM PATIENT_HISTORY b
               WHERE b.visit_date <= ADD_MONTHS(a.visit_date, -12))

A: select distinct * from PatientHistory
where lastVisit = date_sub(lastVisit,interval 1 year)

A: If you want to determine whether a patient has been treated for at least a year (which your comment makes it sound like) then couldn't you do a query like:
SELECT *
FROM Patients p
WHERE
    DATEDIFF(d,
             (SELECT MIN(AppointmentDate) FROM Appointments a WHERE a.PatientID = p.PatientID),
             (SELECT MAX(AppointmentDate) FROM Appointments a WHERE a.PatientID = p.PatientID)) >= 365

I don't know if that syntax will work offhand, but the concept is to say, "Return only those patients where the number of days since their earliest and most recent appointments is at least 365 days.

A: It's fairly straight to do it with WINDOW FUNCTIONS in Oracle.
If your VISITS table is something like:
create table visits (
    patient_id number,
    visit_date date,
    ....
);

You can use this simple query:
select patient_id, visit_date,
       lead(visit_date, 1, null)
           over (partition by patient_id order by visit_date) as next_visit_date
  from visits;

And will get in one row, visit_date value, and following visit_date value for the same patient.
Then with a simple where, you can check for your one year condition.


text:
Q: How to verify if the content of two Docker images is exactly the same? How can we determine that two Docker images have exactly the same file system structure, and that the content of corresponding files is the same, irrespective of file timestamps?
I tried the image IDs but they differ when building from the same Dockerfile and a clean local repository. I did this test by building one image, cleaning the local repository, then touching one of the files to change its modification date, then building the second image, and their image IDs do not match. I used Docker 17.06 (the latest version I believe).

A: After some research I came up with a solution which is fast and clean per my tests.
The overall solution is this:

*

*Create a container for your image via docker create ...

*Export its entire file system to a tar archive via docker export ...

*Pipe the archive directory names, symlink names, symlink contents, file names, and file contents, to an hash function (e.g., MD5)

*Compare the hashes of different images to verify if their contents are equal or not

And that's it.
Technically, this can be done as follows:
1) Create file md5docker, and give it execution rights, e.g., chmod +x md5docker:
#!/bin/sh
dir=$(dirname "$0")
docker create $1 | { read cid; docker export $cid | $dir/tarcat | md5; docker rm $cid > /dev/null; }

2) Create file tarcat, and give it execution rights, e.g., chmod +x tarcat:
#!/usr/bin/env python3
# coding=utf-8

if __name__ == '__main__':
    import sys
    import tarfile
    with tarfile.open(fileobj=sys.stdin.buffer, mode="r|*") as tar:
        for tarinfo in tar:
            if tarinfo.isfile():
                print(tarinfo.name, flush=True)
                with tar.extractfile(tarinfo) as file:
                    sys.stdout.buffer.write(file.read())
            elif tarinfo.isdir():
                print(tarinfo.name, flush=True)
            elif tarinfo.issym() or tarinfo.islnk():
                print(tarinfo.name, flush=True)
                print(tarinfo.linkname, flush=True)
            else:
                print("\33[0;31mIGNORING:\33[0m ", tarinfo.name, file=sys.stderr)

3) Now invoke ./md5docker <image>, where <image> is your image name or id, to compute an MD5 hash of the entire file system of your image.
To verify if two images have the same contents just check that their hashes are equal as computed in step 3).
Note that this solution only considers as content directory structure, regular file contents, and symlinks (soft and hard). If you need more just change the tarcat script by adding more elif clauses testing for the content you wish to include (see Python's tarfile, and look for methods TarInfo.isXXX() corresponding to the needed content).
The only limitation I see in this solution is its dependency on Python (I am using Python3, but it should be very easy to adapt to Python2). A better solution without any dependency, and probably faster (hey, this is already very fast), is to write the tarcat script in a language supporting static linking so that a standalone executable file was enough (i.e., one not requiring any external dependencies, but the sole OS). I leave this as a future exercise in C, Rust, OCaml, Haskell, you choose.
Note, if MD5 does not suit your needs, just replace md5 inside the first script with your hash utility.
Hope this helps anyone reading.

A: Amazes me that docker doesn't do this sort of thing out of the box. Here's a variant on @mljrg's technique:
#!/bin/sh

docker create $1 | {
  read cid
  docker export $cid | tar Oxv 2>&1 | shasum -a 256
  docker rm $cid > /dev/null
}

It's shorter, doesn't need a python dependency or a second script at all, I'm sure there are downsides but it seems to work for me with the few tests I've done.

A: There doesn't seem to be a standard way for doing this. The best way that I can think of is using the Docker multistage build feature.
For example, here I am comparing the apline and debian images. In yourm case set the image names to the ones you want to compare
I basically copy all the file from each image into a git repository and commit after each copy.
FROM alpine as image1

FROM debian as image2

FROM ubuntu
RUN apt-get update && apt-get install -y git
RUN git config --global user.email "you@example.com" &&\
 git config --global user.name "Your Name"

RUN mkdir images
WORKDIR images
RUN git init

COPY --from=image1 / .
RUN git add . && git commit -m "image1"

COPY --from=image2 / .
RUN git add . && git commit -m "image2"

CMD tail > /dev/null

This will give you an image with a git repository that records the differences between the two images.
docker build -t compare .
docker run -it compare bash

Now if you do a git log you can see the logs and you can compare the two commits using git diff <commit1> <commit2>
Note: If the image building fails at the second commit, this means that the images are identical, since a git commit will fail if there are no changes to commit.

A: If you want to compare content of images you can use docker inspect <imageName> command and you can look at section RootFS
docker inspect redis
    "RootFS": {
        "Type": "layers",
        "Layers": [
            "sha256:eda7136a91b7b4ba57aee64509b42bda59e630afcb2b63482d1b3341bf6e2bbb",
            "sha256:c4c228cb4e20c84a0e268dda4ba36eea3c3b1e34c239126b6ee63de430720635",
            "sha256:e7ec07c2297f9507eeaccc02b0148dae0a3a473adec4ab8ec1cbaacde62928d9",
            "sha256:38e87cc81b6bed0c57f650d88ed8939aa71140b289a183ae158f1fa8e0de3ca8",
            "sha256:d0f537e75fa6bdad0df5f844c7854dc8f6631ff292eb53dc41e897bc453c3f11",
            "sha256:28caa9731d5da4265bad76fc67e6be12dfb2f5598c95a0c0d284a9a2443932bc"
        ]
    }

if all layers are identical then images contains identical content

A: If we rebuild the Dockerfile it is almost certainly going to produce a new hash.
The only way to create an image with the same hash is to use docker save and docker load.  See https://docs.docker.com/engine/reference/commandline/save/
We could then use Bukharov Sergey's answer (i.e. docker inspect) to inspect the layers, looking at the section with key 'RootFS'.


text:
Q: Firefox (3.6.3 Mac) fails to float left the last of a set of left-floated list items I have a set of <li> elements in an unordered list. The items are all floated left, with a bit of space between them. Problem is, the last list item is wrapped (isn't at the end of the list, but leftmost on a new line). I have no idea why. The rendering is fine with Mac Safari and with IE 7.
The CSS for the li items floats them left:
list-style: none;
float: left;
padding: 1px 1px 0 1px;
margin-right: 1px;
border: 1px solid #2A3139;  /* to hold space for hover border */

Another factoid: the unordered list is in a div (for clipping purposes; the list is scrolled horizontally); the CSS for the <ul> specifies:
overflow: none;
position: relative;

(though I don't think this is related to the problem... but one never knows)

A: Is the width of your container div wide enough to accommodate the width of all your li elements PLUS their margins and borders? If not, the floats will wrap to the next line if there is not enough space.


text:
Q: extending Wpf MouseButtonEventArgs to enable custom args when any event handler is created there is no option i know of that i could pass my own argument to the event handler.
for example MouseDown event,
void TxblckLineNum_MouseDown(object sender, RoutedEventArgs e)
{
    //do stuff with e ...
}

i need to pass some more properties within the e parameter so i have tried to derive from various EventArgs classes and i couldn't use any of them as e
what is the best approach for passing some extra data into the event handler ?

A: TxblckLine.MouseDown += new System.Windows.Input.MouseButtonEventHandler((s, e) => TxblckLineNum_MouseDown(s, e, SomePar, SomeOtherPar));

void TxblckLineNum_MouseDown(object sender, RoutedEventArgs e, string SomePar, int SomeOtherPar)
{
    //do stuff with SomePar / SomeOtherPar...
}


text:
Q: iPhone app compatibility i just want how to make sure that my application will be compatible with iPhone 4, 3GS,3G,iPad touch ?
should i set up any parameters in Xcode or interface builder or both ?
THX in advance :)

A: To force you application to be used only with some devices, this is done while publishing your application on the AppStore.
Speaking about code, the compatibility factor is not the device, but the iOS version. In that case, in your build settings, you can set the "iOS Deployment Target".


text:
Q: If $Aut_K(L)$ operates transitive over the zeros of $f$, then $f$ is irreducible Let $K$ be a field, $f\in K[X]$ a separable polynomial and $L$ a splitting field of $f$.
Show that if $Aut_K(L)$ operates transitive over the zeros of f, then f is irreducible.
Can someone help?

A: Hint: supose $\;a_1,...,a_k\;$ are the roots of $\;f(x)=g(x)h(x)\;$ , and suppose $\;a_1,a_2\;$ are roots of the different non-constant factors $\;g(x)\,,\,\,h(x)\;$ .
Is it possible that $\;\sigma a_1=a_2\;$ , for some $\;\sigma\in\text{Aut}_KL\;$ , as given in the problem?


text:
Q: Considerations regarding a p2p social network While the are many social networks in the wild, most rely on data stored on a central site owned by a third party.
I'd like to build a solution, where data remains local on member's systems. Think of the project as an address book, which automagically updates contact's data as soon a a contact changes its coordinates. This base idea might get extended later on...
Updates will be transferred using public/private key cryptography using a central host. The sole role of the host is to be a store and forward intermediate. Private keys remain private on each member's system.
If two client are both online and a p2p connection could be established, the clients could transfer data telegrams without the central host.
Thus, sender and receiver will be the only parties which are able create authentic messages.
Questions:

*

*Do exist certain protocols which I should adopt?

*Are there any security concerns I should keep in mind?

*Do exist certain services which should be integrated or used somehow?

More technically:

*

*Use e.g. Amazon or Google provided services?

*Or better use a raw web-server? If yes: Why?

*Which algorithm and key length should be used?

UPDATE-1
I googled my own question title and found this academic project developed 2008/09: http://www.lifesocial.org/.

A: The solution you are describing sounds remarkably like email, with encrypted messages as the payload, and an application rather than a human being creating the messages.
It doesn't really sound like "p2p" - in most P2P protocols, the only requirement for central servers is discovery - you're using store & forward.
As a quick proof of concept, I'd set up an email server, and build an application that sends emails to addresses registered on that server, encrypted using PGP - the tooling and libraries are available, so you should be able to get that up and running in days, rather than weeks. In my experience, building a throw-away PoC for this kind of question is a great way of sifting out the nugget of my idea.
The second issue is that the nature of a social network is that it's a network. Your design may require you to store more than the data of the two direct contacts - you may also have to store their friends, or at least the public interactions those friends have had.
This may not be part of your plan, but if it is, you need to think it through early on - you may end up having to transmit the entire social graph to each participant for local storage, which creates a scalability problem....

A: The paper about Safebook might be interesting for you.
Also you could take a look at other distributed OSN and see what they are doing.

A: None of the federated networks mentioned on http://en.wikipedia.org/wiki/Distributed_social_network is actually distributed. What Stefan intends to do is indeed new and was only explored by some proprietary folks.

A: I've been thinking about the same concept for the last two years. I've finally decided to give it a try using Python.
I've spent the better part of last night and this morning writing a sockets communication script & server. I also plan to remove the central server from the equation as it's just plain cumbersome and there's no point to it when all the members could keep copies of their friend's keys.
Each profile could be accessed via a hashed string of someone's public key. My social network relies on nodes and pods. Pods are computers which have their ports open to the network. They help with relaying traffic as most firewalls block incoming socket requests. Nodes store information and share it with other nodes. Each node will get a directory of active pods which may be used to relay their traffic.

A: The PeerSoN project looks like something you might be interested in: http://www.peerson.net/index.shtml
They have done a lot of research and the papers are available on their site.

A: Some thoughts about it:

*

*protocols to use: you could think exactly on P2P programs and their design

*security concerns: privacy. Take a great care to not open doors: a whole system can get compromised 'cause you have opened some door.

*services: you could integrate with the regular social networks through their APIs

People will have to install a program in their computers and remeber to open it everytime, like any P2P client. Leaving everything on a web-server has a smaller footprint / necessity of user action.
Somehow you'll need a centralized server to manage the searches. You can't just broadcast the internet to find friends. Or you'll have to rely uppon email requests to add somenone, and to do that you'll need to know the email in advance.
The fewer friends /contacts use your program, the fewer ones will want to use it, since it won't have contact information available.
I see that your server will be a store and forward, so the update problem is solved.