text:
Q: Encoding Node/Postegres SQL_ASCII Tenho uma API em Node que se conecta com um banco PostgreSQL utilizando o módulo "pg", onde o banco em questão usa o encoding "SQL_ASCII". Não tenho a opção de mudar o encoding do banco pois o mesmo é da prefeitura da minha cidade.
Quando faço uma busca em uma tabela/campo que contém caracteres especiais como por exemplo "Administração", tenho o seguinte retorno: "Administr\\xe7\\xe3o".

Pelas pesquisas que andei fazendo descobri que \xe7 é o codigo Unicode da letra ç, inclusive consigo traduzir essa string se utilizo métodos do JavaScript como decodeURIComponent("\xe7"),

Porém, a resposta que  tenho é com DUAS barras ("\\xe7"), sendo assim, todos os métodos que tentei utilizar nenhum funcionou. Obviamente também tentei fazer o '\\xe7'.replace('\\\\\', '\\') para então tentar utilizar o decode, mas não tive sucesso.
Quando coloco essa string em uma página HTML (utf8), ela mostra da seguinte forma: "Administr\xe7\xe3o" com 1 barra, sendo que o meu objetivo é mostrar a palavra correta.
Onde estou errando?

A: Acho que você está confundindo as codificações. %C3%A7 é ç codificado em URI, xe7 é o apenas o hexadecimal de ç.
Tente dessa forma:

const area = "Administra\\\\xe7\\\\xe3o";
console.log(area);

const area_decod = unescape(area.replace(/\\\\x/g, '%'));
console.log(area_decod);


text:
Q: How to get Codecov to consume Apex coverage data without getting stuck "Processing..."? I've followed this Salesforce blog Drive your Testing Strategy with Code Coverage to get LWC and Apex code coverage numbers reported in Codecov via GitHub actions. The LWC part works well, but it appears that the Apex test results cause Codecov to get stuck "Processing...".
Have you experience and solved this problem for Apex?
(Yes I have a ticket raised with Codecov as well and will post any solution they provide here. But this appears to be Salesforce language specific i.e. Apex problem that someone on this site may have experienced.)

A: Codecov support think that this Salesforce change https://developer.salesforce.com/blogs/2021/04/clearer-apex-commands.html is tripping up their parser so will look at it a bit more. Apex is probably not a priority for them though, so this might stay broken.
But good work from Codecov support to engage with a customer presently on a free trial.
Based on the SF link, I've tried:

*

*-r junit and that didn't fix it

*-r tap and that didn't work

*-r json and that didn't work

redpajama_set_name: RedPajamaStackExchange


text:
Q: Particle Effect Stopped When Its Parent Node Being Re-added To The Scene I attached a SKEmitterNode to a SKSpriteNode. At the beginning, everything was fine. But after changing the parent node of the sprite node, particle effects stopped for some reason.
To attach the emitter node to the sprite node, in the sprite node class:
self.addChild(theEmitterNode)

In the game scene, I first attached the sprite node to NodeA, where particle effects worked as expected:
theSpriteNode.theEmitterNode.targetNode = self // self is the scene
nodeA.addChild(theSpriteNode)

But when I change the parent of the sprite node, particle effects stopped:
self.theSpriteNode.removeFromParent()
nodeB.addChild(theSpriteNode)

Any ideas how to solve it?


text:
Q: Find empty positions in a grid In a Contents table, items are stored in X,Y coordinates:
Contents
-------
id
parent_id
pos_x
pos_y

Assume the container size is 3 by 3. I'd like to find which positions in a given container are free. So far I've generated a 2D matrix:
SELECT *
FROM
    (SELECT rownum X FROM dual  CONNECT BY LEVEL <= 3 ) xaxis
INNER JOIN
    (SELECT rownum Y FROM dual  CONNECT BY LEVEL <=3 ORDER BY 1) yaxis
ON xaxis.X <> yaxis.Y OR xaxis.X = yaxis.Y

Then I attempt to JOIN the queries together, excluding X,Y positions present in Contents:
SELECT X, Y
FROM
    (SELECT rownum X FROM dual  CONNECT BY LEVEL <= 3 ) xaxis
INNER JOIN
    (SELECT rownum Y FROM dual  CONNECT BY LEVEL <=3 ORDER BY 1) yaxis
ON xaxis.X <> yaxis.Y OR xaxis.X = yaxis.Y

INNER JOIN (
    SELECT pos_x, pos_y FROM Contents WHERE parent_id = ?) items
ON items.posx <> xaxis.X AND items.posy <> yaxis.Y;

This doesn't treat each pair as unique, and excludes values from all rows if a position is occupied. For example, assuming that (2, 2) is occupied, the above returns:
X   Y
-----
1   1
1   3
3   1
3   3

Essentially I'm trying to get the difference of the two sets. Any help appreciated.

A: I figured out the answer right before I posted the question, so I thought I'd post it and answer it at the same time. Stating the problem as get the difference of the two sets set me in the right direction.
The answer is the MINUS operator. Replace the final JOIN with MINUS and you get the intended results:
select X, Y
from
    (select rownum X from dual  CONNECT BY LEVEL <= 3 ) xaxis
inner join
    (select rownum Y from dual  CONNECT BY LEVEL <=3 order by 1) yaxis
on xaxis.X <> yaxis.Y OR xaxis.X = yaxis.Y

MINUS

select pos_x, pos_y FROM Contents WHERE parent_id = ?;

which returns the intended result (note the lack of (2, 2)):
X   Y
-----
1   1
1   2
1   3
2   1
2   3
3   1
3   2
3   3

Today was a good day

A: You could do this with an outer join rather than a minus (although you'd have to test both to find out which is more performant for your data!).
If you are only doing it for a single parent_id at a time, you would do:
WITH CONTENTS AS (SELECT 1 parent_id, 2 pos_x, 2 pos_y FROM dual UNION ALL
                  SELECT 2 parent_id, 2 pos_x, 1 pos_y FROM dual)
SELECT xaxis.x,
       yaxis.y
FROM   ((SELECT LEVEL x FROM dual CONNECT BY LEVEL <= 3) xaxis
        CROSS JOIN (SELECT LEVEL y FROM dual CONNECT BY LEVEL <= 3) yaxis)
       LEFT OUTER JOIN CONTENTS c ON c.pos_x = xaxis.x AND c.pos_y = yaxis.y AND c.parent_id = 1
WHERE  c.parent_id IS NULL
ORDER BY x, y;

         X          Y
---------- ----------
         1          1
         1          2
         1          3
         2          1
         2          3
         3          1
         3          2
         3          3

Alternatively, if you want to run it for all parent_ids, you could use a partitioned outer join like so:
WITH CONTENTS AS (SELECT 1 parent_id, 2 pos_x, 2 pos_y FROM dual UNION ALL
                  SELECT 2 parent_id, 2 pos_x, 1 pos_y FROM dual)
SELECT c.parent_id,
       xaxis.x,
       yaxis.y
FROM   ((SELECT LEVEL x FROM dual CONNECT BY LEVEL <= 3) xaxis
        CROSS JOIN (SELECT LEVEL y FROM dual CONNECT BY LEVEL <= 3) yaxis)
       LEFT OUTER JOIN CONTENTS c PARTITION BY (c.parent_id) ON c.pos_x = xaxis.x AND c.pos_y = yaxis.y
WHERE  c.pos_x IS NULL
AND    c.pos_y IS NULL
ORDER BY c.parent_id,
         xaxis.x,
         yaxis.y;

 PARENT_ID          X          Y
---------- ---------- ----------
         1          1          1
         1          1          2
         1          1          3
         1          2          1
         1          2          3
         1          3          1
         1          3          2
         1          3          3
         2          1          1
         2          1          2
         2          1          3
         2          2          2
         2          2          3
         2          3          1
         2          3          2
         2          3          3


text:
Q: Передача кода клавиши в аргумент функции есть код
element.keydown(arrowMove(Key.Code));

Реализовать хочу в
function arrowMove(key)
        {
            if (key == 55)
            {
                //что то делаем
            }
            else
            {
               return false;
            }
        }

Так собственно как передать код клавиши которая будет нажата на элементе.
Пробывал передавть event но толку ноль

A: Можно так
element.keydown(function(event){
  arrowMove(event.keyCode);
});

или
element.keydown(arrowMove);
function arrowMove(e) {
  if (e.keyCode == 55) {
    //что-то делаем
  }
}


text:
Q: ReactJS: cannot type into input field on certain web browsers I am creating a React component which includes several input feilds.
I have encountered an issue on the iPad(Safari and Chrome) and Safari browser on Mac.
I cannot type into the Input feilds.
var InputComponent = React.createClass({
    getInitialState : function(){
        return {telephone : ''}
    },
    handleChange : function(event){
        console.log(event.target.value);
    },
    render : function(){
        return(

                    Contact tel
                    <input id="telephone" onChange={this.handleChange} defaultValue={this.state.telephone}/>

        )
    }
})

I have tried several variations on the input element itself without any luck.

A: You need to close the update loop by setting your state in the handle change. Because react maintains its own virtual DOM, you want react to be making your DOM changes, not the standard browser.
var InputComponent = React.createClass({
   getInitialState : function(){
       return {telephone : ''}
   },
   handleChange : function(event){
       this.setState({
           telephone: event.target.value
       })
   },
   render : function(){

       return(

                Contact tel
                <input id="telephone" onChange={this.handleChange} value={this.state.telephone}/>

         )
   }
})

Also, I think you want to use the value prop, rather than defaultValue.


text:
Q: Nginx 405 Not Allowed - PHPMAILER I uploaded a website with a PHPMailer v5. It works well in localhost but when I tried it online, Nginx-405-not-allowed page shows. below is my configuration for my mail function.
  require 'vendor/phpmailer/phpmailer/PHPMailerAutoload.php';
  $mail = new PHPMailer(true);
  $mail->isSMTP();
  $mail->Host = 'smtp.gmail.com';
  $mail->SMTPAuth = true;
  $mail->Username = 'myaccount@gmail.com';
  $mail->Password = 'mypassword';
  $mail->SMTPSecure = 'tls';
  $mail->Port = 587;

A: I found my answer. The problem is in the web server provider. It seems like there are some web servers don't accept smtp.gmail.com and thus I created an email from the domain and set the host, username, password and as well as the port to what the web server provider provides. Hope you guys visit here will solve your questions.


text:
Q: If I have multiple instances of the same javascript object on a page, how can I select data from a dropdown within a specific one? So I have a widget that needs to be able to run multiple times within the same webpage. I have a dropdown with a list of names, and an Update button. Using:
updateBtn.onclick = function() {
        var selected = document.getElementById("list");
        var selectedCompany = selected.options[selected.selectedIndex].text;
        getData(selectedCompany);
}

I'm searching the whole webpage for the first instance of the 'list' drop-down box.
How can I search so I find the value of the drop-down within the same instance of the widget instead?

A: If you attach the event listener to all instances of the button, you can use this to search up the document tree to get your parent container. Since this will reffer to the button you clicked.
Or, attach a unique attribute like data-button="firstOne" data-button="secondOne" if your system allows for that.
Loose example
var selected = this.parentNode.querySelector('#list');

Let me know if I misinterpreted your question in any way.


text:
Q: Page Refresh Changes the Selected tab and shows the main tab. How can I keep the selected tab intact? I am using Atlassian Javascript framework to create tabs in my page. Every time I refresh the page it goes back to the default tab and leaves the selected tab.
I added this piece of code after searching for the same problem in stack overflow but it is not working.

This is the code I have for creating tabs:

Tab One

Tab Two

Tab three

Tab Four

Tab5

For reference you can also have a look into
http://jsfiddle.net/alok15ee/5wpmsqe5/1/

A: On the line:
$('#prod-discovery a[href="' + hash + '"]').tab('show');

isn't there a '#' missing? When extracting the href value out of the current tab using substring(1), you're removing the hash.
Try to make it work by replacing the line above with:
    $('#prod-discovery a[href="#' + hash + '"]').tab('show');

A: I needed to add
 to make sure tab state persists which uses HTML5 Local storage and also needed to remove to active-tab class.


text:
Q: Flash - how to start playing an SWF film being loaded before it is complete? I have a large SWF flash file being loaded by a parent SWF and I would like to start playing the film being loaded, let's say, when it is 50% completed. According to my expected user's bandwidth and the size of my film I will calculate the best moment to do that (the film could be 20%, 30% or 50% loaded). I want to leave users waiting the minimum and I don't need to wait until my flash is 100%.
Ok, that said, here is the problem. I am in ActionScript 3. I have one film loading another and I want to anticipate the loaded film start. I have an onProgressHandler(mProgress:ProgressEvent) function (with listener launched by ProgressEvent.PROGRESS) and I have a regular onLoadComplete(e:Event) function (with listener launched by Event.COMPLETE). I could check for 20% completed during my regular onProgressHandler. But then, when I have identified this point has been reached, how can I anticipate the launching of the film? I mean, my Event.COMPLETE handler passes the e:Event and I can use e.target to get the loaded object into my film. But what happens if I want to start that process before it is complete? I cannot pass this e:Event because the COMPLETE handler hasn't been launched yet...
One important thing to say. The film that is loading is almost empty. It is very light. The heavy film is the one being loaded and I want to attach that film being loaded to a movie clip in my film before it has completed loading. Is that possible?
I hope I have made myself clear. In case I haven't, I will try to explain further.
Any assistance will be very much appreciated. Thank you so much.

A: the progressEvent has a bytesLoaded property that you can use to decide when to start your movie.
By knowing the total bytes, and the bytes loaded, all you have to do is set a time interval to determine the user's actual download speed. Once you have all that information, you'll be able to determine if the user has downloaded enough to start the movie.
Check the adobe site for more on ProgressEvent: http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/events/ProgressEvent.html
escapetheory.com.au


text:
Q: Android streaming MSMPEG-4 V3 Video I have a camera, that streams application/x-mplayer2 type video, format : MSMPEG-4 V3 Video. When I try to open stream with android, it trows an error : "Sorry, this video cannot be played.". I try to stream with this:
private void playVideo() {
            try {
                final String path = "http://82.140.132.217:8001";
                System.out.println("path --> "+path);
                Log.v(TAG, "path: " + path);
                if (path == null || path.length() == 0) {
                    Toast.makeText(MainActivity.this, "File URL/path is empty",
                            Toast.LENGTH_LONG).show();

                } else {
                    // If the path has not changed, just start the media player
                    if (path.equals(current) && mVideoView != null) {
                        mVideoView.start();
                        mVideoView.requestFocus();
                        return;
                    }
                    current = path;
                    System.out.println("Current path --> "+path);
                    mVideoView.setVideoPath(getDataSource(path));
                    mVideoView.start();
                    mVideoView.requestFocus();

                    System.out.println("end try in play");

                }
            } catch (Exception e) {
                Log.e(TAG, "error: " + e.getMessage(), e);
                if (mVideoView != null) {
                    mVideoView.stopPlayback();
                }
            }
        }

How can I stream this type of video? Or is there any way to convert video stream to another type?
Thanks!

A: application/x-mplayer2 is not a video format , here is the list http://developer.android.com/guide/appendix/media-formats.html of video formats and streams supported by android.
Once you knew actual format and stream type of your camera , if it is not in compatible format you can use FFMPEG to convert that stream.


text:
Q: Is there server based html5 widget that will allow me to stream pulseaudio audio to a browser? I have a Web based VPN running at home that I access from work and Pandora works pretty well since it's all HTML5, but other sites like Youtube and flash based media does not work since my VPN can't repackage and proxy flash.
I have a java based VNC viewer that lets me work on my desktop from home which is wrapped in my VPN's SSL, however I cannot hear anything playing on my computer since VNC does not wrap sound, at least not with my java viewer. My idea to pipe pulse audio from my Linux desktop to my linux web server and run a widget that any HTML5 compatible browser could stream live/slightly delayed audio.
I'm just not sure what to look for to get this working if it's at all possible


text:
Q: Netplan Configuration ens4:
        dhcp4: false
        addresses: [192.168.8.4/24]
        nameservers:
            addresses: [1.1.1.1,8.8.8.8]
        set-name: ens4
        match:
            macaddress: xx:xx:xx:xx:xx:xx

I read a few guides and most of them had /24 as the allocation. I tried putting /32 and im not clear on why /24 works and /32 doesn't? In ubuntu 16.04 I only have to put the single address.

A: Before (with /etc/network/interfaces) you had to put the netmask as a separate entry. With netplan they decided to merge the IP address and netmask value into one, so you have to specify the netmask as part of the IP address. Putting /24 would correspond to a netmask value of 255.255.255.0. Putting /32 would not make sense as it would reduce the size of the network to just the address itself.
You can read more about this here: Ubuntu 17.10 Server static IP netplan - how to set netmask


text:
Q: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'jaxws:inInterceptors' I'm using Maven in Java EE Luna and trying to fix the error in my beans.xml before I do the Maven install to build and test the web service that I built. There is an error at my code which says "cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'jaxws:inInterceptors'". The exact line with the error is the following in my beans.xml file:
<jaxws:inInterceptors>

I tried googling online and the suggestion was to add the dependency related jawxs to my pom.xml file, but it didn't work so I'm wondering what is wrong with my xml code..
This is the code in my beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:jaxws="http://cxf.apache.org/jaxws"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

        <import resource="classpath:META-INF/cxf/cxf.xml" />

        <!-- Spring's component scan for identifying beans to be managed by the container. -->
        <context:component-scan base-package="au.edu.unsw.soacourse.addressing"/>

        <jaxws:endpoint
          id="GNAFAddressingService"
          implementor="au.edu.unsw.soacourse.addressing.GNAFAddressingService"
          address="/GNAFAddressingServiceImpl" />

          <jaxws:inInterceptors>
            <ref bean="GNAFAddressingServiceSOAPInterceptor" />
          </jaxws:inInterceptors>

        <bean id="GNAFAddressingServiceSOAPInterceptor" class="au.edu.unsw.soacourse.addressing.GNAFAddressingServiceSOAPInterceptor" />

</beans>

This is the code in my pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>au.edu.unsw.soacourse</groupId>
    <artifactId>GNAFAddressingService</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Simple CXF Java-first SOAP project using Spring configuration</name>
    <description>Simple CXF Java-first SOAP project using Spring configuration</description>
    <dependencies>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-bindings-soap</artifactId>
            <version>${cxf.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-rs-extension-providers</artifactId>
            <version>${cxf.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.8.11.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.0.5</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>3.0.5</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <!-- comp9322: adding a Maven plug-in from Apache CXF
        for code generation (cxf-codegen-plugin). This plug-in
        runs WSDL2Java which is the actual tool that generates
        code from WSDL. This plug-in will run as a new goal
        'generate-sources', which means you can also execute it
        using 'mvn generate-sources' in the command line, or from
        Run As -> Maven -> mvn generate-sources.
        -->
        <plugins>
            <plugin>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-codegen-plugin</artifactId>
                <version>3.0.4</version>
                <executions>
                  <execution>
                    <id>generate-sources</id>
                    <phase>generate-sources</phase>
                  <configuration>
                      <sourceRoot>src/main/java-generated</sourceRoot>
                      <wsdlOptions>
                          <wsdlOption>
                              <wsdl>${basedir}/src/main/resources/wsdl/GNAFAddressingService.wsdl</wsdl>
                          </wsdlOption>
                      </wsdlOptions>
                  </configuration>
                  <goals>
                      <goal>wsdl2java</goal>
                  </goals>
                  </execution>
                </executions>
            </plugin>
        </plugins>

        <pluginManagement>
            <plugins>
                <plugin>
                    <!-- mvn clean install tomcat:run-war to deploy
                    Look for "Running war on http://xxx" and
                    "Setting the server's publish address to be /yyy"
                    in console output; WSDL browser address will be
                    concatenation of the two: http://xxx/yyy?wsdl
                    -->
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.0</version>
                    <executions>
                        <execution>
                            <id>start-tomcat</id>
                            <goals>
                                <goal>run-war</goal>
                            </goals>
                            <phase>pre-integration-test</phase>
                            <configuration>
                                <port>${test.server.port}</port>
                                <path>/webservice</path>
                                <fork>true</fork>
                                <useSeparateTomcatClassLoader>true</useSeparateTomcatClassLoader>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <!-- comp9322: maven-compiler-plugin part
                        referencing JDK 1.7 instead of default 1.6
                        -->
                        <source>1.7</source>
                        <target>1.7</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-eclipse-plugin</artifactId>
                    <configuration>
                        <projectNameTemplate>[artifactId]-[version]</projectNameTemplate>
                        <wtpmanifest>true</wtpmanifest>
                        <wtpapplicationxml>true</wtpapplicationxml>
                        <wtpversion>2.0</wtpversion>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

</project>

A: In your code there is space and a new line after xsi:schemaLocation=". Try to remove it and bring the first value on the same line.
Change
xsi:schemaLocation="
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd

To this:
xsi:schemaLocation="http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd

A: The <jaxws:inInterceptors> node must be inside to the <jaxws:endpoint> node.
Example:
<jaxws:endpoint
          id="GNAFAddressingService"
          implementor="au.edu.unsw.soacourse.addressing.GNAFAddressingService"
          address="/GNAFAddressingServiceImpl">

          <jaxws:inInterceptors>
            <ref bean="GNAFAddressingServiceSOAPInterceptor" />
          </jaxws:inInterceptors>

        <bean id="GNAFAddressingServiceSOAPInterceptor" class="au.edu.unsw.soacourse.addressing.GNAFAddressingServiceSOAPInterceptor" />
<jaxws:endpoint>


text:
Q: Remove child throws exception This code throw me a strange exception. Node "" was not found in the collection but when I check the outerHTML of span its National Cheng Kung University. Why it try to remove different span?
doc = web.Load(urlTeams);

foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//tr[contains(@id,'Cell')]"))
{
    HtmlNode span = node.SelectSingleNode(".//span");
    lbResults2.Items.Add(span.InnerText);
    lbResults.Items.Add(node.RemoveChild(span).InnerText.Trim());
}

A: Since you're getting all spans recursively under the current node (that's what // means in XPATH), you may get a span that is not a child of node, but a grand child.
In this case the call node.RemoveChild(span) will fail as you see. What you want to do instead is span.ParentNode.RemoveChild(span).


text:
Q: update part of a value of a json object using JQ Have a value inside a JSON object with a variable that needs to be updated using JQ, below is my son file and jq command I'm using to update accountid in json file
{"bucketname":"test/$accountid/123","objectname":"test/$accountid/123","targetlocation":"$TARGET_LOCATION"}

JQ Command
jq 'map(.$accountid = "123")' myjson.json

Error
jq: error (at myjson.json:1): Cannot index string with string "$accountid"

I'm I missing something here?

A: From the comments, it would appear you should be using map_values and perhaps something like sub. Consider therefore this example:
echo '{"bucketname":"test/$accountid/123","objectname":"test/$accountid/123","targetlocation":"$TARGET_LOCATION"}' |
 jq 'map_values( sub("[$]accountid";"123") )'

produces:
{
  "bucketname": "test/123/123",
  "objectname": "test/123/123",
  "targetlocation": "$TARGET_LOCATION"
}

Sharpening
You might want to sharpen the criteria for substituion, e.g.
sub("[$]accountid(?<tail>(/|$))"; "123\(.tail)" )


text:
Q: Excel VBA Macro to refresh UDF's without making them Volatile I have a bunch of different UDF in my spreadsheet (Which are not volatile), I'm wonder if it is possible to have another UDF that's called "Refresh" which will refresh all UDF used on the sheet?
I don't wish to make any of my UDF volitle due to the amount of data involved but having a button that can refresh them would solve my issue, any help/code would be appreciated.
Here is the UDF:
Function HexCode(cell As Range) As String
     HexCode = Right("000000" & Hex(cell.Interior.Color), 6)
End Function

A: Identify the cells containing your UDF and recalculate them? That's easy: just use the RefreshUDF() macro below.
Refresh those cells from a function, recalculated on the sheet as part of the sheet's 'calculation tree'?  Verboten!
I've coded RefreshUDF as a subroutine because Excel won't let you do that: functions in cells cannot change other cells' values by any method other than passing the cell's own value into the dependency chain of the calculation tree.
...Except that you can capture the WorksheetChange() event and use it to read a target cell and run RefreshUDF. Take care with that, you might find it runs repeatedly (or, worse, that there's a loop) if you're changing a 'precedent' cell feeding values into the target cell.
The code below will be slow: there are several optimisations available, starting with setting calculation to manual, so that each cell refresh doesn't recalculate the entire sheet;  but it'll get you started:

Public Sub RefreshUDF(UDFname as string, Optional wsh as Excel.Worksheet)
Dim myCell As Excel.Range
If wsh Is Nothing Then
    Set wsh = ActiveSheet
End If
For Each myCell In wsh.UsedRange
    If IsError(myCell) Then
        ' No action
    Else
        If Instr(1, myCell.Formula, UDFname & "(", vbTextCompare) Then
            myCell.Calculate
        End If
    End If
Next myCell
End Sub

Obvious points:

Firstly, you might have another function that has a very similar name - 'ExtendedHexCode' instead of 'HexCode' - and this function will recalculate them both.
Secondly, this won't handle merged cells and array formulae well.
Thirdly, if you really are interested in the interior colour of the cell, you might be surprised to hear that this property is unchanged by conditional formatting - the cell changes colour, but the Format Condition's displayed colour isn't the same property as Interior.Color.
Also: I have to ask - have you looked up Application.Volatile = False ?  That should be the first line of your function... And you might find that cells with conditional formatting are volatile, no matter what you do.


text:
Q: Webkit: Resize div and elements within div, according to window size I have div element that contains text which I am trying to resize while scaling the interior text with it.
The webkit-transform: scale( blah, blah ) CSS property is great for scaling the div by  specific factor, but I need it to scale proportional to the window size.
Anyone know any ways to do this?

A: You can use percents? And make a proportion if you need to.


text:
Q: How to use \eqalignno properly? I'm trying to use the following aligned equations, but It does not work and gives bunch of error. This is my first time trying to use this command so kind of struggling to make it right. I could find what is wrong with it.
\eqalignno{\min_{V} \quad & V^{H}C_{0}V & \hbox{(6a)} \cr
         {\rm s.t}.\quad &\underline{p}_{j}\leq V^{H}\Phi_{j}^{\phi}V\leq\bar{p}_{j},\quad j\in N, \phi \in\Phi&\hbox{(6b)}\cr
         & \underline{q}_{j}\leq V^{H}\Psi_{j}^{\phi}V\leq\bar{q}_{j},\quad j\in N,\phi\in\Phi&\hbox{(6c)}\cr
         & \underline{v}_{j}\leq V^{H}E_{j}^{\phi}V\leq\bar{v}_{j},\quad j\in N, \phi\in\Phi&\hbox{(6d)}}

A: It seems what this command  achieves can be obtained by align nested in a subequations environment. Maybe you'd be interested in grouping the three constraints as a single subequation:
\documentclass{article}
\usepackage{mathtools}

\begin{document}

\setcounter{equation}{5}
\begin{subequations}
  \begin{align}
    \min_{V} \quad & V^{H}C_{0}V \\
  \textrm{s.t. } \quad &\underline{p}_{j}\leq V^{H}\Phi_{j}^{\phi}V\leq\bar{p}_{j},\quad j\in N, \phi \in\Phi \\
         & \underline{q}_{j}\leq V^{H}\Psi_{j}^{\phi}V\leq\bar{q}_{j},\quad j\in N,\phi\in\Phi \\
         & \underline{v}_{j}\leq V^{H}E_{j}^{\phi}V\leq\bar{v}_{j},\quad j\in N, \phi\in\Phi
  \end{align}
\end{subequations}

\begin{subequations}
  \begin{alignat}{2}
   & \min_{V } \quad V^{H}C_{0}V \\
 & \begin{rcases}
  \textrm{s.t. } &\underline{p}_{j}\leq V^{H}\Phi_{j}^{\phi}V\leq\bar{p}_{j},\quad j\in N, \phi \in\Phi \\
         & \underline{q}_{j}\leq V^{H}\Psi_{j}^{\phi}V\leq\bar{q}_{j},\quad j\in N,\phi\in\Phi \\
         & \underline{v}_{j}\leq V^{H}E_{j}^{\phi}V\leq\bar{v}_{j},\quad j\in N, \phi\in\Phi
\end{rcases}
  \end{alignat}
\end{subequations}

 \end{document}


text:
Q: MacBook Pro shuts down when unplugged I have a late 2008 MacBook Pro work computer. Here's the sequence of events:

*

*I fully charge the battery

*I unplug the Mac from the power cable

*The Mac immediately shuts down

Before unplugging the Mac, I press the battery power indicator button and all lights are green. When I unplug the Mac I press the indicator button again and only one light is green.
I've tried resetting the PRAM, SMC and even bought a new battery but the problem persists. Here is the System Information.
How can I get my MacBook Pro to stay powered on when not plugged in?
Update: It was a dead battery. Apple gave me a new one for free.

A: Looks like your battery is dead. Your system report states that:
37.   Condition:    Service Battery
Time to either stay plugged to power, or get a new battery.

A: If you bought a new battery, and that didn't fix the issue then I would say it is a short in the logic board. If it is still under Apple Care, I'd take it into a store, or call 1(800)MY-APPLE to get it checked out, and serviced.

A: This is really anormal. Have Apple repair your Mac.


text:
Q: Continuous dynamical system bifurcation diagram help!$\dot{x} = x [r -(1 - x^2)] [r - (2x^3 - 2x)]$ So in dynamical system class, I ran into this equation.

$\dot{x} =  x [r -(1 - x^2)] [r - (2x^3 - 2x)]$

How can one possibly sketch the bifurcation diagram and locate and identify all bifurcations in this family?
I know if I solve $0 = x [r -(1 - x^2)] [r - (2x^3 - 2x)]$
 I can find some of the fixed (equilibrium) points for this family. There is one at $x = 0$, $x = \pm\sqrt{1-r}$, and there should be a few more. But I don't even know how to start to sketch a bifurcation diagram for this family!  Please help!

A:
Not sure if this is what you are looking for but this is a plot of the equilibrium solutions $x$ as functions of $r$. We can see from the graph that the number of equilibria changes moving from left to right from 4 to 5 to 6 to 3(on the $x$ axis) to 6 to 5 to 4 and then finally 2 for $r\geq1$. The Mathematica code I used is:
sol1 = Solve[x^2 + r - 1 == 0, x];
sol2 = Solve[2 x^3 - 2 x - r == 0, x];
Plot[{0, sol1[[1, 1, 2]], sol1[[2, 1, 2]], sol2[[1, 1, 2]],
  sol2[[2, 1, 2]], sol2[[3, 1, 2]]}, {r, -5, 5}]


text:
Q: Firebase - Thread 1: signal SIGABRT | FIRApp.configure() | Swift 4
I want to use Firebase, I installed it to my project, but when I write FIRApp.configure() in AppDelegate.swift, I'm getting Thread 1: signal SIGABRT. How can I solve this problem? I'm using Swift 4 with Xcode 9.

A: Update cocoapods and re install Podfile.
Change:
FIRApp.configure() -> FirebaseApp.configure()
Also change language settings from Swift 4 -> Swift 3.2
That worked for me.
Let me know if it works.

A: I've been pulling my hair for 2 days...
here is what I found

*

*make sure you have the right GoogleService-info.plist file

*enable the .plist file point to your target app


text:
Q: Ruby on Rails "bin/rails routes" and "bin/rails server" not working Recently started learning Ruby on Rails to build up a web API, code with VS code, following the youtube video: https://www.youtube.com/watch?v=6KqbPJtA5O8&list=PLbTv9eGiI03u1-JFkFpPGsR_hMre6WX3e
After installing everything, create a project with rails new apiproject --api
And the next step is to check the routes with bin/rails routes and got the error
Error: Command 'routes' not recognized
Did you mean: `$ rake routes` ?

Usage: rails COMMAND [ARGS]

The most common rails commands are:
 generate    Generate new code (short-cut alias: "g")
 console     Start the Rails console (short-cut alias: "c")
 server      Start the Rails server (short-cut alias: "s")
 dbconsole   Start a console for the database specified in config/database.yml
             (short-cut alias: "db")
 new         Create a new Rails application. "rails new my_app" creates a
             new application called MyApp in "./my_app"

In addition to those, there are:
 destroy      Undo code generated with "generate" (short-cut alias: "d")
 plugin new   Generates skeleton for developing a Rails plugin
 runner       Run a piece of code in the application environment (short-cut alias: "r")

All commands can be run with -h (or --help) for more information.

In the video, it supposed to return

I have tried rake route but the result is not what I expected as in the video.
After that, I tried to start the server first with bin/rails server, and I keep getting the error:
/Users/jolin/.rvm/gems/ruby-2.7.0/gems/activesupport-4.2.2/lib/active_support/core_ext/object/duplicable.rb:85: warning: BigDecimal.new is deprecated; use BigDecimal() method instead.
=> Booting WEBrick
=> Rails 4.2.2 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
/Users/jolin/.rvm/gems/ruby-2.7.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Fixnum is deprecated
/Users/jolin/.rvm/gems/ruby-2.7.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Bignum is deprecated
Exiting
Traceback (most recent call last):
        9377: from bin/rails:3:in `<main>'
        9376: from bin/rails:3:in `load'
        9375: from /Users/jolin/Desktop/RoR/liborapi/bin/spring:15:in `<top (required)>'
        9374: from /Users/jolin/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/rubygems/core_ext/kernel_require.rb:72:in `require'
        9373: from /Users/jolin/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/rubygems/core_ext/kernel_require.rb:72:in `require'
        9372: from /Users/jolin/.rvm/gems/ruby-2.7.0/gems/spring-4.1.0/lib/spring/binstub.rb:11:in `<top (required)>'
        9371: from /Users/jolin/.rvm/gems/ruby-2.7.0/gems/spring-4.1.0/lib/spring/binstub.rb:11:in `load'
        9370: from /Users/jolin/.rvm/gems/ruby-2.7.0/gems/spring-4.1.0/bin/spring:49:in `<top (required)>'
         ... 9365 levels...
           4: from /Users/jolin/.rvm/gems/ruby-2.7.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>'
           3: from /Users/jolin/.rvm/gems/ruby-2.7.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>'
           2: from /Users/jolin/.rvm/gems/ruby-2.7.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>'
           1: from /Users/jolin/.rvm/gems/ruby-2.7.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>'
/Users/jolin/.rvm/gems/ruby-2.7.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>': stack level too deep (SystemStackError)

I previous got undefined method <class:BigDecimal> error, but after add gem 'bigdecimal', '1.4.2' to Gemfile, it resolved, but I couldn't find a way to solve this issue.
I have so struggled even in the very first step, I have tried to upgrade/downgrade my Ruby and Rails in a different versions...
My current versions:
Ruby: ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-darwin19]
Rails: Rails 4.2.2
(But with rails -v, I always got Deprecation warning: Expected string default value for '--rc'; got false (boolean).
This will be rejected in the future unless you explicitly pass the options check_default_type: false or call allow_incompatible_default_type! in your code
You can silence deprecations warning by setting the environment variable THOR_SILENCE_DEPRECATION.)
rvm: rvm 1.29.12 (latest) by Michal Papis, Piotr Kuczynski, Wayne E. Seguin [https://rvm.io]
gem: 3.1.2
Update
After trying upgrade ruby, downgrade ruby, downgrade rails
I am now keeping getting error as below while I run bin/rails server:
Traceback (most recent call last):
        4: from bin/rails:3:in `<main>'
        3: from bin/rails:3:in `load'
        2: from /Users/jolin/Desktop/RoR/liborapi/bin/spring:10:in `<top (required)>'
        1: from /Users/jolin/Desktop/RoR/liborapi/bin/spring:10:in `read'
/Users/jolin/Desktop/RoR/liborapi/bin/spring:10:in `read': No such file or directory @ rb_sysopen - /Users/jolin/Desktop/RoR/liborapi/Gemfile.lock (Errno::ENOENT)

A: I would recommend running it in Ruby 2.5.3 as in the screen shot. I don't think Rails 4.2 is tested or supported in ruby 2.7. You could also try installing the later version of ruby 2.7.6.
Current version of rails is 7.0.x, and Ruby 3.1.x.
Segmentation fault is usually a result of Ruby installation, you can try installing ruby 2.7.6 and try again.

A: The rails routes command was introduced with Ruby on Rails 5.0. In versions prior 5.0 it was called rake routes.
This means because of the old version of Rails you are using you can simply call rake routes and get the same response.
But it is worth noting that the youtube video you are following is about Ruby on Rails 6.0. But you are using Ruby on Rails 4.2.2. Your local environment is 2 major versions and more than 4 years behind. You will very likely face more compatibility issues when you continue working with such an ancient and unmaintained version of Ruby on Rails.
I suggest that you upgrade your local environment to at least Ruby 2.7 and Ruby on Rails 6.2 or even better Ruby 3.1 and Ruby on Rails 7.0. There is no benefit in learning Rails is outdated and unmaintained versions.

A: Hi I got the same issue
Don't use bin/rails routes command
just use rails routes
This will solve your problem just let me know whether this work or not for you


text:
Q: Collinearity of points Let ABC be an arbitrary triangle, and P, Q, R be the intersections of the tangent lines to circumcicles at the vertices with the extensions of respective opposite sides. Show that P, Q, R are colinears.

Here is an interactive applet, thanks to Geogebra's amazing super-powers.

A: This is a special case of Pascal's hexagon theorem in which the six points are in fact only three (and the segment «from one point to itself» is the tangent to the conic)


text:
Q: how to compare two data frames based in difference in date I have two data frames, each has #id column and date column,
I want to find rows in both Data frames that have same id with a date difference more than > 2 days

A: Normally it's helpful to include a datafrme so that the responder doesn't need to create it. :)
import pandas as pd
from datetime import timedelta

Create two dataframes:
df1 = pd.DataFrame(data={"id":[0,1,2,3,4], "date":["2019-01-01","2019-01-03","2019-01-05","2019-01-07","2019-01-09"]})
df1["date"] = pd.to_datetime(df1["date"])

df2 = pd.DataFrame(data={"id":[0,1,2,8,4], "date":["2019-01-02","2019-01-06","2019-01-09","2019-01-07","2019-01-10"]})
df2["date"] = pd.to_datetime(df2["date"])

They will look like this:
DF1
   id       date
0   0 2019-01-01
1   1 2019-01-03
2   2 2019-01-05
3   3 2019-01-07
4   4 2019-01-09

DF2
   id       date
0   0 2019-01-02
1   1 2019-01-06
2   2 2019-01-09
3   8 2019-01-07
4   4 2019-01-10

Merge the two dataframes on 'id' columns:
df_result = df1.merge(df2, on="id")

Resulting in:
   id     date_x     date_y
0   0 2019-01-01 2019-01-02
1   1 2019-01-03 2019-01-06
2   2 2019-01-05 2019-01-09
3   4 2019-01-09 2019-01-10

Then subtract the two day columns and filter for greater than two.
df_result[(df_result["date_y"] - df_result["date_x"]) > timedelta(days=2)]

   id     date_x     date_y
1   1 2019-01-03 2019-01-06
2   2 2019-01-05 2019-01-09


text:
Q: How to make sure that the following recursive function is resolved or completed and then do some operations? i made a recursive function which will get the file details from a share point document library recursively but unable to know whether the recursive function is resolved or completed
 //function definition
        getFiles = function getFiles(folderUrl) {
                    var deferred = $.Deferred();
                    try {
                        $pnp.sp.web.getFolderByServerRelativeUrl(folderUrl).expand("Folders, Files").get().then(function (r) {
                            r.Folders.forEach(function (item) {
    //recursive call
     getFiles(item.ServerRelativeUrl);
                            });
                            r.Files.forEach(function (item) {
                                console.log(item.ServerRelativeUrl);
                                allfilesrecursive.push(item);
                            });
                            deferred.resolve(allfilesrecursive);
                        }).catch(function (err) {
                            Errorlog(JSON.stringify(err), 'getFiles catch', 'TestFileUpload.js', fileuploaddetails.currentBrowserURL);
                            deferred.reject();
                        });

                    } catch (err) {
                        Errorlog(JSON.stringify(err), 'getFiles', 'TestFileUpload.js', fileuploaddetails.currentBrowserURL);
                        deferred.reject();
                    }
                    return deferred.promise();
                }


text:
Q: this void function is not working ;( #include <stdio.h>

void fun();

void main()
{
    int i;
    for (i=0; i<0; i++) fun();
}

void fun()
{
    static int cnt = 0;
    cnt++;
    printf("count is %d\n", cnt);
}

and this merely prints blank ;(
What's wrong with my code?
I debugged and it showed no bugs here.

A: Your for loop is wrong. It will only loop if i is less than 0 but since i is 0 it never does.
A way to fix it would be changing the upper bound of the loop like:
for (i=0; i<20; i++) fun(); // Calls fun 20 times

A: You are running your loop with the condition
i < 0

i is initialized as 0. So it is never less than 0.
Change this to:
    for (i=0; i<10; i++) fun();

And it should run 10 times.

A: the problem is at for (i=0; i<0; i++) fun(); i<0 means that the loop exits when i<0 is false. So, the code just exits without executing the fun()


text:
Q: Как создать словарь, с вложенным словарем и сортировкой по дате на Python (3.9.6) У меня есть список вывода логов биометрического контроля из текстового файла. Данные логи контроллера были отформатированы, и занесены как список. Данные значения уже до этого отсортированы, в список "заходит" первое событие, и последнее. В формате:
monitor_last_first = [
    ['Ваня', '8:33', '01.01.1995'],
    ['Ваня', '18:40', '01.01.1995'],
    ['Петя', '9:42', '01.01.1995'],
    ['Петя', '21:51', '01.01.1995'],
    ['Петя', '9:02', '02.01.1995'],
    ['Петя', '18:51', '02.01.1995'],
    ['Женя', '10:01', '01.01.1995'],
    ['Женя', '20:51', '01.01.1995'],

]

Мне необходимо создать словарь, с вложенным словарем. Значения для данного словаря должны браться из данного списка, а именно имя, и дата. После чего сортироваться, дабы в итоговом словаре было имя того кто пришел/ушел, и все его приходы/уходы, с привязкой по дате. В формате:
monitor_dict = {
    {'Ваня': {'01.01.1995': ['08:33', '18:40']}},
    {'Петя': {'01.01.1995': ['09:42', '21:51']}, {'02.01.1995': ['09:02', '18:51']},
    ['Женя': {'01.01.1995': ['10:01', '20:51']},

}

Проект домашний, не учебный/рабочий. По этому определенный алгоритм решения не нужен. Скорость тоже не играет сути, будет это выполняться 5 мкс, или 10 секунд не особо важно, так как скрипт запускается раз в месяц. Буду очень благодарен за хотя-бы наводку по решению, уже гуглил довольно много, решения не нашел.

A: Нужно просто налету сгенерировать словарь из словарей, состоящих из списка:
monitor_last_first = [
    ['Ваня', '8:33', '01.01.1995'],
    ['Ваня', '18:40', '01.01.1995'],
    ['Петя', '9:42', '01.01.1995'],
    ['Петя', '21:51', '01.01.1995'],
    ['Петя', '9:02', '02.01.1995'],
    ['Петя', '18:51', '02.01.1995'],
    ['Женя', '10:01', '01.01.1995'],
    ['Женя', '20:51', '01.01.1995'],
]

monitor_dict = dict()
for name, time, date in monitor_last_first:
    if name not in monitor_dict:
        monitor_dict[name] = dict()

    if date not in monitor_dict[name]:
        monitor_dict[name][date] = []

    monitor_dict[name][date].append(time)

Тот же код, что выше, но через defaultdict:
from collections import defaultdict

...

monitor_dict = defaultdict(lambda: defaultdict(list))
for name, time, date in monitor_last_first:
    monitor_dict[name][date].append(time)

Проверяем:
print(monitor_dict)

import json
print(json.dumps(monitor_dict, indent=4, ensure_ascii=False))

Результат:
{'Ваня': {'01.01.1995': ['8:33', '18:40']}, 'Петя': {'01.01.1995': ['9:42', '21:51'], '02.01.1995': ['9:02', '18:51']}, 'Женя': {'01.01.1995': ['10:01', '20:51']}}
{
    "Ваня": {
        "01.01.1995": [
            "8:33",
            "18:40"
        ]
    },
    "Петя": {
        "01.01.1995": [
            "9:42",
            "21:51"
        ],
        "02.01.1995": [
            "9:02",
            "18:51"
        ]
    },
    "Женя": {
        "01.01.1995": [
            "10:01",
            "20:51"
        ]
    }
}

PS.
Если нужно, что время добавлялось с лидирующим 0, то можно добавить в цикл строку:
time = time.zfill(5)

A: Решение в одну строчку, если не считать импортов... :)
from itertools import groupby
from operator import itemgetter

monitor_dict = dict([person, dict([date, list(map(itemgetter(1), times))] for date, times in groupby(visits, itemgetter(2)))] for person, visits in groupby(monitor_last_first, itemgetter(0)))


text:
Q: forzar una condición palabra exacta en mysql Tengo esta tabla con un campo llamado nombre y marca_temp
Los nombre de los registros pueden ser:
IMPRESORA HP XXXXX
IMPRESORA MP YYYYY
IMPRESORA AMP ZZZZZ
MP IMPRESORA RRRRR
IMPRESORA 3500 MP
IMPRESORA 5200 HP

Y tengo este update que busca dentro del nombre una palabra y la establece en el campo marca_temp
tep_db_query("update " . TABLE . " set marca_temp = 'MP' where nombre like '%MP%' and marca_temp = '' ");

tep_db_query("update " . TABLE . " set marca_temp = 'HP' where nombre like '%HP%' and marca_temp = '' ");

tep_db_query("update " . TABLE . " set marca_temp = 'AMP' where nombre like '%AMP%' and marca_temp = '' ");

Pero tengo un problema, necesito que la palabra en la consulta sea EXACTA ya que por ejemplo todas contienen MP por la palabra IMPRESORA y me establece en la marca_temp todas en MP
¿Como hago para que el campo sea la palabra exacta y completa?

A: Podrías utilizar REGEXP y marcadores de límite de palabras ([[:<:]] y [[:>:]])
Ejemplo:
UPDATE $table
  SET marca_temp = '$word'
  WHERE nombre REGEXP '[[:<:]]$word[[:>:]]'
    AND marca_temp = ''

Nota: reemplazar $table y $word
Demo

Aplicado a tu código:
$word = 'MP';
$table = TABLE;
tep_db_query("update $table set marca_temp = '$word' where nombre REGEXP '[[:<:]]$word[[:>:]]' and marca_temp = ''");

A: Los % dentro de tu clausula LIKE a ambos extremos de la palabra a buscar significa que te va a buscar la igualdad independientemente de donde esta se produzca.
Aprovechándote de ello podrías hacer algo como:
tep_db_query("update " . TABLE . " set marca_temp = 'MP' where nombre like '% MP %' and marca_temp = '' ");

tep_db_query("update " . TABLE . " set marca_temp = 'HP' where nombre like '% HP %' and marca_temp = '' ");

tep_db_query("update " . TABLE . " set marca_temp = 'AMP' where nombre like '% AMP %' and marca_temp = '' ");

Al añadir el espacio delante y detrás de la igualdad deberías conseguir que el update solamente se produzca cuando la palabra buscada es la que aparece en el medio de tu campo nombre.


text:
Q: re-render GoogleMapReact Hi I am creating nextjs Application in which I have used GoogleMapReact from google-map-react library,I want to re-render my GoogleMapReact component according to the new prop
here is my map.js file
import GoogleMapReact from 'google-map-react'
import { AsYouType } from 'libphonenumber-js'
import React, { useState, useEffect } from 'react';

const phoneFormat = new AsYouType('US')
const Marker = props => `

          ${props.city}

${props.street}

        ${props.city}, ${props.stateIso}, ${props.countryIso}, ${props.postalCode}

        Phone: ${phoneFormat.input(props.phone)}

        Directions

`
// Map component should always take in array of LocationSummary object
// ToDo: setting prop types.
export default function Map(props) {
  const defaultProps = {
    center: {
    lat: (typeof(props.latitude) === "undefined" ? 37.0902 : props.latitude),
    lng: (typeof(props.longitude) === "undefined" ? 95.7129: props.longitude),
    },
    zoom: 5
  }

  function handleApiLoaded(map){
    let infowindow = new google.maps.InfoWindow()
    props.locations.map((location) => {
      let marker = new google.maps.Marker({position: {lat: parseFloat(location.latitude), lng: parseFloat(location.longitude)}, map: map, title: location.name})
      marker.addListener('click', function() {
        infowindow.close()
        infowindow.setContent(Marker(location))
        infowindow.open(map, marker)
      })
    })
  }
  return (

      <GoogleMapReact
        bootstrapURLKeys={{ key: '123' }}
        center={defaultProps.center}
        defaultZoom={defaultProps.zoom}
        yesIWantToUseGoogleMapApiInternals
        onGoogleApiLoaded={({ map }) => handleApiLoaded(map)}
      />

  )
}

Here prop.locations has the updated array result , but the issue is its not getting refreshed in my map , Can anyone suggest me how can I do this so that my map will re render on data change??

A: You're using onGoogleApiLoaded in a wrong way.
By looking into the source code you can see that onGoogleApiLoaded is never called twice:
if (!this_.googleApiLoadedCalled_) {
    this_._onGoogleApiLoaded({ map, maps, ref: this_.googleMapDom_ });
    this_.googleApiLoadedCalled_ = true;
}

You're using react google map component in a wrong way. It should be like this one:
<GoogleMapReact
    bootstrapURLKeys={{ key: '123' }}
    center={defaultProps.center}
    defaultZoom={defaultProps.zoom}
>
    { props.locations.map(location => (
        <Marker
            lat={location.lat}
            lng={location.lng}
        />
    )) }
</GoogleMapReact>

For marker and info window, please look at the example


text:
Q: Some readble content, but impossible to JSON dump to file This text file (30 bytes only, the content is '(Ne pas r\xe9pondre a ce message)') can be opened and inserted in a dict successfully :
import json

d = {}

with open('temp.txt', 'r') as f:
   d['blah'] = f.read()

with open('test.txt', 'w') as f:
    data = json.dumps(d)
    f.write(data)

But it is impossible to dump the dict into a JSON file (see traceback below). Why?
I tried lots of solutions provided by various SO questions. The closest solution I could get was this answer. When using this, I can dump to file, but then the JSON file looks like this:
# test.txt
{"blah": "(Ne pas r\u00e9pondre a ce message)"}

instead of
# test.txt
{"blah": "(Ne pas répondre a ce message)"}

Traceback:
  File "C:\Python27\lib\json\encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 9: invalid continuation byte
[Finished in 0.1s with exit code 1]

A: Your file is not UTF-8 encoded. It uses a Latin codec, like ISO-8859-1 or Windows Codepage 1252. Reading the file gives you the encoded text.
JSON however requires Unicode text. Python 2 has a separate Unicode type, and byte strings (type str) need to be decoded using a suitable codec. The json.dumps() function uses UTF-8 by default; UTF-8 is a widely used codec for encoding Unicode text data that can handle all codepoints in the standard, and is also the default codec for JSON strings to use (JSON requires documents to be encoding in one of 3 UTF codecs).
You need to either decode the string manually or tell json.dumps() what codec to use for the byte string:
data = json.dumps(d, encoding='latin1')  # applies to all bytestrings in d

or
d['blah'] = d['blah'].decode('latin1')
data = json.dumps(d)

or using io.open() to decode as you read:
import io

with io.open('test.txt', 'w', encoding='latin1') as f:
    d['blah'] = f.read()

By default, the json library produces ASCII-safe JSON output by using the \uhhhh escape syntax the JSON standard allows for. This is entirely normal, the output is valid JSON and readable by any compliant JSON decoder.
If you must produce UTF-8 encoded output without the \uhhhh escape sequences, see Saving utf-8 texts in json.dumps as UTF8, not as \u escape sequence


text:
Q: How to get bean using application context in spring boot I am developing a SpringBoot project and I want to get the bean by its name using applicationContext. I have tried many solution from web but could not succeed. My Requirement is that I have a controller
ControllerA

and inside the controller I have a method getBean(String className). I want to get instance of registered bean. I have hibernate entities and I want to get an instance of the bean by passing the name of class only in getBean method.
Please help if someone know the solution.

A: You can use ApplicationContextAware.

ApplicationContextAware:
Interface to be implemented by any object that wishes to be notified
of the ApplicationContext that it runs in. Implementing this interface
makes sense for example when an object requires access to a set of
collaborating beans.

There are a few methods for obtaining a reference to the application context. You can implement ApplicationContextAware as in the following example:
package hello;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

@Component
public class ApplicationContextProvider implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

 public ApplicationContext getContext() {
        return applicationContext;
    }

}

Update:
When Spring instantiates beans, it looks for ApplicationContextAware implementations, If they are found, the setApplicationContext() methods will be invoked.
In this way, Spring is setting current applicationcontext.
Code snippet from Spring's source code:
private void invokeAwareInterfaces(Object bean) {
        .....
        .....
 if (bean instanceof ApplicationContextAware) {
  ((ApplicationContextAware)bean).setApplicationContext(this.applicationContext);
   }
}

Once you get the reference to Application context, you get fetch the bean whichever you want by using getBean().

A: Even after adding @Autowire if your class is not a RestController or Configuration Class, the applicationContext object was coming as null. Tried Creating new class with below and it is working fine:
@Component
public class SpringContext implements ApplicationContextAware{

   private static ApplicationContext applicationContext;

   @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws
     BeansException {
    this.applicationContext=applicationContext;
   }
 }

you can then implement a getter method in the same class as per your need to get the bean. Like:
    applicationContext.getBean(String serviceName,Interface.Class)

A: Using SpringApplication.run(Class<?> primarySource, String... arg) worked for me. E.g.:
@SpringBootApplication
public class YourApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(YourApplication.class, args);

    }
}

A: As an alternative approach you can use ConfigurableApplicationContext to get bean of any class which is annotated with @Component, @Repository or @Service.
Let's say you want to get a bean of the class BaseComponent :
@Service
public class BaseComponent {
    public String getMessage() {
        return "hello world";
    }
}

Now you can use ConfigurableApplicationContext to get the bean:
@Component
public class DemoComponent {
    @Autowired
    ConfigurableApplicationContext applicationContext;

    public BaseComponent getBeanOfBaseComponent() {
        return applicationContext.getBean(BaseComponent.class);
    }
}

A: You can use the ApplicationContextAware class that can provide the application context.
public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext ctx = null;

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }

    @Override
    public void setApplicationContext(final ApplicationContext ctx) throws BeansException {
        ApplicationContextProvider.ctx = ctx;
    }

    /**
     * Tries to autowire the specified instance of the class if one of the specified
     * beans which need to be autowired are null.
     *
     * @param classToAutowire        the instance of the class which holds @Autowire
     *                               annotations
     * @param beansToAutowireInClass the beans which have the @Autowire annotation
     *                               in the specified {#classToAutowire}
     */
    public static void autowire(Object classToAutowire, Object... beansToAutowireInClass) {
        for (Object bean : beansToAutowireInClass) {
            if (bean == null) {
                ctx.getAutowireCapableBeanFactory().autowireBean(classToAutowire);
            }
        }
    }

}

A: actually you want to get the object from the Spring engine, where the engine already maintaining the object of your required class at that starting of the spring application(Initialization of the Spring engine).Now the thing is you just have to get that object to a reference.
in a service class
@Autowired
private ApplicationContext context;

SomeClass sc = (SomeClass)context.getBean(SomeClass.class);

now in the reference of the sc you are having the object.
Hope explained well. If any doubt please let me know.

A: You can Autowire the ApplicationContext, either as a field
@Autowired
private ApplicationContext context;

or a method
@Autowired
public void context(ApplicationContext context) { this.context = context; }

Finally use
context.getBean(SomeClass.class)

A: If you are inside of Spring bean (in this case @Controller bean) you shouldn't use Spring context instance at all. Just autowire className bean directly.
BTW, avoid using field injection as it's considered as bad practice.

A: One API method I use when I'm not sure what the bean name is org.springframework.beans.factory.ListableBeanFactory#getBeanNamesForType(java.lang.Class<?>). I simple pass it the class type and it retrieves a list of beans for me. You can be as specific or general as you'd like to retrieve all the beans associated with that type and its subtypes, example
@Autowired
ApplicationContext ctx

...

SomeController controller = ctx.getBeanNamesForType(SomeController)

A: Just use:

org.springframework.beans.factory.BeanFactory#getBean(java.lang.Class)

Example:
@Component
public class Example {

    @Autowired
    private ApplicationContext context;

    public MyService getMyServiceBean() {
        return context.getBean(MyService.class);
    }

    // your code uses getMyServiceBean()
}

A: You can use ServiceLocatorFactoryBean. First you need to create an interface for your class
public interface YourClassFactory {
    YourClass getClassByName(String name);
}

Then you have to create a config file for ServiceLocatorBean
@Configuration
@Component
public class ServiceLocatorFactoryBeanConfig {

    @Bean
    public ServiceLocatorFactoryBean serviceLocatorBean(){
        ServiceLocatorFactoryBean bean = new ServiceLocatorFactoryBean();
        bean.setServiceLocatorInterface(YourClassFactory.class);
        return bean;
    }
}

Now you can find your class by name like that
@Autowired
private YourClassfactory factory;

YourClass getYourClass(String name){
    return factory.getClassByName(name);
}

A: Easy way in configration class call the BEAN annoted method . Yes u heard it right---- :P  calling SpringBoot @Bean annoted method return the same bean from config .I was trying to call a logout in @predestroy method in config class from a bean and direcltly called the method to get the same bean .
P.S. : I added debug in the @bean annotated method but it didn't entered the method even when i called it.Sure to blame -----> Spring Magic <----


text:
Q: Help me understand this TCP/IP code snippet I am reading the book "TCP/IP Lean" and I came across the following code which i do not understand. Could anyone explain it to me?
WORD buff_in(CBUFF *bp, BYTE *data, WORD len)
{
    WORD in, n, n1, n2;
    in = (WORD)bp->in & (bp->len-1);
    n = minw(len, buff_freelen(bp));
    n1 = minw(n, (WORD)(bp->len - in));
    n2 = n - n1;
    if (n1 && data) memcpy(&bp->data[in], data, n1);
    if (n2 && data) memcpy(bp->data, &data[n1], n2);
    bp->in += n;
    return(n);
}

A: You really should give some more context of this code. WORD is probably 4 bytes long since this is TCP/IP internals.
It appears to have something to do with copying data from a C buffer into an IPv4 packet. The two memcpy calls, seem to be swapping around two chunks of data.
It would help if you could explain what the inputs to buff_in are supposed to represent. CBUFF is a bit misleading because it is clearly a structure of some sort. Maybe just a length byte followed by a data buffer, but it would help if you told us for sure.

A: It appears to be copying up to len bytes of data from data to a circular buffer bp.
bp->len is the length of the circular buffer, and has to be a power of two, and  bp->in is the index within the circular buffer at which the next byte is to be written.  buff_freelen(bp) returns the amount of free space in the circular buffer, and minw() returns the minimum of the two arguments.
n is set to the amount of bytes to be copied, the minimum of the supplied len or the amount of free space in the destination buffer.  It then splits this into two chunks - n1, which is copied in starting at bp->data[in] and finishing at or before bp->data[bp->len - 1], and n2 (possibly zero length) which is copied in starting at bp->data[0].
It advances bp->in and returns n, the number of bytes copied.


text:
Q: Django e-commerce 1.2, missing settings.py file I'm reading the Django 1.2 e-commerce book by Jesse Legg.
I have used Django before and had no problems doing the usual basic stuff (admin apps etc).
However I'm stumped on this one.
Near the bottom of Page 17 it says:
"""
we will create our settings file and a root URLs file in our project module:
ecommerce_book/settings.py and ecommerce_book/urls.py. It is recommended
that you copy these files from the companion source code.
"""
The settings.py file is not in the companion source code. I have emailed the author and Packt but so far no reply.
Does anybody know how to locate this settings.py file?
I'm familiar with the usual method suggested i.e.
python django-admin.py startproject ecommerce_book
However, the author seems to be saying there is a custom settings.py file which needs to be used in this particular case. (but it's not included in the downloaded source code)

A: python django-admin.py startproject ecommerce_book

Though I'm not sure this initial settings.py will be the same you want. To the praticular settings.py contact authors or publishing.


text:
Q: Google Play In-app Billing API version is less than 3 I just started beta testing the 2.0 update to the billing library for the Play Store and a lot of my users are getting this error Google Play In-app Billing API version is less than 3.
Is this just a matter of time before they update or are some devices stuck on older versions or what?

A: It was normal, because at that moment it is not connected to any Google account.
So make sure you have an emulator with Google Play services.
-> Go to Google Play and enter your account credentials. After you close and reopen the app.

A: I started seeing this error when using the Emulator without logging into Google Play.
Once I logged into Google Play with my account the error went away.

A: In-app Billing API version goes with the Google Play Store and v3 is actually quite old (at least 3 years old)
PBL will check user's client version and will return this error message if their devices have a very old Play Store installed on their devices. If you're migrating from AIDL to PBL and you didn't check client's billing API version before, you could end up with seeing users reporting this issue.
You shouldn't expect this error message if you're upgrading from PBL 1.x to 2.0 because PBL 1.x is newer than v3 and it will also do this check. You may want to file a bug to the Google team in this case.


text:
Q: Remove Google Marker using Lat or Long I want to remove Marker using Lat or Long values. I have created a remove Marker function which removes the marker that exists on map.

A: While removing marker from google map , just set setMap(null) ,

<input type="button" onclick="removeMarker(-25.363882, 131.044922)" value="Remove" />


text:
Q: ReactJs : How to display a specific data of an object from an array of objects with a click I have an Array with a list of objects , each object contains an ID ,title , job description and salary. I saved it in a separate file as below :
  export const CareerList = [
  {
    id: 1,
    title: "Junior Accountant",
    salary: "1500$",
    jobDescription: [
      "Maintains financial records for subsidiary companies by analyzing balance sheets and general ledger accounts",
      "Reconciles general and subsidiary bank accounts by gathering and balancing information",
      "Provides financial status information by preparing special reports; completing special projects",
      "Corrects errors by posting adjusting journal entries",
      "Maintains general ledger accounts by reconciling accounts receivable detail and control accounts; adjusting entries for amortizations prepaids; analyzing and reconciling retainage and accounts payable ledgers; preparing fixed asset depreciation and accruals",
      "Secures financial information by completing database backups; keeping information confidential",
      "Maintains accounting controls by following policies and procedures; complying with federal, state, and local financial legal requirements",
      "Updates job knowledge by participating in educational opportunities; reading professional publications",
      "Accomplishes accounting and organization mission by completing related results as needed",
    ],
  },
  {
    id: 2,
    title: "Research Analyst",
    salary: "3500$",
    jobDescription: [
      "Support the Director of Research & Impact and the Research Manager in implementing all phases of ANDE research projects",
      "Design and administer surveys and conduct secondary data collection from online sources to aggregate data related to global SGB support.",
      "Clean and analyze data to identify key trends, and develop reports communicating these insights to practitioners",
      "Track new research developments related to SGBs and collect and synthesize this research for ANDE members.",
      "Provide support in identifying and selecting consultants and interns to support research activities and coordinate with these consultants and interns to carry out research.",
      "Manage the content of ANDE's various online research portals, such as www.galidata.org, http://ecosystems.andeglobal.org, and www.andeglobal.org/knowledge-hub.",
      "Manage administrative functions related to project funding (e.g. tracking expenses).",
    ],
  },

I am trying to create two modals , one modal which only display the job titles  with the button job details next to it , and if I clicked on a particular job button, the list modal should hide and another modal with that specific job details should show, any suggestion how it can be done?
    import { CareerList } from "../data/Careers";
import ButtonMedium from "../UI/ButtonMedium";
import JobDetails from "./JobDetails";

const Backdrop = (props) => {
  return

;
};

const CareerOverlay = () => {
  const [showJobDetails, setShowJobDetails] = useState(false);

  const displayJobDetails = () => {
    setShowJobDetails(true);
  };

  return (
    <>

        {CareerList.map((job, index) => {
          return (

{job.title}

              <ButtonMedium onClick={displayJobDetails}>
                Job Detail
              </ButtonMedium>
              {showJobDetails && (
                <JobDetails careerList={CareerList} id={job.id} />
              )}

          );
        })}

    </>
  );
};

const CareerOpportunities = (props) => {
  return (
    <>
      {reactDom.createPortal(
        <Backdrop onHide={props.onHide} />,
        document.getElementById("backdrop")
      )}
      {reactDom.createPortal(
        <CareerOverlay onShow={props.onShow} />,
        document.getElementById("career")
      )}
    </>
  );
};

export default CareerOpportunities;

import React from "react";
import classes from "./JobDetails.module.css";

const JobDetails = (props) => {
  const particularJob = props.careerList.find((job) => job.is === props.id);

  return (

{particularJob.title}

  );
};

export default JobDetails;

A: You can split each item using new child component. So each item can manage modal state individually.
const CareerListItem = (props) => {
  const [showJobDetails, setShowJobDetails] = useState(false);

  const displayJobDetails = () => {
    setShowJobDetails(true);
  };

  return (

{job.title}

      <ButtonMedium onClick={displayJobDetails}>
        Job Detail
      </ButtonMedium>
      {showJobDetails && (
        <JobDetails job={props.job} />
      )}

  )
}

const CareerOverlay = () => {
  return (
    <>

        {CareerList.map((job, index) => {
          return (
            <CareerListItem job={job} />
          )
        })}

    </>
  );
};
...
const JobDetails = (props) => {
  return (

{props.job.title}

details here...

  );
};

A: Although the other answer seems alright, I'd also advise you to use portals for modals in React, and by that way you won't be bothered by stacking order when you're styling both modals.
Read more about portals here:
https://reactjs.org/docs/portals.html


text:
Q: How to update (renewed) org's admin certificate in the channel config (which has expired org's admin certificate) - hyperledger fabric I created a test network which has 2 orgs (each with one peer), 1 orderer in kubernetes using BAF. Orgs are joined in the channel called testchannel. Orderer msp, peer msp and tls certs expired within 1 day. Before it expired, I renewed all the certs using dcm tool and kept it in my local. First I updated the orderer tls cert in system channel and in application channel from orderer cli, by fetching the channel config, decoded, updated renewed orderer tls certs under consenters, encoded and updated the channel config using peer channel update command. I received a successfully submitted message.
Later replaced orderer msp, peer msp and tls certs in the vault and restarted all the services. When I checked the orderer logs, it didn't show any expiry error.
Now my network's previous certificate expired. Now it is using renewed certs. I am able to invoke and query transactions.
Now I want to add a new org called org3 to the existing (testchannel).
I created a new org (org3). When I tried to join that org to the channel, during peer channel update it failed. It shows the following error,
Error: got unexpected status: BAD_REQUEST -- error applying config update to existing channel 'testchannel': error authorizing update: error validating DeltaSet: policy for [Group] /Channel/Application not satisfied: implicit policy evaluation failed - 0 sub-policies were satisfied, but this policy requires 2 of the 'Admins' sub-policies to be satisfied

This error is because of wrong admin certs. Then only I found that during certificate renewal, I updated only orderer tls certs. But the channel config also contains each org's admin certs and cacerts. Now the channel config contains expired certs. But the orgs and vault contain renewed certs.
This is the cause for the above mentioned error.
Can anyone suggest a way to resolve this? How can we update org's admin certificate in the channel config which has expired certificate?
Thanks in advance......


text:
Q: Procmail recipe, mail owned by root I'm using a combination of Postfix and Procmail to handle inbound email on one of my servers. Each user has a local account and I've been using the below /usr/local/etc/procmailrc successfully for years:
DEFAULT=$HOME/mail/
LOGFILE=/var/log/procmail

I've recently added a recipe to direct messages flagged as spam to a separate folder:
:0
* ^X-Spam-Flag: YES
$HOME/mail/.Junk/

However, it seems in some cases the messages going into this folder are owned by root instead of the correct user. I've never had this issue with the Inbox, and it also seems like it only affects certain users.
I managed to catch one of the Procmail processes in ps and it does seem to run as the correct user. (This user also has root owned mail in the Junk folder)
# ps axu | grep procmail
{correct-local-username}   7402   0.0  0.2  12140   1780 ??  Ss   11:37AM      0:00.01 /usr/local/bin/procmail -a

Does anyone have an idea why messages handled by the recipe would end up owned by root, while messages going to the default folder would get the correct owner?
Is there anything I can do (even if it's hacky such as calling chown from the Procmail recipe) to make sure the messages are always owned by the correct user?
In case it's of importance, Procmail is configured in Postix as follows:
mailbox_command = /usr/local/bin/procmail -a "$EXTENSION"

A: Check the permissions on the junk folder are correct, but could you also add the following to your procmail.cf:
DROPPRIVS=yes

I'm no expert on procmail, but according to this man entry, it should drop any priveleges that procmail has had, and the recipient doesn't (emphasis mine).
 DROPPRIVS            If  set  to  `yes'  procmail   will   drop   all
                      privileges  it  might  have  had (suid or sgid).
                      This is only useful if  you  want  to  guarantee
                      that the bottom half of the /etc/procmailrc file
                      is executed on behalf of the recipient.

Key part; executed on behalf of the recipient.
Explanation of why this works form user @Tripleee:

The DEFAULT delivery happens after an implicit DROPPRIVS, but if you explicitly deliver something while in privileged mode, you also need to explicitly drop your privileges.


text:
Q: postgres doesn't autogenerate PK if the PK is inserted manually I have a simple table like this:
CREATE TABLE IF NOT EXISTS myval
(
    id integer NOT NULL DEFAULT nextval('myval_myval_id_seq'::regclass),
    name character varying(255),
    CONSTRAINT "PK_aa671c3359a0359082a84ecb801" PRIMARY KEY (id)
)

the sequence definition is:
CREATE SEQUENCE IF NOT EXISTS myval_myval_id_seq
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 2147483647
    CACHE 1
    OWNED BY myval.myval_id;

when I insert data along with the primary key:
INSERT INTO myval(id, name) VALUES (1, 'sdf');
INSERT INTO myval(id, name) VALUES (2, 'sdf');
INSERT INTO myval(id, name) VALUES (3, 'sdf');
INSERT INTO myval(id, name) VALUES (4, 'sdf');

then, I insert it without the PK:
INSERT INTO myval(name) VALUES ('new sdf');

it gives an error saying:

duplicate key value violates unique constraint "PK_aa671c3359a0359082a84ecb801",
DETAIL:  Key (myval_id)=(1) already exists.

I expected it to start with PK value of 5 but, instead it gives an error. Can we configure postgres to skip conflicting values and generate from the closest available value to use instead of throwing an error?

A: The best way to avoid such conflicts is to use identity columns - in this case a GENERATED ALWAYS AS IDENTITY seems the right option.
CREATE TABLE IF NOT EXISTS myval
(
    id integer GENERATED ALWAYS AS IDENTITY,
    name character varying(255),
    CONSTRAINT "PK_aa671c3359a0359082a84ecb801" PRIMARY KEY (id)
);

This will work like a sequence (serial), however it will fail if the user tries to manually insert a value in this column
INSERT INTO myval (id,name)
VALUES (1,'foor');

ERROR:  cannot insert a non-DEFAULT value into column "id"
DETAIL:  Column "id" is an identity column defined as GENERATED ALWAYS.
TIP:  Use OVERRIDING SYSTEM VALUE to override.

If for whatever reason you must override this behavior in a certain INSERT statement you can do so using OVERRIDING SYSTEM VALUE, as the error message above suggests
INSERT INTO myval (id,name) OVERRIDING SYSTEM VALUE
VALUES (1,'foo');

You might be able to achieve a sequential value using serial even if the user screws things up with inserts, e.g. using trigger functions. But such an architecture is hard to maintain and imho is definitely not worth the trouble.
Demo: db<>fiddle


text:
Q: Subspace topology and homeomorphic mapping The following example is written in Set Theory and General Topology (by Fuichi Uchida, Textbook in the Japanese Language).

Example 25.4 Let subspace $X$ of $R^2$ with usual topology be
$X=\{(x,\sin(\frac{1}{x}))\mid x>0\} \cup \{(0,y) \mid -1\leq y \leq 1\}.$
Let subset A of X be
$A=\{(x,\sin(\frac{1}{x}))\mid x>0 \}.$
We have $A$ is homeomorphic to the interval $(0,\infty)$.

I would like to know a proof that $A$ is homeomorphic to the interval $(0,\infty)$. We need to show that the mapping $(0, \infty) \rightarrow A$ is bijective and continuous, and that the inverse mapping is also continuous. The mapping $(0, \infty) \rightarrow A$ is clearly bijective. If we could accept that $\sin(\frac{1}{x})$ is a continuous function for $x > 0$, then we know that this mapping is continuous. Finally, we should prove that the inverse mapping $A \rightarrow (0, \infty)$ is continuous. However, I could not find the proof. Please give me hints concering the inverse mapping $A \rightarrow (0, \infty)$ is continuous.
PD. Sorry about my English, but it is not my native language.

A: Consider$$\begin{array}{rccc}f\colon&(0,\infty)&\longrightarrow&A\\&x&\mapsto&\left(x,\sin\left(\frac1x\right)\right).\end{array}$$Then $f$ is a continuous bijection. And $f^{-1}\colon A\longrightarrow(0,\infty)$ is continuous too, since it is simply the map $(x,y)\mapsto x$. Therefore, $f$ is a homeomorphism.

A: $A$ is the graph of the continuous map $\sin(\frac 1 x) : (0,\infty) \to \mathbb R$.
We shall prove the following theorem:

The graph $G(f) = \{(x,f(x)) \mid x \in X \} \subset X \times Y$ of a continuous map $f : X \to Y$ is homeomorphic to the domain $X$ of $f$. Here $G(f)$ receives the subspace topology of the product $X \times Y$ (which is endowed with the product topology).

*

*The map $i : X \to G(f), i(x) = (x,f(x))$, is continuous.

*The projection $p_X: X \times Y \to X$ is continuous, thus also the restriction $p = p_X \mid_{G(f)} : G(f) \to X$ is continuous.

*We have $p \circ i = id_X, i \circ p = id_{G(f)}$. Thus $i$ and $p$ are homeomorphisms which are inverse to each other.


text:
Q: how to pass 2 files in intent android I need to share 2 csv files I created in my app.
I was able to share one of them with the below code, but how to I pass 2 files to share?
  for (File file : fileList) {

                    if (!file.exists()) {
                        Toast.makeText(ExcelExportActivity.this, "File doesn't exists", Toast.LENGTH_LONG).show();
                        return;
                    }
                    Uri uri = FileProvider.getUriForFile(ExcelExportActivity.this, "com.example.farmers.provider", file);

                    grantUriPermission(ExcelExportActivity.this.getPackageName(), uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    sharingIntent.setType("text/csv");
                    sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);

                }
sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "my subject");
                startActivity(Intent.createChooser(sharingIntent, "sharing with..."));

A: You will need to use Intent.ACTION_SEND_MULTIPLE instead of Intent.ACTION_SEND.
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putExtra(Intent.EXTRA_SUBJECT, "Here are some files.");
intent.setType("text/csv");

ArrayList<Uri> files = new ArrayList<Uri>();

for(String path : filesToSend /* List of the files you want to send */) {
    File file = new File(path);
    Uri uri = Uri.fromFile(file);
    files.add(uri);
}

intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
startActivity(intent);


text:
Q: Options for font size What do I put in the \documentclass so that I can change the font size to any value? I'm asking because for {extarticle} 13pt isn't an option. So what do I do?

A: As stated by @TorbjørnT., the KOMA-classes allow one to use arbitrary font sizes as the base size. The important notice here is that one should load the \RequirePackage{fix-cm} package before \documentclass. This way, you can avoid size substitution which usually occurs when choosing a non-standard fontsize (11.5, 13, 15, etc.). Refer to the KOMA-script manual for more details. Here is an example:
\RequirePackage{fix-cm}
\documentclass[fontsize=13pt,DIV=12]{scrartcl}
\usepackage{lipsum}
\usepackage[T1]{fontenc}
\usepackage{lmodern}

\begin{document}

\lipsum

\end{document}

A: From page 2 of the 2-page user guide of the extarticle document class:

The sizes available are 8pt, 9pt, 10pt, 11pt, 12pt, 14pt, 17pt, and 20pt.

A: The KOMA-classes allow one to use arbitrary font sizes as the base size. To quote the manual:

fontsize=size

In contrast to the standard classes and most other classes that
  provide only a very limited number of font sizes, the KOMA-Script
  classes offer the feature of selection of any desired size for the
  main document font. In this context, any well known TeX unit of
  measure may be used and using a number without unit of measure means
  pt. If you use this option inside the document, the main document font
  size and all dependent

Of course these classes changes a lot of other things as well, but you could try
\documentclass[fontsize=13pt]{scrartcl}


text:
Q: Watchpoints in shared memory? I'm debugging an issue in a patch to PostgreSQL where a word in shared memory seems to get overwritten unintentionally.
Valgrind isn't any help as it can't keep track of interactions in shared memory between multiple processes.
The address that gets overwritten is fairly stable but not totally fixed, though it's always identified by a pointer in a global struct initialized early in startup by each process.
I'm trying to find a way to get a stack trace whenever any process writes to the address of interest, but it's proving rather harder than I would've expected.
gdb watchpoints aren't any help, as gdb can't follow fork() and establish the same watch on child processes. Manually doing it with multiple gdb processes is very cumbersome due to the number of child processes PostgreSQL uses and the timing issues involved in setting it up by hand.
perf userspace probes looked promising, but seem to attach only to functions, there's no apparent way to trap a write to a memory address.
So is there any way to grab stack traces for each writer to a given shared memory address across multiple processes?

A:
gdb can't follow fork() and establish the same watch on child processes

A sufficiently recent GDB can do that. Documentation here and here.


text:
Q: OpenGL-es projection doesn't seem to work I've tried following the lessons about drawing shapes and applying projections to them as found here, but the projection just doesn't seem to work. As far as I know I've copy-pasted all the pieces of code in my project, here are the important code parts:
In my Renderer class:
@Override
public void onDrawFrame(GL10 unused) {
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

    // Set the camera position (View matrix)
    Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);

    // Calculate the projection and view transformation
    Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);

    // Draw shape
    mTriangle.draw(mMVPMatrix);
}

@Override
public void onSurfaceChanged(GL10 unused, int width, int height) {
    GLES20.glViewport(0, 0, width, height);

    float ratio = (float) width / height;
    Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
}

The draw method of my Triangle class:
public void draw(float[] mvpMatrix) {
    GLES20.glUseProgram(mProgram);

    mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition"); // get handle to vertex shader's vPosition member
    GLES20.glEnableVertexAttribArray(mPositionHandle); // Enable a handle to the triangle vertices

    GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, vertexStride, vertexBuffer); // Prepare the triangle coordinate data

    mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor"); // get handle to fragment shader's vColor member
    GLES20.glUniform4fv(mColorHandle, 1, color, 0); // Set color for drawing the triangle

    mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix"); // get handle to shape's transformation matrix
    GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0); // Apply the projection and view transformation

    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount); // Draw the triangle

    GLES20.glDisableVertexAttribArray(mPositionHandle); // Disable vertex array
}

The triangle still is being stretched. What am I doing wrong?

A: Did you try to debug in onSurfaceChanged? What happens in those lines? Especially:

*

*
*

*what are the passed values width and height?

*which value does float ratio = (float) width / height; calculate?

*do you see any changes to the values of mProjMatrix after the call Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7);?

*how does your private final String fragmentShaderCode in class Triangle look like? As  the order of the multiplication in the line "  gl_Position = uMVPMatrix * vPosition;" + is important.
Your provided code looks quiet good, difficult issue here.


text:
Q: Nodejs lost data when using Loop for download many files Today, I'm try to download many file from my server
download.js
function getPhotos(req, res) {
  //Get User Photos
  var fileReader = fs.readFile('./../data/user.json', 'utf8', function(err, data) {
    if (err)
      console.log(err);
    else {
      var dataJson = JSON.parse(data);
      //console.log(dataJson.Person);
      for (var i = 0; i < dataJson.Person.length; i++) {
        var options = {
          host : '10.16.47.128', // Local Server IPAddress
          port : 2013, //Port
          path : '/ExternalServer/avatar/' + dataJson.Person[i].Username + '.jpg',
        };
        //console.log(dataJson.Person[i].Username);
        var fileAvatarPhotos = fs.createWriteStream('./../avatar/' + dataJson.Person[i].Username + '.jpg');
        fs.exists(fileAvatarPhotos, function(exists) {//Check Exist File
          if (exists) {
            var req = http.get(options, function(res) {
              //console.log(res);
              res.pipe(fileAvatarPhotos);
            });
          } else {
            var req = http.get(options, function(res) {
              fs.writeFile(fileAvatarPhotos, '', function(err) {
                if (err)
                  return console.log(err);
                var req = http.get(options, function(res) {
                  //console.log(res);
                  res.pipe(fileAvatarPhotos);
                });
              });
            });
          }
        });
      }
    }
  });
  //End Get User Photos
}

when I run code:
node download.js

System downloaded all photos, but size of photo is 0kb.
and has error:

stream.js:81
        throw er; // Unhandled stream error in pipe.
              ^ Error: OK, close

Beside, when I Throw Loop (EX: fix dataJson.Person[i].Username, change i to 10)
after running code, system reurn correct photo.
what are happening?
How to fix it?
best regard.!

A: It's not a good idea to implement such a functionality in a for loop. That's because inside the loop you have async operations, but every iteration of the loop is executed immediately. In your case you are defining fileAvatarPhotos which is a WriteStream object. The http.get method is asynchronous, so in its callback you may use the fileAvatarPhotos defined for the third iteration of the loop, or the fourth or maybe the first one. It depends. You may try to convert your code to something like this:
var files = ["file1.jpg", "file2.jpg", "file3.jpg"];
var readFile = function(callback) {
    if(files.length > 0) {
        var file = files.shift();
        http.get({path: file}, function(res) {
            // ... process the result
            readFile(callback);
        })
    } else {
        callback();
    }
}
readFile(function() {
    console.log("reading finishes");
});

I.e. readFile is called again and again till there is no more elements in files array.

A: Javascript doesn't have loop block scopes, it has function-based scopes.
That means, as Krasimir points out, that your for-loop variables are overwriting each other
before they are finished being used.
So, you need to at least wrap the innards of that for loop in a function, or things that seem
strange will start happening.
Even if that is fixed, the code will be trying to do all the downloads at the same time, and Krasimir's answer may be cleaner since he avoids that.
Still, using a function to make sure each  for-loop execution gets its own scope is
a good thing to know.
Modify for loop as follows:
for (var i = 0; i < dataJson.Person.length; i++) {
      (function(i){
        var options = {
          host : '10.16.47.128', // Local Server IPAddress
          port : 2013, //Port
          path : '/ExternalServer/avatar/' + dataJson.Person[i].Username + '.jpg',
        };
        //console.log(dataJson.Person[i].Username);
        var fileAvatarPhotos = fs.createWriteStream('./../avatar/' + dataJson.Person[i].Username + '.jpg');
        fs.exists(fileAvatarPhotos, function(exists) {//Check Exist File
          if (exists) {
            var req = http.get(options, function(res) {
              //console.log(res);
              res.pipe(fileAvatarPhotos);
            });
          } else {
            var req = http.get(options, function(res) {
              fs.writeFile(fileAvatarPhotos, '', function(err) {
                if (err)
                  return console.log(err);
                var req = http.get(options, function(res) {
                  //console.log(res);
                  res.pipe(fileAvatarPhotos);
                });  // http.get
              }); // fs.writeFile
            }); // http.get
          } // else
        }); // fs.exists
       })(i); // anonymous function to create scopes for loop
      } //for loop


text:
Q: How to list elements of an array in the order of number of their occurrences? I have an array like this.
$array = array(
'Element1',
'Element2',
'Element3',
'Element1',
'Element1',
'Element4',
'Element4',
'Element2',
'Element2',
'Element2',
'Element2',
'Element4',
'Element5',
'Element5' );

I want an array like this as output.
$output = array('Element2' , 'Element1', 'Element4', 'Element5', 'Element3');

So, what i want is:

*

*Remove all the elements from the array which repeat.

*Order the output array in such manner that the element which occured most in the input array is on top.

A: Use array_count_values() and sort()

A: It should be ok:
$numbers = array_count_values($array);

arsort($numbers); // Thanks Jessica!
$result = array_keys($numbers);

A: Your expected output is contradictory to your requirements listed. Element5 should come before Element3
<pre>
<?php
$values = array(
'Element1',
'Element2',
'Element3',
'Element1',
'Element1',
'Element4',
'Element4',
'Element2',
'Element2',
'Element2',
'Element2',
'Element4',
'Element5',
'Element5' );

$result = array_count_values($values);
arsort($result);
$result = array_keys($result);
print_r($result);
?>