Q: Miniforge Conda "PackagesNotFoundError" on ARM processor for PyTorch I am unable to install any packages with miniforge 3 (conda 4.11.0).
I am attempting this on a Jetson Nano Developer Kit running Jetpack. Initially it had conda installed but it seems to have gone missing, so I decided to reinstall conda. It looks like the base version of anaconda/miniconda is having issues running on ARM processors, and so I downloaded miniforge which apparently is working.
I have set up an environment successfully, but attempting to download pytorch gives the following error:
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from current channels:

  - pytorch

Current channels:

  - https://conda.anaconda.org/pytorch/linux-aarch64
  - https://conda.anaconda.org/pytorch/noarch
  - https://conda.anaconda.org/abinit/linux-aarch64
  - https://conda.anaconda.org/abinit/noarch
  - https://conda.anaconda.org/matsci/linux-aarch64
  - https://conda.anaconda.org/matsci/noarch
  - https://conda.anaconda.org/conda-forge/linux-aarch64
  - https://conda.anaconda.org/conda-forge/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.

This is for Python 3.7.12. It seems this issue persists no matter what version of pytorch I try to install.
I am however able to install some other packages, as I was able to install beautifulsoup4.

A: There is no linux-aarch64 version of pytorch on the default conda channel, see here
This is of course package specific. E.g. there is a linux-aarch64 version of beautifulsoup4 which is why you wre able to install it without an issue.
You can try to install from a different channel that claims to provide a pytorch for aarch64, e.g.
conda install -c kumatea pytorch


Q: Styling a Div Class within Div ID I have a page that has the following div element:

Which of the following should I use to style the class?
#name .class_name
name .class_name
#name class_name

A: Just #name would be enough to apply the style only to that specific element:
#name {
   // your styles here
}

If you want to apply the style to all the elements using the class_name class, then you can use:
.class_name {
   // your styles here
}

A: #name .class_name will apply to the children elements of your div with the .class_name class.
There must not be any spaces between.
You should use: #name.class_name because it is the correct syntax.
But, when working with identifiers, it should be enough to use it alone.
#name {
  // some properties
}

But let's say you have a unique block, which inherits some generic styles, then you could use #idenifier.class to mix styles.
#comments {
    width: 453px;
}

#comments.links
{
   border: 0 none;
}

A: If I got your question right you use
#name .class_name

as in
#name .class_name {
    color:#000;
}

But actually you don't need to do that.
If #name and .class_name are oly used in that div you can just drop the .class_name. Otherwise, if you use multiple stuff with .class_name that don't share the same properties as div #name, you should separate them.
.class_name {
    color:#000;
}
#name {
    width:600px;
}

A: ID's should be unique, so there isn't much point in styling both the id of the div and the class_name.
Just using the ID of the div is fine if that's your goal.
#name
{
   //styles
}

If you want to style every div that has that class name, then just use
.class_name
{
   //styles
}

A: You can read about CSS selectors here:
http://reference.sitepoint.com/css/selectorref
In the CSS you can reference it by class:
.class_name { color: green; }

or by id using #id
#name { color: green; }

or by element type
div { color: green; }

//or by combinations of the above
div.class_name { color: green; }
div#name { color: green; }

A: If you already have #name and .class_name styled, but for some reason you want to style

(that is, a specific style to the element with an id of "name" AND a class of "class_name"), you can use
#name.class_name {
/* note the absence of space between the id and class selector */
    ...
}

Bear in mind that this selector is not supported by Internet Explorer 6.


Q: OrderBy List by another collection Have some problem.
Need to sort the list by another collection:
List<Books> b = new List<Books>();

Class Books:
public partial class Books
{
    public Books()
    {
        this.BookAuthors = new HashSet<BookAuthors>();
    }

    public int BookID { get; set; }
    public string BookName { get; set; }

    public virtual ICollection<BookAuthors> BookAuthors { get; set; }
}

Class BookAuthors:
public partial class BookAuthors
{
    public int Id { get; set; }
    public int AuthorID { get; set; }
    public int BookID { get; set; }

    public virtual Books Books { get; set; }
    public virtual Authors Authors { get; set; }
}

Class Authors:
public partial class Authors
{
    public Authors()
    {
        this.BookAuthors = new HashSet<BookAuthors>();
    }

    public int AuthorID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<BookAuthors> BookAuthors { get; set; }
}

How i can sort b by authors last name?

A: Something like this, though with mutiple authors it remains a question which author you order by:
var sorted =
    from book in b
    let firstAuthor = book.BookAuthors.First()
    let lastName = firstAuthor.LastName
    order book by lastName
    select book

Alternatively you could apply some logic (if you had it)...
var sorted =
    from book in b
    let author = book.BookAuthors.FirstOrDefault(a=>a.Primary) ??
        book.BookAuthors.FirstOrDefault(a=>a.Editor) ??
        book.BookAuthors.First()
    let lastName = author.LastName
    order book by lastName
    select book


Q: unreachable statment error call an activity I'm developping an android application so I'm trying to call  activity1 "myown" in another activity2 "MainActivity" but I just keep getting an error "Unreachable statement" over this line of code
Intent launchActivity2 = new Intent(MainActivity.this, myown.class);
MainActivity.this.startActivity(launchActivity2);

Could you explain to me what may went wrong an tell me how to fix it?
i would be really grateful


Q: SQL to LINQ semi-complex query projecting to ViewModel I know sql well enough to get by professionally, but i'm still new to linq concepts and even less familiar with lambda syntax. below is my sql query... I successfully join 2 tables on matching id's and filter my results by a certain status and select only the newest entry based on date.
select ma.* , mnh.note
from MerchApps ma
join MerchNoteHist mnh on mnh.appid = ma.id
where ma.[Status] != 6 and mnh.CreatedDate = (select max(CreatedDate) from
MerchantNoteHistories where appid = ma.Id)

The ultimate goal is to project this query to my viewmodel.
public class ViewModelListItem
{
    public int Id { get; set; }
    public DateTime CreatedDate { get; set; }
    public ApplicationStatus Status { get; set; }
    public string RecentNote { get; set; }
   ... //other things that aren't related to the question
}

Issue is: find the correct max usage.
My best attempt at LINQ lambda syntax, what I've been able to piece together after doing research:
_db.MerchApps
            .Join(_db.MerchNoteHist,
                ma => ma.Id,
                note => note.AppId,
                (ma, note) => new { MA = ma, Note = note })
                .Include(x => x.MA.User)
                .Where(x => x.MA.Status != ApplicationStatus.Approved)
                .Include(x => x.Note.Note)
                .Where(x => x.Note.CreatedDate == Max(x.Note.CreatedDate) //<--Issue is here, because I can't find the correct max usage.
            .ProjectTo<ViewModelListItem>(_mapperConfig)
            .OrderBy(x => x.Status).ThenBy(x => x.CreatedDate).ToListAsync();

The final step is to lay it all out in a view from a foreach loop that uses the above viewmodel.
After research and trial-and-error and working through lunch to try to figure this out... I'm a solid 7 hours into this and at my wits end. Any help at all would be appreciated.

A: You should use a GroupJoin instead of Join, this will yield a set of MerchNoteHist (I'm assuming this is the same table as MerchantNoteHistories here) that match the AppId.
Then, you can use an aggregate (Max) in the resultSelector of the function.
Here's roughly what your code should look like:
_db.MerchApps
        .Where(ma => ma.User.Status != ApplicationStatus.Approved)
        .GroupJoin(
            _db.MerchNoteHist,
            ma => ma.Id,
            noteList => note.AppId,
            (ma, noteList) => new
            {
               MA = ma,
               Note = noteList.OrderByDescending(n=>n.CreatedDate).First()
            })
            //rest of your logic here

A: Alternatively you could put this in as the second Where clause:
.Where(x => x.Note.CreatedDate== _db.MerchNoteHist
    .Where(y => y.AppId == x.Note.AppId).OrderByDescending(y => y.CreatedDate)
        .First().CreatedDate)


Q: AWS: Permissions for exporting logs from Cloudwatch to Amazon S3 I am trying to export logs from one of my CloudWatch log groups into Amazon S3, using AWS console.
I followed the guide from AWS documentation but with little success. My organization does not allow me to manage IAM roles/policies, however I was able to find out that my role is allowed all log-related operations (logs:* on all resources within the account).
Currently, I am stuck on the following error message:

Could not create export task. PutObject call on the given bucket failed. Please check if CloudWatch Logs has been granted permission to perform this operation.

My bucket policy is set in the following way:
{
    [
        ...
        {
            "Sid": "Cloudwatch Log Export 1",
            "Effect": "Allow",
            "Principal": {
                "Service": "logs.eu-central-1.amazonaws.com"
            },
            "Action": "s3:GetBucketAcl",
            "Resource": "arn:aws:s3:::my-bucket"
        },
        {
            "Sid": "Cloudwatch Log Export 2",
            "Effect": "Allow",
            "Principal": {
                "Service": "logs.eu-central-1.amazonaws.com"
            },
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::my-bucket/*"
        }
    ]
}

Prior to editing bucket policy, my error message had been

Could not create export task. GetBucketAcl call on the given bucket failed. Please check if CloudWatch Logs has been granted permission to perform this operation.

but editing the bucket policy fixed that. I would expect allowing PutObject to do the same, but this has not been the case.
Thank you for help.

A: Please check this guide Export log data to Amazon S3 using the AWS CLI

Policy's looks like the document that you share but slight different.
Assuming that you are doing this in same account and same region, please check that you are placing the right region ( in this example is us-east-2)
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "s3:GetBucketAcl",
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::my-exported-logs",
            "Principal": { "Service": "logs.us-east-2.amazonaws.com" }
        },
        {
            "Action": "s3:PutObject" ,
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::my-exported-logs/*",
            "Condition": { "StringEquals": { "s3:x-amz-acl": "bucket-owner-full-control" } },
            "Principal": { "Service": "logs.us-east-2.amazonaws.com" }
        }
    ]
}

I think that bucket owner full control is not the problem here, the only chance is the region.
Anyway, take a look to the other two examples in case that you were in different accounts/ using role instead user.
This solved my issue, that was the same that you mention.

A: Ensure when exporting the data you configure the following aptly
S3 bucket prefix - optional This would be the object name you want to use to store the logs.
While creating the policy for PutBucket, you must ensure the object/prefix is captured adequately. See the diff for the PutBucket statement Resource:

 {
   "Version": "2012-10-17",
   "Statement": [
     {
         "Action": "s3:GetBucketAcl",
         "Effect": "Allow",
         "Resource": "arn:aws:s3:::my-exported-logs",
         "Principal": { "Service": "logs.us-east-2.amazonaws.com" }
     },
     {
         "Action": "s3:PutObject" ,
         "Effect": "Allow",
-        "Resource": "arn:aws:s3:::my-exported-logs/*",
+        "Resource": "arn:aws:s3:::my-exported-logs/**_where_i_want_to_store_my_logs_***",
         "Condition": { "StringEquals": { "s3:x-amz-acl": "bucket-owner-full-control" } },
         "Principal": { "Service": "logs.us-east-2.amazonaws.com" }
     }
   ]
 }

A: One thing to check is your encryption settings. According to https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/S3ExportTasksConsole.html

Exporting log data to Amazon S3 buckets that are encrypted by AWS KMS is not supported.

Amazon S3-managed keys (SSE-S3) bucket encryption might solve your problem. If you use SSE-KMS, Cloudwatch can't access your encryption key in order to properly encrypt the objects as they are put into the bucket.

A: I had the same situation and what worked for me is to add the bucket name itself as a resource in the Allow PutObject Sid, like:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowLogsExportGetBucketAcl",
            "Effect": "Allow",
            "Principal": {
                "Service": "logs.eu-west-1.amazonaws.com"
            },
            "Action": "s3:GetBucketAcl",
            "Resource": "arn:aws:s3:::my-bucket"
        },
        {
            "Sid": "AllowLogsExportPutObject",
            "Effect": "Allow",
            "Principal": {
                "Service": "logs.eu-west-1.amazonaws.com"
            },
            "Action": "s3:PutObject",
            "Resource": [
                "my-bucket",
                "my-bucket/*"
            ]
        }
    ]
}

I also believe that all the other answers are relevant, especially using the time in milliseconds.


Q: C# Expression tree for string interpolation I have a program that reads a json file with some property names of a certain class. The values of the configured property names should compose up a key.
Lets take an example:
Class:
class SomeClass
{
    public string PropertyOne { get; set; }
    public string PropertyTwo { get; set; }
    public string PropertyThree { get; set; }
    public string PropertyFour { get; set; }
}

var someClass = new SomeClass
            {
                PropertyOne = "Value1",
                PropertyTwo = "Value2",
                PropertyThree = "Value3",
                PropertyFour = "Value4",
            };

Configuration file:
{
   "Properties": ["PropertyOne", "PropertyTwo"]
}

If I knew the properties at compile time I would have create a lambda like:
Func<SomeClass, string> keyFactory = x => $"{x.PropertyOne}|{x.PropertoTwo}"

Is there a way to compile such a lambda using expressions? Or any other suggestions maybe?

A: In Expression Tree, string interpolation is converted to string.Format. Analogue of your sample will be:
Func<SomeClass, string> keyFactory =
   x => string.Format("{0}|{1}", x.PropertyOne, x.PropertoTwo);

The following function created such delegate dynamically:
private static MethodInfo _fromatMethodInfo = typeof(string).GetMethod(nameof(string.Format), new Type[] { typeof(string), typeof(object[]) });

public static Func<T, string> GenerateKeyFactory<T>(IEnumerable<string> propertyNames)
{
    var entityParam = Expression.Parameter(typeof(T), "e");

    var args = propertyNames.Select(p => (Expression)Expression.PropertyOrField(entityParam, p))
            .ToList();

    var formatStr = string.Join('|', args.Select((_, idx) => $"{{{idx}}}"));

    var argsParam = Expression.NewArrayInit(typeof(object), args);

    var body = Expression.Call(_fromatMethodInfo, Expression.Constant(formatStr), argsParam);
    var lambda = Expression.Lambda<Func<T, string>>(body, entityParam);
    var compiled = lambda.Compile();

    return compiled;
}

Usage:
var keyFactory = GenerateKeyFactory<SomeClass>(new[] { "PropertyOne", "PropertyTwo", "PropertyThree" });


Q: Sending Multipart data using Retrofit Interface
public interface iUpload{
        @Multipart
        @POST("/uploadmultiplepropimages/")
         SamplePojoClass getUploadData(
            @Part("prop_id") RequestBody prop_id,
            @Part("type") RequestBody type,
            @Part("prop_photos") TypedFile prop_photos
        );
}

I'm sending like this.  I cant send request body text like this.
@Override

    protected Void doInBackground(String... params) {

        String s = params[0];
        File photoFile = new File(s);
        System.out.println("file path:"+photoFile);
        TypedFile photoTypedFile = new TypedFile("image/png", photoFile);

        RequestBody idd = RequestBody.create(MediaType.parse("text/plain"), "");
        RequestBody type = RequestBody.create(MediaType.parse("text/plain"), "single");

        try {
            //uploadImageResponse = RequestResponse.getUploadData(AccountUtils.getProfileId(),photoTypedFile);
            uploadImageResponse = RequestResponse.getUploadData(idd,type,photoTypedFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }`

It says error:

Cannot access ByteString class file.

A: I hope you have added okio dependency in your gradle file. This will resolve Cannot access ByteString class file error.
compile 'com.squareup.okio:okio:1.13.0'

Then Edit your iUpload interface file like:
public interface iUpload{
        @Multipart
        @POST("/uploadmultiplepropimages/")
        SamplePojoClass getUploadData(
                @Part MultipartBody.Part file
                @Part MultipartBody.Part prop_id,
                @Part MultipartBody.Part type
        );
    }

Then write MultipartBody.Part like this:
RequestBody lRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), pFile);
     MultipartBody.Part lFile = MultipartBody.Part.createFormData("file", pFile.getName(), lRequestBody);
     MultipartBody.Part id = MultipartBody.Part.createFormData("prop_id", "WRITE_ID_HERE");
     MultipartBody.Part type = MultipartBody.Part.createFormData("type", "WRITE TYPE HERE");

and finally pass these parameters to your api like this:
uploadImageResponse = RequestResponse.getUploadData(lFile,id,type);

I hope it will resolve your problem.
Note: Here pFile is instance of File. To get file from dicrectory you can write code like:
File pFile = new File("PATH_OF_FILE");

A: I have done Multipart upload in okhttp. I hope this will help.
        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
        multipartBuilder.setType(MultipartBody.FORM);
        multipartBuilder.addFormDataPart("prop_photos", photoFile, RequestBody.create(MEDIA_TYPE_PNG, file));

            multipartBuilder
                         .addFormDataPart("type", type)
                        .addFormDataPart("prop_id", prop_id);

    RequestBody requestBody = multipartBuilder.build();
    Request request1 = new Request.Builder().url(urlString).post(requestBody).build();

A: Use the following fuction for your problem
public static RegisterResponse Uploadimage(String id, String photo,String proof) {

        File file1 = null, file2 = null;
        try {
            if (photo.trim() != null && !photo.trim().equals("")) {
                file1 = new File(photo);
            }
            if (proof.trim() != null && !proof.trim().equals("")) {
                file2 = new File(proof);
            }

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(WEB_SERVICE + "protoupload.php?");

            MultipartEntity reqEntity = new MultipartEntity();

            // reqEntity.addPart("studentid", new StringBody(
            // Global.profileDetail.id));
            reqEntity.addPart("id", new StringBody(id));

            if (file1 == null) {
                reqEntity.addPart("photo", new StringBody(""));
            } else {
                FileBody bin1 = new FileBody(file1);
                reqEntity.addPart("photo", bin1);
            }
            if (file2 == null) {
                reqEntity.addPart("proof", new StringBody(""));
            } else {
                FileBody bin2 = new FileBody(file2);
                reqEntity.addPart("proof", bin2);
            }
            post.setEntity(reqEntity);
            HttpResponse response = client.execute(post);
            HttpEntity resEntity = response.getEntity();
            String inputStreamString = EntityUtils.toString(resEntity);

            if (inputStreamString.contains("result")) {

                return new Gson().fromJson(inputStreamString,
                        RegisterResponse.class);
            }

        } catch (Exception ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        }

        return new RegisterResponse();
    }


Q: Unimplemented Javascript primitive caml_pure_js_expr I want to write and compile cubes.ml such that 1) it wraps an OCaml function to make a JS function that can be called in web; 2) the OCaml function and the bytecode can still be tested in a command line under Linux.
cubes.ml is as follows:
let () =
  let oneArgument (a: int) = a + 100 in
  Js.Unsafe.global##.jsOneArgument := Js.wrap_callback oneArgument;
  print_string "hello\n";
  exit 0

The following 2 commands generate a bytecode T, and translates T to cubes.js:
ocamlfind ocamlc -package js_of_ocaml.ppx -linkpkg cubes.ml -o T

js_of_ocaml T -o cubes.js

I have tested that the function jsOneArgument of cubes.js can well be called by other JS or HTML files. So my 1) goal is satisfied.
However, my 2) goal cannot be satisfied: ./T returns an error:
:testweb $ ./T
Unimplemented Javascript primitive caml_pure_js_expr!

Although node cubes.js returns hello, I do need to be able to test ./T directly, because when there is an error, it would show well the error position, whereas the information shown by node cubes.js is not readable...
So does anyone know how to solve that?
PS: node --version gives v6.1.0; npm --version gives 3.8.6; ocaml -version gives The OCaml toplevel, version 4.02.3.
js_of_ocaml --version gives 2.7.

A: I don't see anyway to avoid the use of node but you can improve the information returned by it by

*

*compiling the OCaml with the debug info (add -g option to ocamlc)

*add the options --debuginfo --sourcemap --pretty to the invocation of js_of_ocaml
In your example, you'd have to do
ocamlfind ocamlc -g -package js_of_ocaml.ppx -linkpkg cubes.ml -o T
js_of_ocaml --debuginfo --sourcemap --pretty T -o cubes.js


Q: High accuracy but bad predictions on Keras Tensorflow I have a 9 class dataset with 7000 images, I use MobilenetV2 for training my set and ImageGenerator, resulting in 82% percent val accuracy. But when i predict my test images, it always predicts a false class. I have no idea what is wrong with it.Here is my code;
My ImageGenerator:
image_gen = ImageDataGenerator(rotation_range = 20,
                               width_shift_range=0.12,
                               height_shift_range=0.12,
                               shear_range=0.1,
                               zoom_range = 0.06,
                               horizontal_flip=True,
                               fill_mode='nearest',
                               rescale=1./255)

My model:
Model = Sequential()

Model.add(Conv2D(filters=32,kernel_size=(3,3),input_shape=image_shape,activation='relu'))
Model.add(MaxPool2D(pool_size=(2,2)))

Model.add(Conv2D(filters=64,kernel_size=(3,3),input_shape=image_shape,activation='relu'))
Model.add(MaxPool2D(pool_size=(2,2)))

Model.add(Conv2D(filters=64,kernel_size=(3,3),input_shape=image_shape,activation='relu'))
Model.add(MaxPool2D(pool_size=(2,2)))

Model.add(Conv2D(filters=64,kernel_size=(3,3),input_shape=image_shape,activation='relu'))
Model.add(MaxPool2D(pool_size=(2,2)))

Model.add(Flatten())

Model.add(Dense(256,activation='relu'))

Model.add(Dense(9,activation='softmax'))

MobilenetV2:
height=224
width=224
img_shape=(height, width, 3)
dropout=.3
lr=.001
class_count=9 # number of classes
img_shape=(height, width, 3)
base_model=tf.keras.applications.MobileNetV2( include_top=False, input_shape=img_shape, pooling='max', weights='imagenet')
x=base_model.output
x=keras.layers.BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001 )(x)
x = Dense(512, kernel_regularizer = regularizers.l2(l = 0.016),activity_regularizer=regularizers.l1(0.006),
                bias_regularizer=regularizers.l1(0.006) ,activation='relu', kernel_initializer= tf.keras.initializers.GlorotUniform(seed=123))(x)
x=Dropout(rate=dropout, seed=123)(x)
output=Dense(class_count, activation='softmax',kernel_initializer=tf.keras.initializers.GlorotUniform(seed=123))(x)
Model = keras.models.Model(inputs=base_model.input, outputs=output)
Model.compile( loss='categorical_crossentropy', metrics=['accuracy'],optimizer='Adamax')

My Rlronp:
rlronp=tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=1, verbose=1, mode='auto', min_delta=0.0001, cooldown=0, min_lr=0)

My train_image_gen:
train_image_gen = image_gen.flow_from_directory(train_path,
                                                target_size=image_shape[:2],
                                                color_mode='rgb',
                                                batch_size=batch_size,
                                                class_mode='categorical')

My test_image_gen:
test_image_gen = image_gen.flow_from_directory(test_path,
                                                target_size=image_shape[:2],
                                                color_mode='rgb',
                                                batch_size=batch_size,
                                            class_mode='categorical',shuffle=False)

My earlystop:
early_stop = EarlyStopping(monitor='val_loss',patience=4)

My Model fit:
results = Model.fit(train_image_gen,epochs=20,
                              validation_data=test_image_gen,callbacks=[rlronp,early_stop],class_weight=class_weight
                              )

Training and accuracy:
Epoch 20/20 200/200 [==============================] - 529s 3s/step -
 loss: 0.3995 - accuracy: 0.9925 - val_loss: 0.8637 - val_accuracy: 0.8258

My problem is when i predict an image from test set, it predicts the false class, 90% of time.
For example here, it has to be 3rd class, but max is on 2nd class.
array([[0.08064549, 0.04599327, 0.27055973, 0.05219262, 0.055945  ,
        0.25723988, 0.07608379, 0.10404343, 0.05729679]], dtype=float32)

I tried collecting my own dataset with 156 class and 2.5k images, but it was even worse.
My loss on 20 epochs:

A: accuracy: 0.9925; val_accuracy: 0.8258
Clearly the model is overfitted,

*

*Try using regularization techniques such as L2,L1 or Dropout, they will work.

*Try to Collect More data(Or use data augumentation)

*Or search for other Neural Network Architectures

*The best method is plot val_loss v/s loss

r = model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=15)

import matplotlib.pyplot as plt
plt.plot(r.history['loss'], label='loss')
plt.plot(r.history['val_loss'], label='val_loss')
plt.legend()

and check the point where loss and val_loss meet each other and then at the point of intersection see the number of epochs (say x) and train the model for x epochs only.
Hope you will find this useful.

A: Model is overfitted...use dropout layer.. I think it will help
Model.add(Dropout(0.2))


Q: Replacing Golang standard package and calling the original within Assume that there is a special hardware that can make
certain standard library functionality faster.
Hardware might be present or not.
I can write a package that would utilize this hardware with the same
function signatures as in the standard one, but it will force all the applications and other packages to decide which package to import based on the availability of the hardware on the specific target. At build time and with code modifications in all the applications and packages.
Ideally, I would prefer to make the decision of which package to use at runtime and without requiring applications to change their imports.
The package would check for the availability of the hardware and would either use it or execute standard functionality instead.
Is there any way to achieve it?
Any other ways to "intercept" the calls to the standard package functions?

A: It sounds like you're talking about a library that will be used by other applications. You can't (thankfully!) modify the standard library this way - otherwise just importing a package could have incredibly broad and potentially disastrous side-effects. If you want to apply some special hardware-specific optimizations to the standard library, for use by other people in a broad range of projects, your best bet is to make your changes to the standard library and submit a patch.


Q: Prologue -Webframework - How to set thread-local variables for logging when compiling with `--threads:on` flag? I am writing a web-application in nim, using the web-framework prologue and the ORM norm. I've found that the log-messages of prologue and norm that normally appear in the terminal when starting up the application disappear, when you compile with the --threads:on flag.
That is because log-message-handlers and log levels are set as thread-local variables, so when a new thread is created the log-level must be set for that thread again etc.
However, prologue is the one instantiating the threads, so how do I properly set this up for every thread that prologue creates?

A: I found the answer thanks to the help of prologue's creator: xflywind.
The answer is prologue-events.
When prologue creates a thread, it triggers a list of procs, so called events, that are registered on startup. All you need to do is define an event that sets the log-level and provides a handler.
proc setLoggingLevel() =
  addHandler(newConsoleLogger())
  logging.setLogFilter(lvlDebug)

let
  event = initEvent(setLoggingLevel)

var
  app = newApp(settings = settings, startup = @[event])


Q: Automation Script vs Export Template I'm puzzled with the "automation script" vs "export template" in the Resource manager blade. So many sources are mixing those two things, my understanding is that "automation script" was introduced later, but I'm might be wrong.
When I switched the language (English to German) it's saying actually "automation script", so I'm not sure if that's really an UI issue, and why so many different sources have sometimes "automation script" (which I'm getting only in German) or sometimes "export templates"?
https://pasteboard.co/I75s2jJ.png

A: those are 2 different names for the same thing. its actually an api call you can perform without the portal as well. just an inconsistency within UI.
Api call: https://learn.microsoft.com/en-us/rest/api/resources/resourcegroups/exporttemplate


Q: Insert blank rows based on column condition I have to have atlest 4 rows for each manager (mgr col) and so that HR can assign task to each of them. HR will add values in new col, they can assign task up to 4 based. I am thinking to create a macro that can check minimum 4 lines for each manager if less than 4 add it and if more then no need to add.
For example:
Dep Mgr     Task
1   jerry   cheese
1   jerry   bread
2   tom     milk

Expected output:
Dep Mgr     Task     HRtask
1   jerry   cheese   ---
1   jerry   bread    ---
1   jerry    ---     ---
1   jerry    ---     ---
2   tom     milk     ---
2   tom      ---     ---
2   tom      ---     ---
2   tom      ---     ---

--- is blank here.
what I found on internet
Sub Insert4RowsWithCondition()
'    here starting with A3 cell but need to set on unique value in that mgr col automatically
Range("A3").Select
Do Until ActiveCell.Value =""
Selection.EntireRow.Insert
Selection.EntireRow.Insert
ActiveCell.Offset(3,0).Select
Loop

error
It is adding 2 new blank rows after each line which is not useful in my case.

A: Try this... A bit lengthy though... I added the rows depending on Dep count instead of Mgr name, as there can be more than one mgr with same name... So Assuming Dep is some sort of Mgr's ID...
Sub Macro1()

' Get count of Dep
Columns("A:B").Select
Selection.Copy
Range("F1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveSheet.Range("$F:$G").RemoveDuplicates Columns:=Array(1, 2), Header _
    :=xlYes
Range("H2").Select
ActiveCell.FormulaR1C1 = "=COUNTIFS(C1,RC[-2])"
Range("H2").Select
Selection.Copy
lRow = Cells(Rows.Count, 6).End(xlUp).Row
Range("H2:H" & lRow).Select
ActiveSheet.Paste
Application.CutCopyMode = False

' Number of rows to add
lRow = Cells(Rows.Count, 6).End(xlUp).Row
For i = 2 To lRow
    num = Cells(i, 8).Value
    If num < 4 Then
        Range("F" & i & ":" & "G" & i).Copy
        Range("A1").Select
        Selection.End(xlDown).Select
        For j = 1 To 4 - num
            ActiveCell.Offset(1, 0).Select
            ActiveSheet.Paste
        Next
    End If
Next

' Sorting Data
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add2 Key:=Range("A:A") _
    , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
    .SetRange Range("A:D")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

Columns("F:H").ClearContents
Range("A1").Select

End Sub

Hope this Helps...


Q: Flatpickr - Limit the amount of dates that can be selected I am using 'flatpickr' as a datetime picker on my app. This date picker allows for multiple dates to be selected but after reading the docs I can't find any way to limit the maximum amount of selected dates.
Jquery:
$('#gig_date_multi').flatpickr({
  "mode": "multiple",
  "locale": "<%= I18n.locale %>",
  minDate: new Date(),
  enableTime: true,
  time_24hr: true,
  minuteIncrement: 15,

    onChange: function(selectedDates, dateStr, instance) {

      var array = selectedDates;
      if (array.length >= 3) {
        console.log("YOU HAVE REACHED YOUR LIMIT")
      } else {
        console.log("YOU CAN STILL SELECT MORE DATES")
      }

      var newHTML = [];
      $.each(array, function(index, value) {
        var formatted = moment(value).format("HH:mm - dddd Do MMMM YYYY");
        newHTML.push('<span>' + formatted + '</span>');
      });

      $(".multi-dates").html(newHTML.join(""));

    }
});

Here when 3 dates are selected the console outputs "YOU HAVE REACHED YOUR LIMIT" and I was thinking maybe I could disable all dates (apart from previously selected ones) when this occurs.
Flatpickr has a disable and enable function but I am unsure how I can integrate this into the code... I am a jquery beginner.
The docs show these two methods;
{
    "disable": [
        function(date) {
            // return true to disable
            return (date.getDay() === 5 || date.getDay() === 6);

        }
    ],
    "locale": {
        "firstDayOfWeek": 1 // start week on Monday
    }
}

and
{
    enable: ["2017-03-30", "2017-05-21", "2017-06-08", new Date(2017, 8, 9) ]
}

A: You can use:

set(option, value): Sets a config option optionto value, redrawing the calendar and updating the current view, if necessary

In order to disable all dates except the 3 selected you can write:
instance.set('enable', selectedDates);

and, in order to reset you can:
instance.set('enable', []);

A different approach can be based on Enabling dates by a function:
instance.set('enable', [function(date) {
    if (selectedDates.length >= 3) {
        var currDateStr = FlatpickrInstance.prototype.formatDate(date, "d/m/Y")
        var x = selectedDatesStr.indexOf(currDateStr);
        return x != -1;
    } else {
        return true;
    }
}]);

The snippet:

$('#gig_date_multi').flatpickr({
    "mode": "multiple",
    "locale": 'en',
    minDate: new Date(),
    enableTime: true,
    time_24hr: true,
    minuteIncrement: 15,
    onChange: function(selectedDates, dateStr, instance) {
        var selectedDatesStr = selectedDates.reduce(function(acc, ele) {
            var str = instance.formatDate(ele, "d/m/Y");
            acc = (acc == '') ? str : acc + ';' + str;
            return acc;
        }, '');
        instance.set('enable', [function(date) {
            if (selectedDates.length >= 3) {
                var currDateStr = instance.formatDate(date, "d/m/Y")
                var x = selectedDatesStr.indexOf(currDateStr);
                return x != -1;
            } else {
                return true;
            }
        }]);
    }
});
input[type="text"] {
    width: 100%;
    box-sizing: border-box;
    -webkit-box-sizing:border-box;
    -moz-box-sizing: border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/flatpickr/dist/flatpickr.min.css">
<script src="https://unpkg.com/flatpickr"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

<input type="text" id="gig_date_multi">

A: On a side note, if anyone wants to disable past date as well as time selection in Flatpickr, use Date().getTime() like this:
 $("input.picker-datetime").flatpickr({
        enableTime: true,
        dateFormat: "Y-m-d H:i",
        time_24hr: true,
        minDate: new Date().getTime()
    });


Q: Enable squid proxy blocking https I'm trying to block some sites like gmail and outlook from my squid proxy server.
My squid.conf is:
acl blacklist dstdomain "/etc/squid/blacklist.acl"
http_access deny blacklist

And blacklist.acl is:
.atlassian.net
.accounts.google.com
.mail.google.com
.gmail.com
.gmail.google.com

This only seems to work for sites using http (ie. they successfully get blocked)
https sites still are able to get through ?
I'm running squid 4.10 on Ubuntu-20.04
Does anyone know how to achieve this ?
Thanks in advance!

A: this is probably because you haven't enabled SSL bumping, i.e. your http_port directive is set to the default http_port 3128.
I've written about both Squid's SSL setup and blocking websites

*

*configure squid with ICAP & SSL

*block and allow websites with squid

A: When the site is encrypted squid can validate only the Domain but not the entire URL path or keywords in the URL. To block https sites using urlpath_regex we need to setup Squid proxy using SSLbump. It is tricky and a long process , need to carefully configure the SSL bump settings by generating certificates.. but it is possible . I have succeeded in blocking the websites using urlpathregex over https sites...
For more detailed explanation:
Squid.conf file should have the below to achieve block websites using Keywords or Path ie..urlpath_regex
http_port 3128 ssl-bump cert=/usr/local/squid/certificate.pem generate-host-certificates=on dynamic_cert_mem_cache_size=4MB

acl BlockedKeywords url_regex -i "/etc/squid/.."

acl BlockedURLpath urlpath_regex -i "/etc/squid/..."

acl BlockedFIles urlpath_regex -i "/etc/squid3/...."

http_access deny BlockedKeywords

http_access deny BlockedFIles

http_access deny BlockedURLpath


Q: Does ArrayList.clear() also delete all contained objecs? Assuming I have an ArrayList of ArrayLists created in this manner:
  ArrayList< ArrayList<String> > listOfListsOfStrings =
                              new ArrayList< ArrayList<String> >();

If I call:
 listOfListsOfStrings.clear();

Will an attempt to later access any of the Strings inside listOfListsOfStrings always result in a java.lang.NullPointerException?

A: No, just the references will be cleared. If no reference to an object exists anymore it might be garbage collected, but you'd get no NPE, since you then have no way to get a new reference to that object anyway.

A: No, it will not delete objects in the ArrayList if you still have external references to them.  ArrayList.clear() does nothing to the objects being referred to unless they are orphaned, in which case you won't be referring to them later on.


Q: Elixir program, what does this program do? this is one of the practice questions from the upcoming exam, and I have no idea what should be written for init() in order for the output to run.
If someone could help me out, that would be awsome
output: This is what I would run
p1=Pawn.new(),
Obj.call(p1,{:goto, 1, 2}),
1=Obj.call(p1, :x),
2=Obj.call(p1, :y),
Obj.call(p1,{:moveDelta , 3, 1}),
4=Obj.call(p1, :x ) ,
3=Obj.call(p1 ,:y ).

Add the necessary code to the following to support the API used above for the object pawn:
function: I need to fill out the init() function here.
defmodule Obj do

def call(obj,msg) do
send obj,{self(), msg}

receive do
Response -> Response
end
   end
      end

defmodule Pawn do
def new(), do: spawn(__MODULE__,:init, [] ).
def init() do: // fill this out

Thank you for your time

A: I'm reluctant to do all your homework for you. However, given that the code you were given is not valid Elixir, I'll provide you a partial solution. I've implemented the :goto and :x handlers. You should be able to figure out how to write the :moveDelta and :y handlers.
defmodule Obj do
  def call(obj, msg) do
    send obj, { self(), msg }

    receive do
      response -> response
    end
  end
end

defmodule Pawn do
  def new(), do: spawn(__MODULE__,:init, [] )
  def init(), do: loop({0,0})
  def loop({x, y} = state) do
    receive do
      {pid, {:goto, new_x, new_y}} ->
        send pid, {new_x, new_y}
        {new_x, new_y}
      {pid, {:moveDelta, dx, dy}} ->
        state = {x + dx, y + dy}
        send pid, state
        state
      {pid, :x} ->
        send pid, x
        state
      {pid, :y} ->
        send pid, y
        state
    end
    |> loop
  end
end

p1=Pawn.new()
Obj.call(p1,{:goto, 1, 2})
1=Obj.call(p1, :x)
2=Obj.call(p1, :y)
Obj.call(p1,{:moveDelta , 3, 1})
4=Obj.call(p1, :x )
3=Obj.call(p1 ,:y )

The code runs. Here is the output of the test cases you provided (after I fixed the syntax issues:
iex(5)> p1=Pawn.new()
#PID<0.350.0>
iex(6)> Obj.call(p1,{:goto, 1, 2})
{1, 2}
iex(7)> 1=Obj.call(p1, :x)
1
iex(8)> 2=Obj.call(p1, :y)
2
iex(9)> Obj.call(p1,{:moveDelta , 3, 1})
{4, 3}
iex(10)> 4=Obj.call(p1, :x )
4
iex(11)> 3=Obj.call(p1 ,:y )
3
iex(12)>

Also, I fixed syntax issues in the given problem.


Q: Django Error While Submitting Forms Performing system checks...
Unhandled exception in thread started by .wrapper at 0x75abfcd8> Traceback (most recent call last): File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "/home/pi/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "/home/pi/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/pi/.venv/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 673, in exec_module File "", line 222, in _call_with_frames_removed File "/home/pi/tango_with_django_project/tango_with_django_project/urls.py", line 25, in url(r'^rango/', include('rango.urls')), File "/home/pi/.venv/lib/python3.5/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/home/pi/.venv/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 673, in exec_module File "", line 222, in _call_with_frames_removed File "/home/pi/tango_with_django_project/rango/urls.py", line 2, in from rango import views File "/home/pi/tango_with_django_project/rango/views.py", line 5, in from rango.forms import CategoryForm File "/home/pi/tango_with_django_project/rango/forms.py", line 4, in class CategoryForm(forms.ModelForm): File "/home/pi/.venv/lib/python3.5/site-packages/django/forms/models.py", line 243, in new "needs updating." % name django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form CategoryForm needs updating.
Here is my forms.py
from django import forms from rango.models import Page, Category
class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter the category name.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
    model = Category
class PageForm(forms.ModelForm): title = forms.CharField(max_length=128, help_text="Please enter the title of the page.") url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
    model = Page
    fields = ('title', 'url', 'views')
here is my views.py
from django.template import RequestContext from django.shortcuts import render_to_response from rango.models import Category from rango.models import Page from rango.forms import CategoryForm
def index(request): context = RequestContext(request) category_list = Category.objects.order_by('-likes')[:5] context_dict = {'categories': category_list} for category in category_list: category.url = category.name.replace(' ', '_') return render_to_response('rango/index.html', context_dict, context)
def about(request): context = RequestContext(request) context_dict = {'boldmessage': "I am bold font from the context"} return render_to_response('rango/about.html', context_dict, context)
def category(request, category_name_url): context = RequestContext(request) category_name = category_name_url.replace('_', ' ') context_dict = {'category_name': category_name} try: category = Category.objects.get(name=category_name) pages = Page.objects.filter(category=category) context_dict['pages'] = pages context_dict['category'] = category except Category.DoesNotExist: pass return render_to_response('rango/category.html', context_dict, context)
def add_category(request): context = RequestContext(request)
if request.method == 'POST':
    form = CategoryForm(request.POST)
if form.is_valid():
    form.save(commit=True)
    return index(request)
else:
    print (form.errors)

else:
    form = CategoryForm()
return render_to_response('rango/add_category.html', {'form': form}, context)

A: You need to add a fields or exclude attribute to the form class
class CategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = ['name']

Seems like you don't have a model named Category in that case you should inherit from forms.Form
class CategoryForm(forms.Form):
    name = forms.CharField(max_length=128, help_text="Please enter the category name.")


Q: Javascript matching objects of an array I have this array, I wish to pick out all the names which have a URL which contains '/blekinge'.
Any way to do this with map? And present in a list?
I've come this far:
const allaOrter = orter.map((allOrt) =>

{allOrt.url}

)

What I would like to do is to have sort of an ifstatement or a forEach loop that picks out all the URLs which contains /blekinge and present those. But I dont know how...
The real array I'm working with is much bigger and contains loads of urls.
Maybe even make new arrays which contains those elements that have a common url.
I hope my provided example is enough for someone of you guys to help me out. :)
orter.json
[{
        "id": "2",
        "namn": "Blekinge",
        "url": "/blekinge"
    },
    {
        "id": "23",
        "namn": "Karlshamn",
        "url": "/blekinge/karlshamn"
    },
    {
        "id": "24",
        "namn": "Karlskrona",
        "url": "/blekinge/karlskrona"
    },
    {
        "id": "25",
        "namn": "Olofström",
        "url": "/blekinge/olofstrom"
    },
    {
        "id": "26",
        "namn": "Ronneby",
        "url": "/blekinge/ronneby"
    }]

A: Use array.prototype.filter method then map the returned array
const arr = [{
        "id": "2",
        "namn": "Blekinge",
        "url": "/blekinge"
    },
    {
        "id": "23",
        "namn": "Karlshamn",
        "url": "/blekinge/karlshamn"
    },
    {
        "id": "24",
        "namn": "Karlskrona",
        "url": "/blekinge/karlskrona"
    },
    {
        "id": "25",
        "namn": "Olofström",
        "url": "/blekinge/olofstrom"
    },
    {
        "id": "26",
        "namn": "Ronneby",
        "url": "/blekinge/ronneby"
    }]

let filtered = (a) => a.url.includes("/blekinge")

console.log(arr.filter(filtered))

then map the result

A: You should first try to narrow down by matching the object which contains the url /blekinge using the filter method. Once you have filtered, the resulting array can be used to present a list.
To keep things simple, I implemented an unordered list to present the result, but the core of what you need is in the resulting filtered array.

let listElement = document.getElementById('name-list');

let data = [
  {
      "id": "2",
      "name": "Blekinge",
      "url": "/blekinge"
  },
  {
      "id": "23",
      "name": "Karlshamn",
      "url": "/blekinge/karlshamn"
  },
  {
      "id": "24",
      "name": "Karlskrona",
      "url": "/blekinge/karlskrona"
  },
  {
      "id": "25",
      "name": "Olofström",
      "url": "/blekinge/olofstrom"
  },
  {
      "id": "26",
      "name": "Ronneby",
      "url": "/test/ronneby"
  }
];

let updateList = (list, content) => {
  let li = document.createElement("li");

  li.innerHTML = content;

  list.appendChild(li);
};

let filteredData = data.filter(elem => elem.url.indexOf('/blekinge') !== -1);

filteredData.map(elem => updateList(listElement, elem.name));
Matching names

A: Working Demo :

const data = [{
        "id": "2",
        "namn": "Blekinge",
        "url": "/blekinge"
    },
    {
        "id": "23",
        "namn": "Karlshamn",
        "url": "/alpha/beta"
    },
    {
        "id": "24",
        "namn": "Karlskrona",
        "url": "/blekinge/karlskrona"
    },
    {
        "id": "25",
        "namn": "Olofström",
        "url": "/abc/def"
    },
    {
        "id": "26",
        "namn": "Ronneby",
        "url": "/blekinge/ronneby"
    }];

const res = data.filter((obj) => obj.url.indexOf('/blekinge') !== -1);

console.log(res);


Q: i can't pass and get the variable in scalate template As suggested I'm asking new question in new topic.
I have a problem with passing an argument to my scalate template (.ssp)
Below my controller and my template
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Locale locale, Model model) {
    User user = new User("Dawid", "Pacholczyk");

    ModelAndView template = new ModelAndView("defaultTemplate");
    template.addObject("user", user);

    return template;
}

<%@ val bar: String = "this is the default value" %>
<% attributes("title") = "This is the custom title" %>
<%@ var user: User %>

Hi ${user.name},

#do(layout("layouts/default.ssp"))
this is some template output...

${bar}
#end

Now I get exception:

    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is    org.fusesource.scalate.CompilerException: Compilation failed:
    /WEB-INF/scalate/defaultTemplate.ssp:3.13 error: not found: type User

            ^

    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:681)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

Now I don't know what to do. I'll add that when I delete <%@ var user: User %> everything works great
What to do ?

A: You need to import user before you can use it.
<% import somePackage.User %>


Q: Caching a list from a service call in android I'm using retrofit2 to make a service call. One thing that I display is a list.  I have no problem displaying the list even in a case where I have 242 items.  The problem I have is when I select an item from the list to show in a detailed view, a separate activity.
I get this crash in the log
RuntimeException: android.os.TransactionTooLargeException: data parcel size 873448 bytes

If limited the size of the list to 20 items and I no longer get the crash.
What options do I have for caching this list and not pulling out too many to where I get the crash?  I don't want to cache the whole response, just the list and pull out say 20 at a time.
Also, if I end up loading all of them into the list, won't I run into the same problem?


Q: How to correctly define (function || function) inside a Javascript object? This works:

However, this:

Generates an error of "TypeError: 'btoa' called on an object that does not implement interface Window."
Fiddle:
http://jsfiddle.net/kAGU2/
Why does the first example work but the second one emit that error?  What's the correct way to fix this particular error?

A:
Why does the first example work but the second one emit that error?

When the function is called as Base64Encode(), the this context is implicitly set to window. However, when you call it as a method on Test.Base64Encode(), this will refer to Test and btoa grumps about that.

What's the correct way to fix this particular error?

You will need to bind it to the expected context:
Base64Encode = window.btoa
  ? window.btoa.bind(window)
  : CryptoJS.enc.Base64.stringify;

A: Use .bind():
var Test = {
    Base64Encode: function() {
      if (window.btoa)
        return window.btoa.bind(window);

      return CryptoJS.enc.Base64.stringify;
    }()
};

You got the error because you invoked the function via that object property reference. When you do that, the value of this is set to a reference to the object involved. The btoa() function doesn't like that (for who knows what reason), but .bind() creates a wrapper function for you that ensures the proper this.

A: It appears as that btoa function is a member function of Window class. And so it has to be called with this set to window.
In order it to work in your setup you should call it this way:
Test.Base64Encode.call(window,"Please work.");


Q: java.lang.IllegalArgumentException: Not supported: indent-number public String filter(String message) {
    if (message == null) {
        return null;
    }

    // Remove formatting, transformer fails to handle wrong indentation correctly.
    message = message.replaceAll(">\\s*[\\r\\n]+\\s*", ">");
    message = message.replaceAll("\\s*[\\r\\n]+\\s*", " "); // for wrapped attribute lists

    Source xmlInput = new StreamSource(new StringReader(message));
    StringWriter stringWriter = new StringWriter();
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", INDENT); // for Java 6

        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", INDENT.toString()); // Java 1.5
        transformer.transform(xmlInput, new StreamResult(stringWriter));

        String pretty = stringWriter.toString();
        pretty = pretty.replace("\r\n", "\n");
        return pretty;
    } catch (TransformerException e) {
        if (e.getCause() != null && e.getCause() instanceof SAXParseException) {
            return message;
        }
        throw new RuntimeException(e);
    }
}

but i get exception here:
transformerFactory.setAttribute("indent-number", INDENT); // for Java 6

java.lang.IllegalArgumentException: Not supported: indent-number

my java:
java version "1.6.0_33"

why i get this error?

A: Instead of
TransformerFactory transformerFactory = TransformerFactory.newInstance();

you should write
TransformerFactory transformerFactory = new TransformerFactoryImpl();

because not all implementations of TransformerFactory have this field: indent-number.

A: I fixed that exception by commenting this line:
transformerFactory.setAttribute("indent-number", indent);

and adding this line:
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

The exception is gone even though the indetation that appears in the browser is incorrect.

A: Likely because Xalan (as packaged in JDK1.6/1.7) support "indent-number", yet others don't and have their own way of specifying the size of indent. So you have to put in the string appropriate for the XSLT provider. Work out which you're using and see its docs
Aren't standards that don't specify such things great?

A: You should use the predefined constant OutputKeys.INDENT, or if you really insist on hardcoding the value, it should be 'indent', not 'indent-number'.


Q: iOS6: MFMailComposeViewController slow to load and flashes black screen; MailCompositionS begins hogging memory On iOS 6, after sending a few email messages (by using MFMailComposeViewController), the email screens become very slow to open- at first opening with none of the fields populated (no Subject, no body, etc.) for a few seconds, and eventually (after sending about 8 messages), a black screen is displayed to the user for a few seconds before the email view controller is properly displayed.
The log spits out the following line before each black screen is displayed:

[MFMailComposeRemoteViewController: ....] timed out waiting for fence
  barrier from com.apple.MailCompositionService

Also, using MFMailComposeViewController on iOS6 causes the MailCompositionS process to start hogging memory (it's going all the way up to roughly 260MB on my iPhone).  I'm assuming this is the reason for the MFMailComposeViewController display issues.
Everything runs fine on iOS 5.  This issue only occurs on iOS 6.
Has anyone found a way to resolve this issue?
Thanks!
The code is standard, but I'll include it anyway:
-(IBAction)doEmailLog:(id)sender
{
    if( [self canSendMail] )
    {
        // create the compose message view controller
        MFMailComposeViewController* mailComposer = [[MFMailComposeViewController alloc] init];

        // this class will handle the cancel / send results
        mailComposer.mailComposeDelegate = self;

        // fill in the header and body
        [mailComposer setSubject:@"My Subject"];
        [mailComposer setMessageBody:@"My message body" isHTML:NO];

        // attach log file
        if ([[NSFileManager defaultManager] fileExistsAtPath:filename])
        {
            NSData *data = [NSData dataWithContentsOfFile:filename];
            [mailComposer addAttachmentData:data mimeType:@"text/plain" fileName:filename];
        }

        // show the view controller
        [self presentViewController:mailComposer animated:YES completion:^{LogTrace(@"Presented mail view controller");}];
    }
    else
    {
        ...
    }
}

-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    ...

    // dismiss the compose message view controller
    [self dismissViewControllerAnimated:YES completion:^{LogTrace(@"Finished dismissing mail controller");}];
}

A: on ios 6 the mail composer is its own app (inside yours)
:: http://oleb.net/blog/2012/10/remote-view-controllers-in-ios-6/

the code looks good to me if you are using ARC else it leaks and on ios6 that might result in x XPC remotes
if all is good there, Id blame it on a bug in apple's new handling of XPC

A: there's another possible solution:
Remove custom fonts from the appearance methods, if you have any
https://stackoverflow.com/a/19910337/104170


Q: How to download nested json data, convert to excel format in angular 10? employees = [
  {
    SNO : 1,
    name : "HARIPRASATH",
    SALARY : [
      {
        SNO: 1,
        MONTH : 'APRIL',
        DATE : '01-04-2022',
        TIME : '10.AM',
        AMOUNT : 15000
      },
      {
        SNO: 2,
        MONTH : 'MAY',
        DATE : '01-05-2022',
        TIME : '10.AM',
        AMOUNT : 15000
      },
      {
        SNO: 3,
        MONTH : 'JUNE',
        DATE : '01-06-2022',
        TIME : '10.AM',
        AMOUNT : 15000
      }
    ]
  },
  {
    SNO : 2,
    name : "SINDHUJA",
    SALARY : [
      {
        SNO: 1,
        MONTH : 'APRIL',
        DATE : '01-04-2022',
        TIME : '10.AM',
        AMOUNT : 18000
      },
      {
        SNO: 2,
        MONTH : 'MAY',
        DATE : '01-05-2022',
        TIME : '10.AM',
        AMOUNT : 18000
      },
      {
        SNO: 3,
        MONTH : 'JUNE',
        DATE : '01-06-2022',
        TIME : '10.AM',
        AMOUNT : 18000
      }
    ]
  }

I need to convert this table type to excel format like this:


Q: Is it possible to use SQL Server Compact Edition in an Open Source project? I am aware of other solutions like System.Data.Sqlite or Firebird through Dblinq, but since nothing beats SQL Compact Edition (integration-wise) with Visual Studio, I would like to use it and to know if its license allows its usage in Open Source projects.
Thanks.

A: One point to bear in mind is that you would presumably not be distributing the source code for the Compact Edition. This might make your project fail some definitions of "Open source" if the Compact Edition is closely integrated with the rest of your code. This in turn might make it inelligible to be hosted on certain FOSS web servers (I'm thinking of Google Code) and might result in your prtoject getting a bad name amond more zealous FOSS supporters.

A: As long as you don't need replication with a big MS SQL Server you are fine with SQL CE.

A: IANAL, and I do not know if the EULA is compatible with every open source license.
But, as long as you sign up for redistribution rights you should be fine to redistribute it with an open source project.


Q: What classes from Jain SIP (java) should I use to make an SIP client? I am asking to create an SIP client, but I am totally lost ...
After some researches I found the Jain SIP API in java, and I think that I will use it.
However I don't really know what classes I should use and what interfaces I should implement or not.
I have read this article : http://www.oracle.com/technetwork/articles/entarch/introduction-jain-sip-090386.html
And this : http://hudson.jboss.org/hudson/job/jain-sip/lastSuccessfulBuild/artifact/javadoc/javax/sip/package-summary.html#package_description
But I don't understand which part should I implement for an SIP client ? The SipListener OR the SipStack and the SipProvider ?
Thanks.

A: You need to implement both of those classes.
The SipProvider class will connect to your endpoint (Aterisk, for example). Note that this class must be on an static context, because only one connection is allowed per client.
You cant create a SipProvider instance calling a SipStack class, on sipStack.createSipProvider(listeningPoint). After this, you be able to create transactions and send requests to you endpoint.
The SipListener is the class that will process all responses from your server. This means that every request that you send to the server (Via SipProvider) will receive a response on SipListener. So, you must have this listener to process all data returned by your endpoint.
Try to implement the code that was described on oracle article that you cite. I started to develop based on this article, and works very fine!

A: Check the examples at the Reference Implementation https://java.net/projects/jsip/sources/svn/show/trunk/src/examples?rev=2279 to help you moving forward faster


Q: What folders should be git ignored in React Native project? I'm playing with Facebook/React Native, and when I run git init, I have no idea what should be ignored expect node_modules folder,
Should I commit all iOS folder?
Thanks

A: We suggest this .gitignore: react-native/Examples/SampleApp/.gitignore.
It ignores both user-specific Xcode files and the node_modules dir.

A: React Native CLI creates a .gitignore file when you start a new project:
react-native init <ProjectName>

It covers all the basics that should/can be ignored.
Source: https://github.com/facebook/react-native/blob/master/template/_gitignore

A: This is a related question：What should Xcode 6 gitignore file include?
It can be divided into three categories:

*

*IDE(Webstorm,Xcode) config
file,like:.idea/,ios/ProjectName.xcodeproj/xcuserdata

*version control tools(git,svn) file, like: .git

*other files，for example,.DS_Store is OSX dir config file

my answer is which have been inspected in practice:
### SVN template
.svn/
### Xcode template
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore

## Build generated
build/
DerivedData/

## Various settings
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata/

## Other
*.moved-aside
*.xccheckout
*.xcscmblueprint
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff:
.idea/workspace.xml
.idea/tasks.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml

# Sensitive or high-churn files:
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml

# Gradle:
.idea/gradle.xml
.idea/libraries
.idea

# Mongo Explorer plugin:
.idea/mongoSettings.xml

## File-based project format:
*.iws

## Plugin-specific files:

# IntelliJ
/out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### TortoiseGit template
# Project-level settings
/.tgitconfig

*.swp

# node_modules/,Xcode and Webstorm will spend lots of time for indexing this dir
node_modules/

# ios/Pods,
ios/Pods/

# OS X temporary files that should never be committed
.DS_Store
src/components/.DS_Store

# user personal info,for example debug info
ios/ProjectName.xcodeproj/project.xcworkspace/
ios/ProjectName.xcodeproj/xcuserdata

# Podfile versions
ios/Podfile.lock

# Created by .ignore support plugin (hsz.mobi)

Hope it helps you!

A: gitignore.io suggests the following .gitignore file for react-native:
Created by https://www.gitignore.io/api/reactnative
### ReactNative ###
# React Native Stack Base
### ReactNative.Xcode Stack ###
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore

## Build generated
build/
DerivedData/

## Various settings
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata/

## Other
*.moved-aside
*.xccheckout
*.xcscmblueprint

### ReactNative.Node Stack ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

### ReactNative.Buck Stack ###
buck-out/
.buckconfig.local
.buckd/
.buckversion
.fakebuckversion

### ReactNative.macOS Stack ###
*.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon

# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

### ReactNative.Gradle Stack ###
.gradle
**/build/

# Ignore Gradle GUI config
gradle-app.setting

# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar

# Cache of project
.gradletasknamecache

# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties

### ReactNative.Android Stack ###
# Built application files
*.apk
*.ap_

# Files for the ART/Dalvik VM
*.dex

# Java class files
*.class

# Generated files
bin/
gen/
out/

# Gradle files
.gradle/

# Local configuration file (sdk path, etc)
local.properties

# Proguard folder generated by Eclipse
proguard/

# Log Files

# Android Studio Navigation editor temp files
.navigation/

# Android Studio captures folder
captures/

# Intellij
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/dictionaries
.idea/libraries

# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild

# Freeline
freeline.py
freeline/
freeline_project_description.json

### ReactNative.Linux Stack ###
*~

# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*

# KDE directory preferences
.directory

# Linux trash folder which might appear on any partition or disk
.Trash-*

# .nfs files are created when an open file is removed but is still being accessed
.nfs*

# End of https://www.gitignore.io/api/reactnative

A: It's probably worth noting that react-native init <project-name> generates a .gitignore file for you. This will likely be up to date with React Native's current tooling and build outputs. So this should be a good starting point.
Using react-native-cli 1.0.0 and react-native 0.36.0 generated the following .gitignore file:
# OSX
#
.DS_Store

# Xcode
#
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate
project.xcworkspace

# Android/IJ
#
*.iml
.idea
.gradle
local.properties

# node.js
#
node_modules/
npm-debug.log

# BUCK
buck-out/
\.buckd/
android/app/libs
android/keystores/debug.keystore

A: If you look at the React Native examples:
https://github.com/facebook/react-native/tree/master/Examples
Each one has a directory with a contents similar to the iOS directory generated by react-native-cli. Looking further into the Xcode project file, it's referenced in there too, and look at the contents - there's things like the launch screen.
So yes, the iOS directory is needed.
Regarding node_modules, I suggest you look at this answer which provides more information:
https://stackoverflow.com/a/19416403/125680


Q: Pure CSS slider left margin accretion I am in the process of developing a site for a uni project, and I have built an automatically changing slider while only using css (it is a requirement of this project that I don't use anything else). The problem I'm experiencing is that when the slides change, the left margin begins to add up, and I can't figure out why.
I have tried making a page with just the html and css necessary for the slider to work and it works properly there, but not when incorporated into my main css page.
Any pointers would be appreciated!
The site this can be seen on is http://www.darkmatter-designs.com/

A: I can't figure out what the problem is.. The css is really messy, there is a lot of useless  or overwritten properties.. You have to optimize it..
But somehow I found a workaround : set the width of the #css-slider to 864px.. It's not really a proper solution but it works anyway..

A: As you can see you have some margin between the images, which makes their widths effectively bigger a little bit. I see you applied a reset in your css, so this is probably coming from the white space in your html. A quick fix would be to put all the li and img on a single line with no spaces or carriage returns between them, like so:

I know, it's weird.


Q: Implementing multi layer role on Django Working with django Group and Permission. Normally works fine. Now want to add sub admin who can give permission only particular model. How to implement?

A: As per our discussion below are my Steps:

*

*Override Role with company OR you can keep this at Super Admin level.
http://127.0.0.1:8000/admin/auth/role/

*Add separate table for permissions with pk, client ID, RoleID , add, edit, view, delete, model, action (URL) columns

*Add decorator for each of the action or Model and check permissions for that particular action or model.

*Check roles and permission in Admin using common function something like check_role_permissions_admin
//Add below function in separate / common function file.
def check_role_permissions_admin(request, url=None):
    if not hasattr(request.user,"client"):
        return {
            'clientwise': False,
            'add': False,
            'change': False,
            'delete': False,
            'view': False,
            'icon': ''
        }
    super_admin_role = Role.objects.get(pk=1)
    all_roles = request.user.groups.all()
    try:
        action = Actions.objects.get(
            url=url
        )
    except:
        action = None
    if super_admin_role in all_roles:
        return {
            'clientwise': False,
            'add': True,
            'change': True,
            'delete': True,
            'view': True,
            'icon': str(action.icon) if action else ''
        }

    // Write Logic here for Role and Permissions of requested action(s)
    roles = [group for group in request.user.groups.all()]
    permissions = ActionPermissions.objects.filter(
        client=request.user.client,
        role__in=roles,
        action__url=url
    )
    if permissions.exists():
        permobj = permissions[0]
        return {
            'clientwise': True if permobj.client else False,
            'add': True if permobj.add else False,
            'change': True if permobj.change else False,
            'delete': True if permobj.delete else False,
            'view': True if permobj.view else False,
            'icon': permobj.action.icon
        }
    else:
        return {
            'clientwise': False,
            'add': False,
            'change': False,
            'delete': False,
            'view': False,
            'icon': ''
        }

//Add below code in admin.py, for every admin action you need to do following //thing and need
//to make sure that similar entry is added in table permissions.
from module.function import check_role_permissions_admin
@admin.register(ConfigRuleMaster)
class ModelMasterAdmin(admin.ModelAdmin):
    action_form=CustomActionForm
    form = ModelMasterForm
    fields=(('title','template'))
    list_display=('title','template')
    search_fields = ('title','template',)
    list_display_links = []

    def get_model_perms(self, request):
        perms = decorators.check_role_permissions_admin(request, '/admin/lmt/modelmaster/')
        perms['clientwise'] = False
        return perms

    def has_add_permission(self, request):
        perms = decorators.check_role_permissions_admin(request, '/admin/lmt/modelmaster/')
        return perms['add']

    def has_change_permission(self, request, obj=None):
        perms = decorators.check_role_permissions_admin(request, '/admin/lmt/modelmaster/')
        return perms['change']

*Another work is to handle actions through decorators.

But this is very raw version of code I found in my repository, you need to make this logic at very high level to make your client happy and to have full secured code.


Q: WooCommerce: Add class to variation dropdown I want to add the class .form-control to the variation dropdown in the WooCommerce product pages.
It seems that there is an option to do so. I found the function wc_dropdown_variation_attribute_options.
The function has an class attribute:
function wc_dropdown_variation_attribute_options( $args = array() ) {
$args = wp_parse_args( apply_filters( 'woocommerce_dropdown_variation_attribute_options_args', $args ), array(
    'options' => false,
    'attribute' => false,
    'product' => false,
    'selected' => false,
    'name' => '',
    'id' => '',
    'class' => '',
    'show_option_none' => __( 'Choose an option', 'woocommerce' ),
 ) );

Is there any solution to add the class to the dropdown?
I only found the function but no code/snippet to change the class attribute.
Edit: I found a snippet that is customizing the dropdown but I don't know how to use it for only adding the class: https://stackoverflow.com/a/47189725/1788961

A: The answer is in the apply_filters( 'woocommerce_dropdown_variation_attribute_options_args', $args )
You basically need to use that filter to access the $args that are being passed. In your particular situation, this is how you would do it:
add_filter( 'woocommerce_dropdown_variation_attribute_options_args', static function( $args ) {
    $args['class'] = 'form-control';
    return $args;
}, 2 );

What this does, is hooks into the woocommerce_dropdown_variation_attribute_options_args filter and passes the original $args to a static function. Then you basically set the value of the class index of the $args array. Then you return the $args.


Q: Implement realm with data binding in android I am trying to use Android's architecture component i.e.data binding with Realm database using MVVM pattern.
After exploring about the data binding and MVVM , i came across few approaches to bind model with the UI.

*

*Declare Observable primitive fields in model and directly bind them to the android xml file.

*Keep the model as it is with primitive data type and declare Observable fields in View model class
Now, as realm does not support Observable fields the option left is to use Observable
i have referred this article to use realm with data binding  , but this article is pretty old one.
so my questions are

*

*What is preferable while implementing data binding in android , bind model  directly to the android UI or declare obserable variables in view model and map them with the model ?

*best practices to use realm with data binding
My question is pretty specific in context of realm and data binding hence its not a generalize question.

A: I'll answer the first question only as I haven't used Realm for a while.
As you stated yourself, you cannot use Observable fields in the model that you use in Realm and you shouldn't ever do so. Model is to be kept simple.
ViewModel is exactly where Observables belong. They should be bound to the view and only them.
Consider using the new LiveData classes instead of Observables and ViewModels from the new Architecture Components. They make things even easier and are now supported in Data Binding:
LiveData Overview
LiveData with Data Binding


Q: PHP - FPDF Multicell function does not make a new line I'm trying to make a newline inside a multicell. What I've done is:
$pdf->MultiCell(90,10,'test'.'\n'.'test',1,0,'C',1);

According to the manual the multicell should parse the '\n' character and render a newline but it does not (it prints the two byte string '\n' alongside with the actual text)

A: Try to use "\n" instead of '\n' (or even PHP_EOL predefined constant). Use double quotes.
Related:

*

*What is the difference between single-quoted and double-quoted strings in PHP?

*FPDF multicell alignment not working


Q: image height based on mobile orientation I have a problem with a small mobile image gallery. When I change the orientation to portrait the images are too large to be displayed on the screen.
Is it possible with some javascript to make images fit the screen when the orientation changes to portrait? In landscape mode, everything looks fine.

A: yes, you can use CSS3 Media Queries without using JavaScript.
@media screen and (max-width: 450px) {
    img {
        width: 30%;
    }
}

http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

A: Try this:
@media screen and (orientation:portrait) {
    //your css code goes here
}

@media screen and (orientation:landscape) {
    //your css code goes here
}


Q: how can I save a form with ModelMultipleChoiceField? I have a model Calendar and in a form I want to be able to create multiple instances of it.
Here are my models:
class Event(models.Model):
    user = models.ForeignKey(User)

class Group(models.Model):
    name = models.CharField(_('Name'), max_length=80)
    events = models.ManyToManyField(Event, through='Calendar')

class Calendar(models.Model):
    event = models.ForeignKey(Event)
    group = models.ForeignKey(Group)

class CalendarInline(admin.TabularInline):
    model = Calendar
    extra = 1

class GroupAdmin(admin.ModelAdmin):
    inlines = (CalendarInline,)

Here is how I try to code my form:
class AddEventToGroupForm(ModelForm):
    group = ModelMultipleChoiceField(queryset=Group.objects.all(), widget=SelectMultiple())

    def save(self):
        for g in self:
            g.save()

    class Meta:
        model = Calendar
        fields = ('group',)

And here is a part of my view:
e = Event.objects.get(id=event_id)
calentry = Calendar(event=e)
if request.POST:
    f = AddEventToGroupForm(data=request.POST, instance=calentry)
    if f.is_valid():
        f.save()

If I try to submit that form, I get:
AttributeError at /groups/add_event/7/

'BoundField' object has no attribute 'save'

What is the proper way to create multiple instances of Calendar in this
situation?

A: That's not how to deal with many-to-many relationships in forms. You can't iterate through fields in a form and save them, it really doesn't work that way.
In this form, there's only one field, which happens to have multiple values. The thing to do here is to iterate through the values of this field, which you'll find in the cleaned_data dictionary (when the form is valid).
So, in your view, you do something like:
if f.is_valid():
    for group in f.cleaned_data['group']:
        calentry.groups.add(group)

Note you're not 'saving' the AddEventToGroupForm form at all. I would make it a standard forms.Form, rather than a ModelForm, as you're not really depending on any of the ModelForm functionality.


Q: Dependency injection: HttpClient or HttpClientFactory? Everywhere I can see three main approaches to create clients (basic, named, typed) in DI, but I have found nowhere if to inject IHttpClientFactory or HttpClient (both possible).
Q1: What is the difference between injecting IHttpClientFactory or HttpClient please?
Q2: And if IHttpClientFactory is injected, should I use factory.CreateClient() for each call?

A: Summary

*

*HttpClient can only be injected inside Typed clients

*for other usages, you need IHttpClientFactory

*In both scenarios, the lifetime of HttpClientMessageHandler is managed by the framework, so you are not worried about (incorrectly) disposing the HttpClients.

Examples
In order to directly inject HttpClient, you need to register a specific Typed service that will receive the client:
services.AddHttpClient<GithubClient>(c => c.BaseAddress = new System.Uri("https://api.github.com"));

Now we can inject that inside the typed GithubClient
public class GithubClient
{
    public GithubClient(HttpClient client)
    {
        // client.BaseAddress is "https://api.github.com"
    }
}

You can't inject the HttpClient inside AnotherClient, because it is not typed to AnotherClient
public class AnotherClient
{
    public AnotherClient(HttpClient client)
    {
        // InvalidOperationException, can't resolve HttpClient
    }
}

You can, however:
 1. Inject the IHttpClientFactory and call CreateClient(). This client will have BaseAddress set to null.
 2. Or configure AnotherClient as a different typed client with, for example, a different BaseAdress.
Update
Based on your comment, you are registering a Named client. It is still resolved from the IHttpClientFactory.CreateClient() method, but you need to pass the 'name' of the client
Registration
services.AddHttpClient("githubClient", c => c.BaseAddress = new System.Uri("https://api.github.com"));

Usage
// note that we inject IHttpClientFactory
public HomeController(IHttpClientFactory factory)
{
    this.defaultClient = factory.CreateClient(); // BaseAddress: null
    this.namedClient = factory.CreateClient("githubClient"); // BaseAddress: "https://api.github.com"
}

A: Sadly I cannot comment, but only Post an answer. Therefore I suggest you should check out the following Links:
https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests
https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
Regarding your Questions it more or Less boils down to this:
Q1 -> IHttpClientFactory handles the connection pools of HttpClient instances and this will help you regarding load and dispose problems as discribed in the links, if the HttpClient is used wrong.
Q2 -> yes you should use factory.create client according to microsoft docs


Q: Is it safe to use inheritance for meta-data migration? Is it safe to create a template schema for metadata so that other schemas which contain data can inherit from it?
Advantage: Migrations will be seamless for multi tenant scenarios.
Disadvantages: ?
Example:
hello=# CREATE SCHEMA template;

hello=# CREATE TABLE template.cities (
name       text,
population real,
altitude   int;

hello=# CREATE SCHEMA us;

hello=# CREATE TABLE us.cities () INHERITS (template.cities);

hello=# \d us.cities;
                   Table "us.cities"
   Column   |     Type     | Collation | Nullable | Default
------------+--------------+-----------+----------+---------
 name       | text         |           |          |
 population | real         |           |          |
 altitude   | integer      |           |          |
Inherits: template.cities

hello=# CREATE SCHEMA eu;

hello=# CREATE TABLE eu.cities () INHERITS (template.cities);

hello=# \d eu.cities;
                   Table "eu.cities"
   Column   |     Type     | Collation | Nullable | Default
------------+--------------+-----------+----------+---------
 name       | text         |           |          |
 population | real         |           |          |
 altitude   | integer      |           |          |
Inherits: template.cities

hello=# ALTER TABLE cities ADD COLUMN state varchar(30);

hello=# \d us.cities;
                          Table "us.cities"
   Column   |         Type          | Collation | Nullable | Default
------------+-----------------------+-----------+----------+---------
 name       | text                  |           |          |
 population | real                  |           |          |
 altitude   | integer               |           |          |
 state      | character varying(30) |           |          |
Inherits: template.cities

A: I think inheritance is a good approach to this problem.
I can think of two down sides:

*

*It is possible to create additional columns to the inheritance children. If you control DDL, you can probably prevent that.

*You still have to create and modify indexes on all inheritance children individually.
If you are using PostgreSQL v11 or later, you could prevent both problems by using partitioning. The individual tables would then be partitions of the “template” table. This way, you can create indexes centrally by creating a partitioned index on the template table. The disadvantage (that may make this solution impossible) is that you need a partitioning key column in the table.


Q: Setting active link dynamically on static navigation I have "navigation.html" (static coded  navigtaion ) file loaded on multiple pages, using jQuery .load()
Now I need to  dynamically set active
 for each page user clicking on. I can not use body id for specific reasons.
Any other ways to do this?

A: If you can identify your current page by class or id (ex: body > div#contacts) for contacts.html and this class/id is unique then you have to match it with you navigation, other way is to match window.location.href value (parsed if you want) against your navigation.
changeActiveLink is defined in JS (ex:init.js) file which you include to each page
function changeActiveLink() {
  var currentLocation = window.location.href;
  currentLocation = currentLocation.replace('//', '/').split('/');
  var page = currentLocation[currentLocation.length - 1];

  if (page == "") { page = 'index.html'; }

  $('#leftNav1 a[href*="'+ page +'"]').addClass('active');
}

This line is called from each file when "init.js" is included.
$('#leftNav1').load('navigation.html', changeActiveLink);

A: Or you can use any HTML or even HTML5 tag to specify li item.

or

or

and jQuery with window.location object
      $('li[title="' + window.location.path + '"]').addClass("active");

A: You could set up some jquery script to get the url and then find the href of the li that matches that.  This will allow you to addClass() to that li of active.
This of course will only work if your href matches the url


Q: Test if socket is connected Following on from this question, I am trying to set a variable to see if a socket is connected.
However the question's answer doesnt seem to work.  If I console.log the socket variable I get this:

As you can see in the image, it says connected: true but when I run this:
console.log(socket.connected); I simply get false.  The start of my code looks like this:
var socket = io('http://test.domain.net:1234', {reconnection: false});
console.log("Connected:" + socket.connected);

A: I think you should put a timer and then do the console due to the async nature of JavaScript.
var socket = io('http://test.domain.net:1234', {reconnection: false});

setTimeout(function(){
    console.log("Connected:" + socket.connected);
}, 3000);

`


Q: How can I combine multiple webpages and get them as pdf? I have multiple pages that I am getting after filling a form with puppeteer. I am currently using "page.printToPDF" api of puppeteer to obtain the webpage as a pdf but the problem is that I have multiple pages and I would like to combine all of them and get a single pdf. Is there anyway I can achieve this with puppeteer and javascript?

A: Here is an alternative solution, there are many packages for merging pdf files.

Here is how you can use one of the many pdf merging packages.
const PDFMerge = require('pdf-merge');
const files = [
    `${__dirname}/1.pdf`,
    `${__dirname}/2.pdf`
];
const finalFile = `${__dirname}/final.pdf`;

Here is how you can print multiple pages and then merge them.
// goto first page and save pdf file
await page.goto('http://example1.com', {waitUntil: 'networkidle'});
await page.pdf({path: files[0], format: 'A4', printBackground: true})

// goto first page and save pdf file
await page.goto('http://example2.com', {waitUntil: 'networkidle'});
await page.pdf({path: files[1], format: 'A4', printBackground: true})

// merge two of them and save to another file
await PDFMerge(files, {output: finalFile);

It's all about how you take advantages of your resources.

A: var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('https://www.google.co.in/', 'utf8');
var options = {
  format: 'A4',
  "border": {
    "top": "0.2in",            // default is 0, units: mm, cm, in, px
    "bottom": "1in",
    "left": "0.1cm",
    "right": "0.1cm"
  },
};

pdf.create(html, options).toFile('./google.pdf', function(err, res) {
  if (err) return console.log(err);
  console.log(res); // { filename: '/app/businesscard.pdf' }
});

You have to install html-pdf after this use above code. for more information about to convert check link. https://www.npmjs.com/package/html-pdf


Q: My sticky sidebar does not show until the user scrolls down Like the title says, I got the sticky sidebar to work. The only concern is that when the user first get to the page,  the sidebar does not show at all until the user scrolls down, then it does go up and down. I was wondering if there's something wrong with the JS code or something else..? I can't seem to get it to work >-<

There's nothing specific in the CSS or the html. Just a div on the right side class: sidebar and no specific CSS either except for the design of it. I thought there'd be a lot of code so I didn't post it here. Let me know if you do need it..
<!DOCTYPE html>

        <asp:Panel ID="pnl_In_Out" runat="server">

                <%--
--%>

OFFICE RESERVATION

                        <%--

--%>

                                    In

                                                <asp:TextBox ID="txt_SearchDateFrom" CssClass="form-control form-control-inline input-small date-picker" runat="server"></asp:TextBox>

                                                <asp:DropDownList ID="ddl_SearchTimeFrom" CssClass="form-control text-right" Width="145" Height="35" runat="server"></asp:DropDownList>

                                    Out

                                                <asp:TextBox ID="txt_SearchDateTo" CssClass="form-control form-control-inline input-small date-picker" runat="server"></asp:TextBox>

                                                <%--<asp:TextBox ID="txt_SearchTimeTo" CssClass="form-control timepicker timepicker-no-seconds" Width="145" runat="server"></asp:TextBox>--%>
                                                <asp:DropDownList ID="ddl_SearchTimeTo" CssClass="form-control" Width="145" Height="35" runat="server"></asp:DropDownList>

                                <asp:Button ID="btn_Reserve" runat="server" Text="RESERVE" CssClass="btn btn-danger" Width="50%" OnClick="btn_Reserve_Time_Click" />

            </asp:Panel>

            <asp:Panel ID="pnl_Question" runat="server">

                <%--
--%>

QUESTIONS ?

                                                <asp:TextBox ID="txt_Email" CssClass="form-control" Width="145" Font-Size="Small" runat="server" placeholder="Email Address"></asp:TextBox>

                                                <asp:TextBox ID="txt_Message" TextMode="multiline" Rows="3" Font-Size="Small" CssClass="form-control" class="contact-message" Style="width: 100%!important; height: 70px; resize: none;" runat="server" placeholder="Enter Message"></asp:TextBox>

                                <asp:Button ID="btn_Message_Send" runat="server" Text="SEND" CssClass="btn btn-danger" Width="50%" OnClick="btn_Message_Send_Click" />

            </asp:Panel>

            <asp:Panel ID="Panel1" runat="server">

                <%--
--%>

AGENT INFORMATION

                            <%--

--%>

                                <%----%>

Contact Number:
<asp:Label ID="lbl_ListingContactPhone" runat="server" Text="none"></asp:Label>

E-mail Address:
<asp:Label ID="lbl_ListingContactEmail" runat="server" Text="none"></asp:Label>

And the CSS
.sidebar {
            float: right;
            width: 245px;
            margin-left: 850px;
        }

        .sidebar-sticky {
            float: right;
        }

        .sidebar-sticky2 {
            float: right;
        }

        .sidebar-sticky3 {
            float: right;
        }

A: Since the picture is not clear enough to reproduce the issue you described, I would only just point out aspects I observed to be out of place in the script you posted.
I have not studied the logic of the code enough to establish its correctness or a possible lack of it. But I believe some of the variables at play in the script ought to be evaluated during scroll since a change in the page content can invalidate their initial state:
$(document).ready(function() {

  // 1. These variables factor in statically to the feature
  // and it's appropriate that they are evaluated once
  var $sticky = $('.sidebar');
  var $stickyrStopper = $('.sticky-stopper');

  if (!$sticky.offset()) {
    return;
  }

  $(window).scroll(function() {

    var stickOffset = 0;

    // 2. These variables factor in DYNAMICALLY to the feature,
    // and they must be re-evaluated in alignment with
    // changing content for instance.
    // --
    // Therefore they deserve to be evaluated inside the scroll handler.
    var generalSidebarHeight = $sticky.innerHeight();
    var stickyTop = $sticky.offset().top;
    var stickyStopperPosition = $stickyrStopper.offset().top;
    var stopPoint = stickyStopperPosition - generalSidebarHeight - stickOffset;
    var diff = stopPoint + stickOffset;

    var windowTop = $(window).scrollTop();

    if (stopPoint < windowTop) {
      $sticky.css({
        position: 'absolute',
        top: diff
      });
    } else if (stickyTop < windowTop + stickOffset) {
      $sticky.css({
        position: 'fixed',
        top: stickOffset
      });
    } else {
      $sticky.css({
        position: 'fixed',
        top: 'initial'
      });
    }
  });
});

See if that provides you a stepping stone.