text:
Q: Training Process Fails At Downloading Input Data I'm trying to run a training job using a custom Docker image that looks as follows:
FROM 683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-scikit-learn:0.20.0-cpu-py3

RUN pip install -U spacy boto3

RUN python -m spacy download en_core_web_sm

And I'm creating the training job using this:
import boto3
import sagemaker
from sagemaker import get_execution_role

container_uri = "..."
role = get_execution_role()

model = sagemaker.estimator.Estimator(
        image_uri=container_uri,
        role=role,
        instance_count=1,
        instance_type="ml.m4.xlarge",
        volume_size=1,
        entry_point="train.py",
        source_dir="spacy-train-custom",
        dependencies=["spacy-train-custom/configs"],
    output_path=f"s3://test-bucket/output/"
)

model.fit()

I also tried adding a couple of inputs but the result is the same:
Using role ...
2022-10-06 00:21:15 Starting - Starting the training job...
2022-10-06 00:21:40 Starting - Preparing the instances for trainingProfilerReport-1665015675: InProgress
.........
2022-10-06 00:23:09 Downloading - Downloading input data
2022-10-06 00:23:09 Stopping - Stopping the training job
2022-10-06 00:23:09 Stopped - Training job stopped
ProfilerReport-1665015675: Stopping
..
Job ended with status 'Stopped' rather than 'Completed'. This could mean the job timed out or stopped early for some other reason: Consider checking whether it completed as you expect.

Edit:
This is what the training script looks like:
import os
from sagemaker_training import environment
from spacy.cli.train import train

print("start training")

env = environment.Environment()
config_path = env.hyperparameters.pop("config")

overrides = {
    "paths.train": os.path.join(env.channel_input_dirs["train"], "train.spacy"),
}
overrides.update(env.hyperparameters)

use_gpu: int = 0 if env.num_gpus > 0 else -1

train(
    config_path,
    output_path=env.model_dir,
    use_gpu=use_gpu,
    overrides=overrides,
)

A: There are a couple of things wrong with your current approach, therefore there is not a single problem/issue to fix. Instead, I'll attempt to provide some guidance on how to deploy a custom container.
Using a custom docker image via requirements.txt
The simplest way of achieving this is to extend an existing sagemaker container. Scikit-Learn images are good base images to extend; however I recommend to use a requirements.txt file with your desired packages, and save the file in the same directory as your training script. Sagemaker will then install your requirements without the need of changing the docker file for the container. Please look sagemaker docs for more information.
Extending a prebuilt container with env variables and Dockefile
Your current Dockerfile is not complete, unless you omitted the complete dockerfile for brevity.
As mentioned above, based on your apparent requirements, I do not recommend extending a container by modifying the dockerfile, as you'll see there are multiple requirements to accomplish this vs implementing a requirements.txt.
To extend a pre-built SageMaker image, you need to set the following environment variables within your Dockerfile

*

*SAGEMAKER_SUBMIT_DIRECTORY: The directory within the container in
which the Python script for training is located.

*SAGEMAKER_PROGRAM: The Python script that should be invoked and used
as the entry point for training.

Create and Upload the Dockerfile and Python Training Scripts
Your dockerfile should follow the structure below:
# Downloads ssagemaker's  base image
FROM 683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-scikit-learn:0.20.0-cpu-py3

ENV PATH="/opt/ml/code:${PATH}"

# install your package
RUN pip install <library>

# this environment variable is used by the SageMaker image container to determine our user code directory.
ENV SAGEMAKER_SUBMIT_DIRECTORY /opt/ml/code

# /opt/ml and all subdirectories are utilized by SageMaker, use the /code subdirectory to store your user code.
COPY train.py /opt/ml/code/train.py

# Defines train.py as script entrypoint
ENV SAGEMAKER_PROGRAM train.py

Build the container
In the same mdirectory as your dockerfile log in to Docker to access the base container:
! aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 763104351884.dkr.ecr.us-east-1.amazonaws.com

To build the Docker container, run the following Docker build command, including the space followed by a period at the end:
! docker build -t sklearn-extended-container-test .

At this point you should be able to test the docker container locally from your sagemaker notebook or notebook studio
Push the container to ECR
%%sh

# Specify an algorithm name
algorithm_name=<some name>

account=$(aws sts get-caller-identity --query Account --output text)

# Get the region defined in the current configuration (default to us-west-2 if none defined)
region=$(aws configure get region)

fullname="${account}.dkr.ecr.${region}.amazonaws.com/${algorithm_name}:latest"

# If the repository doesn't exist in ECR, create it.

aws ecr describe-repositories --repository-names "${algorithm_name}" > /dev/null 2>&1
if [ $? -ne 0 ]
then
aws ecr create-repository --repository-name "${algorithm_name}" > /dev/null
fi

# Log into Docker
aws ecr get-login-password --region ${region}|docker login --username AWS --password-stdin ${fullname}

# Build the docker image locally with the image name and then push it to ECR
# with the full name.

docker build -t ${algorithm_name} .
docker tag ${algorithm_name} ${fullname}

docker push ${fullname}

After pushing the image you can retrieve the image under:
ecr_image='{}.dkr.ecr.{}.amazonaws.com/{}:latest'.format(account, region, algorithm_name)

For a detailed description please refer to: Sagemaker Dev Guide
Scikit-learn images and input channels
If you are planning on training/fitting the model with any type of data (text/csv or application/x-protobuf), I strongly suggest you read SageMaker SKLearn Estimator Doc. Note that sagemaker's implementation of this particular type of estimator sagemaker.sklearn.estimator.SKLearn uses the same sagemaker.estimator framework you are using.
You should be declaring your input channel directories and passing the data when you call the fit() method. Sagemaker will copy the object into the local directory of the container and it will be accessible "locally". Definitely avoid  reading objects outside the container (s3), this is just bad practice and it will cause problems.
Training.py
If you plan on deploying your model (serve) your training script should have these three functions:

*

*input_fn: Takes request data and deserializes the data into an object
for prediction.

*predict_fn: Takes the deserialized request object and performs
inference against the loaded model.

*output_fn: Takes the result of prediction and serializes this
according to the response content type.
You can also omit these and serve the model with a specific inference script instead of the train. But based on your training script it seems your use case is very basic and you can do all in one entry_point.
Good luck!

A: As you're really running a Scikit-learn container (with light customization), try to use the more high-level SKLearn estimator like shown here, instead of the generic Estimator. This might help you with getting it to work, or provide more guiding error messages.


text:
Q: Migrant from VS 2003 .Net1.1 to VS 2008 .Net 2.0 I converted my app that was implemented in VS 2003 to .net 2.0 VS 2008
afterward my app became slow about 4 times than previous version!
is it normal or not ?
Best regards

A: No. I have never heard of such a performance degradation before from upgrading the target framework.
.NET 2.0 uses another version of the CLR than 1.1, so there might be small differences. Perhaps you are running into some edge case, but we really can't tell without any more information.

redpajama_set_name: RedPajamaStackExchange


text:
Q: evaluated location in assign scxml tag how to dynamically specify location in assign scxml tag? My scxml interpreter does not accept something like this. Parametr expr="_event.data.expr" is evaluated properly. But location parametr accept only exact name string.
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" binding="early" xmlns:qt="http://www.qt.io/2015/02/scxml-ext" datamodel="ecmascript" name="StateMachineMain" qt:editorversion="4.3.1">
...
<transition type="external" event="_assigndata">
    <assign location="_event.data.data_id" expr="_event.data.expr"/>
</transition>
...

For now I'm going to use script bound to event to set the value, but it's somehow clumsy


text:
Q: Changing default player color globally on Tumblr When posting a Soundcloud link on Tumblr, it automatically creates the embed code. But with this I don't have access to the parameters to add a different HEX color and customise my player within my blog.
I'm wondering if there is a way to do this outside of the iframe and if possible do it globally so all my players will match.

A: You could try to use normal embed code from SoundCloud that allows you to do the customization instead of relying on Tumblr's integration.


text:
Q: How to do payment using stripe I am using Stripe to make payment in my application. I got the token Successfully.
I want to know that how the charges will be done, as there is no changes reflected in my Stripe dashboard. I'm using my Stripe Account TestPublish Key.

A: Tokens only represent a card or payment method, not an actual transaction.
Once you've collected and tokenized a customer's payment information, you need to send the token to your backend server so you can use it in an API request, e.g. a charge creation request or customer creation request.
You can find more information in this tutorial: https://stripe.com/docs/charges

A: Common error - you need to test on a real device, not the simulator. Just one of the gotchas of the Stripe API.


text:
Q: Split pdf from A4 into A6 quarters and don't save empty quarters Do not judge strictly, I'm a self-taught beginner)))
Please help me figure out how to share I learned both with the help of PyPDF2 and with the help of PyMuPDF (fitz). But when splitting, it often happens that there is text in only one quarter, but it writes all 4 quarters to the new file, both with text and empty, one with text, the rest are empty, and I need something so that the empty ones are not saved, I wanted to somehow do a check, but it didn't work out, lack of knowledge. I tried to read the newly recorded file and delete empty pages, but there is text on each page, even on empty ones, I open the file in acrobat reader, but the pages are empty, I don't understand how.
Here is my code just in case how and what I do: https://paste.aiogram.dev/opiquhehus.py
This is my first time posting here and I don't know how to attach files. pdf files for example in the telegram channel: https://t.me/+Tq7WpP1ImcjQXSZF.
import copy
import logging
import random
from pathlib import Path

import PyPDF2
import fitz
from PyPDF2.filters import decodeStreamData, ASCII85Decode
from PyPDF2.generic import EncodedStreamObject, DecodedStreamObject

def from_a4_to_a6_not_sync(input_file, output_file):
    input_file = str(input_file.absolute())

    pdf_reader = PyPDF2.PdfFileReader(input_file)

    # print(f'{pdf_reader.getNumPages()=}')
    # print(f'{pdf_reader.documentInfo=}')

    first_page = pdf_reader.getPage(0)

    left_up_side = copy.deepcopy(first_page)
    right_up_side = copy.deepcopy(first_page)
    left_down_side = copy.deepcopy(first_page)
    right_down_side = copy.deepcopy(first_page)

    # print(f'{left_up_side.extractText()=}')
    # print(f'{right_up_side.extractText()=}')
    # print(f'\nДО ОБРЕЗКИ:\n{type(left_up_side)=}\n{left_up_side=}\n')
    # print(f'\nДО ОБРЕЗКИ:\n{type(right_up_side)=}\n{right_up_side=}\n')

    # second_page = pdf_reader.getPage(0)
    # print(f'{type(second_page)=}\n{second_page.extractText()=}')
    # third_page = pdf_reader.getPage(0)
    # fourth_page = pdf_reader.getPage(0)

    first_coord = first_page.mediaBox.upperRight[0]
    second_coord = first_page.mediaBox.upperRight[1]
    # print(f'{first_coord=}')
    # print(f'{second_coord=}')

    # cords_upperLeft = first_page.mediaBox.upperLeft
    # cords_lowerLeft = first_page.mediaBox.lowerLeft
    # cords_upperRight = first_page.mediaBox.upperRight
    # cords_lowerRight = first_page.mediaBox.lowerRight
    # print(f'{cords_upperLeft=}')
    # print(f'{cords_lowerLeft=}')
    # print(f'{cords_upperRight=}')
    # print(f'{cords_lowerRight=}')

    # first_page.mediaBox.lowerRight = (first_coord / 2, second_coord / 2)  # ВЕРХНЯЯ ЛЕВАЯ ЧЕТВЕРТИНКА
    # second_page.mediaBox.lowerLeft = (first_coord / 2, second_coord / 2)  #   ВЕРХНЯЯ ПРАВАЯ ЧЕТВЕРТИНКА
    # third_page.mediaBox.upperRight = (first_coord / 2, second_coord / 2)  #   НИЖНЯЯ ЛЕВАЯ ЧЕТВЕРТИНКА
    # fourth_page.mediaBox.upperLeft = (first_coord / 2, second_coord / 2)  # НИЖНЯЯ ПРАВАЯ ЧЕТВЕРТИНКА

    left_up_side.mediaBox.lowerRight = (first_coord / 2, second_coord / 2)  # ВЕРХНЯЯ ЛЕВАЯ ЧЕТВЕРТИНКА
    right_up_side.mediaBox.lowerLeft = (first_coord / 2, second_coord / 2)  # ВЕРХНЯЯ ПРАВАЯ ЧЕТВЕРТИНКА
    left_down_side.mediaBox.upperRight = (first_coord / 2, second_coord / 2)  # НИЖНЯЯ ЛЕВАЯ ЧЕТВЕРТИНКА
    right_down_side.mediaBox.upperLeft = (first_coord / 2, second_coord / 2)  # НИЖНЯЯ ПРАВАЯ ЧЕТВЕРТИНКА

    # print(f'{first_page=}\n\n')
    # one_page = left_up_side.getContents()
    # second_page = right_up_side.getContents()
    # decode_one = DecodedStreamObject()
    # print(f'{decode_one.getData()}')
    # print(f'{decodeStreamData(second_page)}')

    # print(f'ПОСЛЕ ОБРЕЗКИ:\n{type(left_up_side)=}\n{left_up_side=}\n')
    # print(f'{left_up_side.extractText().encode("utf8")=} {type(left_up_side.extractText())=}')
    # print(f'{right_up_side.extractText().encode("utf8")=} {type(right_up_side.extractText())=}')
    # print(f'{left_up_side.getContents()=} {type(left_up_side.getContents())=}')
    # print(f'{right_up_side.getContents()=} {type(right_up_side.getContents())=}')
    # print(f'\nПОСЛЕ ОБРЕЗКИ:\n{type(left_up_side)=}\n{left_up_side=}\n')
    # print(f'\nПОСЛЕ ОБРЕЗКИ:\n{type(right_up_side)=}\n{right_up_side=}\n')

    pdf_writer = PyPDF2.PdfFileWriter()
    # pdf_writer.addPage(first_page)
    pdf_writer.addPage(left_up_side)
    pdf_writer.addPage(right_up_side)

    with open(output_file, 'wb') as file:
        pdf_writer.write(file)
        file.close()

def fitz_four_piaces(input_file, output_file):
    input_file = str(input_file.absolute())

    src = fitz.open(input_file)
    doc = fitz.open()  # empty output PDF
    page = 0

    for spage in src:  # for each page in input
        r = spage.rect  # input page rectangle
        d = fitz.Rect(spage.cropbox_position,  # CropBox displacement if not
                      spage.cropbox_position)  # starting at (0, 0)

        # --------------------------------------------------------------------------
        # example: cut input page into 2 x 2 parts
        # --------------------------------------------------------------------------
        r1 = r / 2  # top left rect
        r2 = r1 + (r1.width, 0, r1.width, 0)  # top right rect
        r3 = r1 + (0, r1.height, 0, r1.height)  # bottom left rect
        r4 = fitz.Rect(r1.br, r.br)  # bottom right rect
        rect_list = [r1, r2, r3, r4]  # put them in a list

        for rx in rect_list:  # run thru rect list
            count = 0 # почему-то не считает
            rx += d  # add the CropBox displacement
            # print(f'{rx=}')
            page = doc.new_page(-1,  # new output page with rx dimensions
                                width=rx.width,
                                height=rx.height)
            page.show_pdf_page(
                page.rect,  # fill all new page with the image
                src,  # input document
                spage.number,  # input page number
                clip=rx,  # which part to use of input page
            )
            # print(f'{spage.number=}')
            # text_in_page = page.get_text("text")#.encode("utf8")
            # print(f'{text_in_page=}')
            # print(f'{count=} {doc.get_page_text(doc.page_count - 1)=}')
            # print(f'in cicle {doc.page_count - 1=}')
            count += 1

    # that's it, save output file
    # print(f'{doc.metadata=}')
    # print(f'{doc.page_count=}')
    doc.save(output_file,  #
             garbage=3,  # eliminate duplicate objects
             deflate=True,  # compress stuff where possible
             )
    # input_file2 = str(output_file.absolute())
    # src2 = fitz.open(input_file2)
    # print(f'{src2.page_count=}')
    # for page in src2:
    #     print(f'{page.get_text("words")=}')

def fitz_four_piaces_read(input_file):
    input_file = str(input_file.absolute())
    src = fitz.open(input_file)
    print(f'{src.page_count=}')
    for page in src:
        print(f'{page.get_text("text")=}')

destination = Path().joinpath("MAKETS")
destination.mkdir(parents=True, exist_ok=True)
destination_input = destination.joinpath(
    f'up_lef.pdf')  # up_lef_up_rig_low_lef_low_rig

destination_output = destination.joinpath(
    f'output_a6_{random.randint(1, 100)}_{random.randint(1, 200)}.pdf')  # f'output_a6_{random.randint(1, 100)}_{random.randint(1, 200)}.pdf'

# from_a4_to_a6_not_sync(destination_input, destination_output)

fitz_four_piaces(destination_input, destination_output)
fitz_four_piaces_read(destination_output)

A: Solution found! It is necessary after dividing the page into 4 parts, convert the resulting pages into pictures and then compare the size. I will share the code, maybe it will be useful to someone)
import os

import fitz

def get_size(filename):
    st = os.stat(filename)
    return st.st_size

async def from_a4_to_a6(input_file, output_file):
    input_file = str(input_file.absolute())

    src = fitz.open(input_file)
    doc = fitz.open()  # empty output PDF

    for spage in src:  # for each page in input
        r = spage.rect  # input page rectangle
        d = fitz.Rect(spage.cropbox_position,  # CropBox displacement if not
                      spage.cropbox_position)  # starting at (0, 0)
        # --------------------------------------------------------------------------
        # example: cut input page into 2 x 2 parts
        # --------------------------------------------------------------------------
        r1 = r / 2  # top left rect
        r2 = r1 + (r1.width, 0, r1.width, 0)  # top right rect
        r3 = r1 + (0, r1.height, 0, r1.height)  # bottom left rect
        r4 = fitz.Rect(r1.br, r.br)  # bottom right rect
        rect_list = [r1, r2, r3, r4]  # put them in a list

        for rx in rect_list:  # run thru rect list
            rx += d  # add the CropBox displacement
            page = doc.new_page(-1,  # new output page with rx dimensions
                                width=rx.width,
                                height=rx.height)
            page.show_pdf_page(
                page.rect,  # fill all new page with the imageb
                src,  # input document
                spage.number,  # input page number
                clip=rx,  # which part to use of input page
            )
            #  Here we will convert the pdf to an image and check the size
            pix = page.get_pixmap()  # render page to an image
            name_png = f"page-{page.number}.png"  # _{random.randint(1,100)}
            pix.save(name_png)  # store image as a PNG
            imgsize = get_size(name_png)
            os.remove(name_png)
            if imgsize < 1300:  #  A6 blank page size approximately 1209 Yours may be different, check first
                doc.delete_page(pno=-1)
                break

    doc.save(output_file,
             garbage=4,  # eliminate duplicate objects
             clean=True,
             deflate=True,  # compress stuff where possible
             )


text:
Q: how to align sliding window to extract features from multi modal timeseries data? I have two datasets that are collected at different frequencies at the same time. One is recorded at 128Hz and another one is recorded at 512 Hz. I am trying to extract some features using the moving window technique but I have some problems.

*

*Frequencies of both datasets are different.

*the timestamp is in unix format and changes in nanoseconds. hence there won't be any match at the start and end of each second or minute.

*one of the datasets is actually a little longer than the other by a few seconds.

is there any way I can align my window properly with respect to timestamp and calculate features? or if there is another way please suggest me.

A: yes there is a valid solution called pyphisio https://github.com/MPBA/pyphysio
Hope it helps!


text:
Q: Encoding image, using reed-solomon coder I,m trying encode, send and put some noise,and decode an Image in  Python  app using Reed-Solomon coder
I have converted imagage from PIL to numpy array. Now I'm trying to encode this array and then decode it. But I have problem with code word. It's too long. Does anyone know how to solve this problem. Thank You in advance
Error message:
ValueError: Message length is max 223. Message was 226
import unireedsolomon as rs
from PIL import Image
import numpy as np

class REED
  def __init__(self):

    self.img = None
    self.numpyImg = None

  def loadPictureAndConvertToNumpyArray(self):
    self.img = Image.open('PATH')
    self.img.load()
    self.numpyImg = np.array(self.img)

  def reedSolomonEncode(self):

    coder = rs.RSCoder(255,223)
    self.numpyImg = coder.encode(self.numpyImg)

A: The ReedSolomon package's github page clearly indicates that you cannot encode arrays that are larger than k (223 in your case). This means that you have to split your image first before encoding it.
You can split it into chunks of 223 and then work on the encoded chunks:
k = 223
imgChunks = np.array_split(self.numpyImg, range(k, self.numpyImg.shape[0], k))
encodedChunks = [coder.encode(chunk) for chunk in imgChunks]


text:
Q: Coincidence of two topologies Let $X$ be a metric space.
$F$ is a set of mapping from $X$ into itself, Then:
If $F$ is equicontinuous on $X$ then on $F$ the topology of pointwise convergence coinsides with the compact-open topology on $F$.
How can I prove this? many thanks for any help

A: By the notation $[A,B]$, where $A,B \subseteq X$, I will mean $\{f: X \to X: f[A] \subseteq B\}$. The pointwise topology on a set of functions $F$ then has as base all sets of the form $[A,U] \cap F$, where $A$ is finite and $U$ is open, and the compact-open topology on $F$ has as base all sets of the form $[K,U]\cap F$ where $K$ is compact and $U$ is open. As all finite subsets are compact, it's clear that the pointwise topology is always coarser than (i.e. a subset of) the compact-open topology. So to show the reverse inclusion for an equicontinuous family $F$, we need to show the following fact:

For all compact $K$ and open $U$ and $f \in [K,U] \cap F$ there is a finite subset $A$ of $X$ such that $f \in [A,U]\cap F \subseteq [K,U]\cap F$.

Some ideas on how to do this: First find $\varepsilon >0$ such that $B(f[K],\varepsilon) \subseteq U$ by compactness of $f[K]$ and openness of $U$.
Then apply equicontinity of $F$ to find some $\delta>0$ such that $d(x,x') < \delta$ always implies $d(g(x),g(x'))< \frac{\varepsilon}{3}$ (or some other convenient fraction of $\varepsilon$), globally on $X$ or at least on $K$, depending on your definition of equicontinity, and cover $K$ with finitely many balls of radius $\frac{\delta}{2}$. Use their centres as the finite $A$. Use triangle inequalities to show the inclusion we need.


text:
Q: Files corrupt when downloaded through php header I have a download link on my website from where we can download attachments. The pdf file is downloading perfectly but the images, docs and zip file are downloading as corrupt.
Below is the code which I am using for download. The code is working fine in my local pc but not on the server.
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($FilePath));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($FilePath));
readfile($FilePath);
exit;

A: The corruption occurs if your php script echoes anything before your headers.
Try using the same code, but in a separate php script.

A: Try adding
header('Content-Transfer-Encoding: binary');


text:
Q: Downloading file from Azure blob storage via Memory Stream I currently have an endpoint in my .net 7 API that when hit, should download a specific file from my blob storage by using the file name. When I test out the endpoint I get a 500 error stating
"Time outs are not supported in this stream".  I have attached the error below for more information.
Endpoint.cs
public IEndpointRouteBuilder MapEndpoints(IEndpointRouteBuilder endpoints)
{

    endpoints.MapGet("getBlob/{blobname}", async (string blobName, IApplicationFormService applicationFormService) => await applicationFormService.GetBlob(blobName))
        .Produces<FileStreamResult>();

    return endpoints;
}

Service.cs
public async Task<IResult> GetBlob(string blobName)
{

    BlobClient blobClient = _blobServiceClient
        .GetBlobContainerClient("root")
        .GetBlobClient(blobName);

    try
    {
        using (var memoryStream = new MemoryStream())
        {
            await blobClient.DownloadToAsync(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);

            var newMemoryStream = new MemoryStream(memoryStream.ToArray());

            return Results.Ok(new FileStreamResult(newMemoryStream, "application/octet-stream") { FileDownloadName = blobName });
        }

    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }

    return Results.Ok(blobName);
}

A: Based on the stacktrace of the error, it doesn't seems to come from the downloading of the blob, but from your endpoint when it tries to serialize the response to json.
I think the mistake is on the line
            return Results.Ok(new FileStreamResult(newMemoryStream, "application/octet-stream") { FileDownloadName = blobName });

FileStreamResult is already an IActionResult that represents an HTTP 200 response so there's no need to call the Ok() method.
So the line should just be :
            return new FileStreamResult(newMemoryStream, "application/octet-stream") { FileDownloadName = blobName };

A: The issue was that I was returning Results.ok() when I should have returned Results.File()
using (var memoryStream = new MemoryStream())
        {
            await blobClient.DownloadToAsync(memoryStream);
            //memoryStream.Seek(0, SeekOrigin.Begin);

            return Results.File(memoryStream.ToArray(), "application/octet-stream", blobName);
        }


text:
Q: Unexpected results in playing with relations /*
sig a {
}

sig b {
}
*/

pred rel_test(r : univ -> univ) {
    # r = 1
}

run {
    some r : univ -> univ {
        rel_test [r]
    }
} for 2

Running this small test, $r contains one element in every generated instance. When sig a and sig b are uncommented, however, the first instance is this:

In my explanation, $r has 9 tuples here and still, the predicate which asks for a one tuple relation succeeds. Where am I wrong?
An auxiliary question: are these two declarations equivalent?
pred rel_test(r : univ -> univ)
pred rel_test(r : set univ -> univ)

A: The problem is that with the Forbid Overflow option set to No the integer semantics in Alloy is wrap around, and with the default scope of 3 (bits), then indeed 9=1, as you can confirm in the evaluator.
With the signatures a and b commented the biggest relation that can be generated with scope 2 has 4 tuples (since the max size of univ is 2), so the problem does not occur.
It also does not occur in the latest build because I believe it comes with the Forbid Overflow option set to Yes by default, and with that option the semantics of integers rules out instances where overflows occur, precisely the case when you compute the size of the relation with 9 tuples. More details about this alternative integer semantics can be found in the paper "Preventing arithmetic overflows in Alloy" by Aleksandar Milicevic and Daniel Jackson.

A: On the main question:  what version of Alloy are you using?  I'm unable to replicate the behavior you describe (using Alloy 4.2 of 22 Feb 2015 on OS X 10.6.8).
On the auxiliary question:  it appears so.  (The language reference is not quite as explicit as one might wish, but it begins one part of its discussion of multiplicities with "If the right-hand expression denotes a unary relation ..." and (in what I take to be the context so defined) "the default multiplicity is one"; the conditional would make no sense if the default multiplicity were always one.
On the other hand, the same interpretive logic would lead to the conclusion that the language reference believes that unary multiplicity keywords are only allowed before expressions denoting unary relations (which would appear to make r: set univ -> univ ungrammatical).  But Alloy accepts the expression and parses it as set (univ -> univ).  (The alternative parse, (set univ) -> univ, would be very hard to assign a meaning to.)


text:
Q: Problems with function detecting Date Value on Appscript I'm coding a function that returns true in A6 if any new value is entered on row 4 is a Date and false on the other side. But it returns all false, even I enter a Date value or any other value. Can anybody show me my mistake.
function isValidDate(d) {
  if ( Object.prototype.toString.call(d) !== "[object Date]" )
    return false;
  return !isNaN(d.getTime());
}
function onEdit(e) {
  ss2 = e.source;
  chanr = e.range.getRow();
  chancl = e.range.getColumn();
  vlnhap = e.value;
  oct = ss2.getActiveSheet().getRange(chanr,chancl).getCell(1,1);
  if(chanr === 4){
if(isValidDate(oct)){
  ss2.getActiveSheet().getRange('A6').setValue('true');
  }
else{
  ss2.getActiveSheet().getRange('A6').setValue('false');
}
  }
}

A: Why not use regular functions? Try this in A6:
=IF(COUNTIF(
 ARRAYFORMULA(IF(ISERROR(DATEVALUE(
  FILTER(4:4,4:4 <> ""))),false,true)),false)
    > 0,false,true)


text:
Q: Has anyone done a Twitter sentiment analysis using PySpark? Has anyone done a Twitter sentiment analysis using Apache Spark?I have tried this
class Tweet(dict):
    def __init__(self, tweet_in, encoding  = 'utf-8'):
        super(Tweet, self).__init__(self)
        if tweet_in and 'delete' not in tweet_in:
            self['id']           = tweet_in['id']
            self['geo']          = tweet_in['geo']['coordinates'] if tweet_in['geo'] else None
            self['text']         = tweet_in['text'].encode(encoding)
            self['user_id']      = tweet_in['user']['id']
            self['hashtags']     = [x['text'].encode(encoding) for x in tweet_in['entities']['hashtags']]
            self['timestamp']    = dateutil.parser.parse(tweet_in[u'created_at']).replace(tzinfo=None).isoformat()
            self['screen_name']  = tweet_in['user']['screen_name'].encode(encoding)

    def connect_twitter():

        consumer_key    = "personal_info"
        consumer_secret = "personal_info"
        access_token    = "personal_info"
        access_secret   = "personal_info"
        auth            = twitter.OAuth(token           = access_token,
                                        token_secret    = access_secret,
                                        consumer_key    = consumer_key,
                                        consumer_secret = consumer_secret)
        return twitter.TwitterStream(auth=auth)

    def get_next_tweet(twitter_stream, i ):
        block    = False # True
        stream   = twitter_stream.statuses.sample(block=False)
        tweet_in = None
        while not tweet_in or 'delete' in tweet_in:
            tweet_in     = stream.next()
            tweet_parsed = Tweet(tweet_in)

        return json.dumps(tweet_parsed)

    def process_rdd_queue(twitter_stream, nb_tweets = 5):`enter code here`
        rddQueue = []
        for i in range(nb_tweets):
             json_twt  = get_next_tweet(twitter_stream, i )
             dist_twt  = ssc.sparkContext.parallelize([json_twt], 5)
             rddQueue += [dist_twt]

        lines = ssc.queueStream(rddQueue, oneAtATime=False)
        lines.pprint()

enter code here

try    : sc.stop()
except : pass

sc  = SparkContext(appName="PythonStreamingQueueStream")
ssc = StreamingContext(sc, 1)

twitter_stream = connect_twitter()
process_rdd_queue(twitter_stream)

try    : ssc.stop(stopSparkContext=True, stopGraceFully=True)
except : pass

ssc.start()
time.sleep(2)
ssc.stop(stopSparkContext=True, stopGraceFully=True)

Do I need to have a static file where I need positive and negative words for sentiment analysis mechanism.
I am a beginner at this.


text:
Q: How to make dependent dropdownlist in Yii2? I'm trying to make a dependend dropDownList in Yii2. I'm trying to use DepDrop Widget, but I can't understand how to edit the code according to my situation. I have 1 model and inside of it I need to make category dropdown list and according to the category_id, the next dropDownList should be Item. (F.e If I select category 1, the Item should be Item1 and so on).
I guess that extension only can do dropdowns of the same model? I'm new to Yii2, so.
My view file:
<div class="site-create">

<?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'code') ?>
    <?= $form->field($category, 'id')->dropDownList($category, ['id'=>'category-id']); ?>
    <?= $form->field($item, 'subcat')->widget(DepDrop::Item(), [
         'options'=>['id'=>'item-id'],
        'pluginOptions'=>[
         'depends'=>['category-id'],
        'placeholder'=>'Select...',
        'url'=>Url::to(['/site/subcat'])
        ]
   ]); ?>

My $model is different model from $category and $item. I set those variables to use a different model in the action
Here is my action:
    public function actionSubcat() {
    $category = new Category();
    $item = new Item();
    $out = [];
    if (isset($_POST['depdrop_parents'])) {
        $parents = $_POST['depdrop_parents'];
        if ($parents != null) {
            $cat_id = $parents[0];
            $out = self::getSubCatList($cat_id);
            echo Json::encode(['output'=>$out, 'selected'=>'']);

        return $this->render('create', [
                'category' => $category,
                'item' => $item,
            ]);
        }
    }
    echo Json::encode(['output'=>'', 'selected'=>'']);
}
}

Now I'm getting the error message that the $category variable is undefined. Could someone explain me what I'm doing wrong?

A: Actually you dont need any Widgets or Plugins. In yii2 you can easily do Dependent Dropdown list here is example:
echo $form->field($search,'category')->dropDownList(
    ArrayHelper::map(
        \app\models\Category::find()->all(),
        'id','name'
    ),
    [
        'prompt' => Yii::t('app','choose_city'),
        'onchange'=>'
        $.get( "'.Yii::$app->urlManager->createUrl('site/dropdown?id=').'"+$(this).val(), function( data ) {
        $( "select#subcat" ).html( data );
        })'
    ]
);
echo $form->field($search, 'sub_category', ['inputOptions'=>['id'=>'subcat',]])->dropDownList([]);

after that you need to create action for returning action. Example:
 public function actionDropdown($id)
{
    $countPosts = \app\models\SubCategory::find()
        ->where(['category_id' => $id])
        ->count();

    $posts =  \app\models\SubCategory::find()
        ->where(['category_id' => $id])
        ->orderBy('name ASC')
        ->all();
    echo "<option value=''>-</option>";
    if($countPosts>0){
        foreach($posts as $post){
            echo "<option value='".$post->id."'>".Yii::t('app',$post->name)."</option>";
        }
    }

}

thats all.

A: i suggest using knockoutjs for doing this. i answered a similar question here
knockout example is here (category > product)
html:
<select data-bind="options: data, value: selected, optionsText: 'title', optionsCaption: '---'"></select>
<select data-bind="options: dependent"></select>

javascript:
<script>
    function viewmodel() {
        var self = this;

        this.data = [
            { title: 'title a', items: ['a1', 'a2', 'a3'] },
            { title: 'title b', items: ['b1', 'b2', 'b3'] },
            { title: 'title c', items: ['c1', 'c2', 'c3'] }
        ];

        this.selected  = ko.observable();
        this.dependent = ko.computed(function() {
            return ((self.selected() || {}).items || []);
        });

    }

    $(document).ready(function() {
        ko.applyBindings(new viewmodel());
    });
</script>

you can still use $form->field, just add 'data-bind' attribute as inputOption.
if you want to use the field's default values, Json::encode those key-value-pairs and create the viewmodel like this:
ko.applyBindings(new viewmodel(<?= Json::encode($data) ?>));

using those parameters is javascript manual labour

A: <?= $form->field(**$category**, 'id')->dropDownList(**$category_dropdown**, ['id'=>'category-id']); ?>

Both the names are not same:
$category = your model
$category_dropdown = arrayhelper variable in your action
like below
    $transactioncategory = ArrayHelper::map(Transactioncategory::find()->all(), 'id', 'transaction_category');


text:
Q: Shorter and more efficient way of writing this Java code What is the best way to write this code and avoid repeatedly?
if (doAction() || checkNumber() || canMove() || avoidAttackersWhileHeal()) {
    return;
}

if (doCast() || doAttack()) {
    return;
}

I have a ton of methods like this, and each method that returns true means it won't continue, but coding style like this is ugly. Is there any other way to write it?

A: As alternative, you can wrap your single methods in separate Predicate and then build a common predicate with required operations. This final Predicate hides all if...else.
private final Predicate<Void> predicate;

{
    Predicate<Void> doAction = in -> doAction();
    Predicate<Void> checkNumber = in -> checkNumber();
    Predicate<Void> canMove = in -> canMove();
    Predicate<Void> avoidAttackersWhileHeal = in -> avoidAttackersWhileHeal();
    Predicate<Void> doCast = in -> doCast();
    Predicate<Void> doAttack = in -> doAttack();
    predicate = doAction.or(checkNumber).or(canMove).or(avoidAttackersWhileHeal).or(doCast).or(doAttack);
}

public void doIt() {
    predicate.test(null);
}


text:
Q: Edittext with custom offset rectangle background I'd like to create and edittext box with a custom offset background like this:

How should I go about doing this?

A: I'd go with a LinearLayout containing your border as the background drawable, same padding for top, left and right and higher padding at bottom.
Then, setting a custom, stateful 9-patch drawable for your EditText based on your background.
In fact, if you make your background 9-patched, you can use it both in your LinearLayout and your EditText.
Also, you don't have to make your EditText drawable stateful; but I strongly advise you to do so, so the user can actually get visual feedback from your EditText.
Sample code:
layout/your_layout.xml
...
<LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:background="@drawable/bg_border"
     android:paddingLeft="10dip"
     android:paddingRight="10dip"
     android:paddingTop="10dip"
     android:paddingBottom="30dip">

     <EditText
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:background="@drawable/bg_border_statelist" />

</LinearLayout>
...

drawable/bg_border_statelist.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true"
        android:drawable="@drawable/bg_border_selected" />
    <item android:state_focused="true"
        android:drawable="@drawable/bg_border_selected" />
    <item android:drawable="@drawable/bg_border" />
</selector>

Assuming your background image is 9-patch and called bg_border.9.png, and the respective 9-patch version is called bg_border_selected.9.png.
Cheers!


text:
Q: Query for Transactions per second? For performance mornitoring, i would like to have a mysql query which gives the calculated output of TPS. I think tps= Com_commit + Com_rollback / second , but I don't know the query to calculate these formula in mysql. Same related question for TPS had been asked but query was not provided there, so why I ask here. Kindly show me how to calculate values from status in MySQL/MariaDB.

A: It's a bit clunky, but this should give you the tps since restart of MySQL:
SELECT  SUM(IF(variable_name IN ('Com_commit', 'Com_rollback'),
                   variable_value, 0)) /
        SUM(IF(variable_name = 'Uptime',
                   variable_value, 0))
    FROM  information_schema.GLOBAL_STATUS

A: Com_commit and Com_rollback are available in information_schema.global_status.  You need to query them regularly and calculate the difference between readings in order to get quantity per duration.
When I tried to do something similar, a co-worker asked what it would really tell us.  His argument was that it told us nothing about transaction size - no way to know how much work was being done.  For example BEGIN; COMMIT; is a transaction, which will increase your counter, but not tell you anything. Also, if your TPS drops, is that because of a bottleneck, or a drop in application demand?
Don't let that stop you from implementing this monitoring, but make sure you know what you're getting from the number.


text:
Q: Radom post image/link based on custom taxonomy How would I make a widget to display a random post's image and permalink? I would like it to pull from a specific custom content type and only posts have set the custom field of "featured" to "yes".

A: <?php query_posts( 'cat=36&post_type=athletes&showposts=1&orderby=rand'); ?>

changed to :
      <?php
$args = array( 'numberposts' => 36,'category'  => '1','post_type'  => 'athletes', 'orderby' => 'rand');

$lastposts = get_posts( $args );
foreach($lastposts as $post) : setup_postdata($post); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php endforeach; ?>


text:
Q: script for running program 100 times and greping the result Im trying to write a script so that I can run my program 100 times and grep the execution time.
Currently I have this:
#!/bin/bash
i=1
while [ $i -lt 100 ]
do
    (time -p ./mdu -j $i /pkg) &>> tempfile.txt
    echo $i
    let i=$i+1
done
cat tempfile.txt | grep real > plot.txt

However this does not give me the desired output. I wish to only get the execution time of the 100 runs but instead plot.txt comes out with 551 lines of data. All the lines does contain "real 1.31(random time)" but it feels like I get alot of duplicates or something.
What am I doing wrong here?

A: As you wrote it, you append to tempfile.txt the resource use statistics, plus the standard and error outputs of your program. So if these last two streams contain real they will pollute your results. Try:
time (<your-program> &>> log.txt) &>> tempfile.txt

But why don't you use the time utility, instead of the bash builtin, and its options (time -pao tempfile.txt) to append only the statistics to your file? Something like:
#!/bin/bash
i=1
while [ $i -lt 100 ]
do
    /usr/bin/time -pao tempfile.txt ./mdu -j $i /pkg &>> log.txt
    echo $i
    let i=$i+1
done
grep "real" tempfile.txt > plot.txt

Moreover, if you use the time utility you can even specify the output format, instead of using the -p POSIX format and grep the output. If, for your plot, it is more convenient to have only the real time value in [hours:]minutes:seconds:
/usr/bin/time -f'%E' -ao tempfile.txt ...

And if you want it in seconds:
/usr/bin/time -f'%e' -ao tempfile.txt ...

A: You may have 551 lines of data because you kept appending to tempfile.txt and never deleted its contents.
As a side note, your loop runs 99 times, not 100 times. Use either zero-based numbering or <=.
Last but not least, time is quite tricky (in its built-in form), especially due to the way it interacts with pipes.
run_n_times() {
  local -ir N="$1"
  shift
  local -ar args=("$@")
  local -i i
  for ((i = 1; i <= N; ++i)); do
    ( time -p "${args[@]//#/"$i"}"; ) \
    |& awk '/^real/ {print $2}'
  done
}

# A simple test:
run_n_times 3 sleep '#'

# The real thing:
run_n_times 100 ./mdu -j '#' /pkg


text:
Q: PHP POST data via command line You can run a php script from command line by this: php youscript.php
My question: Is it possible to pass the post data to the script like php yourscript.sh post1=test post2=test2 so that you can get this data by $_POST["post1"]?

A: See: http://php.net/manual/en/function.getopt.php
Example #1 getopt() example: The basics
<?php
// Script example.php
$options = getopt("f:hp:");
var_dump($options);
?>

shell> php example.php -fvalue -h
array(2) {
  ["f"]=>
  string(5) "value"
  ["h"]=>
  bool(false)
}

$_POST is set by Apache, which gets $_POST data from a HTTP connection. If you're looking to call php directly via the command line, apache is never called and hence $_POST, $_GET, $_REQUEST etc, these are never set.


text:
Q: Mac OS: Shortcut for restoring a minimized window? I've managed to find or set shortcuts for "zoom" and "maximize" a window, but I can't find the way to restore a minized window, other than click the icon in the dock. Is there a way to set a shortcut for this manuever?

A: Here you go https://apple.stackexchange.com/a/55440:

*

*Command + Tab until you get the app's icon.

*Before releasing Command, press and hold ⌥ (option).


text:
Q: How to sort a multidimensional array by alphanumeric value? I have an array like this below,
Array
(
    [2] => Array
        (
            [id] => 75
            [program] => Apr 2020-Nov 2020
        )

    [1] => Array
        (
            [id] => 73
            [program] => Feb 2016-Aug 2020
        )

    [0] => Array
        (
            [id] => 72
            [program] => May 2020-Dec 2020
        )

)

The resultant array should be
Array
(

    [1] => Array
        (
            [id] => 73
            [current_program] => Feb 2016-Aug 2020
        )
    [2] => Array
        (
            [id] => 75
            [current_program] => Apr 2020-Nov 2020
        )

    [0] => Array
        (
            [id] => 72
            [current_program] => May 2020-Dec 2020
        )

)

It should sort based on the year. I have tried to achieve by "strnatcasecmp", but the array is sorting by alphabet not by the numeric value in it
    usort($programp, function($a, $b) {
        return strnatcasecmp($a['program'], $b['program']);
    });

Any help would be appreciated!
Thanks

A: You need to convert the first month and year into a timestamp, sort that thereby sorting the original:
foreach($programp as $values) {
    $starts[] = strtotime(explode('-', $values['program'])[0]);
}
array_multisort($starts, $programp);

Before sorting the $starts array would look like this, easy to sort:
Array
(
    [0] => 1585692000
    [1] => 1454281200
    [2] => 1588284000
)

You probably want some error checking to make sure $values['program'] is not empty etc...

A: //Sort indexes so the keys are 0,1,2 instead of 1,2,0
//This is important when sorting down below with asort()
$arr = array_values($arr);

//Go through every "program" (dateinterval in your array)
//and make a new array in the format year-monthnr
//Date parse returns the number of jan(1),feb(2),mar(3) etc..
$year_month = [];
foreach(array_column($arr,'program') as $key => $item) {
    $year = explode(' ', explode('-',$item)[0])[1];
    $month = date_parse(explode(' ', explode('-',$item)[0])[0])['month'];
    $year_month[] = $year . '-' . $month;
}

//Sort with mainted indexes (keys)
asort($year_month);

//Create new array "mapped" keys to the original array $arr
$new_arr = [];
foreach($year_month as $key=>$item) {
    $new_arr[] = $arr[$key];
}

Output of $new_arr would be:
Array
(
    [0] => Array
        (
            [id] => 73
            [program] => Feb 2016-Aug 2020
        )

    [1] => Array
        (
            [id] => 75
            [program] => Apr 2020-Nov 2020
        )

    [2] => Array
        (
            [id] => 72
            [program] => May 2020-Dec 2020
        )

)


text:
Q: Switching deploy servers on Bluemix I am not quite sure how to name this question. But, I will list the expectations below to explain it.

*

*Having an application running on Bluemix.

*Having code on local.

*Push through git to Bluemix.

*Restart the application for new code to take effect.

So the question is:
In the above situation, if I want to avoid down time while the server is restarting, which could be long if it is having unexpected issues, how can the website keep transferring data through the Bluemix server. Should I have a shadow server? How do I manage them so they know when to switch (automatic/manual) in case the website won't notice the down time? Many thanks.

A: You need to do a blue green deployment.  Here is an example article http://garage.mybluemix.net/posts/blue-green-deployment/


text:
Q: mocking database methods using fflib As fas as I know it is not possible to mock the methods under Database because salesforce does not allow mocking static methods. However, One can circumvent this limitation by wrapping the static method with another class. I would like to mock the method global static String executeBatch(Database.Batchable batchable, Integer batchSize). I am mocking using the fflib library, I wrote the following code but it trows an error when mocking my DatabaseWrapper class:
@IsTest
private class SuperTest {
    @IsTest
    static void method1Test() {
        fflib_ApexMocks mocks = new fflib_ApexMocks();

        IDatabaseWrapper databaseWrapperMock = (DatabaseWrapper) mocks.mock(DatabaseWrapper.class);

        Application.service.setMock(IDatabaseWrapper.class, databaseWrapperMock);
    }
}

public with sharing class DatabaseWrapper implements IDatabaseWrapper {
    public static IDatabaseWrapper newInstance() {
        return (IDatabaseWrapper) Application.service.newInstance(IDatabaseWrapper.class);
    }

    public String executeBatch(Database.Batchable<SObject> batchable, Integer batchSize) {
        return Database.executeBatch(batchable, batchSize);
    }
}

public interface IDatabaseWrapper {
    String executeBatch(Database.Batchable<SObject> batchable, Integer batchSize);
}

public class Application {
    public static final fflib_Application.ServiceFactory service = new fflib_Application.ServiceFactory(
            new Map<Type, Type>{
                    IDatabaseWrapper.class => DatabaseWrapper.class
            }
    );
}

The error message is:
System.TypeException: Class DatabaseWrapper__sfdc_ApexStub must implement the method: String IDatabaseWrapper.executeBatch(Database.Batchable<SObject>, Integer)
Class.System.Test.createStub: line 93, column 1
Class.fflib_ApexMocks.mock: line 67, column 1
Class.SuperTest.method1Test: line 7, column 1

Any idea what I am I doing wrong?

A: So, the pattern I use is taken from the Salesforce Lightning Platform Enterprise Architecture book Third Edition by Andrew Fawcett, Chapter 5 - Service Layer and Chapter 12, p 505 Unit testing a Controller method (service is being mocked) and the example code in the ApexMocks GitHub testmethods and Readme.md.
Interface
public interface IDatabaseWrapper {
    String executeBatch(String batchableName);
}

Service layer (redirector)
public class DatabaseWrapper {
 /**
 * Factory creation of service object
 **/
 public static IDatabaseWrapper service() {
    return (IDatabaseWrapper) Application.Service.newInstance(IDatabaseWrapper.class);
 }
 public static String executeBatch(String batchableName) {
    service().executeBatch(batchableName);
 }
}

Service layer implementation
public class DatabaseWrapperImpl implements IDatabaseWrapper {
  public String executeBatch(String batchableName) {

     Integer batchSize = 200;  // you could also pass this in
     Type t = Type.forName(batchableClassName);
     Database.Batchable<Sobject> batchable = (Database.Batchable<Sobject>)t.newInstance();
     Database.executeBatch(batchable,batchSize);
  }
}

Application.cls
public static final fflib_Application.ServiceFactory Service =
    new fflib_Application.ServiceFactory(
        new Map<Type, Type> {
                IDatabaseWrapper.class  => DatbaseWrapperImpl.class
        });

Some code under test that uses DatabaseWrapper method
public class MyClass {
  public void myMethod(String batchableClassName) {

     String batchId = DatabaseWrapper.executeBatch(batchableClassName);
     // other work
  }
}

Test method
fflib_ApexMocks mocks = new fflib_ApexMocks();
// Given mock Service class
DatabaseWrapperImpl mockDatabaseWrapper = (DatabaseWrapperImpl) mocks.mock(DatabaseWrapperImpl.class);
// Given mock Service injected
Application.Service.setMock(IDatabaseWrapper.class,mockDatabaseWrapper);

mocks.startStubbing();
mocks.when(mockDatabaseWrapper.executeBatch(fflib_Match.anyString())
            .thenReturn('someBatchId');
mocks.stopStubbing();

// when code under test is executed
new MyClass().myMethod('MyMockBatchable');
// Then verify

When the MyClass.myMethod is invoked at run time, its implementation of executeBatch is mocked and the batchId is returned using the mocks.when - thenReturn construction within the stubbing.
I'd recommend you rename DatabaseWrapper to the fflib pattern - something like BatchServices.cls and BatchServicesImpl.cls.  That is, everything referenced in Application should be a Domain, Selector, Service, or UnitOfWork


text:
Q: Macros to copy and paste in loop For many of you this might be simple. I need to copy and paste data from 2 specific columns to a new spread sheet; but the macros need to stop when it reaches the end of data or when a cell is blank.
So far the code looks like this:
Workbooks.Add
ActiveCell.FormulaR1C1 = _
    "='[Muhanad_Reset_import-TEMPLATE.xlsx]Reset_import-Raw Data'!R1C1"
Range("A1").Select
ActiveCell.FormulaR1C1 = _
    "='[Muhanad_Reset_import-TEMPLATE.xlsx]Reset_import-Raw Data'!RC1"
Range("B1").Select
ActiveCell.FormulaR1C1 = _
    "='[Muhanad_Reset_import-TEMPLATE.xlsx]Reset_import-Raw Data'!R1C3"
Range("B1").Select
ActiveCell.FormulaR1C1 = _
    "='[Muhanad_Reset_import-TEMPLATE.xlsx]Reset_import-Raw Data'!RC3"
Range("A1:B1").Select
Selection.Copy
Range("A2:A101").Select
ActiveSheet.Paste
Range("A1").Select
Windows("Muhanad_Reset_import-TEMPLATE.xlsx").Activate

I know the code for copy and paste code does not work for a good result.

A: Do you mean code like this:
Sub Test()
    Dim lr      As Long
    Dim i       As Long

    lr = ThisWorkbook.Worksheets("Reset_import-Raw Data").Cells(Rows.Count, 1).End(xlUp).Row
    Workbooks.Add

    With ActiveSheet.Range("A1:A" & lr)
        .Formula = "='[Muhanad_Reset_import-TEMPLATE.xlsx]Reset_import-Raw Data'!$A1"
        .Offset(, 1).Formula = "='[Muhanad_Reset_import-TEMPLATE.xlsx]Reset_import-Raw Data'!$C1"
    End With

    Windows("Muhanad_Reset_import-TEMPLATE.xlsm").Activate
End Sub


text:
Q: How do I reorder database by ID? Currently my database is pretty messed up. The id's are not listed properly. I want them to be listed down permanently from 1 to 10. How do I do that? I want them listed from 1 to 10 permanently. Not just with
SELECT * FROM `accounts` ORDER BY `accounts`.`id` ASC

A: I know it's a process but you can make it this way first use this query to get data in order by id
 select * from accounts order by id asc
and insert the data in a dummy table and then just replicate the data of dummy table in your original table i.e. accounts
hope this will work for you


text:
Q: Has leaving the battle any further impacts? I noticed that some players just leave the battle when they lose obviously very early in a match.
Do you lose crowns normally on this way or does it have consequences like temporary bans for example due to unsporting behavior (in the case this behavior is repetitive since the system can't detect for 100% if you left intentionally).

A: There are two outcomes to leaving the battle depending on your actions:
If it happened by accident, or you lost connection, BUT managed to reconnect on time, the battle continues. Obviously your enemy would have pushed you very hardly, but you may still have a chance. The game restarted on me once, but I managed to return on time, and TIE it.
IF you leave the battle intentionally at any point, without going back - The battle continues and you'd lose however crows the enemy manages to destroy, and however many trophies you were supposed to lose. I've left once or twice, seeing the enemy is the taunt-type and didn't want to give him the pleasure of taunting me while waiting for the OK button, i simply left few seconds before the time expired.
There are no repercussions or penalties other than the lose, that would have happened with or without you. The game is single player and you leaving would only penalize you, thus no need for punishment like cool-down or something similar.


text:
Q: Ubuntu 22.04 Audio output not working please i have exactly the problem here ubuntu 22.04 audio output not working (dummy audio) and i also followed the solutions but nothing works. my computer audio doesn't still work. i am using the INFINIX Inbook X Corei5

A:
Make sure your output device is set to "LINE OUT".  However I too did notice some "new problem" with the latest kernel "5.15.0-35-generic #36-Ubuntu SMP Sat May 21 02:24:07 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux"

A: I had the same problem and tried many solutions
Finally I found a solution that works
sudo touch /usr/share/pipewire/media-session.d/with-pulseaudio
systemctl --user restart pipewire-session-manager

I don't have much information about that unfortunately


text:
Q: Timer on onDraw start button -> game.class -> gameview.class then loop again on game.class when player finish the 1st level it will call gameview.class to generate again the 2nd level. My problem is that my timer will also regenerate and restarts when going on the 2nd level. How can I make my timer pause and resume in this kind of flow of game?
on my Game.Class:
public void onCreate(Bundle savedInstanceState) {
timeCounter = new TimeCounter();

    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    this.maze = (Maze) getLastNonConfigurationInstance();
    if (this.maze == null) {
        this.maze = (Maze) extras.get("maze");
    }
    gview = new GameView(this);
    gview.setTimeCounter(timeCounter);
    gview.setMaze(this.maze);
    setContentView(gview);

and on my GameView.Class:
protected void onDraw(Canvas canvas) {
if (startTimer) {
        timeCounter.start();
        invalidate();
        int secondss = timeCounter.getTimeSeconds();
        String text = String.format("%02d:%02d", secondss / 60,
                secondss % 60);
        timer.getTextBounds(text, 0, text.length(), textBounds);
        canvas.drawText(text, (this.getWidth() - textBounds.right) - 5,
                (this.getHeight() - textBounds.bottom) - 5, timer);
    }

and when the 1st level finish it will call this method:
void shownextmaze() {
    Random rand = new Random();
    Intent game = new Intent(context, Game.class);
    nextmaze = rand.nextInt(6) + 1;

    Maze maze = MazeCreator.getMaze(nextmaze);
    game.putExtra("maze", maze);
    context.startActivity(game);
    timeCounter.resume();

}

How can I make my timer run until the 4 levels are cleared?

A: It is logical that onDraw will be called and timer will be start again. You should start your timer in a service and run it in background thread. Each time you want to access it value you can bind to service.
Check this guideline.
In this code each time you open the app you will see updated value:
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(MainActivity.this, MyService.class));
        doBindService();

        ((Button) findViewById(R.id.button1))
                .setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (mBoundService != null) {
                            ((TextView) findViewById(R.id.textView1))
                                    .setText(mBoundService.getValue() + "");
                        }
                    }
                });
        ((Button) findViewById(R.id.button2))
                .setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        mBoundService = null;
                        stopService(new Intent(MainActivity.this,
                                MyService.class));
                        doUnbindService();
                    }
                });

    }

    private MyService mBoundService;
    private boolean mIsBound;

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mBoundService = ((MyService.LocalBinder) service).getService();
            ((TextView) findViewById(R.id.textView1)).setText(mBoundService
                    .getValue() + "");

        }

        public void onServiceDisconnected(ComponentName className) {
            mBoundService = null;
        }
    };

    void doBindService() {
        bindService(new Intent(MainActivity.this, MyService.class),
                mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }

    void doUnbindService() {
        if (mIsBound) {
            // Detach our existing connection.
            unbindService(mConnection);
            mIsBound = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doUnbindService();
    }
}

And a service:
public class MyService extends Service {

    private final IBinder mBinder = new LocalBinder();
    // private TimeCounter timeCounter;
    int x = 0;

    public class LocalBinder extends Binder {
        MyService getService() {
            return MyService.this;
        }
    }

    @Override
    public void onCreate() {
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    x++;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public int getValue() {
        return x;
    }
}

Maybe you need activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:text="Show Updated value" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="28dp"
        android:text="Stop Service" />

</RelativeLayout>


text:
Q: Check the type of a generic lambda parameter I have a generic lambda function that is called with several unrelated structs as its parameter.
Inside, I want to execute some code only if the parameter is of a special type.
auto const my_lambda = [](auto obj) {
    // do something with obj
    if (decltype(obj) == SpecialType) // <-- pseudo code, does not work
         auto x = obj.specialMember; // Access to a special member that is present in SpecialType, but not the other types this lambda is called with
}

A: The approach with decltype already goes into the right direction.
Two types can be compared with std::is_same_v<Type1, Type2>
To prevent the compiler from complaining about the undefined .specialMember for the other calls, if constexpr is needed.
This amounts to:
auto const my_lambda = [](auto obj) {
    // do something with obj
    if constexpr (std::is_same_v<decltype(obj), SpecialType>)
         auto x = obj.specialMember; // Access to a special member that is present in SpecialType, but not the other types this lambda is called with
}

If the parameter is passed as a reference, an additional std::decay_t is needed to strip the parameter type from any const& and the like.
auto const my_lambda = [](auto const& obj) {
    // do something with obj
    if constexpr (std::is_same_v<std::decay_t<decltype(obj)>, SpecialType>)
         auto x = obj.specialMember; // Access to a special member that is present in SpecialType, but not the other types this lambda is called with
}


text:
Q: Firebase (FCM): open activity and pass data on notification click. android There should be clear implementation of how to work with Firebase notification and data. I read many answers but can't seem to make it work. here are my steps:
1.) I am passing notification and data to android in PHP and it seems to be fine:
$msg = array
    (
         "body" => $body,
         "title" => $title,
         "sound" => "mySound"
    );

    $data = array
    (

         "user_id" => $res_id,
         "date" => $date,
         "hal_id" => $hal_id,
         "M_view" => $M_view
    );

    $fields = array
    (
        'registration_ids' => $registrationIds,
        'notification' => $msg,
        'data' => $data
    );

    $headers = array
    (
        'Authorization: key='.API_ACCESS_KEY,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
    curl_setopt( $ch,CURLOPT_POST, true );
    curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
    curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
    $result = curl_exec($ch );
    curl_close( $ch );

2.) when notification and data is received in Android it shows notification. When I click on this notification it opens app. But I can not figure out the way to handle the data when the app is opened. There are couple differences when app is in foreground and backround. The code that I have now is the following:
public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    String user_id = "0";
    String date = "0";
    String cal_id = "0";
    String M_view = "0";

    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        user_id = remoteMessage.getData().get("user_id");
        date = remoteMessage.getData().get("date");
        hal_id = remoteMessage.getData().get("hal_id");
        M_view = remoteMessage.getData().get("M_view");
    }

    //Calling method to generate notification
    sendNotification(remoteMessage.getNotification().getBody(), user_id, date, hal_id, M_view);
}

private void sendNotification(String messageBody, String user_id, String date, String hal_id, String M_view) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    intent.putExtra("fcm_notification", "Y");
    intent.putExtra("user_id", user_id);
    intent.putExtra("date", date);
    intent.putExtra("hal_id", hal_id);
    intent.putExtra("M_view", M_view);
    int uniqueInt = (int) (System.currentTimeMillis() & 0xff);
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), uniqueInt, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
}}

3.) When I use the code above and when I click on notification all it does it opens the app if in background. If app in foreground then on notification click it simply dismisses notification. However, I want to receive data and open specific Activity in both scenarios (background and foreground). I have in MainActivity the following code, but I am not able to get data. fcm_notification, date, hal_id returns null.
public class MainActivity extends Activity {
 UserFunctions userFunctions;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    Intent intent_o = getIntent();
}

@Override
protected void onResume() {
    super.onResume();
    userFunctions = new UserFunctions();
    if(userFunctions.isUserLoggedIn(getApplicationContext())){
        Intent intent_o = getIntent();
        String fcm_notification = intent_o.getStringExtra("fcm_notification") ;
        String user_id = intent_o.getStringExtra("user_id");
        String date = intent_o.getStringExtra("date");
        String hal_id = intent_o.getStringExtra("hal_id");
        String M_view = intent_o.getStringExtra("M_view");
        Intent intent = new Intent(this, JobList.class);

        // THIS RETURNS NULL, user_id = null
        System.out.print("FCM" + user_id);
        startActivity(intent);
        finish();
    }else{
        // user is not logged in show login screen
        Intent login = new Intent(this, LoginActivity.class);
        startActivity(login);
        // Closing dashboard screen
        finish();
    }
}}

IF anyone can direct or advice how can I retrieve data in MainActivity.java from Firebase in either scenario (foreground or background) that would be fantastic.

A: So first off, I'll put in the detail mentioned in the Handling Messages docs.
In the summary under the Both row, it shows that when the app is on foreground, the payload will be handled in your onMessageReceived().
In order to open the activity from onMessageReceived(), you should check if the data you need is in the payload, if it does, call your specific activity then pass all the other details you need via intent.
Now if the app is in background, it is mentioned in the docs that the notification is received by the Android system tray and that the data payload can be retrieved from the extras of the intent.
Just adding in the details from my answer here which pretty much just gives the docs statement and a link to a sample:

Handle notification messages in a backgrounded app
When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.
This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

I think this answer by @ArthurThompson explains it very well:

When you send a notification message with a data payload (notification and data) and the app is in the background you can retrieve the data from the extras of the intent that is launched as a result of the user tapping on the notification.
From the FCM sample which launches the MainActivity when the notification is tapped:

if (getIntent().getExtras() != null) {
    for (String key : getIntent().getExtras().keySet()) {
        String value = getIntent().getExtras().getString(key);
        Log.d(TAG, "Key: " + key + " Value: " + value);
    }
}

A: To invoke the onMessageReceived() method you will need to use another method to send notifications (like creating a Web API to send notifications). Then using it,

remove the notification payload from your FCM messages in order to have the data payload delivered to the onMessageReceived() method.

When your app is in the background, data payload is delivered to the onMessageReceived method only if there is no notification payload.

In case both payloads exist then system automatically handles the
  notification part (system tray) and your app gets the data payload in
  the extras of the intent of launcher Activity (after the user tap on
  the notification).

For more info please refer to the following links:

*

*Why is this happening? How to? How to handle push notifications?

*Original answer by kws. Give him an upvote.

A: After trying all the answers and blogs came up with solution. if anyone needs please use this video as reference
https://www.youtube.com/watch?v=hi8IPLNq59o
IN ADDITION to the video to add intents do in MyFirebaseMessagingService:
public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    String user_id = "0";
    String date = "0";
    String hal_id = "0";
    String M_view = "0";

    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        user_id = remoteMessage.getData().get("user_id");
        date = remoteMessage.getData().get("date");
        cal_id = remoteMessage.getData().get("hal_id");
        M_view = remoteMessage.getData().get("M_view");
    }

    String click_action = remoteMessage.getNotification().getClickAction();

    //Calling method to generate notification
    sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle(), user_id, date, hal_id, M_view, click_action);
}

private void sendNotification(String messageBody, String messageTitle, String user_id, String date, String hal_id, String M_view, String click_action) {
    Intent intent = new Intent(click_action);
    intent.putExtra("user_id", user_id);
    intent.putExtra("date", date);
    intent.putExtra("hal_id", hal_id);
    intent.putExtra("M_view", M_view);

    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(messageTitle)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
}}

and in new NotificationReceive activity in onCreate or onResume add this
    notification_Y_N = (TextView) findViewById(R.id.notification_Y_N);
    user_id_text = (TextView) findViewById(R.id.user_id_text);

    Intent intent_o = getIntent();
    String user_id = intent_o.getStringExtra("user_id");
    String date = intent_o.getStringExtra("date");
    String hal_id = intent_o.getStringExtra("hal_id");
    String M_view = intent_o.getStringExtra("M_view");

    notification_Y_N.setText(date);
    user_id_text.setText(hal_id);

A: You don't need to implement sendNotification and onMessageReceived yourself.
When sending:
$data = array
(
    "user_id" => $res_id
    //whatever fields you want to include
);

$msg = array
(
     "body" => $body,
     "title" => $title,
     "data" => $data
     // more fields
);

android side (on your MainACtivity:
private void handleIntent(Intent intent) {
    String user_id= intent.getStringExtra("user_id");
    if(user_id!= null)
        Log.d(TAG, user_id);
}

and of course:
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    handleIntent(intent);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    handleIntent(getIntent());
}

whatever fields you put in data will be sent to your intent extra.

A: firstly, if you have data object and notification object in response . then ask the backend developer to remove notification object.
i hope my own class help .
public class MyFirebaseService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        Log.d(TAG, "Message data payload:id " + remoteMessage.getData().get("mode_id"));

        sendNotification(remoteMessage.getData().get("body"),
                remoteMessage.getData().get("mode_id"), remoteMessage.getData().get("click_action"));

    }
}

private void sendNotification(String messageBody, String id, String clickAction) {
    Intent intent = new Intent(clickAction);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addNextIntentWithParentStack(intent);
    intent.putExtra("id", id);
    intent.putExtra("body", messageBody);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
            | Intent.FLAG_ACTIVITY_CLEAR_TASK);

    PendingIntent pendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "111")
            .setSmallIcon(R.drawable.venus_logo)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setContentIntent(pendingIntent)
            .setLights(Color.GREEN, 3000, 3000);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel notificationChannel = new NotificationChannel("111", "NOTIFICATION_CHANNEL_NAME", importance);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setShowBadge(false);
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        assert notificationManager != null;
        notificationBuilder.setChannelId("111");
        notificationManager.createNotificationChannel(notificationChannel);
        notificationManager.notify(0, notificationBuilder.build());
    } else {
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(0, notificationBuilder.build());
    }
  }
}

then add this to your manifest file .
    <service
        android:name=".data.services.MyFirebaseService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <activity
        android:name=".ui.notifications.NotificationsDetailsActivity"
        android:excludeFromRecents="true"
        android:launchMode="singleTask"
        android:parentActivityName=".ui.home.HomeActivity"
        android:taskAffinity="">
        <intent-filter>
            <action android:name="co.example.yourApp.ui.notifications_TARGET_NOTIFICATION" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

A: Firebase documentation has a great table to explain how it works

https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages
So if you have both data and notification and app is in a foreground when your receive it then you should create a notification by yourself in your service which extends FirebaseMessagingService (in onMessageReceived method)
In other case (app is in background) you can get your data from intent.extras of Activity, a notification will be created by a system to open main activity of the app


text:
Q: how to post manually created json object in ios Please help me. I want to post this json data which I created manually. And I'm getting error as Object reference not set to an instance of an object.
    {
    customerId = 81;
    lstOrderItems = (
        {
            itemId = 149;
            itemQnt = 1;
            itemTotalPrice = 205;
            lstOrderAttribute = (
                {
                    attributeId = 135;
                    lstOrderAttributeValue = (
                        {
                            attributeValueId = 173;
                        },
                        {
                            attributeValueId = 174;
                        }
                    );
                }
            );
        },
        {
            itemId = 129;
            itemQnt = 1;
            itemTotalPrice = 205;
            lstOrderAttribute = (
            {
                    attributeId = 119;
                    lstOrderAttributeValue = (
                        {
                            attributeValueId = 143;
                        },
                        {
                            attributeValueId = 144;
                        },
                        {
                            attributeValueId = 145;
                        },
                        {
                            attributeValueId = 155;
                        }
                    );
                },
                {
                    attributeId = 120;
                    lstOrderAttributeValue = (
                        {
                            attributeValueId = 146;
                        },
                        {
                            attributeValueId = 147;
                        }
                    );
                },
                {
                    attributeId = 124;
                    lstOrderAttributeValue = (
                        {
                            attributeValueId = 158;
                        },
                        {
                            attributeValueId = 165;
                        }
                    );
                }
            );
        },
        {
            itemId = 132;
            itemQnt = 1;
            itemTotalPrice = 205;
            lstOrderAttribute = ( );
        },
        {
            itemId = 144;
            itemQnt = 1;
            itemTotalPrice = 205;
            lstOrderAttribute = ( );
        }
    );
    orderTotalPrice = 291;
    outletId = 54;
}

A: To make your life a bit easier i won't suggest you to construct a json on your own, instead make a dictionary (or array, as per the need) and pass it to json serializer, it will construct a valid json for you (if possible).
Sample code:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:userFirstName, @"fname", userLastName, @"lname", nil];

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                   options:NSJSONWritingPrettyPrinted error:&error];

id json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];

NSLog(@"json : %@", json);

Output log:
2014-03-18 12:03:19.393 DesignMantic[1351:70b] json : {
    fname = John;
    lname = Doe;
}

Pass the constructed json to your service and you are free to invalid json issues.
Reference:
how to create json in objective-c
Hope it helps!
EDIT
Possibly, the data is not serialized to a valid json (may be because it is not convertable to json) and returned nil. You should check it first if the data is converted to json or not rty like this:
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:infoDictionary options:NSJSONWritingPrettyPrinted error:&error];

if(jsonData && [NSJSONSerialization isValidJSONObject:jsonData])
{
NSString *postString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

NSString *url = [NSString stringWithFormat:@"sqwip.ignivainfotech.net/api/customerapi/…"];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:url]];
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
}
else
{
    // Through error, since data sent for JSON serialisation is not convertible to json format
}

A: Your JSON Format is inValid
JSON Syntax Rules
JSON syntax is a subset of the JavaScript object notation syntax:

*

*Data is in name/value pairs

*Data is separated by commas

*Curly braces hold objects

*Square brackets hold arrays

you must have your Format like below one
{
    "firstName": "John",
    "lastName": "Smith",
    "isAlive": true,
    "age": 25,
    "height_cm": 167.64,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021-3100"
    },
    "phoneNumbers": [
        { "type": "home", "number": "212 555-1234" },
        { "type": "fax",  "number": "646 555-4567" }
    ]
}

A: JSONLint is a great way to find out what's wrong with hand-coded JSON.  There are both command-line and web-based versions.
If you were to paste the above JSON into JSONLint.com, you would see that one of the first mistakes you're making is using hash keys that aren't strings.  Fix that, and there may be other errors you'll need to correct.
You'll learn the restrictions of JSON gradually and iteratively using a lint program like this.  Good luck.


text:
Q: How to write correctly in file in C? I have this function:
void write_in_the_log_file(FILE *log_file, int tm_year, int tm_mon, int tm_mday,
                           int tm_hour, int tm_min, int tm_sec)
{
    log_file = fopen(ODIT, "a");
    fprintf(log_file, "Inventory at %02d.%02d.%02d - %02d:%02d:%02d\n", tm_mday, tm_mon, tm_year, tm_hour, tm_min,tm_sec);
    f_print_inventory(log_file);
    fprintf(log_file, "--------------------------------------------------------------\n");
    fclose(log_file);
}

And I call it like this:
  write_in_the_log_file(log_file,
                        tm.tm_year + 1900,
                        tm.tm_mon + 1,
                        tm.tm_mday,
                        tm.tm_hour,
                        tm.tm_min,
                        tm.tm_sec);

Where tm things are the time and they are declared like this:
    time_t T = time(NULL);
    struct tm tm = *localtime(&T);

Also ODIT is:
#define ODIT "odit/log_file.txt"

The problem here is that it is saving it correctly but after it the program crashes with error:
free(): double free detected in tcache 2
Aborted (core dumped)

A: If you are using Mac or Linux, then this path location system can be used, but if you are using Windows OS, then Kindly change the path as per windows path system
try this

#include<stdlib.h>
#include <stdio.h>
#include <unistd.h>
void printData(void);
void ReadData(void);
void printData1(void);
void ReadData1(void);
void MergingFile(void);
int main(int argc, char const *argv[])
{
    printData();
    printData1();
    ReadData();
    ReadData1();
    MergingFile();
    return 0;
}
void printData()
{
    char String[1000]; FILE *file = NULL;
    printf("%s\n\n","Write Few Lines of '30 words' in files to test in File 1 ");
    scanf("%[^\n]",String);
    file = fopen("/Users/hemant/firstFile.txt","w");
    fprintf(file, "%s",String);
    fclose(file);
}
void printData1()
{
    char Stringn[1000];
    FILE *file2 = NULL;
    printf("%s\n\n","Write Few Lines of '30 words' in files to test 2 ");
    scanf("%[^\n]",Stringn);
    file2 = fopen("/Users/hemant/secondFile.txt","w");
    fprintf(file2, "%s",Stringn);
    fclose(file2);
}
void ReadData()
{
       char str[1000];
        FILE *file3 = NULL;
        printf("%s\n\n","You are Reading from First File ");
        file3 = fopen("/Users/hemant/firstFile.txt","r");
        fscanf(file3,"%[^\n]",str);
        printf("%s\n",str);
        fclose(file3);
}
void ReadData1()
{
       char str[1000];
        FILE *file4 = NULL;
        printf("%s\n\n","You are Reading from Second File ");
        file4 = fopen("/Users/hemant/secondFile.txt","r");
        fscanf(file4,"%[^\n]",str);
        printf("%s\n",str);
        fclose(file4);
}
void MergingFile()
{
    int i = 0, j = 0;
    char str[2000],String1[1000],String2[1000];
    FILE *fp = NULL;
    FILE *first = NULL;
    FILE *second = NULL;
    printf("%s\n\n","You are Merging Both firstFile and Second Data into ThirdFile ");
    fp = fopen("/Users/hemant/ThirdFile.txt", "w");
    first = fopen("/Users/hemant/firstFile.txt", "r");
    second = fopen("/Users/hemant/secondFile.txt", "r");
    fscanf(first,"%[^\n]",String1);
    fscanf(second, "%[^\n]",String2);
    while (String1[i] != '\0') {
           str[j] = String1[i];
           i++;
           j++;
       }
       i = 0;
       while (String2[i] != '\0') {
           str[j] = String2[i];
           i++;
           j++;
       }
       str  [j] = '\0';

    fprintf(fp,"%s",str);

    fclose(fp);
    fclose(first);
    fclose(second);
}

A: There are at least 2 problems in your function:

*

*what is the point of taking log_file as an argument in function write_in_the_log_file? If this argument is a valid stream pointer to the log file, use it directly instead of reopening the log file. Otherwise remove this argument and define log_file as a local variable.

*you do not test if fopen() succeeded at opening the log file. ODIT is a relative path "odit/log_file.txt" so fopen() may fail to open the log file if the current directory is not what you assume. You should test the return value and avoid undefined behavior if log_file is a null pointer.
Without a compilable program that exhibits the offending behavior, it is impossible to ascertain where the double free error originates. It looks like a side effect of code with undefined behavior such as the write_in_the_log_file if log_file is null, but this undefined behavior could also be anywhere in the rest of the program.
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <string.h>

void write_in_the_log_file(int tm_year, int tm_mon, int tm_mday,
                           int tm_hour, int tm_min, int tm_sec)
{
    FILE *log_file = fopen(ODIT, "a");
    if (log_file == NULL) {
        fprintf(stderr, "error opening log file %s: %s\n",
                ODIT, strerror(errno));
    } else {
        fprintf(log_file, "Inventory at %02d.%02d.%02d - %02d:%02d:%02d\n",
                tm_mday, tm_mon, tm_year, tm_hour, tm_min, tm_sec);
        f_print_inventory(log_file);
        fprintf(log_file, "--------------------------------------------------------------\n");
        fclose(log_file);
    }
}


text:
Q: Interpretation of non-convergence in metric spaces 1 .From analysis I know a sequence can either have limit or not. If it has a limit it is said convergent if the limit is finite, divergent if it is $+\infty $ or  $-\infty$. Therefore if someone tells me a sequence is not convergent, I can't help but think that it can either be divergent or its limit does not exist.
Why then in  the context of Cauchy sequences, people seem to interpret "$(x_n)$ does not converge as " it converges but outside the space " instead of the previous interpretation?
I know that "In a metric space $(X,d)$, every convergent sequence is a Cauchy sequence"
So if a sequence converges outside the space, why people/textbooks say "it doesn't converge"  when in fact it does (outside the space, but it does!) and leave out the other more natural possibilities ( divergence or of inexistent limit)? If they always wrote  "it doesn't converge in the space X", then I wouldn't argue.

A: I don't doubt that you have described correctly the concpet of convergent (and divergent) sequence as you have learned it, but you should keep in mind that, by far, the usual definition is: a sequence (of real numbers) converges if it has a limit and it diverges otherwise. So, for instance, the sequence $\bigl((-1)^n\bigr)_{n\in\Bbb N}$ diverges.
Now, if you are working on a metric space $(X,d)$, you can say that a certain sequence $(x_n)_{n\in\Bbb N}$ doesn't converge on $X$, but that's redundant, since, if you are working on $(X,d)$, then $X$ is your whole universe. So, you can simply say that it doesn't converge (or that it diverges).
It turns out that for every metric space $(X,d)$ and for every Cauchy sequence of elements of $X$, there is a larger space $\left(\overline X,D\right)$ such that, on that space, the sequence converges. Note that asserting that $\left(\overline X,D\right)$ is a larger space means two things:

*

*$X\subset\overline X$;

*if $x_1,x_2\in X$, then $D(x_1,x_2)=d(x_1,x_2)$.

In particular, the sequence $(x_n)_{n\in\Bbb N}$ may well converge on $\left(\overline X,D\right)$ and diverge on $(X,d)$. The concept of convergence depends upon the space that you are working with.


text:
Q: Z3 with Craig interpolation (iz3) I'm trying to generate Craig interpolants using the C API but I get incorrect results.
However, when I dump the same problem to a file via Z3_write_interpolation_problem and call iZ3 I get the expected interpolant.
I attach the code to be able to reproduce the same results.
I'm using z3 4.1

#include<stdio.h>
#include<stdlib.h
#include<assert.h>
#include<stdarg.h>
#include<memory.h>
#include<setjmp.h>
#include<iz3.h>

Z3_ast mk_var(Z3_context ctx, const char * name, Z3_sort ty)
{
   Z3_symbol   s  = Z3_mk_string_symbol(ctx, name);
   return Z3_mk_const(ctx, s, ty);
}

Z3_ast mk_int_var(Z3_context ctx, const char * name)
{
   Z3_sort ty = Z3_mk_int_sort(ctx);
   return mk_var(ctx, name, ty);
}

void interpolation_1(){
// Create context
Z3_config  cfg = Z3_mk_config();
Z3_context ctx = Z3_mk_interpolation_context(cfg);

// Build formulae
Z3_ast x0,x1,x2;
x0 = mk_int_var(ctx, "x0");
x1 = mk_int_var(ctx, "x1");
x2 = mk_int_var(ctx, "x2");
Z3_ast zero = Z3_mk_numeral(ctx, "0", Z3_mk_int_sort(ctx));
Z3_ast two  = Z3_mk_numeral(ctx, "2", Z3_mk_int_sort(ctx));
Z3_ast ten  = Z3_mk_numeral(ctx, "10", Z3_mk_int_sort(ctx));

Z3_ast c2_operands[2] = { x0, two };
Z3_ast c1 = Z3_mk_eq(ctx, x0, zero);
Z3_ast c2 = Z3_mk_eq(ctx, x1, Z3_mk_add(ctx, 2, c2_operands));
Z3_ast c3_operands[2] = { x1, two };
Z3_ast c3 = Z3_mk_eq(ctx, x2, Z3_mk_add(ctx, 2, c3_operands));
Z3_ast c4 = Z3_mk_gt(ctx, x2, ten);

Z3_ast A_operands[3] = { c1, c2, c3};
Z3_ast AB[2] = { Z3_mk_and(ctx,3, A_operands), c4 };

// Generate interpolant
Z3_push(ctx);
Z3_ast interps[1];
Z3_lbool status = Z3_interpolate(ctx, 2, AB, NULL, NULL, interps);
assert(status ==  Z3_L_FALSE && "A and B should be unsat");
printf("Interpolant: %s\n",Z3_ast_to_string(ctx, interps[0]));

// To dump the interpolation into a SMT file
// execute "iz3 tmp.smt" to compare
Z3_write_interpolation_problem(ctx, 2, AB, NULL, "tmp.smt");

Z3_pop(ctx,1);
}

int main() {
  interpolation_1();
}

I generate an executable using the command:

g++ -fopenmp -o interpolation interpolation.c
  -I/home/jorge/Systems/z3/include -I/home/jorge/Systems/z3/iz3/include  -L/home/jorge/Systems/z3/lib -L/home/jorge/Systems/z3/iz3/lib -L/home/jorge/Systems/libfoci-1.1 -lz3 -liz3 -lfoci

Note that the constraints are basically:

A = (x=0 and x1 = x0+2 and x2 = x1 + 2),
and B = (x2 > 10)

which are clearly unsat. Moreover, it's also easy to see that the only common variable is x2. Thus, any valid interpolant can only include x2.
If I run the executable ./interpolation I obtain the nonsense interpolant:
(and (>= (+ x0 (* -1 x1)) -2) (>= (+ x1 (* -1 x3)) -2) (<= x0 0))

However, If I run "iz3 tmp.smt" (where tmp.smt is the file generated using Z3_write_interpolation_problem) I obtain a valid interpolant:

unsat interpolant: (<= x2 10)

Is this a bug? or am I missing some important precondition when I call Z3_interpolate?
P.S. I could not find any example using iZ3 with the C API.
Cheers,
Jorge

A: iZ3 was not built against version 4+ and the enumeration types and other features from the
headers from the different versions have changed. You cannot yet use iZ3 against the latest
versions of Z3. We hope to address this soon, most likely by placing the iZ3 stack along with
the rest of Z3 sources, but in the meanwhile use the previous release where iZ3 was built for.


text:
Q: will_paginate and facebook/facebooker I'm using will_paginate in a facebook application and when i click on
the next button or a page number i get the url below. This is fine if
everyone was using safari, but it breaks on ie and ff. That and people
can't copy and paste the url to others. Anyone have any ideas how to
fix this.
http://apps.facebook.com/application/users/4785/votes.fbml?_method=GE...  URL TOO BIG

A: Already discussed here. And solved.


text:
Q: How to use LINQ Like function with group of characters? How to use LINQ Like function with group of characters?
EF.Functions.Like("abc", "[a-c]bc"); //false
EF.Functions.Like("123", "[0-9][0-9][0-9]"); //false

The above functions appear to not work. What am I missing?