text:
Q: Android Studio: AVD options give the error "The skin directory does not point to a valid skin", but only when editing the virtual device In Android Studio (Arctic Fox | 2020.3.1 Patch 1), the initial creation and subsequent launch of a new virtual device in the emulator completes without any issues and the device frame shows properly. However, when opting to edit the virtual device, an error pops up briefly at the bottom of the window saying, "The skin directory does not point to a valid skin," and the Enable Device Frame option becomes un-ticked. If you cancel out of the Android Device Configuration window, the skin will still load correctly. If you check the Enable Device Frame checkbox and select the Finish button, the emulator will load without a skin. Going back to the device's option page shows that the Enable Device Frame checkbox has once again become un-ticked. Is this a bug and/or is there a workaround to this? I want to boot from a particular snapshot each time the emulator loads, but cannot do that without accessing the option page (whereby the skin will disappear once I finalize my option selection.)

A: I had the same issue when creating a new AVD:

*

*Click "Show Advanced Settings"

*Set "Custom skin definition" to "No Skin"

*Error is gone

A: I had this problem, I discovered I didn't have the SDK version downloaded for the version I had selected in AVD.
To solve in Android Studio Select: Tools > SDK Manager
Then check you have downloaded the SDK for the android version you are trying to use in AVD

A: I had the same issue.

*

*Create a new device.

*Compare the config.ini files between the two.
I found mine in C:\Users\USER\.android\avd\Pixel_4_API_30.avd\

*Edit accordingly.

*Restart.


text:
Q: Python : Pandas Sum with more than one condition I want to know how to do a sum on a column depending of the value of another column (0 or 1)
   id   area PP
a   0,95999998  0
a   0,44    1
b   1,6900001   0
c   2   0
d   5,8499999   0
e   0,66000003  1

I can find the area for each id
surface_id = df.groupby("id")["area"].sum()

But what I also want is the area by id if PP = 1 to get something like this :
   id   area_PP
a   0,44
b   0
c   0
d   0
e   0,66000003

A: Try:
df.eval('area * PP').groupby(df.id).sum()

This works by simply multiplying the area column by the PP column.  0 naturally cancels out the area appropriately.
I chose to use eval because it's cooler and for large data should be faster.
This does the same thing
(df.area * df.PP).groupby(df.id).sum()

A: One way using transform but longer
df['area_pp'] = df[df.PP == 1].groupby("id")["area"].transform('sum')
df.fillna(0, inplace = True)

    id  area        PP  area_pp
0   a   0,95999998  0   0
1   a   0,44        1   0,44
2   b   1,6900001   0   0
3   c   2           0   0
4   d   5,8499999   0   0
5   e   0,66000003  1   0,66000003

A: Another way:
total=df.groupby(['id', 'PP'])['area'].sum().reset_index(level=1)
total[total.PP==1].drop(axis=1, labels='PP')

A: If you were to just want the positively labeled instances in the output:
df = pd.DataFrame({'id': ('a', 'a', 'b', 'c', 'd', 'e'), 'area': (0.96, 0.44,
1.69, 2., 5.85, 0.66), 'PP': (0, 1, 0, 0, 0, 1)})
df2 = df.where(df.PP==1).groupby('id')['area'].sum()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pyrhon: Get days of month present in current month? I have df with two columns number and day. I'm trying to get the frequency of particular days if day is True.
From Monday - 0 to sunday - 6 as per calendar.
For 1(Tuesday) there are 4 Tuesdays present in the month of may.
Similarly for 6(Sunday) there are 5 Sundays in may.
df
    df= pd.DataFrame(data = {'number' : ['1', '2', '3', '4', '6'], 'day' : [True, False, False, False, True]})

        number  day
    0   1       True
    1   2       False
    2   3       False
    3   4       False
    4   6       True

My excepted output:
        number          day
    0   7,14,21,28      True
    1   2               False
    2   3               False
    3   4               False
    4   3,10,17,24,31   True

A: Let us try Calendar
from calendar import Calendar
a=np.array(Calendar().monthdayscalendar(2020,5))
l=[','.join(a[:,int(x)][a[:,int(x)]!=0].astype(str)) if y else x for x, y  in zip(df.number,df.day)]
['5,12,19,26', '2', '3', '4', '3,10,17,24,31']
df['number']=l

A: My solution is more general that the other, i.e. it computes days
for the current month, whenever you run this code.
Start from some preparatory computation:
# Start of the current month
dStart = pd.offsets.MonthBegin(0).rollback(pd.Timestamp.today().normalize())
# DataFrame for the current month, for now only "Date" column
mnth = pd.DataFrame({'Date': pd.date_range(start=dStart,
    periods=dStart.daysinmonth)})
# Add "Day of Week" column
mnth['DoW'] = mnth.Date.dt.dayofweek
# Add "Day" column (as string)
mnth['Day'] = mnth.Date.dt.day.astype(str)
# Convert to list of days (for each DoW)
mnth = mnth.groupby('DoW').Day.apply(lambda s: ','.join(list(s)))

And to conditionally change each number in df it is enough to run
a single instruction:
df.number = df.apply(lambda row: mnth.loc[int(row.number)]
    if row.day else row.number, axis=1)

The result, for May 2020, is:
          number    day
0     5,12,19,26   True
1              2  False
2              3  False
3              4  False
4  3,10,17,24,31   True


text:
Q: Character limitation for WordPress WYSIWYG editor I limited the number of characters that can be added as content for a special page (event submission page). It works fine in text or code mode in WordPress but not when I use the WYSIWYG editor.
Any idea how to change it so it also works using the WordPress editor?
Thank you so much!
Here is the JS I am using.
     // Set your character limit
     var count_limit = 1000;

     // Set the initial symbol count on page load
     $('#tcepostcontent-wc span').html($('#tcepostcontent').val());

     $('#tcepostcontent').on('keyup', function () {
      var char_count = $(this).val().length;
      var tcepostcontent = $(this).val();
      var text_remaining = count_limit - char_count;

     // Update the character count on every key up
     $('#tcepostcontent-wc span').html(text_remaining);

     if (char_count >= count_limit) {
       $('#tcepostcontent-wc').css('color', 'red');
       $(this).val(tcepostcontent.substr(1, count_limit));
     } else {
       $('#tcepostcontent-wc').css('color', null);
     }

     }).after('
Max 1000 are available 1000
');

A: The visual editor of WordPress is TinyMCE and he implement a custom API there you can use to solve this topic. You should use the follow source, add it in a small custom plugin, change the id for tinyMCE.activeEditor.editorId of the editor, activate it, and done.
add_filter( 'tiny_mce_before_init', 'wpse24113_tiny_mce_before_init' );
function wpse24113_tiny_mce_before_init( $initArray ) {

    $initArray['setup'] = <<<JS
[function( ed ) {
    ed.onKeyDown.add( function( ed, e ) {
        if ( tinyMCE.activeEditor.editorId == 'content-id' ) {

            var content = tinyMCE.activeEditor.getContent();
            var max = 300;
            var len = content.length;

            if (len >= max) {
              $( '#charNum' ).html( 'You've got more then '+max+' characters!' );
            } else {
             var charCount = max - len;

             $( '#charNum').html( charCount + ' characters left' );
            }
         }
    });

}][0]
JS;

    return $initArray;
}

The source is from this answer in the SE Forum for WordPress topics.


text:
Q: JmsListener does not receive message from Activemq I have a Spring JmsListener in my code. It's receive and consume message for 2 days but suddenly after this 2 days it receive no message from external activemq. However there is some pending message in its queue. When I reset the activemq and consumer, the consumer receive large amount of message. When the messages are pending the consumer connected to the activemq(on behalf of spring actuator logs).
The logs and config show that activemq did not push message to consumer. I have another services like this consumer that receive the message from other queue. Also the second consumer has same problem.   I want to know why this problem happened and how can I solve this problem.
Here is my config and log:
Consumer:
application.xml:
spring.jms.pub-sub-domain=false
spring.jms.template.delivery-mode=persistent
spring.activemq.broker-url=${BROKER_URL:failover:(tcp://activemq1:61616,tcp://activemq2:61616)?maxReconnectDelay=2500}
spring.activemq.user=${BROKER_USER:admin}
spring.activemq.password=${BROKER_PASSWORD:admin}

JmsConfiguration:
@EnableJms
@Configuration
public class JmsConfiguration {
    @Bean
    public JmsListenerContainerFactory<?> myFactory(ActiveMQConnectionFactory connectionFactory,
                                                    DefaultJmsListenerContainerFactoryConfigurer configurer) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
        redeliveryPolicy.setMaximumRedeliveries(0);
        connectionFactory.setRedeliveryPolicy(redeliveryPolicy);
        factory.setMessageConverter(messageConverter());
        configurer.configure(factory, connectionFactory);
        return factory;
    }

    private MessageConverter messageConverter() {
        MappingJackson2MessageConverter messageConverter = new MappingJackson2MessageConverter();
        messageConverter.setTargetType(MessageType.TEXT);
        messageConverter.setTypeIdPropertyName("_type");
        return messageConverter;
    }
}

Listener:
@Component
public class MessageReceiver {

        @JmsListener(destination = Constant.OFFICE_REQUEST_QUEUE, containerFactory = "myFactory")
        public void receive(RequestMessage requestMessage,  @Headers Map<String,Object> headers) throws NonPersistenceServiceException {
            // do someting on received message
        }
    }

Activemq config:
activemq.xml:
<beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>file:${activemq.conf}/credentials.properties</value>
        </property>
    </bean>

    <bean id="logQuery" class="io.fabric8.insight.log.log4j.Log4jLogQuery"
          lazy-init="false" scope="singleton"
          init-method="start" destroy-method="stop">
    </bean>

    <bean id="oracleDS" class="oracle.jdbc.pool.OracleDataSource" destroy-method="close">
          <property name="URL" value="jdbc:oracle:thin:@(DESCRIPTION= (SDU=32768)(ADDRESS=(PROTOCOL=TCP)(HOST= dms-db1-vip)(PORT=1521)) (ADDRESS=(PROTOCOL=TCP)(HOST= dms-db2-vip)(PORT=1521)) (LOAD_BALANCE=yes)(FAILOVER=ON)(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)(failover_mode=(type=select)(method=basic)(retries=5)(delay=1))))"/>
          <property name="user" value="ora_user"/>
          <property name="password" value="ora_pass"/>
    </bean>

    <broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}" >

        <plugins>
            <redeliveryPlugin fallbackToDeadLetter="true"
                              sendToDlqIfMaxRetriesExceeded="true">
                <redeliveryPolicyMap>
                    <redeliveryPolicyMap>

                        <defaultEntry>
                            <redeliveryPolicy
                                              useExponentialBackOff="true"
                                              backOffMultiplier="2"
                                              maximumRedeliveryDelay="1200000"
                                              maximumRedeliveries="82"/>
                        </defaultEntry>
                    </redeliveryPolicyMap>
                </redeliveryPolicyMap>
            </redeliveryPlugin>
        </plugins>

        <destinationPolicy>
            <policyMap>
              <policyEntries>
                <policyEntry queue=">">
                  <deadLetterStrategy>
                    <individualDeadLetterStrategy queuePrefix="DLQ." useQueueForQueueMessages="true"/>
                  </deadLetterStrategy>
                </policyEntry>
              </policyEntries>
            </policyMap>
        </destinationPolicy>

        <managementContext>
            <managementContext createConnector="false"/>
        </managementContext>

        <persistenceAdapter>
            <jdbcPersistenceAdapter dataSource="#oracleDS" />
        </persistenceAdapter>

          <systemUsage>
            <systemUsage>
                <memoryUsage>
                    <memoryUsage percentOfJvmHeap="70" />
                </memoryUsage>
                <storeUsage>
                    <storeUsage limit="100 gb"/>
                </storeUsage>
                <tempUsage>
                    <tempUsage limit="50 gb"/>
                </tempUsage>
            </systemUsage>
        </systemUsage>

        <transportConnectors>
            <transportConnector name="openwire" uri="tcp://0.0.0.0:61616?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="stomp" uri="stomp://0.0.0.0:61613?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="mqtt" uri="mqtt://0.0.0.0:1883?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="ws" uri="ws://0.0.0.0:61614?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
        </transportConnectors>

        <shutdownHooks>
            <bean xmlns="http://www.springframework.org/schema/beans" class="org.apache.activemq.hooks.SpringContextHook" />
        </shutdownHooks>

    </broker>

    <import resource="jetty.xml"/>

</beans>

Below is The log of actuator in consumer:
{"log":"20:20:26.775 @@@ [ActiveMQ Task-1] INFO  o.a.activemq.transport.failover.FailoverTransport @@@  @@@  @@@\r\n","stream":"stdout"}
{"log":"                Successfully connected to tcp://activemq1:61616\r\n","stream":"stdout"}
{"log":"20:20:36.638 @@@ [ActiveMQ Task-1] INFO  o.a.activemq.transport.failover.FailoverTransport @@@  @@@  @@@\r\n","stream":"stdout"}
{"log":"                Successfully connected to tcp://activemq1:61616\r\n","stream":"stdout"}
{"log":"20:20:36.779 @@@ [ActiveMQ Task-1] INFO  o.a.activemq.transport.failover.FailoverTransport @@@  @@@  @@@\r\n","stream":"stdout"}
{"log":"                Successfully connected to tcp://activemq1:61616\r\n","stream":"stdout"}
{"log":"20:20:46.464 @@@ [ActiveMQ Task-1] INFO  o.a.activemq.transport.failover.FailoverTransport @@@  @@@  @@@\r\n","stream":"stdout"}
{"log":"                Successfully connected to tcp://activemq1:61616\r\n","stream":"stdout"}
{"log":"20:20:46.774 @@@ [ActiveMQ Task-1] INFO  o.a.activemq.transport.failover.FailoverTransport @@@  @@@  @@@\r\n","stream":"stdout"}

Activemq erros log:
2019-03-05 20:19:55,448 | WARN  | Transport Connection to: tcp://10.42.1.0:63493 failed: java.io.IOException: Frame size of 1 GB larger than max allowed 100 MB | org.apache.activemq.broker.TransportConnection.Transport | ActiveMQ Transport: tcp:///10.42.1.0:63493@61616
2019-03-05 20:20:05,776 | WARN  | Transport Connection to: tcp://10.42.1.0:63498 failed: java.io.EOFException | org.apache.activemq.broker.TransportConnection.Transport | ActiveMQ Transport: tcp:///10.42.1.0:63498@61616
2019-03-05 20:20:05,776 | WARN  | Transport Connection to: tcp://10.42.1.0:63497 failed: java.io.EOFException | org.apache.activemq.broker.TransportConnection.Transport | ActiveMQ Transport: tcp:///10.42.1.0:63497@61616

A: Such scenarios are most often the result of one of two issues:

*

*Some network component (router, firewall) silently closes a socket due to inactivity without notifying the client or server so, unless heartbeats are enabled, the connection is dead.

*The consumer thread is somehow "stuck" in user code so it stops receiving new messages; take a stack dump to see what the container threads are doing.


text:
Q: How to save a file to network shared directory in .net core hosted in IIS I always get path not found exception when this happens. I read that .net core runs in Kestrel and doesn't have access to network folders to save the files.
I have setup the application pool to have proper permissions to be able to read and write from the network shared folder but still unable to save the file using File.Copy method in C#.
Any suggestions are welcome.
Thanks


text:
Q: What is the area of math that deals with solving chains of vertex positions within shapes and lines using a set of constraints I apologize for the lengthy title. I have a poor education in math, and do not know correct terminology for many things (My most recent math class was something like algebra 2 in high school, 8 years ago.)
I recently created a Basic CAD Drawing program to help with the silly things like designing standardized letterhead / barcode margins at my current job. To do so I had to re-teach myself many aspects of linear algebra and geometry and it's been the most fun I've had in ages. I would like to take it a step further and learn to solve these linear equations relative to the constraints I set on them, similar to what is done in any modern AutoCAD like program. In the most basic example it might look like this (In this example, the circles around vertexes would represent an anchored point constraint.)
After I add additional constraint types (like these shown in Autodesk AutoCAD) I assume things get exponentially more complex.
Is this all just geometry and linear algebra applied in complex ways? Or is there a name for the type of thing that might point me in the correct directions. (i.e. Do I need to start reading a random book on inverse kinematics?)


text:
Q: I'm trying to make my unity program, detect the terrain, and change the footsteps/ambience, but the code I've found to detect it, is not compiling I'm building my first game, with a couple of mates, And while i've got some small experience in C, I'm completely new to C.
I went to set it up in my FPS Controller, but it's telling me that
2 of my errors are "Only assignment, call, increment, decrement, and new object expressions can be used as statements". While 6 of them are just unexpected symbols.
I'll paste the Ide links below.
In the small section,
Line 8, has one of the first errors, and 2 of the unexpected symbol.
Line 10, also has 2 of the unexpected symbol.

A: Perhaps you are confused when copied code.. You should replace this symbols &lt, &gt with correct. < matches to the less-than sign ( < ) and > matches to the greater-than sign ( > )
Here is correct code:
for (int n=0; n < mix.Length; ++n)
{
   if (mix[n] > maxMix)
   {
       maxIndex = n;
       maxMix = mix[n];
   }
}


text:
Q: Isometric topological sort issue I've just implemented a topological sort algorithm on my isometric game using this guide: https://mazebert.com/2013/04/18/isometric-depth-sorting/

The issue
Here's a little example (this is just a drawing to illustrate my problem because as we say, a picture is worth a thousand words), what I'm expecting is in left and the result of the topological sorting algorithm is in right

So in the right image, the problem is that the box is drawn BEFORE the character and I'm expecting it to be drawn AFTER like in the left image.

Code of the topological sorting algorithm (Typescript)
private TopologicalSort2() {
    // https://mazebert.com/2013/04/18/isometric-depth-sorting/

    for(var i = 0; i < this.Stage.children.length; i++) {
        var a = this.Stage.children[i];
        var behindIndex = 0;

        for(var j = 0; j < this.Stage.children.length; j++) {
            if(i == j) {
                continue;
            }

            var b = this.Stage.children[j];

            if(!a.isoSpritesBehind) {
                a.isoSpritesBehind = [];
            }

            if(!b.isoSpritesBehind) {
                b.isoSpritesBehind = [];
            }

            if(b.posX < a.posX + a.sizeX && b.posY < a.posY + a.sizeY && b.posZ < a.posZ + a.sizeZ) {
                a.isoSpritesBehind[behindIndex++] = b;
            }
        }

        a.isoVisitedFlag = 0;
    }

    var _sortDepth = 0;

    for(var i = 0; i < this.Stage.children.length; ++i) {
        visitNode(this.Stage.children[i]);
    }

    function visitNode(n: PIXI.DisplayObject) {
        if(n.isoVisitedFlag == 0) {
            n.isoVisitedFlag = 1;

            if(!n.isoSpritesBehind) {
                return;
            }

            for(var i = 0; i < n.isoSpritesBehind.length; i++) {
                if(n.isoSpritesBehind[i] == null) {
                    break;
                } else {
                    visitNode(n.isoSpritesBehind[i]);
                    n.isoSpritesBehind[i] = null;
                }
            }

            n.isoDepth = _sortDepth++;
        }
    }

    this.Stage.children.sort((a, b) => {
        if(a.isoDepth - b.isoDepth != 0) {
            return a.isoDepth - b.isoDepth;
        }

        return 0;
    });
}

Informations
Player:
posX: [the x coordinate of the player]
posY: [the y coordinate of the player]
posZ: 0

sizeX: 1
sizeY: 1
sizeZ: 1

Box:
posX: [the x coordinate of the box]
posY: [the y coordinate of the box]
posZ: 0

sizeX: 3
sizeY: 1
sizeZ: 1

X and Y axis

Do you have any idea of the source of this problem? and maybe how to solve it?

A: The way to determine whether one object is before the other requires a bit more linear algebra.
First of all, I would suggest to translate the coordinates from the "world" coordinates to the "view" 2D coordinates, i.e. to the rows and columns of the display.
Note also that the original Z coordinate does not influence the sort order (imagine that an object would be lifted up along the Z axis: we can find a sort order where this move would not have any impact). So the above-mentioned translation could assume all points are at Z=0.
Let's take this set-up, but depicted from "above", so when looking along the Z axis down to the game floor:

In the picture there are 7 objects, numbered from 0 to 6. The line of view in the game would be from the bottom-left of this picture. The coordinate system in which I would suggest to translate some points is depicted with the red row/col axis.
The white diagonals in each object link the two points that would be translated and used in the algorithm. The assumption is that when one object is in front of another, their diagonal lines will not intersect. If they would, it would mean that objects are overlapping each other in the game world, which would mean they are like gasses, not solids :) I will assume this is not the case.
One object A could be in front of another object B when in the new coordinate system, the left-most column coordinate of B falls between the two column coordinates of A (or vice versa). There might not really be such an overlap when their Z coordinates differ enough, but we can ignore that, because when there is no overlap we can do no harm in specifying a certain order anyway.
Now, when the coordinates indicate an overlap, the coordinates of diagonals (of A and B) must be compared with some linear algebra formula, which will determine which one is in front of the other.
Here is your adapted function that does that:
topologicalSort() {
    // Exit if sorting is a non-operation
    if (this.Stage.children.length < 2) return;
    // Add two translated coordinates, where each of the resulting
    //   coordinates has a row (top to bottom) and column
    //   (left to right) part. They represent a position in the final
    //   rendered view (the screen).
    // The two pairs of coordinates are translations of the
    //   points (posX + sizeX, Y, 0) and (posX, posY + sizeY, 0).
    // Z is ignored (0), since it does not influence the order.
    for (let obj of this.Stage.children) {
        obj.leftCol  = obj.posY - obj.posX - obj.sizeX;
        obj.rightCol = obj.posY - obj.posX + obj.sizeY;
        obj.leftRow  = obj.posY + obj.posX + obj.sizeX;
        obj.rightRow = obj.posY + obj.posX + obj.sizeY;
        obj.isoSpritesBehind = [];
    }

    for(let i = 0; i < this.Stage.children.length; i++) {
        let a = this.Stage.children[i];
        // Only loop over the next objects
        for(let j = i + 1; j < this.Stage.children.length; j++) {
            let b = this.Stage.children[j];
            // Get the two objects in order of left column:
            let c = b.leftCol < a.leftCol ? b : a;
            let d = b.leftCol < a.leftCol ? a : b;
            // See if they overlap in the view (ignoring Z):
            if (d.leftCol < c.rightCol) {
                // Determine which is behind: some linear algebra
                if (d.leftRow <
                        (d.leftCol - c.leftCol)/(c.rightCol - c.leftCol)
                        * (c.rightRow - c.leftRow)  + c.leftRow) {
                    // c is in front of d
                    c.isoSpritesBehind.push(d);
                } else { // d is in front of c
                    d.isoSpritesBehind.push(c);
                }
            } // in the else-case it does not matter which one comes first
        }
    }

    // This replaces your visitNode function and call:
    this.Stage.children.forEach(function getDepth(obj) {
        // If depth was already assigned, this node was already visited
        if (!obj.isoDepth) {
            // Get depths recursively, and retain the maximum of those.
            // Add one more to get the depth for the current object
            obj.isoDepth = obj.isoSpritesBehind.length
                ? 1+Math.max(...obj.isoSpritesBehind.map(getDepth))
                : 1; // Depth when there is nothing behind it
        }
        return obj.isoDepth; // Return it for easier recursion
    });

    // Sort like you did, but in shorter syntax
    this.Stage.children.sort((a, b) => a.isoDepth - b.isoDepth);
}

I add a snippet where I completed the class with a minimum of code, enough to make it run and output the final order in terms of object index numbers (as they were originally inserted):

class Game {
    constructor() {
        this.Stage = { children: [] };
    }
    addObject(posX, posY, posZ, sizeX, sizeY, sizeZ) {
        this.Stage.children.push({posX, posY, posZ, sizeX, sizeY, sizeZ,
                id: this.Stage.children.length}); // add a unique id
    }
    topologicalSort() {
        // Exit if sorting is a non-operation
        if (this.Stage.children.length < 2) return;
        // Add two translated coordinates, where each of the resulting
        //   coordinates has a row (top to bottom) and column
        //   (left to right) part. They represent a position in the final
        //   rendered view (the screen).
        // The two pairs of coordinates are translations of the
        //   points (posX + sizeX, Y, 0) and (posX, posY + sizeY, 0).
        // Z is ignored (0), since it does not influence the order.
        for (let obj of this.Stage.children) {
            obj.leftCol  = obj.posY - obj.posX - obj.sizeX;
            obj.rightCol = obj.posY - obj.posX + obj.sizeY;
            obj.leftRow  = obj.posY + obj.posX + obj.sizeX;
            obj.rightRow = obj.posY + obj.posX + obj.sizeY;
            obj.isoSpritesBehind = [];
        }

        for(let i = 0; i < this.Stage.children.length; i++) {
            let a = this.Stage.children[i];
            // Only loop over the next objects
            for(let j = i + 1; j < this.Stage.children.length; j++) {
                let b = this.Stage.children[j];
                // Get the two objects in order of left column:
                let c = b.leftCol < a.leftCol ? b : a;
                let d = b.leftCol < a.leftCol ? a : b;
                // See if they overlap in the view (ignoring Z):
                if (d.leftCol < c.rightCol) {
                    // Determine which is behind: some linear algebra
                    if (d.leftRow <
                            (d.leftCol - c.leftCol)/(c.rightCol - c.leftCol)
                            * (c.rightRow - c.leftRow)  + c.leftRow) {
                        // c is in front of d
                        c.isoSpritesBehind.push(d);
                    } else { // d is in front of c
                        d.isoSpritesBehind.push(c);
                    }
                } // in the else-case it does not matter which one comes first
            }
        }

        // This replaces your visitNode function and call:
        this.Stage.children.forEach(function getDepth(obj) {
            // If depth was already assigned, this node was already visited
            if (!obj.isoDepth) {
                // Get depths recursively, and retain the maximum of those.
                // Add one more to get the depth for the current object
                obj.isoDepth = obj.isoSpritesBehind.length
                    ? 1+Math.max(...obj.isoSpritesBehind.map(getDepth))
                    : 1; // Depth when there is nothing behind it
            }
            return obj.isoDepth; // Return it for easier recursion
        });

        // Sort like you did, but in shorter syntax
        this.Stage.children.sort((a, b) => a.isoDepth - b.isoDepth);
    }
    toString() { // Just print the ids of the children
        return JSON.stringify(this.Stage.children.map( x => x.id ));
    }
}

const game = new Game();
game.addObject( 2, 2, 0, 1, 1, 1 );
game.addObject( 1, 3, 0, 3, 1, 1 );
game.addObject( 6, 1, 0, 1, 3, 1 );
game.addObject( 9, 3, 0, 1, 1, 1 );
game.addObject( 5, 3, 0, 1, 3, 1 );
game.addObject( 7, 2, 0, 1, 1, 1 );
game.addObject( 8, 2, 0, 3, 1, 1 );
game.topologicalSort();
console.log(game + '');

The objects in the snippet are the same as in the picture with the same numbers. The output order is [0,1,4,2,5,6,3] which is the valid sequence for drawing the objects.


text:
Q: Using SwInject in conjunction with a central observer pattern I am using SWInject to maintain dependencies in my app, and the Coordinator pattern to manage logic and dependencies.
Can the SWInject be used in conjunction with a centralized push notification framework with multiple observers in different parts of the app?
Typically, i do that with a Singleton class, but doing that seems to defeat e purpose of using a dependency injection pattern.

A: DI in genaral tries to separate "how do I use the dependency" from "how do I obtain the dependecy". In most cases, latter should not be part of an object's knowledge.
In your case, fact that notification center which object uses to broadacst / receive stuff is a singleton, should be irrelevant to how you implement given object.
DI approach is to pass it as a dependency, and let somebody else worry about who else might be using the same instance. Sure, on the background it might still be a singleton, but you can change this fact when needed (e.g. testing) without changing anything about objects that use it.


text:
Q: Contacts Provider: How to hide Contacts by default from List This may not be something that is possible but I have tried a few things.
I have attempted to set the contacts from my provider into a group that is set to not visible (GROUP_VISIBLE, 0). However, without fail they still show up in the contacts list.
Also, I have set the contacts to have a setting to not be visible and to not show ungrouped contacts and tried several variations of grouping/ungrouping.
Essentially, my goal is to have contacts that primarily are just used for CallerId.
Ideas, thoughts?

A: Contact apps usually allow the user to select the display options he/she likes.
Contact apps are different between different devices, but the options are usually:

*

*Display all contacts (ignoring GROUP_VISIBLE)

*Display visible groups only (usually referred to as "custom" allowing the user the make certain groups visible or not)

*Display a specific group.

By making your contacts in hidden groups you'll be hiding them for some of your users, but not all, also, users could still select a checkbox to make your contact groups visible.
What most caller-ID apps do, is register for incoming-call events, and display a popup with the caller-ID info on top of the stock incoming call screen.
You can use WindowManager.LayoutParams.TYPE_SYSTEM_ALERT to make a view always-on-top so it's above the incoming call screen (like Facebook chatheads).
See this: How to create always-top fullscreen overlay activity in Android
just be sure to make your view a small popup and not full screen, so the user will be able to answer the call.


text:
Q: what is the equivalent of this code in javascript I am trying to read some code which is written in ruby. I am conversant with JavaScript and would like to understand what the code translates to in javascript.
Here is the code:
def two_d_translate(arr)
   new_arr = []

   arr.each do |subArray|
    ele = subArray[0]
    num = subArray[1]

    num.times { new_arr << ele }
  end

  return new_arr
end

The aim of the code is to translate a two-dimensional array to a one-dimensional array by printing the string as many times as the number beside it which is the second element in each sub-array.
I used this to try to imitate it but I wonder if there is something else which could be better.
function two_d_translate(arr) {
  let newArr = '';
  let array = [];

  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; j += 2) {
      let ele = arr[i][j];
      let num = arr[i][j+1];

      if (num === 0){
       continue;
      }

      array[i] = Array(num).fill(ele);
    }
  }

  newArr = array.toString().split(',');
  return newArr;
}

This seems to be cool for this test sample.
arr_1 = [
  ['boot', 3],
  ['camp', 2],
  ['program', 0]
]

console.log(two_d_translate(arr_1));

It will result in the expected output
[ 'boot', 'boot', 'boot', 'camp', 'camp' ]

but wouldn't in this case
arr_1=[
  ['boot', 3],
  ['camp', 0],
  ['program', 2]
]

this would result in an undesirable output which is
[ 'boot', 'boot', 'boot', '', 'program', 'program' ]

A: Reduce your array into a single one
With Array#reduce you are able to iterate over the entire array whilst pushing/concatenating the last calculation into the final result. This, in combination with Array.fill, allows us to create the correct amount, sometimes 0, of the string. And with Array#concat we can easily translate this 3D array into a 2D one. Here is an example:

function translateTo2D(arr) {
  return arr.reduce((result, [name, count]) =>
    result.concat(Array(count).fill(name)),
  []);
}

const arr = [['a', 2], ['b', 0], ['c', 1]];
console.log(translateTo2D(arr));

A: If your environment allows spread syntax, you can do something like this
const arr_1 = [
  ['boot', 3],
  ['camp', 0],
  ['program', 2]
]

const result = arr_1.reduce((acc, [string, times]) => [...acc, ...Array(times).fill(string)], []);
console.log(result); // [ 'boot', 'boot', 'boot', 'program', 'program' ]

A: The trick is to use flatMap to join separate runs together:

let translate = a => a.flatMap(([s, n]) => Array(n).fill(s))

console.log(translate([
    ['boot', 3],
    ['camp', 2],
    ['program', 1]
]))

If your target doesn't support flatMap yet, the equivalent ES6 idiom is [].concat(...map):

let translate = a => [].concat(...a.map(([s, n]) => Array(n).fill(s)))

console.log(translate([
    ['boot', 3],
    ['camp', 2],
    ['program', 1]
]))

As a rule of thumb, you use map/flatMap when transforming "many things" to "many things", and reduce for "many things" to "one thing".


text:
Q: What is the Big-O complexity of nested for loops of increasing length I'm new to the Big O notation and I am a little bit confused on how the following code plays into the Big O notation. In this situation n is just the length of an array and as you can see the two inner for loops are iterating through n^2 and n * 4. How does that play into the Big O notation? At first glance I thought it was n^3 however I am unsure.
    for (int i=0; i < n; i++) {
      for (int j=0; j < n*n; j++)
        sum += data[i] * data[j];
      for (int j=0; j < 4*n; j++)
        sum += data[i] + data[j];
    }

A: O(n * (O(c1 * n^2) + O(c2 * 4 * n))) =
O(n * (O(n^2) + O(n)) =
O(n * O(n^2)) =
O(n ^ 3)

Because sum (+), assignment (=), multiplication (*) and array access ([i]) cost constant.
So you are right.

A: The first loop iterates n times. For each iteration of the first loop second loop iterates n*n times. Therefore the total number of iterations of the second loop is n*(n*n). Furthermore for each iteration of the first loop third loop iterates 4*n times. Therefore the total number of iterations of the third loop is n*(4*n).
Hence complexity is O(n*n*n + n*4*n) -> O(n^3 + n^2) -> O(n^3).
You are right!!


text:
Q: Font description in Mono I want to set a label font in mono develop on windows.but i am a beginner on mono and i don't see Font on properties(like visual studio). how to change font description on Mono?

A: just with code.
public static Pango.FontDescription Font (string Family, int Size,Pango.Style Sty=Pango.Style.Normal)
    {
        Pango.FontDescription F=new Pango.FontDescription();
        F.Family=Family;
        F.Size=Size;
        F.Style=Sty;
        return F;
    }

and
lbl_Inf.ModifyFont(Font("Arial",23));


text:
Q: Want to know Httpurlconnection.setConnectTimeout() working I have made connection to the wechat api using HttpUrlConnection and set connectTimeOut to 500 milis and got the response in 3 seconds and now I decreased the connectTimeOut to 100 milis and getting the response in 2 seconds. So not able to understand the reason behind this, see the code and javadoc but not found anything related to it.

A: You are confused. Connection timeout is not the maximum time to read the response, it is the maximum time to create the connection. Sending the request and reading the response come afterwards.
If you got a response, clearly the connection succeeded within your timeout period, but it then took some seconds to read the response. These are not the same thing.
Possibly you may want to set a read timeout as well, or instead.
But the timeouts you're setting are ridiculously short. Three seconds for a connect timeout and ten seconds for a read timeout would be about the minimum.


text:
Q: Streaming a complex array from nodejs server as a response to http post I'll try to keep it simple:
An example of what I currently have
router.post('/handleMail', async (req, res, next) => {
    var x = [{a:{b:"b"}, c:{ok:"ok}] // just imagine this is convoluted array containing objects.
    res.json({body: x})
})

So lets say variable "x" is HUGE, containing some base64 encoded string etc.
When I try to simply return it like this the process usually stalls.

*

*Will streaming this as a response help this?

*How would I go about streaming it to "res" in this case?

Thanks :)

A: You could try using a library like json-stream-stringify that creates a readable stream from your json that you can pipe into the express response-object:
const JsonStreamStringify = require('json-stream-stringify');

router.post('/handleMail', async (req, res, next) => {
    const jsonObject = [{a:{b:"b"}, c:{ok:"ok}];
    new JsonStreamStringify(jsonObject ).pipe(res);
});


text:
Q: 95% confidence interval for AUROCC? How do I calculate the 95% confidence interval of the area under the ROC curve (AUROCC) on BlueSky Statistics? I know how to create the multivariate logistic model and show the ROC curve and AUROCC. I tried using the Bootstrap Resampling but could not figure out how to get the 95% confidence interval.

A: If you are familiar with R, you may want to enter the corresponding R codes to perform the calculation you are looking for (see chapter 4 of the user manual for V10 for further details on using R code with BlueSky)
For example, I was able to use some R code to directly connect to MySQL as well as to open a SQLite database file.


text:
Q: Unknown file extension ".ts" in ./src/app.ts Before adding
"type": "module", in package.json it used to give the following error

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\Work\ts-api\node_modules\node-fetch\src\index.js
require() of ES modules is not supported.
require() of C:\Work\ts-api\node_modules\node-fetch\src\index.js from C:\Work\ts-api\src\app.ts is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\Work\ts-api\node_modules\node-fetch\package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1080:13)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:\Work\ts-api\src\app.ts:3:1)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Module.m._compile (C:\Work\ts-api\node_modules\ts-node\src\index.ts:1371:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Object.require.extensions.<computed> [as .ts] (C:\Work\ts-api\node_modules\ts-node\src\index.ts:1374:12) {
  code: 'ERR_REQUIRE_ESM'
}

but then I added   "type": "module", in package.json
and it started to giving me the error which I mentioned in title
./src/app.ts
import express,{Application, Request, Response, NextFunction} from 'express';

import fetch from 'node-fetch';

const app:Application = express();

app.get("/",(req:Request, res:Response)=>{
    res.send("Hello world");
})

app.get("/api",async (req:Request, res:Response)=>{
    const response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});
    const data = await response.json();
    console.log(data);
});

app.listen(3000,()=>{
    "Server is started at Port No. 3000"
});

package.json
{
  "name": "ts-api",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node dist/app.js",
    "dev": "nodemon src/app.ts",
    "build": "tsc -p ."
  },
  "keywords": [],
  "type": "module",
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/express": "^4.17.13",
    "@types/node": "^17.0.7",
    "nodemon": "^2.0.15",
    "ts-node": "^10.4.0",
    "typescript": "^4.5.4"
  },
  "dependencies": {
    "express": "^4.17.2",
    "node-fetch": "^3.1.0"
  }
}

tsconfig.json
{
  "compilerOptions": {
    "target": "es2017",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "module": "commonjs",                                /* Specify what module code is generated. */
    "rootDir": "./src",                                  /* Specify the root folder within your source files. */
    "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
    "outDir": "./dist",                                   /* Specify an output folder for all emitted files. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
    "strict": true,                                      /* Enable all strict type-checking options. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

A: I think you should use axios instead of node-fetch because node-fetch doesn't support commonjs ES modules, also you can remove "type": "module"
app.ts
import express,{Application, Request, Response, NextFunction} from 'express';

import axios from 'axios';

const app:Application = express();

app.get("/",(req:Request, res:Response)=>{
    res.send("Hello world");
})

app.get("/api",async (req:Request, res:Response)=>{
    const { data } = await axios.post('https://httpbin.org/post','a=1');
    console.log(data);
});

app.listen(3000,()=>{
    "Server is started at Port No. 3000"
});


text:
Q: Applescript wait till a modal disappear I am writing a script to generate PDF for a lot of mails. Because the PDF generation takes some time, I want the script to wait till

to disappear in Mail. So I can start to process the next one. The following are the attributes of this element.

Since it has no title, how can I specify to wait  till this element to disappear?

A: You need two repeat loops, one waits until the sheet appears and the other waits uniil the sheet disappears.
tell application "System Events"
    tell process "Mail"
        repeat until exists sheet 1 of window 1
            delay 0.5
        end repeat
        repeat while exists sheet 1 of window 1
            delay 0.5
        end repeat
        -- sheet was dismissed
    end tell
end tell


text:
Q: how to resolve g++ warning with -std=c++11: 'auto_ptr' is deprecated Trying out -std=c++11 with the g++ compiler, I got lots of
warning: 'auto_ptr' is deprecated (declared at
/usr/include/c++/4.8/backward/auto_ptr.h:87) [-Wdeprecated-declarations]

What should I use instead of auto_ptr? Please give an informative link or a complete answer.

A: You may use std::unique_ptr instead of std::auto_ptr
And if you copied auto_ptr, you have to std::move the unique_ptr.

A:
"What should I use instead of auto_ptr?"

The class representing std::auto_ptr<>'s behavior most closely is std::unique_ptr<>.


text:
Q: Excel VBA - FormulaArray error (for LARGER(IF())) I use the =LARGE(IF(...);1) function in Excel, from VBA, and I use the FormulaArray. Beacause I get a problem, I did specific functions for the cells:
Sheets("OEVK").Range("J314").FormulaLocal = "=LARGER(IF(jelolt_lista!$C:$C=OEVK!B314;jelolt_lista!$M:$M);1)"
 Sheets("OEVK").Range("J315").FormulaLocal = "=LARGER(IF(jelolt_lista!$C:$C=OEVK!B315;jelolt_lista!$M:$M);2)"
 Sheets("OEVK").Range("J316").FormulaLocal = "=LARGER(IF(jelolt_lista!$C:$C=OEVK!B316;jelolt_lista!$M:$M);3)"
 Sheets("OEVK").Range("J317").FormulaLocal = "=LARGER(IF(jelolt_lista!$C:$C=OEVK!B317;jelolt_lista!$M:$M);1)"
 Sheets("OEVK").Range("J318").FormulaLocal = "=LARGER(IF(jelolt_lista!$C:$C=OEVK!B318;jelolt_lista!$M:$M);2)"
 Sheets("OEVK").Range("J319").FormulaLocal = "=NAGY(HA(jelolt_lista!$C:$C=OEVK!B319;jelolt_lista!$M:$M);3)"
 Sheets("OEVK").Range("J2:J319").FormulaArray = Sheets("OEVK").Range("J2:J319").Formula

I use this in hungarian.
But after the macro running, the relevant links (B2, B4, B6 instead of B2, B3, B4) in cells are incorrect, and I don't know, why.
The result in cells: (NAGY = LARGER, HA = IF)
J2: {=NAGY(HA(jelolt_lista!$C:$C=OEVK!B2;jelolt_lista!$M:$M);1)}
J3: {=NAGY(HA(jelolt_lista!$C:$C=OEVK!B4;jelolt_lista!$M:$M);2)}
J4: {=NAGY(HA(jelolt_lista!$C:$C=OEVK!B6;jelolt_lista!$M:$M);3)}

Can you help us in this problem? I tried with more less range, but it didn't help me...
Thank you for your help!
Best regards,
N

A: There does indeed seem to be a bug in bulk converting range of formulas into array formulas. The row-by-row progrssion starts skipping rows; e.g. B2, B3, B4, ... becomes B2, B4, B6, ... Here are two alternatives.
Individually:
Sub Macro3()
    Dim f As Long

    With Worksheets("OEVK")
        For f = 2 To 319
            .Cells(f, "J").FormulaArray = _
              "=LARGE(IF(jelolt_lista!$C:$C=OEVK!B" & f & ", jelolt_lista!$M:$M), " & (f - 2) Mod 3 + 1 & ")"
        Next f
    End With
End Sub

Write one then fill down,
Sub Macro2()
    With Worksheets("OEVK")
        .Cells(2, "J").FormulaArray = _
          "=LARGE(IF(jelolt_lista!$C:$C=OEVK!B2, jelolt_lista!$M:$M), MOD(ROW(2:2)-2, 3) + 1)"
        .Range(.Cells(2, "J"), .Cells(319, "J")).FillDown
    End With
End Sub

I would agree that your full column ranges need to be cut down to the extents of the actual data.


text:
Q: Joining 2 tables cause resources exceeded error in BigQuery I am trying to fetch records by joining 2 tables, and in this case I consider 6 months worth of data.
I get the "Resources exceeded error".
Could anyone please advice on some query enhancements that would help me in bypassing this error?
Thanks in advance!!
    SELECT
      *
    FROM (
      SELECT
        A.Id1 AS Id1,
        A.Id2 AS Id1,
        StartTime,
        StopTime,
        Duration AS ID,
        Latitude,
        Longitude,
        DateTime
      FROM (
        SELECT
          *
        FROM
          `Tb1`
        WHERE
          HardwareId IN (
            735,
            8055,
            8620,
            9489,
            214,
            7543,
            2471,
            681,
            451)
          AND _PARTITIONTIME BETWEEN TIMESTAMP('2016-01-01')
          AND TIMESTAMP('2016-12-31') ) AS A
      JOIN (
        SELECT
          *
        FROM
          `Tb2.T2016*`
        WHERE
          _TABLE_SUFFIX BETWEEN "0601"
          AND "1231"
          AND HardwareId IN (
            735,
            8055,
            8620,
            9489,
            214,
            7543,
            2471,
            681,
            451) ) AS B
      ON
        A.StartTime < B.DateTime
        AND A.StopTime >= B.DateTime
        AND A.Id1 = B.Id1 )
    ORDER BY
      Id1,
      Id2,
      DateTime`

A: Start with removing ORDER BY part of your query!
ORDER BY
  Id1,
  Id2,
  DateTime

Usually, this is the main reason for
resources exceeded error in BigQuery

I also noticed some issue with your query that most likely related to the fact that you slightly obscured your original query
1 - same column name used
A.Id1 AS Id1,
A.Id2 AS Id1,

2 - different time period
'2016-01-01' - '2016-12-31' in
BETWEEN TIMESTAMP('2016-01-01') AND TIMESTAMP('2016-12-31')

vs. '2016-06-01' - '2016-12-31'
BETWEEN "0601" AND "1231"


text:
Q: rxjs tree search I'm new to rxjs and need to find an algorithm to find nodes by id inside a tree. That's my best approach (available as public gist in gistrun) :
const value= "c.1.3";
const tree= [
  {
    "id": "c.1",
    "children": [
      {
        "id": "c.1.1"
      },
      {
        "id": "c.1.2"
      },
      {
        "id": "c.1.3"
      }
    ]
  }
];

const findTree= (tree)=>Rx.Observable.from(tree)
  .mergeMap(node=>{
    if(!!node.children)
      return findTree(node.children);
    return Rx.Observable.of(node);
  })
  .find(node=>node.id==value);
findTree(tree).subscribe(console.info);

It's failing finding the root, I would like to walk only throw the leafs matching the id start and discard that I'm inventing the wheel.

*

*How can I maintain the search at first level?

*Is there any operator to filter by regexp?

*Any rxjs operator does a recursive find?
Thanks all in advance.

A: Ok, I won't get into detail with your tree example, but I can answer your questions and this may help you figure out some things.
How can I maintain state
One easy way to do that, is to save your state in a temporary object
Observable.of(1)
          .flatMap(number => Observable.of({ start: number, value: 'a' }))
          .subscribe(({start, value}) => console.log(start + '/' + value)); // output: 1/a

Is there any operator to filter by regexp?
No, but you can easily do it yourself like that
let names$ = Observable.of('adam', 'amy', 'ben');
let regex = /a.*/;

names$.filter(name => regex.test(name))  // emits: 'adam', 'amy

Any rxjs operator does a recursive find?
Yes, there is the expand operator. Here is an easy example which should guide you the way
Observable.of(3)
          .expand(x => Observable.of(x-1))
          .takeWhile(x => x >= 0); // emits: 3, 2, 1, 0


text:
Q: How to compare two signatures using javascript or php I'm implementing a multi-factor authentication application in Laravel. I store users signatures when the initially get registered to the system. Whenever they try to log in again, I'm asking to draw their signature again and need to verify their signature with the stored signature. Is there any way to do this process. Please anyone help me out.
Thanks in advance.


text:
Q: Is it possible to use two cells of criteria to return a value from a third column? I have an Google sheets file with two sheets. I'm trying to reference one sheet's text based on two cells of criteria using a formula in the other sheet. I have one sheet that looks similar to this -

And another that looks like this -

I would like to put a formula on the second sheet that basically says - look on the first sheet for the values in columns A and B and return me the value in column C. The tricky part is - the values in the second sheet may be inverted or there may be an instance where only one value is present, like in row 1 in the first sheet. Also the formula should only fill in a value if both columns match. All text combinations in both sheets are unique.
Is it possible to do this with text? Thank you for your help!

A: Try the following
=ArrayFormula((IFERROR(VLOOKUP(R2:R&S2:S,{O2:O&P2:P,Q2:Q},2,0))&
               IFERROR(IF((R2:R<>"")*(S2:S<>""),VLOOKUP(R2:R&S2:S,{P2:P&O2:O,Q2:Q},2,0),""))))

(Do adjust locale and ranges according to your needs)

Functions used:

*

*ArrayFormula

*IFERROR

*IF

*VLOOKUP

A: If you can use two keys concated in the lookup table as a virtual key (i.e. make a key like "CAT|DOG"), then you can use that to look in the secondary table.
If you can't guarantee the sort order of the two keys in the secondary table, you can use the following technique to "sort" the two keys so you can make a single lookup key that's always in one stable order.
Sample Table

A
B
C
D
E
SortedKey

Cat
Dog
TRUE
Cat
Dog
CatDog

Dog
Cat
FALSE
Cat
Dog
CatDog

Formulas
Sample formulas for row #1.

*

*For column C, use formula: =A1<B1

*For column D, use formula: =IF(C1=TRUE, A1, B1)

*For column E, use formula: =IF(C1=TRUE, B1, A1)

*For SortedKey, use formula: =concat(D1, E1)


text:
Q: Сложность в коде телеграм-бота Не могу понять проблему, читал документацию и попытался строчку подогнать под бота, вроде всё правильно, но все равно выходит ошибка.
использую telebot и PyTelegramBotAPI
P.S. каши из табуляций и пробелов нет
Вывод:
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/bin/pythonanywhere_runner.py", line 26, in _pa_run
   code = compile(f.read(), filename.encode("utf8"), "exec")
 File "/home/bot/bot.py", line 38
   class telebot.types.ForceReply(selective: Optional[bool] = None, input_field_placeholder: Optional[str] = None);
IndentationError: unexpected indent

Код:
import telebot
import config

from telebot import types

bot = telebot.TeleBot(config.TOKEN)

@bot.message_handler(commands=['start'])
def welcome(message):

    # keyboard
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    item1 = types.KeyboardButton("test")
    item2 = types.KeyboardButton("test2")

    markup.add(item1, item2)

    bot.send_message(message.chat.id, "Добро пожаловать".format(message.from_user, bot.get_me()),
        parse_mode='html', reply_markup=markup)

 class telebot.types.ForceReply(selective: Optional[bool] = None, input_field_placeholder: Optional[str] = None)

bot.polling(none_stop=True)

A: pip install pytelegrambotapi

напиши вот это в консоль

A: Самостоятельно нашел решение, оказывается нужно было обновить библиотеку pytelegrambotapi.


text:
Q: Magento 2 Admin link not working I have installed magento 2 using composer by follow this commands:- https://www.simicart.com/blog/magento-2-composer/
My magento set up done without any error but with this set up, my new installed magento front end is working but admin link not working.
Can anyone please help me with this? I have tried by clear cache and removed folder of var and pub/static but still same.
Sorry might be my questions will be silly, i am in learning phase so hope you guys can understand.
Thanks

A: I was got same issue in my window local computer and i was solved by this way.
Remove everything, except .htaccess file from pub/static folder.
Open app/etc/di.xml file and find in

Magento\Framework\App\View\Asset\MaterializationStrategy\Symlink

and replace to

Magento\Framework\App\View\Asset\MaterializationStrategy\Copy

Now execute bellow commands.
php bin/magento setup:upgrade;
php bin/magento setup:static-content:deploy -f;
php bin/magento setup:di:compile;
php bin/magento cache:flush;
sudo chmod -R 777 var pub generated;

A: I have installed it again and now this time, i have not included this option in command "--backend-frontname="admin"".
as i have checked dev docs installation link and in that the above option not there so i removed and try again.
And its working now with auto generated admin url.


text:
Q: mysqli::prepare(): Couldn't fetch MySQL I started using mysqli_* functions instead of the old mysql_* functions in PHP, and I'm having a bit of a problem with this code:
public function addUser($table, $code = false, $rows = false) {
   if (!$code) {
      header("Location: " . $this->authenticate());
   } else {
      $this->getToken($code);
   }
   $user = $this->getEndpoint('users/current', false, true);
   $user = $user->response->user;
   if (!$rows)
        $rows = array(
            "remote_id" => $user->id,
            "firstName" => $user->first_name,
            "lastName" => $user->last_name,
            "photo" => $user->photo->medium,
            "gender" => $user->gender == 'male' ? 1 : 2,
            "email" => $user->contact->email,
        );
   $rows['access_token'] = $this->accessToken;
   $stmt = $this->mysql->prepare("SELECT id FROM users WHERE access_token = '{$this->accessToken}'"); //line 136
   $stmt->execute(); //line 137
}

The code returns these 2 errors:

Warning: mysqli::prepare(): Couldn't fetch MySQL in C:\Users\Grega\Server\application\inc\classes\APIConnect.php on line 136
Fatal error: Call to a member function execute() on a non-object in C:\Users\Grega\Server\application\inc\classes\APIConnect.php on line 137

What is the reason for 'Couldn't fetch MySQL'? The database connection is correct, it works in other classes, and the query returns a valid result, if I echo it and execute it in phpMyAdmin. Also, my variable is named mysql NOT mysqli!

A: You should read more about the difference between MYSQL to MYSQLi.
While your code is:
$stmt = $this->mysql->prepare("SELECT id FROM users WHERE access_token = '{$this->accessToken}'");

You should do it like this:
$stmt = $this->mysql->prepare("SELECT id FROM users WHERE access_token = ?");
$stmt->bind_param("s" , $this->accessToken ); //Used 's' as I guess that the accessToken is a string

The binding part is the critical part of the prepare thing. (Your queries are safe)
After that you can use $stmt->execute(); and get_result().

A: For the first error: you probably closed the connection somewhere before this code, and this is why ($stmt -> close() )
For the second error: when you use (prepare()), you first introduce a SQL template to the database, which then has to pass the parameters to the "bind_param()" method to send it to the database with another protocol (to prevent SQL injection) and reduce the request and attach the parameters to SQL with execute() method


text:
Q: File not being created in Ruby script I am trying to open a non existent file and write to it, however when I run the script, no file is being created.
Here is the line of code
File.open("valid_policies.txt", 'a+').write(policy_number.to_s + "\n")

A: Instead of using .write try this instead:
File.open("valid_policies.txt", 'a+') {|f| f.write(policy_number.to_s + "\n") }

A: You're using:
File.open("valid_policies.txt", 'a+').write(policy_number.to_s + "\n")

That's a non-block form of open which doesn't automatically close the file. That means the data is most likely not being written to the file but is sitting in the IO buffer waiting to be flushed/synced. You could add a close but that only propagates non-idiomatic code.
Instead you can use:
File.write("valid_policies.txt", policy_number.to_s + "\n")

File.write automatically creates then writes to the file then closes it. It will overwrite existing files though.
If you aren't sure whether the file exists and want to create it if it doesn't, or append to it, then you use File.open with the a mode instead of a+. From the mode documentation:

"a"  Write-only, each write call appends data at end of file.
       Creates a new file for writing if file does not exist.

Using a+ will work but it unnecessarily opens the file for reading also. Don't do that unless you're sure that's what you have to do.
If I needed to append I'd use:
File.open('valid_policies.txt', 'a') do |fa|
  fa.puts policy_number
end

That's idiomatic Ruby. puts will automatically "stringify" policy_number if it has a to_s method, which it should have since you're already calling it, and it'll also automatically add the trailing "\n" if it doesn't exist at the end of the string. Also, using the block form of open will automatically close the file when the block exists, which is smart house-keeping.


text:
Q: Why won't packages I have installed in the terminal run on Spyder? I have been using Jupyter notebook for a while now and it's worked fine. I tried downloading Spyder today and a lot of the packages I installed in the terminal won't work on Spyder.
For example, pandas_datareader works fine in Jupyter notebook, but it won't work on Spyder. I get a module not found error when I try to import it.
I tried updating the packages as well as deleting and then reinstalling and it still won't work. I downloaded Spyder from the spyder-ide.org website.

A: It is common problem.
You may have two Pythons installed and you use Jupyter with one Python but Spyder may use other Python.
Different Pythons don't share modules.
Run in Spyder and Jupyter
import sys

print( sys.executable )

to see full path to Python used in Spyder and Jupyter and then you can use
/full/path/to/python -m pip install ...

to install modules in correct Pythons.

You may also check in Spyder's settings if you can set path to Python used in project - this way you may change Python and use version which has installed modules. This way you can also use different Pythons (with different modules) in different projects (ie. use virtual environments in projects - venv)

I assumed that Jupyter doesn't means Google Colab which runs Jupyter on Google's server and it install modules on this server - but Spyder runs on local computer.


text:
Q: If $x^Tx \geq y^Ty$ under what conditions for $Q$ is $x^TQx \geq y^TQy$? I am working on an optimization problem:
\begin{equation}
 \min_{v_1,\dots,v_n} \sum_{i=1}^{n} v_i^T Q v_i,
\end{equation}
where the dynamics is $v_{i+1} = A_iv_i$ and $Q \succeq 0$. $A_i$ is a function of $v_i$, i.e, $A_i = f(v_i)$. And based on $A_i$, the optimization would not be quadratic.
Assume $\exists ~ A$ such that $||A||_2 \succeq ||A_i||_2 ~\forall i$ (specifically $I \succeq A^2 \succeq A_i^2 \succeq 0$, and $A_i$ and $A$ are symmetric). I am trying to see if I can bound the cost $v_i^TQv_i$ using $A$ and solve a sub-optimal convex problem. I am wondering if
\begin{equation}\label{eq:cntrl}
 AQA \geq A_iQA_i ~\forall ~ i.
\end{equation}
Since $A^2 \succeq A_i^2$, for some vector $u$, I define $x = Au, y = A_iu$, so that $x^Tx \geq y^Ty$.
If the vector dot product $x^Tx \geq y^Ty$ and $Q$ is a symmetric PSD matrix ($ Q \succeq 0$), is $x^TQx \geq y^TQy$? If no, what other conditions must $Q$ satisfy for $x^TQx \geq y^TQy$ to hold? How about if $x^Tx > y^Ty$?
Alternatively, is there a path to directly show $AQA \geq A_iQA_i$? If not, what about when $A^2\succ A_i^2$?
Thank you for your help.

A: This is true only if $Q$ is a constant multiple of the identity.  If not, it has two distinct eigenvalues $\lambda_1 < \lambda_2$.  Let $x,y$ be unit eigenvectors corresponding to these respective eigenvalues and you see that $x^T x = y^T y = 1$ while $x^T Q x = \lambda_1 < \lambda_2 = y^T Q y$.


text:
Q: What is a good category of tame topological spaces? While the definition of a topological space nicely encapsulates the notion of points being close to each other, it doesn't seem to be a good notion of space. It has quite some problems:

*

*Every definition comes with many different variations:

*

*There is a zoo of separation axioms.

*There are at least four versions of connectivity.

*There are many distinct notions of manifolds and other spaces patched up local models (like CW-complexes).

*Often the definitions don't even seem to be standardized (see for example my question on closed neighborhood deformation retracts or find the "right" definition of locally compact space).

*Those variations are necessary, as there are many pathological counterexamples (like for example the topologist's sine curve, the Warsaw circle or the Hawaiian earring in the context of connectivity).

*There are many unintuitive results (there are space filling curves, injective continuous maps are not embeddings, quotient maps are not open etc.).

*global $\not\Rightarrow$ local. (I find it confusing at best that being path connected does not imply being locally path connected...)

*The category $\mathsf{Top}$ is not cartesian closed. Phrased differently, the sets of maps between spaces do not carry a canonical topology in such a way that composition is continuous. (I am unsure about the set of maps having a topology being intuitive, but it is a very useful tool to have, especially when doing homotopy theory)

Arguably it is good to have such a general setting many subjects in mathematics can build upon. What bothers me is that, as soon as one wants to do something geometric / homotopical, one has to restrict to certain topological spaces, dealing with a lot of additional assumptions to avoid those pathological exceptions. Moreover often the topological notions are not really the right ones, when working in a non-topological context (a scheme seldomly is hausdorff, it may be separated though, borrowing but not using topological intuition). So my question is

What is a good category of tame topological spaces, in the sense that it

*

*is complete, (at least finitely) cocomplete and cartesian (or maybe monoidal) closed

*contains the prime examples of spaces like metric spaces, smooth manifolds, CW-complexes, polyhedra

*makes standard notions coincide (as much as possible) + avoids pathological counterexamples

*has a direct axiomatization (no "Hausdorff spaces, which admit a neighborhood of locally compact opens with connected fibers thingy...")

I am aware of the possibility that this question may not have a satisfying answer. The fact that genius minds like Grothendieck noted "The foundations of topology are inadequate is manifest in the form of false problems [..., which] include the existence of wild phenomena (space-filling curves, etc.) that add complications which are not essential" (On Grothendieck's Tame Topology, p.3) but not come up with a groundbreaking solution (I don't understand o-minimal structures yet, but they do not really look satisfying) leads me to think that the question might not even have one. However I feel like asking this question nonetheless will lead to insights of one kind or another...
As always: thank you for your time and considerations.
PS: The question feels vague, but I don't really know what to specify further. So any suggestions for making it more precise are very welcome...

A: Your conditions cannot happen all at the same time. The category of sequential spaces is complete, co-complete, coreflective, Cartesian closed, and it includes all of the examples you want including metric spaces. This is an example of one of Steenrod's "convenient categories" for doing algebraic topology. However, as soon as you include all metric spaces or all compactly generated spaces you're including tons of what you call "pathological" things like the Hawaiian earring. Additionally, notice that if you want your category of spaces to be complete and contain $S^1$, you're automatically going to be forced to include the Hawaiian earring and infinite dimensional torus. Both of these are connected, compact, locally-path-connected metric spaces but they are not locally contractible. How is this usually handled? The power of "tame" homotopy theory is that you are only interested in things up to weak homotopy equivalence and so you can always replace a space by a weakly homotopy equivalent CW complex. In the case of limits (like the Hawaiian earring) you can replace it with the homotopy limit in the CW-category so that you still have a CW-complex in your hand. So in algebraic topology you really want a "space" not to be so much a geometric-type space but rather an equivalence class of spaces, e.g. a "weak homotopy type." To use it maybe you have to go back and forth between a few categories like the category of compactly generated spaces and it's homotopy category and the category of CW-complexes and its homotopy category....This is really not so bad.
I'd also like to encourage you to be open to the possibility that there are many fascinating and useful theories that involve "pathological" examples. Mapping class groups of infinite type surfaces are large groups that could easily be labelled as pathological yet they are quite popular at the moment. What is considered tame/pathological very much depends on current interests and these change over time as new mathematics is developed. Many times I have found myself using mathematics that I never thought I would. If I had been completely shut off to it as inherently useless or ugly, I would have been severely restricted in what I could do. It is somewhat fashionable in certain fields to react sharply and negatively to considering notions of spaces that are anything but CW-complexes or manifolds and this self-induced bubble probably does more harm than good. I think that with experience comes an appreciation for the non-existence of mathematical objects which are the "best" or which satisfy all ideals at the same time. Rather a mathematical object like a category should only be considered "good" relative to the intended use or application.


text:
Q: Cell probe model From Algorithms 4th Edition
Q. What is the cell-probe model?
A model of computation where we only count accesses to a random-access memory
large enough to hold the input and consider all other operations to be free.
I want to understand this statement. Please help me understand this with examples.

A: Problem: determine whether the number 0 appears in the input, which must be a sorted list L. The cell-probe complexity is exactly ceil(log2(len(L) + 1)) by binary search because that's how many elements of L we have to look at. We don't need big-O to state this result because the overhead of dispatching the probes is not counted.
Problem: determine whether the input is a satisfiable Boolean formula (SAT). Even though this problem is NP-complete and thus not known to have a polynomial-time algorithm, we do know that the cell-probe complexity is at most n, because one algorithm is to read the entire input and do an exponential-time computation that doesn't make any probes.
Since the cell-probe model allows unrealistic amounts of computation, it is almost always used as the setting for an impossibility result, that is, even if we had all the time and space in the world, no algorithm could access less than this much of the input.


text:
Q: SQL to Entities syntax for INNER JOIN and DISTINCT I'm a bit fresh to Entity Framework, and need some advice on the syntax. My goal is to retrieve a distinct list of filtered equipment from one table and match them to ID's in another table.
Here is the RAW SQL that accomplishes the JOIN.
SELECT DISTINCT DowntimeReasons.Equipment, Equipment.ID
FROM DowntimeReasons INNER JOIN Equipment
ON DowntimeReasons.Equipment = Equipment.Equipment
WHERE DowntimeReasons.Emergency = 1
I've been able to recreate the distinct list of equipment in SQL to Entities with the following code.
            var distinctEquipmentList = db.DowntimeReasons
                .Where(x => x.Emergency == true)
                .Distinct()
                .Select(x => x.Equipment)
                .ToList();

But how do I join this list to the IDs I need from the other table?  I'm open to query syntax or method syntax.  Heck, as I'm learning solo, I'm open to any help! Thank you!

A: Without looking at what your entities look like, here's a shot a it.
You can try something like this:
var query = (from dr in db.DowntimeReasons
            join e in db.Equipments on dr.Equipment equals e.Equipment
            where e.Emergency
            select e.Equipment).Distinct().ToList();

If this doesn't work, then please post your entities.
Hope this helps.


text:
Q: Suggestions for replication of data from MS Sql 2005 and MySql My company currently has a transactional db running on Sql Server 2005. We are going to add a MySql (running on linux) reporting db. We'll need to get replication running from the MS-Sql db to the MySql db. It doesn't have to be real time but should be within a few minutes.
I've got pretty good MSSql Dev skills and so-so dba skills but no MySql background. The MySql guy on our team has no MSSql experience.
I was wondering if anybody has setup anything similar and might have some suggestions. I've seen some things on migrating data between the two but not much for on-going replication. Right now my best guess is to set something up in SSIS and run it under the Sql Agent. I'm going to work on the SSIS idea for now but welcome any suggestions.

A: Friend of mine for almost the same case (he copies some data from just a few tables from  MSSQL to MySQL) built something like that:

*

*Added trigger to each table which will be replicated. Trigger save primary key, operation type (i)nsert/(u)pdate/(d)elete and source table name in special table (less or more).

*Small .NET app scans this special tables for new keys every few minutes and reads data from source MSSQL tables and save them in destination tables in MySQL (less or more).

This works fine because:

*

*Tables don't change a lot.

*He copies just a few columns.

Pros:

*

*Fast & easy to implement & change.

Cons:

*

*In house made tool is not perfect :).

A: I think it depends on what reporting software you'll be using on top of the MySQL database.  If you're using Pentaho - they have software to handle this situation.  If reporting is just going to be ad hoc and the structure will remain exactly the same, I would seriously consider setting up another MSSQL instance and working with that.  If you already have MSSQL, don't putz around trying to make the two friendly with each other.  You should be able to have the second MSSQL instance tied down to only limited resources so that the transactional db never gets impacted even if they're on the same machine.

A: A third-party application claims the ability to do this: Daffodil Replicator. I think it's available both as Open Source and Enterprise.

A: SSIS ETL seems like the simplest way to go. You could actually export to a staging area (CSV files) and than import to MySQL. This would take care of different format problems. If you get creative, MySQL supports the CSV storage engine (see here), so this could save the load step in SSIS.


text:
Q: Си запись лишних символов в файл Уже задавал вопрос по своей программе, но возникла новая проблема
Суть - в файле все отрицательные числа заменить нулём. Проблема возникает в том, что, судя по всему, цикл работает некорректно, и откуда-то в файл из буферного файла дописываются лишние числа.
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

void open_file(char *arg,FILE **addr1,FILE **addr2){
    setlocale(LC_ALL, "RUS");
    *addr1=fopen(arg,"r+"); *addr2=fopen("buf.txt","w+");
    printf("1\n");
    if(*addr1==NULL){
        printf("Не могу открыть файл %s\n, проверьте аргумент", arg);
        exit(EXIT_FAILURE);
    }
}

void transform(FILE **addr1,FILE **addr2){
    int res,x,ch;
    printf("1\n");
    for(;;){
        res=fscanf(*addr1,"%d",&x);
        printf("1\n");
        if(res<=0) {
            fputc(x=EOF,*addr2);
            break;
            }
        if(x<0) x=0;
        fprintf(*addr2,"%d ",x);
    }
    printf("1\n");
    fseek(*addr1,0,SEEK_SET);
    fseek(*addr2,0,SEEK_SET);
    while ((ch=fgetc(*addr2))!=EOF){
        fputc(ch,*addr1);
    }
    printf("1\n");
}

void close_file(FILE **addr1,FILE **addr2){
    fclose(*addr1);
    fclose(*addr2);
//  remove("buf.txt");
}

int main(int argc, char ** argv){
    setlocale(LC_ALL, "RUS");
    if (argc!=2){
        printf("Некорректное число аргументов");
        exit(EXIT_FAILURE);
    }
    FILE *addr1, *addr2;
    open_file(argv[1],&addr1,&addr2);
    transform(&addr1,&addr2);
    close_file(&addr1,&addr2);
    return 0;
}

Пробовал записывать как и посимвольно, так и по числу - эффект один и тот же. Где я допускаю ошибку?
Пример содержимого файла: -789 254 355 -98 -48 2


text:
Q: Apache James with AWS Keyspaces for Cassandra
Trying to connect Apache James with AWS Keyspaces. James is able to connect but, failing with the above error after few seconds.

According to the stack trace the exception is thrown from the above method.
Any help is appreciated.
Thank you,

A: As error message shows, the now function isn't supported by Amazon Keyspaces, so James won't work out of box without modification.  You can try to change that function to something like this (see doc for QueryBuilder):
return session.prepare(select()
         .all()
         .from("local"))
         .bind();

and rebuild. But most probably, it will fail in some other place.
P.S. Really, there are plenty of differences from OSS Cassandra, so a lot of code may not work.


text:
Q: Mobile Safari - Javascript open tab without losing focus on current page I'm currently working on a webpage that, when visited, opens up two more webpages in mobile safari.
The only issue is that when the new tabs are loaded, the browser is focusing on the final one to load.
I've tried setting the Safari setting 'Open Links -> In Background' but this only seems to give you the option of holding down on a link then manually selecting to open the link in background (thus remaining focused on the current page).
Is there anyway to automatically open a weblink in Mobile Safari using javascript without losing focus on the current webpage?
Here is an example of the code I am currently using.

Open Tabs

A: I am using a for a long time this kind of logic for "pop-unders".
Hope this will be useful for you:
-Basic idea is to open page itself in new tab and, in the same time, redirect "old" tab/page to some other location
  function popunder_redirect(){
      window.open("#tab");
      window.location="http://redirecturl.com";
    }

Now, as you can see, you have hash link (#tab) right next to your original page link that you can use as some kind of fake history to adjust your javascript or some other page progress thru checking on page load:
jQuery(document).ready(function(){

var hashValue = window.location.hash;     //get hash value

//check for hash value

if (hashValue!=undefined && hashValue=="#tab")

{
      //display progressed page}

else{
     //display start page
}

});


text:
Q: Copiar una cadena a un puntero en C con strcpy() Estoy estudiando C y vi que para copiar una cadena de caracteres a un puntero se debe utilizar la función strcpy(), ya que si se realiza una asignación directa, el puntero señalaría otra dirección de memoria.
Entonces escribí este código:
#include <stdio.h>
#include <string.h>

void main(){
   char *mensaje = "Bienvenida";
   printf("Direccion: %d\n", mensaje);    //-->Direccion: 4210688

   strcpy(mensaje, "Despedida");
   printf("Direccion: %d\n", mensaje);
}

Al ejecutar, solo sale en pantalla el primer printf(), luego hay una pausa y se termina el programa. No sé por qué falla. Agradecería si alguien me explicara.

A: Tu idea base es correcta. Pero hay algunos detalles que explicar.
Primero, veamos lo que dice la documentación sobre cadenas literales:

String literals are not modifiable (and in fact may be placed in read-only memory such as .rodata). If a program attempts to modify the static array formed by a string literal, the behavior is undefined.

Que viene a ser, mas o menos:

Los literales de cadena no son modificables (y de hecho pueden ser colocados en segmentos de memoria de sólo lectura tales como .rodata). Si un programa intenta modificar la zona de memoria ocupada por un literal de cadena, el comportamiento es indefinido.

Así tal cual, ya sería suficiente. No obstante, vamos a profundizar un poco mas.
Cuando un programa se compila y enlaza, el resultado final es algo capaz de ser ejecutado por el sistema operativo destino; ha de atenerse a las normas de dicho destino.
Los sistemas operativos modernos utilizan múltiples técnicas para optimizar el uso de la memoria. Y una de ellas es la capacidad de compartir zonas de la misma entre varias aplicaciones.
Para conseguir esto, la mayoría utiliza el concepto de segmento (no confundir con segmentos de memoria del procesador). Un segmento es un bloque de memoria con ciertos atributos.
Al compilar tu código, se generaría un ejecutable con varios de estos segmentos:

[Código privado] (tu propio código)
  [Código compartido] (librerías dinámicas: printf, strcpy)
  [DatosDeSoloLectura] (los literales "Bienvenida" y "Despedida").

El sistema operativo trata de forma distinta los distintos tipos de segmentos. Todos los mostrados aquí tienen una particularidad: son de solo lectua. Eso permite al sistema optimizar la memoria: si no se pueden escribir, compartir un segmento entre procesos es relativamente fácil: basta con mapearlo a las direcciones accesibles por cada uno.
Ahora ya podemos entrever lo que está pasando:

*

*El compilador genera un ejecutable a partir de tu código. En el, en zonas marcadas como de solo lectura, se encuentran tus literales ( "Bienvenida" y "Despedida" ).

*Creas una variable llamada mensaje, de tipo puntero a char, y haces que apunte a la zona de memoria que contiene el literal "Bienvenida".

*Intentas modificar la zona de memoria a la que apunta mensaje.

*El Sistema Operativo te dice, educadamente, que estás intentando saltarte sus mecanismos de protección de memoria.
¿ Podemos evitar esto ? Bueno, hay varias formas. Quizás la mas sencilla sea esta:
int main( void ) {
   char mensaje[] = "Bienvenida";
   printf( "Direccion: %p\n", mensaje );

   strcpy( mensaje, "Despedida" );
   printf( "Direccion: %p\n", mensaje );

  return 0;
}

Como ves, la única diferencia es como se ha declarado mensaje. Algo sutil ... pero importante :-)

*

*El compilador genera un ejecutable a partir de tu código. En el, en zonas marcadas como de solo lectura, se encuentran tus literales ( "Bienvenida" y "Despedida" ).

*Solicitas al compilador una zona de memoria automática con capacidad suficiente para contener el literal "Bienvenida". A esa zona accederemos mediante un puntero mensaje.

*El compilador copia el literal "Bienvenida" desde su posición original a la zona de memoria apuntada por mensaje.

*Modificas la zona de memoria a la que apunta mensaje.
Puesto que ahora estás utilizando un bloque de memoria declarado como automático, está garantizado que podrás escribir en él sin problemas (bueno, mas o menos ... pero lo dejamos ya).
Nota que toda la parrafada anterior es dependiente del sistema operativo. Dicho de otra manera: tu código fallará en Linux y el Windows. Funcionará perfectamente en, por ejemplo, MS-DOS.
Nota2: Por sugerencia en los comentarios, he arreglado un poco el código: corregir la definición de main, usar "%p" para imprimir punteros, y colocar el return 0 final.


text:
Q: How to specify download directory with pupeteer? I'd like to automate the download of some pdf bill in a specific directory but I didn't manage to do it.
Note i'm using puppeteer 3.0.2 on windows:
I tried to setup it multiple ways :
Initializing the browser:
const browser = await puppeteer.launch({
    headless: navMode,
    userDataDir : "E:/projets/factures/",
    args: [
        '--start-maximized',
        // you can also use '--start-fullscreen'
    ]

});

I also tried:
await page._client.send('Page.setDownloadBehavior', {behavior: 'allow', downloadPath: 'E:/projets/factures/'});

juste before the download
i tried also :
page.on('request', req => {
    if (req.url() === urlFile) {
        const file = fs.createWriteStream('./file.pdf');
        https.get(req.url(), response => response.pipe(file));
    }
});

all of this is before :
await page.goto(urlFile); //urlFile contains the pdf url

The PDF is only downloading in the Default Download Directory

A: here I can get solution for you.
puppeteer - how to set download location
In your code,  'E:/projets/factures/' this seems to be error.
Please try use this like './../../projects/fatures/'
Thanks

A: you can use achieve this easily using puppeteer-extra & a puppeteer-extra-plugin-user-preferences plugin.
please refer to this answer for details


text:
Q: Limit $\lim_{x\rightarrow0}\frac{1}{x}\int_{0}^{\sin x}\sin \frac{1}{t} \cos t^{2}\mathrm{d}t$ Determine whether or not the limit below exists.
$$\lim_{x\rightarrow0}\frac{1}{x}\int_{0}^{\sin x}\sin \frac{1}{t} \cos t^{2}\mathrm{d}t$$
I tried to use the Mean value theorem integrals to prove the limit exists, but it does not exist for $\lim\limits_{x\rightarrow0}\sin \frac{1}{x}$. So I guessed the limit does not exist and used the Cauchy principle to prove it, but I failed.
Any idea will be helpful.

A: Since $\cos t^2$ is monotone decreasing for $t$ sufficiently close to $0$, by the second mean value theorem for integrals there exists $\xi_x \in (0, \sin x)$ such that
$$\int_0^{\sin x} \sin \frac{1}{t} \cos t^2 \, dt = \cos(0) \int_0^{\xi_x}\sin \frac{1}{t}  \, dt = \int_0^{\xi_x}\sin \frac{1}{t}  \, dt$$
Taking $g(t) = t^2 \cos \frac{1}{t}$ for $t > 0$ and $g(0) = 0$,  we have $g'(0) =0$ and for $t>0$,
$$g'(t) = 2t \cos \frac{1}{t} + \sin \frac{1}{t},$$ and, using the FTC,
$$\int_0^{\xi_x}\sin \frac{1}{t}  \, dt = \int_0^{\xi_x} g'(t) \, dt-\int_0^{\xi_x}2t \cos \frac{1}{t} \, dt=\xi_x^2\cos \frac{1}{\xi_x} -  \int_0^{\xi_x}2t \cos \frac{1}{t} \, dt$$
Thus,
$$\frac{1}{x} \int_0^{\sin x} \sin \frac{1}{t} \cos t^2 \, dt = \xi_x \frac{\xi_x}{x}\cos \frac{1}{\xi_x} - \frac{1}{x} \int_0^{\xi_x}2t \cos \frac{1}{t} \, dt$$
We can apply the mean value theorem to the integral on the RHS (since the integrand is continuous) to find $\theta_x \in (0,\xi_x)$ such that
$$\frac{1}{x} \int_0^{\sin x} \sin \frac{1}{t} \cos t^2 \, dt = \xi_x \frac{\xi_x}{x}\cos \frac{1}{\xi_x} - \frac{\xi_x}{x} 2\theta_x \cos \frac{1}{\theta_x} $$
Since $\xi_x/x < 1$, we have
$$\left|\frac{1}{x} \int_0^{\sin x} \sin \frac{1}{t} \cos t^2 \, dt\right| \leqslant \xi_x +2 \theta_x$$
Since $\xi_x , \theta_x \to 0$ as $x  \to 0+$, we get
$$\lim_{x \to 0+}\frac{1}{x} \int_0^{\sin x} \sin \frac{1}{t} \cos t^2 \, dt = 0$$
Similarly we can show that the limit as $x \to 0-$ is $0$ as well.

A: Well, here is a slightly different approach.
Note that $(\sin x) /x\to 1$ as $x\to 0$ and hence (add missing steps here if you need) the desired limit equals the limit of $$\frac {1}{x}\int_{0}^{x}\sin(1/t)\cos t^2\,dt$$ and we can write the above expression as $$\frac{1}{x}\int_{0}^{x}\sin(1/t)(\cos t^2-1)\,dt+\frac{1}{x}\int_0^x\sin(1/t)\,dt$$ The integrand in first integral tends to $0$ as $t\to 0$. Therefore by the fundamental theorem of calculus (part 1) the first term above tends to $0$.
The desired limit thus equals $$\lim_{x\to 0}\frac {1}{x}\int_0^x\sin(1/t)\,dt$$ This is a famous question on this website and the desired limit is $0$. You can prove this by using the auxiliary function $$g(x) =x^2\cos(1/x),x\neq 0,g(0)=0$$ We have $$g'(x) =2x\cos(1/x)+\sin(1/x),x\neq 0,g'(0)=0$$ By fundamental theorem of calculus (part 2) we have $$g(x) =g(x) - g(0)=\int_0^x g'(t) \, dt$$ which means that $$\frac {1}{x}\int_{0}^{x}\sin(1/t)\,dt=\frac{g(x)}{x}-2\cdot\frac{1}{x}\int_0^x t\cos(1/t)\,dt$$ Now the first term on right tends to $g'(0)=0$ and second term on right also tends to $0$ (via fundamental theorem of calculus (part 1) as the integrand tends to $0$ as $t\to 0$).
You should also observe that the above derivation works in case $\cos t^2$ is replaced by any Riemann integrable function $\phi(t)$ which tends to $1$ as $t\to 0$.

For those wondering about the version of FTC used in above I state them explicitly.
FTC Part 1: Let $f:[a, b] \to\mathbb {R} $ be a function which is Riemann integrable on $[a, b]$. Then the function $F:[a, b] \to\mathbb {R} $ defined by $$F(x) =\int_a^x f(t) \, dt$$ is continuous on $[a, b] $. Further if $c\in[a, b] $ is a point such that right hand limit of $f$ at $c$ is $L$ then the right hand derivative of $F$ at $c$ exists and equals $L$ (the statement holds if right is replaced by left).
FTC Part 2: Let $f:[a, b] \to\mathbb {R} $ be Riemann integrable on $[a, b] $ and let $F:[a, b] \to \mathbb {R} $ be continuous on $[a, b] $ and differentiable on $(a, b) $ with $F'(x) =f(x)\, \forall x\in(a, b) $ then $$\int_a^b f(x) \, dx=F(b) - F(a) $$


text:
Q: How can I find the Taylor series of a function using the known Taylor series of a related function? I am trying to calculate the Taylor series for the function:
$$f(x) = {\frac 1 x}(1 - \cos\sqrt{x})$$
How do I do it, if I know the Taylor series for $\cos(x)$?
$\cos x = {\Large \sum\limits_{k = 0}^{\infty}}\dfrac{(-1)^k x^{2k}}{(2k)!}$
It should be done just with algebraic modifications... Do I also need to know the Taylor series for $1/x$? Thank you!

A: First plug in $x \to \sqrt{x}$ to get
$$
\cos(\sqrt{x}) = \sum_{k = 0}^\infty \frac{(-1)^k (\sqrt{x})^{2k}}{(2k)!} = \sum_{k = 0}^\infty \frac{(-1)^k x^{k}}{(2k)!}
$$
Now if you look at
$$
-\cos(\sqrt{x}) = -\sum_{k = 0}^\infty \frac{(-1)^k x^{k}}{(2k)!} = \sum_{k = 0}^\infty \frac{(-1)^{k+1} x^{k}}{(2k)!}
$$
Do you see how to proceed from here?
EDIT:
Notice then that the $k = 0$ term is $-1$ so that when we add $1$ to the sum this term cancels out so
$$
1-\cos(\sqrt{x}) = \sum_{k = 1}^\infty \frac{(-1)^{k+1} x^{k}}{(2k)!}
$$
Finally we have
$$
\frac{1}{x} \left(1-\cos(\sqrt{x}) \right) = \frac{1}{x}\sum_{k = 1}^\infty \frac{(-1)^{k+1} x^{k}}{(2k)!} = \sum_{k = 1}^\infty \frac{(-1)^{k+1} x^{k}}{x(2k)!} = \sum_{k = 1}^\infty \frac{(-1)^{k+1} x^{k-1}}{(2k)!}
$$


text:
Q: Python variables change in every object I'm playing around with pygame for the first time, trying to make multiple rectangles move across the screen. Here's my code:
import pygame

pygame.init()

scrWidth = 1200
scrHeigth = 900
done = False
rectangles = []

screen = pygame.display.set_mode((scrWidth, scrHeigth))
clock = pygame.time.Clock()

class Rectangle:
    speed = [1,1]
    colourSpeed = 300
    colourID = 0
    colour = (0, 0, 255)
    size = 60

    def __init__(self, name = "", x=0, y=0, speed=False, colour=False, size=False):
        self.name = name
        self.x = x
        self.y = y
        self.doesSpeed = speed
        self.doesColour = colour
        self.doesSize = size

    def draw(self):
        pygame.draw.rect(screen, self.colour, pygame.Rect(self.x, self.y, self.size, self.size))

    def checkCollision(self):
        if self.x < 0 or self.x > scrWidth-self.size:
            self.speed[0] = -self.speed[0]
        if self.y < 0 or self.y > scrHeigth-self.size:
            self.speed[1] = -self.speed[1]

    def move(self):
        self.x += self.speed[0]
        self.y += self.speed[1]

    def changeColour(self):
        self.colourID = (self.colourID+1)%self.colourSpeed
        if 0 <= self.colourID < (self.colourSpeed/3):
            self.colour = (0, 0, 255)
        elif (self.colourSpeed/3) <= self.colourID < (2*self.colourSpeed/3):
            self.colour = (0, 255, 0)
        elif (2*self.colourSpeed/3) <= self.colourID < self.colourSpeed:
            self.colour = (255, 0, 0)

rect1 = Rectangle("rect1", 30, 30, False, True, False)
rectangles.append(rect1)
rect2 = Rectangle("rect2", 300, 300)
rectangles.append(rect2)

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done=True

    screen.fill((0, 0, 0))
    for obj in rectangles:
        obj.checkCollision()
        if obj.doesColour: obj.changeColour()
        obj.move()
        obj.draw()

    pygame.display.flip()
    clock.tick(60)

The problem is that when a rectangle collides with the edge of the screen all rectangles change direction(speed). However if I make rectangles with different speeds this doesn't happen.
ex: rect1 has speed [1,1] and rect2 has speed [2,2].
What's causing this and how can I fix it?

A: Move the speed, colourSpeed, colourID, colour, size to the init method.
At that moment that fields are defined as class fields, so they are changed globally for all rectangles.
Solution:
def __init__(self, name = "", x=0, y=0, speed=False, colour=False, size=False):
        self.name = name
        self.x = x
        self.y = y
        self.doesSpeed = speed
        self.doesColour = colour
        self.doesSize = size
        # here it comes
        self.speed = [1,1]
        self.colourSpeed = 300
        self.colourID = 0
        self.colour = (0, 0, 255)
        self.size = 60


text:
Q: Deserialize ArrayList in Java I have my own little serialiser class
package mypackage.shared;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Serializer {

    static final String HEXES = "0123456789ABCDEF";

    public static String serialize(Object o) throws IOException {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(stream);

        os.writeObject(o);
        os.close();
        return toHex(stream.toByteArray());
    }

    public static Object deserialize(String hexString)  throws IOException, ClassNotFoundException {
        byte[] serializedBytes = toByteArray(hexString);
        ByteArrayInputStream bis = new ByteArrayInputStream(serializedBytes);
        ObjectInputStream ois = new ObjectInputStream(bis);

        Object o = null;
        o = ois.readObject();
        ois.close();
        return o;
    }

    public static String toHex( byte [] raw ) {
        if ( raw == null ) {
            return null;
        }
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
        for ( final byte b : raw ) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4))
            .append(HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
    }

    private static byte[] toByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

}

It works great for some home made objects I have. However, as soon as I have an ArrayList of these objects it fails to deserialize them. ANy idea why that would be? I find it quite hard to debug since readObject() just fails

A: If serialization doesn't work it means that some object is not serializable.
Try to deserialize an arraylist containing only one home object and do it for all home objects