text:
Q: C++ Call function that is not defined yet I have this code. How do I do this without creating an error?
int function1() {
    if (somethingtrue) {
        function2();
    }
}

int function2() {
    //do stuff
    function1();
}

A: This is a case for a forward declaration.  A forward declaration tells the compiler that the name is going to exist, what it's type is and allows you to use it in a limited context before you define it.
int function2();  // this lets the compiler know that that function is going to exist

int function1() {
    if (somethingtrue) {
        function2(); // now the compiler know what this is
    }
}

int function2() { // this tells the compiler what it has to do now when it runs function2()
    //do stuff
    function1();
}

A: Use forward declaration. You can declare a function before using it by just writing its signature, followed by a semicolon. With that, you promise the compiler that there will be a function definition with the same signature somewhere else.
int function2();

int function1() {
    if (somethingtrue) {
        function2();
    }
}

int function2() {
    //do stuff
    function1();
}

A: Just put this above your functions:
int function1();
int function2();

But don't create an endless loop!
With that two lines you tell the compiler that function1 and function2 will be defined in the future. In bigger projects you would use header files. There you do the same but can use the functions in multiple files.
And also don't forget the return statement. I think your code example was only demonstration but I only want to mention it.
In C++ you must seperate declaration and definition.
Read more about it here: https://stackoverflow.com/a/1410632/4175009

A: Declare second function before first, so it can see it's existence.
int function2();

int function1() {
    if (somethingtrue) {
        function2();
    }
}

int function2() {
    //do stuff
    function1(); //beware of double recursion.
}

A: int function2();

int function1() {
    if (somethingtrue) {
        function2();
    }
}

int function2() {
    //do stuff
    function1();
}

This is called forward declaration. You let the compiler know there is a function called function2(), without defining it. This is enough for the compiler to insert a call to that function when it's called inside function1(), which is then resolved at link-time.

A: Forward declare function2().
int function2(); //forward declaration

int function1() {
    if (somethingtrue) {
        function2();
    }
}

int function2() {
    //do stuff
    function1();
}

A: This will solve your problem:
int function2();

int function1() {
    if (true) {
        function2();
    }
}

int function2() {
    //do stuff
    function1();
}

A: The usual way to do this is to first declare your functions.
The general convention is to put declaration in *.h file, and definition in *.cpp file.
And then include *.h file in *.cpp file.
That way you can use function1 and function2 in other files as well without repeating declaration. You just inlcude functions.h in that other file.
// functions.h
int function1();
int function2();

// functions.cpp
#include "functions.h"

int function1() {
    if (somethingtrue) {
        function2();
    }
}

int function2() {
    //do stuff
    function1();
}

However if you have a lot of functions and you want quick and dirty workaround you can do it like this:
class Root{public:

    int function1() {
        if (somethingtrue) {
            function2(); /// That will work now
        }
    }

    int function2() {
        //do stuff
        function1();
    }

    /// You can also put here variables, structs, classes, etc.
    /// and they will see each other regardless of order in code.

    /// But don't put main here
    /// it won't work

} root;

/// but now to call functoin1 or function2 from outside we need to use root
void main(){
    root.function1();
}

Root and root is just en example here. You can use any unused class name and variable name.


text:
Q: Can I run my full Ubuntu Unity desktop on my Windows machine using X? I am currently running Ubuntu 13 Desktop edition on a second PC on my desk, which has one small monitor. For work reasons my primary machine must be Windows(7), and it has multiple monitors, of varying resolutions.
I wish to have my Ubuntu Desktop fill up all those Windows monitors at their native resolutions so that I can basically make Ubuntu my primary desktop, without physically plugging in the keyboard and monitors into the Ubuntu box. Both machines are connected within a fire walled internal 1Gb network, and both have fixed IP addresses.
Nomachine NX is working pretty well up to now, but seems limited to aping the exact resolution of the (small) monitor I have on the Ubuntu box. VNC the same.
I do not wish to use a VM solution such as VMWare (though this does work), as I need more than one computer for reasons of data analysis throughput.
Is this possible? Is it viable? And how exactly do I go about it?
I have already downloaded and run MobaXterm, and running terminals over SSH seems to work fine. I have also run Firefox and other Ubuntu-machine applications in windows on my Windows machine, by calling them from the SSH terminal command line. But no luck so far getting the full Unity monty across my Windows monitors.

A: This post may be a bit dated, but the principal applies.
Intro to X Forwarding
Unix machines have been able to run software on a remote machine and display the GUI locally for almost two decades. Linux and Mac OS X support X Forwarding with no extra software. Any terminal on Linux should do X Forwarding, Mac users need to run "Applications > Utilities > XTerm". In a command line terminal run "ssh -Y jdoe@compute.example.edu matlab" and you'll be running matlab on "compute.example.edu" but seeing it on your desktop.
Windows users need two pieces of software: an secure shell program (ssh) to establish the remote connection and an X Server to handle the local display.
Prerequisites
Putty for SSH
Xming for the XServer
**Configuring Putty

*

*Add Unix hostname

*Switch Protocol to SSH

*Type name of session in saved sessions

*Click 'Save'

*Expand the 'SSH' tab from the 'Category' list

*Choose 'X11' from 'SSH' list

*Check 'Enable X11 Forwarding'

*Choose 'Session' from 'Category' list

*Click 'Save'

Starting the X Server on Windows
Configuring Xming
Just run "All Programs > Xming Xming" and it should work if you've got PuTTY configured.
Connecting

*

*Start Xming

*Start Putty

*Double click on the saved session you want

*Enter username and password as requested

*You should now be able to run X applications from the host on your local desktop

Source: Math.umn.edu

A: I'm not sure if you tried this already, but you could install Ubuntu within a VM  on Windows by using either VirtualBox or VMware. Then you can fire up the virtual machine on one screen, and use Ubuntu there while still being "physically" on Windows.

A: I can suggest you to use RDP beside VNC,since windows also natively support RDP
And there are FreeRDP or Remmina.But i'm not sure about it's multi monitor support.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Firebase Realtime Database Security Rules for prevent create/delete not working I saw in several places that the way to prevent create and delete was with data.exists() && newData.exists(). But when I implement them in these rules, I can still create and delete to my liking when I'm logged in. What am I doing wrong? My goal is to let authenticated users update, but not create or delete.
"rules": {
    "listings": {
      ".read": true,
      ".write": "data.exists() && newData.exists() && auth != null",
    },
}

A: My guess is that you want to allow the user to update a specific listing, and not all listings at once.
In that case you should define the .write rule on each specific listing:
"rules": {
    "listings": {
      ".read": true,
      "$listingid": {
        ".write": "data.exists() && newData.exists() && auth != null",
      }
    },
}

So with this, a user can update any existing listing, but not all listings at one.


text:
Q: Get ID3DXMesh from CDXUTSDKMesh In a DirectX 11 demo application, I use a CDXUTSDKMesh for my static geometry. It is loaded and already displayed.
I'm doing some experiments related to Precomputed Radiance Transfer in this application. The ID3DXPRTEngine would be a pretty handy tool for the job. Unfortunately, D3DX and DXUT don't seem to be very compatible there.
ID3DXPRTEngine requires a single ID3DXMesh (multiple meshes can be concatenated with D3DXConcatenateMeshes no problem). Is there an easy way to 'convert' CDXUTSDKMesh to one or multiple ID3DXMesh instances?

A: Short Answer: No.
Long answer: It can be done, but it requires that you be able to read the raw vertex data, convert it to the Direct3D 9 FVF system (the old fixed shader pipeline), and write the new data back.
Basically what you're trying to do is inter-operate two different versions of the Direct3D API: version 9.0 and version 11.0. In order to do this, you need to do the following:

*

*Confirm your verticies contain no custom semantics (i.e. D3D11 allows a semantic like RANDOM_EYE_VEC, whereas D3D9 does not).

*Confirm you have the ability to read your vertex and face information into a byte buffer (i.e. a char pointer).

*Create a Direct3D 9 Device and a Direct3D 11 device.

*Open your mesh, pull the data into a byte buffer, and create an ID3DXMesh object from that data. If you have more than 2^16 faces, you will need to split the mesh into two or more meshes.

*Create the PRT Engine from the mesh(es), and run your PRT calculations.

*Read the new information from the mesh(es) using ID3DXBaseMesh::GetVertexBuffer() (not sure if this step is entirely correct as I've never actually used the PRT engine).

*Write the new data back into the CDXUTSDKMesh.
As you may be able to tell, this process is long, prone to error, and very slow. If you're doing this for an offline tool, it may be OK, but if this is to be used in real time, you're probably better off writing your own PRT engine.
Additionally, if your mesh has any custom semantics (i.e. you use a shader that expects some data that wasn't a part of the D3D9 world) then this algorithm will fail. The PRT engine uses the fixed function pipeline, so any new meshes that take advantage of D3D11 features that didn't exist back then are not going to work here.


text:
Q: Comparing Object properties using reflection I have two classes Address and Employee as follows:
 public class Address
{
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

   public class Employee
    {
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public Address EmployeeAddress { get; set; }
    }

I have two employee instances as follows:
    var emp1Address = new Address();
    emp1Address.AddressLine1 = "Microsoft Corporation";
    emp1Address.AddressLine2 = "One Microsoft Way";
    emp1Address.City = "Redmond";
    emp1Address.State = "WA";
    emp1Address.Zip = "98052-6399";

    var emp1 = new Employee();
    emp1.FirstName = "Bill";
    emp1.LastName = "Gates";
    emp1.EmployeeAddress = emp1Address;

    var emp2Address = new Address();
    emp2Address.AddressLine1 = "Gates Foundation";
    emp2Address.AddressLine2 = "One Microsoft Way";
    emp2Address.City = "Redmond";
    emp2Address.State = "WA";
    emp2Address.Zip = "98052-6399";

    var emp2 = new Employee();
    emp2.FirstName = "Melinda";
    emp2.LastName = "Gates";
    emp2.EmployeeAddress = emp2Address;

Now how can I write a method which compares these two employees and returns the list of properties which have different values. So in this example I would like the result to be FirstName and Address.AddressLine1 .

A: You don't necessarily need reflection to perform the comparison. You can write a comparer class that takes two instances of Employee or Address, and compares each field that should match. For any that don't match, you can add a string (or PropertyInfo) element to some list to return to the caller.
Whether you return a PropertyInfo, MemberInfo, or just a string depends on what the caller needs to do with the result. If you actually need to visit the fields that contain differences, the PropertyInfo/MemberInfo may be better - but to just report the differences a string is probaby sufficient.
The main value of reflection would be to write a general purpose object comparer that could take two instances of any kind of object and compare their public fields and properties. This helps avoid writing repetetive comparison code over and over - but that doesn't seem like the case you're in.

A: Here is a generic and recursive solution based on Oskar Kjellin's awnser.
I have posted this code as gist as well, so you can check the latest version or star/clone/fork it :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

protected List<KeyValuePair<Type, PropertyInfo>> RecrusiveReflectionCompare<T>(T first, T second)
        where T : class
    {
        var differences = new List<KeyValuePair<Type, PropertyInfo>>();

        var parentType = first.GetType();

        void CompareObject(object obj1, object obj2, PropertyInfo info)
        {
            if (!obj1.Equals(obj2))
            {
                differences.Add(new KeyValuePair<Type, PropertyInfo>(parentType, info));
            }
        }

        foreach (PropertyInfo property in parentType.GetProperties())
        {
            object value1 = property.GetValue(first, null);
            object value2 = property.GetValue(second, null);

            if (property.PropertyType == typeof(string))
            {
                if (string.IsNullOrEmpty(value1 as string) != string.IsNullOrEmpty(value2 as string))
                {
                    CompareObject(value1, value2, property);
                }
            }
            else if (property.PropertyType.IsPrimitive)
            {
                CompareObject(value1, value2, property);
            }
            else
            {
                if (value1 == null && value2 == null)
                {
                    continue;
                }

                differences.Concat(RecrusiveReflectionCompare(value1, value2));
            }
        }
        return differences;
    }

A: Like LBushskin said, you do not have to do this. This is not the fastest way! Buy if you want, try this:
    public static List<PropertyInfo> GetDifferences(Employee test1, Employee test2)
    {
        List<PropertyInfo> differences = new List<PropertyInfo>();
        foreach (PropertyInfo property in test1.GetType().GetProperties())
        {
            object value1 = property.GetValue(test1, null);
            object value2 = property.GetValue(test2, null);
            if (!value1.Equals(value2))
            {
                differences.Add(property);
            }
        }
        return differences;
    }

A: No need for reflection. Of course, this example is returning a string with the property names...if you need the actual PropertyInfo object, things would get a little more difficult, but not by much.
public static IEnumerable<string> DiffEmployees
    (Employee one, Employee two)
{
    if(one.FirstName != two.FirstName)
        yield return "FirstName";
    if(one.LastName != two.LastName)
        yield return "LastName";
    if(one.Address.AddressLine1 != two.Address.AddressLine1)
        yield return "Address.AddressLine1";

    // And so on.
}

A: public IEnumerable<PropertyInfo> GetNotEqualsProperties(Employee emp1, Employee emp2)
{
    Type employeeType = typeof (Employee);
    var properies = employeeType.GetProperties();
    foreach (var property in properies)
        if(!property.GetValue(emp1, null).Equals(property.GetValue(emp2, null))) //TODO: check for null
            yield return property;
}

And for complex properties you have to override Equals method
public class Address
{
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }

    public override bool Equals(object obj)
    {
        if (obj as Address == null)
            return false;
        return ((Address) obj).AddressLine1.Equals(AddressLine1);
    }
}


text:
Q: Python code to convert a plt file into gcode with a specific format I'd like to convert a set of coordinates from one file format to another. It's for a drawing machine, like a plotter.
The first file is a plt file that looks like this:
PU-3410,7784;PD-3373,-2281;PU16705,7978;PD16435,5325; (continues for thousands of coordinates)
and I'd like to convert it to another text file which would have this format:
G01 X-3410 Y7784 Z1000
G01 X-3373 Y-2281 Z0
G01 X16705 Y7978 Z1000
G01 X-16435 Y5325 Z0
PU means Pen Up (=Z1000 in Gcode) and PD is pen down (Z0).
I'm very new to python, all I know is how to code for Arduino.
This piece of code would be so helpful. I've tried to understand how to open and write files but I'd too novice for this project so I thought I'd ask for help rather than give up.
Really appreciate any help!
Cheers,
Pierre

A: Disclaimer: This might not be perfect, but I think I worked it out.
# Uncomment this to read the file... remember to change your variable names too
# with open('input_filename', 'r') as file:
#    file_text = file.read()

sample_text = 'PU-3410,7784;PD-3373,-2281;PU16705,7978;PD16435,5325;'

coordinates = sample_text.split(';') # Splits the overall text into smaller easier chunks

with open('output_filename', 'a+') as output_file: # Create file handler for output file
    for c in coordinates:
        if c[:2] == 'PU': # Checks the value of the first two characters, and if it is PU, use Z1000
            g_code = 'Z1000'
        else: # Use Z0 otherwise
            g_code = 'Z0'
        c = c[2:] # chop off either PU or PD
        tokens = c.split(',') # Get the numbers
        if len(tokens) < 2: # if something isn't formatted right, exit.
            break
        output_file.write("G01 X{0} Y{1} {2}\n".format(tokens[0], tokens[1], g_code))

There are a few key assumption I made to take note of:
1) There are no formatting errors in the input file
2) All lines will begin with G01
3) I don't know the full specs so other things may be off


text:
Q: Why does podman stop the container why I try to attach to it? Just starting to learn containers so I probably have missed something / not read enough yet, but I have run into a strange behavior and am trying to understand what is happening. I tried googling but haven't been able to find an explanation so I can't tell if I am missing some concepts, running into a some limitation, or encountering a bug.
Basically, when I try to attach to a container, the container stops.
I'm on Fedora 33 using podman v3.1.2 installed from central repos and following the official "Getting Started" guide (here). I am running everything in user-mode (e.g. rootless).
A summary of the initial commands run from the guide:
$ podman pull docker.io/library/httpd >/dev/null
$ podman run -dt -p 8080:80/tcp docker.io/library/httpd
  48cf6fbe988a6feb243c62e5298b37f51709251cc05f8d39f17566e1d7fc17f7

$ podman ps
  CONTAINER ID  IMAGE                    COMMAND           CREATED         STATUS             PORTS                 NAMES
  48cf6fbe988a  docker.io/library/httpd  httpd-foreground  23 seconds ago  Up 22 seconds ago  0.0.0.0:8080->80/tcp  cool_cori

$ curl http://localhost:8080

It works!

$ podman stop -l
  48cf6fbe988a6feb243c62e5298b37f51709251cc05f8d39f17566e1d7fc17f7
$ podman rm -l
  48cf6fbe988a6feb243c62e5298b37f51709251cc05f8d39f17566e1d7fc17f7

So far so good. Now I was trying to move on from the guide just a little. I wanted to see if I could name the container and also attach to it and run a bash terminal from within the container. I skimmed through man podman-run and added the --name and --hostname parameters which seems to be fine. Also read through man podman-attach and it sounds like it should allow me to get a bash terminal in the container but when I use it, it stops the container.
$ podman run -dt --name "mycontainer" --hostname "testbox" -p 8081:80/tcp docker.io/library/httpd
  77e74e729ac0dd86ed5a58aa3481909148de9017ffc52b327f7e69f74da22549

$ curl http://localhost:8081

It works!

$ podman attach mycontainer

$ podman ps
  CONTAINER ID  IMAGE   COMMAND  CREATED  STATUS  PORTS   NAMES

$ podman start mycontainer

$ podman ps
  CONTAINER ID  IMAGE                    COMMAND           CREATED        STATUS            PORTS                 NAMES
  77e74e729ac0  docker.io/library/httpd  httpd-foreground  2 minutes ago  Up 8 seconds ago  0.0.0.0:8081->80/tcp  mycontainer

$ curl http://localhost:8081

It works!

$ podman attach mycontainer
  [Fri Jul 02 23:35:04.479855 2021] [mpm_event:notice] [pid 1:tid 140188888724608] AH00492: caught SIGWINCH, shutting down gracefully

So is this a bug? Otherwise, what am I doing wrong / why is it behaving this way? Apologies if this is something stupid due to gaps in my knowledge. Also not sure why it stops silently the first time I try attaching to it but it prints a message the next time.
I tried googling the error and got 3 results. One was in Chinese and the other 2 didn't look relevant to my situation. I also turned off SELinux via /etc/selinux/config and rebooted but that didn't make any difference.
Edit: also to clarify, I am using defaults. I have not done anything special for either podman, the image, or the container beyond what is shown in the commands. I do have the cockpit package installed as well but am not using it yet.

A: You are trying to get interactive control of the running process. As the container was run with the -t option, apache is attached to a terminal, something not meant to be for a daemon. Attaching to its terminal triggers a Window Change/Resize signal: SIGWINCH. Apache interprets this as the signal it reserves to be asked a graceful shutdown: container stops.
You should probably do this instead:

*

*run the daemon as a daemon (no -t)
podman run -d --name "mycontainer" --hostname "testbox" -p 8081:80/tcp docker.io/library/httpd

*replace podman attach with podman exec

NAME
podman-attach - Attach to a running container
[...]
DESCRIPTION The attach command allows you to attach to a running
container using the container's ID or name, either to view its ongoing
output or to control it interactively.

vs

NAME
podman-exec - Execute a command in a running container
[...]
DESCRIPTION
podman exec executes a command in a running container.

$ podman exec -it mycontainer bash
root@testbox:/usr/local/apache2# ps -ef
bash: ps: command not found
root@testbox:/usr/local/apache2# ls -l /proc/1/exe
lrwxrwxrwx 1 root root 0 Jul  3 11:50 /proc/1/exe -> /usr/local/apache2/bin/httpd
root@testbox:/usr/local/apache2#


text:
Q: SOAP web service call with NTLM auth not working C# I'm trying to do a SOAP web service call using NTLM authentication but it doesn't work.
I used the WSDL service.
What I did so far:
BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress address = new EndpointAddress("http://uri.test/");
_client = new TEST_PortClient(binding, address);

if (_client.ClientCredentials != null)
{
  _client.ClientCredentials.Windows.AllowNtlm = true; // this method is deprecated
  _client.ClientCredentials.Windows.ClientCredential.UserName = "username";
  _client.ClientCredentials.Windows.ClientCredential.Password = "password";
}
_client.Open(); // this works successfully
string message = string.Empty;
if (_client.TestConnection(ref message)) // this throw an exception *
{
  // do something
}

The exception thrown is:
The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'NTLM'.
What should I do to make it works?

A: I solved it in this way:
BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress address = new EndpointAddress(Uri);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

binding.MessageEncoding = WSMessageEncoding.Text;
binding.TextEncoding = Encoding.UTF8;
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;

_client = new TEST_PortClient(binding, address);

if (_client.ClientCredentials != null)
{
  _client.ClientCredentials.Windows.ClientCredential = new NetworkCredential("username", "password");
  _client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;

}
_client.Open();

string message = string.Empty;
if (_client.TestConnection(ref message))
{
  // do something
}


text:
Q: ComboBox auto close I'm using a combobox with a custom item renderer, each item containing a "delete" button to remove the corresponding item from the list. The problem is that when I click on this button, the combobox popup automatically closes, how can I force it to stay open when I click on the button ?
This is how is declared my ComboBox :
<s:ComboBox id="addressIn" width="150" height="23" skinClass="maincomponents.ServerAddressComboBoxSkin" dataProvider="{this._servers}" enabled="true" enabled.loading="false" />

The corresponding skin :
<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:fb="http://ns.adobe.com/flashbuilder/2009" alpha.disabled=".5">

    <fx:Metadata>
        <![CDATA[
        /**
        * @copy spark.skins.spark.ApplicationSkin#hostComponent
        */
        [HostComponent("spark.components.ComboBox")]
        ]]>
    </fx:Metadata>

    <s:states>
        <s:State name="normal" />
        <s:State name="open" />
        <s:State name="disabled" />
    </s:states>

    <s:PopUpAnchor id="popUp"  displayPopUp.normal="false" displayPopUp.open="true" includeIn="open"
                   left="0" right="0" top="0" bottom="0" itemDestructionPolicy="auto"
                   popUpPosition="below" popUpWidthMatchesAnchorWidth="true">

        <s:Group id="dropDown">

            <s:RectangularDropShadow id="dropShadow" blurX="20" blurY="20" alpha="0.45" distance="7"
                                     angle="90" color="#000000" left="0" top="0" right="0" bottom="0"/>

            <s:Rect id="border" left="0" right="0" top="0" bottom="0">
                <s:stroke>

                    <s:SolidColorStroke id="borderStroke" weight="1"/>
                </s:stroke>
            </s:Rect>

            <s:Rect id="background" left="1" right="1" top="1" bottom="1" >
                <s:fill>

                    <s:SolidColor id="bgFill" color="0xFFFFFF" />
                </s:fill>
            </s:Rect>

            <s:Scroller id="scroller" left="0" top="0" right="0" bottom="0" horizontalScrollPolicy="off" skinClass="fbcomponents.skinScrollSettingsDD">

                <s:DataGroup id="dataGroup" clipAndEnableScrolling="true" itemRenderer="maincomponents.DataList_ServerRepeatedItem">
                    <s:layout>
                        <s:VerticalLayout gap="0" horizontalAlign="contentJustify" requestedMinRowCount="1" requestedMaxRowCount="6"/>
                    </s:layout>
                </s:DataGroup>
            </s:Scroller>

        </s:Group>
    </s:PopUpAnchor>

    <s:Button id="openButton" width="20" right="0" top="0" bottom="0" focusEnabled="false"
              skinClass="maincomponents.ServerAddressComboBoxButtonSkin" tabEnabled="false" />

    <s:TextInput id="textInput" enabled.disabled="false"
                 left="0" right="19" top="0" bottom="0"
                 skinClass="maincomponents.ServerAddressComboBoxTextInputSkin"/>

</s:SparkSkin>

And the item renderer :
<s:ItemRenderer xmlns:s="library://ns.adobe.com/flex/spark"
                xmlns:fx="http://ns.adobe.com/mxml/2009"
                xmlns:fc="http://ns.adobe.com/flashcatalyst/2009"
                xmlns:ai="http://ns.adobe.com/ai/2009"
                xmlns:d="http://ns.adobe.com/fxg/2008/dt" dataChange="onDataChangeHandler(event)" valueCommit="adaptBg()"
                xmlns:flm="http://ns.adobe.com/flame/2008"
                minWidth="161" height="20" autoDrawBackground="false" fc:resizable="true">

    <fx:Script>
        <![CDATA[
            import mx.events.FlexEvent;
            import mx.events.StateChangeEvent;

            import spark.components.List;

            protected function onDataChangeHandler(event:FlexEvent):void
            {
                this.title.text = this.data as String;
                this.adaptBg();
            }

             protected function adaptBg():void
            {
                this.bg.color = (itemIndex % 2 == 0) ? 0xEFEFEF : 0xE0E0E0;
            }

        ]]>
    </fx:Script>

    <s:states>
        <s:State name="normal"/>
        <s:State name="hovered"/>
        <s:State name="selected"/>
    </s:states>
    <s:Rect x="0" y="0" width="161" height="20">
        <s:fill>
            <s:SolidColor id="bg" color="#EFEFEF"/>
        </s:fill>
    </s:Rect>
    <s:Rect x="0" y="0" width="161" height="20"
            visible.normal="false">
        <s:fill>
            <s:LinearGradient x="137" y="0" scaleX="31" rotation="90">
                <s:GradientEntry ratio="0" color="#FFEDD1"/>
                <s:GradientEntry ratio="0.5" color="#FFD180"/>
                <s:GradientEntry ratio="0.51" color="#EBAA1D"/>
                <s:GradientEntry ratio="1" color="#CF951A"/>
            </s:LinearGradient>
        </s:fill>
        <s:fill.hovered>
            <s:SolidColor alpha="0.24" color="#000000"/>
        </s:fill.hovered>
    </s:Rect>
    <s:Button x="5" y="2" width="20" height="16" buttonDown="trace('ok');" />
    <s:RichText id="title" d:id="103" d:userLabel="caldera0003" x="32" verticalCenter="1" ai:aa="2" color="#292929"
                columnCount="1" fontFamily="HelveticaNeueLT Pro 57 Cn" fontSize="14"
                kerning="on" tabStops="S36" flm:variant="34"
                whiteSpaceCollapse="preserve"/>
    <s:Rect width="274" height="31"
            visible="false" alpha.hovered="0.3"
            alpha.normal="0"
            alpha.selected="0.5">
        <s:fill>
            <s:SolidColor color="0xCED7EE"/>
        </s:fill>
    </s:Rect>
</s:ItemRenderer>

A: I've mentioned it in the comments, but you pointed out there is a difference with your situation. First read my answer to this question about adding a 'delete' button to DropDownList items: Create dropdownlist with delete button in this itemrenderer
There is only one thing you need to change from that code to get what you want, i.e. the popup must stay open when an item is removed. Go to the custom ItemRenderer, find the 'delete' Button tag and just prevent the event from propagating. If the event doesn't propagate, the DropDownList will never catch it and the popup will never close when the user clicks on the Button.
<s:Button verticalCenter="0" right="10" width="16" height="16"
          mouseDown="event.stopImmediatePropagation(); remove()" />

A: Maybe I'm understanding something wrong, but can't you just add mouseDown handler on your delete button and stop event propagation in it? Like
<s:Button x="5" y="2"
          width="20" height="16"
          mouseDown="button1_mouseDownHandler(event)" buttonDown="trace('ok');"
          />

and
protected function button1_mouseDownHandler(event:MouseEvent):void
{
    event.stopPropagation();
    ...
}

A: Maybe you should extend your combobox to stay open when it loses focus or closes? Pressing delete button causes focus lost event to your combobox.


text:
Q: How to reinstall Mac OS Leopard server without the original disc We just received a Mac Xserve (donated!) and now I have to find something to do with it.  There are personal files scattered all over and a bunch of services running, so I'd like to just reinstall from scratch, but we didn't get any discs with it.  And I can't find a place to download Leopard Server from Apple.
I've never installed Mac OS before. But it doesn't look like it uses product keys. So is there a way to reinstall it without the original disc?
The rest of our servers are running Ubuntu 10.04, so I'm also considering just torching Mac OS and installing Ubuntu.  However, then it looks like I would have to fiddle with EFI.

A: The only way to get the download for 10.5 or 10.6 server from Apple is to become member of the Mac Developer program, which will offer this as a resource. However, this is not free.
An alternative would be to use Lion and Lion server if you use an Intel based machine, which you can download from the Mac App Store. However, to get the download, you will need at least MacOS Snow Leopard, as the App Store is not available for earlier versions of the OS.
Re keys: MacOS Server is the only MacOS variant that uses product keys. You can (and should) get the key from the Server Admin application if you manage to get hands of an Install CD for Leopard Server.


text:
Q: Edit element's attribute in cinnamon.css I am a newbie.
I am trying to edit some Linux Mint theme effect.
I got the Mojave theme from here. By default, this sub menu is scrollable:

After mouse hovering:

So how can I expand it by default? Thank you and sorry for my ignorance.


text:
Q: Работа с JobIntentService в kotlin Как мне сделать так, чтобы выводилось сообщение так как это делают программы, когда например висят как сервис и оповещают о чем нибудь в уведомлениях? Я новичок в разработке для android и на kotlin. Я сделал рабочий пример, с тостами, но они не выводятся и я понимаю что не так делаю, но как надо правильно? вот код.
MainActivity.kt
package com.xverizex.service

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import com.xverizex.service.enqueueWork

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val intent = Intent(this, SimpleJobIntentService::class.java)
        enqueueWork(this, intent)

    }
}

SimpleJobIntentService.kt
package com.xverizex.service

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.ResultReceiver
import android.widget.ThemedSpinnerAdapter
import android.widget.Toast
import androidx.core.app.JobIntentService
val JOB_ID : Int = 1000;

fun enqueueWork(context: Context, work: Intent) {
    JobIntentService.enqueueWork(context, SimpleJobIntentService::class.java, JOB_ID, work)
}

class SimpleJobIntentService : JobIntentService() {

    override fun onHandleWork(intent: Intent) {
        toast ("Executing: back")
        for ( i in 0 .. 10 ){
            try {
                Thread.sleep(1000)
            } catch (ex : InterruptedException) {

            }
        }
        toast("end 10 seconds")
    }

    override fun onDestroy() {
        super.onDestroy()
        toast("All work complete")
    }

    var handler = Looper.getMainLooper()

    fun toast (text : CharSequence) {
        Looper.prepare()
        handler.run {
            Toast.makeText(this@SimpleJobIntentService, text, Toast.LENGTH_SHORT).show()
        }
        Looper.loop()
    }

}

Можно конечно распаковать apk какой нибудь программы, и посмотреть smali код, но это надо привыкнуть к этому коду и ещё найти то что нужно среди такой большой кучи кода.

A: Во 1:
Исправьте функцию:
fun toast (text : CharSequence) {
        Looper.prepare()
        handler.run {
            Toast.makeText(this@SimpleJobIntentService, text, Toast.LENGTH_SHORT)
        }
        Looper.loop()
    }

на:
fun toast (text : CharSequence) {
        Looper.prepare()
        handler.run {
            Toast.makeText(this@SimpleJobIntentService, text, Toast.LENGTH_SHORT).show()
        }
        Looper.loop()
    }

Во 2:
Прочитайте про жизненный цикл приложения на Android:
https://metanit.com/java/android/2.1.php


text:
Q: Excel VBA check cell color with Activecell.Interior.color not working I wish to check whether a cell has a certain color. If true, I want this message box ("Cell Match Color"). Otherwise, I wish to have Message box ("Cell does not match color.")
Option Explicit
Sub Autoselect()
    Dim Refcolor As Long
    Set Refcolor = RGB(220, 230, 241)
    If ActiveCell.Interior.Color = Refcolor Then MsgBox ("Cell Match
    Color") Else: MsgBox ("Cell does not match color")
End Sub

A: Just remove keyword Set when you assign value to variable Refcolor.
Set is used to assign objects to variable and you are assigning primitive value.
Sub Autoselect()
    Dim Refcolor As Long

    Refcolor = RGB(220, 230, 241)

    If ActiveCell.Interior.Color = Refcolor Then
        MsgBox ("Cell Match Color")
    Else
        MsgBox ("Cell does not match color")
    End If

End Sub


text:
Q: fit a sine curve to my data in python, matplotlib Here is my data in excel
I want to fit this data in a sine curve
here is my code,
#Fitting function
def func(x, offset, A, freq, phi):
    return offset + A * np.sin(freq * x + phi)

#Experimental x and y data points
# test_df is the input excel df
x_data = test_df['x_data']
y_data = test_df['y_data']

#Plot input data points
plt.plot(x_data, y_data, 'bo', label='experimental-data')

# Initial guess for the parameters
initial_guess = [.38, 2.3, .76, 2.77]

#Perform the curve-fit
popt, pcov = curve_fit(func, x_data, y_data, initial_guess)
print(popt)

#x values for the fitted function
x_fit = np.arange(0.0, 31, 0.01)

#Plot the fitted function
plt.plot(x_fit, func(x_fit, *popt), 'r')

plt.show()

This is the graph.

I think this is not the best fit. I would like to have suggestion to improve the curve fit.

A: Well, it does not seem to be a mathematical function, as for example for argument value 15 you may have multiple values (f(x) equals what?). Thus, it won't be a classical
interpolation in this case. If you could normalize the data somehow, ie make a function out of it, then you could use numpy.
Simplest approach would be to add some small disturbance where arguments' values are equal. Let's look at an example in your data:
4   0.0326
4   0.014
4   -0.0086
4   0.0067

So, as you can see, you can't tell what's the relation's value for f(4). If you'd disturb the arguments a bit, eg:
3.9     -0.0086
3.95    0.0067
4       0.014
4.05    0.0326

And so on for all such examples from your data file. Simplest approach would be to group these values by their x argument, sort and disturb.
That would obviously introduce some error, but, well...you are curve fitting anyway, right?
To formulate a sine, you have to know the amplitude, frequency and phase: f(x) = A * sin(F*x + p) where A is the amplitude, F is the frequency and p is the phase. Numpy has dedicated methods for this if you've got a proper data set prepared:
How do I fit a sine curve to my data with pylab and numpy?


text:
Q: Aplicativo Android e Banco de Dados MySQL Tenho um aplicativo desenvolvido em Android e preciso me conectar a um banco de dados MySQL que está local em um Desktop. Consigo facilmente o endereço de IP da máquina onde está o banco. Como posso efetuar a conexão entre o aplicativo e o banco MySQL local no Desktop sem a utilização de webservices?

A: Você pode fazer isso usando JODBC mysql e AsyncTask, fazendo conexão direta. Não esqueça de colocar o jodbc na pasta libs do seu projeto.


text:
Q: Star Trek book with a battle (ongoing in the story) that is so large it looks like a sun I am trying to find a Star Trek book where a battle is occurring. The battle is so big that it looks like the sun. The battle occurs at the end of the book

A: Are you talking about the novelization of Star Trek: Insurrection?
Chapter 13, page 279:

Picard closed his eyes, but for a blazing milli-second, it was like staring wide-eyed at a daytime sun...then the brightness dimmed....

It's not really that big of a battle though; this was just a struggle between Picard and Ru'afo.

A: The Voyager novel Ragnarok is about two races locked in combat - their weapons were underdeveloped compared to their shield technology, so the battle consisted of millions of ships pressing against one another until a ship's shields failed and it was crushed.
Voyager approached, mistaking it for a strange star based on the energy output, I believe.
After trying to determine the cause of the battle, of which both sides do not remember how it started, Voyager somehow gets involved (naturally) and finds a way to shift the frequency of their phasers to slice through the ships, destroying many on both sides of the conflict.
In the end, both sides agree to a cease fire to fight their new enemy, the Federation. The only problem is that their top speed was warp 1 or 2, so they won't be in Federation space for a thousand years.


text:
Q: The assembly is not strongly named or is not signed with the minimal key length while running .msi file I am registering dll in GAC. My dll is not strongly named.I have error like 'The assembly is not strongly named or is not signed with the minimal key length'. Is it compulsorily that the dll should be strongly typed? Or if any other option please suggest me.

A: Assemblies must be strong name signed (not strongly typed) with sn.exe before they can be installed in the GAC. sn.exe will generate a key file. In VS 2013 in the Properies of the Dll build there is a Signing option, just check the Sign the assembly box and browse to the file created by sn.exe (or in some cases use a standard snk file that your company uses for its assemblies).


text:
Q: Not recognize one menu item in Android I don't understand why in this case is not recongnizing my menu item.
I have another activities with similar code and it's working fine, but in this case i'm having NPE.
Layouts
General (activity_completas)
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.CompletasActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_breviario_general" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

content_breviario_general
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <include
        android:id="@+id/include"
        layout="@layout/tv_zoomable" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminate="true"
        app:layout_constraintBottom_toTopOf="@+id/include"
        app:layout_constraintEnd_toStartOf="@+id/include"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

</androidx.constraintlayout.widget.ConstraintLayout>

Menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".activities.BreviarioActivity">

<item
    android:id="@+id/item_voz"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:icon="@drawable/ic_play"
    android:visible="false"
    android:title="@string/leer"
    app:showAsAction="ifRoom" />
<item
    android:id="@+id/item_calendario"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:icon="@drawable/ic_calendar_toolbar"
    android:title="@string/all_calendar"
    app:showAsAction="ifRoom" />
</menu>

Java code
Relevant parts only for this case:
public class CompletasActivity extends AppCompatActivity {
    //...
    private Menu menu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_completas);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        showData();
    }

    private void showData() {
        sbReader = new StringBuilder();
        //I fill sbReader correctly
        if (sbReader.length()>0) {
            menu.findItem(R.id.item_voz).setVisible(true);  //******NPE here*******
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.menu = menu;
        getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case android.R.id.home:
                if (tts != null) {
                    tts.cerrar();
                }
                NavUtils.navigateUpFromSameTask(this);
                return true;

            case R.id.item_voz:
                String html = String.valueOf(Utils.fromHtml(sbReader.toString()));
                String[] textParts = html.split(SEPARADOR);
                tts = new TTS(getApplicationContext(), textParts);
                return true;

            case R.id.item_calendario:
                Intent i = new Intent(this, CalendarioActivity.class);
                startActivity(i);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (tts != null) {
            tts.cerrar();
        }
    }
}

Error

java.lang.NullPointerException: Attempt to invoke interface method
  'android.view.MenuItem android.view.Menu.findItem(int)' on a null
  object reference

I do the same thing in another activities and i don't have NEP. What's happening here?

A: You are getting null point exception because your menu isn't instantiated. As i can see, your are calling showData before creating the menu. Call showData in the onCreateMenu. This should solve your problem.


text:
Q: How do I override / add to the method_missing while maintaining searchlogic functionality? I want to add some behavior to my model when method_missing is thrown, but I know searchlogic already uses that for their named search scopes.
What is the proper way to extend method_missing functionality? Is there a way to react to a method_missing trigger? Much like how one would bind functions to events in javascript?

A: when you say you want something to happen when method missing is thrown, do you mean every time or just when search logic didn't find something? The former is quite simple:
def method_missing(name, *)
  if name =~ /foo/i
    # call your custom method
    # or for example define_method
  else
    # you do not want to handle the
    # method, so fall back to standard behavior
    super
  end
end

Where you replace name =~ /foo/i with a condition that checks whether you want to handle the missing method or not. The latter is not as easy. I can't answer it, because i do not know search logic, but you'd have to check whether search logic found something or not before calling your custom method.


text:
Q: MySQL Queries Running At Different Speeds I have a web system that i am migrating over to aws and most areas seem to be fine. There is one specific click on the web system that is extremely slow on aws side. I was able to locate the mysql query that gets executed in order to compare it to the old system and everything is the same, even the indexes. The query is below
select distinct cf_1274 from vtiger_cf_1274
inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_cf_1274.picklist_valueid
where roleid in ("H3","H4","H5","H51","H50","H49","H2") and picklistid in (select picklistid from vtiger_cf_1274)
order by sortid asc

The only difference i can see between the two is that the old mysql server version is 5.0.95 and the newer version is 5.6.X
I was also able to run an explain on both and this is where i saw differences. The newer system had a few "Using Join Buffer (Block Nested Loop)" on the extra column in the explain query where as the old one did not. Im assuming this must be the issue, but im not sure how to approach it.

A: Your query does not qualify what fields are coming from what table, at a minimum, you should even apply ALIAS to the query as I started here.
You are joining to the picklist table with the vtiger_cf_1274 table by the picklist value, so why not do a join on BOTH picklist value AND picklist ID.  This way, you can get rid of the IN ( select ) qualifier.
Also, I that becomes the new join criteria, I would have your role picklist table indexed on the (picklistvalueid, picklistid) to optimize the criteria..
Showing sample data context of these tables would help confirm / simplify / resolve your query.
select distinct
      cf_1274
   from
      vtiger_cf_1274 VT
         inner join vtiger_role2picklist PL
            on VT.picklist_valueid = PL.picklistvalueid
           AND VT.picklistid = PL.picklistID ???
   where
          roleid in ("H3","H4","H5","H51","H50","H49","H2")
   order by
      sortid asc


text:
Q: calendar with months and years without dates I need a calendar that shows only the months and years without the dates, because I am developing a web project for bus agencies, and it will have an option to show for every month for every agent how many tickets he sold and how much money he made! somehow like google adsense calendar where you pick the time or period. I am using an already made calendar but its with dates,months,years. Maybe there is a change to modify it to show only months and years but I am not good with javascripting at all! this is it:
http://www.softcomplex.com/products/tigra_calendar/docs/

My question is what would you recommend me to use or to do? is there any better way or tutorial to make this type of calendar or an already made calendar?
THANK YOU FOR YOUR TIME AND HELP.

A: Why dont you just  add loop for year and month drop down box (select option list), as you dont need date.That is the simplest way.
var year=1950
<select name='year'>
fo(i=year;i<2012:i++)
{
 <option value=i>i</option
}
</select>

var month=1
<select name='month'>
fo(i=month;i<=12:i++)
{
 <option value=i>i</option
}
</select>

you can do this in php loop and js validate or only js itself .your wish


text:
Q: A new project management algorithm wanted for finite number of workers I'm studying task-based parallel computing and got interested in a variation of the old project management problem -- the critical path of an activity-on-vertex (AOV) project network, which can be calculated using the topological sorting algorithm if there's no deadlock cycle. The total time of those activities on a critical path gives the minimum completion time of the project.
But this is assuming we always have enough workers simultaneously finishing the activities with no dependence on each other. If the number of workers (processors/cores) available is finite, certain activities can wait not because some activities they depend on have not yet been finished, but simply because all workers are now busy doing other activities. This is a simplified model for today's multi-core parallel computing. If there's only one worker who has to do all the activities, the project completion time is the total time of all activities. We are back to single-core serial computing that way.
Is there an efficient algorithm that gives the minimum completion time of an AOV network given a finite number of workers available? How should we wisely choose which activities to do first when the doable activities is more than the number of workers so as to minimize the idling time of workers later on? The minimum time should be somewhere in between the critical path time (infinite workers) and the total time of all activities (one worker). It should also be greater than equal to the total time divided by the number of workers (no idling). Is there an algorithm to get that minimum time?

A: I found a C++ conference video called "work stealing" that almost answers my question. At 18:40, the problem is said on the slide to be NP-hard if activities cannot be paused, further divided, or transferred from worker to worker. Such restrictions make decisions of which workers to finish which jobs (activities) too hard to make. Work stealing is therefore introduced to avoid making such difficult decisions beforehand. Instead, it makes such decions no longer crucial so long as certain apparent greedy rules are followed. The whole project will be always finished as soon as possible under the constraint of either the critical path or the no-idling time of the finite number of workers or both. The video then goes on talking about how to make the procedure of "work stealing" between different workers (processors) more efficient by making the implementation distributed and cache-friendly, etc.
According to the video, future C++ shared-memory parallel coding will be task-based rather than loop-based. To solve a problem, the programmer defines a bunch of tasks to finish and their dependence relations to respect, and then the coding language will automatically schedule the tasks on multiple cores at run time in a flexible way. This "event-driven"-like way of implementing a flexible code by a distributed task queuing system will become very useful in parallel computing.
When an optimization problem is NP-hard, the best way to solve it is to find ways to avoid it.


text:
Q: How to default a Person FormField in New Form Template? Without using any addons, has anyone discovered a way to set a default value for a <SharePoint:FormField> where the field is a Person/Group? We'd like to default a field on our newform to the current user and are finding that it's much more difficult than anticipated.
I believe once rendered the FormField is actually resolved into a <SharePoint:ClientPeoplePicker>. Due to inspecting the HTML rendered for both.
At the very least I thought I had the option to use <SharePoint:ClientPeoplePicker> but it looks like you can't assign a field to that control. Furthermore, you can't cast a FormField and I'm really looking to avoid having to use the CSOM people picker which I know how to populate but is several lines of code and a lot of effort for something I hoped would be so simple.
I've tried populating the item's field on several stages of my control's life-cycle, starting with OnInit. It looks like it gets set and I can write the value onto the form but it won't resolve in the FormField. Furthermore, if I set the value on OnInit the value won't even save to the item after pressing the Save button.
I've tried doing an system update to the field on the OnInit but afterwards I get an error if I try to save the form saying there was an invalid save (or something of the sort).
Edit: I've resorted to client-side and am very close. I'm using the code below:
ExecuteOrDelayUntilScriptLoaded(function () {
    setTimeout(function () {
        var ppDiv = $("[id$='ClientPeoplePicker'][title='Owner']");
        var ppEditor = ppDiv.find("[title='Owner']");
        var spPP = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv[0].id];

        ppEditor.val("domain\\user");
        spPP.AddUnresolvedUserFromEditor(true);
    }, 2000);
}, "clientpeoplepicker.js");

The above code works, but notice how I have to set a timeout. What happens is that SPClientPeoplePicker.SPClientPeoplePickerDict is not initialized directly after clientpeoplepicker.js is loaded. Now the question I'm looking for is how can I get an event kicked off once this array gets loaded? I don't want to use a timeout because if the time might vary due to client resources which at that point are out of my hand. There's also a race condition to take into consideration.

A: jQuery & SPServices (client side) are my preferred tools for this type of task:
    thisUserAccount = $().SPServices.SPGetCurrentUser({fieldName: "Name"});

    // Set the [PeopleColName] to be the Logged in user
    $().SPFindPeoplePicker({
        peoplePickerDisplayName: "PeopleColName",
        valueToSet: thisUserAccount
    });

A: I got this to work on NewForm.aspx by running the ExecuteOrDelayUntilScriptLoaded function after cui.js load, not clientpeoplepicker.js
So replacing the clientpeoplepicker.js with cui.js should help.
EDIT: we're currently using this fragment - the bigger whole, of which this is a fragment, runs in an ExecuteOrDelayUntilScriptLoaded(..., "core.js") function
    var val = "string with user names;or logins";
    var elem = editForm.find("div.sp-peoplepicker-topLevel");

    if (elem.length == 1) {
        function isIE() {
            var myNav = navigator.userAgent.toLowerCase();
            return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
        }
        function ppHandler() {
            var ppdiv = elem;
            var ppinst = SPClientPeoplePicker.SPClientPeoplePickerDict[ppdiv[0].id];
            var ppinput = ppdiv.find(".sp-peoplepicker-editorInput");
            var splitUsers = val.split(";");
            for (var i=0; i < splitUsers.length; i++) {
                ppinput.val(splitUsers[i]);
                ppinst.AddUnresolvedUserFromEditor(true);
            }
            ppdiv.find('.sp-peoplepicker-delImage').css('display', 'none');

        }
        if (isIE() > 9) {
            setTimeout(ppHandler, 2000);
        } else {
            $(window).load(ppHandler);
        }
        return;
    }

A: function SetAndResolvePeoplePicker(fieldName, userAccountName) {

var controlName = fieldName;

var peoplePickerDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']");

var peoplePickerEditor = peoplePickerDiv.find("[title='" + controlName + "']");

var spPeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerDiv[0].id];

peoplePickerEditor.val(userAccountName);

spPeoplePicker.AddUnresolvedUserFromEditor(true);

//disable the field

spPeoplePicker.SetEnabledState(false);

//hide the delete/remove use image from the people picker

$('.sp-peoplepicker-delImage').css('display','none');

}

Click Here More Details


text:
Q: How can i group the elements by key and append the values for that particular key using javascript? I have a requirement to group the elements by key and append the values for that particular key using JavaScript . Below is the actual and expected data. Can anyone please help me to fix it ?
Actual
[
    {
        "num": 152332,
        "subReport": "HS_ONE"
    },
    {
        "num": 152332,
        "subReport": "HS_TWO"
    },
    {
        "num": 152331,
        "subReport": "HS_THREE"
    },
    {
        "num": 152331,
        "subReport": "HS_FOUR"
    }
]

Expected
[
    {
        "num": 152332,
        "subReport": "HS_ONE,HS_TWO"
    },
    {
        "num": 152331,
        "subReport": "HS_THREE,HS_FOUR"
    }
]

A: You can use Map and reduce

let data = [{"num": 152332,"subReport": "HS_BIT"},{"num": 152332,"subReport": "HS_LOG"},{"num": 152331,"subReport": "HS_LOG"},{"num": 152331,"subReport": "HS_GENERAL"}]

let final = data.reduce((op,{num,subReport})=>{
  op.set(num, op.get(num) && (op.get(num) + ',' + subReport) ||  subReport)
  return op
},new Map())

let output = [...final].map(([num,subReport])=>({num,subReport}))

console.log(output)

A: You can do:

const data = [{"num": 152332,"subReport": "HS_ONE"},{"num": 152332,"subReport": "HS_TWO"},{"num": 152331,"subReport": "HS_THREE"},{"num": 152331,"subReport": "HS_FOUR"}];
const obj = data.reduce((a, {num, subReport}) => (a[num] = a[num] ? [...a[num], subReport] : [subReport], a), {});
const result = Object.keys(obj).map(k => ({ num: k, subReport: obj[k].join(', ') }));

console.log(result);

A: You can simply loop the array and create a custom Object data structure with unique key on num. Then, get the values of the object to make the final array as expected:

var arr = [{
    "num": 152332,
    "subReport": "HS_BIT"
  },
  {
    "num": 152332,
    "subReport": "HS_LOG"
  },
  {
    "num": 152331,
    "subReport": "HS_LOG"
  },
  {
    "num": 152331,
    "subReport": "HS_GENERAL"
  }
];
let resObj = {};
arr.forEach((obj) => {
  if (resObj[obj.num]) {
    resObj[obj.num].subReport += ', ' + obj.subReport
  } else {
    resObj[obj.num] = obj;
  }
});
var resArray = Object.values(resObj);
console.log(resArray);

This approach is also better for array with large size as the complexity is only O(n) which is more when we use reduce().

A: You can use reduce with find:

const arr = [
  { num: 152332, subReport: 'HS_BIT' },
  { num: 152332, subReport: 'HS_LOG' },
  { num: 152331, subReport: 'HS_LOG' },
  { num: 152331, subReport: 'HS_GENERAL' }
]

const out = arr.reduce((a, o) => {
  const item = a.find(i => i.num === o.num)
  item ? (item.subReport = `${item.subReport},${o.subReport}`) : a.push(o)
  return a
}, [])

console.log(out)

However, this will result in a time complexity of O(n2). Using a map will help reduce this to O(n):

const arr = [
  { num: 152332, subReport: 'HS_BIT' },
  { num: 152332, subReport: 'HS_LOG' },
  { num: 152331, subReport: 'HS_LOG' },
  { num: 152331, subReport: 'HS_GENERAL' }
]
const map = new Map([])
const out = arr.reduce((a, o, i) => {
  const num = map.get(o.num)
  num + 1 ? a[num].subReport = `${a[num].subReport},${o.subReport}` : map.set(o.num, a.push(o) - 1)
  return a
}, [])

console.log(out)


text:
Q: Is there any API in GCP to get the resource usage details..? I am looking for some API's in GCP that can fetch the usage of resource in terms of usage hours, storage usage etc

A: If you are interested in obtaining the information about the use of Compute Engine resources so that correlate actual consumption with billing, you can use on the resource usage reports.
Once you set it up, usage reports will be delivered into a preconfigured Cloud Storage Bucket. There are two types of reports that are generated on a regular basis:

*

*Daily usage reports

*Monthly rollup report

The supported metrics cover resources in question:

*

*Virtual machines

*Persistent disks

*Images

*Snapshots

*Static IP addresses

*Load balancers

The generated reports contain quantity of consumed resources measured in units (count, seconds, hours, etc) specific for a resource type.
You can manage the usage reports feature with Cloud Console, gcloud and API.
Please see Compute Engine > Doc > Viewing usage reports for more details.


text:
Q: ROLLBACK event triggers in postgresql I know it may sound odd but is there any way I can call my trigger on ROLLBACK event in a table? I was going through postgresql triggers documentation, there are events only for CREATE, UPDATE, DELETE and INSERT on table.
My requirement is on transaction ROLLBACK my trigger will select last_id from a table and reset table sequence with value = last_id + 1; in short I want to preserve sequence values on rollback.
Any kind of ideas and feed back will be appreciated guys!

A: You can't use a sequence for this. You need a single serialization point through which all inserts have to go - otherwise the "gapless" attribute can not be guaranteed. You also need to make sure that no rows will ever be deleted from that table.
The serialization also means that only a single transaction can insert rows into that table - all other inserts have to wait until the "previous" insert has been committed or rolled back.
One pattern how this can be implemented is to have a table where the the "sequence" numbers are stored. Let's assume we need this for invoice numbers which have to be gapless for legal reasons.
So we first create the table to hold the "current value":
create table slow_sequence
(
  seq_name        varchar(100) not null primary key,
  current_value   integer not null default 0
);

-- create a "sequence" for invoices
insert into slow_sequence values ('invoice');

Now we need a function that will generate the next number but that guarantees that no two transactions can obtain the next number at the same time.
create or replace function next_number(p_seq_name text)
  returns integer
as
$$
  update slow_sequence
     set current_value = current_value + 1
  where seq_name = p_seq_name
  returning current_value;
$$
language sql;

The function will increment the counter and return the incremented value as a result. Due to the update the row for the sequence is now locked and no other transaction can update that value. If the calling transaction is rolled back, so is the update to the sequence counter. If it is committed, the new value is persisted.
To ensure that every transaction uses the function, a trigger should be created.
Create the table in question:
create table invoice
(
  invoice_number integer not null primary key,
  customer_id    integer not null,
  due_date       date not null
);

Now create the trigger function and the trigger:
create or replace function f_invoice_trigger()
  returns trigger
as
$$
begin
  -- the number is assigned unconditionally so that this can't
  -- be prevented by supplying a specific number
  new.invoice_number := next_number('invoice');
  return new;
end;
$$
language plpgsql;

create trigger invoice_trigger
  before insert on invoice
  for each row
  execute procedure f_invoice_trigger();

Now if one transaction does this:
insert into invoice (customer_id, due_date)
values (42, date '2015-12-01');

The new number is generated. A second transaction then needs to wait until the first insert is committed or rolled back.

As I said: this solution is not scalable. Not at all. It will slow down your application massively if there are a lot of inserts into that table. But you can't have both: a scalable and correct implementation of a gapless sequence.
I'm also pretty sure that there are edge case that are not covered by the above code. So it's pretty likely that you can still wind up with gaps.


text:
Q: InfoWindow shouldFocus in Jquery not working Where and how should I add InfoWindow.open({anchor: marker, shouldFocus: false}); so that the browser doesn't focus on the Google Map embedded on the web page?
I have seen plenty of examples in plain JS, but I can't get any of them to work with this existing jquery code.
I keep trying, but cannot figure it out.
    ! function(e) {
    e.fn.gMap = function(o, a) {
        switch (o) {
            case "addMarker":
                return e(this).trigger("gMap.addMarker", [a.latitude, a.longitude, a.content, a.icon, a.popup]);
            case "centerAt":
                return e(this).trigger("gMap.centerAt", [a.latitude, a.longitude, a.zoom]);
            case "clearMarkers":
                return e(this).trigger("gMap.clearMarkers")
        }
        var n = e.extend({}, e.fn.gMap.defaults, o);
        return this.each(function() {
            var o = new google.maps.Map(this);
            e(this).data("gMap.reference", o);
            var a = new google.maps.Geocoder;
            n.address ? a.geocode({
                address: n.address
            }, function(e) {
                e && e.length && o.setCenter(e[0].geometry.location)
            }) : n.latitude && n.longitude ? o.setCenter(new google.maps.LatLng(n.latitude, n.longitude)) : e.isArray(n.markers) && n.markers.length > 0 ? n.markers[0].address ? a.geocode({
                address: n.markers[0].address
            }, function(e) {
                e && e.length > 0 && o.setCenter(e[0].geometry.location)
            }) : o.setCenter(new google.maps.LatLng(n.markers[0].latitude, n.markers[0].longitude)) : o.setCenter(new google.maps.LatLng(34.885931, 9.84375)), o.setZoom(n.zoom), o.setMapTypeId(google.maps.MapTypeId[n.maptype]);
            var s = {
                scrollwheel: n.scrollwheel,
                disableDoubleClickZoom: !n.doubleclickzoom
            };
            n.controls === !1 ? e.extend(s, {
                disableDefaultUI: !0
            }) : 0 !== n.controls.length && e.extend(s, n.controls, {
                disableDefaultUI: !0
            }), o.setOptions(s), o.setOptions({
                styles: n.styles
            });
            var t, r, i = new google.maps.Marker;
            t = new google.maps.MarkerImage(n.icon.image), t.size = new google.maps.Size(n.icon.iconsize[0], n.icon.iconsize[1]), t.anchor = new google.maps.Point(n.icon.iconanchor[0], n.icon.iconanchor[1]), i.setIcon(t), n.icon.shadow && (r = new google.maps.MarkerImage(n.icon.shadow), r.size = new google.maps.Size(n.icon.shadowsize[0], n.icon.shadowsize[1]), r.anchor = new google.maps.Point(n.icon.shadowanchor[0], n.icon.shadowanchor[1]), i.setShadow(r)), e(this).bind("gMap.centerAt", function(e, a, n, s) {
                s && o.setZoom(s), o.panTo(new google.maps.LatLng(parseFloat(a), parseFloat(n)))
            });
            var g = [];
            e(this).bind("gMap.clearMarkers", function() {
                for (; g[0];) g.pop().setMap(null)
            });
            var l;
            e(this).bind("gMap.addMarker", function(e, a, s, t, r, d) {
                var c, p, m = new google.maps.LatLng(parseFloat(a), parseFloat(s)),
                    h = new google.maps.Marker({
                        position: m
                    });
                if (r ? (c = new google.maps.MarkerImage(r.image), c.size = new google.maps.Size(r.iconsize[0], r.iconsize[1]), c.anchor = new google.maps.Point(r.iconanchor[0], r.iconanchor[1]), h.setIcon(c), r.shadow && (p = new google.maps.MarkerImage(r.shadow), p.size = new google.maps.Size(r.shadowsize[0], r.shadowsize[1]), p.anchor = new google.maps.Point(r.shadowanchor[0], r.shadowanchor[1]), i.setShadow(p))) : (h.setIcon(i.getIcon()), h.setShadow(i.getShadow())), t) {
                    "_latlng" === t && (t = a + ", " + s);
                    var w = new google.maps.InfoWindow({
                        content: n.html_prepend + t + n.html_append
                    });

                    google.maps.event.addListener(h, "click", function() {
                        l && l.close(), w.open(o, h), l = w
                    }), d && google.maps.event.addListenerOnce(o, "tilesloaded", function() {
                        w.open(o, h)
                    })
                }
                h.setMap(o), g.push(h)
            });
            for (var d, c = this, p = function(o) {
                    return function(a) {
                        a && a.length > 0 && e(c).trigger("gMap.addMarker", [a[0].geometry.location.lat(), a[0].geometry.location.lng(), o.html, o.icon, o.popup])
                    }
                }, m = 0; m < n.markers.length; m++) d = n.markers[m], d.address ? ("_address" === d.html && (d.html = d.address), a.geocode({
                address: d.address
            }, p(d))) : e(this).trigger("gMap.addMarker", [d.latitude, d.longitude, d.html, d.icon, d.popup])
        })
    }, e.fn.gMap.defaults = {
        address: "",
        latitude: 0,
        longitude: 0,
        zoom: 1,
        markers: [],
        controls: [],
        styles: [],
        scrollwheel: !1,
        doubleclickzoom: !0,
        maptype: "ROADMAP",
        html_prepend: '
',
        html_append: "
",
        icon: {
            image: "https://www.google.com/mapfiles/marker.png",
            shadow: "https://www.google.com/mapfiles/shadow50.png",
            iconsize: [20, 34],
            shadowsize: [37, 34],
            iconanchor: [9, 34],
            shadowanchor: [6, 34]
        }
    }
}(jQuery);

A: This solves it. Edit this:
d && google.maps.event.addListenerOnce(o, "tilesloaded", function() {
                    w.open(o, h)
                })

to this:
d && google.maps.event.addListenerOnce(o, "tilesloaded", function() {
                    w.open({anchor: h, shouldFocus: false})
                })


text:
Q: Kafka consumer speed increases with session timeout/max poll records I'm currently trying to read from one Kafka topic, doing some transformation and producing the messages to another topic.
However, i am having a lot of issues with the Consumer. First of all, if we set reasonable session timeout/max poll records values (like 10 s), the consumer takes super long, constantly rebalances and sometimes sends duplicated messages. If we increase the params to crazy values like 30 min, the speed increases dramatically. But the problem is once it reaches the 30 min mark, it rebalances and takes around 30 min to start up again.
I have been playing with a lot of different params but still lost on how to fix this. Any ideas? Thanks

A: This may be due to some configuration issues. Based on your question I would suggest to please check your auto commit property.
Because ideally kafka does rebalance if it does not recieve the acknowledgement of the message read before session timeout happens. If it is set as false then either set it to true or make sure to commit to kafka once you are done processing the message


text:
Q: Estimating Amazon products price I'm trying to develop an AI tool that can price items based on information of online products found on Amazon, JD etc (unfortunately I can't access the prices of those platforms due their strict anti-web scraping capabilities)  . I'm not looking for something super accurate. I just need the program to be able to allocate a reasonable price that's not too far off from what you would expect in reality. Are there existing solutions for this kind of applications?

A: If you don't already have access to amazon product api, your best bet is to use some other free/paid third-party public API. In our startup we use amazon-price from RapidAPI, it supports up to 1000 products in a single request. We've tried other options but most of them don't support bulk price and/or are more expensive possibly due to the fact that they also provide other data apart from just price.


text:
Q: NMOS high-side switch for buck converter I am studying a buck converter using an NMOS for the high-side switching.
The inverter is supplied by a 3.7 V battery and should power a 0.6 Ω load. The switching is done by a 100 kHz 0-3.3 V PWM generated by a microcontroller. The duty cycle is around 50%.
I suspect a bootstrap is used to drive the high-side MOSFET ON but I don't fully understand it. Can someone tell me if this circuit works and if so, how?
(I suspect the inductor value is also too low, causing strong current ripples (around 0.9 A))

A: Your MOSFET is wired as a source follower and this means that without boot-strapping it will have poor efficiency. The gate has to rise several volts higher (usually 10 volts higher) than the source to properly turn on the MOSFET and allow full conduction in other words.
Given that your circuit can only drive the gate to 3.7 volts (at best) and, given that the threshold voltage for very light current conduction (1 μA) of the NDS7002A is 2.1 volts typically, you are likely to get very poor results.
The inductor does appear to be a little low in value but, concentrate on getting the MOSFET boot-strapped. That's your big issue.

*

*See this document from Rohm that explains how boot strapping works.

Maybe this will help (a synchronous buck converter): -

*

*The lower MOSFET M1 is easily turned on because its source is connected to ground.

*So, when M1 activates, capacitor CB is charged to Vcc by connecting CB's negative terminal to ground and, the positive terminal of CB is connected to Vcc via the diode.

*After M1 deactivates and M2 initially activates, M2's gate voltage is at Vcc and is enough to start activating it.

*As M2 turns on, it rapidly lifts its source and, in doing so, it will lift the bootstrap capacitor's negative terminal.

*In lifting CB's negative terminal, CBs positive terminal (which is Vcc higher) becomes even higher than Vcc and starts activating M2 even more.

*As M2 fully turns on, CBs, positive terminal will be at "High voltage" plus Vcc and, of course, this satisfies the requirements to fully turn on M2 (its source voltage equals its drain voltage).

It's all about storing enough charge in CB so that it can power M2's driver circuit inside the chip.

A: Does it have to be N-MOS?
Note that Vgs determines on/off state.  Not Vg to GND.  When on, Vs = Vin, so Vg = Vin + Vgs(on).
So we use a bootstrap circuit to supply the gate voltage while it's on.  Fine.
But this can only happen if there is something to charge the bootstrap in the first place.  Not fine.
In a synchronous buck converter, we can have the low side fire first (or disable the high side until this has happened), ensuring charge.  In the diode version, we have no such luck.  Perhaps only on first startup, the output is at zero (the load has discharged the capacitor), and the bootstrap charges through the load.  (This requires Cboot ≪ Cout, which is normally the case.)  But that's not all.  Sufficient load current must always be flowing, so that the catch diode is active, drawing more than enough current to keep the bootstrap charged.  If load current drops low enough, for long enough, the bootstrap runs out and never recovers.
We can partially solve this with a pull-up resistor, and optionally an output pull-down in case there isn't always a load attached.  This works for Vout near zero, but Vout subtracts from Vin into the bootstrap and eventually we'll run into the same problem as before.  (This is essentially immediate for the single cell battery case, but can be feasible for higher input voltages, like say 100V in, 12V bootstrap, and output up to, maybe 75V?)
Better is to use a charge pump, or fully isolated supply, so the gate drive is always powered.  In the charge pump case, an AC source powers a capacitor, the far end of which goes to clamp diodes at the gate drive circuit (the basic half-wave voltage doubler arrangement).  This loses voltage from the diodes, again not very battery friendly, but is reasonable for say 10-15V supplies and Vin up to 200V or so (notice that the swing of the switch node itself, injects much more charge through the capacitor -- putting a huge burden in terms of peak current flow on both the AC source and clamp diode load; this makes it unsuitable for high voltages).  With an isolator, just any DC-DC supply, flyback or whatever, will do; Vgs(on) can then be other than battery voltage, allowing for example non-logic-level parts (10V drive could be an option; not that it will be necessary here).
Best, however, will simply be using a P-ch MOSFET.  While performance is poorer than N-MOS, this is a fairly small penalty at these low voltages.  Gate drive can be direct from a controller, driver IC, or even MCU if you're doing it that way, and the driver can be direct powered by the battery (assuming battery or 5V compatible supply range).  (If using 3.3V logic, a simple e.g. 74HC3G04 can be used as level translator + driver, using one as inverter and two in parallel as driver.  Or all three in parallel and not minding the inversion.)


text:
Q: PHP-Can't understand what is happening in this line of code         for($reg3=0; $reg3<128; $reg3++)
        {
             $reg1[$reg3] = $reg1[$reg3] ^ ($reg6[$reg3+256] & 1);
        }

I really don't understand what is happening here $reg1[$reg3] ^ ($reg6[$reg3+256] & 1);
and what would be it's vb.net equivalent code.

A: It is performing a bitwise XOR between two operands, one of which is produced by applying a bitwise AND to two other operands. Other than that, it's standard array indexes and addition.
The VB.Net code would be exactly the same if the types of the expressions support these operators (we don't know what the values of the variables are).

A: ^ and & are binary/bitwise operators - more here: Bitwise Operators
^ - Xor (exclusive or)
& - And
I'm guessing this is recompiled code or obfuscated - if not, thems some horrible variable names.
Switching for more traditional variable names: $reg3->$i, $reg1->$a, $reg6->$b we get:
for($i=0; $i<128; $i++) {
   $a[$i] = $a[$i] ^ ($b[$i+256] & 1);
}

It goes through the first 128 elements of array (or perhaps string) $a.  For each element, XOR it (^ ($b...) with the last bit only (& 1) of an element in array (or string) $b that is 256 places further on.  $a must be at least 128 elements, $b must be at least 384 elements.

A: & is a bitwise AND operator.
^ is a bitwise XOR operator.


text:
Q: NSArray (and other Cocoa types) @property values While in the process of debugging code written by a co-worker, I stumbled across the following that has me mystified:
NSMutableArray *array = [NSMutableArray array];
NSUInteger arrayCount = array.count;

Why does this work? It also works for NSDictionary and other types, but nowhere in the documentation nor Cocoa headers can those @property definitions be found.
Googling for "NSArray property" doesn't yield many useful results, so I'm reaching out to SO for what will surely be a very embarrassing question.

A: It works because dot syntax has nothing to do with properties.  It is simply syntactic sugar (though I don't like it, so perhaps it's "syntactic salt").
When you use dot syntax as the rvalue to an expression (or the expression to the right of the equal sign), it simple turns:
bar = myObject.thing;

Into
bar = [myObject thing];

When the dot is to the left of the equal sign (as an lvalue), it turns it into the setter.  So:
myObject.thing = 42;

Becomes
[myObject setThing:42];

So yes, you can do things like myObject.retain.  But you should never ever do that.  You should only ever use dot syntax as accessors to declared properties (ie, things that have been explicitly declared via @property).  <insert remark about how you should never use dot syntax at all.>
For more information, checkout out the documentation on dot syntax (specifically the "incorrect use" section).

A: the dot syntax is actually just an alternative for accessing methods that either take no parameter and return a value like array.count.  It is bad form to actually access the methods in that way.
It can also be used for things like [object setValue:(id)something]  and access it by doing object.setValue = something;


text:
Q: Trying to use cmd via c# I am trying to use a cmd command prompt that works just fine when I use it in a normal cmd window via Windows --> Start --> cmd
My code looks like this
"C:\Program Files\Rapid-I\RapidMiner5\scripts\rapidminer.bat" -f
"C:\Users\user\.RapidMiner5\repositories\Local Repository\test.rmp"

That works just fine.
The problem is when I am trying to write this code in C# by opening a cmd window via C#
This is the c# code
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd", "/c \"C:\\Program Files\\Rapid-I\\RapidMiner5\\scripts\\rapidminer.bat\" -f \"C:\\Users\\user\\.RapidMiner5\\repositories\\Local Repository\\test.rmp\"");

You can see I quoted the same way like the code that work in the regular cmd
But I am getting a can't recognize program files.

A: Try this:
string fullPath = @"C:\Program Files\Rapid-I\RapidMiner5\scripts\rapidminer.bat";
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = Path.GetFileName(fullPath);
p.WorkingDirectory = Path.GetDirectoryName(fullPath);
p.Arguments = @"/c -f ""C:\Users\user\.RapidMiner5\repositories\Local Repository\test.rmp""";
Process.Start(p);

I modified my original code to add arguments to your process.
One last thing you could try is putting your original command into a batch file and calling the batch file from your ProcessStartInfo object like so:
C#:
string fullPath = @"C:\Program Files\Rapid-I\RapidMiner5\scripts\run.bat";
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = Path.GetFileName(fullPath);
p.WorkingDirectory = Path.GetDirectoryName(fullPath);
Process.Start(p);


text:
Q: Trying to pass filename to ExcelWriter I am trying to pass a customized filename variable to ExcelWriter but cannot get the ExcelWriter portion of this to work for some reason.  If I replace "Sheetname" with "Temp.xlsx" in the ExcelWriter function this works, but i'm not able to pass my variable to the function.  I need to be able to store today's date in the filename every time the script is run.
Spreadsheet = pandas.DataFrame()
Sheetname = 'Makino Machine Metrics ' + time.strftime("%m/%d/%Y") +'.xlsx'
writer = pandas.ExcelWriter(Sheetname, engine = 'xlsxwriter')
Spreadsheet.to_excel(writer, sheet_name= 'Results',index = False)
workbook = writer.book
worksheet = writer.sheets['Results']
writer.save()

Thanks in Advance for the help

A: When I run your program I get the following error:
IOError: [Errno 2] No such file or directory:
         'Makino Machine Metrics 07/12/2016.xlsx'

You can fix it by removing the forward slashes from the date part:
import pandas
import time

Spreadsheet = pandas.DataFrame()
Sheetname = 'Makino Machine Metrics ' + time.strftime("%m_%d_%Y") +'.xlsx'
writer = pandas.ExcelWriter(Sheetname, engine = 'xlsxwriter')

Spreadsheet.to_excel(writer, sheet_name='Results', index=False)
workbook = writer.book
worksheet = writer.sheets['Results']
writer.save()

Looks like the error comes from open:
 >>> open('12/12/12.xlsx', 'w')
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 IOError: [Errno 2] No such file or directory: '12/12/12.xlsx'

So, either escape those characters or use another character in the date, like in the example above.


text:
Q: angularjs xdomain socket timeout I am running an Angular app on my local machine which connects to a local API via CORS. The app runs on localhost:8000, and the API runs on localhost:7999.
In the past I have counted on xdomain to handle my IE9 compatibility, but this time I'm not having any luck with it. Here's the console log from IE9...
LOG: xdomain (localhost:8000): adding slave: 'localhost:7999'

LOG: xdomain (localhost:8000): proxying request to slave: 'localhost:7999'

LOG: xdomain (localhost:8000): creating iframe xdomain-8f12dd3f

LOG: xdomain (localhost:8000): new socket: xdomain-20f6dbf3

xdomain (localhost:8000): Timeout waiting on iframe socket

Has any one else encountered this problem?

A: I had a very similar problem.
It turned out my proxy.html (needed for xdomain) was being sent with a 'X-Frame-Options' header, which was preventing the page working in an iFrame which is what xdomain uses.
Removing the 'X-Frame-Options' header from proxy.html on your server or web framework should be able to solve your problem. Make sure you're only removing it for proxy.html though.


text:
Q: Error Redirect Loop This web page has a redirect loop.
The web page at localhost:3613/SqaSuite/LessPermission.aspx has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.
Here are some suggestions:

*

*Reload this web page later.

*Learn more about this problem:

Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many
  redirects.

Despite of clearing cookies and having no recursive and/or many loop redirecting, I am having this error.
help ?

A: Check if you have somewhere on your page (eg called "SamePage.aspx"), or somewhere global, this endless loop.
 Response.Redirect("SamePage.aspx");

and change it to
 if(!HttpContext.Current.Request.Path.EndsWith("SamePage.aspx", StringComparison.InvariantCultureIgnoreCase))
       Response.Redirect("SamePage.aspx");

A: Try this:
if (!IsPostBack)
{
    Response.Redirect("~/Default.aspx");
}

A: Could also be because Button.PostBackUrl is redirecting to the same page. That was my problem.

A: By default asp.net MVC enables OwinStartup and redirects to Login under Account controller. You can refer to Startup.Auth for the same. Doing as below will fix the issue.
 <appSettings>
    <add key="owin:AutomaticAppStartup" value="false" />
  </appSettings>


text:
Q: Encrypt with Double Length 3DES Key in Java and produce 16 bytes array cipher I need to create a double length 3DES key in Java using a 16 bytes array key material, encrypt with it a message and get back 16 bytes length array. I am able to get it working with 24 bytes but not 16 bytes...
Because DESede expects 24 byte[], the only way to produce a double length 3DES Key with a 16 bytes long key material, I was able to by using a DESede instance and then increasing its length by appending first 8 bytes at the end to get 24 bytes. Like so:
    byte[] keyMaterial = // Assume this one is 16 bytes.

    byte[] newKeyBytes = ByteBuffer.wrap( new byte[ 24 ] )
            .put( Arrays.copyOfRange( keyMaterial, 0, 16 ) )
            .put( Arrays.copyOfRange( keyMaterial, 0, 8 ) )
            .array();

    SecretKeyFactory mySecretKeyFactory = SecretKeyFactory.getInstance( "DESede" );
    KeySpec myKeySpec = new DESedeKeySpec( newKeyBytes );
    SecretKey encryptionKey = mySecretKeyFactory.generateSecret( myKeySpec );

Now when I have my DESede key I can use it to encrypt the message the following way. Also, I need to use "ECB" mode:
    Cipher cipher = Cipher.getInstance( "DESede/ECB/PKCS5Padding" );
    cipher.init( Cipher.ENCRYPT_MODE, encryptionKey );
    byte[] returnValue = cipher.doFinal( dataToEncrypt )

But as a result I get back 24 byte array rather than 16 byte array and I guess this is because I am encrypting with 24 byte array.
Is there a way to create a 3DES SecretKey 16 bytes long rather than 24 bytes, OR when encrypting with 24 byte long SecretKey, get back a 16 bytes long ciphered message as I need rather than 24 bytes long?
Thank you!

A: I think I have just found an answer to my question.
https://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html
I used DESede/ECB/NoPadding and when used with NoPadding, then encrypting a 16 bytes array message with 24 bytes SecretKey produces a 16 bytes long cipher message which is exactly what I need.
I hope this finding is correct. Please correct me if I am mistaken.


text:
Q: PHP mail send multipart inconsistently working I'm currently having issues with sending PHP multipart emails. I've been looking online to check my code is correct and it appears to be. I found some code on another Stack question and tweaked my code to ensure it was the same as the code that the developer said worked for them. The following code is part of a function:
$mime_boundary = 'Multipart_Boundary_x'.md5(time()).'x';

$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/alternative; boundary=\"$mime_boundary\"\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n";
$replyto .= "reply-to: $replyto";

$body = "This is a multi-part message in mime format.\r\n\r\n";

# Plain text
$body.= "--$mime_boundary\r\n";
$body.= "Content-Type: text/plain; charset=\"charset=iso-8859-1\"\r\n";
$body.= "Content-Transfer-Encoding: 7bit\r\n";
$body.= $text_content;
$body.= "\r\n";

# HTML
$body.= "--$mime_boundary\r\n";
$body.= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n";
$body.= "Content-Transfer-Encoding: 7bit\r\n";
$body.= $html_content;
$body.= "\r\n";

# End
$body.= "--$mime_boundary--\r\n";

$headers .= "From: $from\r\n";
$headers .= "X-Sender-IP: $_SERVER['SERVER_ADDR']\r\n";
$headers .= 'Date: '.date('n/d/Y g:i A')."\r\n";
$replyto .= "reply-to: $replyto";

# Return
return mail($to, $subject, $body, $headers);

This works for most mail clients. It will appear in HTML in Mac Thunderbird and Gmail. However, there is someone on Windows 7 using Thunderbird and it is coming through as the HTML email with the html code showing rather than a HTML email.
Is there something I am doing wrong? And is there anything I need to configure on Apache to make this work? Help would be really appreciated as I'm just hitting brick walls with this at the moment.

A: Regarding my comment above, I highly recommend you use PHPMailer, however, before I switched over the PHPMailer this was the format for sending multipart emails I used:
--52664dd6e3ea3
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

Hello

--52664dd6e3ea3
Content-Type: multipart/related; type="text/html"; boundary="html52664dd6e3ea3"

--html52664dd6e3ea3
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

Hello

--html52664dd6e3ea3--
--52664dd6e3ea3--

And if you want attachments:
--52664e536e0b0
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

Hello

--52664e536e0b0
Content-Type: multipart/related; type="text/html"; boundary="html52664e536e0b0"

--html52664e536e0b0
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

Hello

--html52664e536e0b0
Content-Type: application/octet-stream; name=filename.ext
Content-Transfer-Encoding: base64
Content-Disposition: attachment

{BASE64CODEHERE}

--html52664e536e0b0--
--52664e536e0b0--

And multiple attachments here:
--52664e536e0b0
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

Hello

--52664e536e0b0
Content-Type: multipart/related; type="text/html"; boundary="html52664e536e0b0"

--html52664e536e0b0
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

Hello

--html52664e536e0b0
Content-Type: application/octet-stream; name=filename.ext
Content-Transfer-Encoding: base64
Content-Disposition: attachment

{BASE64CODEHERE}

--html52664e536e0b0
Content-Type: application/octet-stream; name=filename.ext
Content-Transfer-Encoding: base64
Content-Disposition: attachment

{BASE64CODEHERE}

--html52664e536e0b0--
--52664e536e0b0--


text:
Q: Type error inserting data into sqlite in flask I'm trying to insert data into a table from a form and from a different table, but I'm getting this error.

TypeError: function takes at most 2 arguments (3 given)
db.execute("INSERT INTO chapters (chapter, book_id) VALUES (?, ?)", [request.form['chapter']], book_id)

@app.route('/newbook')
def new_book():
    return render_template('newbook.html')

@app.route('/addbook', methods=['GET', 'POST'])
def addbook():
    db = get_db()
    db.execute("INSERT INTO books (title) VALUES (?)",
        [request.form['title']])
    db.commit()

    return redirect(url_for('new_chapter'))

@app.route('/newchapter')
def new_chapter():
    return render_template('newchapter.html')

@app.route('/addchapter', methods=['GET', 'POST'])
def addchapter():
    db = get_db()
    cur = db.execute("SELECT last_insert_rowid()")
    book_id = cur.fetchone()

    db.execute("INSERT INTO chapters (chapter, book_id) VALUES (?, ?)", [request.form['chapter']], book_id)
    db.commit()

    return redirect(url_for('new_concepts'))

A: The error is telling you what's wrong, you've given the following line 3 arguments when it only can accept 2.
db.execute("INSERT INTO chapters (chapter, book_id) VALUES (?, ?)", [request.form['chapter']], book_id)

The 1st argument is supposed to be the SQL query while the 2nd argument is supposed to be a list of values that will replace the ? placeholders. However, you've accidentally put the book_id outside of the list, causing it to be passed as a 3rd argument. It should be inside the list as follows:
db.execute("INSERT INTO chapters (chapter, book_id) VALUES (?, ?)", [request.form['chapter'], book_id])


text:
Q: Reuse same database object when doing multiple lookups - Django This question involves caching/optimisation/reducing calls to the database in Django
My (hypothetical) scenario is that I'm pulling a list of addresses from a server, which changes every so often.
Now the postcode may well be common between some of the addresses.
I already have a list of postcodes in my database, for which the model looks something like:
class PostCode(models.Model);
     postcode = models.CharField(max_length=10)
     country = models.CharField(max_length=100)
     name_of_postman = models.CharField(max_length=50)

For each address, I need to create a new 'address' object, and store that in the database, which requires me to lookup the postcode (which is a foreign key)
class Address(models.Model):
     address_line1 = models.CharField(...)
     ...
     postcode = models.ForeignKey(PostCode, related_name='+')

Now, whilst iterating over my addresses obtained from the server, I'm finding I have to do something like:
for address in all_addresses:
   ...
   if address.is_useful():
       Address.objects.create(address_line1=line1, postcode=Postcode.objects.get(postcode=postcode))

As you can see, I'm retrieving the postcode every time I save an address, which isn't very optimal if I've already retrieved that postcode whilst saving a different address.
What I'd like to do is optimise this so that if the same postcode is used 100 times for different addresses, I'm not having to retrieve the same stuff from the database 100 times.
(I don't want to pre-populate a list of all the postcodes, since I might not need them all (see the address.is_useful() line)
My current ideas have been:
create a dict and store already-getted objects in that. Something like:
postcodes = {}
for address in all_addresses:
   ...
   if address.is_useful():
        Address.objects.create(address_line1=line1, postcode=postcodes.setdefault(postcode, Postcode.objects.get(postcode=postcode)))

this brings me to the question of database caching. Is this effectively what database caching acheives (albeit in a slightly more complex way)? If so, I guess I may as well just use database caching.

UPDATE:
My setdefault() solution won't work, since the default value, whatever it is, is processed every time irrespective of if it's used:
>>> dict = {}
>>> def val():
...     print 'running the val() function'
...     return 1
...
>>>
>>> dict.setdefault('key', val())
running the val() function
1
>>> dict.setdefault('key', val())
running the val() function
1

A: Why don't you extract the postcode before going into the for loop?
postcode_obj = Postcode.objects.get(postcode=postcode)
for address in all_addresses:
...
    Address.objects.create(address_line1=line1, postcode=postcode_obj)

That way you have 1 query for the postcode.