text:
Q: Map reduce to duplicate the output files in order to put in different tables in hive I have a MASTER table and two other tables in hive
Master table contains

MsgId,NbOfTxs,InitgPty,PmtInf,DbtrAcct

Sub Master Table 1
MsgId,NbOfTxs,DbtrAcct

Sub Master Table 2
MsgId,NbOfTxs,InitgPty

The data are in xml format .I have written MR code to parse it . I would like to create different part -r files so that they  put output to the tables in hive directly
How can I put or load the OUTPUT files  directly to hive using MapReduce to load in  corresponding hive tables or is there a better way to put these files in hive tables
My code below
package xmlcsvMR;
import javax.xml.stream.XMLStreamConstants;//XMLInputFactory;
import java.io.*;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import javax.xml.stream.*;

public class XmlParser11
{

        public static class XmlInputFormat1 extends TextInputFormat {

        public static final String START_TAG_KEY = "xmlinput.start";
        public static final String END_TAG_KEY = "xmlinput.end";

        public RecordReader<LongWritable, Text> createRecordReader(
                InputSplit split, TaskAttemptContext context) {
            return new XmlRecordReader();
        }

        /**
         * XMLRecordReader class to read through a given xml document to output
         * xml blocks as records as specified by the start tag and end tag
         *
         */

        public static class XmlRecordReader extends
                RecordReader<LongWritable, Text> {
            private byte[] startTag;
            private byte[] endTag;
            private long start;
            private long end;
            private FSDataInputStream fsin;
            private DataOutputBuffer buffer = new DataOutputBuffer();

            private LongWritable key = new LongWritable();
            private Text value = new Text();
                @Override
            public void initialize(InputSplit split, TaskAttemptContext context)
                    throws IOException, InterruptedException {
                Configuration conf = context.getConfiguration();
                startTag = conf.get(START_TAG_KEY).getBytes("utf-8");
                endTag = conf.get(END_TAG_KEY).getBytes("utf-8");
                FileSplit fileSplit = (FileSplit) split;

                // open the file and seek to the start of the split
                start = fileSplit.getStart();
                end = start + fileSplit.getLength();
                Path file = fileSplit.getPath();
                FileSystem fs = file.getFileSystem(conf);
                fsin = fs.open(fileSplit.getPath());
                fsin.seek(start);

            }
        @Override
            public boolean nextKeyValue() throws IOException,
                    InterruptedException {
                if (fsin.getPos() < end) {
                    if (readUntilMatch(startTag, false)) {
                        try {
                            buffer.write(startTag);
                            if (readUntilMatch(endTag, true)) {
                                key.set(fsin.getPos());
                                value.set(buffer.getData(), 0,
                                        buffer.getLength());
                                return true;
                            }
                        } finally {
                            buffer.reset();
                        }
                    }
                }
                return false;
            }
        @Override
           public LongWritable getCurrentKey() throws IOException,
                    InterruptedException {
                return key;
            }

        @Override
            public Text getCurrentValue() throws IOException,
                    InterruptedException {
                return value;
            }
        @Override
            public void close() throws IOException {
                fsin.close();
            }
        @Override
            public float getProgress() throws IOException {
                return (fsin.getPos() - start) / (float) (end - start);
            }

            private boolean readUntilMatch(byte[] match, boolean withinBlock)
                    throws IOException {
                int i = 0;
                while (true) {
                    int b = fsin.read();
                    // end of file:
                    if (b == -1)
                        return false;
                    // save to buffer:
                    if (withinBlock)
                        buffer.write(b);
                    // check if we're matching:
                    if (b == match[i]) {
                        i++;
                        if (i >= match.length)
                            return true;
                    } else
                        i = 0;
                    // see if we've passed the stop point:
                    if (!withinBlock && i == 0 && fsin.getPos() >= end)
                        return false;
                }
            }
        }
    }

        public static class Map extends Mapper<LongWritable, Text,
    Text, Text> {
  @Override
  protected void map(LongWritable key, Text value,
                     Mapper.Context context)
      throws
      IOException, InterruptedException {
    String document = value.toString();
    System.out.println("'" + document + "'");
        try {
      XMLStreamReader reader =
          XMLInputFactory.newInstance().createXMLStreamReader(new
              ByteArrayInputStream(document.getBytes()));
      String propertyName = "";
      String propertyValue = "";
      String currentElement = "";
      while (reader.hasNext()) {
        int code = reader.next();
        switch (code) {
          case XMLStreamConstants.START_ELEMENT: //START_ELEMENT:
            currentElement = reader.getLocalName();
            break;
          case XMLStreamConstants.CHARACTERS:  //CHARACTERS:
            if (currentElement.equalsIgnoreCase("MsgId")) {
              propertyName += reader.getText();
              //System.out.println(propertyName);
            } else if (currentElement.equalsIgnoreCase("NbOfTxs")) {
              propertyValue += reader.getText();
              //System.out.println(propertyValue);
            }
            break;
        }
      }
      reader.close();
      context.write(new Text(propertyName.trim()), new Text(propertyValue.trim()));

    }
        catch(Exception e){
                throw new IOException(e);

                }

  }
}
public static class Reduce
    extends Reducer<Text, Text, Text, Text> {
private Text outputKey = new Text();
  public void reduce(Text key, Iterable<Text> values,
                     Context context)
      throws IOException, InterruptedException {

  for (Text value : values) {
     outputKey.set(constructPropertyXml(key, value));
      context.write(outputKey, null);
    }
  }
 public static String constructPropertyXml(Text name, Text value) {
    StringBuilder sb = new StringBuilder();
    sb.append("MsgID ").append(name)
        .append("  NbOfTxs ").append(value);
        return sb.toString();
  }

}

        public static void main(String[] args) throws Exception
        {
                Configuration conf = new Configuration();

                conf.set("xmlinput.start", "<Event>");
                conf.set("xmlinput.end", "</Event>");
                conf.set("mapred.textoutputformat.separatorText", ",");
                Job job = new Job(conf);
                job.setJarByClass(XmlParser11.class);
                job.setOutputKeyClass(Text.class);
                job.setOutputValueClass(Text.class);

                job.setMapperClass(XmlParser11.Map.class);
                job.setReducerClass(XmlParser11.Reduce.class);

                job.setInputFormatClass(XmlInputFormat1.class);
                job.setOutputFormatClass(TextOutputFormat.class);

                FileInputFormat.addInputPath(job, new Path(args[0]));
                FileOutputFormat.setOutputPath(job, new Path(args[1]));

                job.waitForCompletion(true);
        }
}

A: Try using MultiOutputs. You can write to different files using this option, and hence can make different copies of output to be loaded into Hive.
A very good example is here using hadoop 1.0.2
Below is the example taken from javadocs:
Usage in Reducer:

 <K, V> String generateFileName(K k, V v) {
   return k.toString() + "_" + v.toString();
 }

 public class MOReduce extends
   Reducer<WritableComparable, Writable,WritableComparable, Writable> {
 private MultipleOutputs mos;
 public void setup(Context context) {
 ...
 mos = new MultipleOutputs(context);
 }

 public void reduce(WritableComparable key, Iterator<Writable> values,
 Context context)
 throws IOException {
 ...
 mos.write("text", , key, new Text("Hello"));
 mos.write("seq", LongWritable(1), new Text("Bye"), "seq_a");
 mos.write("seq", LongWritable(2), key, new Text("Chau"), "seq_b");
 mos.write(key, new Text("value"), generateFileName(key, new Text("value")));
 ...
 }

 public void cleanup(Context) throws IOException {
 mos.close();
 ...
 }

 }


text:
Q: How to make a Chrome Extension to redirect when specific pages are accessed in Manifest V3 I'm trying to make a Chrome extension that redirects to a pre defined page when a specified page is loaded.
I'm using webRequest for this, But now that I have to migrate to Manifest V3, webRequest can not be used anymore.
Can anyone help me with rewrite the script to make it work with Manifest V3?
Here's the script that I use to redirect pages:
var host = "http://example.com";
chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
         return {redirectUrl: host + details.url.match(/^https?:\/\/[^\/]+([\S\s]*)/)[1]};
    },
    {
        urls: [
            "*://foo.com/demo*",
            "*://www.foo.com/test/*"
        ],
        types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
    },
    ["blocking"]
);

A: I would not recommend using declarativeNetRequest for this task, it is very limited in its capabilities and has an awkward interface.
It sounds like you want to redirect the user prior to the page being loaded. If that's the case, you need to hook into the request/response lifecycle using chrome.debugger API. I describe how to do that here- his application seems easily adaptable to your own. This is the only way to get the same caliber request manipulation capabilities in MV3 as in MV2.
Alternative approach:
-Use the chrome.webNavigation API. This will just entail setting up event listeners/handlers for one or more of the following:
onBeforeNavigate -> onCommitted -> [onDOMContentLoaded] -> onCompleted

Here you can find many examples of other projects using this API.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I output a multiply expression in a Django template? I'm using Django and Python 3.7.  On my view, how can I output an expression?  I would like to do
<td>{{ fp_stat.avg_score * dow_index }}</td>

but I get this error
Could not parse the remainder: ' * dow_index' from 'fp_stat.avg_score * dow_index'

I would prefer not to create an additional attribute in my model, but if that's the only way then I guess I'll have to do that.

A: You can do this kind of thing using template filters.
For example;
@register.filter
def multiply(value, arg):
    try:
        return value * arg
    except Exception:
        return ''

So you could do {{ fp_stat.avg_score|multiply:dow_index }}
And there is a package for this which does a much better job of implementing this type of filter;
https://pypi.org/project/django-mathfilters/


text:
Q: TypeError: Cannot read property 'addContact' of undefined onSubmit I am working on a React project and I am currently stocked here with this error below even when it seems all my codes are in order.
I really can't figure out why I am having this error. I have checked both on google and here too. The answers to the questions similar to this didn't
really solve my challenge, hence me coming here to ask, perhaps someone can figure out where exactly I missed something. Thanks guys
Error:
TypeError: Cannot read property 'addContact' of undefined
onSubmit
  52 |
  53 |  const onSubmit = (e) => {
  54 |    e.preventDefault();
> 55 |    contactContext.addContact(contact);
  56 |    setContact({
  57 |      name: "",
  58 |      sex: "Female",

My Codes are given below:
ContactForm.jsx:
import React, { useState, useContext } from "react";
import ContactContext from "./../../contact/contactContext";

const ContactForm = () => {
  const contactContext = useContext({ ContactContext });
  const [contact, setContact] = useState({
    name: "",
    sex: "Female",
    dateOfBirth: "",
    resTown: "",
    hometown: "",
    resAddress: "",
    stateOfOrigin: "",
    lgaOfOrigin: "",
    nationality: "",
    regDate: "",
    hospName: "",
    headDoctor: "",
    hospTown: "",
    onDuty: "",
    hospResAddress: "",
    hospState: "",
    hospLga: "",
    birthType: "",
    babyWeight: "",
  });

  const {
    name,
    sex,
    dateOfBirth,
    resTown,
    hometown,
    resAddress,
    stateOfOrigin,
    lgaOfOrigin,
    nationality,
    regDate,
    hospName,
    headDoctor,
    hospTown,
    onDuty,
    hospResAddress,
    hospState,
    hospLga,
    birthType,
    babyWeight,
  } = contact;

  const onChange = (e) =>
    setContact({ ...contact, [e.target.name]: e.target.value });

  const onSubmit = (e) => {
    e.preventDefault();
    contactContext.addContact(contact);
    setContact({
      name: "",
      sex: "Female",
      dateOfBirth: "",
      resTown: "",
      hometown: "",
      resAddress: "",
      stateOfOrigin: "",
      lgaOfOrigin: "",
      nationality: "",
      regDate: "",
      hospName: "",
      headDoctor: "",
      hospTown: "",
      onDuty: "",
      hospResAddress: "",
      hospState: "",
      hospLga: "",
      birthType: "",
      babyWeight: "",
    });
  };

ContactReducer.jsx
import {
  GET_CONTACTS,
  ADD_CONTACT,
  DELETE_CONTACT,
  SET_CURRENT,
  CLEAR_CURRENT,
  UPDATE_CONTACT,
  FILTER_CONTACTS,
  CLEAR_CONTACTS,
  CLEAR_FILTER,
  CONTACT_ERROR,
} from "../types";

export default (state, action) => {
  switch (action.type) {
    case ADD_CONTACT:
      return {
        ...state,
        contacts: [...state.contacts, action.payload],
      };
    default:
      return state;
  }
};

ContactState.jsx
import React, { useReducer } from "react";
import { v4 as uuid } from "uuid";
import ContactContext from "./contactContext";
import contactReducer from "./contactReducer";

import {
  GET_CONTACTS,
  ADD_CONTACT,
  DELETE_CONTACT,
  SET_CURRENT,
  CLEAR_CURRENT,
  UPDATE_CONTACT,
  FILTER_CONTACTS,
  CLEAR_CONTACTS,
  CLEAR_FILTER,
  CONTACT_ERROR,
} from "../types";

const ContactState = (props) => {
  const initialState = {
    contacts: [
      {
        id: 1,
        name: "John Doe",
        hospName: "someText",
        dateOfBirth: "sameDate",
        sex: "someText",
        resTown: "someText",
        hometown: "someText",
        resAddress: "someText",
        stateOfOrigin: "someText",
        lgaOfOrigin: "someText",
        nationality: "someText",
        regDate: "someDate",
        headDoctor: "someText",
        hospTown: "someText",
        onDuty: "someText",
        hospResAddress: "someText",
        hospState: "someText",
        hospLga: "someText",
        birthType: "someText",
        babyWeight: "someFigure",
      },
      {
        id: 2,
        name: "Sara Mathew",
        hospName: "someText",
        dateOfBirth: "sameDate",
        sex: "someText",
        resTown: "someText",
        hometown: "someText",
        resAddress: "someText",
        stateOfOrigin: "someText",
        lgaOfOrigin: "someText",
        nationality: "someText",
        regDate: "someDate",
        headDoctor: "someText",
        hospTown: "someText",
        onDuty: "someText",
        hospResAddress: "someText",
        hospState: "someText",
        hospLga: "someText",
        birthType: "someText",
        babyWeight: "someFigure",
      },

    ],
  };

  const [state, dispatch] = useReducer(contactReducer, initialState);

  // Add Contact
  const addContact = (contact) => {
    contact.id = uuid.v4();
    dispatch({ type: ADD_CONTACT, payload: contact });
  };

  // Delete Contact

  // Set Current Contact

  // Clear Current Contact

  // Update Contact

  return (
    <ContactContext.Provider
      value={{
        contacts: state.contacts,
        addContact,
      }}
    >
      {props.children}
    </ContactContext.Provider>
  );
};

export default ContactState;

A: If you read useContext definition:
Don't forget that the argument to useContext must be the context object itself:

Correct: useContext(MyContext)
Incorrect: useContext(MyContext.Consumer)
Incorrect: useContext(MyContext.Provider)

So in your case it should be this:
const contactContext = useContext(ContactContext );

Remove {} these in useContext


text:
Q: JavaScript testing promise I'm trying to test a function which recives a promise like this
{
state: 'fulfilled'
value:[Array]
}

function register (foo) {
    return new Promise((resolve,reject)=>{
        query = "INSERT IGNORE INTO....";
        connection.query(query, [foo.value.from, foo.value.id], (err, res, fields) => {
        if(err){
            return undefined //this will change
        }
        return foo
        })
    })
}

The thing is I am returning, non rejecting neither resolving. So when Im testing..
    it('insertion error', function () {
        var res = 'error'
        connection = {
            query: (query, input, cb) =>{
                return cb(res, null, null)
            }
        }
        let database = proxyquire('path/to',{
            './connection': connection
        })

        var input =
        {
            value: {

        id: 'bar',
        data: [],
        from: 'foo'
        }}

        return database.register(input)
        .then( (result) => {
            expect(result).to.be.undefined
        })
        .catch( (err) => {
            console.log(err)
            err = new Error (`Test fail: ${err}`)
            throw err;
        })
    })

The function works well, Im pretty sure of that.
The other thing I'm sure of is that the THEN/CATCH condition never shows up. I know if I replace the return for resolve it will show up, but I need to be returned.
What should I modify, or how should I test it.

A: This is a basic example how can you make a promisse, in this example you can send true or false in the register() function.

function register ( foo ) {
   return new Promise( (resolve, reject) =>{
         if(foo){
            resolve('Done');
         }else{
            reject('Error')
         }
   } )
}

register(false).then( result=>{
   document.write('promisse success... ', result);
} ).catch( error => {
   document.write('promisse error... ', error);
} )


text:
Q: how to execute stored procedure or query via batch file and send the results in email via batch file I can execute the query via batch file and send it to the folder but I need to send the results to an email and I am not sure how to send the sql query/sp results in an email via batch file.
Any suggestions and help is appreciated.
Thanks

A: It sounds like you're executing your SQL query and I'm guess dumping it to a text file (let's say output.txt). I'm assuming Windows and I'm assuming SQL Server since you didn't specify. The answer is below, but I would like to offer two options instead:
OPTION 1: Setup SQL Server to send your email which would have several benefits including:

*

*SQL Agency can control scheduling & logging

*You get a SQL-Only solution

*Email is centrally managed instead of being in a bunch of different batch files.

It's not hard to setup email in SQL and is clearly explained here:
How to send email from SQL Server?
OPTION 2: Use PowerShell to make your SQL call.
The answer to your question (below) uses PowerShell to send the email message. Since you'll use PS for that you might as well use PS to make your database call. You can find hundreds of examples of how to call SQL from PS.
Finally the answer you asked for...
If you want to continue to use a command line solution (maybe you have to kick off a bunch of non-SQL commands) you'll need to use PowerShell (assuming you don't want start making things complicated, like writing your own .exe).
STEP 1: Read the contents of the query (output.txt) by using:
$sqlOutput = Get-Content Output.txt -Raw
STEP 2: Use $sqlOutput as the body of the email. Here's a nice walkthrough:
http://www.howtogeek.com/120011/stupid-geek-tricks-how-to-send-email-from-the-command-line-in-windows-without-extra-software/
STEP 3: If you want to attach the file as an attachment, you can use the example here:
https://msdn.microsoft.com/en-us/library/system.net.mail.attachment(v=vs.110).aspx


text:
Q: How to pass data to parent layout from database Laravel I want to pass the user data from my database into parent layout (app.layouts). Purpose of that is, there is a column that stores token in my database. I want to pass that to parent layout in order to use that in metatag.
How I will use it:
<meta name="access-token" content="{{$user->token}}"></meta>
The problem is, I can't find out how to pass the user data into layouts.
Usually, when I would pass the data into views I would do:
$users = User::all();

return view('welcome')->with(['user' => $user]);

But the code returns to view, I need to pass to layout, not view. Technically, layout is a view too but I don't think that would work.
Are there any easier solutions of that problem? Thanks for any help.

A: You can use View::composer:
// Using class based composers...
View::composer(
    'profile', 'App\Http\View\Composers\ProfileComposer'
);

// Using Closure based composers...
View::composer('dashboard', function ($view) {
    //
});

see https://laravel.com/docs/7.x/views#view-composers


text:
Q: Lists nested inside dictionary So I'm trying to develop a way to way to store 4 different categories (lets call them A, B, C, D) inside a dictionary so that I can access the keys/values inside each dictionary and check them against a file name. So far, I've been able to store 3 of these categories inside the dictionary but not the 4th. The categories were from an excel file and then copied over to a regular .txt file (I've included the .txt file). Is there a way to add a 4th component to my dictionary?
Link .txt file: https://drive.google.com/file/d/0B2s43FKt5BZgQldULXVOR0RBeTg/view?usp=sharing
Here's my script:
from collections import defaultdict
source_file = <file path>-<file name>.txt
data_set = defaultdict(list)    #sets up a defaultdict because there may be multiple overlapping keys
s = [b for b in [i.strip('\n').split('\t') for i in open(source_file)] if b]  # removes new line & tab spaces in .txt file
for a, b, c, d in s: # a is donor, b is barcode, c is batch, d is donor
  if a == 'Component1':  # We don't want to save the column headings
    pass
  else:
    data_set[a].append({b: c})  # creates the default dictionary

the output is like this as of the moment:
{'1':[{'ab':'tg'},{'dd':'dd'}],'2':{'dc':'yh'},3:{'we':'hh'}}

A: You can store your columns as tuples:
import csv
from collections import defaultdict
source_file = "<file path>-<file name>.txt"
data_set = defaultdict(list)
with open(source_file) as f:
    lines = csv.reader(f, delimiter='\t')
    _ = next(lines) # skip header
    for donor, barcode, batch, donor2 in lines:
        data_set[a].append((barcode, batch, donor2))  # save columns as tuple


text:
Q: Matlab RGB Image to Gray Scale Manually I have a RGB image and want to apply following formulas to it so I get another image. How can I do that? I know how to read/write image and I know how to loop and apply formulas but I don't know functions to extract number of rows and columns of image in a variable and image pixles values of 3 planes in 3-dimensional plane.
I = imread('myimage.jpg');

RGBImagePixles = [?, ?, ?] %of I

ROWS = ? %of I
COLUMNS = ? %of I

for r = 0 : ROWS
   for c = 0 : COLUMNS
      N[r, c] = RGBImagePixles[r,c,1] + RGBImagePixles[r,c,2] + RGBImagePixles[r,c,3]
   end
end

figure, imshow(N);

A: The output of imread is a 3 dimensional array, actually 3 matrices stacked along the 3rd dimension - so if your image is m pixels high and n pixels wide, you'd get a m x n x 3 array.
so:
RGBImagePixles = I;
ROWS = size (I,1);
COLUMNS = size(I,2);

and you can replace the loop with:
N = sum(I, 3);

However, I am not sure that simple summation is what you need in order to produce a grayscale image.

A: [ROWS COLUMNS DIMS] = size(I);

A: I assume that RGB to grayscale is just an example, and your real goal is to learn how to manipulate the pixels of an image. Otherwise, you should just use:
ImageRGB = imread('yourfile.jpg')
ImageGray = rgb2gray(ImageRGB)

To do it by hand:
ImageRGB = imread('yourfile.jpg')
ImageGray = sum(ImageRGB,3) / (3*255)

You have to divide by 3*255 because matlab expects a grayscale image's values to be between 0 and 1, while the RGB values will between 0 and 255 in each channel.


text:
Q: How to add an image before breadcrumb on specific page I made a new page using Magento2 admin panel and coded it with HTML. Now I want to add an image before breadcrumb on this page. Any help will be highly appreciated.

A: To add image before breadcrumb , first create a block and put your image in that block.
For example I am using about us page and adding image in that , taking a block , block name : test-image where my image is placed.

Now in your CMS page where is your HTMl content is placed, use below code to update XMl of page
<move element="test-image" destination="page.top" before="breadcrumbs"/>

keep cache disabled

A: Please add below code in your static CMS page's Design Section -> Layout update XML
    <move element="your.static.block.name" destination="page.top" before="breadcrumbs"/>

Note: Don't forget to change the element attribute value with the
  value of your block name.


text:
Q: iOS Facebook Api, make a like to a comment post I want to like a comment of a post on Facebook, I use the same as like the post. For like a post, it works, but for like a comment fail.
Doc:
https://developers.facebook.com/docs/graph-api/reference/object/likes
My Code:
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"/%@/likes", postId_]
                             parameters:nil
                             HTTPMethod:@"POST"
                      completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
                        {  //Error:
                        }];

The Error is:

Error Domain=com.facebook.sdk Code=5 "The operation couldn't be completed. (com.facebook.sdk error 5.)" UserInfo=0x158999b0 {com.facebook.sdk:HTTPStatusCode=400, com.facebook.sdk:ParsedJSONResponseKey={
      body =     {
          error =         {
              code = 100;
              message = "(#100) Error finding the requested story";
              type = OAuthException;
          };
      };
      code = 400;
  }, com.facebook.sdk:ErrorSessionKey=}

A: Here is how I do it, and it works like a charm
    // post is my module object, encapsulates the info form the post
    // pass the post ID
    NSString *graphPath = [NSString stringWithFormat:@"%@/likes", post.postID];

    FBRequest *request = [FBRequest requestForGraphPath:graphPath];
    // DELETE or POST the like
    NSString *method = post.liked?@"DELETE":@"POST";
    [request setHTTPMethod:method];

    [request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        BOOL success = YES;
        success = (error)?NO:YES;
        if(success) {

        }
    }];

Note: make sure you have publish permissions

A: In my project I use the following code:
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:URL, @"object", nil];

  if (FBSession.activeSession.isOpen) {
    if (FBSession.activeSession.accessTokenData.accessToken) {
      [FBRequestConnection startWithGraphPath:@"/me/og.likes"
                                   parameters:params
                                   HTTPMethod:@"POST"
                            completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                              NSLog(@"Just liked on Facebook!");
                            }];
    } else NSLog(@"Cannot open FBSession");
  }

There no code for opening or initializing FBSession - I hope, it's not a problem?

A: I think, we all can trust Facebook, yes? :)
Go to https://developers.facebook.com/docs/reference/opengraph/action-type/og.likes, select "IOS SDK" tab and look at the code.


text:
Q: How can I stop DiskUtilities from requesting permission every time I try to create an image from a CD I have a big stack of CDs from the 90s that I want to keep the data from, but don't want the physical CD anymore. So I'm using Disk Utility to create the disk images.
Every time I do (by right-clicking the volume in Disk Utility and clicking "Image from {volume name}"), I get this message:

The first time it happened, I figured it would be a one-time thing, but it happens every time. Googling the message results in no helpful information. How can I prevent it from asking for permission each time?
Running macOS 10.13.6, Disk Utility 17.0.3, using an Apple USB SuperDrive with a MacBook Pro 15" from 2016.

A: Mac OS X Snow Leopard is a DVD not a CD and I'd imagine some of the other discs you're trying to copy are DVD's too. Anyway, I can replicate your situation however, I also can do it from Disk Utility without being prompted for my password.
To do that, first unmount the disc and then select the parent node, e.g. on my Apple SuperDrive it's HL-DT-ST DVDRW GX40N, and option-click (right-click) and select: Image from HL-DT-ST DVDRW GX40N Media
In the subsequent dialog box change Save As: to something more user friendly, and change Format: to: DVD/CD master
Click the Save button and the disc will then start coping without being prompted for your password.
When finished click the Done button.
You can mount then disc image by double-clicking on it in Finder.

The above instruction are for Data DVD/CD discs  not Audio CD discs. Also note that I do not have a Hybrid Data DVD/CD/Audio CD disc to test whether or not the method shown above will work with that kind of disc.

A: I wouldn't use Disk Utility to make a copy of a CD.  The reason you're seeing the password dialog is because Disk Utility accesses the "raw" disk device.  You don't need to do this to make a copy.
There are a number of "better" (and free) alternatives.

*

*XLD - X Lossless Decoder.  It's an old GUI app that hasn't been updated in about a year (at the time of this post), but it still works on  El Capitan, Sierra, and High Sierra.  It even has binaries for PowerPC based Macs.

*dd - a Terminal based utility that makes bit-for-bit copies of any type of CD.  Just use the command:
$ dd if=/dev/diskX of=/path/to/image.iso

Where X is the disk identifier of the CD/DVD drive and the path/to/image.iso is the location and file name of the disk you want to save

*ffmpeg - A free library that included with many Audio/Video applications (i.e. Handbrake).  You can use this in Terminal as well.  Just issue the command to get a lossless copy of the CD:
$ ffmpeg -f libcdio -ss 0 -i /dev/diskx /path/to/image.flac

Again, where X is the disk identifier and the /path/to/image.flac is the location and filename of the CD image you want to create.


text:
Q: Apple Pay button styling for woocommerce I would like to customise the Apple-Pay button that comes with Woocommerce/Stripe. By default the button has a 4px border-radius, which I would like to change to 0px. Additionally the button is within a wrapper and I would like to change its padding-top to 0px. I wonder if this can be amended through CSS? Below is the source HTML code (any hint as to how to progress would be greatly appreciated).

A: Try adding the following CSS:
#wc-stripe-payment-request-button {
  background-color: black;
  border: solid black 1px;
}

Does that provide the desired appearance?

A: It seems like stripe for Woocommerce loads the payment request buttons through an iframe from js.stripe.com ... unfortunately it is not possible to stylize content in an iframe which comes from a different domain. I read this page on iframe style for reference. #wc-stripe-payment-request-button selector which woocommerce provides is the id to a DIV which contains the iframe (payment request buttons). Find my Pseudo element solution below:
EDIT: Here is what im using.. It has all my styles in it, so adjust them to your liking but it works great. Let me know if you have any questions.
Note: My cart background is white and my payment buttons are set to 60px height dark style in Woocommerce settings. You might possibily need to add media queries to adjust for your theme break points but its fairly responsive out of box. If you do not want the outline with "express checkout" just delete this piece of code "#wc-stripe-payment-request-button::after{CSS styles}".. Thought I would add it incase someone has an interest to "copify" Cheers.
Screen shot of the final product

#wc-stripe-payment-request-button-separator {font-size:80%; margin:10px 0px 8px 0px!important;
color:#bababa;
    padding:0px!important;
}
#wc-stripe-payment-request-button{outline: 3px solid #E6E6E6;outline-offset:18px;padding:1px 5px 0px 5px;transform:scale(.8);
}
#wc-stripe-payment-request-button::before {content:'';
width:99%;
    height:66px;
    position:absolute;
    z-index:999;
    bottom:-3px;
left: calc(50% - 49.5%);
    pointer-events: none;
    border:7px solid #fff;
    outline:4px solid #fff;
background:rgb(255,255,255,.6);
}

#wc-stripe-payment-request-button::after {content:'EXPRESS CHECKOUT';position:absolute;
    background:#fff;
    font-size:87%;
    color:#aaaaaa;
    font-family: 'Oswald', sans-serif !important;letter-spacing:.12em;
    display:block;
    left: calc(50% - 82px);
    font-weight:400;
    padding:0px 4px 0px 8px;
margin:-96px 0px 0px 0px;
}

A: Simple and best styling for apple pay button that is totally adjustable in all layouts(iPhone/MacBook). Its currently running on my website.
Here is the CSS
#applePay {
    width: 100%;
    height: 50px;
    display: none;
    -webkit-appearance: -apple-pay-button;
    -apple-pay-button-style: black;
    -apple-pay-button-type: book;
}

Here is the HTML

Pay With ApplePay

   <button type="button" id="applePay" lang="en"></button>

<?= Yii::t("app", 'ApplePay is possible on this browser, but not currently activated') ?>

<?= Yii::t("app", 'ApplePay is not available on this browser') ?>

<?= Yii::t("app", 'Test transaction completed, thanks') ?>


text:
Q: How can i use expander as a child item of treeview in WPF I want to show a custom set of repeating datas
Class M

 prop1 // treeview heading

 List<String> // treeview items

 List<ClassSub> [ prop 1, porp2 ,List<String> sub items] //as an expander with List<String> as expander items

Class M

  prop1 // treeview heading

  prop2  // treeview items

  List<ClassSub>[prop1 ,prop2,List<String>...]//as an expander

Can i use a Treeview + Expander combination to arrange this complete set of data?
Or do i need to use a Codeplex librarys like http://complexdatatemplates.codeplex.com [But i dont see a clear documentation on   it]

A: here is how I offer to solve your issue
xaml
<TreeView ItemsSource="{Binding TreeItems}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding SubItems}">
            <Expander Header="{Binding Header}">
                <ItemsControl Margin="25,0,0,0" ItemsSource="{Binding TreeItems}" />
            </Expander>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

Item class
class Item
{
    public string Header { get; set; }
    public List<string> TreeItems { get; set; }
    public List<Item> SubItems { get; set; }
}

View Model
class ViewModel
{
    public ViewModel()
    {
        TreeItems = new ObservableCollection<Item>();
        string[] data = new string[]{
                "Subchapter 1","Subchapter 2",
            };
        Item item = new Item()
        {
            Header = "Sub Getting Started",
            TreeItems = new List<string>(data)
        };

        TreeItems.Add(new Item()
        {
            Header = "Getting Started 1",
            SubItems = new List<Item>(new Item[] { item }),
            TreeItems = new List<string>(data)
        });
        TreeItems.Add(new Item()
        {
            Header = "Getting Started 2",
            SubItems = new List<Item>(new Item[] { item }),
            TreeItems = new List<string>(data)
        });
        TreeItems.Add(new Item()
        {
            Header = "Getting Started 3",
            SubItems = new List<Item>(new Item[] { item }),
            TreeItems = new List<string>(data)
        });
    }

    public ObservableCollection<Item> TreeItems { get; private set; }
}

result

In example above I haven't styled the Expander to match the one in screenshot posted in question. let me know if that is also required.

EDIT
as discussed, to display SubChapter1.1. and 1.2 to be visible by default or expand any other tree view item by default
start by defining a style for TreeViewItem in the resources
<TreeView.Resources>
    <Style TargetType="TreeViewItem">
        <Setter Property="IsExpanded"
                Value="{Binding IsExpanded}" />
    </Style>
</TreeView.Resources>

add a property IsExpanded to BookChapter class
public class BookChapter
{
    public string name { get; set; }
    public string id { get; set; }
    public List<BookPage> pages { get; set; }
    //public List<Enrichment> enrichment { get; set; }
    public List<SubChapter> chapters { get; set; }

    public bool IsExpanded { get; set; }

}

then set IsExpanded to true if you want it to be initially expanded
BookChapter cha = new BookChapter { name = "Chapter Intro", pages = pags, IsExpanded=true };

result

you can control other tree items in a similar manner too.

EDIT 2
sample for the same using Listbox and data templates
<Grid>
    <Grid.Resources>
        <DataTemplate x:Key="chapterTemplate">
            <Expander Header="{Binding name}" IsExpanded="{Binding IsExpanded}">
                <StackPanel>
                    <ItemsControl Margin="25,0,0,0"
                                  ItemsSource="{Binding pages}">
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <Button Content="{Binding Path=label}">
                                </Button>
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>
                    <ListBox ItemsSource="{Binding chapters}"
                             BorderBrush="{x:Null}"
                             Margin="20,0,0,0" />
                </StackPanel>
            </Expander>
        </DataTemplate>
        <DataTemplate DataType="{x:Type l:BookChapter}">
            <ContentControl Content="{Binding}"
                            ContentTemplate="{StaticResource chapterTemplate}" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type l:SubChapter}">
            <ContentControl Content="{Binding}"
                            ContentTemplate="{StaticResource chapterTemplate}" />
        </DataTemplate>

        <DataTemplate DataType="{x:Type l:BookPage}">
            <Button Content="{Binding Path=label}" />
        </DataTemplate>
    </Grid.Resources>

    <ListBox ItemsSource="{Binding}"
             Name="TOCView" />
</Grid>

result

with this approach you may not need to template the tree view item for the arrow. just template the expander as you wish
as a suggestion you can reuse BookChapter class as subchapters instead of creating a new class for SubChapter unless necessary.


text:
Q: Apache Camel Rest 503 Error I've created a rest call using camel. This is configured to use camel servlet component and I'm using tomcat.
When hitting the rest api URL, I get a few successful responses (approx. 5-10 requests), but then after that it gets a 503 error. According to camel, this exchange has completed. The logs all show that it has been completed but then the client is hanging and waiting for a response.
I cannot find what is going wrong as I cant believe this is an issue with the application itself as there are successful responses, but we have not had this issue before using Spring Rest (which we are using for a different application)
Does anyone have any ideas? I can give more information on request


text:
Q: What does | mean when diff is run on two files? When I run:
diff -y <file1> <file2>

what is the | character telling me?
i.e.
Video_Codec_List : v210  |  Codecs Video : v210

A: As explained in the GNU diffutils documentation (using info diffutils "output formats" "side by side")
`|'
     The corresponding lines differ, and they are either both complete
     or both incomplete.

FYI the complete list of markers is given as
white space
     The corresponding lines are in common.  That is, either the lines
     are identical, or the difference is ignored because of one of the
     `--ignore' options (*note White Space::).

`|'
     The corresponding lines differ, and they are either both complete
     or both incomplete.

`<'
     The files differ and only the first file contains the line.

`>'
     The files differ and only the second file contains the line.

`('
     Only the first file contains the line, but the difference is
     ignored.

`)'
     Only the second file contains the line, but the difference is
     ignored.

`\'
     The corresponding lines differ, and only the first line is
     incomplete.

`/'
     The corresponding lines differ, and only the second line is
     incomplete.


text:
Q: Why does my Powershell script to convert .vss to .vssx result in errors on execution? Does this seem to be correct? I am getting errors on trying to convert .vss to .vssx.
     >> $directoryToUpdate='C:\office\Stencils\*'
     >> $visio= New-Object -comVisio.Application
     >> foreach($vssFile in (get-childitem "$directoryToUpdate\*.vss" -Recurse")){
     >>    write-host "Working on $vssfile"
     >>    $doc=$visio.Documents.Open($vssFile.FullName)
     >>    $vssxFileName=[io.path]::ChangeExtension($vssFile,'.vssx')
     >>    $doc.SaveAs($VSSXFileName)
     >>    $doc.close();
     >> }

The output error messages are:
At line:1 char:21
+ >> foreach($vssFile in (get-childitem "$directoryToUpdate\*.vss" -Rec ...
+                     ~~
Unexpected token 'in' in expression or statement.
At line:1 char:20
+ >> foreach($vssFile in (get-childitem "$directoryToUpdate\*.vss" -Rec ...
+                    ~
Missing closing ')' in expression.
At line:19 char:73
+ ... ch($vssFile in (get-childitem "$directoryToUpdate\*.vss" -Recurse")){
+                                                                        ~
Unexpected token ')' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

A: I would say you are overcomplicating this. Here is a slight refactor of your code.
$visio = New-Object -com Visio.Application

 Get-ChildItem -Path 'C:\office\Stencils\*.vss' -Recurse |
 ForEach-Object {
    "Working on $($PSItem.Name)"

    $doc          = $visio.Documents.Open($PSItem.FullName)
    $vssxFileName = [io.path]::ChangeExtension($PSItem,'.vssx')

    $doc.SaveAs($VSSXFileName)
    $doc.close()
 }


text:
Q: Eclipse libgdx import cannot be resolved I am following this tutorial http://steigert.blogspot.com/2012/02/3-libgdx-tutorial-scene2d.html and i get an error in eclipse for these imports:
import com.badlogic.gdx.scenes.scene2d.OnActionCompleted;
    import com.badlogic.gdx.scenes.scene2d.actions.Delay;
    import com.badlogic.gdx.scenes.scene2d.actions.FadeIn;
    import com.badlogic.gdx.scenes.scene2d.actions.FadeOut;
    import com.badlogic.gdx.scenes.scene2d.actions.Sequence;
    import com.badlogic.gdx.scenes.scene2d.ui.Align;
    import com.badlogic.gdx.scenes.scene2d.ui.Image;
    import com.badlogic.gdx.scenes.scene2d.ui.Image.Scaling;
all other libgdx imports work fine but these give me the import cannot be resolved error
does anyone of you know how to fix this?

A: Now that I can see my code, yes - the libgdx version used in the steigert demos is not the latest, and lots of scene2d has changed since then.
http://steigert.blogspot.com/2012/07/13-libgdx-tutorial-libgdx-refactoring.html
You can get his refactored/updated code at:
https://code.google.com/p/steigert-libgdx/source/browse/tags/


text:
Q: Encrypt and Decrypt with AES ECB mode 'BadPaddingException' in some cases In android/java app
   public static void setKey(String myKey) {

        MessageDigest sha = null;
        try {
            key = new byte[]{(byte) '5', (byte) 'F', (byte) '8', (byte) 'p', (byte) 'J', (byte) 't', (byte) 'v', (byte) 'U', (byte) 'm', (byte) 'q', (byte) 'k', (byte) '7', (byte) 'A', (byte) 'M', (byte) 'v', (byte) 'b', (byte) 'q', (byte) 'o', (byte) 'H', (byte) 'M', (byte) '9', (byte) 'a', (byte) 'p', (byte) '4', (byte) '9', (byte) 'm', (byte) 'c', (byte) 'u', (byte) 'u', (byte) '5', (byte) 'B', (byte) 'X'};
            System.out.println(new String(key, "UTF-8"));
            secretKey = new SecretKeySpec(key, "AES");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static String encrypt(String strToEncrypt) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            setEncryptedarr(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
            setEncryptedString(String.valueOf(Base64.encode(cipher.doFinal(strToEncrypt.getBytes("UTF-8")), Base64.DEFAULT)));
            //setEncryptedString(Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error while encrypting: " + e.toString());
        }
        return null;
    }

    public static String decryptbyte(byte[] strToDecrypt) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            setDecryptedarr(cipher.doFinal(strToDecrypt));
            System.out.println("encrypt : decropted size : " + getDecryptedarr().length);
            setDecryptedString(new String(cipher.doFinal(strToDecrypt)));
        } catch (Exception e) {
            System.out.println("Error wnhile decrypting: " + e.toString());
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String strToDecrypt) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            setDecryptedarr(cipher.doFinal(Base64.decode(strToDecrypt, Base64.DEFAULT)));
            setDecryptedString(new String(cipher.doFinal(Base64.decode(strToDecrypt, Base64.DEFAULT))));

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error while decrypting: " + e.toString());

        }
        return null;
    }

I am working on this code : http://aesencryption.net/
I use this snipped code is working well when use it in case of :
encryptbyte and decryptbyte whitch take byte[]
and I test it it's result of encryption in this site http://aesencryption.net/
but i need it to decript data came from server (response is came string)
and when I convert the String to byte[] the code always thraw exception :
javax.crypto.IllegalBlockSizeException: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length**
I think it's when covert the String to byte[] it change , if that what is the right way to convert .
Advice please .
This code thraw exception :
try {
    AES.setKey("");
    final String strToDecrypt = "tATTXSdXI4w0oiu/fzgpyA==";
    AES.decryptbyte(toBytes(strToDecrypt.toCharArray()));
} catch (Exception ex) {
    ex.printStackTrace();
}

this is the exception
01-21 15:24:55.861 15700-15700/ W/System.err: javax.crypto.IllegalBlockSizeException: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
01-21 15:24:55.861 15700-15700/ W/System.err:     at com.android.org.conscrypt.NativeCrypto.EVP_CipherFinal_ex(Native Method)
01-21 15:24:55.861 15700-15700/ W/System.err:     at com.android.org.conscrypt.OpenSSLCipher.doFinalInternal(OpenSSLCipher.java:430)
01-21 15:24:55.861 15700-15700/ W/System.err:     at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:466)
01-21 15:24:55.861 15700-15700/ W/System.err:     at javax.crypto.Cipher.doFinal(Cipher.java:1340)
 01-21 15:24:55.861 15700-15700/ W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
01-21 15:24:55.861 15700-15700/ W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2648)
01-21 15:24:55.861 15700-15700/ W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2769)
01-21 15:24:55.861 15700-15700/ W/System.err:     at android.app.ActivityThread.access$900(ActivityThread.java:177)
01-21 15:24:55.861 15700-15700/ W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430)
01-21 15:24:55.861 15700-15700/ W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
01-21 15:24:55.861 15700-15700/ W/System.err:     at android.os.Looper.loop(Looper.java:135)
01-21 15:24:55.861 15700-15700/ W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5910)
01-21 15:24:55.861 15700-15700/ W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
01-21 15:24:55.861 15700-15700/ W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
01-21 15:24:55.861 15700-15700/ W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
01-21 15:24:55.861 15700-15700/ W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

A: The final bit of code: strToDecrypt = "tATTXSdXI4w0oiu/fzgpyA==" seems to have a base64 encoding, notice the trailing == characters. This makes sense since encryption is data byte oriented, not string oriented.
Base64 "tATTXSdXI4w0oiu/fzgpyA=="
hexadecimal: B404D35D2757238C34A22BBF7F3829C8 (16 bytes).
You need to decode the Base64 to data bytes for the code:
AES.setKey("");
final String strToDecrypt = "tATTXSdXI4w0oiu/fzgpyA==";
AES.decryptbyte(toBytes(strToDecrypt.toCharArray()));

Also note that the above code has an empty string for a key, that is an error.

A: I solve it ....
the server encrypt AES with out padding and ZeroBytePadding mode  is the only working mode ...
working code :
public class AESCryptt {
    private static final String TAG = "AESCrypt";
    private static final String AES_MODE = "AES/ECB/ZeroBytePadding";
    private static final String CHARSET = "UTF-8";//
    public static boolean DEBUG_LOG_ENABLED = false;

    private static SecretKeySpec generateKey(final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        byte[] key = new byte[]{your key in byte here (byte) a, (byte) f , ..... };
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        return secretKeySpec;
    }

    /**
     * Encrypt and encode message using 256-bit AES with key generated from password.
     *
     *
     * @param password used to generated key
     * @param message the thing you want to encrypt assumed String UTF-8
     * @return Base64 encoded CipherText
     * @throws GeneralSecurityException if problems occur during encryption
     */
    public static String encrypt(final String password, String message)
            throws GeneralSecurityException {
        try {
            final SecretKeySpec key = generateKey(password);
            log("message", message);
            byte[] cipherText = encrypt(key, ivBytes, message.getBytes(CHARSET));
            //NO_WRAP is important as was getting \n at the end
            String encoded = String.valueOf(Base64.encodeToString(cipherText, Base64.NO_PADDING ));
            log("Base64.NO_WRAP", encoded);
            return encoded;
        } catch (UnsupportedEncodingException e) {
            if (DEBUG_LOG_ENABLED)
                Log.e(TAG, "UnsupportedEncodingException ", e);
            throw new GeneralSecurityException(e);
        }
    }

    /**
     * More flexible AES encrypt that doesn't encode
     * @param key AES key typically 128, 192 or 256 bit
     * @param iv Initiation Vector
     * @param message in bytes (assumed it's already been decoded)
     * @return Encrypted cipher text (not encoded)
     * @throws GeneralSecurityException if something goes wrong during encryption
     */
    public static byte[] encrypt(final SecretKeySpec key, final byte[] iv, final byte[] message)
            throws GeneralSecurityException {
        final Cipher cipher = Cipher.getInstance(AES_MODE);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, key);//, ivSpec
        byte[] cipherText = cipher.doFinal(message);
        log("cipherText", cipherText);
        return cipherText;
    }

    /**
     * Decrypt and decode ciphertext using 256-bit AES with key generated from password
     *
     * @param password used to generated key
     * @param base64EncodedCipherText the encrpyted message encoded with base64
     * @return message in Plain text (String UTF-8)
     * @throws GeneralSecurityException if there's an issue decrypting
     */
    public static String decrypt(final String password, String base64EncodedCipherText)
            throws GeneralSecurityException {

        try {
            final SecretKeySpec key = generateKey(password);
            log("base64EncodedCipherText", base64EncodedCipherText);
            byte[] decodedCipherText = Base64.decode(base64EncodedCipherText, Base64.DEFAULT);
            log("decodedCipherText", decodedCipherText);
            byte[] decryptedBytes = decrypt(key, ivBytes, decodedCipherText);
            log("decryptedBytes", decryptedBytes);
            String message = new String(decryptedBytes, CHARSET);
            log("message", message);
            return message;
        } catch (UnsupportedEncodingException e) {
            if (DEBUG_LOG_ENABLED)
                Log.e(TAG, "UnsupportedEncodingException ", e);
            throw new GeneralSecurityException(e);
        }
    }

    /**
     * More flexible AES decrypt that doesn't encode
     *
     * @param key AES key typically 128, 192 or 256 bit
     * @param iv Initiation Vector
     * @param decodedCipherText in bytes (assumed it's already been decoded)
     * @return Decrypted message cipher text (not encoded)
     * @throws GeneralSecurityException if something goes wrong during encryption
     */
    public static byte[] decrypt(final SecretKeySpec key, final byte[] iv, final byte[] decodedCipherText)
            throws GeneralSecurityException {
        final Cipher cipher = Cipher.getInstance(AES_MODE );
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, key);//, ivSpec
        byte[] decryptedBytes = cipher.doFinal(decodedCipherText);
        log("decryptedBytes", decryptedBytes);
        return decryptedBytes;
    }

    private static void log(String what, byte[] bytes) {
        if (DEBUG_LOG_ENABLED)
            Log.d(TAG, what + "[" + bytes.length + "] [" + bytesToHex(bytes) + "]");
    }

    private static void log(String what, String value) {
        if (DEBUG_LOG_ENABLED)
            Log.d(TAG, what + "[" + value.length() + "] [" + value + "]");
    }

    /**
     * Converts byte array to hexidecimal useful for logging and fault finding
     * @param bytes
     * @return
     */
    private static String bytesToHex(byte[] bytes) {
        final char[] hexArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
                '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] hexChars = new char[bytes.length * 2];
        int v;
        for (int j = 0; j < bytes.length; j++) {
            v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    private AESCryptt() {
    }
}

and you can call it like that :
    try {
        header = AESCryptt.encrypt("the key is fixed is this case",header);
    } catch (Exception ex) {
        ex.printStackTrace();
        System.out.println("eee , exception during encrypt log in data . . . .");
    }


text:
Q: Add confirmation pop-up to admin form "Save" button I have custom module which adds admin form. There is a button "Save" in the form container that saves the entire form and adds some data to the database.

I would like to avoid situation that user accidentally clicks the button.
How to add a javascript to the button that would display (on button click) a pop-up window with text like:
"Are you sure you want save? Yes/No"?
If user clicks "Yes", then the default action for the "Save" button will be triggered and form will be submitted. If user clicks "No" then nothing happens. This will prevent accidentally saving the form.
Is there anything like this available in magento admin forms? If not, how to add this feature to my form?
class Super_Awesome_Block_Adminhtml_Example_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
    public function __construct()
    {
        parent::__construct();

        $this->_blockGroup = 'awesome';
        $this->_controller = 'adminhtml_example';

        $this->_addButton(
            'my_button_save',
            array(
                'label' => Mage::helper('adminhtml')->__('Save'),
                'class' => 'save',
            ),
            100
        );
    }
}

A: Something like this may help you
 $base_fieldset->addField(
                'your_btn', 'button', array(
            'name' => 'your_btn',
            'label' => Mage::helper('testmodule')->__(
                    'Click on folowing link to test popup Dialog:'
            ),
            'value' => $this->helper('testmodule')->__('Test popup dialog >>'),
            'class' => 'form-button',
            'onclick' => 'javascript:openMyPopup()'
                )
        );
        $form->setUseContainer(true);
        $this->setForm($form);
        parent::_prepareForm();

Then in layout file
<?php echo $this->getFormInitScripts() ?>
<script type="text/javascript">
    function openMyPopup() {
        var url = '<?php echo $this->getUrl('adminhtml/dashboard/index') ?>?';
        if ($('browser_window') && typeof(Windows) != 'undefined') {
            Windows.focus('browser_window');
            return;
        }
        var dialogWindow = Dialog.info(null, {
            closable:true,
            resizable:false,
            draggable:true,
            className:'magento',
            windowClassName:'popup-window',
            title:'Test popup Dialog',
            top:50,
            width:300,
            height:150,
            zIndex:1000,
            recenterAuto:false,
            hideEffect:Element.hide,
            showEffect:Element.show,
            id:'browser_window',
            url:url,
            onClose:function (param, el) {
                alert('onClose');
            }
        });
    }
    function closePopup() {
        Windows.close('browser_window');
    }
</script>

A: Magento gives you default validation process. You can use it. In your Grid.php,
For example you need validation for email field, So
protected function _prepareColumns()
  {
      $this->addColumn('email', array(
          'header'    => Mage::helper('sendsms')->__('Email'),
          'align'     =>'left',
          'index'     => 'email',
          'required'  => true,
      ));

[...]

}

Here  'required'  => true, it enables validation for you..!
Thats it ..Cheers..!

A: I have to do this for promo (coupon) module in admin. So I am writing how to do this.
Module file:
<config>
<modules>
    <NS_Promo>
        <active>true</active>
        <codePool>local</codePool>
        <depends>
            <Mage_Adminhtml/>
        </depends>
    </NS_Promo>
</modules>

app/local/NS/Promo/etc/config.xml
<config>
    <modules>
        <Ns_Promo>
            <version>0.1.0</version>
        </Ns_Promo>
    </modules>
    <global>
        <blocks>
            <adminhtml>
                <rewrite>
                    <promo_quote_edit>NS_Promo_Block_Quote_Edit</promo_quote_edit>
                </rewrite>
            </adminhtml>
        </blocks>
    </global>
</config>

app/local/NS/Promo/Block/Quote/Edit
    class NS_Promo_Block_Quote_Edit extends Mage_Adminhtml_Block_Promo_Quote_Edit
{

    /**
     * Initialize form
     * Add "Save and Continue" button
     *
     * Murtaza: added a js function to confirm
     * if admin user wants to add promo withoud coupon
     */
    public function __construct()
    {
        parent::__construct();

        $this->_updateButton('save', 'onclick', 'return confirmFunction(\'save\');');
        $this->_updateButton('save_and_continue_edit', 'onclick', 'return confirmFunction(\'savencontinue\');');
    }
}

js confirmFunction is:
function confirmFunction(type) {
     if (!window.confirm('<?php echo Mage::helper('salesrule')->__('message?') ?>')) {
            return false;
        }

        if (type == 'save') {
            editForm.submit();
        } else {
            editForm.submit($('edit_form').action + 'back/edit/');
        }
}

hope this will help someone :)


text:
Q: How to find out which areas are affected by flooding due to heavy rain? I'm working on a little project to visualize affected streets of flooding due to heavy rain. I already got a DEM for my study area and filled the depressions with r.fill.dir.
Since I never worked on hydrological analysis with QGIS, I don't exactly know which workflow/tools I should use to determine the affected area of the flooding due to heavy rain. I know that in reality the affected area is a slope which channels the water downwards. I already could modelling this with r.watershed. But is there a way or a tool to calculate the area of the flooding in relation of the amount of rainfall?

A: I am unsure how accurate you want your results to be, my understanding is that you can do one of two approaches:

*

*Find known water level points for the rainfall event and create an interpolated surface, do a quick raster calc to find areas where terrain is higher than the water surface and youll get an approximate extent of flooding.

*The more standard industry practice is to use a hydraulic solver engine to get a more realistic flood extent. As you said the affected area is a slope, hence the water levels will vary across the watershed. There are several modelling tools out there, but HEC RAS 2D is a free to use solver which may be useful. TUFLOW and Flood Modeller also have free versions which may be suitable.


text:
Q: Pass an object type as parameter I would like to replace the following function, almost exact copies of this function exist in my project with only the object type that is different. What I would like to do is pass an object type as a parameter.
private void reloadBooks()
{
    var books = session.Query.All<Book>();
    boklist = new System.ComponentModel.BindingList<Book>(books.ToList<Book>());

    lstBooks.ItemsSource = boklist;
}

I was thinking about something like this:
private void getRecordsOfType(object objObject)
{
    System.ComponentModel.BindingList<objObject.GetType()> recordList = new System.ComponentModel.BindingList<objObject.GetType()>();

    var records = session.Query.All<objObject.GetType()>();
    recordList = new System.ComponentModel.BindingList<objObject.GetType()>(records.ToList<bjObject.GetType()>());

    return recordList;
}

But this doesn't seem to work, I get the following message:

"Operator '<' cannot be applied to operands of type 'method group' and 'System.Type'"

I read something similar about using generics but I don't see that being useful in this situation.

A: Generics is exactly what you want:
private BindingList<T> getRecordsOfType<T>()
{
    var records = session.Query.All<T>();
    return new System.ComponentModel.BindingList<T>(records.ToList<T>());
}

A: Try this:
private System.ComponentModel.BindingList<T> getRecordsOfType<T>()
{
    System.ComponentModel.BindingList<T> recordList = new System.ComponentModel.BindingList<T>();

    var records = session.Query.All<T>();
    recordList = new System.ComponentModel.BindingList<T>(records.ToList<T>());

    return recordList;
}

A: Use a generic type parameter:
private BindingList<T> getRecordsOfType<T>()
{
    var records = session.Query.All<T>();
    recordList = new System.ComponentModel.BindingList<T>(records.ToList<T>());
    return recordList;
}


text:
Q: windbg 10.0 do not show line numbers When I switched from windows 7 to windows 10 (new SDK of course) I faced this different behavior in WinDBG when showing callstack with command "kc":
Windows 7:
KERNELBASE!RaiseException
msvcr120!_CxxThrowException
msvcp120!std::_Xout_of_range

Windows 10:
00 KERNELBASE!RaiseException
01 msvcr120!_CxxThrowException
02 msvcp120!std::_Xout_of_range

How to get rid of line numbers?
00
01
02

which are links like ".frame 0n0;dv /t /v"

A: turn off dml
kd> .prefer_dml 0
DML versions of commands off by default
kd> kc

WARNING: Stack unwind information not available. Following frames may be wrong.
LiveKdD
nt!KiInitialPCR
nt!KeWaitForSingleObject
nt!NtWaitForSingleObject
nt!KiFastCallEntry
ntdll!KiFastSystemCallRet
kd> .prefer_dml 1
DML versions of commands on by default
kd> kc
 #
WARNING: Stack unwind information not available. Following frames may be wrong.
00 LiveKdD
01 nt!KiInitialPCR
02 nt!KeWaitForSingleObject
03 nt!NtWaitForSingleObject
04 nt!KiFastCallEntry
05 ntdll!KiFastSystemCallRet


text:
Q: Word Problem - Finding Equations for Cost I've gotten stuck on my homework with a word problem that asks to find two equations for cost. I'm not really sure where to start, exactly! Word problems are my downfall every single time without fail... The question is:
A cylindrical can is to be constructed to hold $400 \text{ cm}^3$ of liquid. The cost of the material for the circular top and bottom of the can is $3$ cents per square centimetre and the cost of the material used for the curved sides is $2$ cents per square centimetre. Find two equations for the cost, $C$, in terms of i) the radius of the top and bottom, $r$, and ii) the height of the can, $h$.
(Does the area of a circle come into play in finding the answer?)
If someone could walk me through this, that would be great! Thanks in advance!

A: Work out the total cost in terms of the dimensions $r$ and $h$. The area of a circle of radius $r$ is $\pi r^2$, and we have to count the top and bottom separately, so the total cost of the top and bottom is $2(0.03)\pi r^2$. The circumference of the can is $2\pi r$, and the height is $h$, so the area of the side is $2\pi rh$, and the cost of the side is $2(0.02)\pi rh$. The total cost is therefore $$C = 0.06\pi r^2 + 0.04\pi rh.\tag{1}$$ In order to express this in terms of just $r$ or just $h$, you must find some relationship between $r$ and $h$ that lets you solve for one of them in terms of the other. This is where the known volume comes in. The volume is the area of the base times the height: $V = \pi r^2h$. But we know what this is: it's $400$, so $\pi r^2h = 400$. Now you can solve this for $h$ in terms of $r$ and substitute into $(1)$ to get $C$ in terms of $r$, and you can also solve it for $r$ in terms of $h$ and substitute into $(1)$ to get $C$ in terms of $h$.

A: $C=2r^2\pi C_1+2r\pi hC_2$
$C=2r\pi (rC_1+hC_2)$  ,and we know that $V=r^2\pi h \Rightarrow$$ h=\frac{V}{r^2 \pi}$ ,or $r=\sqrt{\frac{V}{\pi h}}$
Now you have to substitute $h$ in equation for $C$ to get the first equation in terms of $r$ and after that make substitution of $r$ in equation for $C$ in order to get second equation in terms of $h$


text:
Q: Do there exist equidistributed countable subgroups in (compact) Lie groups? By an equidistributed countable subgroup I mean a countable subgroup (with a finite or possibly countable set of generators) that is dense in $G$ such that for any sufficiently nice function (Haar measurable or stronger, although probably no stronger than continuous almost everywhere and (locally) bounded) you have
$$\int f(g)d\mu=\lim_{n\rightarrow\infty}\frac{1}{\left|W_n\right|}\sum_{g\in W_n}f(g)$$
where $W_n$ (in the finitely generated case) is the set of elements generated by products of $n$ generators (and their inverses) (in the infinitely generated case $W_n$ would be something like the set of words of length $n$ consisting of the first $n$ generators and their inverses, something to ensure $W_n$ is finite at each step).
I'm primarily interested in the finitely generated case for compact Lie groups. This is obvious for compact Abelian groups and I think it might be trivial for the infinitely generated case (just let the generators be an equidistributed sequence in $G$ or something).


text:
Q: Multiple unwanted clicks with showing/hiding DIV elements Javascript I have written a function which hides or shows the content of a div when you click on the applicable button. However, when I do so, you have to click the button a couple of times before it shows the content. After that only one click is needed until you click on a unrelated button then the same thing happens. Here is the function: Does anybody have a solution please?
function openBtn(){
  var acc = document.getElementsByClassName("myDIV");
  var i;

  for (i = 0; i < acc.length; i++) {
      acc[i].onclick = function() {
          this.classList.toggle("active");
          var panel = this.nextElementSibling;
          if (panel.style.display === "block") {
              panel.style.display = "none";
          } else {
              panel.style.display = "block";
          }
      };
  }
}

UPDATE
Here is the full code for the website as requested:
<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="sample_reception_page.css">

Example

<button onclick="newSample()">ADD</button>

        <button onclick="delbtn()" class="delbtn" id="delbtn" style="float: right;">Delete</button>
        <button onclick="openBtn()" id="sample" class="accordion" style="float: left;">Button</button>

          <input type="text" name="test">

A: You're applying muliple onclicks to the button with class="accordion".
Remove inline onclick from this button:
<button id="sample" class="accordion" style="float: left;">Button</button>

and call openBtn after defining it.
function openBtn() {
  var acc = document.getElementsByClassName("accordion");
  var i;

  for (i = 0; i < acc.length; i++) {
      acc[i].onclick = function() {
          this.classList.toggle("active");
          var panel = this.nextElementSibling;
          if (panel.style.display === "block") {
              panel.style.display = "none";
          } else {
              panel.style.display = "block";
          }
      };
  }
}
openBtn()

Probably change the name of openBtn function also to reflect what it is actually doing which is adding onclick event listener to all the buttons with class accordion.


text:
Q: Rails Paperclip Link Existing S3 Assets I have a Video model with a video attachment (using Paperclip and AWS S3 for storage). When a new video is created/uploaded we're using Zencoder to encode the uploaded video into the various formats that we need. This all happens off site and the new encodings are uploaded by zencoder back into S3.
How would I link these new files as styles/variations of the attachment?
In addition, Zencoder also generates thumbnails for us, so how could I also link those to the model instance?


text:
Q: javax.persistence.EntityManager.createQuery: when with / when without resultClass
*

*javax.persistence.EntityManager.createQuery(String qlString)

*javax.persistence.EntityManager.createQuery(String qlString, Class<ResultType> resultClass)
In which cases the qlString is sufficent and in which cases I also need to add the resultClass?
And: what part does the type of the result play in this regard (List<ResultType> result = q.getResultList()) ?

A: javax.persistence.EntityManager.createQuery(String qlString) returns a Query, while javax.persistence.EntityManager.createQuery(String qlString, Class<ResultType> resultClass) returns a TypedQuery<ResultType>.
You can use both to retrieve results, however the Query class will return non-generic Object instances or a List, while the TypedQuery<ResultType> would return ResultType instances or a List<ResultType>.

A: The result class is used to auto cast your result to the given type.  If you don't specify it, the result is a list of object arrays.  List<Object[]>
In Java, it is not usualy possible to cast from one generic type to another, so always use the version with the type, as the following code will be clearer, typesafe, and will not require casting.
If you only select specific fields in you query, and not a single field or entity, you do not need to specify it because the default List<Object[]>is returned.


text:
Q: WordPress rewrite URL returning 404 Not Found I'm trying to redirect this url:
myurl.com/track/124
to this one:
myurl.com/wp-content/themes/themefolder/track.php?id=124
The parameter value 124 can be anything.  I have modified the .htaccess file on the root of the server so now it has this:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^track/?$ wp-content/themes/themefolder/track.php?id=$1 [QSA,R,L]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

However when I go to myurl.com/track/124 I 404 Not Found returned.  Can anyone spot the problem and help me fix this?

*

*Another question: Is there a way to make sure the URL does not show wp-content/themes/themefolder/track.php?id=124 and keeps is track/124
Thanks

A: I think you need to change
RewriteRule ^track/?$ wp-content/themes/themefolder/track.php?id=$1 [QSA,R,L]

to
RewriteRule ^track/(\d+) wp-content/themes/themefolder/track.php?id=$1 [QSA,R,L]

A: Try using Wordpress' built in function add_rewrite_rule
add_filter('init','my_rewrite_rules');
function my_rewrite_rules(){
     add_rewrite_rule('^track/([^/]*)/?','wp-content/themes/themefolder/track.php?id=$matches[1]','top');
}

You will then need to visit your permalinks page in settings (Dashboard->Settings->Permalinks->Save Changes) in order for the added rule to take effect.


text:
Q: Amazon SQS, How to send message into other person Queue I would like to create a small messaging(Sending/Receiving) system using Amazon SQS, My question is, eg: if I logged-in to SQS, and created a message, and I would like to submit/post this message to another person queue? is this possible ? If Yes, how we can do that.
What my whole scenario is

*

*Submit message into Other User SQS & trigger notification using SNS.

*Once User read that message, remove it from SQS and sync into User

*S3 Bucket. Read S3 Bucket and show messages in chat form.


text:
Q: posting html form data redirect I am posting modal data to a back end using HTML post and action attr. The form post fine and updates the backend as well the only thing is after pressing submit the url changes and takes me to my POST url. How can this be stopped? I want to stay on the same page after clicking submit and just have the backend update without being taken to my POST url.
<form method="POST"id="goForm"action="http://post_endpoint"enctype="application/x-www-form-urlencoded">
    Name: <input type="text" value="">
    <button type="submit value="submit">Send<button>

</form>

A: To submit an HTML form without reloading the page, you have to use Javascript.
Here is a similar question with answers: Submit form without page reloading


text:
Q: how can i find additional sample code from android sdk? for example I wanna use PopMenu,
then I wanna find some sample code:as we all know that the android sdk contains all the sample code for all the android components but
how do i know under which path I should do the search ?
because they are under different folders.
it's really disturbing me that every time taking that much time to find it.

A: Please start your android studio and follow below steps :

*

*Start Android Studio and Open SDK Manager.

*Now click on 'Launch Stand alone SDK Manager' and check if samples
are downloaded or not. If not then please download it.

*After downloading samples please click on 'File' menu and import
your samples.

Edited :
Kindly note that as of Android Studio 1.4 Preview 2, 'Import Sample' moved to ' File -> New -> Import sample'.

Thank you.!!


text:
Q: Pillow module doesn't import correctly I'm making a program that requires to check a certain pixel on the screen, to check what color it was, and it seems like Pillow was good for this, however when I tried to import it (Yes I did install it using pip), I get this error:
ImportError: No module named Pillow
I've tried all of these imports:
import PIL
import Pillow
import pillow
from Pillow import Image
from PIL import Image
from PIL import *
from Pillow import *

But all of them return an error of "No module named x"
When I try to install Pillow using PIP I get:
Requirement already satisfied: pillow in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (6.1.0)

I have also installed Image using PIP as well:
Requirement already satisfied: pillow in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from Image) (6.1.0)
Requirement already satisfied: django in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from Image) (3.0.4)
Requirement already satisfied: pytz in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from django->Image) (2019.3)
Requirement already satisfied: asgiref~=3.2 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from django->Image) (3.2.3)
Requirement already satisfied: sqlparse>=0.2.2 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from django->Image) (0.3.1)

If there are other modules I could use that would be good for this I would be open to hear about those as it specifically doesn't need to be Pillow, it just seemed like the best one to use. Anyone know why this doesn't seem to import correctly?

A: There are too many possibilities as to what is going wrong. You are on a Mac, so you could be using:

*

*Apple-supplied Python 2.7, which has no corresponding pip and is obsolete

*Apple-supplied Python 3.7, which does have a pip

*homebrew Python 3

*homebrew Python 2 and is obsolete

So, the first thing you need to do is say how you start your Python, so if you type python3 to start Python, then you need to provide the output of running:
type python3        # or "type python" if you start Python by typing "python"

If you type pip3 to start pip, you need to provide the output of running:
type pip3           # or "type pip" if you start pip by typing "pip"

Then you (and we) will know what Python/pip combination you are intending to use. Once that is clear, you should get in the habit of using a shebang to select the correct Python that you are targeting, so your script should be:
#!/usr/bin/env python3
import this, that
...

for example, if you want to target Python3.
Once that is clear, the correct import statement is:
from PIL import Image


text:
Q: C# Add elements to Dictionary with key as string and value as another Dictionary Background:
I have a dictionary diskInfo with key as string and value as dictionary of type string, double. For each entry into the foreach loop, I calculate the disk space and store the result into spaceInfo dictionary. This is then passed on to be stored as the value for corresponding key in diskInfo dictionary.
Problem
Each time I clear existing entries in spaceInfo and readd the key value pairs before storing into diskInfo dictionary. At the end of the loop, diskInfo dictionary has keys stored in correctly, but count of values is 0 for all keys. I am new to using Dictionaries, so could you please help in explaining why this happens.
Thankyou
Dictionary<string, double> spaceInfo = new Dictionary<string, double>();
Dictionary<string, Dictionary<string, double>> diskInfo = new Dictionary<string, Dictionary<string, double>>();
foreach (ManagementObject mo in queryCollection)
        {
            double size = Convert.ToDouble(mo["Size"]) / divisor;
            double free = Convert.ToDouble(mo["FreeSpace"]) / divisor;

            double percentFree = (free / size) * 100;

            spaceInfo.Add("size",size);
            spaceInfo.Add("freeSpace",free);
            spaceInfo.Add("percentFree",percentFree);

            diskInfo.Add(Convert.ToString(mo["Name"]),spaceInfo);

            spaceInfo.Clear();
        }

A: Try Something like this
diskInfo.Add(Convert.ToString(mo["Name"]), new Dictionary<string, double>(spaceInfo));

The problem because of shallow copying.
You must perform deep copying to avoid such problems.
The copy constructor in the Dictionary class might help you solving the problem since it creates new instance from the spaceInfo object.
But the better way to do this is by creating class for the SpaceInformation.
class SpaceInfo
{
    private double _size;
    private double _free;
    private double _percentFree;

    public double Size
    {
        get;
        set;
    }

    public double Free
    {
        get;
        set;
    }

    public double PercentFree
    {
        get;
        set ;
    }

    public SpaceInfo(double size, double free)
    {
        Size = size;
        Free = free;
        PercentFree = (free / size) * 100;
    }
}

 /*Inside the loop*/
 double size = Convert.ToDouble(mo["Size"]) / divisor;
 double free = Convert.ToDouble(mo["FreeSpace"]) / divisor;
 SpaceInfo spaceInfo = new SpaceInfo(size, free);
 Dictionary<string, SpaceInfo> diskInfo = new Dictionary<string, SpaceInfo>();
 diskInfo.Add(Convert.ToString(mo["Name"]), spaceInfo);

`

A: Hope that you missed the point that, Dictionary is a reference type variable so if you made any changes in an instance means it will reflect all the places, so have to create separate instance in each iteration,
You should try something like this:
foreach (ManagementObject mo in queryCollection)
{
   double size = Convert.ToDouble(mo["Size"]) / divisor;
   double free = Convert.ToDouble(mo["FreeSpace"]) / divisor;
   double percentFree = (free / size) * 100;

   // Adding items here

   diskInfo.Add(mo["Name"].ToString(), new Dictionary<string, double>()
                                       {
                                           {"size",size},
                                           {"freeSpace",free},
                                           {"percentFree",percentFree}
                                       }

}

Or even like this by few modifications to your code; which means you have to create a new instance of spaceInfo in each iteration instead of clearing them.
foreach (ManagementObject mo in queryCollection)
{
    double size = Convert.ToDouble(mo["Size"]) / divisor;
    double free = Convert.ToDouble(mo["FreeSpace"]) / divisor;
    double percentFree = (free / size) * 100;

    spaceInfo = new Dictionary<string, double>();
    spaceInfo.Add("size",size);
    spaceInfo.Add("freeSpace",free);
    spaceInfo.Add("percentFree",percentFree);

    diskInfo.Add(Convert.ToString(mo["Name"]),spaceInfo);
}


text:
Q: Unable to re-change the value of a Javascript attribute I have two images which I'm toggling and a zoom on those images is supposed to be displayed according to the selected image. On the first page load everything works fine (image appears, zoom appears). After I click the image, the image swaps and the zoom works fine as well. However, if I click again, I'm getting the image toggled correctly, but the zoom image does not refresh even for further clicks (keep displaying the zoom for the 2nd loaded image).
I'm trying to change the attributes of data-zoom-image but no luck. Any suggestions?
function pageLoad(sender, args) {
    zooming();
}
function chngimg(x) {

       if ($("#zoom_mw").attr("src") == x) {

           var rimage;
           rimage = $("#zoom_mw").attr('rearimage');

           $("#zoom_mw").attr("src", rimage);
           $("#zoom_mw").removeAttr("data-zoom-image");

           $("#zoom_mw").attr("data-zoom-image", rimage);
           $("#zoom_mw").elevateZoom({ scrollZoom: true });
       } else  {
           var fimage;
           fimage = $("#zoom_mw").attr('frontimage');
           $("#zoom_mw").attr("src", fimage);

           $("#zoom_mw").attr("data-zoom-image", fimage);

           $("#zoom_mw").elevateZoom({ scrollZoom: true });
       }
   }

<img style="border:1px solid #e8e8e6;" id="zoom_mw"
onclick="chngimg('<%= Session("ImagePathFront")%>')"
frontimage='<%= Session("ImagePathFront")%>'
rearimage='<%= Session("ImagePathRear")%>'
    src='<%= Session("ImagePathFront")%>'
    width="500" height="250"  />

A: I assume that you are using this library. Is this the case?
In my demo i copied your code and currently

*

*it toggles the images.

*Your function pageLoad() calls a function zooming() but the code you provided does not execute pageLoad and the function zooming() is missing.

*The call to elevateZoom is not working for me. Are you missing a reference?

If you are using elevateZoom than you have to provide the URL for the larger Image

Their exsample Gallery & Lightbox seems to me that it comes close what you are looking for:

And the matching javascript
//initiate the plugin and pass the id of the div containing gallery images
$("#zoom_03").elevateZoom({gallery:'gallery_01',
        cursor: 'pointer', galleryActiveClass: 'active'
        , imageCrossfade: true
        , loadingIcon: 'http://www.elevateweb.co.uk/spinner.gif'});

//pass the images to Fancybox
$("#zoom_03").bind("click", function(e) {
  var ez =   $('#zoom_03').data('elevateZoom');
    $.fancybox(ez.getGalleryList());
  return false;
});

Please ask additional questions or comment if i misunderstood you.


text:
Q: How to fix "Underfull \hbox (badness 10000)" warning? I have this small .tex file.
\documentclass{article}
\usepackage[T2A]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{titling}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{tikz}

\setlength{\droptitle}{-3.5cm}
\setlength{\parindent}{0cm}
\newcommand{\squad}{\hspace{0.5em}}

\author{vladgovor77771}
\title{Some article}

\begin{document}
\maketitle

\textbf{Task 1} \newline
Task description: \newline

\end{document}

When compiling, it warns about line
\textbf{Task 1} \newline

With the following message:
"Underfull \hbox (badness 10000)".
How do I fix this?

A: A quick and nice solution is to use package parskip, and instead of using \newline or \\ for line breaks, simply insert an empty line
\documentclass{article}
\usepackage[T2A]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{titling}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{tikz}
\usepackage{parskip} %% <-- added

\setlength{\droptitle}{-3.5cm}
\setlength{\parindent}{0cm}
\newcommand{\squad}{\hspace{0.5em}}

\author{vladgovor77771}
\title{Some article}

\begin{document}
\maketitle

\textbf{Task 1}

Task description:

\end{document}

The warning will be gone.

By the way, to know why it happened, refer to this question on TeX Stack Exchange.

A: Instead of forcing an underfull box with \newline, you could simply leave an empty line to start a new paragraph:
\documentclass{article}
\usepackage[T2A]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{titling}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{tikz}

\setlength{\droptitle}{-3.5cm}
\setlength{\parindent}{0cm}
\newcommand{\squad}{\hspace{0.5em}}

\author{vladgovor77771}
\title{Some article}

\begin{document}
\maketitle

\textbf{Task 1}

Task description:

blabla

\end{document}

A: I had a similar issue, I solved it by removing any \newline or \\ at the and of every sentence that had nothing textual below.
For instance, two examples that causes that problem:
An example. \\
This is well used. \\
This line will cause the error. \\

(I'm a new paragraph) \\
Because there's nothing directly underneath.\\
The last line does NOT require a "newline".

This is a thid paragraph. \\
:D

The same is true for figures or similar
This is a line.
Putting a "newline", as here, before a \begin will cause the error. \\
\begin{figure}[h]
....
\end{figure}


text:
Q: Regarding client side code generation from WSDL I am a new bie to the world of webservices , I have to develop the client side code that is the java code,I have been provided a wsdl which I can see by opening that wsdl in the browser , As i have access to wsdl please let me know how can I generate the client side code from that wsdl itself through Axis 2, any help will be appreciated, Thanks in advance

A: There are many ways to generate client and server stubs.
you can use WSDL2Code Plug-in approach
This plugin takes as input a WSDL and generates client and server stubs for calling or implementing a Web service matching the WSDL.
add the following section to your POM
      <plugin>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-wsdl2code-maven-plugin</artifactId>
            <version>1.6.0</version>
            <executions>
                <execution>
                    <id>ws1</id>
                    <goals>
                        <goal>wsdl2code</goal>
                    </goals>
                    <configuration>
                       <unpackClasses>true</unpackClasses>
                       <databindingName>adb</databindingName>
                       <packageName>ma.glasnost.sample.axis2-maven</packageName>
                       <wsdlFile>src/main/resources/ws.wsdl</wsdlFile>
                       <outputDirectory>target/generated-sources</outputDirectory>
                       <syncMode>sync</syncMode>
                    </configuration>
                </execution>
           ..... if you have many web services
            </executions>
        </plugin>

Also add axis2 jars as a dependency
 <dependency>
          <groupId>org.apache.axis2</groupId>
          <artifactId>axis2</artifactId>
          <version>1.4</version>
 </dependency>

A: Here a brief overview what you will have to do to generate the client-side java code:

*

*Open the URL pointing to wsdl document in the webbrowser.

*Save that webpage as a xml document.

*Rename the file to have a .wsdl extension (optional)

*Then you need to run the WSDLToJava java file through the java command this class will be contained in the axis.jar

*Provide the wsdl filename as an argument to this java file.

*Provide all the jar files needed as a classpath argument to this java command

So your command will look something like below:
java -classpath axis.jar;%CATALINA_HOME%/shared/lib/commons-httpclient.jar;%CATALINA_HOME%/shared/lib/log4j.jar;%CATALINA_HOME%/shared/lib/commons-logging.jar;wsdl4j.jar;commons-net.jar;commons-discovery.jar;jaxrpc.jar;soap.jar;saaj.jar org.apache.axis.wsdl.WSDL2Java your_wsdl_fileName.wsdl

A: If you are using Eclipse then use Java code generation as mentioned in this link.http://axis.apache.org/axis2/java/core/tools/eclipse/wsdl2java-plugin.html#WSDL2Java


text:
Q: Moving images into folders with image filename I have a folder called folder1 that has a bunch of pictures in it, and I would like to save each picture in an individual folder. The folder should have the same name as the file, for example if the picture is called "st123" I would like to create a folder called "st123" and move the picture into the folder. I have tried the following, but I get the error cannot move to a subdirectory of itself. Is there another way to solve this?
Otherwise, would it be possible to save the image "st123" in a folder called "123" (so the last 3 characters)?
#!/bin/bash
Parent="/home/me/myfiles/folder1"
for file in $Parent; do
dir="${file%%.*}"
mkdir -p "$dir"
mv "$file" "$dir"
done

A: You almost have it working! Change part of line 3 so the for loop iterates over what's inside the directory instead of the directory itself:
#!/bin/bash
Parent="/home/me/myfiles/folder1"
for file in $Parent/*; do
dir="${file%%.*}"
mkdir -p "$dir"
mv "$file" "$dir"
done

https://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html#Command-Substitution

A: This solution might be useful to you, though if you'd like to iterate over the images recursively I suggest you to use find. If that's indeed the case, let me know and I'll edit this answer with relevant code.
for image in /home/me/myfiles/folder1/*; do
    if [[ -f $image ]]; then
        newf="${image%%?([ab]).*}"
        mkdir -p "$newf"
        mv -- "$image" "$newf"
    fi
done

Test ( extglob is enabled ):
$ [/home/rany/] touch test/st123a.tif test/st123b.tif test/st456.jpg test/st456b.jpg test/st789.tif
$ [/home/rany/] for image in test/*; do newf="${image%%?([ab]).*}"; mkdir -p "$newf"; mv -- "$image" "$newf";done
$ [/home/rany/] tree test
test
├── st123
│   ├── st123a.tif
│   └── st123b.tif
├── st456
│   ├── st456b.jpg
│   └── st456.jpg
└── st789
    └── st789.tif

3 directories, 5 files

EDIT:
According to OP request I added the following changes:

*

*Trim file-name's suffix a or b, so that, for example, file names st123a.ext and st123b.ext will go to the same directory st123. Important: this feature requires extglob enabled ( i.e. shopt -s extglob ).


text:
Q: What is the next such palindrome Consider the sequence of  palindromic numbers where each term is defined as the smallest  palindromic number with exactly k distinct palindromic prime factors (to avoid ambiguity, here I mean a palindromic number whose prime factors are ALL also palindromic numbers.). The sequence begins: $2$,$6$,$66$,$6666$:

*

*$2$

*$6$=$2$.$3$

*$66$=$2$.$3$.$11$

*$6666$=$2$.$3$.$11$.$101$

What is the next term after $6666$,does the next term exist ?. I have checked palindromes up to $10^9$( But I know that if there are infinitely many primes of the form $10000....00001$,then this sequence is absolutely infinite.). So what is the next term ?

A: From a relatively quick test, the recurrent sequence
$$a_0=6,\quad
a_{n+1}=a_n\cdot (10^{2^{n-1}}+1), \quad n\ge3$$
are of numbers with $2^n$ repeated 6's.
I have no answer if there something that can generate  other lenghts, like 666 or 66666, etc...


text:
Q: How to setup PHP version per project / workspace in Visual Studio Code? I have multiple PHP projects and some are in PHP 7.4 and others are in PHP 8.0.
Is there a way to setup the PHP version per project / workspace ?
[Not that it helps much but machine is a Linux Mint 20 box and Visual Studio Code 1.55.1]

A: It seems that Visual Studio Code does not support this kind of configuration. So you can not setup the PHP executable per project or workspace.
The only IDE (tried Visual Code, Netbeans and PHPStorm) that I found to support this kind of feature was PHPStorm.


text:
Q: BroadcastReceiver with intent-filter for them? Her is what I'm trying to accomplish:

*

*When user tries to share some text from any app (Like sharing a tweet or a link), my app will appear in the sharing list.

*If he select my app, some simple code will be run (like showing a Toast) then that's it. No interface or UI is needed.

Here is how I did it:
AndroidManifest.xml
<receiver
android:name=".MyBroadcastReceiver" >
    <intent-filter
        android:label="select my app">
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
</receiver>

MyBroadcastReceiver.java
public void onReceive(Context arg0, Intent arg1) {
    // TODO Auto-generated method stub
    //Some simple code
    Toast.makeText(arg0, "My Receiver is cool", Toast.LENGTH_LONG).show();
}

This didn't work, my app doesn't show in the sharing list.
Why I work with BroadcatReceivers and not with Activities? Because I don't want any UI and I think that is why we have receivers (correct my plz)
Am I doing it right?

A:
This didn't work, my app doesn't show in the sharing list.

ACTION_SEND is used with activities. You are attempting to use a BroadcastReceiver. Since a BroadcastReceiver is not an activity, this will not work.

Am I doing it right?

No.

If he select my app, some simple code will be run (like showing a Toast) then that's it. No interface or UI is needed.

You still need an activity. However, if you give the activity Theme.NoDisplay, and you do not call setContentView(), there will be no UI for the activity. Usually, you just call finish() from onCreate() after doing whatever it is you wanted to do (in this case, display a Toast).
For example, this sample application shows an activity (FauxSender) set up to do precisely what you want: respond to ACTION_SEND with a Toast. It has another activity that issues an ACTION_SEND so you can see the results.