text:
Q: ggplot throwing an error in weird circumstances I am trying to run this following code:
p <- ggplot(data=cuernavaca.map, aes(long, lat, group=group))
p + geom_polygon(size=0.1, aes(fill=pobtot)) + coord_equal() + facet_wrap(~nombre_municipio,scales="free") + coord_equal()  + scale_fill_gradient2(low="blue", high="red", midpoint=mean(cuernavaca.map$pobtot, na.rm=TRUE))+ tema.mapas + ggtitle("Cuervaca y Zona metropolitana\nPoblación Total") + labs(fill="Población total")

but I got this error:

Error: ggplot2 doesn't know how to deal with data of class uneval

The object cuernavaca.map is a fortified SpatialDataFrame.
The weird thing is that this only happens in one machine (Ubuntu 13.04, RStudio 0.97.551, R 3.0.1) when I execute the knit2html or I hit the button knit HTML, If I execute the lines of code in the console (inside RStudio) everything works (I mean, the plot is done), If I cut and paste that code in other .Rmd file it works and If I execute it in another Ubuntu box (same specs as above) or MacOS X, it works!
Any ideas?
UPDATE:
As is written in the comments, the problem seems to be the order of the unnamed parameters, so I change the code to this:
ggplot(data = cuernavaca.map) +
geom_polygon(mapping = aes(x = long, y = lat, group = group, colour = NA, fill = pobtot)) +
coord_equal() +
facet_wrap(~nombre_municipio, scales = "free") +
scale_fill_gradient2(low = "blue", high = "red", midpoint = mean(cuernavaca.map$pobtot,
na.rm = TRUE)) +
tema.mapas +
ggtitle("Cuervaca y Zona metropolitana\nPoblación Total") +
labs(fill = "Población total")

And know is everything working ... almost.
If you see the code I remove the size parameter in the geom_polygon and I set the colour to NA, I made that, not for aesthetics reasons, but because, that parameters are not working: the line width of the polygon gets enormous and the color is just ignored, sometimes gets light red, in others it just disappears...
As a funny thing, the plots below this one, are working now, too, but guess what? The code is the following:
ggplot(legend = FALSE) +
geom_polygon(data = cuernavaca.map, size = 0.1, aes(long,
lat, group = group, colour = "grey80", fill = ind_vul)) +
scale_fill_gradient2(low = "blue", high = "red", midpoint = mean(cuernavaca.map$ind_vul, na.rm = TRUE)) +
geom_point(data = puntos.df, aes(as.numeric(long), as.numeric(lat), colour = geografico), size = 2) +
facet_wrap(~municipio, scales = "free") +
tema.mapas +
labs(fill = "Índice de vulnerabilidad")

puntos.df is a data.frame with latitude and longitude, so no big deal, but not how the size parameters is out of the aes and is working (I am not getting a error of "not know how to deal with a numeric... blah blah")
Could be a memory issue?

A: As is told in the edit, the answer was using named parameters:
ggplot(data = cuernavaca.map) +
geom_polygon(mapping = aes(x = long, y = lat, group = group, colour = NA, fill = pobtot)) +
coord_equal() +
facet_wrap(~nombre_municipio, scales = "free") +
scale_fill_gradient2(low = "blue", high = "red", midpoint = mean(cuernavaca.map$pobtot, na.rm = TRUE)) +

There are some unanswered questions, but I posted a new one in: ggplot map with points: size, colour, legend, aesthetics problems


text:
Q: Android - ViewPager Adapter, set primary item before adapter is instantiated I know i can do
 viewPager.setCurrentItem(position)

to set my view pager at the desired position. My question is if and how i can do this before the adapter is instantiated.
Meaning that if I do
pagerAdapter = new ViewPagerAdapter(arg1,arg2....);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(position);

item 0 is first build and after that the item at the desired position is also build. Which takes double the time...In my adapter each item needs quite a lot of work to be build, so it would be best to avoid the 0 position item to be build if possible. Maybe by passing the desired position as an argument at the adapter's instantiation...?
Any way to do that?

A: If the time and work is what you're worry about, I'd try to avoid building the page at position 0 until the desired one has been built. You could use a variable lets say "desiredPageHasBeenBuilt" in your adapter, when requesting the item at position 0 you could return an "empty page" if the variable desiredPageHasBeenBuilt is false, when your desired page has been build set the variable to true and the page 0 can be built.

A: For a solution that works in Android M as well as older versions, use reflection as follows:
int currentItem = 5;

// Set initial position first...
Field field = ViewPager.class.getDeclaredField("mRestoredCurItem");
field.setAccessible(true);
field.set(mPager, currentItem);

// ...and then set adapter
mPager.setAdapter(adapter);

Using reflection is safe, because you control the ViewPager implementation (it's included with your app).
If you use Proguard, then you need to include the following in its config:
-keepclassmembers class android.support.v4.view.ViewPager {
    private int mRestoredCurItem;
}

or the field mRestoredCurItem will be renamed by Proguard.

A: You can just set blank adapter and after that set your real adapter this way you will "trick" the viewpager and you want load any data you dont want to.
this.viewPager.setAdapter(new PagerAdapter() {
        @Override
        public int getCount() {
            return 0;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return false;
        }
    });
this.viewPager.setCurrentItem(imagePosition, false);
this.viewPager.setAdapter(adapter);
this.viewPager.setCurrentItem(imagePosition, false);

A: You can fool the viewpager to start at a given position before the adapter is set, by calling onRestoreInstanceState, like this:
int currentItem = 5;

Parcel parcel = Parcel.obtain();
writeParcelable(BaseSavedState.EMPTY_STATE, 0);

writeInt(currentItem);
writeParcelable(null, 0);

setDataPosition(0);
SavedState savedState = ViewPager.SavedState.CREATOR.createFromParcel(parcel);

mPager.onRestoreInstanceState(savedState);

mPager.setAdapter(mAdapter);

A: Maybe this is not the answer you're looking for, but have you tried to it as it was designed? Do not start heavy work on page fragment before it is attached to the screen. That way you'll get that behavior you want without hacking android implementation.

A: you can do this trick:
refactor all of your heavy work into a function, because creating a fragment is not takes much time, and only execute the function when user is going to see it by calling that function inside OnPageChangeListener listener and at the
@Override
public void onPageSelected(int position){
    // call your function that do heavy working
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS 5: willRotateToInterfaceOrientation:duration not called when first loading controller I've implemented this method in my code to know when an interface orientation change will occur:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration

I rely on this to be called to setup my views.  In either iOS 4 or 5 it gets called properly when the orientation changes.
In iOS 4 it also gets called when the controller first loads (regardless of if the orientation changes or not, it gets called once at the beginning with the correct orientation).
The problem is I noticed in iOS 5 this does not happen anymore.  The method gets called when the orientation changes but not when the controller initially loads.  This is a problem for me because I rely on this to setup the initial view placement based on the orientation.
Any ideas why this behaviour changed?  What's the best way to handle this?  Should I check what the orientation is in viewDidLoad if on iOS 5 and then manually call the willRotate and didRotate methods?  This feels a bit like a hack.
Thanks for any input you can provide.

A: Since I'm pressed for time I've had to work around this odd behaviour and manually call the orientation methods in viewDidLoad.  This is a bit of a hack but it's working fine so far.
In viewDidLoad I added this:
if ( SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.0") ) {
    UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    [self willRotateToInterfaceOrientation:interfaceOrientation duration:0.2f];
}

I've then added this in a common header file:
// iOS Version Checking
#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

I got the iOS version checking defines from an answer to this question on SO.

A: Even I faced a similar issue and had to override it in the tabbarcontroller derived class to get this to work:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [_tabBarConroller willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
}

Hope this helps!!

A: I've run into this same problem and have been pulling my hair out. I've finally discovered a solution but unfortunately this will be iOS 5.0 + only:
Place the following code in your viewDidLoad method in your custom UIViewController:
double delayInSeconds = 0.1f;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [UIViewController attemptRotationToDeviceOrientation];
});

This will push the rotation update to the next run loop. attemptRotationToDeviceOrientation is an iOS 5.0+ call.

A: Since iOS 5 and higher you should build you view controllers hierarchy (using -addChildViewController:). Then child view controllers begin to call -willRotateToInterfaceOrientation:interfaceOrientation: and other interface related methods again (because parent controller will notify them about UI orientation changes).
Please, do not use any 'dirty' methods.
Useful documentation:
Apple docs about 'addChildViewController:'


text:
Q: Transmuting u8 buffer to struct in Rust I have a byte buffer of unknown size, and I want to create a local struct variable pointing to the memory of the beginning of the buffer. Following what I'd do in C, I tried a lot of different things in Rust and kept getting errors. This is my latest attempt:
use std::mem::{size_of, transmute};

#[repr(C, packed)]
struct MyStruct {
    foo: u16,
    bar: u8,
}

fn main() {
    let v: Vec<u8> = vec![1, 2, 3];
    let buffer = v.as_slice();
    let s: MyStruct = unsafe { transmute(buffer[..size_of::<MyStruct>()]) };
}

I get an error:
error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
   --> src/main.rs:12:42
    |
12  |     let s: MyStruct = unsafe { transmute(buffer[..size_of::<MyStruct>()]) };
    |                                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `[u8]`
    = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>

A: If you don't want to copy the data to the struct but instead leave it in place, you can use slice::align_to. This creates a &MyStruct instead:
#[repr(C, packed)]
#[derive(Debug, Copy, Clone)]
struct MyStruct {
    foo: u16,
    bar: u8,
}

fn main() {
    let v = vec![1u8, 2, 3];

    // I copied this code from Stack Overflow
    // without understanding why this case is safe.
    let (head, body, _tail) = unsafe { v.align_to::<MyStruct>() };
    assert!(head.is_empty(), "Data was not aligned");
    let my_struct = &body[0];

    println!("{:?}", my_struct);
}

Here, it's safe to use align_to to transmute some bytes to MyStruct because we've used repr(C, packed) and all of the types in MyStruct can be any arbitrary bytes.
See also:

*

*How to read a struct from a file in Rust?

*Can I take a byte array and deserialize it into a struct?

A: You can use methods on raw pointers and functions in std::ptr to directly read/write objects in place.

*

*std::ptr::read

*std::ptr::read_unaligned

*std::ptr::write

*std::ptr::write_unaligned
In your case:
fn main() {
    let v: Vec<u8> = vec![1, 2, 3];
    let s: MyStruct = unsafe { std::ptr::read(v.as_ptr() as *const _) };
    println!("here is the struct: {:?}", s);
}

I would encourage you to wrap this in a reusable method and perform a length check on the source buffer before attempting the read.

A: I gave up on the transmute stuff. *mut (raw pointers) in Rust are pretty similar to C pointers, so this was easy:
#[repr(C, packed)] // necessary
#[derive(Debug, Copy, Clone)] // not necessary
struct MyStruct {
    foo: u16,
    bar: u8,
}

fn main() {
    let v: Vec<u8> = vec![1, 2, 3];
    let buffer = v.as_slice();
    let mut s_safe: Option<&MyStruct> = None;
    let c_buf = buffer.as_ptr();
    let s = c_buf as *mut MyStruct;
    unsafe {
        let ref s2 = *s;
        s_safe = Some(s2);
    }
    println!("here is the struct: {:?}", s_safe.unwrap());
}

The unsafe tag there is no joke, but the way I'm using this, I know my buffer is filled and take the proper precautions involving endianness later on.


text:
Q: Node.js Programming Pattern for getting Execution Context I am writing a web app in node.js. Now every processing on the server is always in the context of a session which is either retrieved or created at the very first stage when the request hits the server. After this the execution flows through multiple modules and callbacks within them. What I am struggling with is in creating a programming pattern so that at any point in the code the session object is available without the programmer requiring it to pass it as an argument in each function call.
If all of the code was in one single file I could have had a closure but if there are function calls to other modules in other files how do I program so that the session object is available in the called function without passing it as an argument. I feel there should be some link between the two functions in the two files but how to arrange that is where I am getting stuck.
In general I would like to say there is always a execution context which could be a session or a network request whose processing is spread across multiple files and the execution context object is to be made available at all points. There can actually be multiple use cases like having one Log object for each network request or one Log object per session. And the plumbing required to make this work should be fitted sideways without the application programmer bothering about it. He just knows that that execution context is available at all places.
I think it should fairly common problem faced by everyone so please give me some ideas.
Following is the problem
MainServer.js

  app = require('express').createServer();
  app_module1 = require('AppModule1');
  var session = get_session();
  app.get('/my/page', app_module1.func1);

AppModule1.js

  app_module2 = require('AppModule2');
  exports.func1 = function(req,res){

     //  I want to know which the session context this code is running for

     app_module2.func2(req,res);

   }

AppModule2.js

   exports.func2 = function(req,res){

    // I want to know where the session context in which this code is running

    }

A: You can achieve this using Domains -- a new node 0.8 feature. The idea is to run each request in it's own domain, providing a space for per-request data. You can get to the current request's domain without having to pass it all over via process.domain.
Here is an example of getting it setup to work with express:
How to use Node.js 0.8.x domains with express?
Note that domains in general are somewhat experimental and process.domain in particular is undocumented (though apparently not going away in 0.8 and there is some discussion on making it permanent). I suggest following their recommendation and adding an app-specific property to process.domain.data.
https://github.com/joyent/node/issues/3733
https://groups.google.com/d/msg/nodejs-dev/gBpJeQr0fWM/-y7fzzRMYBcJ

A: Since you are using Express, you can get session attached to every request. The implementation is following:
var express = require('express');
var app = express.createServer();
app.configure('development', function() {
  app.use(express.cookieParser());
  app.use(express.session({secret: 'foo', key: 'express.sid'}));
});

Then upon every request, you can access session like this:
app.get('/your/path', function(req, res) {
  console.log(req.session);
});

I assume you want to have some kind of unique identifier for every session so that you can trace its context. SessionID can be found in the 'express.sid' cookie that we are setting for each session.
app.get('/your/path', function(req, res) {
  console.log(req.cookies['express.sid']);
});

So basically, you don't have to do anything else but add cookie parser and enable sessions for your express app and then when you pass the request to these functions, you can recognize the session ID. You MUST pass the request though, you cannot build a system where it just knows the session because you are writing a server and session is available upon request.

A: What express does, and the common practice for building an http stack on node.js is use http middleware to "enhance" or add functionality to the request and response objects coming into the callback from your server.  It's very simple and straight-forward.
module.exports = function(req, res, next) {
    req.session = require('my-session-lib');
    next();
};

req and res are automatically passed into your handler, and from their you'll need to keep them available to the appropriate layers of your architecture.  In your example, it's available like so:
AppModule2.js
exports.func2 = function(req,res){

    // I want to know where the session context in which this code is running
    req.session; // <== right here

}

A: Nodetime is a profiling tool that does internally what you're trying to do.  It provides  a function that instruments your code in such a way that calls resulting from a particular HTTP request are associated with that request.  For example, it understands how much time a request spent in Mongo, Redis or MySQL.  Take a look at the video on the site to see what I mean http://vimeo.com/39524802.
The library adds probes to various modules.   However, I have not been able to see how exactly the context (url) is passed between them.  Hopefully someone can figure this out and post an explanation.
EDIT: Sorry, I think this was a red-herring.  Nodetime is using the stack trace to associate calls with one another.  The results it presents are aggregates across potentially many calls to the same URL, so this is not a solution for OP's problem.


text:
Q: How to show a website as a wallpaper in Windows 10? is there a way to show a webpage on the windows 10 desktop (as a wallpaper, not in the browser)? I'd like to show an URL to google calendar on the background.
I have no idea to get this done. (Is it configurable? Is there a solution in Python 3, c# or elsewhat?)
merlinuwe

A: the easy solution:
Install this:  http://www.stefanbion.de/htmlwindow/
and add a link to the desktop with this target:
C:\HtmlWindow\HtmlWindow.exe "Kalender" "https://calendar.google.com/calendar/r" 3600

The not so easy solution:
Install selenium: pip install selenium
Download the geckodriver from https://github.com/mozilla/geckodriver/releases
and put it somewhere in your path.
from selenium import webdriver
driver = webdriver.Firefox(executable_path='C:\ImPfad\geckodriver.exe')
driver.get(r"https://www.google.de/")
driver.save_screenshot(r"C:\Users\Me\Desktop\Kalender.png")
driver.quit()

(tested)
But there is an open issue: When the page need credentials (login, password), you have still a problem.


text:
Q: I meet an surprised error in Google tensorflow2.0 tutorials in text_classification_rnn When i reading Google tensorflow2.0 tutorials, i meet an surprised error when i try to test in my jupyter. It is so strange!It run fluently in Google colab! The tutorials is this
My computer GPU is gtx1060 6G, and memory is 16G, I think my computer is ok to run this tutorials.
I try run it on Jupyter, and it run error.But run fluently on Google colab!
You can see the error code following or go to the web:

from __future__ import absolute_import, division, print_function, unicode_literals

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

import tensorflow_datasets as tfds
# tfds.disable_progress_bar()
(train_data, test_data), info = tfds.load(
    'imdb_reviews/subwords8k',
    split = (tfds.Split.TRAIN, tfds.Split.TEST),
    with_info=True, as_supervised=True)
encoder = info.features['text'].encoder
padded_shapes = ([None],())
train_batches = train_data.shuffle(1000).padded_batch(10, padded_shapes = padded_shapes)
test_batches = test_data.shuffle(1000).padded_batch(10, padded_shapes = padded_shapes)

embedding_dim=16

model = keras.Sequential([
    layers.Embedding(encoder.vocab_size, embedding_dim,mask_zero=True),
    layers.Bidirectional(tf.keras.layers.LSTM(32)),
    layers.Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=['accuracy'])

history = model.fit(
    train_batches,
    epochs=10,
    validation_data=test_batches, validation_steps=20,verbose=2)

It is my first time meeting this error, and I don't know how to fix it, but it run fluently on Google colab, I don't know why?
The error following:

Epoch 1/10
---------------------------------------------------------------------------
CancelledError                            Traceback (most recent call last)
<ipython-input-2-8f27353fef79> in <module>
     31     train_batches,
     32     epochs=10,
---> 33     validation_data=test_batches, validation_steps=20,verbose=2)

c:\users\sha\anaconda3\envs\tensorflow2\lib\site-packages\tensorflow_core\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    726         max_queue_size=max_queue_size,
    727         workers=workers,
--> 728         use_multiprocessing=use_multiprocessing)
    729
    730   def evaluate(self,

c:\users\sha\anaconda3\envs\tensorflow2\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in fit(self, model, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, **kwargs)
    322                 mode=ModeKeys.TRAIN,
    323                 training_context=training_context,
--> 324                 total_epochs=epochs)
    325             cbks.make_logs(model, epoch_logs, training_result, ModeKeys.TRAIN)
    326

c:\users\sha\anaconda3\envs\tensorflow2\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in run_one_epoch(model, iterator, execution_function, dataset_size, batch_size, strategy, steps_per_epoch, num_samples, mode, training_context, total_epochs)
    121         step=step, mode=mode, size=current_batch_size) as batch_logs:
    122       try:
--> 123         batch_outs = execution_function(iterator)
    124       except (StopIteration, errors.OutOfRangeError):
    125         # TODO(kaftan): File bug about tf function and errors.OutOfRangeError?

c:\users\sha\anaconda3\envs\tensorflow2\lib\site-packages\tensorflow_core\python\keras\engine\training_v2_utils.py in execution_function(input_fn)
     84     # `numpy` translates Tensors to values in Eager mode.
     85     return nest.map_structure(_non_none_constant_value,
---> 86                               distributed_function(input_fn))
     87
     88   return execution_function

c:\users\sha\anaconda3\envs\tensorflow2\lib\site-packages\tensorflow_core\python\eager\def_function.py in __call__(self, *args, **kwds)
    455
    456     tracing_count = self._get_tracing_count()
--> 457     result = self._call(*args, **kwds)
    458     if tracing_count == self._get_tracing_count():
    459       self._call_counter.called_without_tracing()

c:\users\sha\anaconda3\envs\tensorflow2\lib\site-packages\tensorflow_core\python\eager\def_function.py in _call(self, *args, **kwds)
    485       # In this case we have created variables on the first call, so we run the
    486       # defunned version which is guaranteed to never create variables.
--> 487       return self._stateless_fn(*args, **kwds)  # pylint: disable=not-callable
    488     elif self._stateful_fn is not None:
    489       # Release the lock early so that multiple threads can perform the call

c:\users\sha\anaconda3\envs\tensorflow2\lib\site-packages\tensorflow_core\python\eager\function.py in __call__(self, *args, **kwargs)
   1821     """Calls a graph function specialized to the inputs."""
   1822     graph_function, args, kwargs = self._maybe_define_function(args, kwargs)
-> 1823     return graph_function._filtered_call(args, kwargs)  # pylint: disable=protected-access
   1824
   1825   @property

c:\users\sha\anaconda3\envs\tensorflow2\lib\site-packages\tensorflow_core\python\eager\function.py in _filtered_call(self, args, kwargs)
   1139          if isinstance(t, (ops.Tensor,
   1140                            resource_variable_ops.BaseResourceVariable))),
-> 1141         self.captured_inputs)
   1142
   1143   def _call_flat(self, args, captured_inputs, cancellation_manager=None):

c:\users\sha\anaconda3\envs\tensorflow2\lib\site-packages\tensorflow_core\python\eager\function.py in _call_flat(self, args, captured_inputs, cancellation_manager)
   1222     if executing_eagerly:
   1223       flat_outputs = forward_function.call(
-> 1224           ctx, args, cancellation_manager=cancellation_manager)
   1225     else:
   1226       gradient_name = self._delayed_rewrite_functions.register()

c:\users\sha\anaconda3\envs\tensorflow2\lib\site-packages\tensorflow_core\python\eager\function.py in call(self, ctx, args, cancellation_manager)
    509               inputs=args,
    510               attrs=("executor_type", executor_type, "config_proto", config),
--> 511               ctx=ctx)
    512         else:
    513           outputs = execute.execute_with_cancellation(

c:\users\sha\anaconda3\envs\tensorflow2\lib\site-packages\tensorflow_core\python\eager\execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     65     else:
     66       message = e.message
---> 67     six.raise_from(core._status_to_exception(e.code, message), None)
     68   except TypeError as e:
     69     keras_symbolic_tensors = [

c:\users\sha\anaconda3\envs\tensorflow2\lib\site-packages\six.py in raise_from(value, from_value)

CancelledError:  [_Derived_]RecvAsync is cancelled.
     [[{{node Reshape_11/_38}}]] [Op:__inference_distributed_function_16087]

Function call stack:
distributed_function

Thanks for anyone help me!

A: Try to reduce the batch_size, it should work.


text:
Q: .groupby & .fillna with median # Create a groupby object: by_sex_class
by_sex_class = titanic.groupby(["sex","pclass"]).count()

# Write a function that imputes median
def impute_median(series):
    return series.fillna(series.median())

# Impute age and assign to titanic['age']
titanic.age = by_sex_class["age"].transform(impute_median)

# Print the output of titanic.tail(10)
print(titanic.tail(10))

I'm unclear how can we assign the column, ["age"] from modified (grouped) df, by_sex_class, to the original (un-grouped) df, titanic.
Wouldn't the assignments be jumbled up?
Thanks in advance for your explanations.

A: I will recommend using this
df['age'].fillna(df.groupby(["sex","pclass"])['age'].transform('median'),inplace=True)

A: The new values are matched to the original dataframe by the index (when you group, you still keep the original index).
df['age'] = df.groupby(["sex","pclass"])['age'].transform(lambda x: x.fillna(x.median()))


text:
Q: Alphabet Series Generation in SQL Server I am trying to generate a series of alphabets, using SQL Server.
Suppose I have a tables as follows
DECLARE @Funding TABLE (FundingDetailID INT,FundingID INT, DetailDescription VARCHAR(50))
INSERT INTO @Funding (FundingDetailID ,FundingID , DetailDescription) VALUES (1,107,'Desc 1')
INSERT INTO @Funding (FundingDetailID ,FundingID , DetailDescription) VALUES (1,107,'Desc 2')
INSERT INTO @Funding (FundingDetailID ,FundingID , DetailDescription) VALUES (1,107,'Desc 3')

I am trying to obtain the following result.
a) Desc 1
b) Desc 2
c) Desc 3

How do I generate "a)", "b)", …  ? I am not allowed to add any extra temp table or table variable for storing the alphabets initially. They should be generated.
And this is to be done in SQL Server 2005.
Any thoughts ?
Thanks
Lijo Cheeran Joseph

A: Use ROW_NUMBER() as follows
DECLARE @Funding TABLE (FundingDetailID INT,FundingID INT, DetailDescription VARCHAR(50))
INSERT INTO @Funding VALUES (1,107,'Desc 1')
INSERT INTO @Funding VALUES (1,107,'Desc 2')
INSERT INTO @Funding VALUES (1,107,'Desc 3')

SELECT CHAR (CAST (96+ROW_NUMBER() OVER (Order BY FundingDetailID) AS VARCHAR)) + ') ' + DetailDescription
FROM @Funding

-----------------------------------------------------
a) Desc 1
b) Desc 2
c) Desc 3

A: Raj More already posted the row_number() while I was writing it.  I voted for his answer, but here's my variant which does an update on the table, just in case you are interested in that.
update  f1
set     f1.DetailDescription = char(96 + f2.rn) + ') ' + f2.DetailDescription
from    @Funding f1
join    (
        select  row_number() over (order by FundingDetailId,
                                      FundingId, DetailDescription) as rn
        ,       *
        from    @Funding f
        ) f2
on      f1.FundingDetailID = f2.FundingDetailID
        and f1.FundingID = f2.FundingID
        and f1.DetailDescription = f2.DetailDescription

select  *
from    @Funding


text:
Q: How to install Python 2.7 on Fedora 32 Linux when the newest version is Python 3.8? There is a software suite named amitools, which allows use of retro or vintage or whatever the term for nostalgia is these days, of AmigaOS programs directly from a Linux command line without using a full-scale emulator. It is written in Python.
I have installed the latest official version, only it's not working properly for me. One of the developers of amitools told me his version would work better. There's only one problem: his version is written in Python 2.7, whereas the official version is written in Python 3.8. These seem to be incompatible with each other.
I am running a Fedora 32 Linux system. I have both /usr/bin/python2 and /usr/bin/python3 installed. /usr/bin/python used to be a symlink to /usr/bin/python3, I changed it to /usr/bin/python3. But installing the software suite still isn't working.
Apparently I need the 2.7 version of "pip" (a Python installer program) to install the software suite. But "sudo dnf install python-pip" tells me I already have python-pip version 3.8 installed, and there doesn't seem to be a package called "python-pip2" or "python-pip2.7" available.
What I am trying to do here is install an older version of Python and pip alongside my current version, just to see if the developer's version of amitools works any better than the official version, because it's written in an older version of Python.

A: python2-pip isn't available from the Fedora 32 repos as Python 2 is no longer supported. You can install it from the UnitedRPMs repo with the following but I wouldn't recommend it as it's not a supported repo:
rpm --import https://raw.githubusercontent.com/UnitedRPMs/unitedrpms/master/URPMS-GPG-PUBLICKEY-Fedora

yum install https://github.com/UnitedRPMs/unitedrpms/releases/download/17/unitedrpms-$(rpm -E %fedora)-17.fc$(rpm -E %fedora).noarch.rpm -y

The best option is to build it from the source code. You can get it from here: https://github.com/python/cpython/releases/tag/v2.7.18
In regards to your comment below, as a regular user:
pip install amitools==0.1.0 --user


text:
Q: Unhandled Expcetion C++ - VS2012 If a std::exception is thrown from my code, Test Explorer will just show "Message: Unhandled C++ Exception". It does show the proper stack trace though.
Is it possible to have Test Explorer show the message from the what() method of std::exception?

A: what method will only tell you the name of the exception. may be there is some method like stack trace similar to java.


text:
Q: What is error in my usage of datetime module? sunrise = tt.strftime('%I:%M %p', tt.gmtime(json_data['sys']['sunrise'] - 21600))
sunset = tt.strftime('%H:%M %p', tt.gmtime(json_data['sys']['sunset'] - 21600))

Results:
Sunrise is: 05:45 PM
Sunset is: 07:20 AM

But sunrise is am  and sunset is pm.
Please tell me what's the error.

A: Possible duplicate of How can I account for period (AM/PM) using strftime?.
As stated in the answers to that question, when using the directive %p, you should use the 12-hour format %I instead of the 24-hour format %H to output the equivalent AM or PM for your locale.
You can also try reading the docs for strftime() here,


text:
Q: Vagrant not recognizing Powershell version I am currently trying to use Cmder shell to run vagrant but when I'm trying to add vagrant box it spit out the following error:
λ  vagrant box add ubuntu/trusty64
Vagrant failed to initialize at a very early stage:
The version of powershell currently installed on this host is less than
the required minimum version. Please upgrade the installed version of
powershell to the minimum required version and run the command again.
Installed version: N/A
Minimum required version: 3
My powershell version is 5.1.19041.1023, Wondow 10.


text:
Q: Jama and Commons Math don't give desired result for relatively big matrix I am using Jama and Apache Commons Math to solve linear algebra equations. They both work fine when the matrix is small (4x4). But not when it is relatively big (25x25). Below are my implemenations:
Jama:
    public double[][] solve(double[][] startState, double[][] input){
    double[][] answer = new double[1][input.length-1];
    Matrix A = new Matrix(input);
    Matrix B = new Matrix(startState);
    Matrix X = A.solve(B);
    answer = X.getArray();
    return answer;
}

This works fine for:
    double[][] startState = {{1},{2},{1},{2}};
    double[][] input = {{1,1,0,0},{1,1,1,0},{0,1,1,1,},{0,0,1,1}};
    double[][] answer = new JamaSolution().solve(startState, input);

But it fails for:
    double[][] startState = { {0},{1},{2},{0},{2}, {0},{2},{1},{1},{0}, {0},{2},{1},{2},{2}, {1},{1},{1},{1},{2}, {1},{2},{1},{0},{0} };
    double[][] input={
             {1,1,0,0,0, 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {1,1,1,0,0, 0,1,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {0,1,1,1,0, 0,0,1,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {0,0,1,1,1, 0,0,0,1,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {0,0,0,1,1, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,

             {1,0,0,0,0, 1,1,0,0,0, 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {0,1,0,0,0, 1,1,1,0,0, 0,1,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {0,0,1,0,0, 0,1,1,1,0, 0,0,1,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {0,0,0,1,0, 0,0,1,1,1, 0,0,0,1,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {0,0,0,0,0, 0,0,0,1,1, 0,0,0,0,1, 0,0,0,0,0, 0,0,0,0,0} ,

             {0,0,0,0,0, 1,0,0,0,0, 1,1,0,0,0, 1,0,0,0,0, 0,0,0,0,0} ,
             {0,0,0,0,0, 0,1,0,0,0, 1,1,1,0,0, 0,1,0,0,0, 0,0,0,0,0} ,
             {0,0,0,0,0, 0,0,1,0,0, 0,1,1,1,0, 0,0,1,0,0, 0,0,0,0,0} ,
             {0,0,0,0,0, 0,0,0,1,0, 0,0,1,1,1, 0,0,0,1,0, 0,0,0,0,0} ,
             {0,0,0,0,0, 0,0,0,0,1, 0,0,0,1,1, 0,0,0,0,1, 0,0,0,0,0} ,

             {0,0,0,0,0, 0,0,0,0,0, 1,0,0,0,0, 1,1,0,0,0, 1,0,0,0,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,1,0,0,0, 1,1,1,0,0, 0,0,0,0,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,0,1,0,0, 0,1,1,1,0, 0,0,1,0,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,0,0,1,0, 0,0,1,1,1, 0,0,0,1,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1, 0,0,0,1,1, 0,0,0,0,1} ,

             {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 1,0,0,0,0, 1,1,0,0,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 1,1,1,0,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,1,0,0, 0,1,1,1,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,1,0, 0,0,1,1,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1, 0,0,0,0,1} ,

    };

Commons Math:
    public void solve(double[] startState, double[][] input){
        RealMatrix coefficients = new Array2DRowRealMatrix(input, false);
        DecompositionSolver solver = new LUDecomposition(coefficients).getSolver();
        RealVector constants = new ArrayRealVector(startState, false);
        RealVector solution = solver.solve(constants);
    }

This works fine for:
    double[] startState = {1,2,1,2};
    double[][] input = {{1,1,0,0},{1,1,1,0},{0,1,1,1,},{0,0,1,1}};

But fails for:
    double[] startState = { 0,1,2,0,2, 0,2,1,1,0, 0,2,1,2,2, 1,1,1,1,2, 1,2,1,0,0 };
    double[][] input={
             {1,1,0,0,0, 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {1,1,1,0,0, 0,1,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {0,1,1,1,0, 0,0,1,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {0,0,1,1,1, 0,0,0,1,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {0,0,0,1,1, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,

             {1,0,0,0,0, 1,1,0,0,0, 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {0,1,0,0,0, 1,1,1,0,0, 0,1,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {0,0,1,0,0, 0,1,1,1,0, 0,0,1,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {0,0,0,1,0, 0,0,1,1,1, 0,0,0,1,0, 0,0,0,0,0, 0,0,0,0,0} ,
             {0,0,0,0,0, 0,0,0,1,1, 0,0,0,0,1, 0,0,0,0,0, 0,0,0,0,0} ,

             {0,0,0,0,0, 1,0,0,0,0, 1,1,0,0,0, 1,0,0,0,0, 0,0,0,0,0} ,
             {0,0,0,0,0, 0,1,0,0,0, 1,1,1,0,0, 0,1,0,0,0, 0,0,0,0,0} ,
             {0,0,0,0,0, 0,0,1,0,0, 0,1,1,1,0, 0,0,1,0,0, 0,0,0,0,0} ,
             {0,0,0,0,0, 0,0,0,1,0, 0,0,1,1,1, 0,0,0,1,0, 0,0,0,0,0} ,
             {0,0,0,0,0, 0,0,0,0,1, 0,0,0,1,1, 0,0,0,0,1, 0,0,0,0,0} ,

             {0,0,0,0,0, 0,0,0,0,0, 1,0,0,0,0, 1,1,0,0,0, 1,0,0,0,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,1,0,0,0, 1,1,1,0,0, 0,0,0,0,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,0,1,0,0, 0,1,1,1,0, 0,0,1,0,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,0,0,1,0, 0,0,1,1,1, 0,0,0,1,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1, 0,0,0,1,1, 0,0,0,0,1} ,

             {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 1,0,0,0,0, 1,1,0,0,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 1,1,1,0,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,1,0,0, 0,1,1,1,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,1,0, 0,0,1,1,0} ,
             {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1, 0,0,0,0,1} ,

    };

What I mean by "fails" is that, I know there is at least one solution available which has all integer values but my implementation gives me fraction values.


text:
Q: When did user accounts using UIDs above 1000 become normal? And why? We have a really old NIS domain which is mapping some user accounts to UIDs less than 1000. I'm wondering

*

*when did using UIDs greater than or equal to 1000 for human users become 'standard',

*why did it become a convention? Are there any practical implications or reasons for this? (i.e. anything similar like the 'convention' of trusting ports below 1000)

A: According the UNIX and Linux System Administration Handbook (5th Edition) the idea behind starting UIDs at 1000 is to provide plenty of room for nonhuman users that might get added in the future.


text:
Q: Diagonal dashed line in array I would like to have a diagonal dashed line in an array cell. In the example, it should replace \ddot. For me, \ddot is inconvenient since I already use dots with different meaning.
\documentclass{article}

\begin{document}

$$\begin{array}{cccccc}
    +&+&+&&&&\\
    \cdot&\cdot&-\\
    +&+&+&&&&\\
    &&&\ddots&&\\
    &&&&\cdot&+&-\\
    &&&&\cdot&+&-\\
    &&&&\cdot&+&-
\end{array}$$

\end{document}

A: It's possible with nicematrix:
\documentclass{article}
\usepackage{nicematrix}
\usepackage{tikz}

\begin{document}
\[\begin{NiceMatrix}
+&+&+&&&&\\
\cdot&\cdot&-\\
+&+&+&&&&\\
&&&\Ddots[line-style=dashed]&&\\
&&&&\cdot&+&-\\
&&&&\cdot&+&-\\
&&&&\cdot&+&-
\end{NiceMatrix}\]
\end{document}

A: With pstricks and a simpler  matrix environment:  make  the last + in the third row and the first + in the fifth  \rnode and connect them by a dashed line.
\documentclass{article}
\usepackage{amsmath}
\usepackage{pst-node}

\begin{document}

    \[ \begin{matrix}
    +&+&+&&&&\\
    \cdot&\cdot&-\\
    +&+&\rnode{A}{+}&&&&\\
    &&&&&\\
    &&&&\cdot&\rnode{B}{+}&-\\
    &&&&\cdot&+&-\\
    &&&&\cdot&+&-
\end{matrix}
\ncline[linestyle=dashed, linewidth=0.4pt, dash=2.5pt 2.5pt, nodesep=2pt]{A}{B}
 \]%

\end{document}

A: You could use TikZ:
\documentclass{article}
\usepackage{tikz}

\begin{document}
    $$\begin{array}{ccccccc}
    +&+&+&&&&\\
    \cdot&\cdot&-\\
    +&+&+&&&&\\
    &&&\begin{tikzpicture}
        \draw [dashed] (0.0,1.0) -- (1.0,0.0);
        \end{tikzpicture}&&\\
    &&&&\cdot&+&-\\
    &&&&\cdot&+&-\\
    &&&&\cdot&+&-
    \end{array}$$
\end{document}


text:
Q: MegaCLI not seeing RAID card (LSI 9271-4i) I have a server with LSI 9271-4i card and 4 HDDs. One day the server started malfunctioning and it wouldn't list any drive information. I rebooted the server and it never came up, so I have been using IPMI to check what's happening to it.
The server is not booting up due to the hardware RAID throwing errors.
I loaded Debian Live CD, installed MegaCLI but when I list adapters it shows nothing:
/opt/MegaRAID/MegaCli/MegaCli64 -Adpcount

Controller Count: 0.

Exit Code: 0x00

Any other command I try to show adapters, returns blank and the same Exit Code 0x00.
One error message I caught on bootup is:
LSI MegaRAID SAS-MFI BIOS
Version 5.45.07.0 (Build November 12, 2013)
Copyright(c) 2013 LSI Corporation
HA -0 (Bus 5 Dev 0) LSI MegaRAID SAS 9271-4i
FW package: 23.22.0-0012

Cache data was lost due to an unexpected power-off or reboot during a write operation, but the adapter has recovered. This could be due to memory problems, bad battery, or you may not have a battery installed.
Press any key to continue or 'C' o load the configuration utility

# When I pressed 'C' it didn't load anything.

When I run lspci, I can see the card:
$ lspci | grep -i raid
05:00.0 RAID bus controller: LSI Logic / Symbios Logic MegaRAID SAS 2208 [Thunderbolt] (rev 05)

Is there anything I can try to revive this server short of replacing the RAID card or its battery?
Thanks in advance.


text:
Q: Remote connection between two android Devices I am just thinking how a teamviewer kinda application can be developed for the Android devices.
I just want to know the ways of implementing an application through which I can access Another Android device including all the events that happens on the host device(just like TeamViewer for desktop). I know that there is TeamViewer app for Android but I just want to try myself
I heard about some protocols like RDP/VNC but those are for desktop sharing. But is there any protocol for Android device sharing ? (Note: I would like to do it using intenet)
If there is anything wrong in the way I ask please let me know..
Thanks

A: You cannot remote the interface of 3rd party applications running on a secured (what consumers normally have) device.  Such a device does not permit you to capture the screen display of other applications* or to inject touch/key events into them.
If you want to confine your work to unsecured (ie, "rooted") devices, there are a number of open source projects out there, and probably some compiled and ready-to-install apps as well.  And if you only want the android device to be the computer the user holds (and not the one being remote-operated) then that is possible.
(* a few vendors have shipped devices not entirely following Google's recommendations, on which it is possible for an application to grab the screen display, however they still don't permit injecting input events)


text:
Q: JQuery Plugin with 2 Selectors I created a JQuery tooltip plugin which can be used in two ways:

*

*The tooltip content is the title of the HTML anchor;

*The tooltip content is passed as an option;
I would like to have another option:

*

*The entire tooltip markup would be an element in the page.
Let me give an example of what I am looking for:
$("table td.Task a.Menu", "li div.Menu").Tooltip();
So every link Menu under "table td.Task" would fire a tooltip.
The tooltip markup would be the div.Menu under the same LI of the a.Menu
How to change my plugin to also being able to do this? My current code is:
(function ($) {

  $.fn.Tooltip = function (options) {

    var defaults = {
      content: "",
      class: "Tooltip",
      id: "Tooltip"
    };

    var options = $.extend({}, defaults, options);

    var tooltip;

    $(this).each(function () {

      var title = $(this).attr("title");
      if (title == undefined && options.content == "") return;

      $(this).mouseenter(function (e) {

        $(this).removeAttr("title")
        tooltip = "
{content}
"

        var content = options.content == "" ? title : options.content;
        tooltip = tootip.replace("{class}", options.class).replace("{id}", options.id).replace("{content}", content);

        $("body").append(tooltip);
        $("#" + options.id).fadeIn("fast");

      }), // Mouse Enter

      // Mouse Leave, Mouse Down and Mouse Move functions ...

    }
   }

Thank You!

A: Not going to rewrite the whole plugin but could add an option that returns content from page:
var defaults = {
      content: "",
      class: "Tooltip",
      id: "Tooltip",
      contentSource: 'title' /* "title" as default or "html" for in page*/
      htmlSource: function($el){
         /* write whatever traverse returns content wanted*/
         return  $el.siblings('div.foo').html();
      }
    };

Now when you set content check which source
/* should cache $(this) since using it numerous times*/
var $this=$(this)

var content;
if( options.contentSource !='title'){
   content=options.htmlSource($this);
}else{
  content= /* existing code*/
}

Usege:
$("table td.Task a.Menu", "li div.Menu").Tooltip({
      contentSource: 'html',
      htmlSource: function($el){
          return  $el.parent().find('.someClass').html();
      }
});


text:
Q: Cmd Opening a document that is on my desktop but in my language desktop is called\Pracovná plocha) it looks like my problem is with my folder placement.I have a program in python that opens another python file. When I use this command  "os.system("redditapi.py")   (H:\Pracovná plocha\bot\redditapi.py)It looks like it only reads until H:\Pracovná. Because it gives me this error 'H:\Pracovná' is not recognized as an internal or external command,
operable program or batch file. More insight:https://www.reddit.com/r/learnpython/comments/ihtvxb/python_is_not_recognized_as_an_internal_or/?utm_source=share&utm_medium=web2x&context=3. How could I solve this problem. Thank you for your answers.


text:
Q: A code using SharePoint classes doesn't run on systems not having SharePoint installed I have a window application which uses SP classes to create a site. I works fine on a system having Windows Server 2003 R2 with sharepoint installed.
But it doesn't work on a system having XP installed and SharePoint not installed.
The fact is that both of these systems are on a intranet. So I assumed that the NON-SP system would be able to run the code and create a site on the system having SP installed if all the required parameters (like serverLocation, domain, username, password) are provided.
I did copied the DLLs to these NON-SP system and referenced them to build the project:

*

*Microsoft.SharePoint.dll

*microsoft.sharepoint.portal.dll

*Microsoft.SharePoint.Publishing.dll

But this too didn't worked.

*

*What am I missing?

*Is my assumption wrong?

A: Yes, your assumption is wrong. The SharePoint server side API is only valid when run from a machine on the SharePoint farm. Access from client machines must be funneled through the web services layer.

A: That's wierd assuming that it would work. Microsoft.SharePoint.dll internally refers to dozen libraries and depends on files installed with sharepoint and database, created when installing SharePoint.
Edit: Ohh, i understood - you wanted to access server from other machine with object model. As mentioned, you can't. But you can use SharePoint web services to interact with sharepoint.
SharePoint 2010 also intredouces client object model that will allow you limited interaction with sharepoint from clientmachine from object model.

A: You need to install Visual studio extension for windows SharePoint services in your development system. You can download it from
http://www.microsoft.com/downloads/en/confirmation.aspx?familyId=7bf65b28-06e2-4e87-9bad-086e32185e68&displayLang=en
If you try to install the Visual Studio 2005 Extensions for Windows SharePoint Services 3.0 Tools (VSeWSS) on a workstation,It would probably fail and throw the following error:
This product can only be installed if Windows SharePoint Services 3.0 has been installed first.
SharePoint 2007 or MOSS  is a server product and as such it can only be installed on the Windows Server family platform and it can't be installed in windows XP or vista. There is a work around to solve this issue. Simply do the following registry setting.
Click Start -> Run -> regedit and click OK.
 Expand HKEY_LOCAL_MACHINE, expand SOFTWARE, expand Microsoft, expand Shared Tools.
 Right click Web server extension, click new. Then click key, type 12.0
 Right click 12.0 click new, click string value and type Sharepoint
 Right click sharepoint, click modify, Type Installed in value data field.


text:
Q: strange compilation error about pthreadtypes.h: 'section' attribute I met a very strange error during compile my code using clang.
here is my command
$clang -c -emit-llvm -I/OP-TEE/op-tee-os/optee_os/lib/libutee/include/ -I/OP-TEE/op-tee-os/optee_os/lib/libutils/ext/include/ test_function_call_ta.c

and here is the error:
In file included from /usr/include/stdlib.h:314:
In file included from /usr/include/x86_64-linux-gnu/sys/types.h:270:
/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h:200:5: error: 'section' attribute only applies to functions, methods,
      properties, and global variables
  } __data;
    ^
/opensource_projects/OP-TEE/op-tee-os/optee_os/lib/libutils/ext/include/compiler.h:51:17: note: expanded
      from macro '__data'
#define __data          __section(".data")
                        ^
/opensource_projects/OP-TEE/op-tee-os/optee_os/lib/libutils/ext/include/compiler.h:50:37: note: expanded
      from macro '__section'
#define __section(x)    __attribute__((section(x)))

I was wondering why this error is happening, because I did not use any section attributes in the source code.
Thanks in advance!

A: Finally, I fixed this issue. The reason is that I import a wrong header file by "-I". The correct one should in another folder...


text:
Q: Group Time Series Is there a way to group time series on all the dates every 30 minutes or x minutes. My question is very similar to this one. If I wanted to group by hours in a date, I would just need
data=pd.DataFrame({'Values':  1,'Date':pd.date_range('01-01-2017',periods=3600,freq='T')})
data.set_index(['Date'],inplace=True)
grouped=data.groupby(data.index.hour)

Running a for-loop and printing the last group give me:
for time,group in grouped:
    print(group)
                     Values
Date
2017-01-01 23:00:00       1
2017-01-01 23:01:00       1
2017-01-01 23:02:00       1
2017-01-01 23:03:00       1
2017-01-01 23:04:00       1
2017-01-01 23:05:00       1
2017-01-01 23:06:00       1
2017-01-01 23:07:00       1
2017-01-01 23:08:00       1
2017-01-01 23:09:00       1
2017-01-01 23:10:00       1
2017-01-01 23:11:00       1
2017-01-01 23:12:00       1
2017-01-01 23:13:00       1
2017-01-01 23:14:00       1
2017-01-01 23:15:00       1
2017-01-01 23:16:00       1
2017-01-01 23:17:00       1
2017-01-01 23:18:00       1
2017-01-01 23:19:00       1
2017-01-01 23:20:00       1
2017-01-01 23:21:00       1
2017-01-01 23:22:00       1
2017-01-01 23:23:00       1
2017-01-01 23:24:00       1
2017-01-01 23:25:00       1
2017-01-01 23:26:00       1
2017-01-01 23:27:00       1
2017-01-01 23:28:00       1
2017-01-01 23:29:00       1
                    ...
2017-01-02 23:30:00       1
2017-01-02 23:31:00       1
2017-01-02 23:32:00       1
2017-01-02 23:33:00       1
2017-01-02 23:34:00       1
2017-01-02 23:35:00       1
2017-01-02 23:36:00       1
2017-01-02 23:37:00       1
2017-01-02 23:38:00       1
2017-01-02 23:39:00       1
2017-01-02 23:40:00       1
2017-01-02 23:41:00       1
2017-01-02 23:42:00       1
2017-01-02 23:43:00       1
2017-01-02 23:44:00       1
2017-01-02 23:45:00       1
2017-01-02 23:46:00       1
2017-01-02 23:47:00       1
2017-01-02 23:48:00       1
2017-01-02 23:49:00       1
2017-01-02 23:50:00       1
2017-01-02 23:51:00       1
2017-01-02 23:52:00       1
2017-01-02 23:53:00       1
2017-01-02 23:54:00       1
2017-01-02 23:55:00       1
2017-01-02 23:56:00       1
2017-01-02 23:57:00       1
2017-01-02 23:58:00       1
2017-01-02 23:59:00       1

But there is no times.30min command.
EDIT:
I am trying to group every thirty minutes for all the dates. I want the output exactly like the above command but for an x minutes. The default grouped = df.groupby(pd.TimeGrouper('30T')) does not work, because it groups the dates individually. So if I have minute timestamps of dates say 2017-01-01 and 2017-01-02, pd.TimeGrouper('30T'), splits up 0:00-0:30 2017-01-01 and 0:00-0:30 2017-01-02 into seperate groups. I would like them combined.

A: Use pd.TimeGrouper
grouped = df.groupby(pd.TimeGrouper('30T'))

Demo
tidx = pd.date_range('2017-03-01', periods=240, freq='T')

df = pd.DataFrame(np.random.randint(10, size=(len(tidx), 3)), tidx, list('ABC'))

df.groupby(pd.TimeGrouper('30T')).sum()

                       A    B    C
2017-03-01 00:00:00  134  115  145
2017-03-01 00:30:00  139  113  130
2017-03-01 01:00:00  159  123  147
2017-03-01 01:30:00  115  143  156
2017-03-01 02:00:00  144  145  134
2017-03-01 02:30:00  142  143  166
2017-03-01 03:00:00  152  154  130
2017-03-01 03:30:00  121  121  170

A: Okay, I think I you want to do this instead:
data=pd.DataFrame({'Values':  1,'Date':pd.date_range('01-01-2017',periods=3600,freq='T')})
data.set_index(['Date'],inplace=True)

g = data.groupby([data.index.hour, data.index.minute // 15])
#this will group the each day in 15-minute intervals for all dates.
for n,g in grouped:
    print(g)

Output:
                    Values
Date
2017-01-01 00:00:00       1
2017-01-01 00:01:00       1
2017-01-01 00:02:00       1
2017-01-01 00:03:00       1
2017-01-01 00:04:00       1
2017-01-01 00:05:00       1
2017-01-01 00:06:00       1
2017-01-01 00:07:00       1
2017-01-01 00:08:00       1
2017-01-01 00:09:00       1
2017-01-01 00:10:00       1
2017-01-01 00:11:00       1
2017-01-01 00:12:00       1
2017-01-01 00:13:00       1
2017-01-01 00:14:00       1
2017-01-02 00:00:00       1
2017-01-02 00:01:00       1
2017-01-02 00:02:00       1
2017-01-02 00:03:00       1
2017-01-02 00:04:00       1
2017-01-02 00:05:00       1
2017-01-02 00:06:00       1
2017-01-02 00:07:00       1
2017-01-02 00:08:00       1
2017-01-02 00:09:00       1
2017-01-02 00:10:00       1
2017-01-02 00:11:00       1
2017-01-02 00:12:00       1
2017-01-02 00:13:00       1
2017-01-02 00:14:00       1

You can use pd.Grouper or resample.  (Note: pd.TimeGrouper has no advantages over pd.Grouper.)
Method 1 use pd.Grouper:
df = pd.DataFrame({'Values':  1,'Date':pd.date_range('01-01-2017',periods=3600,freq='T')})

df.groupby(pd.Grouper(freq='15T',key='Date')).sum()

Output:
                     Values
Date
2017-01-01 00:00:00      15
2017-01-01 00:15:00      15
2017-01-01 00:30:00      15
2017-01-01 00:45:00      15
2017-01-01 01:00:00      15

Method 2 use resample:
df.resample('15T', on='Date').sum()

Output:
                     Values
Date
2017-01-01 00:00:00      15
2017-01-01 00:15:00      15
2017-01-01 00:30:00      15
2017-01-01 00:45:00      15
2017-01-01 01:00:00      15

Alternatively to both methods if your date is in the index as a datetime dtype, then you have a DatetimeIndex, you need to omit the key and on paramaters in Method 1 and Method 2, respectively.


text:
Q: Host file redirect for download another file I edited my host file like this.
example.com/abc/a.zip example.com/abc/b.ziP

So what I need to do is when I enter example.com/abc/a.zip url in browser it should be redirected to example.com/abc/b.zip. But that doesn't work. So where is the fault?
And are there any other ways to do this?

A: Remapping URL
If you want to remap url to a different location, but clients still access and know original url, you should use RewriteRule directive.
Try to add this lines in VirtualHost section:
  RewriteEngine on
  RewriteRule ^/abc/a\.zip$ /abc/b.ziP [PT]

Here is RewriteRule syntax:
  RewriteRule Pattern Substitution [flags]

where, according to apache mod_rewrite manual:
  Pattern: In VirtualHost context, The Pattern will initially be matched
       against the part of the URL after the hostname and port, and
       before the query string (e.g. "/app1/index.html").
  Substitution: A DocumentRoot-relative path to the resource to be served.
       Note that mod_rewrite tries to guess whether you have specified a
       file-system path or a URL-path by checking to see if the first
       segment of the path exists at the root of the file-system.
       For example, if you specify a Substitution string of
       /www/file.html, then this will be treated as a URL-path unless
       a directory named www exists at the root or your file-system
       (or, in the case of using rewrites in a .htaccess file, relative
       to your document root), in which case it will be treated as a
       file-system path.
       If you wish other URL-mapping directives (such as Alias) to be
       applied to the resulting URL-path, use the [PT] flag as described below.
  flag: special action

In this case flag value is PT tha means:
  passthrough|PT    Forces the resulting URI to be passed back to the URL
      mapping engine for processing of other URI-to-filename translators,
      such as Alias or Redirect. details ...

Here is useful link with examples.
There is Alias directive that remap content location too. This one is useful if content location is outside of DocumentRoot.
Redirect request
If you want to inform the client that the requested content is located at a different URL, and instruct the client to make a new request with the new URL, you should use Redirect directive.
try adding this line in VirtualHost section:
  Redirect permanent /abc/a.zip http://example.com/abc/b.ziP

This is useful to inform robot that contents are moved in other location, and prevent errors of indexing in search engines.

A: For simple redirects, the RewriteEngine is overkill. Just add this to your site definition:
Redirect /abc/a.zip http://example.com/abc/b.zip

See the example in the Apache documentation.


text:
Q: How to make App_Data folder up to date in ASP.NET MVC 5 I'm working on an ASP.NET MVC 5 project, I had 4 different contexts, each one in a separate file, then I changed my plan and decided to create one file containing the 4 contexts.
When I did so, the App_Data folder still has the 4 previous contexts (files) with the extension .mdf, although I used migrations and brought my database up to data.
The second issue is that when I run any view I get a 404 error

The resource cannot be found

although I updated all contexts in all controllers and recreated the views.
Here is my connection string:
<connectionStrings>
    <add name="HotelString"
         connectionString="Data Source=(localDb)\MSSQLLocalDb;Initial Catalog=HotelDb;Integrated Security=true"
         providerName="System.Data.SqlClient" />
</connectionStrings>

and context is:
namespace HIMS.Context
{
    public class ModelsContext : DbContext
    {
        public DbSet<Reservation> reservations { get; set; }
        public DbSet<CEO> ceo { get; set; }
        public DbSet<ControlPanel> controlPanels { get; set; }
        public DbSet<UserAccount> userAccount { get; set; }

        public ModelsContext() : base("Name=HotelString") { }
    }
}

Any suggestions how to resolve those issues would be appreciated.

A: the issue has been solved , i had to delete all controllers and recreate them.


text:
Q: Django 2 Настройка системы комментариев Проблема следующая: когда я добавляю новый комментарий под публикацией на своем сайте, он отображается нормально, но если вдруг зажать какую-либо клавишу или написать очень длинное слово, то текст не переносится, а выходит за пределы полей. Как с этим бороться?

A: Только причём тут django?
Добавьте текстовому полю css свойство overflow-wrap: break-word;, которое отлично воспринимают все браузеры.


text:
Q: find $z$ that satisfies $z^2=3+4i$ Super basic question but some reason either I'm not doing this right or something is wrong.
The best route usually with these questions is to transform $3+4i$ to $re^{it}$ representation.
Ok, so $r^2=3^2+4^2 = 25$, so $r=5$. And $\frac{4}{3}=\tan(t)$ so that means $t \approx 0.3217$ and I'm not going to get an exact answer like that.
Another method would be to solve quadratic formula $z^2-3-4i=0$ that means $z_0=\frac{\sqrt{12+16i}}{2}$ and $z_1=\frac{-\sqrt{12+16i}}{2}$
But now I have the same problem, $12+16i$ doesn't have a "pretty" polar representation so its difficult to find $\sqrt{12+16i}$
I want to find an exact solution, not approximate, and it should be easy since the answers are $2+i$ and $-2-i$
Edit:
Also, something else is weird here. I know that if $z_0$ is some root of a polynomial then it's conjugate is also a root.but $2+i$ and $-2-i$ are not conjugates.

A: Hint:
$$z^2=3+4i=5e^{it+2k\pi i}\;,\;\;k\in\Bbb Z\;,\;\;t=\arctan\frac43\implies$$
$$z=\sqrt[2]5e^{\frac{it+2k\pi i}2}\;,\;\;k=0,1\;\;\text{(Why it is enough to take only these vales of}\;\;k\;?)$$
A more basic approach: put$\;z=a+bi\;,\;\;a,b\in\Bbb R\;$ , so that
$$3+4i=(a+bi)^2=(a^2-b^2)+2abi\implies\begin{cases}a^2-b^2=3\\{}\\2ab=4\implies b=\frac2a\end{cases}\;\;\implies$$
$$a^2-\frac4{a^2}=3\implies 0=a^4-3a^2-4=(a^2-4)(a^2+1)\implies a=\pm2$$
and thus
$$\;b=\pm\frac22=\pm1\;\implies a+bi=\begin{cases}\;\;\;2+i\\{}\\-2-i\end{cases}$$

A: This can be computed by a Simple Square Root Denesting Rule:
$\ 3+4\sqrt{-1}\ $ has norm $= 25.\:$ $\rm\ \color{blue}{subtracting\ out}\,\ \sqrt{norm}\ = -5\,\ $ yields $\,\  8+4\sqrt{-1}\:$
which has $\, {\rm\ \sqrt{trace}}\, =\, \sqrt{16}\, =\, 4.\ \  \rm \color{brown}{Dividing\ it\ out}\ $ of the above  yields $\ \ 2+\sqrt{-1}$
Remark $\ $ Many more worked examples are in prior posts on this denesting rule.

A: $$
z^2=3+4i\\
(a+bi)^2=3+4i,\;\;\;\;a,b\in\mathbb{R}\\
a^2+2abi-b^2=3+4i
$$
Now you have a system of equations:
$$
a^2-b^2=3\tag{1}
$$
$$
2ab=4\tag{2}
$$
$$
b=\dfrac2a
$$
Substitute $b$ in $(1)$:
$$a^2-\dfrac4{a^2}=3$$
Now let $t=a^2$, then
$$
t^2-3a-4=0\\
t=\dfrac{3\pm\sqrt{9+16}}{2}
$$
which have solutions $t_1=4$ and $t_2=-1$. Notice that $t_2$ cannot be solution, so only solution is
$$
t=4\\
a^2=4\\
a=\pm2
$$
So, we have solutions $a=2,b=1$ and $a=-2,b=-1$. Solutions of $z$ are
$$z=2+i\;\;\;\;\text{or}\;\;\;\;z=-2-i$$

A: We can use the double angle formula to find the components of $z$:
$$ \cos \theta = \pm \sqrt{\frac{1 + \cos 2\theta}{2}}$$
$$ \sin \theta = \pm \sqrt{\frac{1 - \cos 2\theta}{2}}$$
Here $\theta$ is the argument of $z$ and $2\theta$ the argument of $z^2$.
We know $ \cos 2\theta = \frac{3}{5}$ so $\cos \theta = \pm \sqrt{\frac{4}{5}}$ and $\sin \theta = \pm\sqrt{\frac{1}{5}}$. Since $z^2$ lies on the first quadrant (between $0$ and $\pi/2$), its two square roots must lie on the first and third quadrants, respectively, therefore the final answer is
$$ z_1 = \sqrt{5} \left( \sqrt{\frac{4}{5}} + i\sqrt{\frac{1}{5}} \right) = 2 + i $$
$$ z_2 = -z_1 = -2 - i $$
Alternatively: Since the numbers are relatively simple, we can let $z = x + yi$. Then
$$ z^2 = (x^2 - y^2) + 2xyi = 3 + 4i $$
Now equate the real and imaginary part to get this system of equations:
$$ x^2 - y^2 = 3 $$
$$ 2xy = 4 $$


text:
Q: Node JS code not running in order I have no idea why the code do not run as I expected.
When the UserExist is called, it should either console.log one of the statements that I set in my function code.
But the result is like the following the picture. Apreciate that if somebody can help!!
Console
var sql = require('mssql');
var config = require('./configuration/sqlconfig');

var Username = "Testing";

sql.connect(config);
console.log("Connected to DB");

if (!UserExist(Username)) {
    InsertNewRecord(Username);
}

function isEmptyObject(obj) {
    return !Object.keys(obj).length;
}

// This should work both there and elsewhere.
function isEmptyObject(obj) {
    for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            return false;
        }
    }
    return true;
}

function UserExist(Username) {
        console.log('Checking whether user exists or not... ');
        new sql.Request().query("SELECT * FROM dbo.DB_Users WHERE Username =     '" + Username + "';")
        .then(function (recordset) {
            if (isEmptyObject(recordset)) {
                console.log("The User does not exist, ready to insert");
                return true;
            } else {
                console.log("The user is existed already.");
                return false;
            }
        }).catch(function (err) {
            //When errors come
        });
}

function InsertNewRecord(Username) {
    console.log('Attempting to Insert records...');
    new sql.Request().query("INSERT INTO dbo.Embright_Users (Username) VALUES ('" + Username + "');");
    console.log("Added one new record");
}

A: The callbacks are not chained correctly. The InsertNewRecord() should be passed as callback to UserExist() function to make sure the execute in sequence. eg:
// Calling UserExist with a callback instead of 'if' statement
UserExist(Username, InsertNewRecord)

function UserExist(Username, callback) {
    console.log('Checking whether user exists or not... ');
    new sql.Request().query("SELECT * FROM dbo.DB_Users WHERE Username =     '" + Username + "';")
    .then(function (recordset) {
        if (isEmptyObject(recordset)) {
            console.log("The User does not exist, ready to insert");
            // Calling InsertNewRecord with the username passed
            callback(Username);
        } else {
            console.log("The user is existed already.");
           // Do nothing
        }
    }).catch(function (err) {
        //When errors come
    });
}


text:
Q: How i can update junction table automatically and access data from junction table? Now I have 2 tables: demo(detailed information about users) and users(login and password), then I create a junction table(ID, demo_ID and user_ID).
The system working like this:

*

*User register

*User login

*User fill form where he gave a detailed information

And I want to fill junction table automatically with user_ID and demo_ID where user_ID will LOGGED USER and demo_ID the information of exactly this user.
How can I do this? Please help me =)

A: You can use query like -
INSERT INTO rel_users_demo (demo_ID,users_ID) SELECT demo.ID, users.ID join on demo.EMail = users.email
You have not mentioned which column you have in common(foreign key) between demo and users. you can keep your column at place of xx and yy.


text:
Q: GDBM sequential access: bug? I implemented the following GBDM example:
#include <boost/lexical_cast.hpp>
#include <gdbm.h>
#include <iostream>
#include <string>
#include <string.h>

struct record
{
    int a;
    int b;
};

int main(int argc, char* argv[])
{
    GDBM_FILE db;

    db = gdbm_open("gdbm.db", 512, GDBM_WRCREAT | GDBM_NOLOCK | GDBM_SYNC, 0664, NULL);

    datum lekey;
    datum levalue;
    for (int i = 0; i < 10; ++i) {
        record r;
        r.a = i;
        r.b = i + 1;
        lekey.dptr = (char*) boost::lexical_cast<std::string>(i).c_str();
        lekey.dsize = strlen(lekey.dptr) + 1;
        levalue.dptr = (char*) &r;
        levalue.dsize = sizeof(record);
        gdbm_store(db, lekey, levalue, GDBM_INSERT);
    }
    gdbm_sync(db);

    for(lekey = gdbm_firstkey(db);
        lekey.dptr != NULL;
        lekey = gdbm_nextkey(db, lekey)) {
        levalue = gdbm_fetch(db, lekey);
        record* r = (record*) levalue.dptr;
        if (r) {
            std::cout << lekey.dptr << " " << r->a << " " << r->b << std::endl;
            free(levalue.dptr);
        }
    }

    gdbm_close(db);

    return 0;
}

The output is the following:
$ ./gdbm_example
3 3 4
6 6 7
2 2 3
9 9 10
5 5 6
1 1 2
8 8 9
4 4 5

Why would 0 0 1 and 7 7 8 be left out? Is this a bug or am I doing something wrong?

A: Joachim is right, using boost::lexical_cast is out of place here. Rewrite your example using this:
std::string s;
std::stringstream str;
str << i;
s = str.str();
lekey.dptr = (char*) s.c_str();

and it will work as expected.

A: A problem might be this line:
lekey.dptr = (char*) boost::lexical_cast<std::string>(i).c_str();

This stores the pointer to a temporary variable, and so is undefined behavior.
The key doesn't have to be a string, it can as well be a number, so you can use e.g.:
lekey.dptr = &i;
lekey.dsize = sizeof(i);


text:
Q: Showing $\lim_{n\to\infty}\int_{\mathbb{R}} f(x)f(x+n) dx=0$ Problem
Let $f(x)\in L^2(-\infty,\infty)$. Prove that
$$
\lim_{n\to\infty}\int_{-\infty}^\infty f(x)f(x+n) dx=0.
$$
My attempt
Let $N\in\mathbb{N}$ and $f_N(x):=f(x)\chi_{[-N,N]}(x)$.
For any $n\in\mathbb{N}$, consider
$$
\begin{split}
\int_{-\infty}^\infty f(x)f_N(x+n)dx&=\int_{-\infty}^\infty f(x)f(x+n)\chi_{[-N,N]}(x+n)dx\\
&=\int_{-\infty}^\infty f(x)f(x+n)\chi_{[-N-n,N-n]}(x)dx\\
&=\int_{-N-n}^{N-n}f(x)f(x+n)dx
\end{split}
$$
This is where I get stuck.
We know for a.e. $x\in\mathbb{R}$ that $\lim_{n\to\infty} f(x+n)=0$. Thus, if I were allowed to interchange limit and integral, I would get the desired conclusion. I tried Dominated Convergence Theorem, but could not find a way to dominate the integrand by an integrable function not depending on $n$.
Maybe there is a different approach. Any hints? I'd like to be able to say the absolute value of the above integral is less than any $\varepsilon>0$ for $n$ large enough, and then since $N$ is arbitrary, the conclusion follows.

A: Hint: There exists a continuous function $g$ with compact support such that $ \|f-g\|_2 <\epsilon$. $\int g(x)g(x+n)=0$ for $n$ sufficiently large and $|\int f(x)f(x+n)-\int g(x)g(x+n)| <\epsilon ( \|f\|_2+ \|g\|_2)$ by Holder's inequlaity.
A simpler proof: (continuity of $g$ is not required to we can simplify the proof as follows:)
Let $g(x)=f(x)$ for $|x| \leq N$ and $0$ for $|x| >N$. Observe that $ g(x)g(x+n)=0$ for all $x$ if $n >2N$ and that $\int |f-g|^{2} \to 0$ as $N \to \infty$. . Hence $\int g(x)g(x+n)dx=0$ fo $n >2N$. Now $$\int f(x)f(x+n) -\int g(x)g(x+n)$$ $$=\int f(x)f(x+n) -\int g(x)f(x+n)+\int g(x)f(x+n) -\int g(x)g(x+n).$$ Use Holder's inequality to show that this quantity tends to $0$ as $N \to \infty$.

A: Pick $\epsilon\gt0$. Find $n$ so that
$$
\int_{|x|\ge n/2}f(x)^2\,\mathrm{d}x\le\frac{\epsilon^2}{4\|f\|_2^2}\tag1
$$
Then
$$
\begin{align}
&\int_{-\infty}^\infty|f(x)|\,|f(x+n)|\,\mathrm{d}x\\
&=\int_{-\infty}^{-n/2}\color{#090}{|f(x)|}\,\color{#E80}{|f(x+n)|}\,\mathrm{d}x+\int_{-n/2}^\infty\color{#C00}{|f(x)|}\,\color{#00F}{|f(x+n)|}\,\mathrm{d}x\tag2\\
&\le\color{#090}{\left(\int_{-\infty}^{-n/2}f(x)^2\,\mathrm{d}x\right)^{1/2}}\color{#E80}{\left(\int_{-\infty}^{-n/2}f(x+n)^2\,\mathrm{d}x\right)^{1/2}}\\
&+\color{#C00}{\left(\int_{-n/2}^\infty f(x)^2\,\mathrm{d}x\right)^{1/2}}\color{#00F}{\left(\int_{-n/2}^\infty f(x+n)^2\,\mathrm{d}x\right)^{1/2}}\tag3\\
&=\color{#090}{\left(\int_{-\infty}^{-n/2}f(x)^2\,\mathrm{d}x\right)^{1/2}}\color{#E80}{\left(\int_{-\infty}^{n/2}f(x)^2\,\mathrm{d}x\right)^{1/2}}\\
&+\color{#C00}{\left(\int_{-n/2}^\infty f(x)^2\,\mathrm{d}x\right)^{1/2}}\color{#00F}{\left(\int_{n/2}^\infty f(x)^2\,\mathrm{d}x\right)^{1/2}}\tag4\\
&\le\color{#090}{\frac\epsilon{2\|f\|_2}}\color{#E80}{\|f\|_2}+\color{#C00}{\|f\|_2}\color{#00F}{\frac\epsilon{2\|f\|_2}}\tag5\\[6pt]
&=\epsilon\tag6
\end{align}
$$
Explanation:
$(2)$: break the domain of integration at $-n/2$
$(3)$: Cauchy-Schwarz (twice)
$(4)$: substitute $x\mapsto x-n$ in the orange and blue integrals
$(5)$: apply $(1)$ to the green and blue integrals
$(6)$: simplify

A: In your attempt, try $\int \Big(f(x)\mathbb{1}_{[-N,N]}(x)\Big)\Big(f(x+n)\mathbb{1}_{[-N,N]}(x+n)\Big)\,dx$
Notice that for all $n$ large enough, $\mathbb{1}_{[-N,N]}\mathbb{1}_{[-N-n,N-n]}=0$
This in a way is similar to the suggestion by Prof. Rama Murthy since
$\|f\mathbb{1}_N-f\|_2\xrightarrow{N\rightarrow\infty}0$
Thus setting $f_N=f\mathbb{1}_N$ and $\tau_{-n}f=f(\cdot+n)$ for all $f\in L_2$, and using translation invariance of Lebesgue's measure ($\|\tau_{-n}f\|_2=\|f\|_2$ for all $n$), $\|f_N\|_2\leq\|f\|_2$ for ll $N$, and Cauchy-Schwartz inequality, we obtain
\begin{aligned}
\|f\,\tau_{-n}f\|_2&\leq\|f\,\tau_{-n}f-f_N\,\tau_{-n}f_N\|_2+\|f_N\,\tau_{-n}f_N\|_2\\
&\leq\|f-f_N\|_2\|\tau_{-n}f\|_2+ \|f_N\|\|\tau_{-n}f-\tau_{-n}f_N\|_2+\|f_N\,\tau_{-n}f_N\|_2\\
&\leq2\|f-f_N\|_2\|f\|_2 + \|f_N\,\tau_{-n}f_N\|_2\
\end{aligned}
The rest should be straight forward.

For similar proof, if you are aware of the fact that $\mathcal{C}_{00}(\mathbb{R})$ is dense in $L_2$, you may show the result holds  for continuous functions of compact support.


text:
Q: Could not able to get the text of elements. I want to use the dynamic xpath here to get the text of the header elements Here is the HTML. I want to use the dynamic xpath here to get the text of the header elements.

TUTORIALS

hElements = "//div[@class='w3-bar w3-theme w3-card-2 w3-wide notranslate']//a"
#is my xpath fetches all the header elements
hElementsSize = len(browser.driver.find_elements_by_xpath(hElements))
#fetches the size of the header elements
print("Total Header Elements:", hElementsSize)
hElementsText = browser.driver.find_element_by_xpath(hElements).text
print(hElementsText)
#i'm not able to get the text of the header elements

A: The way you are expecting text using browser.driver.find_element_by_xpath will return first element's text which is empty as i can see in HTML shared by You. findElement locates the first element in the DOM in case multiple elements are there.
Need to use find_elements and loop through to check expected one
hElements = "//div[@class='w3-bar w3-theme w3-card-2 w3-wide notranslate']//a"
listOfElement = driver.find_elements_by_xpath(hElements)
print("Total Header Elements:", len(listOfElement))

for element in listOfElement:
    print(element.text)

A: If you want to return them all, assuming your xpath is correct, you would have to use find_elements_by_xpath. Then it returns a list of all the elements it found.
hElementsText = browser.driver.find_elements_by_xpath(hElements)
for el in hElementsText:
    print(el.text)

A: The desired element is a JavaScript enabled element, so to retrieve the text from the element you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

*

*Using CSS_SELECTOR and get_attribute() method:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.w3-bar.w3-theme.w3-card-2.w3-wide.notranslate a#navbtn_tutorials"))).get_attribute("innerHTML"))

*Using XPATH and text attribute:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='w3-bar w3-theme w3-card-2 w3-wide notranslate']//a[@id='navbtn_tutorials']"))).text)

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


text:
Q: Visual Studio 2013 SSDT - Support for SQL Server 2008 R2? I have a question for someone out there who has Visual Studio 2013 - SSDT installed... I know that we cannot deploy SSIS packages to a SQL Server version less than 2014, what about SSRS reports? Everyone on my team except the database guys have been using VS2013 for some time now. I want to upgrade too!!! If I convinced the business to upgrade the SSIS servers to 2014, we would still need to support SSRS reports in 2008R2 (because of SharePoint 2010). Arggg... Leave it to Microsoft to leave the database developers behind (again). A new version of Visual Studio is out for preview and I don't want to be two versions behind.
Can someone please check to see if you can deploy an SSRS report to a 2008 R2 server using Visual Studio 2013? I know it's a long shot. Otherwise, I'll have to go through the massive 2013 install just to have my dreams crushed when it doesn't work out..
Thanks All!

A: SSDT-BI 2014 for VS 2013 can support SSRS 2008 R2. It just can't support SSIS 2008R2. Please see the blog below:
http://blogs.msdn.com/b/analysisservices/archive/2014/04/03/sql-server-data-tools-business-intelligence-for-visual-studio-2013-ssdt-bi.aspx


text:
Q: Efficient pattern for access the latest data in many-to-many relationship? I have two objects with MTM relationship
User
------------
id
name

Location
------------
id
latitude
longitude
date_created

userlocation
------------
id
fk_user_id
fk_location_id

When accessing the data, I usually just need to know the latest location associated with a user but I do want to store all of user's previous locations. The write to read ratio is about 1:10
I believe this is a pretty common persistence pattern, I wonder what's the most standard way to approach it? Is it to do a JOIN and form a new View?

A: The pattern would be JOIN table userlocation on itself:
SELECT t1.*
    FROM userlocation AS t1
    LEFT JOIN userlocation AS t2 ON t1.fk_user_id = t2.fk_user_id AND t1.fk_location_id = t2.fk_location_id AND t1.id> t2.id
WHERE
    t2.id IS null

Basically what happens there is that you try to join to every row in table userlocation another row from the same table but with smaller key. If it is not first record for fk_user_id/fk_location_id combination than there will be some other record inserted with smaller key. If it is smallest key in group than jointed column will return NULL as there are no previous keys.
At this stage you just filter out rows from first table where expected column with smaller key in NULL. Having this you can easily join needed information on particular user or location to extend query as you need it.

A: I think your question is already answered here: SQL join: selecting the last records in a one-to-many relationship
There are attendant issues with that approach as the userlocation table gets very large.
But personally, I would have approached it by creating an extra column in User called last_userlocation_id that will be set to the value of id (autoincrement) when a new row is added to userlocation (during the WRITE)
If you do that then your SQL for READ is greatly simplified to:
SELECT User.name, Location.latitude, Location.longitude FROM
User
LEFT JOIN userlocation ON userlocation.id = User.last_userlocation_id
LEFT JOIN Location ON Location.id = userlocation.fk_location_id

The reason for using a LEFT JOIN instead of an INNER JOIN is to cater for Users that don't have any recorded location yet. In that case latitude, and longitude will be NULL


text:
Q: Elastic Beanstalk Custom CloudWatch Logs I have an Elastic Beanstalk Environment on AWS where I deploy via Docker container. I've enabled the default logs from the UI Configuration of Beanstalk and we get standard logs such as eb-activity.log in CloudWatch.
My goal is to integrate the custom logfile: logger.log into CloudWatch.
Dockerrun.aws.json looks like this:
{
  "AWSEBDockerrunVersion": "1",
  "Ports": [
    {
      "ContainerPort": "3000"
    }
  ],
  "Logging": "/path/to/logs"
}

Then in .ebextensions/01_cloudwatch.config I have
files:
  /etc/awslogs/config/my_app_log.conf:
    content: |
        [/var/log/eb-docker/containers/eb-current-app/logger.log]
        log_group_name=/aws/elasticbeanstalk/appname/var/log/eb-docker/containers/eb-current-app/logger.log
        log_stream_name={instance_id}
        file=/var/log/eb-docker/containers/eb-current-app/logger.log
    group: root
    mode: "000600"
    owner: root

The eb-user has full permissions of CloudWatch (CloudWatchFullAccess and CloudWatchLogsFullAccess). Also, I can validate the existence of /var/log/eb-docker/containers/eb-current-app/logger.log.
Still, logs don't appear in CloudWatch. In the same directory there are afc818177506-stdouterr.log files that appear in CloudWatch, they're being configured in /etc/awslogs/config/beanstalklogs.conf. Moreover, I made sure to do sudo service awslogs restart.
Any idea how to debug the problem or do you see any obvious mistake I did so logger.log does not appear in CloudWatch? Many thanks!
PS. I've already looked at the similar questions and have tried a good amount of time to solve the issue without success, so your help is needed.

A: According to the Cloudwatch agent FAQ at the bottom of this reference, these are common reasons log events are not sent:

*

*size of log event is > 256K

*timestamp of log entries is off (>2 hours in future or >2 weeks in past) - perhaps clear your log file if you have a stale logger.log

*log events older than the retention period

*large log batches spanning more than 24hr

Lastly - to troubleshoot why cloudwatch log agent might be failing, check
/var/log/awslogs.log
and to troubleshoot the agent was installed correctly on the EC2 instance, check /var/log/awslogs-agent-setup.log
See if any of these tips help, and post back if you are still stuck with more information and we will continue to try and help you.


text:
Q: Probability of repeated sampling from random draws with replacement I am sampling 552025 patients from a population of 647117 patients. If this sampling is done with replacement, please can someone help tell me :
1) what is the probability that there is any occurrence of repeated sampling of patients?
2) the number of repeated patients from the 552025 sampled patients?
I do sincerely apologise if this question has been covered elsewhere. There are several questions that have a similar title to mine, but, entering the posts, they do not seem to cover the same topic in the body text per se.
I would be grateful for the mathematical solutions and/or formulae to approach the problem generally.
Thank you.
Kareem

A: Suppose, more generally, that you have $N$ people in total and wish to sample $m$ with replacement?  What is the expected number of distinct people sampled more than once?
Let $X_i$ denote the indicator variable for the $i^{th}$ person.  Thus $X_i=1$ if that person is sampled more than once, and $X_i=0$ otherwise.  By Linearity of Expectation, the answer we want, $E=E[N,m]$, is given by the sum $E=\sum_{i=1}^NE[X_i]$.  Of course $E[X_i]$ is just the probability that the $i^{th}$ person is sampled at least twice.  To compute that, we compute the probability that this person is never sampled or sampled exactly once.
Never sampled:  $\left( \frac {N-1}N \right)^m$.
Sampled exactly once:  $m\times \frac 1N \times \left( \frac {N-1}N \right)^{m-1}$
The probability that the person is sampled at least twice is, of course, just $1$ less the sum of those two values.
Thus $$E[N,m]=m\times \left(1-\left( \frac {N-1}N \right)^m-m\times \frac 1N \times \left( \frac {N-1}N \right)^{m-1} \right)$$
Combining all this and using the values you specify, we get that $$E[552025,647117]=0.210391739\times 552025=116141.4998$$
Of course the probability that there are no duplicates is effectively $0$.  If you want to compute it exactly, note that it is given in general by $$\prod_{i=0}^{m-1} \frac {N-i}N$$  To see that this is, effectively, $0$ in your case note that from $i=323559$ to the end each term is less than $\frac 12$ so your expression is less than $\left( \frac 12 \right)^{228466}$ which is about $7.6\times 10^{-68776}$


text:
Q: Run multiple commands inside a buildah container separated by the boolean AND (&&) operator from the command line How can I run multiple commands inside a buildah container using bash's boolean AND && operator from the host's command line?
Here's an example of my issue that starts from a debian image:
$ buildah pull debian:buster && container=$(buildah from debian:buster)
$ buildah run $container -- apt -y update && apt -y upgrade
Hit:1 http://security.debian.org/debian-security buster/updates InRelease
Hit:2 http://deb.debian.org/debian buster InRelease
Hit:3 http://deb.debian.org/debian buster-updates InRelease
Reading package lists... Done
Building dependency tree
Reading state information... Done
All packages are up to date.
bash: apt: command not found...
Install package 'apt' to provide command 'apt'? [N/y]

My host shell interprets the boolean AND && outside the command for buildah. My expectation is to have the right side of the boolean AND to be run inside the buildah container.

A: How about?
buildah run $container -- sh -c 'apt -y update && apt -y upgrade'.


text:
Q: Save TensorFlowJS MobileNet + KNN to TFLite I have trained a KNN on top of MobileNet logits results using TensorFlowJS.
And I want to know how can I export the result of the MobileNet + KNN to a TFLite model.
const knn = knnClassifier.create()
const net = await mobilenet.load()

const handleTrain = (imgEl, label) => {
  const image = tf.browser.fromPixels(imgEl);
  const activation = net.infer(image, true);
  knn.addExample(activation, label)
}

A: 1. Save the model
Save the model this example saves the file to the native file system or if you need it to be saved in other places then check the documentation.
await model.save('file:///path/to/my-model');

You should have a JSON file and a binary weight file(s) after this step.
2. Convert from TensorFlow.js Layers model to Saved Model format
tfjs_model.json is the path to the model.json that you get from the previous step and saved_model is the path where you want to save the SavedModel format.
You can read more about using the TensorflowJS Converter from here.
tensorflowjs_converter --input_format=tfjs_layers_model --output_format=keras_saved_model tfjs_model.json saved_model

3. Convert from SavedModel format to TFLite format
Converting from a SavedModel format to TFLite is the recommended way to do this as per the documentation.
import tensorflow as tf

# Convert the model
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) # path to the SavedModel directory
tflite_model = converter.convert()

# Save the model.
with open('model.tflite', 'wb') as f:
  f.write(tflite_model)


text:
Q: Android Duplicate class com.google.android.gms.location.places.zza found in modules I am trying to Integrate Google New Place library in my Project as old place library is deprecated. After adding new place library com.google.android.libraries.places:places:1.0.0 it is creating below error.How to resolve this
Duplicate class com.google.android.gms.location.places.zza found in modules classes.jar
(com.google.android.gms:play-services-places-placereport:16.0.0) and classes.jar
(com.google.android.gms:play-services-places:11.8.0)

Below is my app level gradle file
apply plugin: 'com.android.application'

allprojects {
repositories {
    google()
}
repositories {
    maven {
        url 'https://maven.google.com'
    }
}
repositories {
    jcenter()
    maven { url "https://jitpack.io" }
}
}

android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
    applicationId "com.api.app"
    minSdkVersion 16
    targetSdkVersion 26
    versionCode 27
    versionName "1.5"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    manifestPlaceholders = [HOCKEYAPP_APP_ID: "51a9c4471559421b8d53a07cbb3e3fa0"]
    useLibrary 'org.apache.http.legacy'
    multiDexEnabled true

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

implementation('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
    transitive = true;
}

implementation ('com.google.android.libraries.places:places:1.0.0') {
    exclude group: 'com.github.bumptech.glide', module: 'glide'
}

implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support:recyclerview-v7:26.1.0'
implementation 'com.android.support:cardview-v7:26.1.0'
implementation 'com.squareup.okhttp3:okhttp:3.8.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0-beta2'
implementation 'com.iarcuschin:simpleratingbar:0.1.5'
implementation 'com.google.code.gson:gson:2.8.1'

implementation "com.google.android.gms:play-services-maps:11.8.0"
implementation "com.google.android.gms:play-services-location:11.8.0"
implementation "com.google.android.gms:play-services-places:11.8.0"
implementation "com.google.firebase:firebase-auth:11.8.0"

implementation "com.google.firebase:firebase-messaging:11.8.0"
implementation "com.google.firebase:firebase-database:11.8.0"
implementation "com.google.firebase:firebase-invites:11.8.0"
implementation "com.google.android.gms:play-services:11.8.0"

implementation 'com.android.support:multidex:1.0.1'
implementation 'com.hbb20:ccp:1.7.2'
implementation 'de.hdodenhof:circleimageview:2.1.0'
implementation 'net.hockeyapp.android:HockeySDK:4.1.3'
implementation 'com.android.volley:volley:1.1.0'
implementation 'com.facebook.android:facebook-android-sdk:4.0.0'
implementation 'com.google.code.gson:gson:2.7'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.github.krtkush:LinearTimer:v2.1.0'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.github.bumptech.glide:glide:3.6.1'

api "com.sothree.slidinguppanel:library:3.0.0"
implementation 'com.google.maps.android:android-maps-utils:0.4'

implementation 'com.iarcuschin:simpleratingbar:0.1.5'
implementation 'com.paypal.sdk:paypal-android-sdk:2.15.3'
testImplementation 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

And below is my Project level gradle
buildscript {
repositories {
    jcenter()
    maven { url 'https://maven.google.com' }
    google()

}
dependencies {
    classpath 'com.android.tools.build:gradle:3.5.0'
    classpath 'com.google.gms:google-services:3.1.0'
}
}

allprojects {
repositories {
    jcenter()
    maven { url 'https://maven.google.com' }
}
}

project.ext {
supportVersion = '26.0.1'
googleVersion = '11.8.0'
}

task clean(type: Delete) {
delete rootProject.buildDir
}

task createWrapper(type: Wrapper) {
gradleVersion = '5.4.1'
}

A: Don't
implementation ('com.google.android.libraries.places:places:1.0.0') {
    exclude group: 'com.github.bumptech.glide', module: 'glide'
}

You can try with
implementation "com.google.android.libraries.places:places:1.1.0"

The Google Play Services version of the Places SDK for Android (i.e. com.google.android.gms:play-services-places) was turned off on July 29, 2019, and is no longer available. A new version of the Places SDK for Android is now available.
Do
dependencies {

    implementation 'com.google.android.libraries.places:places:2.2.0'
}

Read Migrating to the New Places SDK .
FYI
You are using very old versions. If you want to use latest then libraries will not work unless you make the following changes in your app:

*

*Upgrade compileSdkVersion to 28 or later.

*Update your app to use Jetpack (AndroidX).

AndroidX replaces the original support library APIs with packages in the androidx namespace. Read official guideline about AndroidX Overview.


text:
Q: Predicate in Prolog, predicate works only for numbers I'm having trouble writing a predicate in the Prolog:
In Prolog, define a predicate replace1(L1, L2) that is satisfied when the list L2 is derived from the list L1 by replacing each element with an element of the form element * element.
Example: L1 = [1, aa, 3], L2 = [1 * 1, aa * aa, 3 * 3].
I tried this way, but this predicate only works for numbers:
replace1 ([], []) :- !.
replace1 ([X | Xs], [Z | Zs]) :-
  Z is X * X,
  replace1 (Xs, Zs).

A: You are using is/2 which is arithmetic evaluation operator. You could just use = and would get what you want.
replace([], []).
replace([X|Xs], [Y|Ys]) :-
    Y = X * X,
    replace(Xs, Ys).

This gives:
| ?- replace([1, aa, 3], X).
X = [1*1,aa*aa,3*3]

You can also just use pattern matching within the head itself:
replace([], []).
replace([X|Xs], [X*X|Ys]) :-  replace(Xs, Ys).


text:
Q: Search CSV for matching field and use initial date I am attempting to search a CSV file for rows with duplicate device names. The output should record the date from the 1st matching row and also record the date from the last row found. I need some assistance with the logic of removing duplicate device names from the CSV file, whilst also keeping a record of when a device was first and last seen.
import time as epoch

# AlertTime, DeviceName, Status
Input = [['14/08/2016 13:00', 'device-A', 'UP'], ['14/08/2016 13:15', 'device-B', 'DOWN'], ['15/08/2016 17:30', 'device-A', 'UP']]

# FirstSeen, LastSeen, DeviceName, Status
Output = []

# Last 48 hours
now = epoch.time()
cutoff = now - (172800)

for i in Input:
    AlertTime = epoch.mktime(epoch.strptime(i[0], '%d/%m/%Y %H:%M'))
    if AlertTime > cutoff:
        Result = [i[0], i[0], i[1], i[2]]
        Output.append(Result)

print(Output)

Output (3 entries):
[['14/08/2016 13:00', '14/08/2016 13:00', 'device-A', 'UP'], ['14/08/2016 13:15', '14/08/2016 13:15', 'device-B', 'DOWN'], ['15/08/2016 17:30', '15/08/2016 17:30', 'device-A', 'UP']]

Wanted Output (2 entries):
[['14/08/2016 13:15', '14/08/2016 13:15', 'device-B', 'DOWN'], ['14/08/2016 13:00', '15/08/2016 17:30', 'device-A', 'UP']]

A: As Vedang Mehta said in the comments, you could use a dict to store the data.
    my_dict = {}
    for i in Input:
        AlertTime = epoch.mktime(epoch.strptime(i[0], '%d/%m/%Y %H:%M'))
        if AlertTime > cutoff:
            #if we have seen this device before, update it
            if i[1] in my_dict:
                my_dict[i[1]] = (my_dict[i[1]][0], i[0], i[2])
            #if we haven't seen it, add it
            else:
                my_dict[i[1]] = (i[0],i[0],i[2])

After this, all your devices will be stored in my_dict containing (first_seen, last_seen and status).

A: You can use an OrderedDict to preserve the order that devices are seen in the CSV file. A dictionary is used to automatically remove duplicates.
The following works by attempting to update an existing dictionary entry, if it not already present, Python generates a KeyError exception. In this case a new entry can be added with an identical start and end alert time. When updating an entry, the existing first_seen is used to update the entry with the latest found alert_time and status. At the end, the dictionary is parsed to create your required output format:
from collections import OrderedDict

# AlertTime, DeviceName, Status
input_data = [['14/08/2016 13:00', 'device-A', 'UP'], ['14/08/2016 13:15', 'device-B', 'DOWN'], ['15/08/2016 17:30', 'device-A', 'UP']]

entries = OrderedDict()

for alert_time, device_name, status in input_data:
    try:
        entries[device_name] = [entries[device_name][0], alert_time, status]
    except KeyError as e:
        entries[device_name] = [alert_time, alert_time, status]

# Convert the dictionary of entries into the required format
output_data = [[device_name, first_seen, last_seen, status] for device_name, [first_seen, last_seen, status] in entries.items()]

print(output_data)

Giving you output as:
[['device-A', '14/08/2016 13:00', '15/08/2016 17:30', 'UP'], ['device-B', '14/08/2016 13:15', '14/08/2016 13:15', 'DOWN']]