text:
Q: How do I make this code write data to the database? There's a problem - for some reason I don't understand, the code doesn't want to write a value to the database. The concept of the code is as follows - a person sends a message and the bot writes his message to the database. If there is an error in the code, it writes "ERR". But the bot at the stage of sending the message, is just not going to send the data to the database, it doesn't even give any sending sign. Thanks for any help
Code:
@dp.message_handler(Text(equals="Buy"))
async def with_pureee(message: types.Message):
    await message.reply("Loading...")
    keyboard = ReplyKeyboardRemove()
    back = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
    buttons = ["back"]
    back.add(*buttons)
    await message.answer("Please, write your name", reply_markup=back)
    @dp.message_handler()
    async def names(message: types.Message):
        mes = message.text
        if mes == "Back":
            return
        else:
            try:
                conn = await aiomysql.connect(host='localhost', port=3306,
                                           user='root', password='', db='aiodb', loop=loop)
                cur = await conn.cursor()
                await cur.execute("INSERT INTO users(name) values(msg)")
                await conn.commit()
                await cur.close()
            except Exception as e:
                @dp.message_handler()
                async def names(message: types.Message):
                    await message.answer("ERR")

A: Look at the following line of code
await cur.execute("INSERT INTO users(name) values(msg)")

The name field must be a string so it should have single quotes 'msg' or it could be that you were trying to pass a variable into the statement. That should be done differently. See here
await cur.execute("INSERT INTO users(name) values('msg')")

In addition, look at the error trapping. Ensure that it return the actual error and not a generic error message like 'ERR'

A: Rewrite your code like this and all works.
@dp.message_handler(text="Buy")
async def with_pureee(message: types.Message, state: FSMContext):
    await message.reply("Loading...")
    keyboard = ReplyKeyboardRemove()
    back = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
    # buttons = ["back"] - here was a mistake, lowercase instead of capitalized
    buttons = ["Back"]
    back.add(*buttons)
    await message.answer("Please, write your name", reply_markup=back)
    await state.set_state('get_name')

@dp.message_handler(state='get_name')
async def names(message: types.Message, state: FSMContext):
    mes = message.text
    if mes == "Back":
        await state.finish()
    else:
        try:
            conn = await aiomysql.connect(host='localhost', port=3306,
                                           user='root', password='', db='aiodb', loop=loop)
            cur = await conn.cursor()
            await cur.execute("INSERT INTO users(name) VALUES ({})".format(mes))
            await conn.commit()
            await cur.close()

            await message.answer(f'user {mes} added')
        except Exception as e:
            await message.answer(f"ERR {e}") # add 'e' to watch the error description
        finally:
            conn.close()
            await state.finish()

It's better to use FSM to get info from user.
Also you could rewrite this:
await cur.execute("INSERT INTO users(name) VALUES (" + mes + ")")
await conn.commit()
await cur.close()

like this:
async with conn.cursor() as cur:
    await cur.execute("INSERT INTO users(name) VALUES (" + mes + ")")

so you don't need to close connection.

aiomysql tutorial has lots of examples, for example
inserting data


text:
Q: Easier way to extract only prefixed elements from mixed xml/html This is my working nightmare: we have a bunch of files that are html pages but which contain additional xml elements (all prefixed with our company name 'TLA') to provide data and structure for an older program which I am now rewriting.
Example Form:

    <title>Highly Simplified Example Form</title>

    <TLA:document>
        <TLA:contexts>
            <TLA:context id="id_1" value=""></TLA:context>
        </TLA:contexts>
        <TLA:page>
            <TLA:question id="q_id_1">

                            <input id="input_id_1" type="text" />

            </TLA:question>
        </TLA:page>

    </TLA:document>

My task is to write a pre-processor that will split a document like this into two documents: an xml file containing only the 'TLA' elements and an html file containing only the html elements.
Example XML:
<?xml version="1.0" encoding="utf-8" ?>
<TLA:document>
    <TLA:contexts>
      <TLA:context id="id_1" value=""></TLA:context>
    </TLA:contexts>
    <TLA:page>
      <TLA:question  id="q_id_1">
      </TLA:question>
    </TLA:page>

</TLA:document>

Example HTML:

    <title>Highly Simplified Example Form</title>

                <input id="input_id_1" type="text" />

Now I can do this by processing each element one at a time and copying them to new documents but I'm thinking that there might be an easier way to do this by using a one or two pass transform or some clever serialization but I have no idea which avenues to explore.
So does anyone have a suggestion as to how to process this? Ideally VB.net but C# or something else is also acceptable.
Update:
It seems that xslt is the way to do this but I know so little about it that I still need some help. It seems that  //namespace::TLA may be the right xpath to extract the data elements but I have no idea how to implement it.

A: XSLT was the best choice for solving this problem.

*

*To extract the HTML see this question.

*To extract the namespace see this question.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get earlier value based on a value name in a column I would like to get the previous day value depending on an attribute's name hence applying a two-level filter to my calculated column.
I am currently stuck with the following formula giving me a blank column.
Column = CALCULATE(
                    MAX(useractivity[Value]),
                    FILTER(
                            useractivity,
                            useractivity[Dates]=EARLIER(useractivity[Dates])-1
                        ),
                    FILTER(
                        an IFS function maybe?
                    ))

I would like to have the following output:
+------------------+-----------+---------+----------------+
|      Dates       | Attribute |  Value  | Previous_Value |
+------------------+-----------+---------+----------------+
| 31 december 2018 | active    | 100,000 |         80,000 |
| 31 december 2018 | inactive  |  50,000 |         40,000 |
| 29 december 2018 | active    |  80,000 |            ... |
| 29 december 2018 | inactive  |  40,000 |            ... |
+------------------+-----------+---------+----------------+

A: This is similar to my answer here. Calculate the previous date and then do a lookup.
Previous_Value =
VAR PrevDay =
    CALCULATE (
        LASTDATE ( useractivity[Dates] ),
        ALLEXCEPT ( useractivity, useractivity[Attribute] ),
        useractivity[Dates] < EARLIER ( useractivity[Dates] )
    )
RETURN
    LOOKUPVALUE (
        useractivity[Value],
        useractivity[Dates], PrevDay,
        useractivity[Attribute], useractivity[Attribute]
    )

Edit
As a measure, you need some minor tweaks,
Previous_Value =
VAR PrevDay =
    CALCULATE (
        LASTDATE ( useractivity[Dates] ),
        FILTER(
            ALLEXCEPT ( useractivity, useractivity[Attribute] ),
            useractivity[Dates] < MAX( useractivity[Dates] )
        )
    )
RETURN
    LOOKUPVALUE (
        useractivity[Value],
        useractivity[Dates], PrevDay,
        useractivity[Attribute], MAX(useractivity[Attribute])
    )


text:
Q: Reading JSON using fetch in typescript/javascript I was looking for this stuff on the internet and I found that:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch. I am relativey new to typescript so there are a few things that confuse me.
First what's the difference between:
fetch('data.json')
.then(function(response) {
    return response.json();
})
.then(function(myJson) {
    console.log(JSON.stringify(myJson));
   //data = myJson;
});

and
fetch('data.json')
.then(function(response) {
    console.log(JSON.stringify(response.json()));
    //data = response.json();
})

The first works well but the second piece of code does't. Why is that? As far as I know fetch retuns the promise of JSON and in .then, response.json() holds the actual JSON object. But the second version doesn't work (I get undefined in console).
My second question is how to get out the value of myJson. I tried doing that with global variable but it didn't work (I get undefined in console):
var data
fetch('data.json')
.then(function(response) {
    return response.json();
})
.then(function(myJson) {
   //console.log(JSON.stringify(myJson));
   data = myJson;
});
console.log(JSON.stringify(data));

A: The reason we need to use response.json() is because Fetch returns an HTTP response. To extract the JSON body content from the response, we use json() method.
The reason you are getting undefined is because of async nature of javascript. Try using async and await to solve this issue or print the data inside of the then() not outside of it.


text:
Q: Jersey 2.9 set resource-lifecyle per-session I have a web-application where I need to have one instance of my resource per session.
I tried to follow the example given here, replacing the PerSessionRessource part with my own class
https://jersey.java.net/documentation/latest/ioc.html
However it seems like the Provider is not used, at least I can see that I'm acessing a new instance of my resource class with my second request.
I try to register it within the application as follows:
public class MyApplication extends ResourceConfig {

    public MyApplication() {
        System.out.println("Registering the application");
        register(PerSessionComponentProvider.class);

        register(new AbstractBinder() {
            @Override
            protected void configure() {
                bindFactory(HttpSessionFactory.class).to(HttpSession.class);
                bind(SessionInjectResolver.class)
                .to(new TypeLiteral<InjectionResolver<SessionInject>>(){})
                .in(Singleton.class);

        }
    }

            );
}

How can I make sure that I access the same instance of my resource with every httprequest from a client. In Jersey 1.x there seems to have been the @PerSession annotation, how can I get this functionality in Jersey 2.x?
Thanks in advance!


text:
Q: Arrays of Strings in Excel VBA I am working with XML data files, and these have a lot of tables of data. There are many table-types, and each different table-type has a fixed number of fields.
I would like a generic table class. This class would have a string containing the name of its table type, like "condition" or "encounter". I would like to have this class have a pointer to a Public array of strings that has been initialized to hold all of the expected fieldnames of this table type.
For example, I will have:
The public variables:
Public cond_fnames() As String
Public enc_fnames() As String

be initialized as:
cond_fnames = Split("id,strName,strDesc,aFieldNames,aModifiers", ",")
enc_fnames = Split("id,strName,strDesc,strImg,nTreasureID", ",")

(the above examples are truncated, and are actually much longer)
I don't want each table-class-object to have to have the whole array of strings as I expect to have to create a lot of table-class-objects.
How can I have a class object hold a pointer to the public array of strings?
(the reason I want this array of strings is that I am using this as an index mechanism for storing the associated table value. XML table fields have a fieldname and a value. So in the above "conditions" table, the value for the fieldname "strDesc" would be stored in the 3rd collection position. Perhaps there is a better way to do this indexing. I had thought of using enums, but don't know how to have the enumerated values be private to each class (different XML tables can have the same value field-names, at different positions within the table) nor do I want each table-class-object to have to have storage for the long list of field-names.)

A: I ended up using a collection to hold all of the string's, rather than an array. That way I can have the TableType class hold the collection of table fieldnames.
To answer the question in the comment, the 'table' nature of the data is due to the XML file data format that I am dealing with. It consists of many many 'tables' in the format:
       <table name="conditions">
        <column name="id">13</column>
        <column name="strName">Heat exhaustion</column>
        <column name="strDesc"><us> is suffering from heat exhaustion.</column>
        <column name="aFieldNames">fWaterConsumptionRate,fSleepQuality,m_fMoraleHidden,m_fDefense,MinSafeTemp,MaxSafeTemp,fPassiveRewarmPerHour</column>
        <column name="aModifiers">0.5,-0.75,-0.1,-0.02,15,15,-1</column>
  .
  .
       </table>

That is a "conditions" table entry in the XML file. There are about 25 different table-types, each with their own fixed set of fieldnames, and many of the fieldnames are common between the table-types.
Each "conditions" table entry will all have the same fieldnames, but they could be in any order. I am populating Userforms that contain textboxes for each of these table fields for each of these table-types, so I have a LOT of textboxes and I need to populate them in a known, sequential fashion, as I do not want to have to know the 'name' or handle to each text box.
To do this, I just have collections. The collection of fieldnames (otherwise known as the 'column name' from the XML file table entry) is used to find the index into the collection of fieldvalues, and this index is also used to write the fieldvalue into its corresponding collection of textboxes.
Anyways, since classes can't have public arrays, I ended up using a collection.
Thanks for your time in trying to understand the question.


text:
Q: How to make a responsive multi-control ui with Dynamic? I want to create a custom ui control with interacting elements.
For simplicity, assume there are going to be three Sliders, where each successive Slider's max value depends on the current value of the preceding Slider.
{
 Slider[Dynamic[x, (y=f[y, # - 1]; x = #)&], {3, 10, 1}],
 Slider[Dynamic[y, (z=f[z, # - 1]; y = #)&], {2, Dynamic[x-1], 1}],
 Slider[Dynamic[z], {1, Dynamic[y-1], 1}]
 } // Column

where f, is an auxiliary function that limits the value of the first argument, if it exceeds the value of the second argument:
f[x_, max_] := Which[
  x > max, max,
  True, x
 ]

After a certain amount of experimentation, I realized that the second argument of Dynamic needs to include all the expressions that involve changing variables, otherwise the outcome is not user friendly.
For example, this is how I'd modify the second argument of Dynamic in the first Slider:
...(y=f[y,#-1];z=f[z,y-1];y=#)&... (* first slider mod *)

Notice how the mod includes z, now. Similar modifications should be made in the second Slider.
However, notice that including at the second argument of Dynamic all the expressions that are needed to change the respective variables, becomes cumbersome for anything larger than an ensamble of three Sliderss.
Also, it seems that automating the construction of such a composite ui element becomes progressively difficult as the dependence relations between variables get more elaborate (and the f functions get more complicated).
So, my question is, is there another way to construct a composite ui element, like the one above, where each successive element responds to the values of previous elements?
The response I'm more interested here, is for the max value of dependent sliders to change in an expected manner, when the value of a preceding master sliders changes.

A: Concerning this:

Also, it seems that automating the construction of such a composite ui element becomes progressively difficult as the dependence relations between variables get more elaborate (and the f functions get more complicated).

All I can say is that complicated relationships might require complicated code.  Here's a way to keep it all in one place, so that updates are done in a consistent way ("consistent" being defined by the programmer through the code). The tracking function looks the same for all controls, at least in this MWE.  If the update can be checked quickly, then the UI should be satisfactorily responsive.
ClearAll[update];
SetAttributes[update, HoldAll];
update[vars_] := Function[{val, expr}
   , expr = val (* perform default update *)
   ; (* update all vars in "consistent" way: *)
   vars = FoldList[Min[#2, #1 - 1] &, vars]
   , HoldRest];

 {Slider[Dynamic[x, update[{x, y, z}]], {3, 10, 1}],
  Slider[Dynamic[y, update[{x, y, z}]], {2, Dynamic[x - 1], 1}],
  Slider[Dynamic[z, update[{x, y, z}]], {1, Dynamic[y - 1], 1}]
  } // Column

Expanding this MWE is straightforward:
 {Slider[Dynamic[w, update[{w, x, y, z}]], {4, 10, 1}],
  Slider[Dynamic[x, update[{w, x, y, z}]], {3, Dynamic[w - 1], 1}],
  Slider[Dynamic[y, update[{w, x, y, z}]], {2, Dynamic[x - 1], 1}],
  Slider[Dynamic[z, update[{w, x, y, z}]], {1, Dynamic[y - 1], 1}]
  } // Column


text:
Q: Boot DOS in High Memory I have burned a bootable disk which contains MS-DOS with the RAM drive, himem.sys. Even though, I still cannot boot it on computer with 4GB memory or more. After that, I burned a Windows 98 Live CD, still, I am not able to boot it on computer with 3.5G memory or more. it says: "Cannot fit in the memory".
My question is, what's happening in the memory? why does it say "cannot fit" when the memory is obviously large enough to fit? How should I make it bootable on these high memory computer?


text:
Q: Warning: It is ambiguous to apply a single loc constraint on multiple IO primitives; we will keep the constraint on the instance I think I have some designing problem in VHDL.
I am trying to set some pin to high and low. to set another connected board.
I am getting the following warnings:
 [Constraints 18-5] Cannot loc instance 'processing_system7_0_PS_PORB_IBUF' at site B5, Site location is not valid [D:/Sensor/receiver/receiver.srcs/sources_1/edk/module_1/implementation/module_1_processing_system7_0_wrapper.ncf:137]

 [Constraints 18-5] Cannot loc instance 'processing_system7_0_PS_SRSTB_IBUF' at site C9, Site location is not valid [D:/Sensor/receiver/receiver.srcs/sources_1/edk/module_1/implementation/module_1_processing_system7_0_wrapper.ncf:138]

 [Constraints 18-5] Cannot loc instance 'processing_system7_0_PS_CLK_IBUF' at site F7, Site location is not valid [D:/Sensor/receiver/receiver.srcs/sources_1/edk/module_1/implementation/module_1_processing_system7_0_wrapper.ncf:139]

 [Designutils 20-1397] We found multiple IO primitives connected to net 'module_1_i/receiver_0_rs_uart_out_pin'. It is ambiguous to apply a single loc constraint on multiple IO primitives; we will keep the constraint on the instance 'module_1_i/receiver_0/XST_VCC' driving the net 'module_1_i/receiver_0_rs_uart_out_pin'. [D:/Sensor/receiver/receiver.srcs/sources_1/edk/module_1/data/module_1.ncf:5]

 [Constraints 18-5] Cannot loc instance 'module_1_i/receiver_0/XST_VCC' at site J15, Unknown instance type 'VCC' [D:/Sensor/receiver/receiver.srcs/sources_1/edk/module_1/data/module_1.ncf:5]

 [Designutils 20-1397] We found multiple IO primitives connected to net 'module_1_i/receiver_0_rs_te_485_pin'. It is ambiguous to apply a single loc constraint on multiple IO primitives; we will keep the constraint on the instance 'module_1_i/receiver_0/XST_GND' driving the net 'module_1_i/receiver_0_rs_te_485_pin'. [D:/Sensor/receiver/receiver.srcs/sources_1/edk/module_1/data/module_1.ncf:6]

 [Constraints 18-5] Cannot loc instance 'module_1_i/receiver_0/XST_GND' at site J16, Unknown instance type 'GND' [D:/Sensor/receiver/receiver.srcs/sources_1/edk/module_1/data/module_1.ncf:6]

 [Designutils 20-1397] We found multiple IO primitives connected to net 'module_1_i/receiver_0_rs_hf_out_pin'. It is ambiguous to apply a single loc constraint on multiple IO primitives; we will keep the constraint on the instance 'module_1_i/receiver_0/XST_VCC' driving the net 'module_1_i/receiver_0_rs_hf_out_pin'. [D:/Sensor/receiver/receiver.srcs/sources_1/edk/module_1/data/module_1.ncf:7]

 [Constraints 18-5] Cannot loc instance 'module_1_i/receiver_0/XST_VCC' at site L17, Unknown instance type 'VCC' [D:/Sensor/receiver/receiver.srcs/sources_1/edk/module_1/data/module_1.ncf:7]

 [Designutils 20-1397] We found multiple IO primitives connected to net 'module_1_i/receiver_0_rs_rxen_bar_pin'. It is ambiguous to apply a single loc constraint on multiple IO primitives; we will keep the constraint on the instance 'module_1_i/receiver_0/XST_GND' driving the net 'module_1_i/receiver_0_rs_rxen_bar_pin'. [D:/Sensor/receiver/receiver.srcs/sources_1/edk/module_1/data/module_1.ncf:8]

 [Constraints 18-5] Cannot loc instance 'module_1_i/receiver_0/XST_GND' at site N17, Unknown instance type 'GND' [D:/Sensor/receiver/receiver.srcs/sources_1/edk/module_1/data/module_1.ncf:8]

 [Designutils 20-1397] We found multiple IO primitives connected to net 'module_1_i/receiver_0_rs_dxen_pin'. It is ambiguous to apply a single loc constraint on multiple IO primitives; we will keep the constraint on the instance 'module_1_i/receiver_0/XST_VCC' driving the net 'module_1_i/receiver_0_rs_dxen_pin'. [D:/Sensor/receiver/receiver.srcs/sources_1/edk/module_1/data/module_1.ncf:9]

 [Constraints 18-5] Cannot loc instance 'module_1_i/receiver_0/XST_VCC' at site M15, Unknown instance type 'VCC' [D:/Sensor/receiver/receiver.srcs/sources_1/edk/module_1/data/module_1.ncf:9]

The code part which is causing these warnings is might be this:
I have an IP in EDK project:
which has two files: reciever.vhd and user_logic.vh.
In the user_logic.vhd I made some out ports and I am trying to assign high and low values to those ports.
    entity user_logic is
      port
      (

            rs_rx           : in  std_logic;
            rs_clk_in       : in  std_logic;
            rs_dxen             : out std_logic;
            rs_uart_out     : out std_logic;
            rs_hf_out       : out std_logic;
            rs_rxen_bar     : out std_logic;
            rs_te_485       : out std_logic;
                    Bus2IP_Resetn                  : in  std_logic;

      );
architecture IMP of user_logic is
    signal q : unsigned(9 downto 0) := (others => '0');
    signal rx_clk : std_logic := '0' ;

    signal  rs_dxen_i      : std_logic;
    signal  rs_uart_out_i  : std_logic;
    signal  rs_hf_out_i     : std_logic;
    signal  rs_rxen_bar_i   : std_logic;
    signal  rs_te_485_i     : std_logic;

begin

    rs_dxen  <= rs_dxen_i;
    rs_uart_out <= rs_uart_out_i;
    rs_hf_out <= rs_hf_out_i;
    rs_rxen_bar <= rs_rxen_bar_i;
    rs_te_485 <= rs_te_485_i;

    process ( Bus2IP_Resetn, rs_clk_in ) is

    begin

        if(Bus2IP_Resetn = '1') then

            rs_dxen_i  <= '1';
            rs_uart_out_i <= '1';
            rs_hf_out_i <= '1';
            rs_rxen_bar_i <= '0';
            rs_te_485_i <= '0';

    elsif rs_clk_in'event and rs_clk_in = '1' then

    q <= q + 1;

    rx_clk <= q(9);   --- 58.gdfg/2^9=~ 115.82Khz baud rate = 115200

    end if;
   end process;

I make these ports external ports and connect to some pins.
But I receive the warnings I mentioned above and I am not able to set the corresponding pins to high and low.
But If in the code I don't assign any values to the out ports the warnings doesn't come.
warning for B5, C9 nad F7 can be ignored. three warning always comes. The other warning doesn't comes if I not put this part after begin: rs_dxen <= rs_dxen_i; rs_uart_out <= rs_uart_out_i; rs_hf_out <= rs_hf_out_i; rs_rxen_bar <= rs_rxen_bar_i; rs_te_485 <= rs_te_485_i;

A: The VHDL is fine. The apparent problem is that the pin mappings are invalid.
The first thing I'd suspect is that the pin mappings belong to a different variant of the FPGA, so that e.g. B5, C9 and F7 do not have input buffers because these are power supply pins in this variant, or something similar.
The unknown instance type 'GND' is suspicious though.


text:
Q: Why one element's CSS negative margin takes out the other element from floated box This is piece of bigger project but what happens is that use of negative margin on one element (.pag) takes the other element (#ar_wr_in) out from floated box (#ar_wr)?
It works fine in Firefox but does not in Chrome or IE.
HTML:

pagination

isdjs fjs odifj

CSS:
body {
  color: #f00;
  background: #191919;
  font-family: LucidaGrande, Helvetica, Arial, sans;
}

section {
  display: block;
  float: left;
}

section {
  margin: 0px;
}

#ar_wr {
  width: 59%;
  padding: 1%;
  background: #ffddff;
  border-radius: 5px;
  margin-right: 1.5%;
}

#ar_wr {
  float: left;
  margin-top: 80px;
}

#ar_wr_in {
  width 100%;
  float: left;
  margin-top: 17px;
}

.pag {
  font-size: 12px;
  margin-top: -77px;
  /* background: #ddffff; */
  position: relative;
}

.ar {
  width: 100%;
  margin-bottom: 40px;
  position: relative;
  background: #ddffff;
}

Here is JSFiddle
Is there some fix or hack for this to make it look as in Firefox?
Thank you

A: If you make your pagination element have absolute positioning then it can happily sit outside it's parent without affecting other non-absolute elements that come after it:
.pag {
  font-size: 12px;
  margin-top: -77px;
  /* background: #ddffff; */
  position: absolute;
}

Strange that Firefox treats it differently, but I would actually expect the result that you see in Chrome from using relative positioning like that.


text:
Q: How to programatically add an option to an optiongroup in selectize.js I want to dynamically add an option to an optiongroup in Selectize.js.  The API only has
addOption(data)
updateOption(value, data)
addOptionGroup(id, data)

without much help on what "data" is.  I've seen the examples for adding an option but no mention of using optionGroups
$('#button-addoption').on('click', function() {
    control.addOption({
    id: 4,
    title: 'Something New',
    url: 'http://google.com'
});

Thanks

A: Data is the object passed to the optgroup rendering method.
And so, you can put anything in it.
$('#selectize').selectize({
    ...
    optgroupField: 'mygroup',
    render: {
        optgroup_header: function(data, escape) {
            return '
' + escape(data.a) + escape(data.b) '
';
        }
    },
    ...
});

And then, whenever you want, you can add groups and options in the selectize:
//add group
var optGroup = { a: 'fruit', b: ... };
$('#selectize')[0].selectize.addOptionGroup('0', optGroup);

//add option
var option = { value: 'abc', text: 'banana', mygroup: '1'};
$('#selectize')[0].selectize.addOption(option);

Of course, if you only want a label for the group, you can do this:
//code
...
render: {
    optgroup_header: function(data, escape) {
    return '
' + escape(data) + '
';
}
...
//code

$('#selectize')[0].selectize.addOptionGroup('1', 'meat');

You can see the API demo (search for 'Optgroups (programmatic)' in page).


text:
Q: Phenomenology application of quantum anomaly Anomaly means that: the system has a symmetry at classical level (both discrete and continous), but when we quantize the theory, the system no longer holds the symmetry.
I'm wondering for every anomaly, if we can design a experiment to check? For example, the global chiral anomaly, we can measure the life time of photons when the pi zero particle decays. And for parity anomaly, the corresponding experiment is quantum hall effect. However, currently I don't know how to check the conformal anomaly and the gravitational anomaly. And by the way I'm not sure if the gauge anomaly will cause any physical observable effect.

A: The main distinction here is between global and gauge anomalies.
As you described, a symmetry is anomalous if it is realized by our classical description of the system but is broken quantum mechanically (i.e. the Lagrangian is invariant under the symmetry but the path integral is not).
Generally, it depends on the system you're considering and what type of symmetry is anomalous, but I'll focus on anomalies in particle physics. Roughly speaking, we should distinguish between anomalies in global symmetries and in gauge symmetries. As you suggested, we can measure global anomalies in particle physics by observing some decay process not allowed by that symmetry (e.g. proton decay and baryon number conservation).
These are distinct from gauge anomalies. Gauge symmetries are not real symmetries of the physical system but are redundancies in our description of the theory (which we put in to make, for instance, Lorentz invariance manifest). Because gauge symmetries are not real, they shouldn't be broken by quantum effects. This is why gauge and gravitational anomalies must all cancel in the theory, otherwise the quantum theory would be inconsistent. Gravitational anomalies are simply another kind of gauge anomaly, as local diffeomorphism invariance is a gauge symmetry of gravity.
So global anomalies are fine, the quantum theory just didn't have some symmetry you thought it might, and we can measure these in experiments. Gauge anomalies (and gravitational anomalies) are a sign that the theory doesn't make sense and should be zero in a physical system.
A few other things to note:

*

*There are a number of other interesting anomalies not mentioned above, e.g. 't Hooft anomalies.

*Conformal anomalies indicate the breaking of the scale invariance of a theory. QCD (with massless quarks and gluons) is classically scale invariant, but we know that this must be broken as QCD confines (and the quarks and gluons around us sit inside protons and neutrons).

*Technically speaking, a gauge anomaly sometimes means that you need to add more degrees of freedom to the theory.


text:
Q: Arduino based EEPROM programmer acts weird I use an Arduino Mega to program an AT28C256 by using this code [1], but there is a weird issue!
The Arduino's pin 41 is connected to the AT28C256's pin 16 which is I/O 4. It works without any problem up to 27-30 bytes, but afterwards it goes low!
For example, I tried to write 0xEA (11101010) to the first 200 addresses, first 29 bytes were fine, but after that all bytes were 0xE2 which means 11100010. I tired to program different EEPROMs with different data, e.g. 0xFF (11111111) but again after 30 bytes it was all 0xF7 (11110111).
I double checked connections and the circuit, everything seems to be fine (otherwise how could the first few bytes be correct?). I also captured the data with a logic analyzer, the capture shows this data line goes low after few bytes.
What could be wrong?
[1] https://create.arduino.cc/editor/albs_br/94b6f3f5-413d-4714-80dc-836bf5b3705c/preview

A: It looks like the code you linked to does not follow the standard programming algorithm of an EEPROM but just blindly programs a byte without ever polling for the end of the write cycle. The code waits 1 ms after programming every byte, but the write cycle time of an EEPROM can be larger than that see the AT28C256 datasheet, page 9.
Normally you check for the end of the EEPROM write cycle by reading back data from the EEPROM and checking if bit 7 of the data read back is equal to bit 7 of the data being written. This is explained in the data sheet, the I/O7 !DATA polling algorithm, page 1.

Your code just assumes the write cycle is finished within 1 ms (the delay(1) between the writeEnable() and chipDisable() calls and proceeds to programming the next byte. As some EEPROMs have a maximum write cycle time larger than 1 ms, this can fail.

The solution is to either implement a polling algorithm, which is preferred because it's faster and more reliable but it's also more complicated. The alternative is to wait for the maximum amount of time allowed for a write cycle (~10ms but this is dependent on your device).


text:
Q: Converting angle of circle to time in minutes I have been trying to develop a clock control with a help of a circle. So if the circle is at 360 degree its 3'O clock, if its 90 degree then it will be 12'o clock. I can't figure out what formula can be used to find the time in hh:mm format if I have the angle of the circle.
eg.
9'o clock is 180 degree.
3'o clock is 360 degree
12'o clock is 90 degree and so on.

A: There's probably a more concise way to do this, but here's what you need to do.

*

*Calculate the decimal value of the time, using  3 - (1/30) * (angle mod 360)

*If the result is less than zero, add 12.

*Take the integer portion to use as the hours, replacing a value of zero with 12.

*Take the remainder (the decimal portion of the calculation from step 1) and convert to minutes by multiplying by 60.

*Format your hours and minutes, padding with leading zeros if less than 10, and combine them with the colon.

An example implementation in java:
public static String convertAngleToTimeString(float angle) {
    String time = "";
    float decimalValue = 3.0f - (1.0f/30.0f) * (angle % 360);
    if (decimalValue < 0)
        decimalValue += 12.0f;

    int hours = (int)decimalValue;
    if (hours == 0)
        hours = 12;
    time += (hours < 10 ? "0" + hours: hours) + ":";
    int minutes = (int)(decimalValue * 60) % 60;
    time += minutes < 10 ? "0" + minutes: minutes;
    return time;
}

A: You could check out these formula's on Wikipedia, they might help: http://en.wikipedia.org/wiki/Clock_angle_problem
But other than that, you could do something simple like, degrees/360 * 12. + offset.
For example, if we set that 360 degrees is 12 o'clock, and you had 90 degrees. You would get. 90/360 * 12 = 3. So that would be 3'o clock. Then you could add your offset, which in your case is 3 so it would be 6 o'clock.

A: First assume 12 o'clock is at 0 degrees. This makes sense because the degrees just increases when going around the clock once, and so does the hours (there's no wrap-around), so maybe we can just multiply the hours by a constant.
To have it reach 360 again at 12 o'clock, we need to multiply the hours by 360/12 = 30.
So now 3 o'clock is at 90 degrees and 12 o'clock is at 0.
Subtract 90 and we have 3 o'clock at 0 and 12 o'clock at -90.
Then make it negative and we have 3 o'clock at 0 and 12 o'clock at 90, as required.
There we go, now you just need to put it all together.

A: hrs=date +%H                                  #H >>
min=date +%M                                  #min >>
dim=echo "scale=2; $hrs * 60 + $min" | bc     #day in minutes >>
dis=echo "scale=2; $dim * 60 + $sec" | bc     #day in seconds >>
did=echo "scale=2; $dis / 240" | bc           #day in degree >>
The Planet revolution is One degree per 240 seconds.
I work to make a sumerian-time-sys .
One sumerian hour is equivant with two current HRS or 30 revolution-degree.  search for sexagesimal systems.
Have fun!


text:
Q: Understanding PHP templates I am confused of the concept of templates in PHP. What does it really mean?What is the concept of templates in php?

    template

A: A template is basically a visual representation of something (like data I.E), can be dynamic or not, the template should hold placeholders that will be replaced with values passed to the template. Usually a template is a skeleton that should serve only as the visual representation (styles, markup). The main purpose of templates is to separate the logic from the visualization.
In MVC, the templates would be the View Layer.


text: Q: Variational Principle for a System of Differential Equations I am studying a differential operator of the form $$ L\left(\begin{array}{c} u \\ v \end{array}\right) = -\Delta \left(\begin{array}{c} u \\ v \end{array}\right) + V(x)\left(\begin{array}{c} u \\ v \end{array}\right) $$ where $V: \mathbb{R^n} \rightarrow M_{2\times 2}$ is smooth. Suppose further that $V$ is not of the form where the operator $L$ can be reduced to considering two separate scalar problems (e.g. $V$ is not diagonal, upper triangular, or lower triangular for all $x$). Does anyone know of a reference that talks about a variational principle for such an operator? I am mostly interested in the smallest eigenvalue of $L$ and the eigenspace of the smallest eigenvalue.


text:
Q: How do I get NetworkManager to keep the same IP? The DHCP-provided IP on my laptop changes periodically. It runs CentOS 6.5 and uses NetworkManager.
My desktop, running Sabayon, on the same network, does not have this problem.
How can I get NetworkManager to renew an existing DHCP lease instead of getting a new one?

A: The best way to guarantee the same IP at all times for a given host is to set up a MAC Address IP reservation in the DHCP server.  Get the MAC address if your laptop, then go to your DHCP server, and assign a specific IP address to be issued to a host requesting from that MAC address.

A: The dhclient that NetworkManager calls should be the same irregardless.
On my Fedora 19 system I'm getting the following command run via NetworkManager when I allow it to connect:
/sbin/dhclient -d -sf /usr/libexec/nm-dhcp-client.action     \
  -pf /var/run/dhclient-wlp3s0.pid                           \
  -lf /var/lib/NetworkManager/dhclient-5117671a-6bc3-4f6f-a3c0-54e615efe85c-wlp3s0.lease \
  -cf /var/lib/NetworkManager/dhclient-wlp3s0.conf wlp3s0

You can go through and check the setup of dhclient by looking at the various configuration files it's making use of via the command line.
Statically assigning IPs by MAC
I'll mention this even though @DopeGhoti did as well, but, in general, you typically take your systems' MAC addresses and configure your DHCP server so that it statically assigns the same IP addresses to the same MAC addresses. This gives you the best of both worlds, where you can centrally manage this assignment, but still not have to manually configure it on each host.
But in your case it sounds strange to me that the client isn't simply renewing the same IP that it previously had. That's normally the default behavior in DHCP client/server setups so I would suspect that something isn't configured quite right on your DHCP client.
Example
This is just to illustrate what I'm suggesting, realize you'd have to do something similar, configuring your network in whatever device happens to be providing your DHCP service. If you we're running your own DHCP server you could do something like this per host in your /etc/dhcpd.conf:
host grinchy {
   hardware ethernet 00:26:C7:85:A7:20;  # wifi (thinkpad 410)
  fixed-address grinchy.bubba.net;
  # fixed-address 192.168.1.19;
}

Doing it this way the host requires no knowledge of the networking configuration, but could still be given a consistent, static, IP.

A: The proper term is a Lease Reservation. This is where you set a specific address on your DHCP server for a MAC address. This is NOT like a static IP in the sense that, if there are no more addresses, and your computer isn't using that one, it WILL BE given to another machine if needed. So, in essence, with DHCP, there is no way to 'guarantee' one particular address, but then again that's what DNS is for :-)


text:
Q: Replace %20 with a space in filenames? I have a list of files that are using %20 to indicate a space in their names.
I'm currently trying to do the following to change them all from %20 to a space " ".
for x in *.txt
  do mv $x $(echo $x | sed -e 's/%20/ /')
done

That doesn't play nice. It spits out this:
usage: mv [-f | -i | -n] [-v] source target
       mv [-f | -i | -n] [-v] source ... directory

But I do the same thing on some of my images when I'm importing them and it works fine:
for x in *_MG*.CR2
  do mv $x $(echo $x | sed -e 's/_MG/_IMG/')
done

Forgetting that one is using .TXT and the other is .CR2, what am I totally overlooking here?
Keeping in mind I'm using a work laptop so I can't add Homebrew to install any additional software. And it's Mac OS X for the OS.

A: Use rename and replace the %20 with a space in all type of files:
$ rename -n 's/%20/ /g' *

File%20with%20in00.yA2 renamed as File with in00.yA2
File%20with%20in01.h9H renamed as File with in01.h9H
File%20with%20in02.CNR renamed as File with in02.CNR
File%20with%20in03.PuP renamed as File with in03.PuP
File%20with%20in04.js8 renamed as File with in04.js8
File%20with%20in05.KdZ renamed as File with in05.KdZ

In OS X you can use a specialized tool such as the Perl-based rename utility. you can install it using popular package manager Homebrew : brew install rename
Note: remove -n option to perform actual renaming.

A: Since the output of the mv probably will have spaces you need to put double quotes around the result in order not to try and execute commands in the for loop like:
mv abc%20def abc def

where mv has too many arguments. These are the ones giving you the usage: message.
What you should do is:
for x in *_MG*.CR2
do
  mv -- "$x" "$(printf '%s\n' "$x" | sed 's/_MG/_IMG/')"
done

A: There's no need to use sed, this can be handled by parameter expansion
mv -- "$x" "${x//%20/ }"

FWIW, I'd be replacing those %20s with an underscore (or something); I hate file names that contain spaces. But I guess learning how to write bash scripts that can handle spaces and other special characters in file names is a Good Thing. :)
As Izkata mentions in the comments, it's very important to quote parameters! Double quotes in bash (& related shells) aren't mere string delimiters, they also signify that you don't want word-splitting to occur. So if x contains a filename with a space in it $x will be treated as two arguments, but "$x" will be treated as a single argument. If we use single quotes we inhibit parameter expansion so '$x' just results in a literal string containing $x, which is generally not what we want. :)
PS. Thanks to Monsieur Chazelas for supplying the missing -- in my command line. -- indicates the end of options in the argument list; without it it's possible for file names commencing with - to be interpreted as options.


text:
Q: Converting string to float issue Hello world I have some issue trying to convert string that contains float number (ex. string s = "23.532") to float. Please take a look. Values are taken from .txt file.
Screenshot #1
Screenshot #2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Chart Properties
            chart1.ChartAreas[0].AxisX.ScaleView.Zoom(-5, 5);
            chart1.ChartAreas[0].AxisY.ScaleView.Zoom(0, 1000);
            chart1.ChartAreas[0].AxisX.ScaleView.Zoomable = true;

            chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;

        }

        private void BLoad_Click(object sender, EventArgs e)
        {
            //Load File
            string SingleNumb= "";
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                StreamReader sr = new StreamReader(File.OpenRead(ofd.FileName));

                while ((SingleNumb = sr.ReadLine()) != null)
                {
                    float value = float.Parse(SingleNumb);
                    //MessageBox.Show(value.ToString()); just to correct values
                }

                   //chart1.Series[0].Points.AddXY(Single.Parse(SingleNumb), i++);

                sr.Dispose();
                sr.Close();
            }

        }
    }
}

text file
0.534
-0.283
4.632
-8.5325

A: You should use float.TryParse(string, float) because it will test whether the string that you want to parse can be converted to a float before converting it.
Try this:
string floatString = "23.532";
float number = 0;
if (float.TryParse(floatString, out number)) Console.WriteLine($"Number = {number}");

float.TryParse(string, float) Method Converts the string representation of a number to its single-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed. true means succeeded and false otherwise.

A: If your string uses dot (.) as decimal separator, you should use this overload:
 float xFreq = Convert.ToSingle(param, CultureInfo.InvariantCulture);

Not really sure, but Additional information looks Slavic to me and the default decimal separator might be comma (,) instead of dot.  Of course, this depends on the culture of the current thread which depends on Regional settings.

A: Use TryParse and check the result.
float number;

if(float.TryParse(floatString, out number))
{
   ...
}

A: Update while loop inside the function BLoad_Click(...) as below:
while((SingleNumb = sr.ReadLine()) != null)
{
    NumberStyles style = NumberStyles.Any;
    CultureInfo culture = CultureInfo.InvariantCulture;

    float value = 0.0f;
    if (float.TryParse(SingleNumb, style, culture, out value))
    {
        MessageBox.Show(value.ToString());
    }
    else
    {
        MessageBox.Show("Conversion failed!");
    }
}

Note: 'float.TryParse(...)' - Converts the string representation of a number to its floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

A: Could you try:
string SingleNumb = "23.532";
float value = float.Parse(SingleNumb);

Result from conversion:

I wonder if the value you're loading from the file is a valid string!

A: You're looking for the Convert.ToSingle() method:
string floatString = "23.532";
float actualFloat = Convert.ToSingle(floatString);

A: Can you try this....
string SingleNumb = "";
string[] lines = System.IO.File.ReadAllLines(@"C:\testFile.txt");

// Display the file contents by using a foreach loop.
foreach (string line in lines)
{
     if((SingleNumb = line) != null)
     {
         float value = float.Parse(SingleNumb);
     }
}

(*) create a file "testFile.txt" in C:\ with the values that you have.
This should work as you expect.


text:
Q: Gmail API access on desktop + service bus endpoint, share token? I have a desktop and service bus that works in unison.
Basically I want to set it up so that the desktop app allows the user to authorise the desktop and service bus access to read and create emails on behalf of the user.
Firstly if I pass the access token to the server to save, I read that it's short lived, how would I ensure the server can always access the gmail apis if the access token ends up expiring?
On the desktop its interactive for the gmail api libraries to spawn a new web page, but on the service bus endpoint, it can't exactly call one of the authorize methods the gmail .net app provides and be able to have the user re-authorise it.
So what's the best approach to keep this as seamless as possible?
Thanks in advance!


text:
Q: Stop onclick method running with jQuery I have a button similar to below
<button id="uniqueId" onclick="runMethod(this)">Submit</button>

What I'm trying to do is stop the runMethod from running, until after I've done a check of my own. I've tried using the stopImmediatePropagation function, but this doesn't seem to have worked. Here's my jQuery:
$j(document).on('click', '#uniqueId', function(event) {
    event.stopImmediatePropagation();
    if(condition == true) {
        // continue...
    } else {
        return false;
    }

    return false;
});

Note: runMethod basically validates the form, then triggers a submit.

A: What you want to do, especially in the way that you want to do it, requires a some sort of workaround that will always be a bit fiddly. It is a better idea to change the way the button behaves (e.g. handle the whole of the click event on the inside of the jQuery click() function or something along those lines). However I have found sort of a solution for your problem, based on the assumption that your user will first hover over the button. I am sure you can extend that functionality to the keyboard's Tab event, but maybe it will not work perfectly for mobile devices' touch input. So, bear in mind the following solution is a semi-complete workaround for your problem:
$(document).ready(function(){
    var methodToRun = "runMethod(this)";    // Store the value of the onclick attribute of your button.
    var condition = false;                  // Suppose it is enabled at first.
    $('#uniqueId').attr('onclick',null);
    $('#uniqueId').hover(function(){
        // Check your stuff here
        condition = !condition;     // This will change to both true and false as your hover in and out of the button.
        console.log(condition);     // Log the condition's value.
        if(condition == true){
            $('#uniqueId').attr('onclick',methodToRun); // Enable the button's event before the click.
        }
    },
    function(){
        console.log('inactive');    // When you stop hovering over the button, it will log this.
        $('#uniqueId').attr('onclick',null);    // Disable the on click event.
    });
});

What this does is it uses the hover event to trigger your checking logic and when the user finally clicks on the button, the button is enabled if the logic was correct, otherwise it does not do anything. Try it live on this fiddle.
P.S.: Convert $ to $j as necessary to adapt this.
P.S.2: Use the Javascript console to check how the fiddle works as it will not change anything on the page by itself.

A: Your problem is the submit event, just make :
 $('form').on('submit', function(e) {
     e.preventDefault();
 });

and it works. Don't bind the button click, only the submit form. By this way, you prevent to submit the form and the button needs to be type button:
 <button type="button" .....>Submit</button>

Assuming there's a form that is submitted when button is clicked.

A: Try adding
event.cancelBubble();

Hence your code becomes:
$j(document).on('click', '#uniqueId', function(event) {
    // Don't propogate the event to the document

 if (event.stopPropagation) {
      event.stopPropagation();   // W3C model
  } else {
      event.cancelBubble = true; // IE model
  }

    if(condition == true) {
        // continue...
    } else {
        return false;
    }

    return false;
});

A: Your code is mostly correct but you need to remove J:
$(document).on('click', '#uniqueId', function(event) {...

You also need to remove the onClick event from the inline code - there's no need to have it there when you're assigning it via jQuery.
<button id="uniqueId">Submit</button>


text:
Q: Why does Ngrok give me this error about port 3000? I am trying to use NGROK so that I can use BeEF xss, whenever I start it and check the links, I get the error
"was successfully tunneled to your ngrok client, but the client failed to establish a connection to the local address localhost:3000.
Make sure that a web service is running on localhost:3000 and that it is a valid address.
The error encountered was: dial tcp [::1]:3000: connect: connection refused"


text:
Q: Can we get a stronger GUI indication of a change in Input Source? I often switch input sources to type in different languages' alphabets.
Because the same key is used to switch to each new input source, it is hard to remember the state of the system. Of course I can look at the toolbar, but that is just a small indicator.
Can we get a stronger indication, like a change in the color of the toolbar and dock, as input sources change?

A: An alternative approach would be to not use the "same" key to switch each new input source.  Instead you can try the Kawa app, which lets you give each layout its own keyboard shortcut.

A: In the input source menu bar tab, there is an option to show the input source name, which should make it a lot easier to see.

Additionally, holding down the keyboard shortcut for "Select the previous input source" (not "Select the next source in Input menu"!) shows a menu that allows you to cycle through all of your input sources:


text:
Q: How to speed up parallelization in Python I have the following function:
def function(arguments, process_number):
    calclulations that build vector_1 and vector_2 of size 100000 each
    return vector_1, vector_2

I need to run this function in parallel, for 200 different values of process_number. I am not interested in having an output ordered by process_number, so I am using apply_async(),  in the following fashion:
def parallelizing():
    number_of_process
    pool = mp.Pool(mp.cpu_count())

    size = 100000
    vector_1 = np.zeros(size)
    vector_2 = np.zeros(size)

    returned_object = [pool.apply_async(function,args=(args, procnum)) for procnum in range(number_of_process)]
    pool.close()
    pool.join()
    for r in returned_object:
        vector_1 += r.get()[0]
        vector_2 += r.get()[1]

So at the end of the day, I just have to add together all the vectors that I get as results from the function I am parallelizing.
The problem is that a big portion of the time used by the process is actually storing memory to build the [returned_object] list, which I think it is really not necessary as I simply need the return of the function to be added and then forgotten.
So I am trying to avoid building a huge list of objects, each containing at least two vecotrs of floats of size 100000, and get directly into the "addition" step.
Is there a way? Should I define a global variable and write on it inside the function? I fear it might lead to concurrency and screw things up. As I said, I really don't care about getting an ordered result, given that I simply need to add things up.

Edit from  Cireo answer down below:
Ok just to confirm if I understood. Instead of using the apply_async method, I would do something like the following:
def function(args, queue_1, queue_2):
     #do calculation
     queue.put(vector_1)
     queue.put(vector_2)

and inside the function that calls the parallelization I simply do
def parallelizing():
         queue1 = Queue()
         queue2=Queue()
         processid = np.arange(200)
         p = Process(target=f, args=(args,queue1,queue2,prcoessid))
         p.start()
         p.join()

What I don't really understand is how, instead of putting things in a Queue which to me seems as computationally intensive as creating a list, I can instead add the returns of my functions. if I do Queue.put() don't I end up with the same list as before?

A: It sounds like you've self-diagnosed this problem as the same as
Share the list of lists in multiprocessing
Don't create the list at all, just use a Queue or similar to send results from all your subprocesses back into the main process.  You said you don't care about order, so that should be pretty straightforward.
You could also investigate using shared memory, or just sharing the object across processes (though the second option might not be fast enough)
https://docs.python.org/3/library/multiprocessing.shared_memory.html

A: I'm not well acquainted with the multiprocessing module, but I am with threading, I'm not sure which would perform better,  but this is how I would thread it:
import numpy as np
from threading import Thread

def function(arguments, process_number, results, index):
    print(arguments, process_number)

    #calclulations that build vector_1 and vector_2 of size 100000 each
    # example arrays/vectors
    vector_1 = np.zeros(10000)
    vector_2 = np.zeros(10000)
    results[index] = (vector_1, vector_2)

count = 200

threads = [None] * count
results = [None] * count

args = ("example", "arguments")
process_numbers = range(1, count + 1)

for process_number, i in zip(process_numbers, range(count)):
    threads[i] = Thread(target=function, args=(args,process_number, results, i))
    threads[i].start()

for i in range(count):
    threads[i].join()

size = 10000
vector_1 = np.zeros(size)
vector_2 = np.zeros(size)

for result in results:
    vector_1 += result[0]
    vector_2 += result[1]


text:
Q: Why WinXP faster than Xubuntu under Virtualbox? I have two VMs configured identically (hardware wise), the only difference is that the Windows XP one is uber fast and the Xubuntu very slow. I know this is an open ended question, but would anyone have any hunches on why?

A: If it's a fresh install of XP (without updates, antivirus and everything else you need) then it will seem very fast compared with Xubuntu.
The minimum & recommended RAM for Xubuntu are 256mb & 512mb, which is 4 time more than XP.
Lubuntu would provide similar performance to XP.


text:
Q: Passing arguments to a function while assigning a value to the argument, javascript let's say we have variable a = "value1" and I pass it to a function through an argument called "arg"
now inside the function, I'm assigning arg to a value "value2"
my question is :
how passing arguments really work?
will "value2" be assigned to "arg" or variable "a" or both?
does arg get replaced with variable a (during passing)?
and what really confuses me is what gets passed, is it the name of the variable or its value ?
thank's
    var a = "value1";

    function myfunc(arg) {
        arg="value2";
    }

    myfunc(a);


text:
Q: Independent in statistics and independent in linear algebra? In statistics it says two random variables are independent if and only if $F_{X,Y}=F_X(x)F_Y(y)$
If linear algebra it says:
Two or more functions (random variable is a function), equations, or vectors $f_1, f_2, ...,$ which are not linearly dependent, i.e., cannot be expressed in the form
$a_1f_1+a_2f_2+...+a_nf_n=0 $
with $a_1, a_2, ...$ constants which are not all zero are said to be linearly independent.
My question is :Are there any relationship between these two definitions?
Thanks.

A: If two vectors are linearly independent, they are orthogonal, and their dot product is zero. The covariance is equivalent to (n times) the dot product, and the correlation is the normalized dot product. Correlation and covariance are zero if the variates are independent.


text:
Q: W/BroadcastQueue: Permission Denial: W/BroadcastQueue: Permission Denial: broadcasting Intent { act=com.moca.push.ACTION_PUSH_RECEIVE Hi im working with MOCA SDK,
all works but when I try to receiver action notification,
the app show me:

06-07 15:28:43.025 479-493/? W/BroadcastQueue: Permission Denial:
  broadcasting Intent { act=com.moca.push.ACTION_PUSH_RECEIVE
  dat=intent://moca/action/PQH24yPZTMuE8juAh2uxEw flg=0x10
  cmp=com.procibernetica.moca/com.innoquant.moca.push.MOCAPushReceiver
  bnds=[63,290][657,375] (has extras) } from com.procibernetica.moca
  (pid=-1, uid=10109) requires com.google.android.c2dm.permission.SEND
  due to receiver
  com.procibernetica.moca/com.innoquant.moca.push.MOCAPushReceiver

 <receiver
            android:name="com.innoquant.moca.push.MOCAPushReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.innoquant.moca.push.ACTION_PUSH_RECEIVE" />
                <action android:name="com.innoquant.moca.push.ACTION_PUSH_DISMISSED" />
            </intent-filter>
        </receiver>

 <receiver
            android:name="com.innoquant.moca.push.GcmPushReceiver"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="com.procibernetica.moca" />
            </intent-filter>
        </receiver>

At the moment I can't find the solution, if any one have a suggestion or response, I really appreciate this


text:
Q: Closed form for convolutions of random variables Is it possible to get Mathematica (9) to calculate PDF's for combined distributions? I can't seem to find the right notation, if this is possible at all. My attempts:
PDF[NormalDistribution[0, 1] + NormalDistribution[0, 1], x]

Nor can we store a distribution to a variable:
z \[Distributed] NormalDistribution[0, 1]
PDF[z, x]

A: dist = TransformedDistribution[u + v,
 {u \[Distributed] NormalDistribution[μ1, σ1],
  v \[Distributed] NormalDistribution[μ2, σ2]}];
PDF[dist, x]

Note: check the correct syntax for PDF in the docs.


text:
Q: Internal angles of a quadrilateral in MATLAB I have four points (x1, y1) ... (x4, y4) which describe four points in an image. They need not be in a cyclic order. I want to know the  all the internal angels of the quadrilateral formed by joining these four points
so I need a function like
function [theta1, theta2, theta3, theta4] = find_angels_quadrilateral([x1,y1], [x2,y2], [x3,y3], [x4,y4])
   # Logic goes here
end

I have tried atan2(y1-y2, x1-x2) four times and so on, but there is no guarantee that they are cyclic, so unable to proceed further.
More importantly any toolbox provides this functionality for me in MATLAB already?

A: A simple approach would be to compute first the convex hull of the points using convhull. It will return the points in a cyclic order (counterclockwise).
K = convhull([x1, x2, x3, x4], [y1, y2, y3, y4])

It will return something like that:
K =

     1
     3
     4
     2
     1

Meaning point [x1,y1] is the first, then comes [x3,y3], then [x4,y4] and so on (first point is duplicated at the end to close the hull, so you can ignore that).
After that you can compute the angles with no problems.


text:
Q: Are these two methods equivalent? This question is related to one I just asked here.
Givenservers is a private static ConcurrentHashMap, are the following two methods and the third approach all equivalent in that the servers map will reflect the change made by all three?
1.
public static synchronized int releaseConnection(Server s) {
    return servers.get(s.getId()).decrementConns();
}

2.
public static synchronized int releaseConnection(Server s) {
    return s.decrementConns();
}

3.  just call decrementConns() where its needed (in other classes)?

A: 3rd way is best and should be sufficient.
All 3 will do the job but 1 and 2 are not needed as you are working with ConcurrentHashMap.


text:
Q: Java String.replaceAll regex What is the regex to strip the MY-CORP\ part of na inputed string like MY-CORP\My.Name with the java String.replaceAll method so I can get only the My.Name part?
I tried
public static String stripDomain(String userWithDomain) {
    return userWithDomain.replaceAll("^.*\\", "");
}

but i got Unexpected internal error near index 4 ^.*

A: Your problem is that the backslash has special meaning both in Java strings and in regexes. So you need four slashes in the Java source code, passing two to the regex parser to get one literal one in the regex:
return userWithDomain.replaceAll("^.*\\\\", "");


text:
Q: Ubuntu distorts sounds at higher volume I recently (~2 weeks) switched to Ubuntu and the sound is crazy distorted at volumes higher than 50%. At 50%, the speaker volume is not high enough for regular usage. I've so far tried tweaking around with AlsaMixer and replacing PulseAudio with Pipewire and neither solved my problem.
How do i fix this?
To see a sample of the distortion, here's a 45 second video. You can skip ahead to 35 (-10) seconds / 15 (-30) seconds to hear the distortion.
Note - this isn't an issue with the speakers/hardware as they worked perfectly fine when I used Windows.
I own an Acer Swift 3 (2018 version) - SF314-52. Terminal Output of sudo lspci -v:
00:1f.3 Audio device: Intel Corporation Sunrise Point-LP HD Audio (rev 21) (prog-if 80)
    Subsystem: Acer Incorporated [ALI] Sunrise Point-LP HD Audio
    Flags: bus master, fast devsel, latency 32, IRQ 129
    Memory at b1120000 (64-bit, non-prefetchable) [size=16K]
    Memory at b1100000 (64-bit, non-prefetchable) [size=64K]
    Capabilities: [50] Power Management version 3
    Capabilities: [60] MSI: Enable+ Count=1/1 Maskable- 64bit+
    Kernel driver in use: snd_hda_intel
    Kernel modules: snd_hda_intel, snd_soc_skl

Updating: adding output of aplay -l:
**** List of PLAYBACK Hardware Devices ****
card 0: PCH [HDA Intel PCH], device 0: ALC255 Analog [ALC255 Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 3: HDMI 0 [HDMI 0]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 7: HDMI 1 [HDMI 1]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 8: HDMI 2 [HDMI 2]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 9: HDMI 3 [HDMI 3]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 10: HDMI 4 [HDMI 4]
  Subdevices: 1/1
  Subdevice #0: subdevice #0


text:
Q: two join fields as valueField I am trying to combine two join fields as a valueField in a dropdown combo.
After checking https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#finding-key-value-pairs and How do I create a keyValue pair (display field) by combining/having two fields in CakePHP 3? I tried the following:
This works:
$authorities = $this->Books->Authorities->find('list', [
            'valueField' => 'author.name'])
            ->contain(['Authors', 'AuthorTypes']);

This works too:
$authorities = $this->Books->Authorities->find('list', [
            'valueField' => 'author_type.name'])
            ->contain(['Authors', 'AuthorTypes']);

But this doesn't:
$authorities = $this->Books->Authorities->find('list', [
            'valueField' => function ($row) {
                return $row['author.name'] . ' - ' . $row['author_type.name'];
            }])
        ->contain(['Authors', 'AuthorTypes']);

I can't understand why. Any ideas? :)

A: As one of the comments suggested, follow this examples.
Your code should be:
$authorities = $this->Books->Authorities->find('list', [
            'valueField' => function ($row) {
                return $row->author->name . ' - ' . $row->author->name;
            }])
            ->contain(['Authors', 'AuthorTypes']);

This is called Customize Key-Value Output. The $row argument is an object instead of a simple array_object.


text:
Q: completion with the second argument of a command in texstudio From Texsudio manual on autocompletion files:
"The classifiers specifying the meaning of arguments (like c or i) always apply to the first non-optional parameter. This is a current limitation of the cwl format and the LaTeX parser in TXS. For example \ref{label}#r and \ref[option]{label}#r will work as expected, but \ref{arg}{label}#r will interpret arg as reference. We recommend not to specify any class in such a case."
Does it mean that there is no way to use the second argument of command as a label recognized by texstudio or one can "skip class" and use the next argument?
for example:
\newcommand{\dplot}[3]{
\begin{figure}
    \centering
    \subfigure[]{\includegraphics[width=0.49\columnwidth]{Fig/#1}
        \label{fig:#1}}
    \hspace*{-0.01\columnwidth}
    \subfigure[]{\includegraphics[width=0.49\columnwidth]{Fig/#2}
        \label{fig:#2}}
    \vspace*{-0.01\columnwidth}
    \caption{#3}
    \label{fig:#1:#2}\label{fig:#1_Full}
\end{figure}
}

I can use cwl file to recognize 1st argument by adding:
\dplot{label}#l

Could I do some skipping like:
\dplot{}{label}#l

in order to use the second argument as a label?

A: The statement you mentioned from the manual is outdated.
If you use the #l qualifier, you can define an arbitray argument as label, but it's name has to be label.
\dplot{arg}{label}#l

If you want to use a different name or multiple labels, you can use the inline definition with labeldef.
\dplot{label1%labeldef}{label2%labeldef}

Note: Your example will still not work, because the names labels and references have to be identical. Otherwise TeXstudio cannot match them. You cannot \dplot{mylabel} and \ref{fig:mylabel}. See also autocomplete with labels defined by user commands.


text:
Q: If $f_{n-1}^2=(f_n/2)^2+h^2$ then $n=6$ How can I prove that if $f_n$ is a term of the Fibonacci sequence divisible by $4$ and if $$f_{n-1}^2=(f_n/2)^2+h^2,$$ $h\in\Bbb Z^+$ then $n=6$?
I know that since $\gcd(f_k,f_{k+1})=1$ for every $k\in\Bbb N$ then $h$ must be odd and that if $h=2m+1$ with $m\in\Bbb Z$ then $h=(m+1)^2-m^2$. But I cannot assume that $f_{n-1}=(f_n/2)+1$ so I don't know how to proceed.
Any help is really appreciated.

A: We need $4h^2 = 4f_{n-1}^2-f_n^2 = (2f_{n-1}+f_n)(2f_{n-1}-f_n) = (4f_{n-2}+3f_{n-3})f_{n-3}$.
Since $\gcd(f_{n-2},f_{n-3}) = 1$, we have $\gcd(4f_{n-2}+3f_{n-3},f_{n-3}) = \gcd(4f_{n-2},f_{n-3}) \in \{1,2,4\}$.
Let $v_p(n)$ denote the largest integer $k$ such that $p^k \mid n$.
Then, if $p \ge 3$ is a prime such that $p \mid f_{n-3}$, then $p \not\mid (4f_{n-2}+3f_{n-3})$, and so we have $v_p(f_{n-3}) = v_p((4f_{n-2}+3f_{n-3})f_{n-3}) = v_p(4h^2) = v_p(h^2) = 2v_p(h)$, which is even.
If $p \ge 3$ is a prime such that $p \not\mid f_{n-3}$, then trivially, $v_p(f_{n-3}) = 0$, which is even.
Therefore, $v_p(f_{n-3})$ is even for all primes $p \ge 3$.
Hence $f_{n-3}$ is either a perfect square or twice a perfect square.
By this link the only Fibonacci numbers which are perfect squares are $0,1,144$, and the only Fibonacci numbers which are twice a perfect square are $0,2,8$. So it remains to check all of these $5$ cases and see which work.

A: Recall the pythagorean triples are of the form $(u^2-v^2,2uv,u^2+v^2)$. As you pointed out $h = 2m+1$ is the odd member of the triplet, that makes $\dfrac{f_n}{2} = 2uv$ and $f_{n-1} = u^2+v^2$. Thus, $f_{n-3} = 2(u-v)^2$.
The only Fibonacci Number $f_k$ which is twice a perfect square are when $k = 0,3,6$.
${n-3}$ cannot be $0,6$. Thus, $n = 6$.

A: Note that
$$h^2=f_{n-1}^2-(f_n/2)^2=(f_{n-1}-f_n/2)(f_{n-1}+f_n/2)$$
Now
\begin{align*}\gcd(f_{n-1}-f_n/2,f_{n-1}+f_n/2)&=\gcd(f_{n-1}-f_n/2,f_n)=\gcd(f_{n-1}-f_n/2,f_n/2)\\&=\gcd(f_{n-1},f_n/2)=1\end{align*}
(the second step is allowed since $f_{n-1}-f_n/2$ must be odd and you already know the last step)
This means $f_{n-1}-f_n/2=f_{n-1}/2-f_{n-2}/2=f_{n-3}/2$ must be a perfect square, but it is well known this is only possible for $n=3$, $n=6$, or $n=9$. But only for $n=6$ is $f_{n-1}+f_n/2$ also a square.


text:
Q: RXjava with MVVM and Retrofit I want to use RxJava with MVVM but I don't understand why it doesn't respond CompositeDisposable with my Response class
I want to deal with RxJava that is by but I don't know how to link CompositeDisposable  with
LiveData
...
LiveData
     public
        LiveData <HomeResponse> setMenu() {
            final MutableLiveData <HomeResponse> data = new MutableLiveData <>( );

                compositeDisposable.add(apiRequest.getMenu()
                                                .subscribeOn( Schedulers.io())
                                                .observeOn( AndroidSchedulers.mainThread())
                                                .subscribe( new Consumer <Response<HomeResponse>>() {
                                                    @Override
                                                    public void accept(Response<HomeResponse>
                                                     registrationModelResponse) throws Exception  {

                                                       data.setValue(registrationModelResponse.body());
                                                    }
                                                }));

            return data;
        }

.....
Response class :
  public
class HomeResponse {

    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("totalResults")
    @Expose
    private Integer totalResults;
    @SerializedName("Menu")
    @Expose
    private List <MainMenu> MainMenu = null;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Integer getTotalResults() {
        return totalResults;
    }

    public void setTotalResults(Integer totalResults) {
        this.totalResults = totalResults;
    }

    public List<MainMenu> getMainMenu() {
        return MainMenu;
    }

    public void setAUsers(List<MainMenu> MainMenu) {
        this.MainMenu = MainMenu;
    }
}

.....
my API :
  @GET("getmenu.php")
   Observable<List <HomeResponse>> getMenu();

..............
error hear ...
 .subscribe( new Consumer <Response<HomeResponse>>() {
                                                @Override
                                                public void accept(Response<HomeResponse>
                                                 registrationModelResponse) throws Exception  {

                                                   data.setValue(registrationModelResponse.body());
                                                }
                                            }));

enter image description here

A: I think's maybe you confuse how to handle LiveData.
Regularly, if you want to get value from LiveData, your activity or fragment is the one who need to observe it. Like this example.
// I have 'valueA' as variable in viewModel.
val valueA = MutableLiveData<String>()

// In Main Activity. I observe 'valueA' here
fun initObserver() {
    viewModel.valueA.observe(this, Observer { it -> // it is value of livedata 'data'
        // do something with 'valueA'.
    })
}

And your setMenu() function should not return value from API because when you call API like that it's asynchronous call. So when you return your value your API call still not complete.
This should be your function.
public void setMenu() {
        final MutableLiveData <List<HomeResponse>> data = new MutableLiveData <>( );

            compositeDisposable.add(apiRequest.getMenu()
                                            .subscribeOn( Schedulers.io())
                                            .observeOn( AndroidSchedulers.mainThread())
                                            .subscribe( new Consumer <List<HomeResponse>>() {
                                                @Override
                                                public void accept(List<HomeResponse>
                                                 registrationModelResponse) throws Exception  {

                                                   data.setValue(registrationModelResponse);
                                                }
                                            }));

    }

PS. Sorry for my terrible English skill.
PS2. Your Response from API will return List<HomeResponse>, but in your comsumer it's become Result<HomeResponse> so it's will cause error.


text:
Q: JLabel[][] array index out of bound error I'm getting an array index out of bound exception on the following code. I used debugger and this is what happened.

JLabel[][] labelHolder = new JLabel[8][8];

    for(int i=0; i<8; i++){
        for(int j=0; i<8; j++){
            labelHolder[i][j] = new JLabel ();   <- error occur right on this line when i=j=0

I have not clue why this is because if I just swap out the i and j for 0 and 0, it work perfectly :S

A: The condition in your second for-loop checks against the value of i instead of j
for(int j = 0; i < 8 ; j++)

should be
for(int j = 0; j < 8 ; j++)

A: Use:
for(int j=0; j<8; j++){
             ^

A: for(int j=0; i<8; j++){ This line has the problem, it should read j<8.

A: In your second loop, your stop condition is mistaken: replace i < 8 by j < 8.


text:
Q: Calculate the constants (transmission rate etc.) in the SIRV model without knowing S, I values calculated in the model I want to model the pandemic using the SIRV model below:
$$\frac{dS}{dt}=\beta S(t)I(t)-\gamma I(t)$$
$$\frac{dR}{dt}=rI(t)+u(t)$$
$$\frac{dS}{dt}=-\beta S(t)I(t)-u(t)$$
Since there is no data about the parameters ($\gamma$ and $\beta$) of Covid-19, I want to calculate them based on the data of infected population on the governments' website. I want to use the method about inverse problem provided by this article.
Is this an unsolvable problem?
One the one hand, the method of calculating $\beta$ and $\gamma$ requires us to know values of $S$ and $I$, which need to be obtained from the formulas above. On the other hand, I cannot calculate the above formulas without knowing $\gamma$ and $\beta$.


text:
Q: Must inherited be called on the first line? I have seen a piece of code like this (not mine).
The author sets FField on the first line in the constructor before calling inherited. I am curious if this code valid.
TTest = class(TBaseObject, ITest)
    private
    protected
        FField: TObject;
    end;

constructor TTest.Create(aField: TObject);
begin
    FField:= aField;
    inherited Create();
    ...
end;

I think the memory for FField was already allocated and nilled at that point. Right?

A: The code is valid. By the time your constructor runs, the instance has been allocated and default initialised.
Setting a member before calling the inherited constructor means that if the inherited constructor accesses that member, it will read the value provided by the call to the derived constructor. Whilst the inherited constructor cannot directly access the member, in this case, it could access it by calling a virtual method. Note, however, that calling virtual methods from constructors is a somewhat dubious practice, because the instance may be partially constructed.


text:
Q: Execute function if and only if a certain amount of time has elapsed since subscription with RxJS I am making an API call through an Observable. If this API call takes more than 200ms, I would like to show a loading screen (by assigning 'true' to my 'loading' variable), otherwise I don't want to show anything, in order to avoid a blink on screen.
Is there an RxJS operator capable of doing this ?
this.apiService.get(`/api/someEndpoint`)

// I hope for something like
.triggerIfAtLeastThisAmountOfTimeHasElapsed(200, () => {
  this.loading = true;
})

.subscribe(response => {

  // Process the response

  this.loading = false;
});

A: There are many ways to do this so you can use for example this:
const api = this.apiService.get(`/api/someEndpoint`);
const loading = Observable
  .timer(1000)
  .do(() => loading = true) // show loading
  .ignoreElements(); // or `filter(() => false)

Observable.merge(api, loading)
  .take(1)
  .subscribe(() => loading = false);

A: Along the same lines of Martin's response, this is an example that should simulate your context
const obs1 = Observable.timer(200).take(1);

const apiSubject = new Subject<string>();
const apiObs = apiSubject.asObservable();
const apiExecutionElapsed = 1000;

const obs3 = Observable.merge(obs1, apiObs);

let loading = undefined;

obs3.subscribe(
  data => {
    console.log(data);
    if (loading === undefined && data === 0) {
      loading = true;
    } else {
      loading = false;
    }
    console.log('loading', loading);
  },
  console.error,
  () => {
    loading = false;
    console.log('loading', loading);
  }
)

setTimeout(() => {
  apiSubject.next('I am the result of the API');
  apiSubject.complete()}, apiExecutionElapsed)

If the execution of the api (apiExecutionElapsed) takes longer than the configured timer (200 ms in this case) you see the loading flag to become first true and then false. Otherwise it remains always false.


text:
Q: what is the correct way to feed an ssl certificate into phantomjs I need to access an internal site protected via client side certificates. Therefore to use phantomjs I exported the certificate I use in Firefox to access the site and converted it into private key and certificate using openssl command line. I now what phantomjs to present that certificate to the ssl server when accessing a page on the server. How do I do it?
I've tried this
phantomjs --ssl-certificates-path=/etc/pki  --ignore-ssl-errors=yes --proxy=myproxy:myport test.js

with /etc/pki being the path I've put the certificate and key
test.js is just this;-
page = require('webpage').create()
page.open('https://myprotectedsite/', function(status) {
console.log(status);
phantom.exit();
})

But it doesn't work. console.log(status) is always 'fail'
What do I need to do?

A: Client certificate support has actually has been implemented since the original accepted answer. I'm posting this in order to help others who will stumble upon this question as well. You can find the parameters for enabling X509/PKI certificate support in PhantomJS's CLI instructions:
phantomjs --ssl-certificates-path=/path/to/pki/rootCA.pem
          --ssl-client-certificate-file=/path/to/pki/cert.pem
          --ssl-client-key-file=/path/to/pki/cert.np.key

A: I look for the decision too. it isn't implemented
https://github.com/ariya/phantomjs/issues/10524
"--ssl-certificates-path" - It is used for the CA certificate

A: The feature it's implemented you can see on github project, the thing is that it's not already included in the actual stable release (2.0.0), however it's planned to be included on 2.0.1 release. Meanwhile you can download a 2.0.1 build from here (the link is from git discussion).
I try using 2.0.1 version and I can access to the site correctly passing the SSL client authorization with the follow command:
Finally new PhantomJS 2.1 version was released which includes this feature, you can download from here and test the SSL client authorization using the follow command:
phantomjs --ssl-client-certificate-file=C:\tmp\clientcert.cer
          --ssl-client-key-file=C:\tmp\clientcert.key
          --ssl-client-key-passphrase=1111
          --ignore-ssl-errors=true
          C:\tmp\test.js

Notes
I only test this on Windows.
I try to use a PKCS12 file as keystore but seems that with this format doesn't work, so using openssl I extract the certificate and the private key using the follow commands:
Extract cert for --ssl-client-certificate-file parameter
openssl pkcs12 -nokeys -clcerts -in a.p12 -out clientcert.cer

Extract key for --ssl-client-key-file parameter
openssl pkcs12 -nocerts -in a.p12 -out clientcert.key

Additionally I use --ignore-ssl-errors=true to avoid the configuration of the trust store for the validation of the server certificate.
As script I use test.js which contains the same has OP show on the question:
page = require('webpage').create()
page.open('https://myproject', function(status) {
      page.render('C:/temp/connect.png');
      console.log(status);
      phantom.exit();
})


text:
Q: When and why to use &?, =?, @? in AngularJS? I followed some tutorials to create angular directives. In the isolate scope, some tutorials define scope like this:
scope: {
  model: '=?',
  data:  '@?'
}

Meanwhile, some tutorials define scope without question mark like this:
scope: {
  model: '=',
  data:  '@'
}

Can anybody explain me the difference or the purpose of these with examples? Thank you.

A: The &, @, and = symbols are used to define the bindings (one-way, bi-directional, etc) for isolated scope objects, as you already know. Here is a pretty thorough tutorial on how all this works.
The ? symbol is used to indicate that the parent scope property to which the isolated scope binding refers to is optional. This means that if for some reason the parent scope property doesn't exist, then your application will continue to run without throwing the NON_ASSIGNABLE_MODEL_EXPRESSION exception.


text:
Q: Disable Author Archive just for certain roles in bulk Hi I have a lot of users that have the role in wordpress as "Buyer" I want to be able to disable these users archive page so it is not public but I want to keep public users that have the role as "Agent". Is there a easy way to do this in bulk at all?
I found #chrisguitarguy plugin at Disable author pages for specific users very good but you have to disable the user one at a time and it is absolute nightmare to do this if you have alot of users.
Does anyone have a solution at all?
Thanks

A: A simple way to achieve this is to do a conditional redirect on template_redirect action. In the action callback, check that the request is for an author archive of the specified role and if it is, then do the redirect.
function my_disabled_author_archive_role() {
    return 'buyer';
}

add_action(
    'template_redirect',
    function() {
        // Is this an author archive?
        if ( ! is_author() ) {
            return;
        }
        // Does the author have the specified role?
        $author = get_queried_object();
        if ( ! in_array( my_disabled_author_archive_role(), (array) $author->roles ) ) {
            return;
        }
        // Redirect to somewhere
        if ( wp_safe_redirect( home_url() ) ) {
            exit;
        }
    }
);

If you want to exclude the role also from the default WP sitemap, then filter the users sitemap query args.
add_filter(
    'wp_sitemaps_users_query_args',
    function($args) {
        $args['role__not_in'] = my_disabled_author_archive_role();
        return $args;
    }
);


text:
Q: Using Cron job with Codeigniter Result to this for some hours now i have been trying to use cron job to automatic upgrade user in my db by calling the the controller.
but this is what i keep getting on my email, i dont know where have gone wrong.
i will greately appreciate if anyone can please correct me

A PHP Error was encountered

Severity: Warning

Message:  session_start(): Cannot send session cookie - headers already sent

Filename: Session/Session.php

Line Number: 143

Backtrace:

                        File: /home/esclubso/public_html/application/core/My_Controller.php

                        Line: 8

                        Function: __construct

                        File: /home/esclubso/public_html/application/controllers/Welcome.php

                        Line: 6

                        Function: __construct

                        File: /home/esclubso/public_html/index.php

                        Line: 316

                        Function: require_once

i have spent time deleting all with space from my controller yet nothing seem to be working and here is my controller
<?php
class My_Controller extends CI_Controller{
    public $layout;
    public $layout2;
    public $admin_layout;
    public $user_layout;
    public function __construct(){
        parent::__construct(); // this is the line 8

        $this->layout   ='master';

        $this->user_layout  ='dashboard/user_dashboard/master';
        $this->admin_layout ='dashboard/admin_dashboard/master';
        $this->load->library('Session_checker');

        $this->load->model('Action');
        $this->load->model('Login_user');
        $this->load->model('Reaction');
        $this->load->model('Upgrade_account');
        $this->load->model('Manage_user');
    }
}

My welcome controler
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends My_Controller {
    public function __construct(){
        parent::__construct(); // this is the line 6
    }
    public function index(){
        $this->load->view('index');
    }
}


text:
Q: Título dinámico en JavaFX soy un principiante aprendiendo JavaFX, el problema que tengo es que en mi programa quiero colocar un título que cambia cada que se use un una variable string, que esta variable String obtenga el valor de un choiceBox, y coloque el texto en el título. Intente colocar un nodo textField, un textArea y un Text para realizar esta acción con el método setText(), sin embargo al leer documentación de JavaFX, entiendo que estos nodos sólo pueden mostrar texto ingresado por el usuario (si me equivoco, agradecería la corrección),¿Cómo puedo realizar dicha acción?. Saludos

A: cambiar título de Stage con ComboBox y  TextField

ComboBox tiene una propiedad que puede ser escuchada valueProperty() toda vez que se selecciona un nuevo valor para el objeto comboBox éste le pasa el String a stage en stage.setTitle(comboBox.getValue()). lo mismo con TextField toda vez que se actualiza el text este le pasa stage.setTitle(textField.getText())
Esta es una aplicación JavaFX en una sola clase que puede probar
public class App extends Application {

    @Override
    public void start(Stage stage) {

        ObservableList<String> values =FXCollections.observableArrayList();
        values.addAll("titulo1","titulo2","titulo3");

        ChoiceBox<String> choiceBox = new ChoiceBox<String>(values);
        choiceBox.valueProperty().addListener(e-> stage.setTitle(choiceBox.getValue()));

        TextField textField = new TextField();
        textField.setPromptText("cambiar título");
        textField.textProperty().addListener((o) -> {
            stage.setTitle(textField.getText());
        });

        HBox hBox = new HBox(choiceBox,textField);
        hBox.setSpacing(20);
        hBox.setAlignment(Pos.CENTER);

        Scene scene = new Scene(hBox, 640, 480);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

}


text:
Q: class scopes in PHP This is an outline of a problem which I'm struggling to solve in my code. I guess my knowledge of scope isn't that great.. I don't understand why the function getGreeting is giving a parse error.
<?php

class Class_1 {

    public $t;

    public function __construct() {
        $this->t = "hello world";
    }

    public function helloWorld() {
        return $this->t;
    }
}

$x = new Class_1();

function getGreeting() {
    return $x->helloWorld();;
}

echo getGreeting();

?>

the error I get is:
Fatal error: Call to a member function helloWorld() on a non-object.

A: Because you need to initialize object in the function to access it's methods from it :
 function getGreeting() {
    $x = new Class_1();
    return $x->helloWorld();;
}

Example


text:
Q: Any ideas why Mavericks is slowing down due to BetterSnapTool? I use BetterSnapTool to resize my windows with keyboard shortcuts. Since upgrading to Mavericks, after I've used my computer for 6-12ish hours, scrolling and moving things around the screen using the trackpad becomes sluggish and stutters. When I close BetterSnapTool, it fixes the issue, and it stays fixed until I relaunch.
Any ideas what is causing the issue? Is there an easy, low overhead way to automatically quit and relaunch BetterSnapTool every 4 hours or so?

A: (This answers the second question about how to automate restarting BetterSnapTool. Since I haven't experienced the issue described and have no second-hand explanations, I can't answer the question of why this is happening.)
Here is a quick and simple AppleScript I whipped up that works for restarting BetterSnapTools:
tell application "BetterSnapTool"
quit
end tell

delay 2 -- Wait for BetterSnapTool to close

tell application "BetterSnapTool" to activate

If you want to set this to automatically run every, say, 6 hours I think your best bet is to create a Launch Daemon using launchd. A quick presentation of this approach can be found here. For more information, check the entry on creating Launch Daemons in the apple developer's library.
You said "low overhead", which I took to mean using only methods native to OS X. If you're fine with third-party software, though, this GUI application for cron (the precursor to launchd) scheduling seems promising (but I haven't tried it so can't be certain).


text:
Q: ruby 1.8.7 installation error on ubuntu 11.10 recently I re installed Ubuntu 11.10 and was trying to set my working ruby and rails framework. But now I can not install 1.8.7 on my system. I loaded RVM successfully, i hope. The version it displays is 1.20.4. But as I proceed to install my rubies it throws error as
No binary rubies available for: ubuntu/11.10/x86_64/ruby-1.8.7-p371.
Continuing with compilation. Please read 'rvm mount' to get more information on binary rubies.
I have gone through so many online suggestion but nothing seems to work.
Any ideas guyz???
Also when I check the available ruby versions using rvm list known, it displays the list of rubies available and 1.8.7 is among one of them, then why this error appears as No binary rubies available. I need to have ruby 1.9.3 and 1.8.7.
kumar@Jarvis-Dell-XPS-L502X:~$ rvm install ruby-1.8.7
Searching for binary rubies, this might take some time.

No binary rubies available for: ubuntu/11.10/x86_64/ruby-1.8.7-p371.
Continuing with compilation. Please read 'rvm mount' to get more information on binary  rubies.

Installing requirements for ubuntu, might require sudo password.
Hit http://it.archive.ubuntu.com oneiric Release.gpg
Hit http://it.archive.ubuntu.com oneiric-updates Release.gpg

kumar@Jarvis-Dell-XPS-L502X:~$ rvm -v
rvm 1.20.4 (master) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis       <mpapis@gmail.com> [https://rvm.io/]

A: Please refer the link http://coding.smashingmagazine.com/2011/06/21/set-up-an-ubuntu-local-development-machine-for-ruby-on-rails/ this tutorial guides you perfectly for your Ruby Set up on Ubuntu 11.10

A: You can try to replace RVM with rbenv. Did you try rbenv before?


text:
Q: Invalid instance type when creating elasticsearch domain through cloudformation I am trying to deploy an elasticsearch domain through CFT, but getting following error:
Invalid instance type: r6g.large.elasticsearch (Service: AWSElasticsearch; Status Code: 409; Error Code: InvalidTypeException;
My CFT is :
Resources:
  ElasticsearchDomain:
    Type: 'AWS::Elasticsearch::Domain'
    Properties:
      DomainName: test
      ElasticsearchVersion: 7.10
      ElasticsearchClusterConfig:
        InstanceCount: '1'
        InstanceType: r6g.large.elasticsearch
      EBSOptions:
        EBSEnabled: true
        Iops: '0'
        VolumeSize: '10'
        VolumeType: 'standard'
      AccessPolicies:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              AWS: '*'
            Action: 'es:*'
            Resource: '*'
      AdvancedOptions:
        rest.action.multi.allow_explicit_index: true
      Tags:
        - Key: foo
          Value: bar
      VPCOptions:
        SubnetIds:
          - Ref: subnet
        SecurityGroupIds:
          - Ref: mySecurityGroup
  vpc:
    Type: 'AWS::EC2::VPC'
    Properties:
      CidrBlock: 10.0.0.0/16
  subnet:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId:
        Ref: vpc
      CidrBlock: 10.0.0.0/24
      AvailabilityZone: us-west-2a
  mySecurityGroup:
    Type: 'AWS::EC2::SecurityGroup'
    Properties:
      GroupDescription: test
      VpcId:
        Ref: vpc
      GroupName: testsg
      SecurityGroupIngress:
        - FromPort: 443
          IpProtocol: tcp
          ToPort: 443
          CidrIp: 0.0.0.0/0

please ignore the hard coding of variables, that was done to eliminate use of parameters.
I can see in documentation that r6g.large is indeed supported. the code works when using instance type as given in this answer, but my use-case requires having r6g.large as instance type. Any help would be appreciated.

A: problem isn't with your instance type, it's the version your are using for elasticSearch in your CFT.

ElasticsearchVersion: 7.10

The R6G instance types require Elasticsearch 7.9 or later or any version of OpenSearch. basically it's compatible only with latest one, please change the version and give a try.


text:
Q: How can I get the length of a protein chain from a PDB file with Biopython? I have tried it this way first:
for model in structure:
    for residue in model.get_residues():
        if PDB.is_aa(residue):
            x += 1

and then that way:
len(structure[0][chain])

But none of them seem to work...

A: Your code should work and give you the correct results.
from Bio import PDB
parser = PDB.PDBParser()

pdb1 ='./1bfg.pdb'
structure = parser.get_structure("1bfg", pdb1)
model = structure[0]
res_no = 0
non_resi = 0

for model in structure:
    for chain in model:
        for r in chain.get_residues():
            if r.id[0] == ' ':
                res_no +=1
            else:
                non_resi +=1

print ("Residues:  %i" % (res_no))
print ("Other:     %i" % (non_resi))
res_no2 = 0
non_resi2 = 0
for model in structure:
    for residue in model.get_residues():
        if PDB.is_aa(residue):
            res_no2 += 1

        else:
            non_resi2 += 1

print ("Residues2: %i" % (res_no2))
print ("Other2:    %i" % (non_resi2))

Output:
Residues:  126
Other:     99
Residues2: 126
Other2:    99

Your statement
print (len(structure[0]['A']))

gives you the sum (225) of all residues, in this case all amino acids and water atoms.
The numbers seem to be correct when compared to manual inspection using PyMol.
What is the specific error message you are getting or the output you are expecting? Any specific PDB file?

Since the PDB file is mostly used to store the coordinates of the resolved atoms, it is not always possible to get the full structure. Another approach would be use to the cif files.
from Bio import PDB
parser = PDB.PDBParser()

pdb1 ='./1bfg.cif'

m = PDB.MMCIF2Dict.MMCIF2Dict(pdb1)

if '_entity_poly.pdbx_seq_one_letter_code' in m.keys():
    print ('Full structure:')
    full_structure = (m['_entity_poly.pdbx_seq_one_letter_code'])
    print (full_structure)
    print (len(full_structure))

Output:

Full structure:
  PALPEDGGSGAFPPGHFKDPKRLYCKNGGFFLRIHPDGRVDGVREKSDPHIKLQLQAEERGVVSIKGVSANRYLAMKEDGRLLASKSVTDECFFFERLESNNYNTYRSRKYTSWYVALKRTGQYKLGSKTGPGQKAILFLPMSAKS
  146

For multiple chains:
from Bio import PDB
parser = PDB.PDBParser()

pdb1 ='./4hlu.cif'

m = PDB.MMCIF2Dict.MMCIF2Dict(pdb1)

if '_entity_poly.pdbx_seq_one_letter_code' in m.keys():
    full_structure = m['_entity_poly.pdbx_seq_one_letter_code']
    chains = m['_entity_poly.pdbx_strand_id']
    for c in chains:
        print('Chain %s' % (c))
        print('Sequence: %s' % (full_structure[chains.index(c)]))

A: It's just:
from Bio.PDB import PDBParser
from Bio import PDB

pdb = PDBParser().get_structure("1bfg", "1bfg.pdb")

for chain in pdb.get_chains():
    print(len([_ for _ in chain.get_residues() if PDB.is_aa(_)]))

A: I appreciated Peters' answer, but I also realized the res.id[0] == " " is more robust (i.e. HIE). PDB.is_aa() cannot detect HIE is an amino acid while HIE is ε-nitrogen protonated histidine. So I recommend:
from Bio import PDB
parser = PDB.PDBParser()

pdb1 ='./1bfg.pdb'
structure = parser.get_structure("1bfg", pdb)
model = structure[0]
res_no = 0
non_resi = 0

for model in structure:
    for chain in model:
        for r in chain.get_residues():
            if r.id[0] == ' ':
                res_no +=1
            else:
                non_resi +=1

print ("Residues:  %i" % (res_no))
print ("Other:     %i" % (non_resi))

A: I think you would actually want to do something like
m = Bio.PDB.MMCIF2Dict.MMCIF2Dict(pdb_cif_file)
if '_entity_poly.pdbx_seq_one_letter_code' in m.keys():
    full_structure = m['_entity_poly.pdbx_seq_one_letter_code']
    chains = m['_entity_poly.pdbx_strand_id']
    for c in chains:
        for ci in c.split(','):
            print('Chain %s' % (ci))
            print('Sequence: %s' % (full_structure[chains.index(c)]))