text:
Q: CakePHP 2.3.1 Auth Component I've recently been pouring over some CakePHP tutorials on the Auth Component, and am using this for reference: http://miftyisbored.com/a-complete-login-and-authentication-application-tutorial-for-cakephp-2-3/
My Cake version is 2.3.1
I'm using Firebug for debugging. The database passwords are hashing right, and I can Register and new user just fine, however logging in is a different story. When I try to access a page that requires Authentication, I get the login page, enter a valid user/pass, and it redirects me right back to the login page. In firebug the POST header is 200 OK and just returns the login page again. I'm guessing I may have something wrong with my session config or something, as if the session isn't being looked up. Here's my UsersController.php:
<?php
class UsersController extends AppController {
    public $name = 'Users';
    public $helpers = array('Html','Form');

    public function beforeFilter() {
            parent::beforeFilter();
            $this->Auth->allow('add', 'login');
        }

    public function login() {

            //if already logged-in, redirect
            if($this->Session->check('Auth.User')){
                $this->redirect(array('controller'=>'admin','action' => 'admin_index'));
            }

            // if we get the post information, try to authenticate
            if ($this->request->is('post')) {
                if ($this->Auth->login()) {
                    $this->Session->setFlash(__('Welcome, '. $this->Auth->user('username')));
                    $this->redirect($this->Auth->redirectUrl());
                } else {
                    $this->Session->setFlash(__('Invalid username or password'));
                }
            }
        }

    public function logout() {
        return $this->redirect($this->Auth->logout());
    }

    public function index() {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    public function view($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('user', $this->User->read(null, $id));
    }

    public function add() {
        if ($this->request->is('post')) {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                return $this->redirect(array('action' => 'login'));
            }
            $this->Session->setFlash(
                __('The user could not be saved. Please, try again.')
            );
        }
    }

    public function edit($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash(
                __('The user could not be saved. Please, try again.')
            );
        } else {
            $this->request->data = $this->User->read(null, $id);
            unset($this->request->data['User']['password']);
        }
    }

    public function delete($id = null) {
        $this->request->onlyAllow('post');

        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->User->delete()) {
            $this->Session->setFlash(__('User deleted'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('User was not deleted'));
        return $this->redirect(array('action' => 'index'));
    }

}
?>

My Model seems to be working ok, but I can provide any additional code if this isn't where my error is at! Thanks bunches!

A: the problem is in the encryptacion of your passwords, see if you're doing a beforesave and you need make a encryption when saving and password that you log in to verify if they are the same in your DB
User model
 public function beforeSave($options = array()) {
    // hash our password

    if (!$this->id) {
        $passwordHasher = new SimplePasswordHasher();
        $this->data['User']['password'] = $passwordHasher->hash($this->data['User']['password']);
    }
    return true;
}

AppController
public function beforeFilter() {
    Security::setHash('sha1');
    $this->Auth->allow('index', 'display', 'view');
}

In your database for the password the right is varchar (30)


text:
Q: ReactNative rerenders component when the user opens the page I have two components the first where user can add a place to the favorites and the second is favorites component where user may see all his favorite places. When the user for the first time opens the favorites component everything works as expected: all the favorite places that user has already added to the favorites rendered. But if user go to the first component and add one more place and then go to the second component new place will not appear because component has already rendered and the state didn't changed because useEffect not triggered. Help me please what should I use in my FavouritePlaces component instead of useEffect to rerender this component every time when user open FavouritePlaces?
Component where user can add to favorites:
const ModalWindow = ({navigateToPlace, sendDataToParent, visible, marker}: HomeNavigationProps<"ModalWindow">) => {
    const regex = /(<([^>]+)>)|( )|(&nbps)/ig;
    const result = marker.description.replace(regex, '');
    const [favKeys, setFavKeys] = useState([]);
    const onDismiss = () => {
        sendDataToParent(false)
    }
    const onNavigationTap = () => {
        onDismiss();
        navigateToPlace(true, marker.coordinates);
    }
    const getFavourites = async () => {
        let keys = []
        keys = await AsyncStorage.getAllKeys()
        setFavKeys(keys);
    }
    const onHeartPress = async () => {
        const jsonValue = JSON.stringify(marker)
        try {
            if (favKeys.includes(marker.id.toString())){
                await AsyncStorage.removeItem(marker.id.toString())
                await getFavourites();
            } else {
                await AsyncStorage.setItem(marker.id.toString(), jsonValue)
                await getFavourites();
            }
        } catch (e) {
            console.log('error in onHeartPress', e)
        }
        console.log('Done.')
        //remove after test
        try {
            await AsyncStorage.removeItem('__react_native_storage_test')
        } catch(e) {
            // remove error
        }
        console.log('Done.')
    }
    return (
        <Modal visible={visible} onDismiss={onDismiss} contentContainerStyle={styles.container}>
            <IconButton
                style={
                    styles.iconButton
                }
                icon="close"
                color={Colors.black}
                size={30}
                onPress={() => onDismiss()}
            />
            <Text
                style={{fontStyle: "italic", fontSize: 20, alignSelf: "center", maxWidth: '75%'}}>{marker.title}
            </Text>
            <CustomCarousel {...{marker}} />
            <ScrollView showsVerticalScrollIndicator={false} style={{marginTop: '3%', marginLeft: '3%', marginRight: '3%'}}>
                <Text>{result}</Text>
            </ScrollView>
            <View style={{flexDirection: "row", justifyContent: "space-around", marginLeft: "3%", marginRight: "3%", marginBottom: "15%"}}>
                <TouchableOpacity onPress={() => onNavigationTap()}>
                    <View style={{flexDirection: "row", alignItems: "center"}}>
                        <Ionicons size={height/20} name={'navigate-circle-outline'} />
                    </View>
                </TouchableOpacity>
            <TouchableOpacity onPress={() => onHeartPress()}>
                {marker.id ?
                    <View style={{flexDirection: "row", alignItems: "center"}}>
                    {favKeys.includes(marker.id.toString()) ? <Ionicons size={height/20} name={'heart-dislike'} /> : <Ionicons size={height/20} name={'heart'} />}
                </View> : undefined}
            </TouchableOpacity>
            </View>
        </Modal>
    );
}

export default ModalWindow;

My Favorite Places component:
const FavouritePlaces = ({navigation}: HomeNavigationProps<"FavouritePlaces">) => {
    const [markers, setMarkers] = useState([]);
    useEffect(() => {
        const getFavourites = async () => {
            let keys = []
            try {
                keys = await AsyncStorage.getAllKeys()
            } catch (e) {
                // read key error
            }
            let values
            try {
                let forDeletion = ['__react_native_storage_test', 'NAVIGATION_STATE_KEY-40.0.0'];
                keys = keys.filter(item => !forDeletion.includes(item))
                values = await AsyncStorage.multiGet(keys)
                setMarkers(values)
            } catch (e) {
                // read error
            }
        }
        getFavourites();
    }, [])
    const transition = (
        <Transition.Together>
            <Transition.Out type='fade'/>
            <Transition.In type='fade'/>
        </Transition.Together>
    );

    const list = useRef<TransitioningView>(null);
    const theme = useTheme()
    const width = (wWidth - theme.spacing.m * 3) / 2;
    const [footerHeight, setFooterHeight] = useState(0);
    return (
        <Box flex={1} backgroundColor="background">
            <StatusBar style="black" />
            <Header
                title="Избранные места"
                left={{icon: 'menu', onPress: () => navigation.openDrawer()}}
                right={{icon: 'shopping-bag', onPress: () => true}}
            />
            <Box flex={1}>
                <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{
                    paddingBottom: footerHeight,

                }}>
                    <Transitioning.View ref={list} transition={transition} style={{}}>
                        {markers ?
                            <Box flexDirection='row' style={{justifyContent: "space-around"}}>
                                <Box>
                                    {markers
                                        .filter((_, i) => i % 2 === 0).map((currentMarker) => <Picture
                                            key={currentMarker}
                                            place={currentMarker}
                                            width={width}
                                            height={height}
                                        />)}
                                </Box>
                                <Box>
                                    {markers
                                        .filter((_, i) => i % 2 !== 0).map((currentMarker) => <Picture
                                            key={currentMarker}
                                            place={currentMarker}
                                            width={width}
                                            height={height}/>)}
                                </Box>
                            </Box> : undefined}
                    </Transitioning.View>
                </ScrollView>
                {/*<TopCurve footerHeight={footerHeight}/>*/}
                <Box position='absolute' bottom={0} left={0} right={0} onLayout={({
                                                                                nativeEvent: {
                                                                                layout: {height},
                                                                                }
                                                                                }) => setFooterHeight(height)}>
                </Box>
            </Box>
        </Box>
    )
}
export default FavouritePlaces

A: Try this
 useEffect(() => {
    // ... Your code goes here
}, [navigation]);

this will render whenever update in navigate

A: I've found the solution. React navigation has hook useIsFocused, so what can we do is:
import { useIsFocused } from "@react-navigation/native";
const isFocused = useIsFocused();
useEffect(() => {
    // ... Your code goes here
}, [isFocused]);

A: You can use React Context API to share the state across the screens.
Check out this Expo Snack I created.
import {
  CompositeNavigationProp,
  NavigationContainer,
  NavigatorScreenParams,
} from '@react-navigation/native';
import {
  createStackNavigator,
  StackNavigationProp,
} from '@react-navigation/stack';
import * as React from 'react';
import {
  Button,
  FlatList,
  ListRenderItem,
  Text,
  TextInput,
  View,
} from 'react-native';

type MainStackParamsList = {
  FavoritePlacesScreen: undefined;
};

type ModalStackParamsList = {
  MainStack: NavigatorScreenParams<MainStackParamsList>;
  AddFavoritePlacesModal: undefined;
};

type FavoritePlace = {
  id: number;
  name: string;
};

type FavoritePlacesContextValue = {
  favoritePlaces: FavoritePlace[];
  addNewFavoritePlace: (favoritePlace: FavoritePlace) => void;
  removeFavoritePlace: (id: number) => void;
};

const FavoritePlacesContext = React.createContext<FavoritePlacesContextValue>({
  favoritePlaces: [],
  addNewFavoritePlace: () => {},
  removeFavoritePlace: () => {},
});

const MainStack = createStackNavigator<MainStackParamsList>();

type FavoritePlacesScreenProps = {
  navigation: CompositeNavigationProp<
    StackNavigationProp<MainStackParamsList, 'FavoritePlacesScreen'>,
    StackNavigationProp<ModalStackParamsList>
  >;
};

const FavoritePlacesScreen = ({navigation}: FavoritePlacesScreenProps) => {
  const {favoritePlaces, removeFavoritePlace} = React.useContext(
    FavoritePlacesContext,
  );

  const renderItem = React.useCallback<ListRenderItem<FavoritePlace>>(
    ({item}) => {
      return (
        <View style={{height: 50, padding: 10, flexDirection: 'row'}}>
          <Text style={{fontSize: 16}}>{item.name}</Text>
          <Button onPress={() => removeFavoritePlace(item.id)} title="Remove" />
        </View>
      );
    },
    [removeFavoritePlace],
  );

  return (
    <View style={{flex: 1}}>
      <FlatList
        data={favoritePlaces}
        keyExtractor={(item) => String(item.id)}
        renderItem={renderItem}
      />
      <Button
        onPress={() => {
          navigation.navigate('AddFavoritePlacesModal');
        }}
        title="Add new favorite"
      />
    </View>
  );
};

const MainStackNavigator = () => {
  return (
    <MainStack.Navigator>
      <MainStack.Screen
        component={FavoritePlacesScreen}
        name="FavoritePlacesScreen"
      />
    </MainStack.Navigator>
  );
};

type AddFavoritePlacesModalProps = {
  navigation: StackNavigationProp<
    ModalStackParamsList,
    'AddFavoritePlacesModal'
  >;
};

const AddFavoritePlacesModal = ({navigation}: AddFavoritePlacesModalProps) => {
  const {addNewFavoritePlace} = React.useContext(FavoritePlacesContext);

  const [favoritePlaceName, setFavoritePlaceName] = React.useState('');

  const handleOnSave = React.useCallback(() => {
    addNewFavoritePlace({
      id: Date.now(),
      name: favoritePlaceName,
    });
    navigation.goBack();
  }, [addNewFavoritePlace, favoritePlaceName, navigation]);

  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
      <View style={{borderRadius: 6, borderWidth: 1, borderColor: '#333'}}>
        <TextInput
          onChangeText={setFavoritePlaceName}
          placeholder="Name your favorite place"
        />
      </View>
      <Button onPress={handleOnSave} title="Save" />
    </View>
  );
};

// Put the favorite places list screen and the add favorite place modal here.
// Then use FavoritePlacesContext.Provider to wrap ModalStack.Navigator in order
// for the context to be available on MainStack
const ModalStack = createStackNavigator<ModalStackParamsList>();

const ModalNavigator = () => {
  const [favoritePlaces, setFavoritePlaces] = React.useState<FavoritePlace[]>(
    [],
  );

  const addNewFavoritePlace = React.useCallback(
    (favoritePlace: FavoritePlace) => {
      setFavoritePlaces((prev) => [...prev, favoritePlace]);
    },
    [],
  );

  const removeFavoritePlace = React.useCallback((id: number) => {
    setFavoritePlaces((prev) =>
      prev.filter((favoritePlace) => favoritePlace.id !== id),
    );
  }, []);

  return (
    <FavoritePlacesContext.Provider
      value={{
        favoritePlaces,
        addNewFavoritePlace,
        removeFavoritePlace,
      }}
    >
      <ModalStack.Navigator headerMode="none">
        <ModalStack.Screen component={MainStackNavigator} name="MainStack" />
        <ModalStack.Screen
          component={AddFavoritePlacesModal}
          name="AddFavoritePlacesModal"
          options={{headerShown: false}}
        />
      </ModalStack.Navigator>
    </FavoritePlacesContext.Provider>
  );
};

const App = () => {
  return (
    <NavigationContainer>
      <ModalNavigator />
    </NavigationContainer>
  );
};

export default App;

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you index an array inside a JSON with an Oracle 12c query? I have a table "move" with one column "move_doc" which is a CLOB. The json stored inside has the structure:
{
moveid : "123",
movedate : "xyz",
submoves: [
{
submoveid: "1",
...
 },
{
submoveid : "2",
...
}
]
}

I know I can run an Oracle 12c query to access the submoves list with:
select move.move_doc.submoves from move move
How do I access particular submoves of the array? And the attributes inside a particular submove?

A: You have to use Oracle functions json_query and/or json_value like this:
SELECT json_value(move_doc, '$.submoves[0].submoveid' RETURNING NUMBER) FROM move;

returns 1.
SELECT json_query(move_doc, '$.submoves[1]') FROM move;

would return the second JSON element, i.e. something like
{
submoveid : "2",
...
}

json_value is used to retrieve a scalar value, json_query is used to retrieve JSON values. You might also want to have a look at json_table which returns an SQL result table and thus can be used in Joins.
See this Oracle Doc for more examples

A: Beda here from the Oracle JSON team.
We have added a new multi-value index in release 21c allowing you to index values from a JSON array. Obviously, 21c is brand new and you want to know how to do this in older releases: Functional indexes (using JSON_Value function) are limited to a single value per JSON document and therefore are not capable to index array values. But: there is a 'JSON search index' which indexes your entire JSON document and therefore also values in the array. Another solution is to use a materialized view usign JSON_Table. This will expand the array values into separate rows.Then you can add a regular B-Tree index on that column.
Sample code here:
JSON indexing with functional indexes and JSON search index
https://livesql.oracle.com/apex/livesql/file/content_HN507PELCEEJGVNW4Q61L34DS.html
JSON and materialized views
https://livesql.oracle.com/apex/livesql/file/content_HYMB1YBP4CPMG6T6MXY5G9X5L.html

A: From what I've looked, In Oracle,  you can index the "whole array" as a single index entry, but not individual elements of an array.
NoSQL databases like MongoDB, Couchbase, Cassandra have "array/collection" indexes which can index individual elements or fields of objects within an array and query them.


text:
Q: Primefaces Schedule is not displayed in Application I got a problem with the Primefaces
.
It is not displayed in my Application which uses <ui:include> and <ui:composition> Tags.
But if I place the Schedule in a Standalone Page without these Tag Combination, it works as expected.
My app.xhtml Page includes a Layout which is defined by the
 Component. I define a Menu at the left side with a <f:ajax> Tag, so that a contentPanel get updated on each click in the menu.
One of these Pages which gets included, is the hldyplanning.xhtml - in this Page a
 should be displayed. For testing I create a new site. The test.xhtml. I decide to implement the Primefaces ShowCase Example for testing it.
I hope that I'm doing something wrong and it is not a Bug or something like that.
Here's the app.xhtml:

    <f:view contentType="text/html">
        <h:head>
            <f:facet name="first">
                <meta content='text/html; charset=UTF-8' http-equiv="Content-Type"/>
                <meta http-equiv="refresh" content="#{session.maxInactiveInterval};url=/LEAN" />
                <title>Lean - Menü</title>
            </f:facet>
        </h:head>

        <h:body style="background: white;">

                    <h:form id="frm_menu">
                        <f:ajax render=":contentPanel" execute="@this">

                        </f:ajax>
                    </h:form>

                    <h:panelGroup id="contentPanel">
                        <ui:include src="#{appController.content}.xhtml" />
                    </h:panelGroup>

        </h:body>

    </f:view>

The appController.java
package lean.controller.view;

import java.util.Map;
import javax.annotation.PostConstruct;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import org.primefaces.model.DefaultMenuModel;
import org.primefaces.model.MenuModel;
import org.primefaces.component.menuitem.MenuItem;
import org.primefaces.component.submenu.Submenu;

@ManagedBean
@RequestScoped
public class AppController {

    private String content = "/app/includes/dashboard";

    private MenuModel menu;
    private Submenu submenu;
    private MenuItem item;

    final private String[] submenu_urlb = { "Urlaubsübersicht", "/app/includes/urlaubsubersicht",
                                            "Urlaubsplanung", "/app/includes/hldyplanning",
                                            "Abteilungsübersicht", "/app/includes/abt_ubersicht",
                                            "Persönliche Übersicht", "/app/includes/per_uberischt",
                                            "Urlaubsanträge", "/app/includes/urlaubsantrage"};

    FacesContext fc;
    ExpressionFactory exfactory;
    HttpServletResponse response;
    Map cookieMap;
    MethodExpression me;

    //<editor-fold defaultstate="collapsed" desc="GETTER UND SETTER">

    public MenuModel getMenu(){
        return menu;
    }

    public MethodExpression getMe() {
        return me;
    }

    public void setMe(MethodExpression me) {
        this.me = me;
    }

    public ExpressionFactory getExfactory() {
        return exfactory;
    }

    public void setExfactory(ExpressionFactory exfactory) {
        this.exfactory = exfactory;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public FacesContext getFc() {
        return fc;
    }

    public void setFc(FacesContext fc) {
        this.fc = fc;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    public Map getCookieMap() {
        return cookieMap;
    }

    public void setCookieMap(Map cookieMap) {
        this.cookieMap = cookieMap;
    }

    //</editor-fold>

    /**
     *
     */
    @PostConstruct
    public void init() {

        setFc(FacesContext.getCurrentInstance());
        setResponse((HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse());
        setCookieMap(FacesContext.getCurrentInstance().getExternalContext().getRequestCookieMap());
        setExfactory(FacesContext.getCurrentInstance().getApplication().getExpressionFactory());

        menu = new DefaultMenuModel();

        //erstes Submenu erzeugen

        submenu = new Submenu();
        submenu.setLabel("Urlaubsplanung");

        for(int i = 0; i <= (submenu_urlb.length-1); i=i+2){
            item = new MenuItem();
            item.setValue(submenu_urlb[i]);
            setMe(getExfactory().createMethodExpression( fc.getELContext(), "#{appController.doNav(\""+submenu_urlb[i+1]+"\")}", void.class, new Class[0]));
            item.setActionExpression(me);
            item.setUpdate(":contentPanel");
            submenu.getChildren().add(item);
        }

        menu.addSubmenu(submenu);

        //zweites Submenu erzeugen
        submenu = new Submenu();
        submenu.setLabel("Account");

        item = new MenuItem();
        item.setValue("Dashboard");
        setMe(getExfactory().createMethodExpression( fc.getELContext(), "#{appController.doNav(\"/app/includes/dashboard\")}", void.class, new Class[0]));
        item.setActionExpression(me);
        item.setUpdate(":contentPanel");
        submenu.getChildren().add(item);

        item = new MenuItem();
        item.setValue("Ausloggen");
        setMe(getExfactory().createMethodExpression( fc.getELContext(), "#{appController.menuitem_logout()}", void.class, new Class[0]));
        item.setActionExpression(me);
        item.setUpdate(":contentPanel");
        submenu.getChildren().add(item);

        menu.addSubmenu(submenu);

    }

    public String menuitem_logout(){

        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "backToStart";

    }

    public void doNav(String nav){

        setContent(nav);

    }
}

The hldyplanning.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui">

    <h:form id="frm_urlbubersicht">

            <f:facet name="header">

                        Urlaubsplanung

            </f:facet>

                        <f:facet name="header">
                            Urlaubsantrag Formular
                        </f:facet>

                        <f:facet name="header">

Persönliche Informationen

                        </f:facet>

                                <h:outputText value="Name:"/>

                                <h:outputText value="#{loginController.sessionData.user_name}" />

                                <h:outputText value="Team:" />

                                <h:outputText value="#{loginController.sessionData.teams_name}" />

                        <f:facet name="header">

Zeitraum

                        </f:facet>

                        <f:facet name="header">

Weiteres

                        </f:facet>

                                    <f:selectItem itemLabel="Urlaub" itemValue="U" />
                                    <f:selectItem itemLabel="Absetzen" itemValue="A" />

                        <f:facet name="header">

Aktion

                        </f:facet>

                                <h:commandButton id="btn_plan" value="Planen" action="#{hldyPlanningController.sendAFL()}" style="width: 170px; height: 30px"/>

                                <h:commandButton id="btn_submit" value="Beantragen" action="#{hldyPlanningController.sendAFL()}" style="width: 170px; height: 30px" />

                        <f:facet name="header">
                            Mitarbeiter, die in diesem Zeitraum auch Urlaub geplant haben
                        </f:facet>

            <h:panelGrid id="eventDetails" columns="2">
                <h:outputLabel for="title" value="Title:" />

                <h:outputLabel for="from" value="From:" />

                    <f:convertDateTime pattern="dd/MM/yyyy" />

                <h:outputLabel for="to" value="To:" />

                    <f:convertDateTime pattern="dd/MM/yyyy" />

                <h:outputLabel for="allDay" value="All Day:" />
                <h:selectBooleanCheckbox id="allDay" value="#{calendarController.event.allDay}" />

            </h:panelGrid>

    </h:form>

</ui:composition>

The test.xhtml

    <f:view contentType="text/html">
        <h:head>
            <f:facet name="first">
                <meta content='text/html; charset=UTF-8' http-equiv="Content-Type"/>
                <title>TEST</title>
            </f:facet>
        </h:head>
        <h:body>
            <h:form>

                    <h:panelGrid id="eventDetails" columns="2">
                        <h:outputLabel for="title" value="Title:" />

                        <h:outputLabel for="from" value="From:" />

                            <f:convertDateTime pattern="dd/MM/yyyy" />

                        <h:outputLabel for="to" value="To:" />

                            <f:convertDateTime pattern="dd/MM/yyyy" />

                        <h:outputLabel for="allDay" value="All Day:" />
                        <h:selectBooleanCheckbox id="allDay" value="#{calendarController.event.allDay}" />

                    </h:panelGrid>

            </h:form>
        </h:body>
    </f:view>

the calendarController.java
package lean.controller.view;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import lean.dataobjects.HolidayDataObj;

import org.primefaces.event.DateSelectEvent;
import org.primefaces.event.ScheduleEntryMoveEvent;
import org.primefaces.event.ScheduleEntryResizeEvent;
import org.primefaces.event.ScheduleEntrySelectEvent;
import org.primefaces.model.DefaultScheduleEvent;
import org.primefaces.model.DefaultScheduleModel;
import org.primefaces.model.LazyScheduleModel;
import org.primefaces.model.ScheduleEvent;
import org.primefaces.model.ScheduleModel;

@ManagedBean(name = "calendarController")
@SessionScoped
public class CalendarController implements Serializable {

        private ScheduleModel eventModel;
        private List<HolidayDataObj> holidayData;

        private ScheduleModel lazyEventModel;

        private ScheduleEvent event = new DefaultScheduleEvent();

        @PostConstruct
        public void init() {
                eventModel = new DefaultScheduleModel();
                eventModel.addEvent(new DefaultScheduleEvent("Champions League Match", previousDay8Pm(), previousDay11Pm()));
                eventModel.addEvent(new DefaultScheduleEvent("Birthday Party", today1Pm(), today6Pm()));
                eventModel.addEvent(new DefaultScheduleEvent("Breakfast at Tiffanys", nextDay9Am(), nextDay11Am()));
                eventModel.addEvent(new DefaultScheduleEvent("Plant the new garden stuff", theDayAfter3Pm(), fourDaysLater3pm()));

                try {
                    holidayData = lean.sql.QueryMySQL.getHolidaysForAll();

                for(int i=0; i<=holidayData.size()-1; i++ ) {
                    eventModel.addEvent( new DefaultScheduleEvent(holidayData.get(i).getUser_name(),holidayData.get(i).getHldy_startdate(),holidayData.get(i).getHldy_enddate()));
                }

                }catch(Exception e){
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "HolidayCollector ", e.getMessage()));
                }

                lazyEventModel = new LazyScheduleModel() {

                        @Override
                        public void loadEvents(Date start, Date end) {
                                clear();

                                Date random = getRandomDate(start);
                                addEvent(new DefaultScheduleEvent("Lazy Event 1", random, random));

                                random = getRandomDate(start);
                                addEvent(new DefaultScheduleEvent("Lazy Event 2", random, random));
                        }
                };
        }

        public Date getRandomDate(Date base) {
                Calendar date = Calendar.getInstance();
                date.setTime(base);
                date.add(Calendar.DATE, ((int) (Math.random()*30)) + 1);        //set random day of month

                return date.getTime();
        }

        public Date getInitialDate() {
                Calendar calendar = Calendar.getInstance();
                calendar.set(calendar.get(Calendar.YEAR), Calendar.FEBRUARY, calendar.get(Calendar.DATE), 0, 0, 0);

                return calendar.getTime();
        }

        public ScheduleModel getEventModel() {
                return eventModel;
        }

        public ScheduleModel getLazyEventModel() {
                return lazyEventModel;
        }

        private Calendar today() {
                Calendar calendar = Calendar.getInstance();
                calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 0, 0, 0);

                return calendar;
        }

        private Date previousDay8Pm() {
                Calendar t = (Calendar) today().clone();
                t.set(Calendar.AM_PM, Calendar.PM);
                t.set(Calendar.DATE, t.get(Calendar.DATE) - 1);
                t.set(Calendar.HOUR, 8);

                return t.getTime();
        }

        private Date previousDay11Pm() {
                Calendar t = (Calendar) today().clone();
                t.set(Calendar.AM_PM, Calendar.PM);
                t.set(Calendar.DATE, t.get(Calendar.DATE) - 1);
                t.set(Calendar.HOUR, 11);

                return t.getTime();
        }

        private Date today1Pm() {
                Calendar t = (Calendar) today().clone();
                t.set(Calendar.AM_PM, Calendar.PM);
                t.set(Calendar.HOUR, 1);

                return t.getTime();
        }

        private Date theDayAfter3Pm() {
                Calendar t = (Calendar) today().clone();
                t.set(Calendar.DATE, t.get(Calendar.DATE) + 2);
                t.set(Calendar.AM_PM, Calendar.PM);
                t.set(Calendar.HOUR, 3);

                return t.getTime();
        }

        private Date today6Pm() {
                Calendar t = (Calendar) today().clone();
                t.set(Calendar.AM_PM, Calendar.PM);
                t.set(Calendar.HOUR, 6);

                return t.getTime();
        }

        private Date nextDay9Am() {
                Calendar t = (Calendar) today().clone();
                t.set(Calendar.AM_PM, Calendar.AM);
                t.set(Calendar.DATE, t.get(Calendar.DATE) + 1);
                t.set(Calendar.HOUR, 9);

                return t.getTime();
        }

        private Date nextDay11Am() {
                Calendar t = (Calendar) today().clone();
                t.set(Calendar.AM_PM, Calendar.AM);
                t.set(Calendar.DATE, t.get(Calendar.DATE) + 1);
                t.set(Calendar.HOUR, 11);

                return t.getTime();
        }

        private Date fourDaysLater3pm() {
                Calendar t = (Calendar) today().clone();
                t.set(Calendar.AM_PM, Calendar.PM);
                t.set(Calendar.DATE, t.get(Calendar.DATE) + 4);
                t.set(Calendar.HOUR, 3);

                return t.getTime();
        }

        public ScheduleEvent getEvent() {
            System.out.println("Getting event: " + event.getId() + " " + event.getTitle());
                return event;
        }

        public void setEvent(ScheduleEvent event) {
            System.out.println("Setting event");
                this.event = event;
        }

        public void addEvent(ActionEvent actionEvent) {
            System.out.println("Adding event");
                if(event.getId() == null){
                        eventModel.addEvent(event);}
                else{
                        eventModel.updateEvent(event);
                }
                event = new DefaultScheduleEvent();
                System.out.println("");
        }

        public void onEventSelect(ScheduleEntrySelectEvent selectEvent) {
            System.out.println("Selected event");
                event = selectEvent.getScheduleEvent();
        }

        public void onDateSelect(DateSelectEvent selectEvent) {
            System.out.println("Selected date");
                event = new DefaultScheduleEvent("", selectEvent.getDate(), selectEvent.getDate());
        }

        public void onEventMove(ScheduleEntryMoveEvent event) {
            System.out.println("Moved event");
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Event moved", "Day delta:" + event.getDayDelta() + ", Minute delta:" + event.getMinuteDelta());

                addMessage(message);
        }

        public void onEventResize(ScheduleEntryResizeEvent event) {
            System.out.println("Resized event");
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Event resized", "Day delta:" + event.getDayDelta() + ", Minute delta:" + event.getMinuteDelta());

                addMessage(message);
        }

        private void addMessage(FacesMessage message) {
                FacesContext.getCurrentInstance().addMessage(null, message);
        }
}

A: Problem Solved:
Search in your Application for Menuitems or Components which uses Ajax. If you don't need it, disable Ajax with ajax="false" and your
 is displayed.
Source

A: Months ago, I learned the same as well, to use ajax="false" on pages where p:schedule exist, but if absolutely necessary, your page does 'not' need to disable AJAX (ajax="false").
My page below, renders a menu with where ajax="false", but also, it has p:calendar and p:commandButton's to update the month view of p:schedule.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <ui:composition>

        <pe:layoutPane position="north">
            <ui:include src="/orders/pf_BrowseLayoutPaneHeaderFacet.xhtml"/>

            <h:form id="ordersScheduleForm_north" >

                <ui:include src="/orders/pf_BrowseMenu.xhtml"/>

                <h:panelGrid columns="2" width="100%">
                    <h:panelGroup layout="block" style="text-align: left !important;" >
                        <h:panelGrid columns="3" cellspacing="5">
                            <h:outputText value="Select Date:" />

                        </h:panelGrid>
                    </h:panelGroup>

                    <h:panelGroup layout="block">
                        <h:panelGrid columns="2" width="100%">
                            <h:panelGroup style="text-align: left !important; font-size: larger !important;">
                                <h:outputText value="#{pf_ordersController.filterTripDateFrom}">
                                    <f:convertDateTime pattern="MMMM yyyy" />
                                </h:outputText>
                            </h:panelGroup>

                            <h:panelGroup layout="block" style="text-align: right !important;" >

                            </h:panelGroup>
                        </h:panelGrid>

                    </h:panelGroup>

                </h:panelGrid>

            </h:form>

        </pe:layoutPane>

        <pe:layoutPane position="center">

            <h:form id="ordersScheduleForm_center" >

            </h:form>

        </pe:layoutPane>

    </ui:composition>


text:
Q: Change the size of pushed viewcontroller I'm presenting a ViewController which has UINavigationController. Is it possible to change the size of whole NavigationViewController just like when showing UINavigationViewController in UIPopOver and the size can be handled with setContentSizeInPopOver. Right now I'm not using UIPopover but I want to change the size of pushed view controller. Setting the frame of UINavigationController of pushed controller in viewDidload isn't helping.

A: For changing the size of view controller that is to be presented u could use this one
   How to present a modal view controller with custom size in center?

A: Not tested.
Try changing the frame of the view controller view's superview to desired frame just before presenting the navigation controller. Remove all the auto re-sizing masks of the view.


text:
Q: How to use magento rest api for native mobile app's web service I have a magento website. Now i want to develop mobile app for this website. So for webservice i have created a custom module. In this module i have a controller called mobileApi. In this mobileApiController i am writing all webservice function. For an example getAllProducts().
Now, on the other hand i want to use magento rest api for access token and
Access token secret. If the access to rest api is valid then only my custom controller i.e. mobileApiController will return data.
I want the system to work like this,
At the time of App launch mobile app will call a webservice to authenticate the rest api access, and the webservice will return valid access token and
Access token secret.
After that on every webservice call it will first validate the rest api access, If access is valid then serve then serve the data otherwise shows authentication error.
I have developed everything and all is working fine, but the problem is at the time of App Launch, when i call the service to get access token and access token secret, magento system takes me to a page where it asks for authentication.
Screenshot (step 1)

After Login it shows me this page.
Screenshot (step 2)

Then if i authenticate the access then rest api get authenticated and returns access token and access token secret then webservice start serving the data.
But how do I manage this authentication from app? I need to skip these two step (step1 and step2).
I want to call the webservice to get the access token and access token secret at the app launch and right away get the access token and access token secret without these step 1 i.e. login and step 2 authorization.
Thanks in advance.


text:
Q: Pythonic way to create a dictionary by iterating I'm trying to write something that answers "what are the possible values in every column?"
I created a dictionary called all_col_vals and iterate from 1 to however many columns my dataframe has. However, when reading about this online, someone stated this looked too much like Java and the more pythonic way would be to use zip. I can't see how I could use zip here.
all_col_vals = {}
for index in range(RCSRdf.shape[1]):
    all_col_vals[RCSRdf.iloc[:,index].name] = set(RCSRdf.iloc[:,index])

The output looks like 'CFN Network': {nan, 'N521', 'N536', 'N401', 'N612', 'N204'}, 'Exam': {'EXRC', 'MXRN', 'HXRT', 'MXRC'} and shows all the possible values for that specific column. The key is the column name.

A: I think @piRSquared's comment is the best option, so I'm going to steal it as an answer and add some explanation.
Answer
Assuming you don't have duplicate columns, use the following:
{k : {*df[k]} for k in df}

Explanation
k represents a column name in df. You don't have to use the .columns attribute to access them because a pandas.DataFrame works similarly to a python dict
df[k] represents the series k
{*df[k]} unpacks the values from the series and places them in a set ({}) which only keeps distinct elements by definition (see definition of a set).
Lastly, using list comprehension to create the dict is faster than defining an empty dict and adding new keys to it via a for-loop.


text:
Q: Join two result in codeigniter I started a new project with codeigniter and I create three tables for users and posts and likes like this
user table has these records

*

*User_ID

*FullName

*UserName

post table has these records

*

*Post_ID

*Title

*User_ID

that user_id field save creator user_id
and like table

*

*Like_ID

*User_ID

*Post_ID

I want to join this three tables and I can do it but I need join two result like this and I don't know what can I do
  $this->db->select('*');
  $this->db->from('Post');
  $this->db->join('User', 'User.User_ID = Post.User_ID', 'left');
  $query = $this->db->get();
  return $query->result();

and this
  $this->db->select('*');
  $this->db->from('Like');
  $this->db->where('User_ID' = $id);
  $query = $this->db->get();
  return $query->result();

and then join these results with together
Please help me

A: You can join multiple tables in single codeigniter query
$this->db->select('*');
$this->db->from('Post');
$this->db->join('User', 'User.User_ID = Post.User_ID', 'left');
$this->db->join('Like','Like.Post_ID = Post.Post_ID AND User.User_ID = $id','left');
$query = $this->db->get();
return $query->result();

A: If I understand your question correctly, you would like to determine which posts the current user likes. The sql statement would look like sg like the following:
select p.*, u.*, l.user_id as like_user_id
from post p
inner join user u on u.user_id=p.user_id    -- I do not think you need a left join here
left join `like` l on p.post_id=l.post_id and l.user_id=$id

I the like table is left joined to the post table using the common post_id fields. In case l.user_id is null, then the current user does not like the post. Based on the above query and your 1st codeigniter code, you should be able to create the codeigniter version of this query.


text:
Q: Flask server could not handle non ascii characters I have wrriten a simple application using flask. Its main objective is to implement CLD2 (language detector) using post and get methods. It is working well for English but for any other language such Urdu, Arabic. It gives invalid results
Following is the corresponding script
# http://127.0.0.1:5000/cld2?text="Your input text string"
# OUTPUT ( It gives output as we done in CC)
#"585&URDU-99-1155"

from flask import Flask,abort,jsonify,request
from flask_restful import Resource, Api, reqparse
import cld2
from bs4 import BeautiflSoup
import sys
import urllib2, urllib
import re

reload(sys)
sys.setdefaultencoding('utf8')

app = Flask(__name__)
api = Api(app)

class HelloWorld(Resource):

    def cld2_states(self, txt):
        txt = txt.encode("utf8")

        isReliable, textBytesFound, details = cld2.detect(txt)
        outstr = str(textBytesFound)
        for item in details:  # Iterate 3 languages
            if item[0] != "Unknown":
                outstr += '&' + item[0] + '-' + str(item[2]) + '-' + str(int(item[3]))
        return outstr

    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('text', type=str)
        parser.add_argument('url', type=str)

        _dict =  dict(parser.parse_args())
        if _dict["text"] is not None:
            value = _dict["text"]
            print type(value)
            return self.cld2_states(value)

        return None

    def post(self):
        data = request.get_json(force=True)
        # print data
        predict_request = [data['content']][1]
        out = self.cld2_states(predict_request)

        return jsonify(score=out)

api.add_resource(HelloWorld, '/cld2')
if __name__ == '__main__':
    app.run(debug=True, port=6161, host='0.0.0.0')

If I give a query via get method, it give correct results but for same query in post method, it return just a number. But if text is in English then post also give correct result.
My client is a simple Java application then iterate over files and find their language one by one.

A: The problem might be with this line:
outstr = str(textBytesFound)

Instead of using str to convert from bytes to str, use str.decode(), like this:
outstr = textBytesFound.decode("utf-8")

(obviously if your text is not encoded with UTF-8, you need to tell Python the correct encoding to use)


text:
Q: PostgreSQL 11 - using format to assign to variable I have been awake for well beyond my schedule and I have been stuck with this issue for a long time, I don't even know what I am looking for to solve, but I wish to use format to insert values that I'll be using for column names, and then executing it... but it keeps giving me errors no matter how much I try changing it :c
Heres the part that im trying to do something that doesnt work, but i think you get the idea what im trying to achieve
    ratelimit := EXECUTE format('(SELECT %I
                      FROM users.ratelimits
                      WHERE user_id = $2)
                     ', $1);

and heres the full code for the brave
CREATE OR REPLACE FUNCTION users.consume_ratelimit(_name text,__user_id integer)
    RETURNS boolean
    LANGUAGE 'plpgsql'
    VOLATILE
    PARALLEL UNSAFE
    COST 100
AS $BODY$DECLARE
    ratelimit INTEGER;
    reset_timeout timestamptz;
    premium BOOLEAN;
BEGIN
    ratelimit := EXECUTE format('(SELECT %I
                      FROM users.ratelimits
                      WHERE user_id = $2)
                     ', $1);

    reset_timeout := EXECUTE format('(SELECT %I_refresh
                      FROM users.ratelimits
                      WHERE user_id = $2)
                     ', $1);

    premium := (SELECT users.is_premium($2));

    IF premium THEN
        RETURN TRUE;

    ELSIF reset_timeout <= NOW() THEN
        UPDATE users.ratelimits
        SET image_refresh = NOW() + '1 hour'::interval,
            image = DEFAULT
            WHERE user_id = $2;
        RAISE NOTICE 'reset';
        RETURN TRUE;

    ELSE
        IF ratelimit > 0 THEN
            EXECUTE format('UPDATE users.ratelimits
            SET %I = %I - 1
            WHERE user_id = $2', $1, $1);
            RAISE NOTICE 'decrement';
            RETURN TRUE;

        ELSIF ratelimit <= 0 THEN
            RAISE NOTICE 'out of credits';
            RETURN FALSE;

        ELSE
            EXECUTE format('INSERT INTO users.ratelimits(user_id) VALUES ($2)
            ON CONFLICT DO UPDATE SET
                %I = excluded.%I,
                %I_refresh = excluded.%I_refresh', $1, $1, $1, $1);
            RAISE NOTICE 'create';
            RETURN TRUE;

        END IF;
    END IF;
END;$BODY$;

A: As documented in the manual you need to use into together with EXECUTE to store the result into a variable. This can handle multiple columns/variables as well, so you only need a single EXECUTE to get both values.
For clarity you should reference parameters by name, not by position.
EXECUTE format('SELECT %I, %I_refresh
                FROM users.ratelimits WHERE user_id = $1'),
                _name, _name)
   USING __user_id
   INTO ratelimit, reset_timeout;

Note the $1 inside the string for format() is a parameter placeholder used when the SQL statement is executed, and will be replaced with the value of the variable specified in the USING clause.
Variable assignment is also more efficient without a SELECT:
premium := users.is_premium(__user_id);

A: It seems some_var := EXECUTE ... will not work. Additionally, params inside of an EXECUTE statement are not the same as those in the function - you need to supply them to the execute statement.
I have not tested this, but perhaps
-- q declared above as text

q := format('
  SELECT %I
  FROM users.ratelimits
  WHERE user_id = %s;
', $1, $2);

EXECUTE q INTO ratelimit;

will work? I also removed the parens from the query, those are unnecessary and may the problem themselves.
I have tested the function
CREATE OR REPLACE FUNCTION test_sum (a int, b int)
RETURNS int
AS $$
DECLARE
  q text;
  result int;
BEGIN
  q := FORMAT ('SELECT %s + %s', $1, $2);
  EXECUTE q INTO result;
  RETURN result;
END
$$ LANGUAGE plpgsql

and that does work. If my suggestion above does not work, perhaps you can use the above as a starting point.


text:
Q: Numpy Boolean Bitwise unexpected behavior I have a code which takes a numpy array of prices, and find discounts in desired range.
For some reason, the output is not as expected.
My code is:
# prices
prices = np.arange(5, (1-0.4-0.01)*5, -0.1)

# calculate discounts for each price
discounts_calculated =  (max(prices)-prices)/max(prices)

# choose prices in range of (10,30) percent discount
chosen_inds = (0.1<=discounts_calculated) & (discounts_calculated<=0.3)
chosen_discounts = discounts_calculated[ chosen_inds ]

# show output
print(prices)
print(discounts_calculated)
print(chosen_discounts)

and the output is:
[5.  4.9 4.8 4.7 4.6 4.5 4.4 4.3 4.2 4.1 4.  3.9 3.8 3.7 3.6 3.5 3.4 3.3
 3.2 3.1 3. ]
[0.   0.02 0.04 0.06 0.08 0.1  0.12 0.14 0.16 0.18 0.2  0.22 0.24 0.26
 0.28 0.3  0.32 0.34 0.36 0.38 0.4 ]
[0.12 0.14 0.16 0.18 0.2  0.22 0.24 0.26 0.28 0.3 ]

Whereas the expected output should include the .1 element at the last array:
[5.  4.9 4.8 4.7 4.6 4.5 4.4 4.3 4.2 4.1 4.  3.9 3.8 3.7 3.6 3.5 3.4 3.3
 3.2 3.1 3. ]
[0.   0.02 0.04 0.06 0.08 0.1  0.12 0.14 0.16 0.18 0.2  0.22 0.24 0.26
 0.28 0.3  0.32 0.34 0.36 0.38 0.4 ]
[0.1 0.12 0.14 0.16 0.18 0.2  0.22 0.24 0.26 0.28 0.3 ]

How can I change the code so that the bitwise comparison would work?


text:
Q: Getting the submatrix with maximum sum? Input: A 2-dimensional array NxN - Matrix - with positive and negative elements.Output: A submatrix of any size such that its summation is the maximum among all possible submatrices.
Requirement: Algorithm complexity to be of O(N^3)
History: With the help of the Algorithmist, Larry and a modification of Kadane's Algorithm, i managed to solve the problem partly which is determining the summation only - below in Java.
Thanks to Ernesto who managed to solve the rest of the problem which is determining the boundaries of the matrix i.e. top-left, bottom-right corners - below in Ruby.

A: Here is a Java version of Ernesto implementation with some modifications:
public int[][] findMaximumSubMatrix(int[][] matrix){
    int dim = matrix.length;
    //computing the vertical prefix sum for columns
    int[][] ps = new int[dim][dim];
    for (int i = 0; i < dim; i++) {
        for (int j = 0; j < dim; j++) {
            if (j == 0) {
                ps[j][i] = matrix[j][i];
            } else {
                ps[j][i] = matrix[j][i] + ps[j - 1][i];
            }
        }
    }

    int maxSum = matrix[0][0];
    int top = 0, left = 0, bottom = 0, right = 0;

    //Auxiliary variables
    int[] sum = new int[dim];
    int[] pos = new int[dim];
    int localMax;

    for (int i = 0; i < dim; i++) {
        for (int k = i; k < dim; k++) {
            // Kadane over all columns with the i..k rows
            reset(sum);
            reset(pos);
            localMax = 0;
            //we keep track of the position of the max value over each Kadane's execution
            // notice that we do not keep track of the max value, but only its position
            sum[0] = ps[k][0] - (i==0 ? 0 : ps[i-1][0]);
            for (int j = 1; j < dim; j++) {
                if (sum[j-1] > 0){
                    sum[j] = sum[j-1] + ps[k][j] - (i==0 ? 0 : ps[i-1][j]);
                    pos[j] = pos[j-1];
                }else{
                    sum[j] = ps[k][j] - (i==0 ? 0 : ps[i-1][j]);
                    pos[j] = j;
                }
                if (sum[j] > sum[localMax]){
                    localMax = j;
                }
            }//Kadane ends here

            if (sum[localMax] > maxSum){
                  /* sum[localMax] is the new max value
                    the corresponding submatrix goes from rows i..k.
                     and from columns pos[localMax]..localMax
                     */
                maxSum = sum[localMax];
                top = i;
                left = pos[localMax];
                bottom = k;
                right = localMax;
            }
        }
    }
    System.out.println("Max SubMatrix determinant = " + maxSum);
    //composing the required matrix
    int[][] output = new int[bottom - top + 1][right - left + 1];
    for(int i = top, k = 0; i <= bottom; i++, k++){
        for(int j = left, l = 0; j <= right ; j++, l++){
            output[k][l] = matrix[i][j];
        }
    }
    return output;
}

private void reset(int[] a) {
    for (int index = 0; index < a.length; index++) {
        a[index] = 0;
    }
}

A: Here's an explanation to go with the posted code. There are two key tricks to make this work efficiently: (I) Kadane's algorithm and (II) using prefix sums. You also need to (III) apply the tricks to the matrix.
Part I: Kadane's algorithm
Kadane's algorithm is a way to find a contiguous subsequence with maximum sum. Let's start with a brute force approach for finding the max contiguous subsequence and then consider optimizing it to get Kadane's algorithm.
Suppose you have the sequence:
-1,  2,  3, -2

For the brute force approach, walk along the sequence generating all possible subsequences as shown below. Considering all possibilities, we can start, extend, or end a list with each step.
At index 0, we consider appending the -1
-1,  2,  3, -2
 ^
Possible subsequences:
-1   [sum -1]

At index 1, we consider appending the 2
-1,  2,  3, -2
     ^
Possible subsequences:
-1 (end)      [sum -1]
-1,  2        [sum  1]
 2            [sum  2]

At index 2, we consider appending the 3
-1,  2,  3, -2
         ^
Possible subsequences:
-1, (end)       [sum -1]
-1,  2 (end)    [sum -1]
 2 (end)        [sum 2]
-1,  2,  3      [sum 4]
 2,  3          [sum 5]
 3              [sum 3]

At index 3, we consider appending the -2
-1,  2,  3, -2
             ^
Possible subsequences:
-1, (end)          [sum -1]
-1,  2 (end)       [sum  1]
 2 (end)           [sum  2]
-1,  2  3 (end)    [sum  4]
 2,  3 (end)       [sum  5]
 3, (end)          [sum  3]
-1,  2,  3, -2     [sum  2]
 2,  3, -2         [sum  3]
 3, -2             [sum  1]
-2                 [sum -2]

For this brute force approach, we finally pick the list with the best sum, (2, 3), and that's the answer. However, to make this efficient, consider that you really don't need to keep every one of the lists. Out of the lists that have not ended, you only need to keep the best one, the others cannot do any better. Out of the lists that have ended, you only might need to keep the best one, and only if it's better than ones that have not ended.
So, you can keep track of what you need with just a position array and a sum array. The position array is defined like this: position[r] = s keeps track of the list which ends at r and starts at s. And, sum[r] gives a sum for the subsequence ending at index r. This is optimized approach is Kadane's algorithm.
Running through the example again keeping track of our progress this way:
At index 0, we consider appending the -1
-1,  2,  3, -2
 ^
We start a new subsequence for the first element.
position[0] = 0
sum[0] = -1

At index 1, we consider appending the 2
-1,  2,  3, -2
     ^
We choose to start a new subsequence because that gives a higher sum than extending.
position[0] = 0      sum[0] = -1
position[1] = 1      sum[1] = 2

At index 2, we consider appending the 3
-1,  2,  3, -2
         ^
We choose to extend a subsequence because that gives a higher sum than starting a new one.
position[0] = 0      sum[0] = -1
position[1] = 1      sum[1] = 2
position[2] = 1      sum[2] = 5

Again, we choose to extend because that gives a higher sum that starting a new one.
-1,  2,  3, -2
             ^
position[0] = 0      sum[0] = -1
position[1] = 1      sum[1] = 2
position[2] = 1      sum[2] = 5
positions[3] = 3     sum[3] = 3

Again, the best sum is 5 and the list is from index 1 to index 2, which is (2, 3).
Part II: Prefix sums
We want to have a way to compute the sum along a row, for any start point to any endpoint. I want to compute that sum in O(1) time rather than just adding, which takes O(m) time where m is the number of elements in the sum. With some precomputing, this can be achieved. Here's how. Suppose you have a matrix:
a   d   g
b   e   h
c   f   i

You can precompute this matrix:
a      d      g
a+b    d+e    g+h
a+b+c  d+e+f  g+h+i

Once that is done you can get the sum running along any column from any start to endpoint in the column just by subtracting two values.
Part III: Bringing tricks together to find the max submatrix
Assume that you know the top and bottom row of the max submatrix. You could do this:

*

*Ignore rows above your top row and ignore rows below your bottom
row.

*With what matrix remains, consider the using sum of each column to
form a sequence (sort of like a row that represents multiple rows).
(You can compute any element of this sequence rapidly with the prefix
sums approach.)

*Use Kadane's approach to figure out best subsequence in this
sequence. The indexes you get will tell you the left and right
positions of the best submatrix.

Now, what about actually figuring out the top and bottom row? Just try all possibilities. Try putting the top anywhere you can and putting the bottom anywhere you can, and run the Kadane-base procedure described previously for every possibility. When you find a max, you keep track of the top and bottom position.
Finding the row and column takes O(M^2) where M is the number of rows. Finding the column takes O(N) time where N is the number of columns. So total time is O(M^2 * N). And, if M=N, the time required is O(N^3).

A: With the help of the Algorithmist and Larry and a modification of Kadane's Algorithm, here is my solution:
int dim = matrix.length;
    //computing the vertical prefix sum for columns
    int[][] ps = new int[dim][dim];
    for (int i = 0; i < dim; i++) {
        for (int j = 0; j < dim; j++) {
            if (j == 0) {
                ps[j][i] = matrix[j][i];
            } else {
                ps[j][i] = matrix[j][i] + ps[j - 1][i];
            }
        }
    }
    int maxSoFar = 0;
    int min , subMatrix;
    //iterate over the possible combinations applying Kadane's Alg.
    for (int i = 0; i < dim; i++) {
        for (int j = i; j < dim; j++) {
            min = 0;
            subMatrix = 0;
            for (int k = 0; k < dim; k++) {
                if (i == 0) {
                    subMatrix += ps[j][k];
                } else {
                    subMatrix += ps[j][k] - ps[i - 1 ][k];
                }
                if(subMatrix < min){
                    min = subMatrix;
                }
                if((subMatrix - min) > maxSoFar){
                    maxSoFar = subMatrix - min;
                }
            }
        }
    }

The only thing left is to determine the submatrix elements, i.e: the top left and the bottom right corner of the submatrix. Anyone suggestion?

A: About recovering the actual submatrix, and not just the maximum sum, here's what I got. Sorry I do not have time to translate my code to your java version, so I'm posting my Ruby code with some comments in the key parts
def max_contiguous_submatrix_n3(m)
  rows = m.count
  cols = rows ? m.first.count : 0

  vps = Array.new(rows)
  for i in 0..rows
    vps[i] = Array.new(cols, 0)
  end

  for j in 0...cols
    vps[0][j] = m[0][j]
    for i in 1...rows
      vps[i][j] = vps[i-1][j] + m[i][j]
    end
  end

  max = [m[0][0],0,0,0,0] # this is the result, stores [max,top,left,bottom,right]
  # these arrays are used over Kadane
  sum = Array.new(cols) # obvious sum array used in Kadane
  pos = Array.new(cols) # keeps track of the beginning position for the max subseq ending in j

  for i in 0...rows
    for k in i...rows
      # Kadane over all columns with the i..k rows
      sum.fill(0) # clean both the sum and pos arrays for the upcoming Kadane
      pos.fill(0)
      local_max = 0 # we keep track of the position of the max value over each Kadane's execution
      # notice that we do not keep track of the max value, but only its position
      sum[0] = vps[k][0] - (i==0 ? 0 : vps[i-1][0])
      for j in 1...cols
        value = vps[k][j] - (i==0 ? 0 : vps[i-1][j])
        if sum[j-1] > 0
          sum[j] = sum[j-1] + value
          pos[j] = pos[j-1]
        else
          sum[j] = value
          pos[j] = j
        end
        if sum[j] > sum[local_max]
          local_max = j
        end
      end
      # Kadane ends here

      # Here's the key thing
      # If the max value obtained over the past Kadane's execution is larger than
      # the current maximum, then update the max array with sum and bounds
      if sum[local_max] > max[0]
        # sum[local_max] is the new max value
        # the corresponding submatrix goes from rows i..k.
        # and from columns pos[local_max]..local_max
        # the array below contains [max_sum,top,left,bottom,right]
        max = [sum[local_max], i, pos[local_max], k, local_max]
      end
    end
  end

  return max # return the array with [max_sum,top,left,bottom,right]
end

Some notes for clarification:
I use an array to store all the values pertaining to the result for convenience. You can just use five standalone variables: max, top, left, bottom, right. It's just easier to assign in one line to the array and then the subroutine returns the array with all the needed information.
If you copy and paste this code in a text-highlight-enabled editor with Ruby support you'll obviously understand it better. Hope this helps!

A: this is my implementation of 2D Kadane algorithm. I think it is more clear. The concept is based on just kadane algorithm. The first and second loop of the main part (that is in the bottom of the code) is to pick every combination of the rows and 3rd loop is to use 1D kadane algorithm by every following column sum (that can be computed in const time because of preprocessing of matrix by subtracting values from two picked (from combintation) rows). Here is the code:
    int [][] m = {
            {1,-5,-5},
            {1,3,-5},
            {1,3,-5}
    };
    int N = m.length;

    // summing columns to be able to count sum between two rows in some column in const time
    for (int i=0; i<N; ++i)
        m[0][i] = m[0][i];
    for (int j=1; j<N; ++j)
        for (int i=0; i<N; ++i)
            m[j][i] = m[j][i] + m[j-1][i];

    int total_max = 0, sum;
    for (int i=0; i<N; ++i) {
        for (int k=i; k<N; ++k) { //for each combination of rows
            sum = 0;
            for (int j=0; j<N; j++) {       //kadane algorithm for every column
                sum += i==0 ? m[k][j] : m[k][j] - m[i-1][j]; //for first upper row is exception
                total_max = Math.max(sum, total_max);
            }
        }
    }

    System.out.println(total_max);

A: There are already plenty of answers, but here is another Java implementation I wrote.  It compares 3 solutions:

*

*Naïve (brute force) - O(n^6) time

*The obvious DP solution - O(n^4) time and O(n^3) space

*The more clever DP solution based on Kadane's algorithm - O(n^3) time and O(n^2) space

There are sample runs for n = 10 thru n = 70 in increments of 10 with a nice output comparing run time and space requirements.

Code:
public class MaxSubarray2D {

    static int LENGTH;
    final static int MAX_VAL = 10;

    public static void main(String[] args) {

        for (int i = 10; i <= 70; i += 10) {
            LENGTH = i;

            int[][] a = new int[LENGTH][LENGTH];

            for (int row = 0; row < LENGTH; row++) {
                for (int col = 0; col < LENGTH; col++) {
                    a[row][col] = (int) (Math.random() * (MAX_VAL + 1));
                    if (Math.random() > 0.5D) {
                        a[row][col] = -a[row][col];
                    }
                    //System.out.printf("%4d", a[row][col]);
                }
                //System.out.println();
            }
            System.out.println("N = " + LENGTH);
            System.out.println("-------");

            long start, end;
            start = System.currentTimeMillis();
            naiveSolution(a);
            end = System.currentTimeMillis();
            System.out.println("   run time: " + (end - start) + " ms   no auxiliary space requirements");
            start = System.currentTimeMillis();
            dynamicProgammingSolution(a);
            end = System.currentTimeMillis();
            System.out.println("   run time: " + (end - start) + " ms   requires auxiliary space for "
                    + ((int) Math.pow(LENGTH, 4)) + " integers");
            start = System.currentTimeMillis();
            kadane2D(a);
            end = System.currentTimeMillis();
            System.out.println("   run time: " + (end - start) + " ms   requires auxiliary space for " +
                    + ((int) Math.pow(LENGTH, 2)) + " integers");
            System.out.println();
            System.out.println();
        }
    }

    // O(N^2) !!!
    public static void kadane2D(int[][] a) {
        int[][] s = new int[LENGTH + 1][LENGTH]; // [ending row][sum from row zero to ending row] (rows 1-indexed!)
        for (int r = 0; r < LENGTH + 1; r++) {
            for (int c = 0; c < LENGTH; c++) {
                s[r][c] = 0;
            }
        }
        for (int r = 1; r < LENGTH + 1; r++) {
            for (int c = 0; c < LENGTH; c++) {
                s[r][c] = s[r - 1][c] + a[r - 1][c];
            }
        }
        int maxSum = Integer.MIN_VALUE;
        int maxRowStart = -1;
        int maxColStart = -1;
        int maxRowEnd = -1;
        int maxColEnd = -1;
        for (int r1 = 1; r1 < LENGTH + 1; r1++) { // rows 1-indexed!
            for (int r2 = r1; r2 < LENGTH + 1; r2++) { // rows 1-indexed!
                int[] s1 = new int[LENGTH];
                for (int c = 0; c < LENGTH; c++) {
                    s1[c] = s[r2][c] - s[r1 - 1][c];
                }
                int max = 0;
                int c1 = 0;
                for (int c = 0; c < LENGTH; c++) {
                    max = s1[c] + max;
                    if (max <= 0) {
                        max = 0;
                        c1 = c + 1;
                    }
                    if (max > maxSum) {
                        maxSum = max;
                        maxRowStart = r1 - 1;
                        maxColStart = c1;
                        maxRowEnd = r2 - 1;
                        maxColEnd = c;
                    }
                }
            }
        }

        System.out.print("KADANE SOLUTION |   Max sum: " + maxSum);
        System.out.print("   Start: (" + maxRowStart + ", " + maxColStart +
                ")   End: (" + maxRowEnd + ", " + maxColEnd + ")");
    }

    // O(N^4) !!!
    public static void dynamicProgammingSolution(int[][] a) {
        int[][][][] dynTable = new int[LENGTH][LENGTH][LENGTH + 1][LENGTH + 1]; // [row][col][height][width]
        int maxSum = Integer.MIN_VALUE;
        int maxRowStart = -1;
        int maxColStart = -1;
        int maxRowEnd = -1;
        int maxColEnd = -1;

        for (int r = 0; r < LENGTH; r++) {
            for (int c = 0; c < LENGTH; c++) {
                for (int h = 0; h < LENGTH + 1; h++) {
                    for (int w = 0; w < LENGTH + 1; w++) {
                        dynTable[r][c][h][w] = 0;
                    }
                }
            }
        }

        for (int r = 0; r < LENGTH; r++) {
            for (int c = 0; c < LENGTH; c++) {
                for (int h = 1; h <= LENGTH - r; h++) {
                    int rowTotal = 0;
                    for (int w = 1; w <= LENGTH - c; w++) {
                        rowTotal += a[r + h - 1][c + w - 1];
                        dynTable[r][c][h][w] = rowTotal + dynTable[r][c][h - 1][w];
                    }
                }
            }
        }

        for (int r = 0; r < LENGTH; r++) {
            for (int c = 0; c < LENGTH; c++) {
                for (int h = 0; h < LENGTH + 1; h++) {
                    for (int w = 0; w < LENGTH + 1; w++) {
                        if (dynTable[r][c][h][w] > maxSum) {
                            maxSum = dynTable[r][c][h][w];
                            maxRowStart = r;
                            maxColStart = c;
                            maxRowEnd = r + h - 1;
                            maxColEnd = c + w - 1;
                        }
                    }
                }
            }
        }

        System.out.print("    DP SOLUTION |   Max sum: " + maxSum);
        System.out.print("   Start: (" + maxRowStart + ", " + maxColStart +
                ")   End: (" + maxRowEnd + ", " + maxColEnd + ")");
    }

    // O(N^6) !!!
    public static void naiveSolution(int[][] a) {
        int maxSum = Integer.MIN_VALUE;
        int maxRowStart = -1;
        int maxColStart = -1;
        int maxRowEnd = -1;
        int maxColEnd = -1;

        for (int rowStart = 0; rowStart < LENGTH; rowStart++) {
            for (int colStart = 0; colStart < LENGTH; colStart++) {
                for (int rowEnd = 0; rowEnd < LENGTH; rowEnd++) {
                    for (int colEnd = 0; colEnd < LENGTH; colEnd++) {
                        int sum = 0;
                        for (int row = rowStart; row <= rowEnd; row++) {
                            for (int col = colStart; col <= colEnd; col++) {
                                sum += a[row][col];
                            }
                        }
                        if (sum > maxSum) {
                            maxSum = sum;
                            maxRowStart = rowStart;
                            maxColStart = colStart;
                            maxRowEnd = rowEnd;
                            maxColEnd = colEnd;
                        }
                    }
                }
            }
        }

        System.out.print(" NAIVE SOLUTION |   Max sum: " + maxSum);
        System.out.print("   Start: (" + maxRowStart + ", " + maxColStart +
                ")   End: (" + maxRowEnd + ", " + maxColEnd + ")");
    }

}

A: I am going to post an answer here and can add actual c++ code if it is requested because I had recently worked through this. Some rumors of a divide and conqueror that can solve this in O(N^2) are out there but I haven't seen any code to support this. In my experience the following is what I have found.
    O(i^3j^3) -- naive brute force method
    o(i^2j^2) -- dynamic programming with memoization
    O(i^2j)   -- using max contiguous sub sequence for an array

if ( i == j )
O(n^6) -- naive
O(n^4) -- dynamic programming
O(n^3) -- max contiguous sub sequence

A: Have a look at JAMA package; I believe it will make your life easier.

A: Here is the C# solution. Ref: http://www.algorithmist.com/index.php/UVa_108
public static MaxSumMatrix FindMaxSumSubmatrix(int[,] inMtrx)
{
    MaxSumMatrix maxSumMtrx = new MaxSumMatrix();

    // Step 1. Create SumMatrix - do the cumulative columnar summation
    // S[i,j] = S[i-1,j]+ inMtrx[i-1,j];
    int m = inMtrx.GetUpperBound(0) + 2;
    int n = inMtrx.GetUpperBound(1)+1;
    int[,] sumMatrix = new int[m, n];

    for (int i = 1; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            sumMatrix[i, j] = sumMatrix[i - 1, j] + inMtrx[i - 1, j];
        }
    }

    PrintMatrix(sumMatrix);

    // Step 2. Create rowSpans starting each rowIdx. For these row spans, create a 1-D array r_ij
    for (int x = 0; x < n; x++)
    {
        for (int y = x; y < n; y++)
        {
            int[] r_ij = new int[n];

            for (int k = 0; k < n; k++)
            {
                r_ij[k] = sumMatrix[y + 1,k] - sumMatrix[x, k];
            }

            // Step 3. Find MaxSubarray of this r_ij. If the sum is greater than the last recorded sum =>
            //          capture Sum, colStartIdx, ColEndIdx.
            //          capture current x as rowTopIdx, y as rowBottomIdx.
            MaxSum currMaxSum = KadanesAlgo.FindMaxSumSubarray(r_ij);

            if (currMaxSum.maxSum > maxSumMtrx.sum)
            {
                maxSumMtrx.sum = currMaxSum.maxSum;
                maxSumMtrx.colStart = currMaxSum.maxStartIdx;
                maxSumMtrx.colEnd = currMaxSum.maxEndIdx;
                maxSumMtrx.rowStart = x;
                maxSumMtrx.rowEnd = y;
            }
        }
    }

    return maxSumMtrx;
}

public static void PrintMatrix(int[,] matrix)
{
    int endRow = matrix.GetUpperBound(0);
    int endCol = matrix.GetUpperBound(1);
    PrintMatrix(matrix, 0, endRow, 0, endCol);
}

public static void PrintMatrix(int[,] matrix, int startRow, int endRow, int startCol, int endCol)
{
    StringBuilder sb = new StringBuilder();
    for (int i = startRow; i <= endRow; i++)
    {
        sb.Append(Environment.NewLine);
        for (int j = startCol; j <= endCol; j++)
        {
            sb.Append(string.Format("{0}  ", matrix[i,j]));
        }
    }

    Console.WriteLine(sb.ToString());
}

// Given an NxN matrix of positive and negative integers, write code to find the sub-matrix with the largest possible sum
public static MaxSum FindMaxSumSubarray(int[] inArr)
{
    int currMax = 0;
    int currStartIndex = 0;
    // initialize maxSum to -infinity, maxStart and maxEnd idx to 0.

    MaxSum mx = new MaxSum(int.MinValue, 0, 0);

    // travers through the array
    for (int currEndIndex = 0; currEndIndex < inArr.Length; currEndIndex++)
    {
        // add element value to the current max.
        currMax += inArr[currEndIndex];

        // if current max is more that the last maxSum calculated, set the maxSum and its idx
        if (currMax > mx.maxSum)
        {
            mx.maxSum = currMax;
            mx.maxStartIdx = currStartIndex;
            mx.maxEndIdx = currEndIndex;
        }

        if (currMax < 0) // if currMax is -ve, change it back to 0
        {
            currMax = 0;
            currStartIndex = currEndIndex + 1;
        }
    }

    return mx;
}

struct MaxSum
{
    public int maxSum;
    public int maxStartIdx;
    public int maxEndIdx;

    public MaxSum(int mxSum, int mxStart, int mxEnd)
    {
        this.maxSum = mxSum;
        this.maxStartIdx = mxStart;
        this.maxEndIdx = mxEnd;
    }
}

class MaxSumMatrix
{
    public int sum = int.MinValue;
    public int rowStart = -1;
    public int rowEnd = -1;
    public int colStart = -1;
    public int colEnd = -1;
}

A: Here is my solution. It's O(n^3) in time and O(n^2) space.
https://gist.github.com/toliuweijing/6097144
// 0th O(n) on all candidate bottoms @B.
// 1th O(n) on candidate tops @T.
// 2th O(n) on finding the maximum @left/@right match.
int maxRect(vector<vector<int> >& mat) {
    int n               = mat.size();
    vector<vector<int> >& colSum = mat;

    for (int i = 1 ; i < n ; ++i)
    for (int j = 0 ; j < n ; ++j)
        colSum[i][j] += colSum[i-1][j];

    int optrect = 0;
    for (int b = 0 ; b < n ; ++b) {
        for (int t = 0 ; t <= b ; ++t) {
            int minLeft = 0;
            int rowSum[n];
            for (int i = 0 ; i < n ; ++i) {
                int col = t == 0 ? colSum[b][i] : colSum[b][i] - colSum[t-1][i];
                rowSum[i] = i == 0? col : col + rowSum[i-1];
                optrect = max(optrect, rowSum[i] - minLeft);
                minLeft = min(minLeft, rowSum[i]);
            }
        }
    }

    return optrect;
}

A: I would just parse the NxN array removing the -ves whatever remains is the highest sum of a sub matrix.
The question doesn't say you have to leave the original matrix intact or that the order matters.


text:
Q: Compute infinite sum of modified Bessel functions and Cos I have encountered the expression
$$\sum_{n >0} K_0(2 \pi \rho n) \cos(2\pi n z)\, ,$$
for which I would like to obtain an explicit, closed expression (that means for me getting rid of any infinite sum). $K_0$ is the $0^{\rm th}$ modified Bessel function of second kind, $\rho \in \mathbb{R}^+$ and $z \in \mathbb R$. I didn't find a closed expression for this quantity in the literature up to now. Does anybody have a clue how to simplify this expression?

A: $$ K_0(2\pi \rho n)=\int_{0}^{+\infty}\frac{\cos(2\pi\rho n t)}{\sqrt{t^2+1}}\,dt=\int_{0}^{+\infty}\frac{\cos(2\pi nt)}{\sqrt{t^2+\rho^2}}\,dt=\int_{0}^{+\infty}\frac{t\sin(2\pi nt)}{2\pi n(t^2+\rho^2)^{3/2}}\,dt $$
hence by multiplying both sides by $\cos(2\pi nz)$ and summing over $n\geq 1$, by the Fourier series of the sawtooth wave
$$ \sum_{n\geq 1}\frac{\sin(2\pi n\theta)}{2\pi n}=\frac{1}{4}-\frac{\{\theta\}}{2} $$
we get
$$ \sum_{n\geq 1}K_0(2\pi \rho n)\cos(2\pi n z)=\int_{0}^{+\infty}\frac{t}{(t^2+\rho^2)^{3/2}}\cdot\frac{\{t-z\}-\{t+z\}}{4}\,dt$$
hence the LHS equals zero if $z\in\frac{1}{2}\mathbb{Z}$ and it is bounded by $\frac{1}{2\rho}$ in absolute value, for any $\rho>0$.
Similar series arise from the application of the Voronoi summation formula.
I recommend these notes from J. Bell as a starting point for further investigations.


text:
Q: Display test parameters input values unabridged in Visual Studio Is there a way to get Visual Studio (2017 Enterprise) to show all values of input parameters with which the test was launched?
In the output window, there are just three dots after certain length, just as in Test explorer (which I have to drag over 2 monitors to see that and the Copy All button there should be named Copy some).
Right now I see in the output and test explorer:
27/05/2019 12:55:29 Error] [xUnit.net 00:00:03.9604849]     SomeNamespace.SomeTestName(sut: SomeClass { }, someString: "spz5cf1f13d-6e3f-4f86-9a6a-5bc4cf9d0fca", foo: Foo { SomeBool = True, SomeId = 138, SomeString = "Duvodf6d90c61-f090-4f22-9e2e-37e2062bb848", SomeString = "ESSKa62ce76d-d56a-40d8-904a-fef1884ac86a", ExtensionData = null, ... }) [FAIL]

I'd like to see all values within Foo class, not "...".
I tried the "Test" options in VS, but nothing in there influences this (including logging level).
Test input is generated by AutoFixture. Sometimes the test passes, sometimes it fails.
Also it is integration test, which contacts web service, which doesn't throw very nice exceptions and basically just tells me "Somehting is wrong".
If I invoke test in debuger enough times, I'll have example o failing input, but there should be an easier way.

A: Apparenlty you need implement ToString in test parameters. The Foo class in question was generated DTO, some component (xUnit?) generated its string representation via reflection with limited length and that was displayed in test explorer and output window.
Once you implement proper ToString, Test Explorer is still showing abriged text, but Output window contains whole result of ToString.


text:
Q: What Layout to use for JavaFx I've been experimenting with different layouts in order to recreate Brandi's Bagel House

However I just can't figure out what layout is being used here.
So far I've tried BorderPane, FlowPane, GridPane, HBox and VBox but I still don't get the correct layout. I'm not allowed to implement any Swing or AWT. It has to be pure JavaFX and I'm not allowed to use any GUI builder like WindowBuilder. Any tip, hints or advice to recreate this [Swing] GUI layout in JavaFX?

A: You have [an image of] a Swing GUI and you want to convert it to JavaFX.
You need a combination of layouts. For the root of the node graph, use a BorderPane.

*

*The top node is a Label but since you want that Label centered, you need to place it in a HBox.

*The left node is the Bagel pane. The RadioButtons are placed in a VBox.

*The center node is the Toppings pane. The CheckBoxes are placed in a VBox.

*The right node is the Coffee pane. The RadioButtons are placed in a VBox.

*The bottom node contains the Buttons. Since you want the Buttons centered, you need to place them in a HBox.

The below code demonstrates. Note that the code for class BorderedTitledPane comes from the accepted answer to this question: GroupBox / TitledBorder in JavaFX 2?
(Since JavaFX does not have a TitledBorder as Swing does.)
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class OrdaCalc extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        BorderPane root = new BorderPane();
        Label label = new Label("Welcome to Brandi's Bagel House");
        HBox labelHBox = new HBox(label);
        labelHBox.setAlignment(Pos.CENTER);
        root.setTop(labelHBox);
        root.setLeft(createLeftPane());
        root.setCenter(createCenterPane());
        root.setRight(createRightPane());
        root.setBottom(createBottomPane());
        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private HBox createBottomPane() {
        Button calculate = new Button("Calculate");
        Button exit = new Button("Exit");
        HBox buttonsHBox = new HBox(10.0d, calculate, exit);
        buttonsHBox.setAlignment(Pos.CENTER);
        return buttonsHBox;
    }

    private BorderedTitledPane createCenterPane() {
        CheckBox creamCheese = new CheckBox("Cream Cheese");
        CheckBox butter = new CheckBox("Butter");
        CheckBox peachJelly = new CheckBox("Peach Jelly");
        CheckBox blueberryJam = new CheckBox("Blueberry Jam");
        VBox vBox = new VBox(5.0d, creamCheese, butter, peachJelly, blueberryJam);
        BorderedTitledPane center = new BorderedTitledPane("Toppings", vBox);
        return center;
    }

    private BorderedTitledPane createLeftPane() {
        RadioButton white = new RadioButton("White");
        RadioButton wheat = new RadioButton("Wheat");
        ToggleGroup group = new ToggleGroup();
        group.getToggles().addAll(white, wheat);
        VBox vBox = new VBox(30.0d, white, wheat);
        BorderedTitledPane left = new BorderedTitledPane("Bagel", vBox);
        return left;
    }

    private BorderedTitledPane createRightPane() {
        RadioButton none = new RadioButton("None");
        RadioButton regular = new RadioButton("Regular");
        RadioButton decaf = new RadioButton("Decaf");
        RadioButton cappuccino = new RadioButton("Cappuccino");
        ToggleGroup group = new ToggleGroup();
        group.getToggles().addAll(none, regular, decaf, cappuccino);
        VBox vBox = new VBox(5.0d, none, regular, decaf, cappuccino);
        BorderedTitledPane right = new BorderedTitledPane("Coffee", vBox);
        return right;
    }

    public static void main(String[] args) {
        launch(args);
    }
}

class BorderedTitledPane extends StackPane {
    BorderedTitledPane(String titleString, Node content) {
        Label title = new Label(" " + titleString + " ");
        title.getStyleClass().add("bordered-titled-title");
        StackPane.setAlignment(title, Pos.TOP_CENTER);

        StackPane contentPane = new StackPane();
        content.getStyleClass().add("bordered-titled-content");
        contentPane.getChildren().add(content);

        getStyleClass().add("bordered-titled-border");
        getChildren().addAll(title, contentPane);
    }
}

Here is file application.css which is located in the same package as class OrdaCalc.
.bordered-titled-title {
  -fx-background-color: white;
  -fx-translate-y: -16;
}

.bordered-titled-border {
  -fx-content-display: top;
  -fx-border-insets: 20 15 15 15;
  -fx-background-color: white;
  -fx-border-color: black;
  -fx-border-width: 2;
}

.bordered-titled-content {
  -fx-padding: 26 10 10 10;
}

Here is a screen capture.


text:
Q: Play too much sound together bug To play multi sound together, i found that i can use WMNLib reference, but when i try to play lots of sound togeter, like this:
static void Main(string[] args)
    {
        for (int i = 0; i< 100; i++)
        {
            var S = new WMPLib.WindowsMediaPlayer();
            S.URL = @"E:\Music\09 - Whod Have Known.mp3";
        }
        Console.ReadLine();
    }

program get bug and cannot play anymore. At my computer, it stop at i = 70, but can i really let the nummer much, much bigger?


text:
Q: Remove the style for all the rows in kendo grid My kendo grid is rendered as
              <tr class="k-master-row" data-uid="e232f2a2-7a9c-496b-bf78-bf56902c11a5" style="background-color: rgb(255, 255, 255);">

all rows are rendered with the same style. How to remove the above style for all rows ?

A: added this in onDataBound event, it removed the style.
            $('tr').removeAttr('style');


text:
Q: How to install github.com/ioi/isolate on Ubuntu I recently tried to make a C++ judge and heard about a tool called "Isolate" (available here):

Run program within a sandbox, so that it cannot communicate with the outside world and its resource consumption is limited. This can be used for example in a programming contest to run untrusted programs submitted by contestants in a controlled environment.

I'm not quite sure how to install it onto my computer (I'm using Ubuntu 20.04), though, and don't understand the steps from the user manual's Installation process.

A: To install you need to open terminal and type:
sudo apt-get update
sudo apt-get install libcap-dev asciidoc-base
cd ~/Downloads
git clone https://github.com/ioi/isolate.git
cd isolate
make
sudo make install

Then follow its local help about usage.


text:
Q: get the string resources dynamic for a question app I am developing a question app. I got some questions in my string resource file. Each time a user touches the textview it changes the question.
I have all the questions stored in an array, but I don't think this is very efficient.
            max_Fragen = FragenBeginner.length - 1;
            min_Fragen = 0;
            //Fragen Nummer
            randomFrage = rand.nextInt((max_Fragen - min_Fragen) + 1) + min_Fragen;
            fragekatalog = getResources().getString(R.string.fragen_FragenBeginner_ + randomFrage);
            frage.setText(fragekatalog);

A: You can use
public static int getStringIdentifier(Context context, String name) {
    return context.getResources().getIdentifier(name, "string", context.getPackageName());
}

to use a variable as a string identifier.


text:
Q: Arango/Foxx server static file After look though the Arango doc's could not find clear as to how to server a html file. This is the only case where I planning using Arango to server a file as Nginx does much better job but Arango hold the data need to known if this page should be legal.
controller.get('/:id', function (req, res){
  var id = req.urlParameters.id;
  if(res.json(db.tire_user.byExample({"uid":id}).toArray()[0]);){
      //here needs to server the static html file
  }
})
.pathParam('id', userIdSchema);

A: Currently the proposed way is to load the contents of the file from disk using the fs module:
https://docs.arangodb.com/ModuleFs/index.html


text:
Q: What is really happening when we do substitution in math Consider a toy case. Suppose we have a+b=10. This basically informs us a relation between two unknown variables a and b, however there is not enough information for us to tell what values do a and b take.
Now suppose we have another piece of information a=4. The standard way of combining the two pieces is by substitution into a+b=10 and we get 4+b=10. Then through math manipulation we can conclude b=6.
But what exactly is happening when we do the substitution? Intuitively if when we substitute a math object in a math statement with another equivalent object the resulting new math statement should be equivalent as before. Is there a better or simpler explanation for this? And is there an axiom?

A: The "equation":

$a + b =10$

is ambiguous. What are we asserting, when stating it ?
Probably not: $\forall a \ \forall b \ (a+b=10)$, which is quite useless.
Stating the problem as: "given $a + b =10$ and let $a=4$, find $b$", sounds like:

check if $\exists b \ (a+b=10)$ is satisfiable in a certain domain (like e.g. $\mathbb N$) when $a=4$.

In this case the question is meaningful; we substitute $4$ for $a$ (foramlly: we instantiate a free variable with a value) and get: $\exists b \ (4+b=10)$ which is satisfied in $\mathbb N$ for $b=6$.

In a formal way, we have to use (as per comment above) the first-order logic with equality substitution axiom (for formulas):

$x=y \to (\varphi \to \varphi')$

where $\varphi'$ is obtained by replacing any number (not necessarily all) of the free occurrences of $x$ in $\varphi$ with $y$.
To be pedantic, we have first to prove (by induction) the "generalized form":

$t_1=t_2 \to (\varphi \to \varphi')$

with $t_i$ terms, because $4$ is not a variable in the language of first-order arithmetic.
Now the substitution will be:
1) $a+b=10$ --- it is $\varphi$
2) $a=4$
3) $\vdash a=4 \to ((a+b=10) \to (4+b=10))$ ---suitable instance of the equality substituion axiom

4) $4+b=10$ --- it is $\varphi'$ : from 1),2) and 3) by modus ponens twice.


text:
Q: VisionKit Barcode Scanner Enabling Highlights Using Swift I am learning how to create a barcode scanner and would like to add highlighting (the yellow square that goes around the numbers when the camera recognizes it)
I believe I should use isHighlightingEnabled: true
But I am not sure what line to put it on in my code. Where should I be placing it and do I need to add anything to make it work?
import UIKit
import Vision
import AVFoundation
import SafariServices

@objc class CMWSTVisionReader: UIViewController {
  // MARK: - Private Variables
  var captureSession = AVCaptureSession()

    @IBOutlet weak var cameraView: UIView!
    @IBOutlet weak var barcodeResult: UILabel!

    // TODO: Make VNDetectBarcodesRequest variable
  lazy var detectBarcodeRequest = VNDetectBarcodesRequest { request, error in
    guard error == nil else {
//      self.showAlert(
//        withTitle: "Barcode error",
//        message: error?.localizedDescription ?? "error")
      return
    }
    self.processClassification(request)
  }

  // MARK: - Override Functions
  override func viewDidLoad() {
    super.viewDidLoad()
    checkPermissions()
    setupCameraLiveView()
  }
  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    // TODO: Stop Session
    captureSession.stopRunning()

  }
}

extension CMWSTVisionReader {
  // MARK: - Camera
  private func checkPermissions() {
    // TODO: Checking permissions
    switch AVCaptureDevice.authorizationStatus(for: .video) {
    // 1
    case .notDetermined:
      AVCaptureDevice.requestAccess(for: .video) { [self] granted in
        if !granted {
          showPermissionsAlert()
        }
      }

    // 2
    case .denied, .restricted:
      showPermissionsAlert()

    // 3
    default:
      return
    }

  }

  private func setupCameraLiveView() {
    // TODO: Setup captureSession
    captureSession.sessionPreset = .hd1280x720

    // TODO: Add input
    // 1
    let videoDevice = AVCaptureDevice
      .default(.builtInWideAngleCamera, for: .video, position: .back)

    // 2
    guard
      let device = videoDevice,
      let videoDeviceInput = try? AVCaptureDeviceInput(device: device),
      captureSession.canAddInput(videoDeviceInput)
      else {
        // 3
        showAlert(
          withTitle: "Cannot Find Camera",
          message: "There seems to be a problem with the camera on your device.")
        return
      }

    // 4
    captureSession.addInput(videoDeviceInput)

    // TODO: Add output
    let captureOutput = AVCaptureVideoDataOutput()
    // TODO: Set video sample rate
    captureOutput.videoSettings =
      [kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA)]
    captureOutput.setSampleBufferDelegate(
      self,
      queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default))

    captureSession.addOutput(captureOutput)

    configurePreviewLayer()

    // TODO: Run session
    captureSession.startRunning()

  }

  // MARK: - Vision
  func processClassification(_ request: VNRequest) {
    // TODO: Main logic
    // 1
    guard let barcodes = request.results else { return }
    DispatchQueue.main.async { [self] in
      if captureSession.isRunning {
        view.layer.sublayers?.removeSubrange(1...)

        // 2
        for barcode in barcodes {
          guard
            // TODO: Check for QR Code symbology and confidence score
            let potentialQRCode = barcode as? VNBarcodeObservation,
            potentialQRCode.confidence > 0.9
            else { return }

          // 3
          observationHandler(payload: potentialQRCode.payloadStringValue)

        }
      }
    }

  }

  // MARK: - Handler
  func observationHandler(payload: String?) {
    // TODO: Open it in Safari
    // 1

      barcodeResult.text = payload
//      guard
//      let payloadString = payload,
//      let url = URL(string: payloadString),
//      ["http", "https"].contains(url.scheme?.lowercased())
//      else { return }
//
//    // 2
//    let config = SFSafariViewController.Configuration()
//    config.entersReaderIfAvailable = true
//
//    // 3
//    let safariVC = SFSafariViewController(url: url, configuration: config)
//    safariVC.delegate = self
//    present(safariVC, animated: true)

  }
}

// MARK: - AVCaptureDelegation
extension CMWSTVisionReader: AVCaptureVideoDataOutputSampleBufferDelegate {
  func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    // TODO: Live Vision
    // 1
    guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
      return
    }

    // 2
    let imageRequestHandler = VNImageRequestHandler(
      cvPixelBuffer: pixelBuffer,
      orientation: .right)

    // 3
    do {
      try imageRequestHandler.perform([detectBarcodeRequest])
    } catch {
      print(error)
    }

  }
}

// MARK: - Helper
extension CMWSTVisionReader {
  private func configurePreviewLayer() {
    let cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    cameraPreviewLayer.videoGravity = .resizeAspectFill
    cameraPreviewLayer.connection?.videoOrientation = .portrait
    cameraPreviewLayer.frame = cameraView.frame
    cameraView.layer.insertSublayer(cameraPreviewLayer, at: 0)
  }

  private func showAlert(withTitle title: String, message: String) {
    DispatchQueue.main.async {
      let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
      alertController.addAction(UIAlertAction(title: "OK", style: .default))
      self.present(alertController, animated: true)
    }
  }

  private func showPermissionsAlert() {
    showAlert(
      withTitle: "Camera Permissions",
      message: "Please open Settings and grant permission for this app to use your camera.")
  }
}

// MARK: - SafariViewControllerDelegate
extension CMWSTVisionReader: SFSafariViewControllerDelegate {
  func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
    captureSession.startRunning()
  }
}