text:
Q: Render conditionally to divs height Within react, I'm trying to render a inner div only if its height doesn't get greater than a given percentage of a outer divs height.
I came up with the following solution:
Wrapper.js
import React from "react";
import Presentation from "./Presentation"

export default class Wrapper extends React.Component{
    constructor(props) {
        super(props);
        this.state = { percentage: 0 };

        this.myRef = React.createRef();
    }

    componentDidMount(){
        this.setState(
            {percentage: this.myRef.current.inner.clientHeight/this.myRef.current.outer.clientHeight * 100}
        )
    }

    componentDidUpdate(prevProps, prevState){
        const percentage = this.myRef.current.inner.clientHeight/this.myRef.current.outer.clientHeight * 100;

        if (prevState.percentage !== this.state.percentage){

            this.setState(
                {percentage: percentage}
            )
        }

    }

    render(){
        return <Presentation ref={this.myRef} percentage={this.state.percentage}>abc</Presentation>
    }
}

Presentation.js
import React, { useRef, useImperativeHandle, forwardRef } from 'react';

const Presentation = (props, ref) => {
    const innerRef = useRef();
    const outerRef = useRef();

    const inputRef = useRef();
    useImperativeHandle(ref, () => ({
        get inner(){
            return innerRef.current
        },
        get outer(){
            return outerRef.current
        }
    }));
    console.log("percentage presentation: ", props.percentage)
    return

Outer

Anteil inner: {props.percentage}

        {props.percentage <= 50 &&
50 größer
}

}

export default forwardRef(Presentation);

Unfortunately it results in an error; Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.
After debugging I figured out what went wrong (there is a infinite loop while rendering going on) but I can't figure out how to resolve it by my own. Can anybody give me a hint for a better solution?


text:
Q: MQ: How does MQ client knows to get the right response message I am newbie to Websphere MQ and i have some basic understanding on the concept of MQ. I know that MQ client would create a message (with MQMD and application data) and then send to MQ manager. MQ client will get the correct response back from MQ Manager. Supposedly there are many messages on the MQ Queue Manager, how does MQ client able to retrieve the right messages? What determines the uniqueness of a MQ message?

A: There are different ways this can be approached - one common way is for the applications processing the messages to use the message ID and correlation ID fields.  The message ID can be randomly generated and saved then copied to correlation ID field to be match when the reply is sent.  Applications can do gets matching on those fields in the message header.
I suggest you read through the application programming guide and reference in the knowledge center.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using Rollup to bundle my lib using RTKQ results in the error: The error in question is could not find react-redux context value; please ensure the component is wrapped in a <Provider>.
I first describe particulars about the library.
Afterwards I describe the environment in which it is run and the error in more detail.
The lib
The lib in question is just a collection of api calls governed by RTKQ.
The apiSlice is exported and can then be used by consumer packages to add it to their store.
I must note that this DID work in the past when the collection of API calls was just another file in the same repo, before I (tried) to move it into it's own and make a lib out of it.
It even still worked in the very early versions of the lib, when I just ... didn't bundle it at all, releasing the bare source code as a package.
It only now stopped working after I tried to do it the proper way.
Its rollup config looks like so:
const resolve = require('@rollup/plugin-node-resolve');
const commonjs = require('@rollup/plugin-commonjs');
const peerDepsExternal = require('rollup-plugin-peer-deps-external');
const babel = require('@rollup/plugin-babel');

const packageJson = require('./package.json');

module.exports = {
  input: 'src/index.js',
  external: [/@babel\/runtime/],
  output: [
    {
      file: packageJson.module,
      format: 'es',
      sourcemap: true,
    }
  ],
  plugins: [
    peerDepsExternal(),
    resolve(),
    babel({
      exclude: 'node_modules/**',
      babelHelpers: 'runtime',
    }),
    commonjs({
    // the @rollup/plugin-babel readme insists that this should be placed before babel runs;
    // but this never worked and in all examples I found this was the way it is here.
      strictRequires: true,
    }),
  ],
};

Its package.json looks like so:
{
  "name": "some-name",
  "version": "1.1.2",
  "main": "dist/esm/index.js",
  "files": [
    "dist"
  ],
  "dependencies": {
    "@babel/runtime": "^7.20.6",
    "@faker-js/faker": "^7.6.0",
    "@reduxjs/toolkit": "^1.8.0",
    "luxon": "^3.1.0",
    "np": "^7.6.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-redux": "^8.0.2",
    "reactjs-localstorage": "^1.0.1"
  },
  "scripts": {
    "lint": "eslint .",
    "lint:fix": "eslint --fix .",
    "prepare": "npm run co:login",
    "prepublishOnly": "npm run build && np --no-publish --no-yarn --no-cleanup",
    "build": "rollup --config",
    "start": "webpack serve",
    "devBuild": "webpack --mode=development",
    "test": "echo \"No tests yet\""
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.20.5",
    "@babel/plugin-transform-runtime": "^7.19.6",
    "@babel/preset-env": "^7.20.2",
    "@rollup/plugin-babel": "^6.0.3",
    "@rollup/plugin-commonjs": "^24.0.0",
    "@rollup/plugin-node-resolve": "^15.0.1",
    "eslint": "^8.17.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-react": "^7.30.0",
    "eslint-plugin-storybook": "^0.5.12",
    "rollup": "^3.7.5",
    "rollup-plugin-peer-deps-external": "^2.2.4",
    "webpack": "^5.70.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.11.1"
  }
}

Its .babelrc file
{
  "presets": ["@babel/preset-env"],
  "plugins": ["@babel/plugin-transform-runtime"]
}

I exports it's api slice created with RTKQ's createApi() and also all defined endpoints.
The consumer
The current sole consumer is a component lib which uses storybook for testing.
Here is part of it's preview.js
import {
  createTheme,
  CssBaseline,
  responsiveFontSizes,
  ThemeProvider,
} from '@mui/material';
import { SnackbarProvider } from 'notistack';

import { MemoryRouter } from 'react-router';

import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
import { apiSlice} from '@my_company/the_lib_with_the_error'; // that's the lib
import { useDispatch } from 'react-redux';
import { useEffect } from 'react';

import { initialize as initializeMSW, mswDecorator } from 'msw-storybook-addon';
import { ConfirmProvider } from 'material-ui-confirm';

// test store
const store = configureStore({
  reducer: {
    [apiSlice.reducerPath]: apiSlice.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(apiSlice.middleware),
  devTools: { trace: true },
});

let theme = createTheme({/** long theming code */});
theme = responsiveFontSizes(theme);

initializeMSW({ waitUntilReady: false });

// I have also incorporated the suggestions of Linda Paiste's answer.
// Sadly, they had no effect.
const SetupApi = () => {
  const dispatch = useDispatch();
  useEffect(() => {
      dispatch(timumApiSlice.util.resetApiState());
  }, [dispatch]);

  return null;
}

const stdLayout = (Story) => {
  store.dispatch(timumApiSlice.util.resetApiState());

  return (
    <>
      <Provider store={store}>
        <ThemeProvider theme={theme}>
          <SnackbarProvider
            maxSnack={3}
            autoHideDuration={3000}
            anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
          >
            <ConfirmProvider>
              <>
                <CssBaseline />
                <SetupApi />
                <MemoryRouter initialEntries={['/']}>
                  <Story />
                </MemoryRouter>
              </>
            </ConfirmProvider>
          </SnackbarProvider>
        </ThemeProvider>
      </Provider>
    </>
  );
};

Has anyone any ideas?
Edit 1

*

*clarified how my setup is.

*restructured the question to make it clearer.

A: The Provider should be outside of all dispatch calls, not in the same component.  You are getting around this by using store.dispatch instead of useDispatch, but a better approach would be to move that call into a sub-component which is rendered inside of the Provider.  Like this:
const SetupApi = () => {
    // It's okay to use the useDispatch hook here, because this component is rendered
    // inside of the Provider.
    const dispatch = useDispatch();

    // Move the side-effects into a useEffect
    useEffect(() => {
        // I'm not sure that this is really needed though?  Isn't your store empty?
        dispatch(timumApiSlice.util.resetApiState());

        window.timumApiSlice = timumApiSlice;

    }, [dispatch]);

    return null;
}

const stdLayout = (Story) => {
    return (
        <Provider store={store}>
            <ThemeProvider theme={theme}>
                <SnackbarProvider
                    maxSnack={3}
                    autoHideDuration={3000}
                    anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
                >
                    <ConfirmProvider>
                        <CssBaseline />
                        <SetupApi/>
                        <MemoryRouter initialEntries={['/']}>
                            <Story />
                        </MemoryRouter>
                    </ConfirmProvider>
                </SnackbarProvider>
            </ThemeProvider>
        </Provider>
    );
};

I also moved the Redux <Provider> outside of your other providers just in case those components are using Redux data.
I can't guarantee that this alone will fix your issues because I don't fully understand your setup.
You must make sure that your store variable contains both the middleware and the reducer from your timumApiSlice API object.

A: I finally managed to figure it out.
First, I didn't set react-redux and @redux/redux-toolkit as peerDependencies.
Instead they were handled as normal dependencies. This led to rollup bundling them into the package.
The component lib itself declared react-redux and @redux/redux-toolkit as dependencies.
I believe that this caused the apiSlice to be created using the redux of the lib but the context was set by the redux of the component lib.
(But this is only an assumptions and may be wrong. Please correct me if so.)
Second, for basically the same reason, I did the same for react and react-dom.


text:
Q: A couple of problems involving divisibility and congruence I'm trying to solve a few problems and can't seem to figure them out. Since they are somewhat related, maybe solving one of them will give me the missing link to solve the others.
$(1)\ \ $ Prove that there's no $a$ so that $ a^3  \equiv -3 \pmod{13}$
So I need to find $a$ so that $a^3 \equiv 10 \pmod{13}$. From this I get that $$a \equiv (13k+10)^{1/3} \pmod{13} $$ If I can prove that there's no k so that $ (13k+10)^{1/3} $ is a integer then the problem is solved, but I can't seem to find a way of doing this.
$(2)\ \ $ Prove that $a^7 \equiv a \pmod{7} $
If $a= 7q + r \rightarrow a^7 \equiv r^7 \pmod{7} $. I think that next step should be $ r^7 \equiv r \pmod{7} $, but I can't figure out why that would hold.
$(3)\ \ $ Prove that $ 7 | a^2 + b^2 \longleftrightarrow 7| a \quad \textbf{and} \quad 7 | b$
Left to right is easy but I have no idea how to do right to left since I know nothing about what 7 divides except from the stated. Any help here would be much appreciated.
There're a lot of problems I can't seem to solve because I don't know how to prove that a number is or isn't a integer like in problem 1 and also quite a few that are similar to problem 3, but I can't seem to find a solution. Any would be much appreciated.

A: HINT $\rm\ (2)\quad\ mod\ 7\!:\ \{\pm 1,\:\pm 2,\:\pm3\}^3\equiv\: \pm1\:,\:$ so squaring yields $\rm\ a^6\equiv 1\ \ if\ \ a\not\equiv 0\:.$
$\rm(3)\quad \ mod\ 7\!:\ \ if\ \ a^2\equiv -b^2\:,\:$ then, by above, cubing yields $\rm\: 1\equiv -1\ $ for $\rm\ a,b\not\equiv 0\:.$
$\rm(1)\quad \ mod\ 13\!:\ \{\pm1,\:\pm3,\:\pm4\}^3 \equiv \pm 1,\ \ \{\pm2,\pm5,\pm6\}^3\equiv \pm 5\:,\: $ and neither is $\rm\:\equiv -3\:.$
If you know Fermat's little theorem or a little group theory then you may employ such to provide more elegant general proofs - using the above special cases as hints.

A: For the first problem, an unimaginative but workable approach is just to check all the possibilities $a=0,1,2,\dots,12$. Do you see why, if these all fail, you're done?
For the 3rd problem, I think you mean right implies left is easy. For left implies right, take each of the numbers $0,1,\dots,6$, square them, divide by 7, and note the remainders. From that you can work out all the possible remainders of $a^2+b^2$, and from that you can answer the question.
Let me know if you've tried to work through this and found my hints too opaque.


text:
Q: Class redefinition problems using forward declarations NOTE: Reupload of a question wrongly marked as duplicate
I'm working with Ogre, but my question resides specifically within namespaces.
I haven't been able to find an answer that helps me here.
I'm trying to forward declare Ogre::xyz classes within my header file for a CameraController.
This is the header file
class Ogre;
class Ogre::SceneNode;
class Ogre::SceneManager;

class CameraController
{
private:
    Ogre::SceneNode* camNode;

    Ogre::SceneManager* scnMgr;
};

This is the cpp file
#include "CameraController.h"

#include <OgreSceneManager.h>
#include <OgreSceneNode.h>

... definitions of functions.

What's the correct way to achieve what I'm trying to do here, in avoiding including unneeded header files within the CameraController.h file
ATTEMPT TO FIX
I attempted the redefinition as marked in a 'duplicate' that talked about declaring classes in namespaces:
namespace Ogre
{
    class SceneManager;
    class SceneNode;
    class Camera;
    class Viewport;
    class Real;
}

class CameraController
{
private:
    Ogre::Real getAspectRatio();

private:
    Ogre::SceneNode* camNode;

    Ogre::Camera* camera;

    Ogre::Viewport* viewPort;

    Ogre::SceneManager* scnMgr;
};

EDIT
So the error I am having now is that the classes that I forward declare within the Ogre namespace are being redefined by the headers that I include in the .cpp file

A: The capitalization of ViewPort and Viewport in the forward declaration is different.  C++ would see them as different values.


text:
Q: Cannot connect to a socket in a Docker container running on Kubernetes I'm trying to connect to a socket that is inside a container and deployed on Kubernetes.
Locally everything works fine but when deployed it throws an error on connect. I tried with different options but with no success.
Client code
const ENDPOINT = "https://traveling.dev/api/chat";  // this will go to the endpoint of service where socket is running

const chatSocket = io(ENDPOINT, {
  rejectUnauthorized: false,
  forceNew: true,
  secure: false,
});
chatSocket.on("connect_error", (err) => {
  console.log(err);
  console.log(`connect_error due to ${err.message}`);
});
console.log("CS", chatSocket);

Server code
const app = express();

app.set("trust proxy", true);
app.use(cors());

const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: "*",
    methods: ["*"],
    allowedHeaders: ["*"],
  },
});

io.on("connection", (socket) => {

  console.log("Socket succesfully connected with id: " + socket.id);

});

const start = async () => {

  server.listen(3000, () => {
    console.log("Started");
  });
};

start();

The thing is code is irrelevant here cause locally it all works fine but I posted it anyways.
What can cause this while containerizing it and putting it on Kubernetes?
And the console log just says server error
Error: server error
    at Socket.onPacket (socket.js:397)
    at XHR.push../node_modules/component-emitter/index.js.Emitter.emit (index.js:145)
    at XHR.onPacket (transport.js:107)
    at callback (polling.js:98)
    at Array.forEach (<anonymous>)
    at XHR.onData (polling.js:102)
    at Request.push../node_modules/component-emitter/index.js.Emitter.emit (index.js:145)
    at Request.onData (polling-xhr.js:232)
    at Request.onLoad (polling-xhr.js:283)
    at XMLHttpRequest.xhr.onreadystatechange (polling-xhr.js:187)

Does anyone have any suggestions on what may cause this and how to fix it?
Also, any idea on how to get more information about the error would be appreciated.
This is the YAML file that creates the Service and a Pod.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: chat-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: chat
  template:
    metadata:
      labels:
        app: chat
    spec:
      containers:
        - name: chat
          image: us.gcr.io/forward-emitter-321609/chat-service
---
apiVersion: v1
kind: Service
metadata:
  name: chat-srv
spec:
  selector:
    app: chat
  ports:
    - name: chat
      protocol: TCP
      port: 3000
      targetPort: 3000

I'm using a loadbalancer on GKE with nginx which IP address is mapped to traveling.dev
This is how my ingress routing service config looks like:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: "true"
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/cors-allow-methods: "PUT, GET, POST, OPTIONS"
    nginx.ingress.kubernetes.io/cors-allow-credentials: "true"
    nginx.ingress.kubernetes.io/configuration-snippet: |
      more_set_headers "Access-Control-Allow-Origin: $http_origin";
spec:
  rules:
    - host: traveling.dev
      http:
        paths:
          - path: /api/chat/?(.*)
            backend:
              serviceName: chat-srv
              servicePort: 3000
          - path: /?(.*)
            backend:
              serviceName: client-srv
              servicePort: 3000

Thanks!

A: Nginx Ingress by default support WebSocket proxying, but you need to configure it.
For this you need to add annotation custom configuration snippet.
You can refer this already answered stackoverflow question.
Nginx ingress controller websocket support


text:
Q: How do i show UIImageview with Animation? I have one UIImageView with round image I want to show ripple effect on the image. How can I show ripple effect on UIImageview with animation? Can anyone suggest?

A: You can use CATransition to show any kind of effect. Here is sample code for it.
CATransition *animation = [CATransition animation];
[animation setDelegate:self];
[animation setDuration:2.0f];
[animation setTimingFunction:UIViewAnimationCurveEaseInOut];
[animation setType:@"rippleEffect" ];
[YOUR_IMAGE_VIEW.layer addAnimation:animation forKey:NULL];

Checkout this apple document, so you will get more idea.
Here is a demo from Jake Chasan about different types of animation.


text:
Q: preventDefault in function with more parameters? I have a function that is run when clicking an input in the DOM. I want to stop the element from being checked until my function can approve it. I'm trying to do this using e.preventDefault(); or event.preventDefault(); (is there any difference?!) but I'm not succeeding, what am I doing wrong?
This is my code without the preventDefault-part.
$(document).on("click","[data-item]", function() {
    cart.updateCart(this);
});

cart.updateCart = function(target) {
   // do stuff and perhaps check the input element
}

I tried this, which is not working:
$(document).on("click","[data-item]", function() {
    cart.updateCart(this, event);
});

cart.updateCart = function(target, event) {
    event.preventDefault();
    console.log(event); // returns MouseEvent -- is this even the correct "event" ?
   // do stuff and perhaps check the input element
}

I think I'm not "getting" how this works. Perhaps someone can explain how this works and what I'm doing wrong?

A: event should be the first parameter passed into your click handler. So your code really should be like this.:
$(document).on("click","[data-item]", function(event) {
    cart.updateCart(this, event);
});

cart.updateCart = function(target, event) {
    event.preventDefault();
    console.log(event); // returns MouseEvent -- is this even the correct "event" ?
   // do stuff and perhaps check the input element
}

You can read more about preventing default actions here.


text:
Q: How to include nested List in asp.net api response I'm working with a nested list (List inside List) everything is working fine but when I try to get response from Api (GetOrders) it is not showing lists. I try to .include(x=>x.ShopOrdersList) but It is only including "ShopOrdersList" and the second list "OrderSummaries" which is inside  "ShopOrdersList" is not showing.
My model is follow
 public class Orders
{
    [Key]
    public int InvoiceNumber { get; set; }
    public int ShopId { get; set; }
    public string ShopName { get; set; }
    public string Address { get; set; }
    public string OwnerName { get; set; }
    public string OwnerCnic { get; set; }
    public string Area { get; set; }

    public string PhoneNumber { get; set; }
    public int TotalSale { get; set; }
    public int TotalProfit { get; set; }
    public int TotalRecover { get; set; }
    public List<ShopOrder> ShopOrdersList { get; set; }
}
public class ShopOrder
{
    [Key]
    public int ShopOrderId { get; set; }
    public DateTime BookingDate { get; set; }
    public DateTime DeliveryDate { get; set; }
    public string OrderBooker { get; set; }
    public string DeliveryMan { get; set; }
    public byte[] Signature { get; set; }
    public int TotalQuantity { get; set; }
    public bool IsDelivered { get; set; }
    public bool IsAccepted { get; set; }
    public bool IsPaymentAdded { get; set; }
    public int TotalProfit { get; set; }
    public int TotalPrice { get; set; }
    public string UserId { get; set; }
    public List<OrderSummary> OrderSummaries { get; set; }
}
public class OrderSummary
{
    [Key]
    public int OrderSummaryId { get; set; }
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string Detail { get; set; }
    public int Price { get; set; }
    public byte[] Image { get; set; }
    public int PcsInCtn { get; set; }
    public int OnePcsPurchasePrice { get; set; }
    public int Ctns { get; set; }
    public int Quantity { get; set; }
    public int TotalPrice { get; set; }
}

and the controller code is
// GET: api/Orders
    public IQueryable<Orders> GetOrders()
    {
        return db.Orders.Include(x => x.ShopOrdersList);
    }

This is response that I'm getting.

Now I want to include "OrderSummaries" list. Thanks in advance.

A: Check this answer EF LINQ include multiple and nested entities
Its saying you can call ThenInclude to add nested entries
 public IQueryable<Orders> GetOrders()
    {
        return db.Orders.Include(x => x.ShopOrdersList).ThenInclude(y=>y.OrderSummaries);
    }


text:
Q: apache/2.4.29 (ubuntu) server at localhost port 80 I am trying to run openEMR project in Eclipse on my Ubuntu 18.04 machine. I have downloaded the project and installed the dependencies using below command.
composer install --no-dev
npm install
npm run build
composer dump-autoload -o

I followed this tutorial to run the application but still I got the below error.

The project is present inside this folder.

And the configurations in Eclipse are:

I tried like below as well:

What am I missing here?

A: You are accessing a resource in your web browser which does not exist in your apache2.
The directory public_html is your Document Root. Therefore, you have to specify a resource that is relative to your Document Root.
Try
http://localhost/openemr-6_0_0/index.php


text:
Q: Google Calendar Desktop Notifications Disappear Now My calendar Event Settings notification is set on "Desktop notifications" and my calendar items used to pop up at the bottom right screen and stay there until I clicked on them or selected "remind me again in 5 minutes".  Now it seems to have changed so that I hear a chime, it pops up on the bottom right of my screen, but then disappears.  That is terrible!  If I'm not in front of my computer and a notification comes up, I won't know it's there.  How can I switch it back so that my notification stays on my screen until I get rid of it?

A: We can try to add event notifications to each calendar as below:
1.Open up your Google Calendar.
2.Click on the Gear icon.
3.Click Settings.
4.Select the calendar to be configured.
5.Scroll down to Event notifications.
6.Click the drop-down and select the type of notification you want to set.
7.Configure the time associated with the alert.

For details we can refer the articles: How to customize your Google Calendar notifications


text:
Q: Why is NASM assembly 64 bit printf not printing value of floating point division? My goal here is to add 3 floating point numbers and divide by 3 to calculate the average and then print the result.
While it assembles and executes, I am getting :
The average of the numbers is 0.000000
rather than the calculated average.
Can someone please tell me why it is displaying 0.000000 instead of the average?
%macro EXITPGM 0
mov eax, 0
call exit
%endmacro

section .data
flt1  dq 0.0

msg db "The average of the numbers is %f",10,0

section .text
global main
extern printf
extern exit

main:
    push rbp
    mov dword [flt1], __float64__(3.93)
    mov rsi, __float64__(9.4)
    mov rdx, __float64__(84.52)
    add rsi, [flt1]
    add rsi, rdx
    mov rdx, 0
    mov rax, rsi
    mov rcx, 3
    div rcx
    mov rdi, msg
    mov rax, 1
    movq xmm0, rax
    call printf

    pop rbp
    EXITPGM


text:
Q: Uploading attachment to sql server using LINQ Uploading files from asp.net to SQL Server 2008, after I upload to SQL Server I see the attach content is: 0x89
My stored procedure accepts : @AttachContent varbinary,
Below is my code how I am uploading.
public bool AttachmentInsert(int mimeTypeId, string attachFileName,
                             byte[] attachContent)
{
   using (DataContextDataContext dc = conn.GetContext())
   {
      int attachId =  (int)dc.spAttachment_Insert(mimeTypeId, attachFileName,
                                                  attachContent).ReturnValue;
      if (attachId != 0)
      {
         return true;
      }
      return false;
   }
}

[Function(Name="dbo.spAttachment_Insert")]
public ISingleResult<spAttachment_InsertResult> spAttachment_Insert(Name="AttachContent", DbType="VarBinary(1)")] System.Data.Linq.Binary attachContent,
{
   IExecuteResult result =
       this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())),
                              mimeTypeID, attachFileName, attachContent);
   return ((ISingleResult<spAttachment_InsertResult>)(result.ReturnValue));
}

Any help how to correct.

A: DbType="VarBinary(1)"

You are truncating the content to 1 byte. Use VarBinary(max) instead.


text:
Q: Why does this code compile without complaining about constructors? A while ago I wrote some code with a set of nested classes. Looking over it today I'm wondering why it compiles when I instantiate an object of type C.
My confusion is this. B has a private constructor. The implementation of this constructor takes care of the construction of A, but the construction of A requires an instance of B. I feel like it's a chicken and the egg scenario. The construction of B requires the construction of A which requires the construction of B etc etc ad infinitum.
I have the following classes - stripped right back to demo the issue:
// ******* A ******** //
class A {
public:
   A(A& _Parent, int id);
private:
   A& Parent;
};

inline A::A(A& _Parent, int id)
: Parent(_Parent)
{
}

// ******* B ******** //
class B:public A {
public:
   static B& GetInstance();
private:
   B();
};

inline B::B()
: A(B::GetInstance(), 0)
{
}

inline B& B::GetInstance()
{
   static B b;
   return b;
}

// ******* C ******** //
class C:public A {
public:
   C();
};

inline C::C()
: A(B::GetInstance(), 0)
{
}

A: Narrowing in on the problem:
inline B& B::GetInstance()
{
   static B b;
   return b;
}

inline B::B()
: A(B::GetInstance(), 0)
{
}

The line static B b; creates a B object the first time the function is called. However, the construction of b then calls GetInstance, which reaches the line static B b; while b is still under construction.
This case is covered by C++14 [stmt.dcl]/4:

[...]  such a variable is considered initialized upon the completion of its initialization. [...] If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.

I excised a part talking about what happens if an exception is thrown, or if two differently threads concurrently try to initialize the static variable. The standard does permit local static variables to be initialized prior to the first call of the function, but even if the implementation did that, the same problem would arise of control re-entering the declaration recursively.

Being undefined behaviour, anything can happen. One possible result is it appearing to work as intended. The standard does not require this to be diagnosed at compile-time -- a difficult thing to analyze.  As indicated in comments, one version of gcc detects this at runtime and throws an exception. Perhaps your original compiler implements local statics by having a flag to indicate whether execution has reached that line yet, and it sets the flag before calling the constructor.
The rationale for having undefined behaviour in the standard is to avoid placing constraints on the way an implementation implements the well-defined behaviour (in this case, the method of ensuring local statics are only initialized once).
Of course, you should find a way to fix the problem as the undefined behaviour may manifest itself differently in future in ways that are hard to predict.

A: Although you didn't show any such code, let's assume something attempts to call the default constructor of C or in some other way calls B::GetInstance().
The first statement in GetInstance() is static B b;.  Since this is the first time we've arrived here, the object b needs to be initialized by calling the default constructor B::B().
The first thing B::B() does is call GetInstance(), intending to then pass the result of that to the A::A(A&, int) constructor.
Which puts us back again at the statement static B b;.  And the C++ Standard says ([stmt.dcl]/4):

Dynamic initialization of a block-scope variable with static storage duration ([basic.stc.static]) or thread storage duration ([basic.stc.thread]) is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization.... If control enters the declaration recursively while the variable is being initialized, the behavior is undefined.

Undefined behavior means anything could happen. It might appear to work, it might crash or hang your program, or it might initialize incorrectly and continue.


text:
Q: How to prevent error "more than 30 operands in 'asm'" with inline assesmbly with gcc I have been writing a minimal lua compiler for educational purposes by translating the lua code to inline assembly in C with gcc.
After a while when my generated output started to become longer with more operands for declared variables and functions in C, this error started to occur.
test.c: In function 'int main()':
test.c:100:6: error: more than 30 operands in 'asm'
     );

When googling the only other info i found was some gcc mailing list from 2008, but they said that there were no fixes except for recompiling gcc (which I am not interested in).
The ironic thing is that often I don't even have 30 operands and I still get this error!
Here's an minimal example (with 19 operands, still gives me that error)
// Standard functions
void io_read(){}
void io_write(){}
void print(){}
int main(){
    // Working vars decl
    long _t0, _t1, _t2, _t3, _t4, _t5, _t6, _t7, _t8;
    long factorial, i, n, x;
    // Strings decl
    const char* _s0 = "enter a number:";
    const char* _s1 = "*number";
    const char* _s2 = "factorial of ";
    const char* _s3 = " is ";
    asm("" // My inline asm code
    : // Output symbols
      [_s0] "+g" (_s0),
      [_s1] "+g" (_s1),
      [_s2] "+g" (_s2),
      [_s3] "+g" (_s3),
      [_t0] "+g" (_t0),
      [_t1] "+g" (_t1),
      [_t3] "+g" (_t3),
      [_t4] "+g" (_t4),
      [_t5] "+g" (_t5),
      [_t6] "+g" (_t6),
      [_t7] "+g" (_t7),
      [_t8] "+g" (_t8),
      [factorial] "+g" (factorial),
      [i] "+g" (i),
      [n] "+g" (n),
      [x] "+g" (x)
    : // Input symbols
      [io_read] "r" (io_read),
      [io_write] "r" (io_write),
      [print] "r" (print)
    : // Clobbers
      "cc", "rax", "rbx", "rcx", "rdx"
    );
}

My gcc version is 6.2.1 20160830
Thanks in advance!

A: So I didn't find a direct solution to the issue, but thanks to Ross Ridge I was able to work around the issue pretty well.
The first imrovement i did was changing "+g" with "g" where possible. Apparently "+g" counts as two operands because it allows both read+write so I replaced the onces possible with "g" which only allows write.
Also, I was able to completely remove my functions as operands by moving them to a global scope and then calling then directly with "call print" instead of "call %[print]". It should be noted however that this only work with inline C and will not work with inline C++.
If you are writing a compiler like me I would recommend staying away from inline assembly though. Seems like more trouble, simply calling C functions manually from Assembler would be easier, and I would certainly not make a compiler on a bigger scale with inline C.
EDIT: I started forcing "m" and "+m" also instead of using "g" and force variables onto the stack which seems to work fine.


text:
Q: Getting objects from json data tree, issue with reusing function I wrote a code (with help from another question) in order to get objects from a json tree.
let objFound = null;

function getObjFromValue(obj, prop, val) {
    Object.keys(obj).forEach((key) => {
        if (objFound == null) {
            if (key === prop && val === obj[key]) {
                objFound = obj;
            }

            if (typeof obj[key] === 'object') {
                getObjFromValue(obj[key], prop, val);
            }
        }
    });

    return objFound;
}

The problem with it is, that I can use it only once since the variable objFound  is global (I need it to stop the forEach loop somehow) and never gets nulled again, so when I make another search I receive the previous and first object that the function found. Is there a way to improve/fix my function?

A: You can use a local variable to return the value, after setting the global variable to null.
let toReturn = objFound;
objFound = null;
return toReturn;

However, this global variable approach might not be the best one. The comment of @pilchard has a good alternative, making the variable local.


text:
Q: Need to write a batch file job I need to write a batch job file to keep two folder in sync.
Inputs : Source and Destination folder names.
senario :

*

*If the destination folder/subfolder is not found – create and proceed

*If the files are already present in both the folders Compare and overwrite destination file if timestamp/size differs.

*If the file not present in source and present in destination, delete the destination file.
kindly help me to write the batch job.
Thanks Vikram

A: A batch file written by a self-professed inexperienced user - even run periodically - is not a good replacement for a sync tool like rsync or dropbox or even the Briefcase built into Windows.  Robocopy looks a good bet.


text:
Q: 18.04 LTS -> 20.04 LTS leaves mysql broken. Unsupported upgrade path https://dev.mysql.com/doc/refman/8.0/en/upgrade-paths.html
I had v18 LTS, just upgraded to v20 LTS, and the version jumps for MySQL are not supported. I'm now stuck with mysql shutting down, because INNODB tables can't be upgraded.
[ERROR] [MY-013168] [InnoDB] Cannot upgrade server earlier than 5.7 to 8.0

What are my options?

A: You have a few options in front of you:

*

*Wipe MySQL clear off the system, remembering to delete the /etc/mysql directory as well, then reinstall and restore from the most recent backup

*Fire up a VM, install MySQL 5.7 (yes, 5.7), stop the database, copy your existing /etc/mysql files to the VM's data directory, start MySQL and have it upgrade your tables, then:

*

*use mysqldump to extract the data and load that into your 20.04 installation, or …

*upgrade the VM to MySQL 8.0, then copy the newly updated data files to your 20.04 installation

*Fire up a Docker container for an instance of MySQL between the version you were running and the most recent 5.7, and just run your database from there

There are a few other options, but they're more work and do not offer any perceivable benefits over the three options above. Generally when I've had to deal with this sort of situation, Option 2 has been the fastest path to success.


text:
Q: iPhone app does not work correctly on iPad after change from universal to iphone only How can I run iPhone apps on iPad after changing the target from an initial 'Universal' to 'iPhone'?
I'm working on a game for iOS (iPhone) using Swift and SpriteKit. The game got rejected today for this reason:

Reasons for Rejection: 2.10: iPhone apps must also run on iPad without
  modification, at iPhone resolution, and at 2X iPhone 3GS resolution

After searching on StackOverflow I found out that it might have something to do with my info.plist file because at first my app was 'universal' and later I've changed it to iPhone-only.
It seems like there's something wrong with the aspect ratio of all the nodes. Take a look at the screenshots below. At the left side is the iPad-simulator and on the right there's the iPhone-simulator.
Maybe the game still thinks it is running on iPad because the nodes appear in 4:3 ratio?
How can I run iPhone apps on iPad after changing the target from an initial 'Universal' to 'iPhone'?
Please help. Thanks!

I've also added a screenshot of my info.plist file.

A: Apple requires that each app targeted on iPhone should run on iPad in the specific manner.
This usually looks like the app on iPad is not full-screen, it's surrounded by black frame that resembles the situation that the iPad is simulating iPhone.
My suggestion is to use size class now to make the app run full-screen on iPad and this should fix your issue with Apple.
Simply choose in your storyboard Regular Width and Regular Height, delete the existing constraints and set new ones.
More help here and apple docs also might come in handy

A: Darvydas' comment solved my problem.

What size does your background node have? Also if you whant your app
  run only on Landscape delete those 2 (Item 0, Item 1 PORTRAIT)


text:
Q: How to manipulate loops with input? i got a for loop and i would like to manipulate the counter i with a input on screen. Below i can select from 1 to 10 and i want this selection to get replaced by the counter in the loop. That means when i choose 2, then i should be 2. I started with the code below, but document.getElementById('options').innerHTML = "i"; seems to be the wrong code to manipulate. Thanks so much for your help!
        <select id="options" size="1">
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
              <option value="6">6</option>
              <option value="7">7</option>
              <option value="8">8</option>
              <option value="9">9</option>
              <option value="10">10</option>
         </select>

    for (i=0, i<someArray; i++){
    do somethingWith[i];}

document.getElementById('options').innerHTML = "i";

A: You need to get the value of the select element and assign that to i.
var i = document.querySelector('#options').value;

for(i < someArray; i++){
    //code
}

A: Add this to HTML
<select onChange="doWork(this)">

In Js
function doWork(obj){

         obj.innerHTML = obj.value

}

A: If want to do some thing on selection, use onchange method with select to trigger a function every time you are selecting an option.
 <select id="options" size="1" onchange="myFunction()">
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
              <option value="6">6</option>
              <option value="7">7</option>
              <option value="8">8</option>
              <option value="9">9</option>
              <option value="10">10</option>
         </select>

But if you only want to dynamically select an option in select tag, this might help
Select your favorite fruit:
<select id="mySelect">
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="pineapple">Pineapple</option>
  <option value="banana">Banana</option>
</select>

<button type="button" onclick="myFunction()">banana</button>


text:
Q: DocuSign API Template Search by Name Limits I'm currently trying to utilize the Templates list API with the search_text query string parameter. When I send a value that exceeds 48 characters, it will not return anything. Does anyone know if there is an assumed/imposed length restriction for using search_text?
Example GET Urls:

*

*Works: /Templates?search_text=Universal Power Purchase Agreement - Massachuset

*Does not work: /Templates?search_text=Universal Power Purchase Agreement - Massachusett

A: You've crossed the maximum length of the search_text parameter. Trying to use a search term that's more than 48 characters will result in the search failing and zero results being returned.


text:
Q: How to get URL of the video from JwPlayer API using PHP? All I want is to get the url of the video I stored, not the playists.
I was able to store video in  JW Server but I don't know how to get them in any certain way..
I'm using JwPlayer PHP Library for that..
https://github.com/jwplayer/jwplatform-php/
What I've done so far:
$jwplatform_api = new
Jwplayer\JwplatformAPI($jwplatform_api_key,$jwplatform_api_secret);

$target_file = 'demo.mp4';
$params = array();
$params['title'] = 'Nobita';
$params['description'] = 'Nobita';
$params['link'] = "http://digitalrace.in/rl/";

I thought, using the url "digitalrace.in/rl/" I could get the video, But all I got was 403 Forbidden...
I know, there's a way by using the PHP Library, but it's not giving  me much satisfaction as anyone could download the vdeo if I use that url and there's no safety and no styling at all and I didn't find that below url in JW Docs anywhere.(PHP Library)
<a href="http://content.jwplatform.com/previews/<?php echo $video_key?>-AKJ8XQCI"

How do I get url of the video, So I can link the video with course..I thought of using Javascript, but don't know how to get video in it...

    Preview


text:
Q: Networking issue, access service indirectly I've got an application and internet service that works fine from my home network, but fails (TCP connection "dies" after a few KB sent) on the university residence network. The admins of the two systems have spent a few months saying that they did nothing to cause this and blaming each other, and not really taking much interest, while all I want is to be able to use the application for more than the occasion I visit home...
I ran some tests, and there seems to be nothing about the data being sent that causes this, at least when the data isn't being sent from that exact server.
What I want to do now is route the connection through another computer outside the university network, which I know does work, as per the diagram below, however I have no idea how to do this, and force a specific application to route through it for its outgoing TCP connection.

A: Sounds to me like a classic university/school/workplace blocking ports or filtering traffic, my first suggestion would be don't try bypass their firewalls, from experience it's there for a reason and they don't look kindly on people getting around it.
Next; changing the routing on your computer will completely depend on the operating system that your using, so what OS are you running on the client?
For it to work you will probably need to create some kind of VPN connection so that the blocked traffic is tunneled through the filter instead of been dropped. Basically this will mean installing a VPN client on the workstation within your university and then also install a VPN server somewhere on the internet (outside of your university).
Alternatively you could purchase a VPN service, in which case you wouldn't need to supply the public internet VPN server, which would save some money if you don't already have the public server.
Finally most VPN services will operate as a default route for your traffic, meaning any internet facing traffic will go over this encrypted tunnel. You simply need to add your own routing on the operating system that will just use the tunnel for your application traffic and all other traffic will be routed as normal.
As stated before this completely depends on the operating system that your using.


text:
Q: Different benchmarks for string manipulation in C# and C++ I have two very simple code in C++ and C#
in c#
for (int counter = 0; counter < 100000; counter ++)
{
    String a = "";
    a = "xyz";
    a = a + 'd';
    a = a + 'c';
    a = a + 'h';
}

in c++
for (int counter = 0; counter < 100000; counter ++)
{
    string a = "";
    a.append("xyz");
    a = a + 'd';
    a = a + 'c';
    a = a + 'h';
}

the strange thing is the c# code took 1/20 time for execution than the c++ code.
could you please help me to find why this happened? and how can I change my c++ code to become faster.

A: It's probably a quirk of the implementations. For example, one optimizer might have figured out that the result of the operations isn't used. Or one might happen to allocate a string large enough to add three extra characters without reallocating while the other didn't. Or it could be a million other things.
Benchmarking with "toy" code really isn't helpful. I wouldn't assume the results apply to any realistic situation.
There are so many obvious optimizations to this code, for example:
string a;
for (int counter = 0; counter < 100000; counter ++)
{
    a = "xyz";
    a.append(1, 'd');
    a.append(1, 'c');
    a.append(1, 'h');
}

That may make a huge difference by reusing the buffer and avoiding extra allocate/copy/free cycles.

A: For large string manipulation use StringBuilder


text:
Q: What link references to include when setting up foundation project in phpStorm Firstly I am new to using foundation.
When you go onto foundations website and you download the complete foundation file you get this index file:

that has link references to the stylesheets and the Js files  and if you start coding everything works just fine, but if I create a foundation project through php storm it downloads the foundation release straight from GitHub, but this folder:

does not have a index file that includes the required css and js files, and I have tried to find the files but they are not included in this version from github. What files do I need to link to get foundation working.

A: In short, you'd need to link foundation.min.css and foundation.min.js. also, make sure you include jquery before the js.
I suggest downloading a bundle from Zurb's site in this link and recieve a good and working bundle.
Foundation is a great framework so don't give up, it's totally worth it.


text:
Q: What Runtime_Bad_Block mean in SMART Attributes? How critical is it? My SSD has the following SMART Attribute Pre-fail.
What does that mean and how critical is it?
183 Runtime_Bad_Block       0x0013   098   001   010    Pre-fail  Always   In_the_past 60

A: 183 0xB7 SATA Downshift Error Count or Runtime Bad Block has the following meaning:

Western Digital, Samsung or Seagate attribute: Either the number of
downshifts of link speed (e.g. from 6Gbit/s to 3Gbit/s) or the total
number of data blocks with detected, uncorrectable errors encountered
during normal operation. Although degradation of this parameter can be
an indicator of drive aging and/or potential electromechanical
problems, it does not directly indicate imminent drive failure.

You can check the SMART attibutes section on Wikipedia for more details.


text:
Q: Understanding ".with" in Ruby Sorry this is probably a question that has been asked many times but as it regards what is a very common word in English it is pretty much impossible to google or search for it.
I have seen a few examples of Ruby code which looks like this:
EnquiryNotification.with(post: @post)

I'm trying to understand what the ".with" part does.  Can anyone shed some light on this please?

A: with is a class method defined on the EnquiryNotification class (or one of its ancestors). The method is neither a keyword in the Ruby language nor is it a common method on classes shipped with Ruby itself or its standard library. As such, to find what this method does, you would likely have to consult the documentation of your chosen framework or application.
An example of a with method defined in a framework is Sequel::Dataset#with to add a CTE to the current query. The method is also available as a class method in Sequel model classes.
It could also be part of ActionMailer as mentioned by Stefan in a comment above.
In any case though, make sure to consult the documentation of your chosen framework or library for details.


text:
Q: Storing image in SQLite I am a beginner in android programming and I am trying to store information and image of different books in SQLite. I got some part of the below code from a site. I am able to store the information i.e author and title of the book but don't know how to store an image. I written the code forBook.java and MySQLiteHelper.java but don't know how to store and insert image using SQLite statement in the MainActivity.java.Can someone help?
This is my Book.java
 public class Book {
 int id;
 String title;
 String author;
 byte[] image;

public Book(){}

public Book(int id,String title, String author, byte[] image) {
    this.id=id;
    this.title = title;
    this.author = author;
    this.image=image;
}
public Book(String title, String author,byte[] image) {
    this.title = title;
    this.author = author;
    this.image=image;
}

//getters & setters
// getting ID
public int getId(){
    return this.id;
}

// setting id
public void setId(int id){
    this.id = id;
}
// getting title
public String getTitle(){
    return this.title;
}

// setting title
public void setTitle(String title){
    this.title = title;
}

// getting authorname
public String getAuthor(){
    return this.author;
}

// setting authorname
public void setAuthor(String author){
    this.author = author;
}
//getting image
public byte[] getImage() {
return this.image;
    }
//setting image
public void setImage(byte[] image) {
    this.image = image;
    }
}

This is my MySQLitehelper.java
public class MySQLiteHelper extends SQLiteOpenHelper {

// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "BookDB";
// Books table name
private static final String TABLE_BOOKS = "books";

// Books Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_AUTHOR = "author";
private static final String KEY_IMAGE = "image";
public MySQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    // SQL statement to create book table
    String CREATE_BOOK_TABLE = "CREATE TABLE" + TABLE_BOOKS+"("+ KEY_ID +" INTEGER PRIMARY KEY,"+ KEY_TITLE+" TEXT,"+ KEY_AUTHOR+ " TEXT," + KEY_IMAGE + " BLOB" + ")";

    // create books table
    db.execSQL(CREATE_BOOK_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older books table if existed
    db.execSQL("DROP TABLE IF EXISTS" + TABLE_BOOKS );

    // create fresh books table
    this.onCreate(db);
}
//---------------------------------------------------------------------
//*** CRUD operations (create "add", read "get", update, delete) book + get all books +      delete all books */

private static final String[] COLUMNS = {KEY_ID,KEY_TITLE,KEY_AUTHOR,KEY_IMAGE};

public void addBook(Book book){
    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put(KEY_TITLE, book.getTitle()); // get title
    values.put(KEY_AUTHOR, book.getAuthor()); // get author
    values.put(KEY_IMAGE, book.getImage()); // get author
    // 3. insert
    db.insert(TABLE_BOOKS, // table
            null, //nullColumnHack
            values); // key/value -> keys = column names/ values = column values

    // 4. close
    db.close();
}

public Book getBook(int id){

    // 1. get reference to readable DB
    SQLiteDatabase db = this.getReadableDatabase();

    // 2. build query
    Cursor cursor =
            db.query(TABLE_BOOKS, // a. table
            COLUMNS, // b. column names
            " id = ?", // c. selections
            new String[] { String.valueOf(id) }, // d. selections args
            null, // e. group by
            null, // f. having
            null, // g. order by
            null); // h. limit

    // 3. if we got results get the first one
    if (cursor != null)
        cursor.moveToFirst();

    // 4. build book object
    Book book = new Book();
    book.setId(Integer.parseInt(cursor.getString(0)));
    book.setTitle(cursor.getString(1));
    book.setAuthor(cursor.getString(2));
    book.setImage(cursor.getBlob(3));
    // 5. return book
    return book;
}

// Get All Books
public List<Book> getAllBooks() {
    List<Book> books = new LinkedList<Book>();

    // 1. build the query
    String query = "SELECT  * FROM " + TABLE_BOOKS;

    // 2. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);

    // 3. go over each row, build book and add it to list
    Book book = null;
    if (cursor.moveToFirst()) {
        do {
            book = new Book();
            book.setId(Integer.parseInt(cursor.getString(0)));
            book.setTitle(cursor.getString(1));
            book.setAuthor(cursor.getString(2));
            book.setImage(cursor.getBlob(3));
            // Add book to books
            books.add(book);
        } while (cursor.moveToNext());
    }
    // return books
    return books;
}

 // Updating single book
public int updateBook(Book book) {

    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put("title", book.getTitle()); // get title
    values.put("author", book.getAuthor()); // get author
    values.put("image", book.getImage()); // get image

    // 3. updating row
    return db.update(TABLE_BOOKS, //table
            values, // column/value
            KEY_ID+" = ?", // selections
            new String[] { String.valueOf(book.getId()) }); //selection args

}

// Deleting single book
public void deleteBook(Book book) {

    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. delete
    db.delete(TABLE_BOOKS,
            KEY_ID+" = ?",
            new String[] { String.valueOf(book.getId()) });

    // 3. close
    db.close();
}
}

This is my MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    MySQLiteHelper db = new MySQLiteHelper(this);

    /**
     * CRUD Operations
     * */
    // add Books
    Log.d("Inserting: ", "Inserting all Books..");
    db.addBook(new Book("Android Application Development Cookbook", "Wei Meng Lee"));
    db.addBook(new Book("Android Programming: The Big Nerd Ranch Guide", "Bill Phillips and Brian Hardy"));
    db.addBook(new Book("Learn Android App Development", "Wallace Jackson"));
   //Reading and getting all books
    Log.d("Reading: ", "Reading all Books..");
    List<Book> list = db.getAllBooks();
    for (Book cn:list) {
        String log = "Id: "+cn.getId()+" ,Title: " + cn.getTitle() + " ,Author: " + cn.getAuthor() + ",Image: "+ cn.getImage();
            // Writing Contacts to log
    Log.d("Name: ", log);
   // delete one book
   db.deleteBook(list.get(0));

}
}
}

A: public void insertImg(int id , Bitmap img ) {

byte[] data = getBitmapAsByteArray(img); // this is a function

insertStatement_logo.bindLong(1, id);
insertStatement_logo.bindBlob(2, data);

insertStatement_logo.executeInsert();
insertStatement_logo.clearBindings() ;

}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();

}
public Bitmap getImage(int i){

String qu = "select img  from table where feedid=" + i ;
Cursor cur = db.rawQuery(qu, null);

if (cur.moveToFirst()){
    byte[] imgByte = cur.getBlob(0);
    cur.close();
    return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
}
if (cur != null && !cur.isClosed()) {
    cur.close();
}

return null ;

}
More

A: For storing Image in a database you need to convert the image data to a binary form an store it in the database and when retrieving the image you need to convert it into the Bitmap format,but this is not recommended because storing images in database are somewhat tricky and complex,alternatively you can store the Image in a folder in sdcard and store only the path in the database,anyway if you still want to store the image in the database you can refer this question

A: private String prepareImage(String imagepath) {
        if (imagepath== null) {
            return "";
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(imagepath, options);
        bitmap = Bitmap.createScaledBitmap(bitmap, 50, 50, true);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 50, baos);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);

        byte[] byteArray = baos.toByteArray();

        String imageString = com.eg_lifestyle.utils.Base64
                .encodeBytes(byteArray);
        bitmap = null;
        System.gc();
        Runtime.getRuntime().gc();
        return imageString;
    }

i hope this is useful to you..

A: This code for me. you can get proper solution
Uri selectedImage = data.getData();
     ImageView imageView=(ImageView)this.findViewById(R.id.imageView1);

    getContentResolver().notifyChange(selectedImage, null);

    ContentResolver cr = getContentResolver();
    Bitmap bitmap;
    try {

        bitmap = android.provider.MediaStore.Images.Media
         .getBitmap(cr, selectedImage);
        imageView.setImageBitmap(bitmap);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        String encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);

        byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT);
        Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
                bytarray.length);

        myDb.execSQL("INSERT INTO imgtbl VALUES('"+encodedImageString+"');");
        Cursor c= myDb.rawQuery("SELECT * FROM imgtbl", null);

       c.moveToFirst();
       String img=c.getString(0);
       byte[] byarray = Base64.decode(img, Base64.DEFAULT);
       Bitmap bmimg = BitmapFactory.decodeByteArray(byarray, 0,
               byarray.length);

        ImageView iv=(ImageView)findViewById(R.id.img2);
        ImageView iv1=(ImageView)findViewById(R.id.img3);

        iv.setImageBitmap(bmimg);
        iv1.setImageBitmap(bmimg);

    } catch (Exception e) {
        Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                .show();

        e.printStackTrace();
    }


text:
Q: php alphanumeric id with fixed letter position I need to create unique alphanumeric IDs, 6 characters long in PHP.
Although I have found a lot of answers solving this problem, I would like the letters to be positioned in specific place in the ID, for example A1B2C3 (first, third and fifth character).
My only solution for this is to create 6 "for" loops (a-z and 0-9 * 3 times) and insert the output in an array and then in MySQL table. There will definitely be no duplicates but is there any better way?
My code so far is:
<?php

   $id=array();

   for($a='A';$a!='AA';$a++){
        for($b=1;$b<=9;$b++){
           for($c='A';$c!='AA';$c++){
              for($d=1;$d<=9;$d++){
                  for($e='A';$e!='AA';$e++){
                     for($f=1;$f<=9;$f++){

                       $id[]=$a.$b.$c.$d.$e.$f;
                     }
                  }
              }
           }
        }
    }

    foreach ($id as $value) {
        echo "$value \n";
    }
?>

A: For unique and random IDs, when you don't need sequential IDs:
$numIds = 20000; // how many ids do you want to generate and insert?

// db setup
$conn = mysqli_connect('localhost', 'root', '', 'dbtest');
$insertstmt = mysqli_prepare($conn, 'INSERT INTO ids (id) VALUES (?)');

// generate ids array
$ids = [];
for ($ii = 0; $ii < $numIds; $ii++) {
  do { // execute loop at least once

    // inspired by @chris85 's comment
    $id = randChr() . rand(0, 9) . randChr() . rand(0, 9) . randChr() . rand(0, 9);

  } while ( // try again if found in either db or array
    idInDb($conn, $id) || // not actually needed on first run
    (0 < count($ids) && in_array($id, $ids, true))
  );
  $ids[] = $id; // is unique, add to array
}

// insert ids
mysqli_stmt_bind_param($insertstmt, 's', $id);
mysqli_autocommit($conn, false);
foreach ( $ids as $id ) {
  mysqli_stmt_execute($insertstmt);
}
mysqli_commit($conn);
mysqli_close($conn);

// helper functions

function randChr () { // generate random alpha character
  return chr(rand(65, 90)); // upper case only
  //return chr(rand(0, 1) ? rand(65, 90) : rand(97, 122));
  // use alternative return for upper AND lower case
}

function idInDB ($conn, $testid) { // check for id in db
  $query = "SELECT id FROM ids WHERE id = '$testid'";
  $result = mysqli_query($conn, $query);
  $found = 0 < mysqli_num_rows($result);
  mysqli_free_result($result);
  return $found;
}

PHP Sandbox demo

A: If you need sequential IDs:
// to start
//$numIds = 20000;
//$id = '';

// to add more
$numIds = 1000;
$id = 'A1J5M2'; // put MAX id from DB here

if ( '' !== $id ) { // increment id
  list($aa, $bb, $cc, $dd, $ee, $ff) = str_split($id);
  $arr = [$aa, $bb, $cc, $dd, $ee, $ff];
  list($aa, $bb, $cc, $dd, $ee, $ff) = incc($arr, count($arr) - 1);
}
else {
  list($aa, $bb, $cc, $dd, $ee, $ff) = ['A',1,'A',1,'A',1];
}

// generate ids
$ids = [];

for($a=$aa;$a!='AA';$a++){
  for($b=$bb;$b<=9;$b++){
    $bb = 1; // reseting b - f is necessary when adding more ids
    for($c=$cc;$c!='AA';$c++){
      $cc = 'A';
      for($d=$dd;$d<=9;$d++){
        $dd = 1;
        for($e=$ee;$e!='AA';$e++){
          $ee = 'A';
          for($f=$ff;$f<=9;$f++){
            $ff = 1;

            $ids[] = "$a$b$c$d$e$f";
            // break out of all loops when desired number is reached
            if ( $numIds <= count($ids) ) { break 6; }
}}}}}}

// db setup
$conn = mysqli_connect('localhost', 'root', '', 'dbtest');
$insertstmt = mysqli_prepare($conn, 'INSERT INTO ids (id) VALUES (?)');

// insert ids
mysqli_stmt_bind_param($insertstmt, 's', $id);
mysqli_autocommit($conn, false);
foreach ( $ids as $id ) {
  mysqli_stmt_execute($insertstmt);
}
mysqli_commit($conn);
mysqli_close($conn);

// function to increment given id, accommodates rolling over, e.g., A9 -> B1
function incc ($arr, $idx) {
  if ( is_int(intval($arr[$idx])) ) {
    if ( 9 == $arr[$idx] ) {
      $arr[$idx] = 1;
      $arr = incc($arr, --$idx); // recursing
    }
    else {
      $arr[$idx]++;
    }
  }
  else {
    if ( 'Z' === $arr[$idx] ) {
      $arr[$idx] = 'A';
      $arr = incc($arr, --$idx);
    }
    else {
      $ord = ord($arr[$idx]);
      $ord++;
      $arr[$idx] = chr($ord);
    }
  }
  return $arr;
}

PHP Sandbox demo


text:
Q: System font is wrong Ubuntu 14.04 LTS.
After rebooting my machine following a hang by the Software Updater (updates appeared not to have been installed, but subsequently have been), the system font is appearing wrong (too small, borderline unreadable) in my main user account.  It appears correctly if I log in as Guest.
The font is wrong in all window titles, Chromium tab headers and code editor in Eclipse.  Haven't tried anything else.
I notice also that I cannot resize the icons in "my" account.  They are stuck at what looks like 0.625 (the size I had them before).  Resizing them from System Settings -> Screen Display works fine in the Guest account but does nothing in "my" account.  This is not a problem for me, they're the size I want them, but possibly provides extra information.
I have downloaded the "GNOME Tweak Tool" and the fonts/sizes it lists are all identical for "my" account and the Guest account.  Changing the size of the "Window titles" font has the expected effect in the Guest account, but no affect in "my" account.
Logging out and rebooting do not help.

A: As your current user settings seem to be corrupted, and the guest account is not affected, do the following:
Go to system settings - User accounts create an additional user (let's call it "User2") with the same privileges as your current user.
Now, log out of the "bad" session and log in as "user2" and come back here to this site.
Everything is fine? Well then you should "accept" this answer as valid by clicking on the little grey check-mark below the "0" to the left of this answer and the next person asking the same kind of question will be able to use it as well.
Done?  OK?
Now,

*

*open the file manager

*browse to the /home/user directory

*copy (not move!) all the files from Downloads to /home/user2/Downloads

*check you did a good job.

*Now delete /home/user/Downloads

*Go back to step 3 and repeat for Documents, Videos, ...

Done!


text:
Q: ivars allowed in Cocoa Touch-based anonymous category but not in "regular" Cocoa? I noticed two things when switching between iOS and regular OS X development:
//SomeClass.h
@interface SomeClass: SomeUIClass

    @property (retain)SomeProperty* someProperty;

@end

//SomeClass.m
@interface SomeClass ()
{
    SomePrivateVar* somePrivateVar;
}
@end

@implementation SomeClass

@synthesize someProperty;
@end

The above will compile just fine under iOS. That is:

*

*I can synthesize the property without declaring an ivar explicitly
in the public @interface

*I can further declare other private ivars in the .m file under the
anonymous category (class extension).

However, if compiling for OS X and subclassing some NS-based class as opposed to a UI-based one (say, NSView instead of UIView), both the above things result in compiler errors.
I guess I thought Objective-C 2. allowed for the above in general, but they are only "shortcuts" in iOS? or what's the deal with them being allowed in iOS but not in OS X?

A: Those are features of the "modern runtime" which can only be used for 64 bit apps on Mac OS X. You're probably building a universal binary that also includes a 32 bit version.


text:
Q: Sum of elements of array I have array like this from DB
$arr = [
  '0.4%',
  '0.5%',
  '0.6%',
];

I would to sum elements. What is the most correct way to do it?

A: You can use
array_sum($arr);

it will automatically convert the values and add them together.


text:
Q: XPath how to get all text in paragraph tag and all its inner nested texts such as bold words I have the below html:

Text a
    Bold inner
Text b.

I want an xpath to get all the text i.e. I want returned: Text a Bold inner Text b..
This: /p/text() will only get me Text a. How can I do this?


text:
Q: result of call warning - want to use the result? I have some difficulties with the new Swift 3.0.  First I know the "result of call is unused" warning has been debated a few times already. I have read the topics in question and usually the suggested answer is to use @discardableResult or using _ = before the function. But in my case this isn't working. Before upgrading xCode the code worked great. I tested it on my iPad and everything was ok. But then once I upgraded xCode and had to convert the code to comply with Swift 3.0 the problem appeared.
The thing is that whatever I do, the object in the game isn't showing as it should. Like I said, previously it worked, but now it doesn't anymore. When the character runs into the object and it crashes it, the game should display a crashed object, but instead it shows an image with a red "X" as if the image isn't there.
Here is the code. I would appreciate any suggestion you guys have. Thanks in advance
            for block in Blocks
        {
            block.move()
            block.isColB()
            if(block.manager.HasFloorL2)
            {
                if(block.isOnL2())
                {
                    if(block.manager.FloorL2Obstact)
                    {
                        block.ObsColL2() // here, result of call to ObscColL2() is unused
                    }
                    break;
                }
            }
            if(block.manager.HasFloorL1)
            {
                if(block.isOnL1())
                {
                    if(block.manager.FloorL1Obstact)
                    {
                        block.ObsColL1() // here, result of call to ObscColL1() is unused
                    }
                    break;
                }
            }
        }

Here is the function it refers to.
    func ObsColL1() -> Bool
{
    if(kong.Node.position.x+kong.Node.size.width*0.7 > self.holder.position.x+ObstacleL1.Node.position.x
        && kong.Node.position.x+kong.Node.size.width*0.7 < self.holder.position.x+ObstacleL1.Node.position.x+ObstacleL1.Node.size.width*0.3)
    {
        if(kong.Y() <= self.holder.position.y+(ObstacleL1.Node.position.y)+ObstacleL1.Node.size.height*0.7 && kong.Y() >= self.holder.position.y+ObstacleL1.Node.position.y)
        {
            if(kong.state != heroStates.flash && !self.ObstacleL1.crashed)
            {
                kong.Node.position.x = self.holder.position.x+ObstacleL1.Node.position.x-(kong.Node.size.width*0.55)
                kong.Node.run(SKAction.moveTo(y: self.holder.position.y+ObstacleL1.Node.position.y+ObstacleL1.Node.size.height/2, duration: 0.5))
                kong.die()
            }
            else
            {
                ObstacleL1.crash()
                return true
            }
        }
    }
    return false
}

EDIT:
before and after
before and after
before and after 2


text:
Q: Matching interacting terms to a vector I am trying to merge the xy vector with z vector according to the interaction terms that are in xy to the terms in z. Then change the final code to Q1, Q2...Q1*Q2
I have two vectors that need to match as vector xy:
x<-c(1,1,1,1,1,1,1,2,2,2,2,2,3,3,3,4,6,6,9,10,16,21)
y<-c(1,2,3,5,6,8,18,1,2,5,6,7,8,12,15,16,11,17,18,19,20,21)

I want any  of 2*6,or 6*11 to be added to the vector z for any case of z because according to vector xy there are interactions between 2,6,11 according to vector z
      xy=paste0(x,"*",y,collapse=",")
      xy
    # [1] #"1*1,1*2,1*3,1*5,1*6,1*8,1*18,2*1,2*2,2*5,2*6,2*7,3*8,3*12,3*15,4*16,6*11,6*17,#9*18,10*19,16*20,21*21"
     z<-c(2,6,11)
     z
    #[1]  2  6 11

I want a fourth vector to have all interactions of z from vector xy and combined into a new vector xyz
     xyz<-print("2+6+11+2*6+6*11")
    #[1] "2+6+11+2*6+2*11+6*11"
     xyz
    #[1] "2+6+11+2*6+2*11+6*11"

then for each varaible 2,6,11 convert to Q1,Q2,Q3 So the end product looks like...
     xyz<-print("Q1+Q2+Q3+Q1*Q2+Q2*Q3")
    #[1]
  #End result:
 #"Q1+Q2+Q3+Q1*Q2+Q2*Q3"

A: Just loop through x/y and add an interaction if they are element of z:
x <- c(1,1,1,1,1,1,1,2,2,2,2,2,3,3,3,4,6,6,9,10,16,21)
y <- c(1,2,3,5,6,8,18,1,2,5,6,7,8,12,15,16,11,17,18,19,20,21)
z <- c(2,6,11)

xyz <- as.character(z)

for(i in 1:length(x)){
  if(x[i] %in% z & y[i] %in% z & x[i] != y[i]){
    xyz <- c(xyz, (paste0(x[i], "*", y[i])))
  }
}

xyz <- paste(xyz, collapse = "+")

Then replace these numbers with any coding you define:
z_map <- c("Q1", "Q2", "Q3")
for(i in 1:length(z)){
  xyz <- gsub(z[i], z_map[i], xyz)
}


text:
Q: Return CATransform3D to map quadrilateral to quadrilateral I'm trying to derive a CATransform3D that will map a quad with 4 corner points to another quad with 4 new corner points. I've spent a little bit of time researching this and it seems the steps involve converting the original Quad to a Square, and then converting that Square to the new Quad. My methods look like this (code borrowed from here):
- (CATransform3D)quadFromSquare_x0:(float)x0 y0:(float)y0 x1:(float)x1 y1:(float)y1 x2:(float)x2 y2:(float)y2 x3:(float)x3 y3:(float)y3 {

    float dx1 = x1 - x2,    dy1 = y1 - y2;
    float dx2 = x3 - x2,    dy2 = y3 - y2;
    float sx = x0 - x1 + x2 - x3;
    float sy = y0 - y1 + y2 - y3;
    float g = (sx * dy2 - dx2 * sy) / (dx1 * dy2 - dx2 * dy1);
    float h = (dx1 * sy - sx * dy1) / (dx1 * dy2 - dx2 * dy1);
    float a = x1 - x0 + g * x1;
    float b = x3 - x0 + h * x3;
    float c = x0;
    float d = y1 - y0 + g * y1;
    float e = y3 - y0 + h * y3;
    float f = y0;

    CATransform3D mat;

    mat.m11 = a;
    mat.m12 = b;
    mat.m13 = 0;
    mat.m14 = c;

    mat.m21 = d;
    mat.m22 = e;
    mat.m23 = 0;
    mat.m24 = f;

    mat.m31 = 0;
    mat.m32 = 0;
    mat.m33 = 1;
    mat.m34 = 0;

    mat.m41 = g;
    mat.m42 = h;
    mat.m43 = 0;
    mat.m44 = 1;

    return mat;

}

- (CATransform3D)squareFromQuad_x0:(float)x0 y0:(float)y0 x1:(float)x1 y1:(float)y1 x2:(float)x2 y2:(float)y2 x3:(float)x3 y3:(float)y3 {

    CATransform3D mat = [self quadFromSquare_x0:x0 y0:y0 x1:x1 y1:y1 x2:x2 y2:y2 x3:x3 y3:y3];

    // invert through adjoint

    float a = mat.m11,      d = mat.m21,    /* ignore */            g = mat.m41;
    float b = mat.m12,      e = mat.m22,    /* 3rd col*/            h = mat.m42;
    /* ignore 3rd row */
    float c = mat.m14,      f = mat.m24;

    float A =     e - f * h;
    float B = c * h - b;
    float C = b * f - c * e;
    float D = f * g - d;
    float E =     a - c * g;
    float F = c * d - a * f;
    float G = d * h - e * g;
    float H = b * g - a * h;
    float I = a * e - b * d;

    // Probably unnecessary since 'I' is also scaled by the determinant,
    //   and 'I' scales the homogeneous coordinate, which, in turn,
    //   scales the X,Y coordinates.
    // Determinant  =   a * (e - f * h) + b * (f * g - d) + c * (d * h - e * g);
    float idet = 1.0f / (a * A           + b * D           + c * G);

    mat.m11 = A * idet;     mat.m21 = D * idet;     mat.m31 = 0;    mat.m41 = G * idet;
    mat.m12 = B * idet;     mat.m22 = E * idet;     mat.m32 = 0;    mat.m42 = H * idet;
    mat.m13 = 0       ;     mat.m23 = 0       ;     mat.m33 = 1;    mat.m43 = 0       ;
    mat.m14 = C * idet;     mat.m24 = F * idet;     mat.m34 = 0;    mat.m44 = I * idet;

    return mat;

}

After calculating both matrices, multiplying them together, and assigning to the view in question, I end up with a transformed view, but it is wildly incorrect. In fact, it seems to be sheared like a parallelogram no matter what I do. What am I missing?
UPDATE 2/1/12
It seems the reason I'm running into issues may be that I need to accommodate for FOV and focal length into the model view matrix (which is the only matrix I can alter directly in Quartz.) I'm not having any luck finding documentation online on how to calculate the proper matrix, though.

A: I was able to achieve this by porting and combining the quad warping and homography code from these two URLs:

*

*http://forum.openframeworks.cc/index.php/topic,509.30.html

*http://forum.openframeworks.cc/index.php?topic=3121.15
UPDATE: I've open sourced a small class that does this: https://github.com/dominikhofmann/DHWarpView


text:
Q: Time complexity of stl set_symmetric_difference I was reading the time complexity of stl set_symmetric_difference
It says:

Up to linear in 2*(count1+count2)-1 (where countX is the distance
  between firstX and lastX): Compares and assigns elements.

I'm confuse with the statement "countX is the distance between firstX and lastX".
Please clarify it with an example.

A:
I'm confused with the statement "countX is the distance between firstX and lastX".

From the example on the same page you are linking to:

first1, last1
Input iterators to the initial and final positions of the first sorted sequence. > The range used is [first1,last1), which contains all the elements between first1 > and last1, including the element pointed by first1 but not the element pointed
  by last1.
first2, last2
Input iterators to the initial and final positions of the second sorted sequence. The range used is [first2,last2).

So, count is the std::distance (i.e. number of hops) between the sorted elements of iterators representing first and last element in the data structure (array in the example). For first (sorted: 5 10 15 20 25) that would be 5.
As for the complexity of std::distance:

Linear.
However, if InputIt additionally meets the requirements of RandomAccessIterator, complexity is constant.


text:
Q: Zoom effect to scroll able Image
I have layout in that it contain a horizontal scroll scale.
My question is how make this type of zoom effect on the center of the layout?
Is it possible?
i have draw the scale in canvas and zoom the canvas??
Please help me.
Thank's in advance.

A: I think you want a Transformation: http://developer.android.com/reference/android/view/animation/Transformation.html
The code in your onDraw method will look something like this:
canvas.save();
transformation.transform(canvas);
drawable.draw(canvas);
canvas.restore();

A: Step 1: At first draw the scale(drawing) on a canvas.
Step 2: get the zooming region, and apply this region as the clipRegion on the canvas ..
Step 3: get the bitmap from the canvas, and draw it on the canvas applying scale on it,scaling pivot point will be the center point of the area you want to zoom,
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bitmap_object = Bitmap.createBitmap(width, height, conf);
Canvas canvas_object = new Canvas(bitmap_object);

/* now  draw your drawing on canvas_object */

Bitmap temp = bitmap_object;

Matrix matrix_object = new Matrix();

/* now set transform and scale on matrix_object to zoom */

Paint paint_object = new Paint();
paint_object.setFilterBitmap(true);

Region reg= /* region of your zooming area */
canvas_object.clipRegion(reg);
canvas_object.drawBitmap(temp,matrix_object,paint_object);


text:
Q: Can 'surgery' be a count noun in the sense of 'medical procedure'? This is something that has bothered me for a long time. Several years ago a remember noticing in the media a shift from using "An operation" to "A surgery" when talking about someone who was undergoing a medical procedure.
Now, to my ears "A surgery" sounded patently wrong. To me it sounded a lot like saying "A water". In the sense of 'medical procedure', surgery is a mass noun to me, and using it as a count noun is ungrammatical.
I'm entirely prepared to be told to go away and stop being so ridiculous. This could all, in the end, entirely be the ramblings of someone who sees the English language in his own peculiar way. But is it just me?
Is "a surgery" a legitimate and commonly accepted use of the word?

A: I find three definitions of surgery in Merriam-Webster's Eleventh Collegiate Dictionary (2003) for which the plural surgeries seems eminently reasonable:

3 a Brit : a physician's or dentist's office b : a room or area where surgery is performed 4 [...] b : OPERATION

That a room where physicians receive and examine or operate on patients may be called "a surgery" and that multiple such rooms may be called "surgeries" seem unexceptionable to me. An entry for "a surgery" appears in John Kersey, A New English Dictionary, eighth edition (1772):

A Surgery, a place or room where a surgeon performs his operations.

And Rowland Jackson, A Physical Dissertation on Drowning (1746) gives this instance of the phrase in action:

The Surgeons of the Town having obtained his Body, in order to make a Skeleton, brought it into a Surgery, where they left it upon a Table ; but when they came next Day to dissect: it, they were surprized to find the Man not only alive, but in good Health, and pissing in the Chimney for want, as he said, of a Chamber-pot.

Definition 4b of surgery (the single word "OPERATION") is presumably a more hotly disputed case. And yet that definition has been appearing in editions of the Merriam-Webster Collegiate series for more than 50 years—since the Seventh Edition (1963).
A Google Books search finds this early instance from John Aitken, Systematic Elements of the Theory and Practice of Surgery (1779):

Spina ventosa indicates a Surgery nearly similar to that proposed for Caries [chapter reference omitted]. Trepanation may produce the most salutary effects before the lamellated portion of the Bone be eroded.

Here, "a Surgery" seems to mean "a form of surgery." But it could just as well mean "an operation." And in this example, from Russell Trall, The Hydropathic Encyclopedia: A System of Hydropathy and Hygiene (1853):

DROPSY OF THE SPINE.—This affection is mostly congenital ; it consists of a soft fluctuating tumor on the spine, from fluid accumulated within the coats of the spinal cord, protruding externally in consequence of some portion of the vertebral column being defective. It is generally fatal, although a cure has taken place spontaneously in a few instances, and several cases have been reported as cured by repeatedly puncturing the sac with a fine needle. With the exception of this surgery, if deemed advisable, the proper course is to attend to the general health, and "trust to nature."

the equivalence between "this surgery" and "this operation" seems clear. Is the phrase "this surgery" less offensive to some sensitive persons' ears than "a surgery" is? I wouldn't be surprised if that proved to be the case—and if it did, it seems to me, instances of "this surgery" might have acted as the advance party of Achaeans entering the city and then unlocking it to the subsequent depredations of "a surgery."
An Ngram chart of "a surgery" (blue line) versus "this surgery" (red line) for the period 1700–2000 suggests that "a surgery" broke out of its fairly stable frequency between the 1870s and the 1930s when "this surgery began its steep ascent during the 1940s:

As the chart indicates, despite the rapid increase in frequency of "a surgery" since about 1970, the frequency of "this surgery" has grown at an even faster rate. The plural form surgeries (green line), meanwhile, has dwarfed both "a surgery" and "this surgery" in frequency, again starting around 1970:

And interestingly, whereas recent instances in the Google Books search results for "a surgery" skew heavily toward instances where "a surgery" is followed by a noun such as "room" or "center," many recent examples of "surgeries" clearly use it in the sense of "operations"—in constructions such as "vascular surgeries are frequent features..." and "By clustering surgeries with similar duration variability characteristics..." and "adverse event rates among glaucoma surgeries..."
It thus appears that dissatisfaction with "a surgery" may be somewhat misdirected, since the terms "this surgery" and "surgeries" show up much more frequently in the Google Books database in the reprehended sense of "operation[s]" than "a surgery" does.


text:
Q: Get loaded resource files list from android webview Is there any way to get the currently successfully loaded and not loaded files from URL into android webview. That is, if I am loading the following,

*

*1.js, 2.js, 3.js

*1.css, 2.css, 3.css

in html page and load the html file into android webview.
I need to list the loaded files in webview and also which are unable to load into android webview. I tried using the onConsoleMessage() from WebchromeClient which detects only the console error alone. This method not getting the error messages for css image.
Is this possible to list the files from URL?

A: You can get the list of resources the WebView is trying to load by overriding WebViewClient.shouldInterceptRequest like so:
class MyWebViewClient extends WebViewClient {

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        android.util.Log.i("MyWebViewClient", "attempting to load resource: " + url);
        return null;
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        android.util.Log.i("MyWebViewClient", "attempting to load resource: " + request.getUrl());
        return null;
    }

}
Remember that shouldInterceptRequest is called on a background thread and so you need synchronize access to any shared data structures.
There is no Java API to find out whether the WebView has successfully loaded a given resource though.


text:
Q: Conceptual Proof of Quadratic Reciprocity What is a conceptual proof of quadratic reciprocity?  I saw the wiki proof using algebraic machinery. I don't know what field extensions, Galois groups etc are. But I want to understand how properties under different moduli primes are getting related. I always wanted to understand how can one use all the modulo p information to understand globally. I would like to know if someone can explain quadratic reciprocity in a way that I will understand.

A: I don't think that there is any answer that is both elementary (comprehensible without knowing what fields, groups, etc are) and conceptually clear.  There are combinatorial proofs such as by Zolotarev (cf. Zolotarev's lemma) or the one (by Eisenstein? or Gauss?) that counts lattice points under the line from (0,0) to (p,q), but they hardly dispel the mystery.
To "understand how can one use all the modulo p information to understand globally", there seems to be no way around the interpretation of QR using Hilbert symbols, or else the far more demanding approach using class field theory.  In the Hilbert symbol formulation, there is a single object, the quadratic polynomial $Q(x,y,z) = x^2 - py^2 - qz^2$ that has nonzero solutions modulo any prime $k$ other than $p$ or $q$; has mod $p$ and mod $q$ solutions according to the signs of the Legendre symbols; and obeys a product formula stating that the product of all the $\pm$ signs at all primes is equal to $1$.  This is a global constraint on the local solvability at different primes.  The proof of the product formula is of course more complicated than the elementary proofs of quadratic reciprocity (you can find it in many places such as Serre's "course in arithmetic") but it has the advantage of being a general principle that applies to other situations.
As you can imagine, the one-sentence description of the product formula leaves out some details.  Solutions mod $p$ are not enough, one needs solutions mod $p^n$ for all $n$, or equivalently, p-adic solutions, but for odd primes and for $Q(x,y,z)$ of degree 2 (i.e., less than $p$) this comes to the same thing.  Real solutions are included as an "infinite" (Archimedean) prime in the product formula.  The 2-adic and real "$\infty$-adic" solutions have to be treated separately as reflected in the existence of supplementary formulae for the Legendre symbols determining squareness of $2$ and $-1$ modulo odd primes.  The basic point is the same, that there is a $\pm 1$ sign for each prime and a constraint that the product of all the signs is $+1$, something that is true for more general quadratic forms and for this particular $Q$ reduces to the statement of quadratic reciprocity.
The same story can be told in increasingly general versions for number fields, global fields and Riemann surfaces, rendered as a localization statement in K-theory, connected to the class field theory of quadratic fields, (maybe expressed in the language of motives), etc.  For myself, I don't see how even with this additional 200 years' hindsight and extensive additional theory, the quadratic reciprocity formula is any less astounding than it was in Euler and Lagrange's time.

A: See Davenport "The Higher Arithmetic" for an elementary approach. Also see "An Introduction to the Theory of Numbers" for several approaches to proving quadratic reciprocity.


text:
Q: using std::enable_if on a method of a templated class Consider the following code
template <class D> class Box {
private:
  D d_;
public:
  Box(D d) : d_(d) {}

  D value() {
    return d_;
  }
  D negate() {
    return -d_;
  }
};

I would like the method negate() to only be present/available when D is arithmetic type.   Is this possible?

A: I figured out a way to do it:
template <class D> class Box {
private:
  D d_;
public:
  Box(D d) : d_(d) {}

  D value() {
    return d_;
  }

  template< typename T=D >
  typename std::enable_if<is_arithmetic<T>::value, T >::type
    negate() {
    return -d_;
  }
};


text:
Q: Which way can 'fit' go? Can I use the word fit like this:

*

*'Pick an envelope that fits everything' as in Pick an envelope that is suitable in size and shape for all the papers you have to put in there

*'The tires won't fit my rims'  as in The tires are too small/big/wide/narrow for my rims

*'Do you think the trunk fits all our luggage?' as in Do you think the trunk is big enough for all our luggage?

*'My car won't fit the space' as in My car is too big for that small parking space.
I caused quite some drama in a forum. For instance, someone said this:

I couldn't either, because subject-verb-object standard English word
  order causes that to be understood as "could one trunk be squeezed
  into all the different pieces of luggage.?" :confused:

or

To fit is either intransitive - My car fits into the space; or
  transitive - My car fits the space.
My car fits into the space - This has a nuance of motion -> my car
  will go into the space. My car fits the space. - This has the nuance
  of "the space is a suitable size for my car."
"The jeans won't fit you." could be interpreted as ... To fit does not
  mean "They won't look good on you." To fit does not mean "You won't
  fit into them"
To fit does mean "They are too large/small."
To fit -> to be a suitable size.

or

Pick an envelope which fits everything." is non standard, reversal of
  usual direction.

or

If one is buying a tire, and tries it out, one might find, "This tire
  does not fit my rims" just as "This hat does not fit my head." This is
  what I call reverse direction, which applies to some contexts.
See definitions 10 and 14 at W-R online, first and second, below: to
  be of the right size or shape for:The dress fitted her perfectly. to
  put with precise placement or adjustment:He fitted the picture into
  the frame. Note the variant of 1. She fitted herself into the dress
  with great difficulty. Second sense, above.

These answers contradict themselves. But if 'fit' means 'suitable' my example sentences are acceptable to say.

A:
'Pick an envelope that fits everything' as in Pick an envelope that is
  suitable in size and shape for all the papers you have to put in there

"Select/choose/pick an/one envelope that fits your needs/requirements/all of the papers."

'The tires won't fit my rims' as in The tires are too
  small/big/wide/narrow for my rims

Be specific and saying exactly what you mean. "These/the tires are too whatever for my rims." I think that sentence was fine, but clarity is always good.

'Do you think the trunk fits all our luggage?' as in Do you think the
  trunk is big enough for all our luggage?

" Will all of the/our luggage fit into the trunk?" Or, "Do you think the trunk is big enough for all our luggage?"
'My car won't fit the space' as in My car is too big for that small parking space.
That works, but again to be absolutely clear, say what you mean. "My car is too big for that parking spot/space." Or, "My big car won't fit in that small space." Or, "My car won't fit in that space because my car is too big." OR, "The parking space to to small to fit my car/for my car to fit."

A: Your sentences are acceptable and will be understood.  What you've done is truncate the preposition or prepositional phrase in each sentence.  With the phrase added they all make sense.

Pick an envelope that fits everything [into it].
The tires won't fit [onto] my rims.
Do you think the trunk fits all our luggage [into it]?
My car won't fit [into] the space.

A: X fit(s) Y means X can wear Y successfully, or that X and Y have complementary shapes and can interlock or other similar action.  It can also mean Y can wear X successfully.

The dress fits me.
I fit the dress.

Both mean the same.  There can be an implication that the direct object is what you are trying to fit the subject to.
X fit(s) can be reflexive, it's equal to saying X fits me or X fits myself, but it can also refer to an elided direct object, e.g. "I bought the dress for Cheryl.  It fits! (= It fits Cheryl)."
X fit(s) in Y means Y is a container capable of successfully containing X.