text:
Q: Creating entity with Magical Record only in OSX (+entityForName: could not locate an entity named '(null)' in this model.) Hi I am having a problem creating entitys with magicalRecord in OSX, I create the model and the NSManagagedSubclasses and so on. But when i run this code in applicationDidFinishLaunching(I am using magicalRecord 2.2):
[MagicalRecord setupCoreDataStack];
Person * person = [Person MR_createEntity];
person.name = @"alex";

I get this in the log:
2013-10-06 18:01:54.320 TestMagicalRecord[7554:303] +[NSManagedObjectContext(MagicalRecord) MR_contextWithStoreCoordinator:](0x7fff71a96238) -> Created Context UNNAMED
2013-10-06 18:01:54.321 TestMagicalRecord[7554:303] +[NSManagedObjectContext(MagicalRecord) MR_setRootSavingContext:](0x7fff71a96238) Set Root Saving Context: <NSManagedObjectContext: 0x101924d00>
2013-10-06 18:01:54.321 TestMagicalRecord[7554:303] +[NSManagedObjectContext(MagicalRecord) MR_newMainQueueContext](0x7fff71a96238) Created Main Queue Context: <NSManagedObjectContext: 0x1001564a0>
2013-10-06 18:01:54.321 TestMagicalRecord[7554:303] +[NSManagedObjectContext(MagicalRecord) MR_setDefaultContext:](0x7fff71a96238) Set Default Context: <NSManagedObjectContext: 0x1001564a0>
2013-10-06 18:01:54.322 TestMagicalRecord[7554:303] +entityForName: could not locate an entity named '(null)' in this model.

When i run the same code in an IOS project it runs with no problems, i have been trying to find sample code for OSX but with no luck, should it be any different?
The Mac sample code in the Magical record Github repo does only contain a project is there a way to run it with the other resources?
I bet its a simple solution but i cant find anything in the Docs/SO that will work.

A: As you also found out in the mean time, this is a bug in the Development branch of Magical Record.
In the 2.2 version of the Development branch, MR_createEntity uses the following method to determine the entity name of the object that should be created:
+ (NSString *) MR_bestGuessAtAnEntityName
{
    if ([self respondsToSelector:@selector(entityName)])
    {
        return [self performSelector:@selector(entityName)];
    }
    return NSStringFromClass(self);
}

But (at least on OS X 10.8), NSObject actually responds to entityName, and invoking
that method returns nil. I could not find any documentation on this, so this might be
some internal undocumented method.
But the effect is that MR_bestGuessAtAnEntityName returns nil, and therefore
+ (id) MR_createInContext:(NSManagedObjectContext *)context
{
    return [NSEntityDescription insertNewObjectForEntityForName:[self MR_bestGuessAtAnEntityName] inManagedObjectContext:context];
}

fails with the error message

+entityForName: could not locate an entity named '(null)' in this model.

So this is a Magical Record bug, and is worth reporting to the maintainers.
The bug occurs only on OS X, because NSObject (or NSManagedObject) does not respond to entityName on iOS.

A: Make sure your model file is being compiled as part of your target. You can see this by selecting the xcdatamodel file in the project navigator, and then in the inspector area, look for the targets it belongs to. Or, you can check your build settings and make sure this file is in the compile files section.

A: The problem was that i did not use the right Branch from Github I had the Development branch instead of the Master Branch! Hope that this helps others who make this stupid mistake...

A: Like Martin R!

*

*Go to file NSManagedObject+MagicalRecord.m

*Find method: + (NSString *) MR_bestGuessAtAnEntityName

*Replace by: return NSStringFromClass(self);
Work fine.


text:
Q: remove model in collection and fire remove event - backbone.js how do I remove remove a  model in collection and make the remove event fire . I tried  people.remove([{ name: "joe3" }]); but it wont work.
var Person = Backbone.Model.extend({

    initialize: function () {
        console.log(" person is initialized");
    },
    defaults: {
        name: "underfined",
        age:"underfined"
    }
});

var People = Backbone.Collection.extend({
    initialize: function () {
        console.log("people collection is initialized");
        this.bind('add', this.onModelAdded, this);
        this.bind('remove', this.onModelRemoved, this);
    },
    model: Person,
    onModelAdded: function(model, collection, options) {
        console.log("options = ", options);
        alert("added");
    },
    onModelRemoved: function (model, collection, options) {
        console.log("options = ", options);
        alert("removed");
    },
});

//var person = new Person({ name: "joe1" });
var people = new People();

//people.add([{ name: "joe2" }]);
people.add([{ name: "joe1" }]);
people.add([{ name: "joe2" }]);
people.add([{ name: "joe3" }]);
people.add([{ name: "joe4" }]);
people.add([{ name: "joe5" }]);

people.remove([{ name: "joe3" }]);

console.log(people.toJSON());

A: Another way is shorter a little and fires the remove event for a collection as well:
people.at(2).destroy();
// OR
people.where({name: "joe2"})[0].destroy();

Triggers a "destroy" event on the model, which will bubble up through any collections that contain it.. http://backbonejs.org/#Model-destroy

A: var Person = Backbone.Model.extend({
    defaults: {
        name: "underfined",
        age:"underfined"
    }
});

var People = Backbone.Collection.extend({
    initialize: function () {
        this.bind('remove', this.onModelRemoved, this);
    },
    model: Person,
    onModelRemoved: function (model, collection, options) {
        alert("removed");
    },
    getByName: function(name){
       return this.filter(function(val) {
          return val.get("name") === name;
        })
    }
});

var people = new People();

people.add(new Person({name:"joe1"}));
people.add(new Person({name:"joe2"}));
people.remove(people.getByName("joe1"));

console.info(people.toJSON());

A: For anyone else looking for a remove where, you can simply chain it with a collection.where call. like so to remove all items matching the search:
people.remove(people.where({name: "joe3"}));

see Backbone collection.where

A: By doing:
people.remove([{ name: "joe3" }]);

you don't remove a model, because you pass just an plain object which is not connected to people collection. Instead you could do something like this:
people.remove(people.at(2));

Or:
var model = new Person({name: "joe3"});
people.add(model);
...
people.remove(model);

will work as well.
So you need to reference actual model object from a collection;
http://jsfiddle.net/kD9Xu/

A: In order to remove "[0]" you can use the following code:
people.findWhere({name: "joe2"}).destroy();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Control combined with the "1, 2, 3" digits dont work Since late there's been a weird bug on my computer or keyboard, for the key combination of control + 1/2/3 don't work anymore. Which I use a lot to switch around in Chrome. This has been really annoying and I have no idea what causes it.
The thing, it works fine when I use the numpad.
I have a Corsair K70, and the operating system I am using is Windows 10. Does anyone know of this problem or is something wrong with my keyboard?
Sorry, to clarify, I was making an example of it being annoying with Chrome, but it happens everywhere.

A: If you have Nvidia Geforce Experience installed you may try solution posted on http://www.tomshardware.co.uk/answers/id-3224159/keys-work-ctrl-pressed.html

"...I found a solution (at least for myself). I switched off 'SHARE' on my Nvidia GeForce Experience software. For some reason it was causing conflict." -Rosinho

A: If you can reproduce this problem on demand, then I suggest testing with an additional USB keyboard attached and also some testing with the OSK (On Screen Keyboard). Start > Run > type "osk", to open it.
If the additional keyboard and OSK function properly, then your keyboard is probably defective. if they do not, then probably an OS or driver issue.


text:
Q: java.lang.VerifyError in ktor server POST in full stack tutorial In the official kotlin tutorial https://kotlinlang.org/docs/multiplatform-full-stack-app.html
I have a ktor server running, and when I do a GET I get the correct json response. When I POST:
POST http://localhost:9090/shoppingList
Content-Type: application/json

{
  "desc": "Peppers ",
  "priority": 5
}

The server returns a 500 with this error:
2023-01-10 08:53:06.605 [DefaultDispatcher-worker-1] INFO  ktor.application - Responding at http://0.0.0.0:9090
2023-01-10 08:53:12.317 [eventLoopGroupProxy-4-2] ERROR ktor.application - Unhandled: POST - /shoppingList
java.lang.VerifyError: class kotlinx.serialization.json.internal.StreamingJsonDecoder overrides final method kotlinx.serialization.encoding.AbstractDecoder.decodeSerializableElement(Lkotlinx/serialization/descriptors/SerialDescriptor;ILkotlinx/serialization/DeserializationStrategy;Ljava/lang/Object;)Ljava/lang/Object;
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
    at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
    at ...

This is just the first part of the tutorial for building a full stack web app in Kotlin so I'd like to work out of the tutorial or I am missing something.
Server code below but this is also copy and paste right out of the turorial and using the tutorial git repo

val shoppingList = mutableListOf(
    ShoppingListItem("Cucumbers ", 1),
    ShoppingListItem("Tomatoes ", 2),
    ShoppingListItem("Orange Juice ", 3)
)
fun main() {
    embeddedServer(Netty, 9090) {

        install(ContentNegotiation) {
            json()
        }
        install(CORS) {
            allowMethod(HttpMethod.Get)
            allowMethod(HttpMethod.Post)
            allowMethod(HttpMethod.Delete)
            anyHost()
        }
        install(Compression) {
            gzip()
        }
        routing {
            route(ShoppingListItem.path) {
                get {
                    call.respond(shoppingList)
                }
                post {
                    shoppingList += call.receive<ShoppingListItem>()
                    call.respond(HttpStatusCode.OK)
                }
                delete("/{id}") {
                    val id = call.parameters["id"]?.toInt() ?: error("Invalid delete request")
                    shoppingList.removeIf { it.id == id }
                    call.respond(HttpStatusCode.OK)
                }
            }
        }

        routing {
            get("/hello") {
                call.respondText("Hello, API!")
            }
        }
    }.start(wait = true)

A: This was because the main branch of the tutorial repo is out of date and needs its dependencies updated per this issue: https://github.com/kotlin-hands-on/jvm-js-fullstack/issues/21


text:
Q: EditText must not contain the < character My android app has an EditText field for email where user can give input.
But I'm trying to limit the options for that EditText so the user can just enter the allowed characters as email address.
So this is my code
<EditText
    android:id="@+id/sign_up_password_edit_text"
    style="@style/SignUpEditTextStyle"
    android:hint="@string/password"
    android:inputType="textPassword"
    android:digits="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 !#$%&'*+-/=?^_`{|}~ (),:;@[\]<>"
   />

but when trying to compile and run the project I'm getting this error:
Error:Execution failed for task ':app:mergeDebugResources'.

Error: The value of attribute "android:digits" associated with an element type "EditText" must not contain the '<' character

How can I fix that and include the '<' character?

A: You need to encode it like web urls.
In your case: use < for '<', > for '>'. For more info, take a look at this.

A: See xml special characters documentation here.

A: escape char on XML,
"   "
'   '
<   <
>   >
&   &

A: When you use wizards to customize any string in your XML file, you can use the following special symbols:
Symbol (name)                 Escape Sequence
< (less-than)  *********               < or <
> (greater-than) *********              > or  >
& (ampersand)    *********              &
' (apostrophe or single quote) *********   '
" (double-quote)  *********                "


text:
Q: PHP 8.1 Enum in laravel Enum case type int does not match enum backing type string I'm working in a Laravel 9 project, I have an Enum file called LoanPurpose and my loan purposes are integers. I'm storing these in my database as integers as this is what's required.
I now want to map them to a custom string to output to the view, but when I attempt to map them I get:

Enum case type int does not match enum backing type string

What am I missing?
<?php

namespace App\Enums\Applications\GB\Payday;

enum LoanPurpose: String
{
    case OTHER = 0;
    case GROCERIES = 1;

    public function label()
    {
        return match($this) {
            self::OTHER => 'Other',
            self::GROCERIES => 'Groceries'
        };
    }
}

*

*0 should be mapped to "Other"

*1 should be mapped to "Groceries"

A: Your backed enums values are all Int, but the type declaration in the enum definition is String
enum LoanPurpose: int
{
    case OTHER = 0;
    case GROCERIES = 1;

    public function label()
    {
        return match($this) {
            self::OTHER => 'Other',
            self::GROCERIES => 'Groceries'
        };
    }
}
$LoanPurpose = LoanPurpose::OTHER;
echo $LoanPurpose->label();//returns Other

Note the type declaration in the enum definition. It indicates that
all enum values are of a given type. You could also make it an int.
Take note that only int and string are allowed as enum values.
If you decide to assign enum values, all cases should have a value.
You cannot mix and match them.


text:
Q: Why does this `grep -o` fail, and how should I work around it? Given the input
echo abc123def | grep -o '[0-9]*'

On one computer (with GNU grep  2.5.4), this returns 123, and on another (with GNU grep 2.5.1) it returns the empty string. Is there some explanation for why grep 2.5.1 fails here, or is it just a bug? I'm using grep -o in this way in a bash script that I'd like to be able to run on different computers (which may have different versions of grep). Is there a "right way" to get consistent behavior?

A: Yes, 2.5.1's -o handling was buggy:
  http://www.mail-archive.com/bug-grep@gnu.org/msg00993.html
Grep is probably not the right tool for this; sed or tr or even perl might be better depending on what the actual task is.

A: you can use the shell. its faster
$ str=abc123def
$ echo ${str//[a-z]/}
123

A: I had the same issue and found that egrep was installed on that machine. A quick solution was using
 echo abc123def | egrep -o '[0-9]*'

A: This will give similar results:
echo abc123def | sed -n 's/[^0-9]*\([0-9]\+\).*/\1/p'

Your question is a near-duplicate of this one.

A: Because you are using a regex so you must use either:

*

*grep -E

*egrep (like Sebastian posted).

Good luck!


text:
Q: In Android, Cannot Refer to non-final Variable Counter The counter variable cannot be referred to in the public void onClick(View v) method, since it is defined in a different method. Below is the relevant code.
    Button button;
    final TextView message;
    int counter = 0;

    button = (Button) findViewById(R.id.button5);
    message = (TextView) findViewById(R.id.tv5);

    message.setText("Clicked " + 0 + " times.");

    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            counter++;
            message.setText("Clicked " + counter + " times.");

        }
    });

Are there any ideas as to how to fix this?
The reason I do not want to declare counter as a final variable is because I still want to change its value in the Onclick method.
Thank you.

A: As @Raghunandan referred the link Accessing Local Variables of the Enclosing Scope, and Declaring and Accessing Members of the Anonymous Class
it's described everything you needs. It's clearly describe that

An anonymous class cannot access local variables in its enclosing
  scope that are not declared as final or effectively final.

Basically click listener is an anonymous class. You can't use local non final variable here. If you want to change the variable scope you have to move it as a class variable. I guess it make sense to you.


text:
Q: Is it possible to clear objects with the get property after calling the class? this below to sample code;
    private ExampleStatus _status;

    public ExampleStatus status
    {
        get
        {
            if (_status == null) _status = new ExampleStatus();

            //if (_status.receivedData) _status.receivedData = false; //this line is incorrect !

            return _status;
        }
    }
    public class ExampleStatus
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool receivedData { get; set; }

        //I don't want to use this method
        public void Clear()
        {
            Id = 0;
            Name = string.Empty;
            receivedData = false;
        }
    }

    int stateType = 0;
    void ContinuousLoop(ExampleStatus statusObj)
    {
        while (true)
        {
            //I don't want to use the options below
            //statusObj.Clear();
            //or
            //statusObj = new ExampleStatus();

            if (stateType == 0)
            {
                statusObj.Id = 0;
                statusObj.Name = "Firs Status";
            }
            else if (stateType == 1)
            {
                statusObj.Id = 1;
                statusObj.Name = "Second Status";
                statusObj.receivedData = true;
            }
            else if (stateType == 2)
            {
                statusObj.Id = 2;
                statusObj.Name = "Third Status";
            }
        }
    }
    void RunThread()
    {
        var t1 = new Thread(() =>
          {
              ContinuousLoop(status);
          });
        t1.Start();
    }

Is it possible to set default values without a method or new instance, as shown in the example?
Actually that's why I'm asking this question:
I will use the class I have defined in many places. I will need to add a block of code, such as the Clear method, to every place I use it.
I'm also curious about one more thing. If I assign a new instance every time to reset my objects, does this cause problems in memory?
I know more or less how garbage collections work. However, they say that in practice it does not work as said in theory.
So if I add "IDisposable" to my Class, it would tell the garbage collector: Welcome, I'm a litter. Will you take me too?


text:
Q: Only in Live - Wildcard Custom Redirects not working (BVN 404 handler) I'm using the BVN 404 handler nuget package to do redirects in my episerver website.
I have a developer, staging and live enviroment.
One of the redirect rules I have is a wild card one. (Box checked)
so for example:
OLD URL: /uk/products/

Should go to the
NEW URL: /uk/services/

as I have the wild card box ticked
/uk/products/productname - Should also be redirected.
This is working in my developer and staging enviroments, but the WILD CARD is not working on our live website.
So on live you only get redirected if the URL is the exact match... So
/uk/products/

that will work and you are redirected. but it only half works in live becuase
/uk/products/productName

is not working in live but is working locally and in our staging enviroment.
I can't work out why, I have checked on the live server to make sure there are no other IIS re-write rules that may be conflicting, I have also made sure we have the same rules in both enviroments, but it still is not working.
Does anyone have any ideas about what could cuase this?
What other things can I check on live?
Any ideas?


text:
Q: Constructors and Inheritence I was wondering how to use a superclass constructor in a subclass but need to instantiate fewer attributes in the subclass. Below are the two classes. I'm not even sure if I'm doing things right currently. In the second class, there's an error that says "Implicit super constructor PropertyDB() is undefined. Must explicitly invoke another constructor." Note that this code is obviously incomplete and there is code that's commented out.
public abstract class PropertyDB {

private int hectares;

    private String crop;

    private int lotWidth;

    private int lotDepth;

    private int buildingCoverage;

    private int lakeFrontage;

    private int numBedrooms;

    private int listPrice;

    //public abstract int getPricePerArea();
    //public abstract int getPricePerBuildingArea();

    public PropertyDB(int newHectares, String newCrop, int newLotWidth, int newLotDepth,
            int newBuildingCoverage, int newLakeFrontage, int newNumBedrooms, int newListPrice){
        hectares = newHectares;
        crop = newCrop;
        lotWidth = newLotWidth;
        lotDepth = newLotDepth;
        buildingCoverage = newBuildingCoverage;
        lakeFrontage = newLakeFrontage;
        numBedrooms = newNumBedrooms;
        listPrice = newListPrice;
    }
}

public class FarmedLand extends PropertyDB{

    public FarmedLand(int newHectares, int newListPrice, String newCorn){
        //super(270, 100, "corn");

        hectares = newHectares;
        listPrice = newListPrice;
        corn = newCorn;
    }
}

A: implicit constructor PropertyDB() exists only if you do not define any other constructors, in which case you will have to explicitly define PropertyDB() constructor.
The reason you see this error "Implicit super constructor PropertyDB() is undefined. Must explicitly invoke another constructor." is that in your public FarmedLand(int newHectares, int newListPrice, String newCorn) constructor, super() is automatically called as the first statement, which does not exist in your superclass.
Here's a simplified example:
public class A { }

can be instantiated by using A a = new A() because public A() { } is an implicit constructor of class A.
public class A {
    public A(int z) { /* do nothing*/ }
}

can not be instantiated using A a = new A() because by defining an explicit constructor public A(int z) the implicit one is no longer available.
Moving onto constructors and inheritance, from Java Language Specification section 8.8.7:

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

So in your case the first statement executed in public FarmedLand(int newHectares, int newListPrice, String newCorn) constructor is an implicit call to super();, which in your case is not defined implicitly (there's already a public PropertyDB(int, String, ...) constructor defined) or explicitly (it's not in the source code)

A: When you have a derived class which extends a base class, the base class always gets constructed before the derived class. If you don't explicitly specify which constructor to use for the base class (like in your example), Java assumes you meant the parameterless constructor (in your case the PropertyDB() constructor).
But wait - PropertyDB doesn't have a parameterless constructor! So your only option is to use super so the Java compiler knows which constructor to call for the base class. In your case, there's only one constructor to choose from, so you have to use it with all 8 arguments. If you want to use less arguments, you either have to specify "default" values (like pass a 0), or else define more constructors for PropertyDB which take fewer arguments.

A: The error you're witnessing is due to the fact that the PropertyDB class doesn't have a default (no-arguments) constructor. Either create it in PropertyDB or call the existing superclass constructor PropertyDB(int newHectares, String newCrop, int newLotWidth, int newLotDepth, int newBuildingCoverage, int newLakeFrontage, int newNumBedrooms, int newListPrice) from the FarmedLand constructor using super.

A: Use super(newHectares, newCorn, 0, 0, 0, 0, newListPrice); instead. 0 is the default value of the int anyway.

A: Your superclass only has one constructor, so your subclass constructor must call it. There's no way around this: the superclass has (for example) a lotWidth field, so the subclass necessarily has that field, and the superclass initializes that field in its constructor, so it will necessarily be initialized in the subclass.
So, unless you modify the superclass in some way, you're going to have to call super(...) as the very first thing in the subclass constructor, specifying values for all its parameters.


text:
Q: Define default directory for keyboard-trigered screenshots in Ubuntu 18.04 Background
I want my screenshots to be saved in my ~/pictures/screenshots directory. I have then followed instructions of the selected answer of Default save directory for gnome-screenshot? — i.e., I've run:
gsettings set org.gnome.gnome-screenshot auto-save-directory "file:///home/$USER/pictures/screenshots"

Problem
When I take a screenshot using the Print Screen key of my keyboard, the .png file is still saved under ~/pictures. (I've checked with dconf GUI, and the setting is file:///home/$USER/pictures/screenshots.
In the comments of the aforementioned question, it is said:

Be aware that Gnome 3.8 doesn't use gnome-screenshot when using keyboard commands.

Question
How to make screenshots made using keyboard commands be saved in my customized ~/pictures/screenshots folder?


text:
Q: Kivy - Optimization For Hand-Helds (Android, IOS, etc) I'm always worried about optimization when it comes to game design and need to ask more experienced kivy users about some concerns.
Which one is truly faster?
Lets say you stored your graphic instructions in class attributes.  If you're going to have a number of graphics updating on the screen every frame, but you're not adding or taking away from the canvas, Ask_Update seems to be the qualified choice.
Lets say you do add and remove graphic pieces around enough.  Would it be better to just Clear the Canvas and canvas.add the stored instructions back?
or
Would it be better to call Clear after every removal or addition?  That would seem like a pain in the tail vs just Clearing and canvas.add the graphics back.
Vectors....
How optimized are Vectors?  Is the function/method a slow process?  Just wondering because I've used 3D engines in the past that had some slow calls and it's usually the mathematical ones.
What is considered a good frame rate for a game app running on a hand-held device?
I also wonder about deleting instances.  Does kivy have some special call for deleting an instance or would the usual del call (after running a cleanup function) and python garbage collection be enough?
I'm researching now because I don't want to develop something only to realize I wasn't aware of Kivy 'dos-and-donts'.

A: Clearing the canvas is inefficient, don't do that unless you actually want to remove everything.
You don't need to call ask_update in general.
Kivy's Vectors aren't particularly optimised, they're just wrappers around lists, but this probably isn't actually a problem for you.
A good framerate target is 60fps.
You can look at KivEnt for a game engine with particularly good performance with Kivy.


text:
Q: Message of the day (MOTD) not working in vagrant with Ubuntu 18.04 I can't get the message of the day to be displayed in my vagrant box and I wonder why.
I created a gist for a reproducible example here (it contains the Vagrantfile and the playbook.yml files).
Here's my Vagrantfile:
Vagrant.require_version ">= 2.2.3"

Vagrant.configure("2") do |config|
  config.vm.provider "virtualbox" do |v|
    v.memory = 2048
    v.cpus = 2
  end
  config.vm.box = "ubuntu/bionic64"
  config.vm.hostname = "cli-tools"
  config.vm.provision "ansible", type: "ansible" do |ansible|
    ansible.playbook = "playbook.yml"
  end

  config.ssh.extra_args = ["-t", "zsh; cd /home/vagrant"]
  config.ssh.forward_x11 = true
end

I provision my box with ansible, there I also create the /etc/update-motd.d/01-custom file.
The first line is #!/bin/sh.
The last line is exit 0.
Running sudo run-parts /etc/update-motd.d/ > /dev/null displays nothing (as expected).
Permissions are set as for the other scripts:
vagrant:~/ $ ls -la /etc/update-motd.d/
total 64
drwxr-xr-x  2 root root 4096 Aug 20 09:14 .
drwxr-xr-x 97 root root 4096 Aug 20 08:16 ..
-rwxr-xr-x  1 root root 1220 Apr  9  2018 00-header
-rwxr-xr-x  1 root root 2387 Aug 20 09:14 01-custom

My /etc/ssh/sshd_config contains the following settings:
...
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd yes
...

Pam configuration in /etc/pam.d/sshd:
...
# Print the message of the day upon successful login.
# This includes a dynamically generated part from /run/motd.dynamic
# and a static (admin-editable) part from /etc/motd.
session    optional     pam_motd.so  motd=/run/motd.dynamic
session    optional     pam_motd.so noupdate
...

Here's the playbook.yml
- hosts: all
  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes
      become: yes

    - name: Install zsh
      apt:
        name: zsh
        state: present
      become: yes

    - name: Check current shell
      shell: if echo $0 = "zsh" ; then echo "true"; else echo "false"; fi
      register: zsh

    - name: Change default shell to zsh
      shell: 'sudo chsh -s /bin/zsh vagrant'
      when: zsh.stdout == "false"

    - name: Check if Oh My Zsh is already installed
      shell: '[ -d "/home/vagrant/.oh-my-zsh" ] && echo "true" || echo "false"'
      register: ohmyzsh_present

    - name: Install Oh My Zsh (it can take several minutes to complete)
      shell: 'sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended'
      when: ohmyzsh_present.stdout == "false"

    - name: Check that the message of the day (motd) file.conf exists
      stat:
        path: /etc/update-motd.d/01-custom
      register: motd_custom

    - name: Create the message of the day (motd) file, if it doesnt exist already (/etc/update-motd.d/01-custom)
      file:
        path: /etc/update-motd.d/01-custom
        state: touch
        mode: 0755
        owner: root
        group: root
      become: yes
      become_user: root
      when: not motd_custom.stat.exists

    - name: Set message of the day (motd)
      blockinfile:
        path: /etc/update-motd.d/01-custom
        marker: ''
        block: |
          #!/bin/sh
          # System Overview
          echo "\033[33;1m\nSystem Overview\n\033[0m"
          /usr/bin/landscape-sysinfo

          # System Updates
          echo "\033[33;1m\nSystem Updates\n\033[0m"
          /usr/lib/update-notifier/apt-check --human-readable
          exit 0
      become: yes
      become_user: root
      when: not motd_custom.stat.exists

    - name: Remove blank lines blockinfile put in
      lineinfile :
        path: /etc/update-motd.d/01-custom
        state: absent
        regexp: '^$'
      become: yes
      become_user: root

    - name: update ssh config file to add the motd
      shell: 'sed -i "s/.*PrintMotd.*/PrintMotd yes/g" /etc/ssh/sshd_config && sudo service ssh restart'
      become: yes
      become_user: root
      when: not motd_custom.stat.exists

I use oh-my-zsh from within my box, could that be the issue there?
Globally speaking, I never got any "motd" displayed in vagrant.
What am I missing here?

A: You should run service motd-news restart or use the Ansible service module to restart motd-news after you add your motd file (or make any changes there).
FWIW You can also use the Ansible User module to set your user's shell to zsh instead of having to check what the current shell is. This will allow you to remove the shell check task.


text:
Q: How to send a message from an instance method to a object of another class I tried to search for an answer about this (simple) question but nothing seems to work well, even books are not so specific (atleast the books I've read), or probably I'm simply missing something important, since I'm a little bit confused I've decided to try here.
Here's the question:
Say that I have a ClassA which contains one or many instance variables.
Then I have a ClassB which contains an Instance Method that modify ClassA variable (is this possible right?) the classes have NOT inheritance from each other, both inherits from NSObject
Then I want to call the method of the ClassB over the ClassA object on the UIViewController. I believe I need a reference between classes but i'm not sure on how to set them to make them works. Imagine I have a Paper which contains writes or numbers (in this case numbers) and a class erase to modify it's variable and erase numbers (for example by subtracting).
here's some code:
Paper.h
@interface Paper : NSObject

@property (nonatomic) int numbers;

@end

Paper.m
#import "Paper.h"

@implementation Paper

@synthesize numbers;

@end

and Eraser.h
@interface Eraser : NSObject

-(void)eraseMethod;

@end

Eraser.m
#import "Eraser.h"

@implementation Eraser

-(void)eraseMethod {
//here I want to make a subtraction of the ivar declared in Paper
}

@end

and finally I'm trying to call it on the UIViewController like so
[paperObject eraseMethod];

I tried by declaring @class in each files as I've read somewhere but this won't help in any way... I hope this is clear as question

A: Ivars are just storage slots and they are private to the class when  without specifying access conditions.You can use property for the purpose of accessing from another class. more info here
in order to achive what you speak of,make the method a class method
see here
#import "Eraser.h"
@implementation Eraser

+(void)eraseMethod {
//here I want to make a subtraction of the ivar declared in Paper
}

@end

thus you can achieve the method in your VC.


text:
Q: formatting mysql data for ouptut into a table Following on from a question earlier today this answer was given to read the data into an array and separate it to print vehicle type and then some data for each vehicle.
<?php
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>

<?php echo $type?>

  <?php foreach ($rows as $vehicleData):?>

<?php echo $vehicleData['name'];?>

  <?php endforeach ?>

<?php endforeach ?>

This is almost perfect for what I want to do but I need to print out two columns from the database ie ford and mondeo before going into the second foreach loop. I've tried print $rows['model'] and all the other combinations I can think of but that doesn't work. Any help much appreciated

A: I'm a bit confused by your question but the SELECT * in the SQL statement means that every column from the database should be present as a key=>value pair in the $row array. So if you needed another "column," output here into an HTML list element
, you just echo (note: not "print") that column name as an array key. So if you needed the type of the car column found in a column with the name "model" you'd do this:
<?php
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>

<?php echo $type?>

  <?php foreach ($rows as $vehicleData):?>

<?php echo $vehicleData['name'];?>

<?php echo $vehicleData['model'];?>

  <?php endforeach ?>

<?php endforeach ?>

EDIT: I'm still unclear on your question, but if every car has the same vehicleType, and you're just looking to grab that once before looping through all the results, I'm guessing this will do it:
<?php
// Set up a SQL query to grab one row
$query_to_grab_only_vehicle_type = "SELECT vehicleType FROM apparatus WHERE 1 LIMIT 0,1";
// Fetch that row and turn it into an array
$vehicle_type_array = mysql_fetch_array(mysql_query($query_to_grab_only_vehicle_type));
// Initialize a variable with the array value that came from the vehicleType column
$vehicle_type = $vehicle_type_array['vehicleType'];
// You could uncomment and use the following to echo out the variable
// echo "Vehicle type: $vehicle_type";

$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>

<?php echo $type?>

  <?php foreach ($rows as $vehicleData):?>

<?php echo $vehicleData['name'];?>

<?php echo $vehicleData['model'];?>

  <?php endforeach ?>

<?php endforeach ?>


text:
Q: Java Writing to the Same txt File On Different Lines I dont have any worthwhile code to show but I am trying to understand the concept.
I am opening a text file in two classes, one time saves a username like "user242," and the other class saves a number "42421,". The way I have set this out it saves on different lines such as:
line: 1 - user242,
line: 2 -42421,
But every time I run the classes again it doesnt go in the format:
line: 1 - user242, user114,
line: 2 - 42421, 42525
It instead messes up and goes:
line: 1 - user242,
line: 2 - 42421, user114,
line: 3 - 4252
I think this is because of my use in newLine();
so is this any way I can fix this so it writes one variable always to the top line and the second always to the second line?

A: you can't insert data into a file. you can overwrite data using RandomAccessFile though. open the file, read the contents, modify and write them back.
you can also look at this Tutorial


text:
Q: Beginner Swift - Trouble changing UILabel.text to stored property in object Very basic question thanks for your help
Trying to change the text of a UILabel by referring to a stored property in object (jName), so you can change in future / add more names / labels, rather than just explicitly declaring firstName.text = "Joe Bloggs"
Don't understand why it won't let me change text to a stored property of jName? I tried initalising the properties but this didn't help either. Anyone know the best way to structure this?
class ViewController: UIViewController {

    @IBOutlet var firstName: UILabel!
    @IBOutlet var thirdName: UILabel!

    struct jName {

        var fName: String = "Joe"
        var lName: String = "Blogs"

        init(fName: String, lName: String) {
            self.fName = fName
            self.lName = lName
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        assignLabels()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func assignLabels() {

        firstName.text = jName.fName
        thirdName.text = jName.lName

    }
}

A: I am putting some code for hint i hope you will get an idea!
struct jName {

var fName: String = "Joe"
var lName: String = "Blogs"

init(fName: String, lName: String) {
    self.fName = fName
    self.lName = lName
}
}

let myname = jName.init(fName: "sanjeet", lName: "kumar")
let mystrng = myname.fName
print(mystrng)

A: First of all, since you are using struct, there is already a builtin constructor, so this part in your code is unnecessary if you're not puting a custom code on it:
init(fName: String, lName: String) {
    self.fName = fName
    self.lName = lName
}

It won't let you change the text because you didn't initialize the struct and you're trying to access its properties directly. You should instantiate the struct before using its properties:
func assignLabels() {
    let jNameStruct = jName(fName: "Joe", lName: "Blogs")
    firstName.text = jNameStruct.fName
    thirdName.text = jNameStruct.lName

}

The other option is to use the static modifier in your variables, so you'd be able to access the stored properties directly:
struct jName {

    static var fName: String = "Joe"
    static var lName: String = "Blogs"

    init(fName: String, lName: String) {
        self.fName = fName
        self.lName = lName
    }
}

A: Since you wrote a struct, you need to create a new instance of it before you can access its properties.
So put this line in your class:
var names = jName(fName: "Joe", lName: "Blogs")

The above line will create a new instance of jName. Now you can use the variable names to access the properties:
func assignLabels() {

    firstName.text = names.fName
    thirdName.text = names.lName

}

From the way you worded your question, I think what you really want is that the label's texts changes automatically when the values of names.fName and names.lName changes. To do this, you need to add property observers to the properties, and in the property observers, you set the label's text:
struct jName {

    var fName: String = "Joe" {
        willSet { firstName.text = newValue }
    }
    var lName: String = "Blogs" {
        willSet { thirdName.text = newValue }
    }

    init(fName: String, lName: String) {
        self.fName = fName
        self.lName = lName
    }
}


text:
Q: rmarkdown version 1.11 throws errors on existing prerendered files I have several learnr tutorials running on a shiny server. After updating rmarkdown to version 1.11 I get the following error message whenever there exists a prerendered HTML file:

Error in file.exists(dep$src$file) : invalid 'file' argument
Calls:  ... shiny_prerendered_html -> shiny_prerendered_prerender -> file.exists
Execution halted

Versions 1.9 and 1.10 work fine.
Any idea/help would be highly appreciated!
I did not manage to produce a short example - all partial files seem to work. A full file can be downloaded here

A: I also have the same problem, a very quick and dirty solution is to delete the index.html file before each new render, but hoping for a more structural solution.


text:
Q: For a linear transformation $f \colon V \to W$, $\dim \mathrm{Ker}\, f + \dim \mathrm{Im}\, f = \dim V$ I've found in my solution book multiple references to this "dimension theorem" but have been unlucky looking for a more extensive description of this. When does this hold? Are there any other hypothesis needed?
Thanks.

A: The Dimension Theorem is often called the "Rank Nullity Theorem", so you may have more luck finding it under that name.
The result holds for any linear transformation and vector spaces; it's not even restricted to finite dimensional spaces, so long as your sum is taken to be a sum of cardinals and you assume the Axiom of Choice (so that all vector spaces have bases).
The Dimension Theorem, aka Rank Nullity Theorem, states:
Dimension Theorem. If $\mathbf{V}$ and $\mathbf{W}$ are any vector spaces (over the same field), and $T$ is any linear transformation from $\mathbf{V}$ to $\mathbf{W}$, then
$\dim(\mathrm{ker} T) + \dim(\mathrm{Im} T) = \dim(\mathbf{V})$
where the sum is a sum of cardinals.
The idea is to start with a basis $\beta$ for $\mathrm{ker} T$, and then extend it to a basis $\beta\cup\gamma$ for all of $\mathbf{V}$. Then you show that the image of $\gamma$ under $T$ is linearly independent: if $\mathbf{v}_1,\ldots,\mathbf{v}_n\in\gamma$ are such that
$$\alpha_1T(\mathbf{v}_1)+\cdots\alpha_nT(\mathbf{v}_n) = \mathbf{0}$$
in $\mathbf{W}$, then you can rewrite this as
$$T(\alpha_1\mathbf{v}_1+\cdots+\alpha_n\mathbf{v}_n) = \mathbf{0}$$
hence $\alpha_1\mathbf{v}_1+\cdots+\alpha_n\mathbf{v}_n\in\mathrm{ker}(T)$. That means that this linear combination of vectors of $\gamma$ lies in the span of $\beta$, but since $\beta\cup\gamma$ is linearly independent, the only way this can happen is if $\alpha_1\mathbf{v}_1+\cdots+\alpha_n\mathbf{v}_n=\mathbf{0}$; this is a linear combination of vectors in $\gamma$, which is linearly independent, so $\alpha_1=\cdots=\alpha_n=0$. This proves that
$$T(\gamma) = \{T(\mathbf{v})\mid \mathbf{v}\in\gamma\}$$
is a linearly independent subset of $\mathbf{W}$. It is now easy to show that $\mathrm{Im}(T) = \mathrm{span}T(\beta\cup\gamma) = \mathrm{span}(T(\gamma))$, so that $\dim(\mathrm{Im}(T)) = |\gamma|$. So you have that
$$\dim\mathbf{V} = |\beta\cup\gamma| = |\beta|+|\gamma| = \dim(\mathrm{ker}\; T) + \dim(\mathrm{Im}\; T),$$
as desired.

A: No, there is no other hypothesis needed. In particular, the dimension of $V$ may be infinite.
See http://en.wikipedia.org/wiki/Rank-nullity_theorem


text:
Q: How do I extract characters from a file name in the Imagemagick convert command line I would like to modify the following command so that the date variables are populated from the filename.
Example: The 020299-INF-A-0922015.JPG should cause the year variable to have the value 2015.
command:
convert 020299-I*.jpg^
 -set filename:oldname "%t"^
 -set month "MM"^
 -set day "DD"^
 -set year "YYYY"^
 -fill red -density 180 -pointsize 60^
 -gravity south -annotate +0+0 "%t"^
 -gravity northwest -annotate +0+0 "%[month]/%[day]/%[year]"^
 .\annotated\%[filename:oldname].png

A: I've lost the will to live doing stupid Windows BATCH stuff, but you can do it something like this:
@echo off
REM Start with your filename
set f=020299-INF-A-0922015.JPG

REM Parse out last chunk, splitting on dashes and dots selecting 4th field
for /f "tokens=4 delims=-." %%a in ("%f%") do set chunk=%%a
echo.%chunk%

REM Take last 4 digits of "chunk" as year
set year=%chunk:~-4%
echo.%year%

REM Take first 2 characters of "chunk" as month
set month=%chunk:~0,2%
echo.%month%

REM Strip year off "chunk", leaving md=month and day part
set md=%chunk:~0,-4%
echo.%md%
REM Take last one or two characters of "md" as day
set day=%md:~2,2%
echo %day%

Output
09222015
2015
09
2

I worked out all the above using DOSTips.com.


text:
Q: Replace specific line in text file I want to replace a line, which has the word "truck_placement: " in it, but the problem is that it replaces the line with this word too: "my_truck_placement: ".
My question is, how I can make it so it ONLY replaces that specific word.
I couldn't find anything on the internet to it. Also I'm new to Python.
cordget = coordinatesentry.get()

    with open(save_file, "r") as f:
        data = f.read()

    data = re.sub(r"truck_placement: .*\n", r"truck_placement: %s\n" % cordget, data)

    with open(save_file, "w") as f:
        f.writelines(data)

Thanks in advance!

A: You can change your regular expression from truck_placement: .*\n to (?<!_)truck_placement: .*\n
Test it here.


text:
Q: Storage events not firing in iOS Safari I have two tabs in iOS Safari, both open to the same page. Both tabs have an event listener for the storage event on the window object, and both write to localstorage when the client clicks/taps/types.
In Internet Explorer the tab not being interacted with receives storage events, but not Safari (On Firefox and Chromium browsers I instead use the Broadcast Channel API for this). In addition, this code was previously tested on Safari (I'm afraid I cannot remember which version) and it worked.
I made sure no JavaScript errors are being thrown on the page, and that I wasn't testing in private browsing mode. Can anyone think of why storage events would simply stop firing?

A: At first I thought this was part of Tracking Prevention (which is still the case for a page and an iframe of the same page on a third-party page trying to communicate), but now I think this is actually a Safari bug.
If you need to communicate cross-tab in Safari, use a Service Worker. My preferred cross-tab setup, in order of preferred to fallback to least-preferred fallback:

*

*Use a BroadcastChannel if supported, as this is literally the use case they were designed for. Not supported by Safari or IE.

*Use the message events of a Service Worker. This is the only method that currently works in Safari, but waking up a Service Worker regularly isn't great. Note that Service Workers don't work in Firefox Private Browsing mode, so it's a good thing Firefox supports BroadcastChannel.

*Use storage events. This is the only cross-tab communication method available in Internet Explorer, but if you don't need to support IE (lucky you) then feel free to not fall back this far. Note that this doesn't work in Safari Private Browsing mode (setting a localStorage item throws an error). Also note that there's an IE localStorage bug that means that the storage event's newValue property is actually the oldValue, so you need to delete the localStorage value after setting it to trigger it twice with the second time having the correct value.

Also note that none of the above will let you communicate between a first-party and third-party context in Safari.


text:
Q: Unexpected data sorting result after filtering from parent and child node I have list of tree node metadataList Like below:
   [
  {
    "data": {
      "metadata": {
        "category": [
          "Csp"
        ]
      }
    },
    "children": [
      {
        "data": {
          "metadata": {
            "category": [
              "Csp"
            ]
          }
        },
        "children": [

        ]
      },
      {
        "data": {
          "metadata": {
            "category": [
              "Mpn"
            ]
          }
        },
        "children": [

        ]
      },
      {
        "data": {
          "metadata": {
            "category": [
              "Mpn"
            ]
          }
        },
        "children": [

        ]
      },
      {
        "data": {
          "metadata": {
            "category": [
              "Mpn"
            ]
          }
        },
        "children": [

        ]
      }
    ]
  },
  {
    "data": {
      "metadata": {
        "category": [
          "Isv"
        ]
      }
    },
    "children": [
      {
        "data": {
          "metadata": {
            "category": [
              "Isv"
            ]
          }
        },
        "children": [

        ]
      },
      {
        "data": {
          "metadata": {
            "category": [
              "Isv"
            ]
          }
        },
        "children": [

        ]
      }
    ]
  },
  {
    "data": {
      "metadata": {
        "category": [
          "Csp"
        ]
      }
    },
    "children": [
      {
        "data": {
          "metadata": {
            "category": [
              "Csp"
            ]
          }
        },
        "children": [

        ]
      }
    ]
  },
  {
    "data": {
      "metadata": {
        "category": [
          "Mpn"
        ]
      }
    },
    "children": [
      {
        "data": {
          "metadata": {
            "category": [
              "Mpn"
            ]
          }
        },
        "children": [

        ]
      },
      {
        "data": {
          "metadata": {
            "category": [
              "Mpn"
            ]
          }
        },
        "children": [

        ]
      },
      {
        "data": {
          "metadata": {
            "category": [
              "Mpn"
            ]
          }
        },
        "children": [

        ]
      },
      {
        "data": {
          "metadata": {
            "category": [
              "Csp"
            ]
          }
        },
        "children": [

        ]
      },
      {
        "data": {
          "metadata": {
            "category": [
              "Isv"
            ]
          }
        },
        "children": [

        ]
      }
    ]
  },
  {
    "data": {
      "metadata": {
        "category": [
          "Incentives"
        ]
      }
    },
    "children": [
      {
        "data": {
          "metadata": {
            "category": [
              "Incentives"
            ]
          }
        },
        "children": [

        ]
      }
    ]
  }
]

Which is a type of array of data and children collection it's class like below:
export default class CurrentTopicMetadataTreeNode {
    public data: CurrentTopicMetadata;
    public children: CurrentTopicMetadataTreeNode[];
}

export default class CurrentTopicMetadata {
    public id: string;
    public metadata: TopicMetadata

}

export class TopicMetadata {
    public category: Category[]

}

export enum Category {
    Csp = 'Csp',
    Mpn = 'Mpn',
    Incentives = 'Incentives',
    Referrals = 'Referrals',
    Isv = 'Isv',

}

What I am trying,  to filter list as data and children order as per category. Let say if filter by a category all data and children belongs to that category should come like below order.

But I am getting data like this order :

One Element On Array Problem Set:
Here in this array if I search with Csp Only data in root node which is Csp and data in children only has one data which contains Csp would be in array.
[{
    "data": {
      "metadata": {
        "category": [
          "Csp"
        ]

      }

    },
    "children": [
      {
        "data": {

          "metadata": {
            "category": [
              "Csp"
            ]

          }

        },
        "children": [

        ]
      },
      {
        "data": {

          "metadata": {
            "category": [
              "Mpn"
            ]
          }

        },
        "children": [

        ]
      },
      {
        "data": {

          "metadata": {
            "category": [
              "Mpn"
            ]
          }

        },
        "children": [

        ]
      },
      {
        "data": {

          "metadata": {
            "category": [
              "Mpn"
            ]

          }

        },
        "children": [

        ]
      }
    ]
  }]

Expected Output: So after filtered by Csp node should be look like this:
[
  {
    "data": {
      "metadata": {
        "category": [
          "Csp"
        ]
      }
    },
    "children": [
      {
        "data": {
          "metadata": {
            "category": [
              "Csp"
            ]
          }
        },
        "children": [

        ]
      }
    ]
  }
]

here is my code, where I am doing wrong?

// Rule 1 check parent metadata category whether be empty

// Rule 2 and 3
function find_in_children(children, parent_category) {
    children_has_same_category = []
    for(var i in children) {
        let child = children[i];
        if(child.children != undefined && child.children.length > 0 && child.data.metadata.category == parent_category) {
            children_has_same_category.push(child);
        }
    }
    if(children_has_same_category.length > 0) {
        return children_has_same_category
    } else {
        for(var i in children) {
            let child = children[i];
            return find_in_children(child.children, parent_category);
        }
    }
}

function check_object(object) {
    let parent_category = object.data.metadata.category[0];
    if(object.children != undefined && object.children.length > 0) {
        return {'data': object.data, 'children': find_in_children(object.children, parent_category)}
    } else {
        return {'data': object.data}
    }
}

function apply_rules(object) {
    // Rule 1 check parent metadata category whether be empty
    if(object.data.metadata.category.length > 0) {
        return {'data': object.data}
    } else {
        return check_object(object)
    }
}

 target = {
    value: 'Isv'
}
filtered_datas = []
for(var i in datas) {
    let data = datas[i];
    if(data.data.metadata.category.length > 0) {
        result = apply_rules(data)
        if(result.data.metadata.category[0] == target.value) {
            filtered_datas.push(result);
        }
    }
}

Here is the data sample and result: https://jsfiddle.net/faridkiron/b02cksL8/#&togetherjs=F7FK3fBULx

A: I have resolve above problem like below way:
const findMatchedChild = (nodeInList, type) => {
    const node = Object.assign({}, nodeInList)
    node.children = nodeInList.children
        .filter(child => child.data.metadata.category.includes(type))
        .map(child => findMatchedChild(child, type))
    return node
}

const cspList = findMatchedChild({ children: data }, 'Csp').children
console.log(JSON.stringify(cspList, null, 2));

Got the expected result.


text:
Q: Zoom effect to another view Can I, by using PHP make a zoom effect that will zoom in the part where I clicked and visually add a new view to that section? What I want is to have a background picture and some clickable areas, when user click on a specific clickable part, that part will zoom in to a certain degree and then display that part in enlarged view and also add another view upon it.
What I want is something similar to http://www.naranglardor.com (click on the blood stains(and no, I'm not in a satanic cult, that book is a fiction about something)).
Is this possible with PHP?
Thankful for tip or any direction towards approaching this.
Best regards,
Gabriel

A: No, you cannot achieve that with PHP.
PHP is a server-side scripting language, meaning that the code is executed on the server.
What you need to achieve such effects is a client-side language, like JavaScript better utilized through jQuery.
To point you into some sort of direction, you can check this links out:
Codrops Tutorials - Excellent for jQuery based animations and effects.
Learning jQuery - Tips and tricks with jQuery.


text:
Q: How do I Write Overlapping Question and Answer Pairs to New Files? I'll start this off by saying that I'm completely new to Python, and this class is the first Python class I've ever taken. I'm trying to complete an assignment and after days of trial and error, I still can't figure out how to answer this question properly. I've been given a text file called QA_Pairs.txt, and in it are question and answer pairs (so line 1 is a question, line 2 is the answer for that question, and so on for about 5000 lines). This is a portion of the file, for context:
"question Who escaped the persecution of House Stark?
answer Faceless Man
question What is Arya trained as at the House of Black and White in Braavos?
answer House Stark
question Who was the faceless man in Braavos?
answer Frey"
Some of the answers have been used to answer more than one question(for example, the answer "Tyrion" has been paired with several questions). So if the same answer or question is used more than once within the file, it should be written to the Overlapping.txt file, otherwise it should be written to unique_QA_pairs.txt.
For some more context, here is the exact way the question is written in my assignment:

*

*How many QA pairs in QA_Pairs.txt? Here (q1, a1) is a pair, where q stands for question, and a for answer.

*Are these pairs unique? For example: (q1, a1) (q1, a1) are identical and overlapping;
(q1, a1) (q1, a2) are overlapping, and (q1, a1) (q2, a1) are overlapping as well. If not
unique, find the overlapping pairs, and generate a unique_QA_Pairs.txt file and an
Overlapping.txt file. The format of unique_QA_Pairs.txt and Overlapping.txt are the
same as QA_Pairs.txt.

So my task is to create a function that takes the overlapping pairs ((q1, a1) and (q1,a2), for example)) and writes them to a new file called Overlapping.txt. All the unique pairs must be written to a new file called unique_QA_pairs.txt. Both files should have the same format as QA_Pairs.txt.
I've tried a bunch of different approaches but nothing seems to be working. This is the best I've got so far:
Overlapping_pairs()
file_object = "QA_Pairs.txt"

overlappedQ = []
overlappedA = []
uniqueQ = []
uniqueA =[]

with open(file_object, 'r') as file:
    i = 1
    for line in file:
        if line.startswith("question"):
            if (line[len("question"):] in uniqueQ):
                overlappedQ.append(line[len("question"):].rstrip("\n"))
                overlappedA.append(line[len("answer"):].rstrip("\n"))

            else:
                uniqueQ.append(line[len("question"):].rstrip("\n"))
        if line.startswith("answer"):
            if (line[len("answer"):] in uniqueA):
                overlappedQ.append(line[len("question"):].rstrip("\n"))
                overlappedA.append(line[len("answer"):].rstrip("\n"))
            else:
                uniqueA.append(line[len("answer"):].rstrip("/n"))

if (len(overlappedA) == 0 and len(overlappedQ) == 0):
    with open ("unique_QA_pairs.txt", "w") as f:
        f.write(uniqueQ[i])
        f.write(uniqueA[i])
        file.write("\n")
else:
    with open("Overlapping.txt", "w") as file:
        for i in range(len(overlappedA)):
            file.write(overlappedQ[i])
            file.write(overlappedA[i])
            file.write("\n")

if name == "main":
Overlapping_pairs()

I know it's not great, so if there are more concise ways to do this, feel free to let me know. Any help is appreciated!

A: One narrow problem is this block of code: the opened file handle is f but
your last write operation tries to use file:
with open ("unique_QA_pairs.txt", "w") as f:
    f.write(uniqueQ[i])
    f.write(uniqueA[i])
    file.write("\n")            # Raises an error.

I don't understand your description of the difference between the two output
files (Overlapping.txt vs unique_QA_pairs.txt), specifically what criteria
are supposed to be used to determine uniqueness. Just the question text, the
question and answer text, or something else?
So I'll focus on a few suggestions for an easier way to read the input data.
You current code is repetitive, with similar calls to rstrip() and len()
lurking in various if-else branches. None of that is needed. Similarly, your
code is complicated by the fact that you are storing the questions and answers
in separate lists. But the data are inherently related: each question pairs
with an answer. So, under most conditions, storing the data in a unified way
will make more sense. In this sketch, I'll use a list of (question, answer)
tuples. Finally, why bother removing the leading question and answer
prefixes on each line if the output files are supposed to have the same format?
Just leave the text alone for the most part.
def overlapping_pairs():
    # Read the Q-A pairs.
    with open('QA_Pairs.txt') as fh:
        pairs = []
        while True:
            q = next(fh, '').rstrip()
            a = next(fh, '').rstrip()
            if q:
                pairs.append((q, a))
            else:
                break

    # Usage illustration.
    for q, a in pairs:
        print(q)
        print(a)

if __name__ == '__main__':
    overlapping_pairs()

If you ultimately need to check for uniqueness of something, that list of
question-answer pairs will be easy to work with. Alternatively, you can retain
the core idea (store related questions and answers together, not apart) but
select a different data structure. For example, one might end up with a dict
keyed by the question text, where each value is a list of answers. That would
tell you which questions are unique (or non-unique) and each unique question
would be linked to all related answers.


text:
Q: How to extract labels.txt file from tflite file? I am trying to extract labels.txt file from coco_ssd_mobilenet_v1_1.0_quant.tflite but I don't know how to do it
output file should look like below :
apple
boy
bat
phone
like this but I can't be able to do it for using it in Kotlin android app development.
I am a beginner so sorry for my mistake.
Link of the Tensor flow file
Link of the docs

A: There is no easy way to  extract label file from a model(You can make use of debugger or model inspector's for the same) . The tensorflow lite file you have referred along with the labels can be found at Tensorflow's github . The path for the label is :

https://github.com/tensorflow/examples/blob/master/lite/examples/object_detection/android/app/src/main/assets/labelmap.txt

This are the labels for the which the model is trained for .


text:
Q: Recursive method counting How does this recursive integer method count the number of nodes in a linked list? How can a constant 1 be added to a memory address?
int length(Node *head) {
  if(head == nullptr)
    return 0;

  return 1 + length(head->link);
}

A: Note that length(head->link) is a function call. The function being called, length, returns an int. So 1 is not being added to a pointer; it is being added to an integer.


text:
Q: Using Cauchy's Integral Formula to compute an integral How do we compute the integral $\displaystyle \int_{|z|=2}{\frac{\,dz}{z^2+1}}$. My first thought was to factor the denominator. I get $z^2+1=(z+i)(z-i)$. Do we have to apply the Cauchy Integral Formula here? Would that be my next step that I should take?

A: Use partial fractions here. Doing so, will have our integrand as,
$$\frac{1}{z^2+1}=\frac{i/2}{z+i}-\frac{i/2}{z-i}$$
Now, as you mentioned, we could proceed with this by applying the Cauchy integral formula to $f(z)=1$. Therefore, we have
$$\frac{1}{2\pi i}\oint_{\mid z \mid = 2}\frac{1}{z^2+1}\,dz=\frac{i}{2}\left(\frac{1}{2\pi i}\right)\oint_{\mid z \mid = 2}\frac{1}{z+i}\,dz-\frac{i}{2}\left(\frac{1}{2\pi i}\right)\oint_{ \mid z \mid = 2}\frac{1}{z-1}\,dz=0$$

A: You can avoid using partial fractions this way.
This function that you have has two simple poles at $z=i$ and $z=-i$, both of which are inside the circle $|z| = 2$. Thus the integral is
$$\int_{|z|=2} \frac {1}{z^2+1}dz = 2\pi i \left( \text{Res}_i \frac {1}{z^2+1} +\text{Res}_{-i} \frac {1}{z^2+1}\right).$$
Now,
$$\text{Res}_i \frac {1}{z^2+1}  = \text{Res}_i \frac {\frac{1}{z+i}}{z-i} = \frac{1}{2i}$$and
$$\text{Res}_{-i} \frac {1}{z^2+1}  = \text{Res}_{-i} \frac {\frac{1}{z-i}}{z+i} = \frac{-1}{2i}.$$
What we have used here s the following:
If $g(z)$ has a simple pole at $z_0$, then
$$\text{Rez}_{z_0} \frac{f(z)}{g(z)} = \frac{f(z_0)}{g'(z_0)}.$$

A: You may want to follow these steps:
(1) Find out all the poles of the integrand.
(2) Check how many of these line inside the curve $|z| = 2$.
(3) Find the residue at every pole identified in step (2).
(4) Use the residue theorem to get your answer.

A: First write
$$
      \oint_{|z|=2}\frac{1}{z^2+1}dz=\oint_{|z-i|=1/2}h(z)\frac{1}{z-i}dz+\oint_{|z+i|=1/2}k(z)\frac{1}{z+i}dz
$$
where $h(z)=\frac{1}{z+i}$ is holomorphic on a neighborhood of $|z-i|\le 1/2$ and $k(z)=\frac{1}{z-i}$ is holomorphic on a neighborhood of $|z+i|\le 1/2$. Using Cauchy's integral formula, the above becomes
$$
              2\pi i h(i) + 2\pi i k(-i)=2\pi i\frac{1}{i+i}+2\pi i\frac{1}{-i-i}=0.
$$


text:
Q: write this line of jQuery in vanilla javascript Can someone help me write this line of jQuery in javascript. It applies a single rule of styling to a class.
$('.dataCard').css('visibilty', 'visible !important');

A: As !important doesn't apply when setting styles with javascript, it would be something like this
 var elems = document.querySelectorAll('.dataCard');

 for (var i=elems.length; i--;) {
      elems[i].style.visibility = 'visible';
 }

A: If you want to make a general purpose function that can replace what you had in jQuery, you could do this:
function setStyle(elemOrSelector, prop, val) {
    var items;
    if (typeof elemOrSelector === "string") {
        // run selector query
        items = document.querySelectorAll(elemOrSelector);
    } else if (elemOrSelector.nodeName) {
        // must be single DOM object
        items = [elemOrSelector];
    } else if (elemOrSelector.length)
        // must be an array or nodeList
        items = elemOrSelector;
    } else {
        // don't know what it is
        return;
    }
    for (var i = 0; i < items.length; i++) {
        items[i].style[prop] = val;
    }
}

setStyle('.dataCard', "visibility", "visible");

This general purpose function allows you to pass either a DOM element, an array like list of DOM elements or a selector string.

If you don't want the general purposeness, then you can just use this:
function setStyle(selector, prop, val) {
    var items = document.querySelectorAll(selector);
    for (var i = 0; i < items.length; i++) {
        items[i].style[prop] = val;
    }
}

setStyle('.dataCard', "visibility", "visible");


text:
Q: Infinity al inicializar una variable Buen día. Estoy tratando de realizar un código con funciones, me pide inicializar la variable est, y al inicializarla en 0, cuando corro el programa me aparece Infinity por la división en 0.
Esa variable se solicita al usuario entonces básicamente quiero que se guarde el valor que el usuario introduzca y se aplique el if.
public static void main(String[] args) {
       int nEstudiantes;
       double precioI=0, total;
       nEstudiantes=leerEst();
       precioI=calcularPrecio();
       total=precioI*nEstudiantes;
       System.out.println("Precio indiviual: $" + precioI);
       System.out.println("Total a pagar: $" + total);
    }
     public static double calcularPrecio(){
           double precio;
           int est;
           if (est>=100)
                 precio=65;
           else
                if(est>=50 && est<=99 )
                    precio=70;
                else
                    if( est>=30 && est<=49)
                        precio=95;
                    else
                    precio=4000.0/est;
                    return precio;
       }
       public static int leerEst(){
           int est;
         Scanner lector= new Scanner(System.in);
        System.out.println("Introduzca el número de estudiantes: ");
        est=lector.nextInt();
        return est;
}

     }

A: Que te parece si enviamos el parámetro en lugar de querer iniciar la variable est, porque al final nunca recibirá nada ya que no puede leer de otra función.
La acomodamos, de la siguiente manera.
public static void main (String[]args)
  {
    int nEstudiantes;
    double precioI = 0, total;
      nEstudiantes = leerEst ();
      precioI = calcularPrecio (nEstudiantes);
      total = precioI * nEstudiantes;
      System.out.println ("Precio indiviual: $" + precioI);
      System.out.println ("Total a pagar: $" + total);
  }
  public static double calcularPrecio (int est)
  {
    double precio;
    if (est >= 100)
      precio = 65;
    else if (est >= 50 && est <= 99)
      precio = 70;
    else if (est >= 30 && est <= 49)
      precio = 95;
    else
      precio = 4000.0 / est;
    return precio;
  }
  public static int leerEst ()
  {
    int est;
    Scanner lector = new Scanner (System.in);
    System.out.println ("Introduzca el nC:mero de estudiantes: ");
    est = lector.nextInt ();
    return est;
  }


text:
Q: Iterated Expecation of Conditional Expectation I'm trying to show that
$$
E[(Y- E[Y|X])(E[Y|X] - E[Y])] = 0.
$$
My attempt is as follows:
\begin{align*}
& E[(Y- E[Y|X])(E[Y|X] - E[Y])] \\
  &= E[YE[Y|X] - Y E[Y] - E[Y|X]^2 +E[Y|X]E[Y]]\\
  &= E[YE[Y|X]] - E[Y E[Y]] - E[E[Y|X]^2] +E[E[Y|X]E[Y]]\\
  &= E[E[Y|X]E[Y|X]] - E[E[Y|X] E[Y]]\\
  &\qquad - E[E[Y|X]^2] +E[E[Y|X]E[Y]]\\
  &= 0
\end{align*}
However, I seemed to have misused the law of iterated expectations when I set
$$
E[YE[Y|X]] = E[E[Y|X]E[Y|X]].
$$
How can I justify this? Or is it just wrong?

A: Note that $E[Y\mid X]$ is $\sigma(X)$-measurable, hence
$$ E[Y\mid X]^2 = E[YE[Y\mid X]\mid X] $$
giving
$$ E \bigl[E [Y \mid X]^2\bigr] = E\bigl[ E[YE[Y\mid X]\mid X] \bigr] = E\bigl[YE[Y\mid X]\bigr]. $$


text:
Q: notifyDataSetChanged(); for update list. When i typed in TextView the list is not change I created one adapter and i used Google Places API to show address.
I called notifyDataSetChanged(); to update the list.
But When i typed in TextView the list is not changed.
Adapter
    adapter = new SelectAddressAdapter(this,android.R.layout.simple_list_item_1, addressList);
    addressListView.setAdapter(adapter);

   addresseEditText.addTextChangedListener(new TextWatcher() {

               @Override
                public void run() {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {

                    GoogleAPIRequestHandler handler = new GoogleAPIRequestHandler();

                    String date= handler.execute(input).get();
                    addressList = new ArrayList<AddressList>();
                    JSONObject jsonObj = new JSONObject(date);

                    JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
                        for (int i = 0; i < predsJsonArray.length(); i++) {
                        AddressList a = new AddressList();
                        String addressJson = predsJsonArray.getJSONObject(i).toString();
                        a.Deserialize(addressJson);
                        addressList.add(a);
        }
        adapter.notifyDataSetChanged();;

A: Change
for (int i = 0; i < predsJsonArray.length(); i++) {
                        AddressList a = new AddressList();
                        String addressJson = predsJsonArray.getJSONObject(i).toString();
                        a.Deserialize(addressJson);
                        addressList.add(a);

To
for (int i = 0; i <= predsJsonArray.length(); i++) {
                      if(i<predsJsonArray.length())
                       {
                        AddressList a = new AddressList();
                        String addressJson = predsJsonArray.getJSONObject(i).toString();
                        a.Deserialize(addressJson);
                        addressList.add(a);
                     }
else
{
              adapter.notifyDataSetChanged();;
}

A: I think you need to implement methods of TextWatcher within you need to add the runOnUiThread method
       addresseEditText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            runOnUiThread(new Runnable() {

                    @Override
                    public void run() {

                GoogleAPIRequestHandler handler = new GoogleAPIRequestHandler();

                String date= handler.execute(input).get();
                addressList = new ArrayList<AddressList>();
                JSONObject jsonObj = new JSONObject(date);

                JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
                    for (int i = 0; i < predsJsonArray.length(); i++) {
                    AddressList a = new AddressList();
                    String addressJson = predsJsonArray.getJSONObject(i).toString();
                    a.Deserialize(addressJson);
                    addressList.add(a);
    }
    adapter.notifyDataSetChanged();
        }
    }
   }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub

        }
    });

A: *

*
private  void setAddressRecyclerView()   {
 adapter = new SelectAddressAdapter(this, android.R.layout.simple_list_item_1, addressList);
 addressListView.setAdapter(adapter);   }

*
private  void updateAddressList(ArrayList<String> updatedAddressList)   {
 this.addressList=updatedAddressList;notifyDataSetChanged(); }

*
private  void edtAddressTextWatcher()   {
 addresseEditText.addTextChangedListener(new TextWatcher() {
     @Override
     public void beforeTextChanged(CharSequence charSequence,  int i,
                                   int i1,
                                   int i2){}
     @Override
     public void onTextChanged(CharSequence charSequence,
                               int i,
                               int i1,
                               int i2)
     {
         try {
             getActivity().runOnUiThread(() -> {
                 if (adapter != null &&
                         addressList != null &&
                         addressList.size() > 0)
                 {
                     String input = charSequence.toString();
                     if (input.length() > 0)
                     {
                         Log.w(TAG, "TextWatcher-------" + charSequence);
                         GoogleAPIRequestHandler handler = new
                                 GoogleAPIRequestHandler();

                         String date= handler.execute(input).get();
                         addressList = new ArrayList<AddressList>();
                         JSONObject jsonObj = new JSONObject(date);

                         JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
                         for (int i = 0; i < predsJsonArray.length(); i++)  {
                             AddressList a = new AddressList();
                             String addressJson = predsJsonArray.getJSONObject(i).toString();
                             a.Deserialize(addressJson);
                             addressList.add(a);
                         }
                         adapter.updateAddressList(addressList);

                     }

                 }
             });
         } catch (Exception e) {
             Log.e(TAG, "Error----TextWatcher----onTextChanged()---" + charSequence.toString());
         }
     }

     @Override
     public void afterTextChanged(Editable editable) {}
 });


text:
Q: Filter for records that exist as foreign key in multiple table I have Django models set up like below.
class Person:
    first_name
    last_name
    # More_fields

class Service1:
    person(fk=Person)
    # Service1_specific_fields

class Service2:
    person(fk=Person)
    # Service2_specific_fields

class Service3:
    person(fk=Person)
    # Service3_specific_fields

# More_services

I'm trying to create an "advanced search" view that will allow users use checkboxes to query the Person model for records that have services matching the checked boxes.
E.g. If checkboxes for services 1, 2, and 3 are checked, results should only be of Persons that have all three services.
Currently it is set up to get all objects from all 3 services and compare them to one another. As expect, this is extremely slow.
What's a better approach for this?

A: What about:
( Person
  .objects
  .filter( service1__pk__isnull = False )
  .filter( service2__pk__isnull = False )
  . and so on

 )

You can use Q() to combine just checked  conditions.


text:
Q: .NET / EF: How do I get around the 'ambiguity problem' to create a query with a group by? I am using the latest version of .NET Core (.NET 5) and Entity Framework Core 6 (preview) to connect to a MySQL database. I am trying to use GroupBy to generate a group by query to execute on the DB server, as described here. Unfortunately, this fails to compile with the error

The call is ambiguous between the following methods or properties: 'System.Linq.Queryable.GroupBy<TSource, TKey>(System.Linq.IQueryable, System.Linq.Expressions.Expression<System.Func<TSource, TKey>>)' and 'System.Linq.AsyncEnumerable.GroupBy<TSource, TKey>(System.Collections.Generic.IAsyncEnumerable, System.Func<TSource, TKey>)

This error is related to LINQ and EF Core sharing the same methods, and is discussed in detail here. I have tried the suggested workaround of creating extension methods for each LINQ call, with the following code:
    {
        public static IQueryable<TEntity> Where<TEntity>(this Microsoft.EntityFrameworkCore.DbSet<TEntity> obj, System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate) where TEntity : class
        {
            return System.Linq.Queryable.Where(obj, predicate);
        }

        public static IQueryable<TResult> GroupBy<TSource, TKey, TElement, TResult>(
            this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, Expression<Func<TSource, TElement>> elementSelector, Expression<Func<TKey, IEnumerable<TElement>, TResult>> resultSelector)
        {
            return System.Linq.Queryable.GroupBy(source, keySelector, elementSelector, resultSelector);
        }

        public static IQueryable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector)
        {
            return System.Linq.Queryable.GroupBy(source, keySelector);
        }

    }

This fixes the issue with 'Where()', however the error remains for GroupBy(). Should I be using a different extension method to resolve this, or some other workaround? I cant use AsEnumerable() as this retrieves all records before performing the grouping.

A: Use .AsQueryable() on your DbSet<T> when IAsyncEnumerable<T> is not needed and visa versa to remove ambiguity:
dbContext.YourEntities
    .AsQueryable() // or .AsAsyncEnumerable()
    // ...
    .GroupBy(ye => ye.PropertyA);

Note this will not be an issue in EFCore 6


text:
Q: Power factor calculation of an offset sine wave across a non-ideal capacitor I got into a discussion with another student while we were studying and we couldn't come to a conclusion.
Assume you have a non-ideal capacitor with some ESR and leakage resistance. If you subject that non-ideal capacitor to an offset sine wave (AC voltage signal with a DC offset) and you wanted to calculated the real power, would you:

*

*Multiply the product of the offset RMS values of the offset voltage and current waveforms by cos(phase shift), or

*Multiply the product of the RMS values of JUST the AC waveforms (without the DC offset) by cos(phase shift) then add the DC power which you can calculate from knowing the ESR and leakage resistance?

A: In your example, the total loss dissipated in heat corresponds to the sum of individual losses in the resistors. You correctly calculate them with \$P_R=I_{rms}^2R\$ with \$R\$ the considered resistance and \$I\$ the current in the resistor. I simulated the below sketch with a 100-\$\Omega\$ resistance across the capacitor. The source delivers 10 V peak at a 1-kHz frequency with a 5-V offset.

You compute the average power - or the real power - by multiplying \$i_{in}(t)\$ and \$i_{tot}(t)\$ and average the result across a cycle. This always works regardless of the type of waveform or distortion. If you deal with sinusoidal signals, then you can involve \$cos\phi\$ applied to the ac component as you mentioned and deal with rms voltage and current.
The below simulation results show the instantaneous waveforms:

If I average the instantaneous power which is plotted in the low-side window, the simulator gives me 744 mW. The rms current flowing in resistor \$R_1\$ is 85.74 mA while in the 1-\$\Omega\$ resistance it is 96.4 mA: \$P_{avg}=85.74m^2\times 100 + 96.4m^2\times 1 = 735.1\;\rm mW + 9.3\;\rm mW = 744.4\;\rm mW\$ in line with the measurement (these numbers should be perfectly equal but you need to exactly position the measurement cursors to isolate a period).
If we now measure the rms ac components (without the dc offset) of the input current and voltage, we find \$V_{in,rms}=7.07\rm\;V\$ and \$I_{tot,rms}=82.7\rm\;mA\$. The phase shift is 31.6° which leads to an intermediate real power of \$V_{ac,rms}I_{ac,rms}\rm cos(\phi)= 498\rm\; mW\$. The dc current is the offset (5 V) divided by the total resistance (\$101\rm\; \Omega\$) and it amounts to 50 mA or 248 mW dissipated in the resistance. Sum 498 mW to 248 mW and you obtain 746 mW in line with what we found.

A:
you wanted to calculated the real power

You would add the powers. You would calculate the DC power and you would calculate the AC power and add the two together.


text:
Q: Generate QGIS maps automatic after updating an Access 2010 or Filemaker Pro 12 database I want to develop a database which consist an interaction with QGIS. After updating the data in the database I want to push on a button and start a process in QGIS. After finishing the process in QGIS I want to import the results in the database. Therefor I need or want to build an executable which starts a process in Python. The part in QGIS is already covered, but is it possible to start the processes in QGIS with an external executable? I have found information about starting an external executable from Python, but I want to do it the other way round. Has anyone experience with starting Python processes from an executable? And which executable can be recommended?
Thanks in advance.


text:
Q: forcing value of lambda inner scope variable to outer variable - python I have already found various answers to this question (eg. lambda function acessing outside variable) and all point to the same hack, namely (eg.) lambda n=i : n*2 with i a variable in the external scope of lambda (hoping I'm not misusing the term scope). However, this is not working and given that all answers I found are generally from couple of years ago, I thought that maybe this has been deprecated and only worked with older versions of python. Does anybody have an idea or suggestion on how to solve this?
SORRY, forgot the MWE
from inspect import getargspec
params = ['a','b']
def test(*args):
    return args[0]*args[1]

func = lambda p=params : test(p)

I expected the signature of func to be ['a','b'] but if I try
func(3,2)
I get a Type error (TypeError: <lambda>() takes at most 1 argument (2 given) )
and it's true signature (from getargspec(func)[0] ) is ['p']
In my real code the thing is more complicated. Shortly:
def fit(self, **kwargs):
        settings = self.synch()
        freepars = self.loglike.get_args()
        func = lambda p=freeparams : self.loglike(p)
        minuit = Minuit(func,**settings)

I need lambda because it's the only way I could think to create inplace a function object depending on a non-hardcoded list of variables (extracted via a method get_params() of the instance self.loglike). So func has to have the correct signature, to match the info inside the dict settings
The inspector gives ['p'] as argument of func, not the list of parameters which should go in loglike. Hope you can easily spot my mistake. Thank you

A: There's no way to do exactly what you want. The syntax you're trying to use to set the signature of the function you're creating doesn't do what you want. It instead sets a default value for the argument you've defined. Python's function syntax allows you to define a function that accepts an arbitrary number of arguments, but it doesn't let you define a function with argument names in a variable.
What you can do is accept *args (or **kwargs) and then do some processing on the value to match it up with a list of argument names. Here's an example where I turn positional arguments in a specific order into keyword arguments to be passed on to another function:
arg_names = ['a', 'b']

def foo(*args):
    if len(args) != len(arg_names):
        raise ValueError("wrong number of arguments passed to foo")

    args_by_name = dict(zip(arg_names, args))

    some_other_function(**args_by_name)

This example isn't terribly useful, but you could do more sophisticated processing on the args_by_name dict (e.g. combining it with another dict), which might be relevant to your actual use case.


text:
Q: Change the page search bar redirects to per Site My sys admin set up our SharePoint so there is basically one big site collection with many subsites run by many different people. Each site under the site collection has its own branding. When I search from my page it redirects to url/mysite/_layouts/OSSSearchResults.aspx? but which displays the search results in the master page of the top site in the site collection. I need this to show the search results in a page that matches my own site master page. Any advice?
UPDATE:
I found a way to change the search results page (see below).
I was able to accomplish this by replacing:
<SharePoint:DelegateControl ID="DelegateControl3" runat="server"
ControlId="SmallSearchInputBox" Version="4"/>

With the following in the Masterpage:
<SharePointWebControls:SearchBoxEx ID="SmallSearchBox" runat="server"
ShowAdvancedSearch="false" QueryPromptString="Enter Search Term…"
DropDownMode="HideDD_NoScope" SearchResultPageURL="mycustomsearchresults.aspx"
ScopeDisplayGroupName="" FrameType="None" DisplaySubmittedSearch="false" />

And then I added a Search Core Results Web Part to the mycustomsearchresults.aspx page to receive the query. It never returns anything but this is a separate problem that existed before I was tasked to brand.

A: You can change the search page by modifying the SRCH_TRAGET_RESULTS_PAGE property on each SPWeb. (And yes it's TRAGET :-( )
$web = Get-SPWeb http://www.address.com
$web.AllProperties["SRCH_TRAGET_RESULTS_PAGE"] = "URL of YOUR SEARCH RESULT PAGE"
$web.update()

A: It sounds like your overall topology doesn't match your needs.
Firstly, search settings are managed at the site collection level, and the page reference that states where results are displayed from a search is managed at that level (not at a subsite level). While you can do Per's suggestion to set each individual web property, as you pointed out, you don't have sufficient access as you'd need to physically login to the SharePoint box to access/set those properties.
Secondly, branding is typically managed at the site collection level. The only easy way to brand by subsite would be to assign it all in SharePoint Designer, which is far from a best practice. Following a best practice model, branding should be deployed as a SharePoint Solution (WSP file) generated by Visual Studio and activated on a Site Collection scope.
If you have a requirement of search results being targeted based on specific sites, and you want to deploy branding in any way that's at all manageable, you probably need to rethink your overall topology. There's many advantages to using Site Collections vs. Sites, specifically when we talk about scaleability and maintainability. As an example, a Site Collection cannot span multiple content databases, so with your current topology all of your content is forced to be in a single database (which potentially complicates DR, and other issues).

A: Instead of replacing the DelegateControl in the masterpage, I would leave it there and create web-scoped feature(s) that leverage this delegate. An example is below. You could have several different features with varying settings, then activate the desired one on each subsite. All with a single masterpage.
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Control Id="SmallSearchInputBox" Sequence="10"
           ControlAssembly="Microsoft.Office.Server.Search, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
           ControlClass="Microsoft.SharePoint.Portal.WebControls.SearchBoxEx">
    <Property Name="UseSiteDefaults">false</Property>
    <Property Name="UseSiteDropDownMode">false</Property>
    <Property Name="FrameType">None</Property>
    <Property Name="ShowAdvancedSearch">false</Property>
    <Property Name="DropDownModeEx">HideScopeDD</Property>
    <Property Name="SearchResultPageURL">/Search/results.aspx</Property>
    <Property Name="QueryPromptString">Enter Search term...</Property>
  </Control>
</Elements>

A: I found a way to change the search results page (see below).
I was able to accomplish this by replacing:
<SharePoint:DelegateControl ID="DelegateControl3" runat="server"
ControlId="SmallSearchInputBox" Version="4"/>

With the following in the Masterpage:
<SharePointWebControls:SearchBoxEx ID="SmallSearchBox" runat="server"
ShowAdvancedSearch="false" QueryPromptString="Enter Search Term…"
DropDownMode="HideDD_NoScope" SearchResultPageURL="mycustomsearchresults.aspx"
ScopeDisplayGroupName="" FrameType="None" DisplaySubmittedSearch="false" />

And then I added a Search Core Results Web Part to the mycustomsearchresults.aspx page to receive the query. It never returns anything but this is a separate problem that existed before I was tasked to brand.


text:
Q: Issue with fetch, response.json() I am trying to make an api call using fetch method in react-native.
I have rn-fetch-blob for uploading images in one screen which is on another different screen. This particular function was for me to initiate a payment online using paystack. though the issue is not about the paystack because this worked in a new project without having rn-fetch-blob in it.
Secondly if i remove response.json(),  it wouldn't return anything but there wouldn't be any error. but with response.json(), if get this error
attempt to invoke interface method 'java.lang.bridge.readablemap. getstring(java.lang.string)' on a null object reference.
I suspect there is a conflict between rn-fetch-blob and fetch because even without using rn-fetch-blob, it runs through perfectly, if i do
fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.movies;
    })
    .catch((error) => {
      console.error(error);
    })

same error comes
i expect a reference value like hyhjgbhgfh
attempt to invoke interface method 'java.lang.bridge.readablemap. getstring(java.lang.string)' on a null object reference.
I logged out response and i saw


text:
Q: JavaScript - how to inject different implementation of function e.g. alert (sharing modules with web & Node.js server side) Situation: There is big number of JavaScript files. I want to run them on Node.js.
But there are several places where e.g. alert() is used, that causes Node.js to fail.
Of course, there is way to look into every file and add import like
alert = require('console').log
but that would stop those files working inn browser (on client side).
Is there way to inject different implementation of alert? That is to change/add function implementation without modifying sources?

A: At the beginning of your code, write:
global.alert = console.log;

A: Basic version
Inside a file silentalert.js
if(typeof global != "undefined"){
  global.alert = typeof console != "undefined" && console.log ? console.log.bind(this) : function(){};
}

Inside your NodeJS scripts:
require('./silentalert');

This code will print alert messages to console.log in NodeJS but will still use alert when run in the browser.
The next implementation offers a more generic approach.

Cross-platform version
Inside a file silentalert.js
var g           = typeof global != "undefined" ? global : (typeof window != "undefined") ? window : {};
var c           = typeof console != "undefined" && console.log ? console.log.bind(this) : function(){};
var _old        = g.alert;
var silentalert = function(activate){
  g.alert       = activate ? c : _old;
};
if(typeof module !== "undefined"){module.exports = silentalert;}

Inside a NodeJS script:
var silentalert = require('./silentalert');
silentalert(true);
// or silentalert(typeof window == "undefined") if you just want to silent alert() on NodeJS
// your script...
silentalert(false);

You can even directly include silentalert.js inside an HTML page:
<script src="./silentalert.js" type="text/javascript"></script>
<script type="text/javascript">
silentalert(true);
// your script...
silentalert(false);
</script>

Note: If you need to support IE8 .bind won't be available in that case replace:
var c = typeof console != "undefined" && console.log ? console.log.bind(this) : function(){};

with
var c = typeof console != "undefined" && console.log ? function(){console.log.apply(console, arguments);} : function(){};

Both scripts allows you to silent alerts in NodeJS while still being able to use them on the client-side.