text:
Q: Do we really need to a priori assume fields, and functions of them, die off at infinity? At the beginning of many QFT books that I've been going through, in the section on classical field theory (whose logic I presume is carried over to many other parts of those books), authors typically impose a version of the least action principle on their fields that I believe is slightly superfluous. This common version of the least action principle is the following:

*

*The action is defined as $S=\int d^4 x \,\mathcal{L}(\phi, \partial \phi )$, where the integration is carried out over all of spacetime.

*fields be an extremum of the action when subject to (functional) variations in the fields
These require one to assume that both the fields and any function of the fields (for the equations for $\phi$ to be unchanged upon adding the total derivative of any function to $\mathcal{L}$) die off at infinity. I think this is a physically sound assumption, but totally unnecessary at this point.
If you instead change the least action principle to the following, you don't have to make any "everything dying off at infinity" assumptions just yet, allowing you to reserve them for when you need them later (imposing that physical fields are operator-valued tempered distributions over $L^2$ functions):

*

*The action over a region of spacetime is defined as $S=\int_{R} d^4 x \mathcal{L}(\phi,\partial \phi)$, where $R$ is some closed volume.

*The equations/realizations of the fields $\phi$ are obtained by imposing that the action is an extremum with respect to functional variations over any closed volume $R$ vanishing on the boundary $\partial R$. (Think of pinning down a region $R$ and wiggling the fields within it)
I've done some calculations and seen that literally everything pops right into place - full derivatives don't change the action, global/internal symmetries still give Noether currents, etc. - when I use that (modified) version.
My question(s): Are there sources that talk about this explicitly? Are there holes in my logic? I presume there are since I'm just a lowly student and these authors probably have thought through this more than I have.


text:
Q: Divs are catching on other divs I have a bunch of toggle buttons with labels underneath.  If the labels for a button get to be too long then what should be the first button of the next row will get stuck on that label.
Heres my code:
https://jsfiddle.net/Android272/c150305z/
I have looked it up and everyone wants to know how to make their site like pintrest. I don't want this to look like that, I want my second and third rows not to be stuck on the first.
some people suggested to place
 display: inline-block;

somewhere but everywere I place it it does not seem to fix it.

A: That's because you're using unequal heights in your divs.
Set a height to your third section's divs and it will remain equal in row:
section:nth-child(3) div {height:110px}

JsFiddle
Edit: Another way is to save the spacing by adjusting the p but still needs to use height for the parent.
This should do:
section:nth-child(3) div {
    height:100px; /* Same amount of space as other divs  */
}
section:nth-child(3) div p {
    margin-top:3px;
    line-height: 15px;
}

JsFiddle

redpajama_set_name: RedPajamaStackExchange


text:
Q: Certain conditions on cancellative semigroups This is extracted from this question following Benjamin Steinberg's suggestion.
For a semigroup $S,$ let $P(S)$ denote the power semigroup of $S,$ which is made up of all non-empty subsets of $S$ with the operation $AB=\{ab\,|\,a\in A,b\in B\}.$
I'm thining about the following conditions $(P1)$ and $(P2)$ on $S:$

$(P1)$ Every left-cancellable element of $P(S)$ is a singleton.
$(P2)$ Every cancellable element of $P(S)$ is a singleton.

1) Are the two conditions equivalent? Are they equivalent for left-cancellative semigroups? Are they equivalent for cancellative semigroups?
2) Can we characterize semigroups satisfying these conditions? Left-cancellative ones? Cancellative ones?
The questions in bold interest me the most. The class of cancellative semigroups satisfying $(P1)$ contains groups and commutative semigroups. From above, any left-cancellative semigroup satisfying $(P1)$ will have to satisfy the right Ore condition.


text:
Q: how to work out the search complexity of a function I have the following two functions and i am trying to compare the time complexity
my first function is a simple for loop:
For (i=0;i<m;i++)
// do stuff

Time complexity:

i=0 is executed once
i< n is executed n+1 times
i++ is executed n times
= 2n+2 = 0(N)

i am struggling to work out my time complexity for this second function:
void search(string word)
{
    Index index;
    if (tree.AVL_Retrieve(word, index)) {
        for (auto i : index.idList)
        {

             for (int j=0;j<m;j++)
                 {
                    //do stuff
                  }
        }
    }
}

i believe that retrieve in AVL tree is O(logN) and my loop is O(N) and then my inner loop is O(M), but as a whole how would i write the time complexity for that search function.
note: we can assume there are N keys in my AVL tree

A: The first for loop runs for (m-1) times, thus having time complexity O(m).
The second function runs the AVL_Retrieve function once and for each loop count of index.idList times, giving the complexity O(log (number of nodes in tree))+O((count of index.idList)*m)


text:
Q: Inequality involving tangent provided $\tan\theta\geq 1$ If $\tan\theta\geq1$, then
$$\sin\theta-\cos\theta\leq\mu(\cos\theta+\sin\theta)\implies\tan\theta\leq\dfrac{1+\mu}{1-\mu}.$$
Why? I get as far as the obvious $$\tan\theta\leq1+\mu(\cos\theta+\sin\theta)$$

A: Assume for the moment that we are in quadrant I (i.e., $\sin{\theta} \ge 0$ and $\cos{\theta} \ge 0$).  Then
$$\frac{\sin{\theta}-\cos{\theta}}{\sin{\theta}+\cos{\theta}} \le \mu$$
Divide through up and down by $\cos{\theta}$:
$$\frac{\tan{\theta}-1}{\tan{\theta}+1} \le \mu$$
which means that
$$\tan{\theta}-1 \le \mu (\tan{\theta}+1) \implies (1-\mu) \tan{\theta} \le 1+\mu$$
The result follows.  You then need to show that this also works in quadrant III.


text:
Q: "File -X: does not exist" message from ipy.exe in Windows PowerShell If I type this line in an MS-DOS command prompt window:
ipy -X:ColorfulConsole

IronPython starts up as expected with the colorful console option enabled. However, if I type the same line in Windows PowerShell I get the message:
File -X: does not exist

Can someone explain what I'm doing wrong?

A: Try this code:
ipy '-X:ColorfulConsole'

Or whatever quoting mechanism is supported in Windows PowerShell - the shell is splitting your argument.
Typing
ipy -X: ColorfulConsole

in MS-DOS command prompt window returns the same response:
File -X: does not exist.


text:
Q: client can not connect againt to my Socket Server - VB.NET I have a thread and a socket server for listening to client. Client software is not for me and it is a Laboratory Software that sends data to my program.
when listening starts there is no problem but when the client software is closed and reopened, that can not send any data to my software.
My listener must be run every time like a service.
This is my code:
Delegate Sub WriteMsgHandle(ByVal Msg As String)
Dim handler As WriteMsgHandle

Dim THS As ThreadStart
Dim TH As Thread
Private Sub btnListen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListen.Click
    Try
        btnListen.Enabled = False

        THS = New ThreadStart(AddressOf Listen)
        TH = New Thread(THS)
        TH.Start()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

End Sub
Public Sub Listen()
    Dim bytesReceived As Integer = 0
    Dim recv() As Byte = New Byte(1) {}
    Dim clientSocket As Socket
    Dim listenerSocket As New Socket _
        (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    Dim IPHost As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
    Dim localadd As IPAddress = IPAddress.Parse(txt_ip.Text)
    Dim ipepServer As IPEndPoint = New IPEndPoint(localadd, txt_port.Text)
    handler = AddressOf WriteMsg
    listenerSocket.Bind(ipepServer)
    listenerSocket.Listen(-1)
    clientSocket = listenerSocket.Accept()

    Dim msgcount As Integer = 0

    If clientSocket.Connected Then

        MsgBox("Connected")

        Do
            bytesReceived = clientSocket.Receive(recv)
            Dim Msg As String

            Msg = Encoding.ASCII.GetString(recv)
            Invoke(handler, Msg)

        Loop While bytesReceived <> 0

    End If
End Sub

A: *

*You're only accepting once. You need to accept in a loop.

*If clientSocket.Connected Then why did you add this? Delete that check. The socket was just accepted so it is connected. Even if it was disconnected do you want to just ignore that error condition?!

*The receive loop is correct.

*You probably want to start each accepted client on a new thread (or use async IO).


text:
Q: Why this code is showing "wrong answer" when i submit it to the online judge? I am quite new to python. I was solving a problem on an online judge.
The problem was:

Take the set of integers
  1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19,...
First, delete every second number, we get following reduced set.
  1,3,5,7,9,11,13,15,17,19,...
Now, delete every third number, we get
  1, 3, 7, 9, 13, 15, 19,...
Continue this process indefinitely……
  Any number that does NOT get deleted due to the above process is called "lucky".

This is my code:
m=int(input())
n=2
while 1:
    if m%n==0:
        print(0)
        break
    if n>m:
        print(1)
        break
    m=m-(m//n)
    n=n+1

another approach:
n=int(input())
def Lucky(n):
 next_position = n

 if Lucky.counter > n:
    return 1

 if n % Lucky.counter == 0:
    return 0

 next_position = next_position - next_position // Lucky.counter

 Lucky.counter = Lucky.counter + 1

 return Lucky(next_position)

Lucky.counter = 2
if Lucky(n):
 print (1)
else:
 print (0)

when I compiled my program it was running successfully and gave correct answers to all the test cases. but when I submitted on the oj it showed "wrong answer" and was written "Possibly your code doesn't work correctly for multiple test-cases (TCs)". on the small test cases (like 2) it showed correct answer but when the number was bigger (like 30886) it was not showing any answer at all.


text:
Q: How to configure hostname resolution to use a custom DNS server in Java? java.net.InetAddress resolves hostnames using the local machine's default host-name resolver by default:

Host name-to-IP address resolution is accomplished through the use of a combination of local machine configuration information and network naming services such as the Domain Name System (DNS) and Network Information Service(NIS). The particular naming services(s) being used is by default the local machine configured one. For any host name, its corresponding IP address is returned. [source]

How can we configure this behavior without modifying the local machine's default hostname resolver?
For example, is there anyway to configure java.net.InetAddress such that it resolves host names through OpenDNS (208.67.222.222, 208.67.220.220) or Google Public DNS (2001:4860:4860::8888, 2001:4860:4860::8844)?
Or is the only solution to explicitly create DNS packet requests, send them to the servers through either java.net.DatagramSocket or java.net.Socket, and parse the responses?

A: For Java versions up to 8, here is the code I wrote to hard-code a foo system name DNS resolution in Java for test cases to pass. Its avantage is to append your specific entrie(s) to default Java runtime DNS resolution.
I recommend not to run it in production. Forced reflective access and Java runtime non-public implementation classes are used !
private static final String FOO_IP = "10.10.8.111";

/** Fake "foo" DNS resolution */
@SuppressWarnings("restriction")
public static class MyHostNameService implements sun.net.spi.nameservice.NameService {
    @Override
    public InetAddress[] lookupAllHostAddr(String paramString) throws UnknownHostException {
        if ("foo".equals(paramString) || "foo.domain.tld".equals(paramString)) {
            final byte[] arrayOfByte = sun.net.util.IPAddressUtil.textToNumericFormatV4(FOO_IP);
            final InetAddress address = InetAddress.getByAddress(paramString, arrayOfByte);
            return new InetAddress[] { address };
        } else {
            throw new UnknownHostException();
        }
    }
    @Override
    public String getHostByAddr(byte[] paramArrayOfByte) throws UnknownHostException {
        throw new UnknownHostException();
    }
}

static {
    // Force to load fake hostname resolution for tests to pass
    try {
        List<sun.net.spi.nameservice.NameService> nameServices =
            (List<sun.net.spi.nameservice.NameService>)
            org.apache.commons.lang3.reflect.FieldUtils.readStaticField(InetAddress.class, "nameServices", true);
        nameServices.add(new MyHostNameService());
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

Hope this helps, but again, to be used with care !

A: Java provided a new system parameter jdk.net.hosts.file for adding customized DNS records, as specified in the source code
 * The HostsFileNameService provides host address mapping
 * by reading the entries in a hosts file, which is specified by
 * {@code jdk.net.hosts.file} system property
 *
 *
The file format is that which corresponds with the /etc/hosts file
 * IP Address host alias list.
 *
 *
When the file lookup is enabled it replaces the default NameService
 * implementation
 *
 * @since 9
 */
private static final class HostsFileNameService implements NameService {

Example: we can start a Java application with JVM Option

*

*-Djdk.net.hosts.file=/path/to/alternative/hosts_file
Where hosts_file content could be:
127.0.0.1    myserver-a.local
10.0.5.10    myserver-b.local
192.168.0.1  myserver-c.local

It will do the DNS trick based on the hosts_file

A: Java 9 removed this capability.  You will need to use a third party DNS client library.
If you are using Java 8 or older you can do:
You can set the system property sun.net.spi.nameservice.nameservers as documented by this site.

A: with the following Interface and allowing access to java.net.* it is possible to use own DNS provider with JDK8 and JDK9. The new Provider is installed via
"INameService.install(new MyNameService());"
public interface INameService extends InvocationHandler {
    public static void install(final INameService dns) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException {
        final Class<?> inetAddressClass = InetAddress.class;
        Object neu;
        Field nameServiceField;
        try {
            final Class<?> iface = Class.forName("java.net.InetAddress$NameService");
            nameServiceField = inetAddressClass.getDeclaredField("nameService");
            neu = Proxy.newProxyInstance(iface.getClassLoader(), new Class<?>[] { iface }, dns);
        } catch(final ClassNotFoundException|NoSuchFieldException e) {
            nameServiceField = inetAddressClass.getDeclaredField("nameServices");
            final Class<?> iface = Class.forName("sun.net.spi.nameservice.NameService");
            neu = Arrays.asList(Proxy.newProxyInstance(iface.getClassLoader(), new Class<?>[] { iface }, dns));
        }
        nameServiceField.setAccessible(true);
        nameServiceField.set(inetAddressClass, neu);
    }

    /**
     * Lookup a host mapping by name. Retrieve the IP addresses associated with a host
     *
     * @param host the specified hostname
     * @return array of IP addresses for the requested host
     * @throws UnknownHostException  if no IP address for the {@code host} could be found
     */
    InetAddress[] lookupAllHostAddr(final String host) throws UnknownHostException;

    /**
     * Lookup the host corresponding to the IP address provided
     *
     * @param addr byte array representing an IP address
     * @return {@code String} representing the host name mapping
     * @throws UnknownHostException
     *             if no host found for the specified IP address
     */
    String getHostByAddr(final byte[] addr) throws UnknownHostException;

    @Override default public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
        switch(method.getName()) {
        case "lookupAllHostAddr": return lookupAllHostAddr((String)args[0]);
        case "getHostByAddr"    : return getHostByAddr    ((byte[])args[0]);
        default                 :
            final StringBuilder o = new StringBuilder();
            o.append(method.getReturnType().getCanonicalName()+" "+method.getName()+"(");
            final Class<?>[] ps = method.getParameterTypes();
            for(int i=0;i<ps.length;++i) {
                if(i>0) o.append(", ");
                o.append(ps[i].getCanonicalName()).append(" p").append(i);
            }
            o.append(")");
            throw new UnsupportedOperationException(o.toString());
        }
    }
}

A: As Pace indicated, the ability to configure name resolution was removed from the JDK. However, in Java 18, it was replaced with the SPI java.net.spi.InetAddressResolverProvider.
Between Java 8 and Java 18, as the JDK Inet4AddressImpl.c eventually ends up calling getnameinfo, you can still intercept that call with LD_PRELOAD shadowing.
There are libraries which make this very straightforward, such as CWrap.


text:
Q: Prevent keyTyped() from triggering when pressing ctrl+s I have an accelerator for ctrl+s and at the same time a keylistener on a JTextField listening for keyTyped(). But when i press ctrl+s i dont want it to trigger keyTyped(). Any suggestions?

A: Why are you listening for "key typed" events on the text field?
Probably a better solution is to use a DocumentListener to be notified when text is added or removed from the text field.
If you state your actual requirement, not your solution we may be able to give other ideas.

A: You can consume the event

e.consume();


text:
Q: Can't Build my PDF I am trying to build my pdf but this issue comes up,

"
  Error : could not start the command : pdflatex -synctex=1 -interaction=nonstopmode "4.6 notes variation of parameters".tex
  "

I may have accidentally clicked F1 through F12 as I haven't used Texmaker in a long time trying to do a quick build.
Can someone help me interpret what this error means?


text:
Q: Why does oidcUserAuthority.getUserInfo() return null after upgrading to 5.6.9 and 5.7.5 I have upgraded from 5.6.2 due to the new vulnerabilities. I also upgraded the other dependencies. In version 5.6.2, oidcUserAuthority.getUserInfo() returns the correct values. But in the newer versions of the jar, it is always null. How do you handle it?
Already tried upgrading all other dependencies to the same version and also updated the spring-aop etc to 5.2.23

A: It's due to https://github.com/spring-projects/spring-security/issues/12144 - the fix is scheduled for the 5.6.10 release.


text:
Q: .js script not responding New to all of this and trying to get my .js script to work in Coda2. If anyone has any idea of why the .js script file is not responding, that would be great!
Thank you in advance!
<!DOCTYPE html>

    <title>Button Magic</title>
    <link rel='stylesheet' type='text/css' href='stylesheet.css' />

Click Me!

In the script:
$(document).ready(function() {
$('div').mouseenter(function() {
    $('div').fadeTo('fast',1);
});
$('div').mouseleave(function(){
    $('div').fadeTo('fast',0.5);
});

});
Please find the image here of my code:
http://postimg.org/image/qis0sitd1/

A: You haven't added a script tag to include jQuery.

A: You haven't included the Jquery lib, please include one.
eg: http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js

A: You have to include the jQuery library. You can use the Google CDN for that:
<!DOCTYPE html>

        <title>Button Magic</title>
        <link rel='stylesheet' type='text/css' href='stylesheet.css' />

Click Me!


text:
Q: angular ng-table does not sort I am having trouble sorting ng-table. I am not sure what's wrong here. Nothing happens when I click on a header.
I have this controller
'use strict';

import $ from 'jquery';
import angular from 'angular';

export default function(app) {
  app.controller('applicationsCtrl', function($scope, ngTableParams, applicationsFactory, $filter) {
    var vm = this;

    var apps = [{title: "Moroni", clientId: 50, blackListed: "no"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"},
                {title: "train", clientId: 30, blackListed: "Yes"} /*,*/];

$scope.tableParams = new ngTableParams({
                page: 1,
                count: 10
            }, {
                total: apps.length,
                getData: function ($defer, params) {
                    $scope.data = params.sorting() ? $filter('orderBy')(apps, params.orderBy()) : apps;
                    $scope.data = apps.slice((params.page() - 1) * params.count(), params.page() * params.count());
                    $defer.resolve($scope.data);
                }
            });
  });
}

this is what my partial view looks like

    <button class="btn btn-default btn-lg" type="button" ng-click="vm.registerApplication()">
       Register Applications
    </button>

          Application Title
          Application ClientId
          Blacklist Status

            {{application.title}}

            {{application.clientId}}

            {{application.blackListed}}

There are no error messages in the console so I am not sure what I am looking for here. Is it an error in my getData() function?

A: I had to remove the

 elements and just use the ng-title in the td, that did it for me.

    <button class="btn btn-default btn-lg" type="button" ng-click="vm.registerApplication()">
       Register Applications
    </button>

            {{application.title}}

            {{application.clientId}}

            {{application.blackListed}}


text: Q: I want to relocate my Logic Pro sound library to this WD hard drive that I briefly used as a time machine drive I understand that time machine hard drives can't be used for relocating Logic sound library, which explains why Logic errors saying it can't relocate to the drive. But considering that the drive is no longer time machine, I thought this was odd. I figured that maybe there was some meta  data on the drive that caused the system to think it was still time machine, so I went into the hidden folders and deleted all the weird time machine related files/folders. (.com.apple.timemachine.supported, .fseventsd, .Spotlight-V100, .Trashes, .DocumentRevisions-V100). After doing this I still get the same error. Maybe there's still some sort of time machine related meta data on the drive. Does any one have any ideas ?


text:
Q: Hibernate does not close my database query sessions, why? Comento un poco cómo está hecha mi aplicación: SpringBoot + Hibernate + Multitenant (DB master + DB for tenant) + Postgressql. I have two datasource configurations, one for the master and one for each client's database. To access the apis, A user logs in by obtaining an access token, which contains information from the tenant. Today the project is in an initial stage, we are very few people accessing the database (approx 3).
My
show max_connections;

In both databases it is 100
But I often skipped this error:
org.postgresql.util.PSQLException: FATAL: sorry, too many clients already.

And do :
SELECT COUNT(*) from pg_stat_activity;

It really is 99,  and pgadmin in service show
postgres - dashboard
but I don't understand why?
I leave the configuration code of the datasource
MASTER
public class MasterDatabaseConfig {

/**
 * Master database configuration properties like username, password, etc.
 */
@Autowired
private MasterDatabaseConfigProperties masterDbProperties;

/**
 * Creates the master datasource bean which is required for creating the entity
 * manager factory bean

 *

 * Note that using names for beans is not mandatory but it is a good practice to
 * ensure that the intended beans are being used where required.
 *
 * @return
 */
@Bean(name = "masterDataSource")
public DataSource masterDataSource() {

    HikariDataSource ds = new HikariDataSource();

    ds.setUsername(masterDbProperties.getUsername());
    ds.setPassword(masterDbProperties.getPassword());
    ds.setJdbcUrl(masterDbProperties.getUrl());
    ds.setDriverClassName(masterDbProperties.getDriverClassName());
    ds.setPoolName(masterDbProperties.getPoolName());

    // HikariCP settings
    // Maximum number of actual connection in the pool
    ds.setMaximumPoolSize(masterDbProperties.getMaxPoolSize());

    // Minimum number of idle connections in the pool
    ds.setMinimumIdle(masterDbProperties.getMinIdle());

    // Maximum waiting time for a connection from the pool
    ds.setConnectionTimeout(masterDbProperties.getConnectionTimeout());

    // Maximum time that a connection is allowed to sit idle in the pool
    ds.setIdleTimeout(masterDbProperties.getIdleTimeout());

    ds.addDataSourceProperty("test-on-borrow", true);
    ds.addDataSourceProperty("remove-abandoned", true);
    ds.setConnectionTestQuery("SELECT 1");
    // LOG.info("Setup of masterDataSource succeeded.");
    return ds;
}

/**
 * Creates the entity manager factory bean which is required to access the JPA
 * functionalities provided by the JPA persistence provider, i.e. Hibernate in
 * this case.

 *

 * Note the {@literal @}Primary annotation which tells Spring boot to
 * create this entity manager as the first thing when starting the application.
 *
 * @return
 */
@Primary
@Bean(name = "masterEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean masterEntityManagerFactory() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();

    // Set the master data source
    em.setDataSource(masterDataSource());

    // The master tenant entity and repository need to be scanned
    em.setPackagesToScan(
            new String[] { Tenant.class.getPackage().getName(), ITenant.class.getPackage().getName() });
    // Setting a name for the persistence unit as Spring sets it as
    // 'default' if not defined
    em.setPersistenceUnitName("masterdb-persistence-unit");

    // Setting Hibernate as the JPA provider
    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);

    // Set the hibernate properties
    em.setJpaProperties(hibernateProperties());

    return em;
}

/**
 * This transaction manager is appropriate for applications that use a single
 * JPA EntityManagerFactory for transactional data access.

 *

 * Note the {@literal @}Qualifier annotation to ensure that the
 * <tt>masterEntityManagerFactory</tt> is used for setting up the transaction
 * manager.
 *
 * @param emf
 * @return
 */
@Bean(name = "masterTransactionManager")
public JpaTransactionManager masterTransactionManager(
        @Qualifier("masterEntityManagerFactory") EntityManagerFactory emf) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);
    return transactionManager;
}

/**
 * Bean post-processor that automatically applies persistence exception
 * translation to any bean marked with Spring's @Repository annotation, adding a
 * corresponding PersistenceExceptionTranslationAdvisor to the exposed proxy
 * (either an existing AOP proxy or a newly generated proxy that implements all
 * of the target's interfaces).
 *
 * @return
 */
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
}

/**
 * The properties for configuring the JPA provider Hibernate.
 *
 * @return
 */
private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put(org.hibernate.cfg.Environment.DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
    properties.put(org.hibernate.cfg.Environment.SHOW_SQL, true);
    properties.put(org.hibernate.cfg.Environment.FORMAT_SQL, true);
    properties.put(org.hibernate.cfg.Environment.ENABLE_LAZY_LOAD_NO_TRANS, true);
    properties.put(org.hibernate.cfg.Environment.HBM2DDL_AUTO, "update");
    properties.put(org.hibernate.cfg.Environment.NON_CONTEXTUAL_LOB_CREATION, true);

    return properties;
}

Application.yml

spring:
  jpa:
    database: postgresql
    open-in-view: false
    show-sql: true
    generate-ddl: false
    jdbc:
        lob:
          non_contextual_creation: true
    hibernate:
      ddl-auto: update
      use_jdbc_metadata_defaults: false
    properties:
      hibernate:
        show_sql: true
        format_sql: true
        type: trace
  jackson:
    serialization:
      fail-on-empty-beans: false
      fail-on-self-references: false
      fail-on-unwrapped-type-identifiers: false

    visibility:
      field: any
    default-property-inclusion: non-empty
  application:
    name: '@pom.artifactId@'
    version: '@pom.version@'

multitenancy:
  mtapp:
    master:
      datasource:
        url: jdbc:postgresql://*******/masterdb
        username: *****
        password: *****
        driverClassName: org.postgresql.Driver
        connectionTimeout: 20000
        maxPoolSize: 262143
        idleTimeout: 300000
        minIdle: 1
        poolName: dbtest-connection-pool

Tenant
public class TenantDatabaseConfig implements ApplicationListener<ApplicationReadyEvent> {

@Bean(name = "tenantJpaVendorAdapter")
public JpaVendorAdapter jpaVendorAdapter() {
    return new HibernateJpaVendorAdapter();
}

@Bean(name = "tenantTransactionManager")
public JpaTransactionManager transactionManager(
        @Qualifier("tenantEntityManagerFactory") EntityManagerFactory tenantEntityManager) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(tenantEntityManager);
    return transactionManager;
}

/**
 * The multi tenant connection provider
 *
 * @return
 */
@Bean(name = "datasourceBasedMultitenantConnectionProvider")
@ConditionalOnBean(name = "masterEntityManagerFactory")
public MultiTenantConnectionProvider multiTenantConnectionProvider() {
    // Autowires the multi connection provider
    return crearDataSource();

}

@Bean(name = "datasource")
public DataSourceBasedMultiTenantConnectionProviderImpl crearDataSource() {

    return new DataSourceBasedMultiTenantConnectionProviderImpl();

}

/**
 * The current tenant identifier resolver
 *
 * @return
 */
@Bean(name = "currentTenantIdentifierResolver")
public CurrentTenantIdentifierResolver currentTenantIdentifierResolver() {
    return new CurrentTenantIdentifierResolverImpl();
}

/**
 * Creates the entity manager factory bean which is required to access the JPA
 * functionalities provided by the JPA persistence provider, i.e. Hibernate in
 * this case.
 *
 * @param connectionProvider
 * @param tenantResolver
 * @return
 */
@Bean(name = "tenantEntityManagerFactory")
@ConditionalOnBean(name = "datasourceBasedMultitenantConnectionProvider")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
        @Qualifier("datasourceBasedMultitenantConnectionProvider") MultiTenantConnectionProvider connectionProvider,
        @Qualifier("currentTenantIdentifierResolver") CurrentTenantIdentifierResolver tenantResolver) {

    System.out.println(" LocalContainerEntityManagerFactoryBean PASO");
    LocalContainerEntityManagerFactoryBean emfBean = new LocalContainerEntityManagerFactoryBean();
    // All tenant related entities, repositories and service classes must be scanned
    emfBean.setPackagesToScan(
            new String[] { Empresa.class.getPackage().getName(), IEmpresa.class.getPackage().getName() });
    emfBean.setJpaVendorAdapter(jpaVendorAdapter());
    emfBean.setPersistenceUnitName("tenantdb-persistence-unit");
    Map<String, Object> properties = new HashMap<>();
    properties.put(org.hibernate.cfg.Environment.MULTI_TENANT, MultiTenancyStrategy.DATABASE);
    properties.put(org.hibernate.cfg.Environment.MULTI_TENANT_CONNECTION_PROVIDER, connectionProvider);
    properties.put(org.hibernate.cfg.Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, tenantResolver);
    // ImprovedNamingStrategy is deprecated and unsupported in Hibernate 5
    // properties.put("hibernate.ejb.naming_strategy",
    // "org.hibernate.cfg.ImprovedNamingStrategy");
    properties.put(org.hibernate.cfg.Environment.DIALECT, "org.hibernate.dialect.PostgreSQL95Dialect"); // LUISINA
    properties.put(org.hibernate.cfg.Environment.SHOW_SQL, true);
    properties.put(org.hibernate.cfg.Environment.FORMAT_SQL, true);
    properties.put(org.hibernate.cfg.Environment.ENABLE_LAZY_LOAD_NO_TRANS, true);
    // properties.put(org.hibernate.cfg.Environment.USE_TRANSIENT_ANNOTATION, true);

    properties.put(org.hibernate.cfg.Environment.HBM2DDL_AUTO, "validate");
    properties.put(org.hibernate.cfg.Environment.NON_CONTEXTUAL_LOB_CREATION, true);

    emfBean.setJpaPropertyMap(properties);
    return emfBean;
}

@Autowired
@Qualifier("datasourceBasedMultitenantConnectionProvider")
MultiTenantConnectionProvider connectionProvider;

@Override
@ConditionalOnBean(name = "datasourceBasedMultitenantConnectionProvider")
public void onApplicationEvent(ApplicationReadyEvent event) {
}

}
Please, if anyone could help me. I am quite new to springboot.
Thank you.


text:
Q: As a library developer, how to prevent users from using an object across multiple Threads/Processes? I am building a library for Python and noticed that one of my users was using the objects incorrectly, by sharing it between 2 Processes.
So, I wanted to bake in a way to prevent the user from doing that.
One way would be to add a "check" before every method call, using a decorator, but that adds a bit of overhead on each method call.
import multiprocessing
import threading

def is_parent():
    return (
        multiprocessing.current_process().name == "MainProcess"
        and threading.current_thread() == threading.main_thread()
    )

def process_unsafe(fn):
    def wrapper(*args, **kwargs):
        if not is_parent():
            raise RuntimeError("Not allowed!")
        fn(*args, **kwargs)

    return wrapper

class NonProcessSafe:
    @process_unsafe
    def foo(self):
        pass

    @process_unsafe
    def bar(self):
        pass

nps = NonProcessSafe()

nps.foo()
nps.bar()

def child():
    # complains
    nps.foo()

p = multiprocessing.Process(target=child)
p.start()
p.join()

Is there any more efficient way to achieve this?

A: As @timgeb mentioned in the comments, there's probably no way to close all the loopholes. Furthermore I'm not sure I fully understand your problem and process/thread/state sharing model...
Anyway, here's an Ansatz that might get you somewhere, at least with regards to processes (in the Unix/Linux sense):
import os

class State:

    def __init__(self):
        self._pid = os.getpid()
        self._state = {}

    def __setitem__(self, key, value):
        if os.getpid() != self._pid:
            raise RuntimeError("this process must not change state")
        self._state[key] = value

The State instance remembers the ID of the process that created it, and can then check against that ID in all (relevant) methods. This will of course require the State be created by its "owner" process, in which case it is invisible to any parent or sibling process anyway, and visible only to itself and its children.
For threads, use threading.get_ident() instead of os.getpid().
If it is always the "main" process that creates the state and then forks worker children, instead you could (in the main process) temporarily mark the state as read-only, fork the worker child so it gets a read-only copy, and then in the main process switch state back to read-write:
class State:
    def __init__(self):
        self._read_only = False
        self._state = {}
    def __setattr__(self, key, value):
        if self._read_only:
            raise RuntimeError("read only!")
        self._state[key] = value

In main process:
def new_worker(fct):
    state = State()
    state._read_only = True
    pid = os.fork()  # or whatever you use to create a new process
    if pid:
        fct()  # state is _read-only=True here in child process
    else:
        state._read_only = False
        state_list.append((pid, state))


text:
Q: List of TFIDF points for Scikit Nearest Neighbor I can run kneighbors for one TFIDF but not for a list of them.
Before the details, I should mention the reason I am doing this is because running kneighbors for each data point is taking a very long time and I imagine giving kneighbors a list of points will be optimized internally.
Based on the NN documentation:
http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.NearestNeighbors.html#sklearn.neighbors.NearestNeighbors.kneighbors
It says I can query for multiple points:
>>>X = [[0., 1., 0.], [1., 0., 1.]]
>>>neigh.kneighbors(X, return_distance=False)
>>>array([[1],
   [2]]...)

I am trying to do the same.
I can run kneighbors for each point individually:
from sklearn.neighbors import NearestNeighbors
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer

samples = ["This is a test","a very good test","some more text"]
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(samples)
tfidf_transformer = TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
neigh = NearestNeighbors(n_neighbors=1, n_jobs=-1)
neigh.fit(X_train_tfidf)

ll=[]
test=["Test if this works","Zoom zoom"]
for k in test:
    predict = count_vect.transform([k])
    X_tfidf2 = tfidf_transformer.transform(predict)
    ll.append(X_tfidf2)
    res = neigh.kneighbors(X_tfidf2, return_distance=False)
#res = neigh.kneighbors(ll, return_distance=False)

When I add all the TFIDF sparse matrices to a list and try I get an error. Uncomment the last line to get error.
Error:
ValueError: setting an array element with a sequence (on the line res = neigh.kneighbors...)

A: try:
from scipy import sparse

from sklearn.neighbors import NearestNeighbors
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer

samples = ["This is a test","a very good test","some more text"]
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(samples)
tfidf_transformer = TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
neigh = NearestNeighbors(n_neighbors=1, n_jobs=-1)
neigh.fit(X_train_tfidf)

ll=[]
test=["Test if this works","Zoom zoom"]
for k in test:
    predict = count_vect.transform([k])
    X_tfidf2 = tfidf_transformer.transform(predict)
    ll.append(X_tfidf2)

ll = sparse.vstack((ll))
res = neigh.kneighbors(ll, return_distance=False)

Without the loop:
    from scipy import sparse
from sklearn.neighbors import NearestNeighbors
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer

samples = ["This is a test","a very good test","some more text"]
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(samples)
tfidf_transformer = TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
neigh = NearestNeighbors(n_neighbors=1, n_jobs=-1)
neigh.fit(X_train_tfidf)

test=["Test if this works","Zoom zoom"]
X_test_counts = count_vect.transform(test)

X_test_tfidf = tfidf_transformer.transform(X_test_counts)

res = neigh.kneighbors(X_test_tfidf, return_distance=False)


text:
Q: Bonjour/DNS-SD on Windows I'm currently working on a cross-platform application (Win/OSX/iOS) which has a C++ (with Boost) back end.  On iOS and OSX I'm using the Cocoa Net Service Browser Delegate functions to discover an embedded device via mDNS, then pass the information to the back end to create the objects it needs to communicate with it.
I wanted to take a similar approach with my Windows MFC front end and I found this article which seemed to do exactly what I want.  However, it seems that using the Bonjour SDK has some really nasty side effects - forcing you to static link to MFC and in my case the only way I can get it to link properly is to not use debug DLLs at all, which is not ideal.
So, the Bonjour SDK isn't really any good for me because it imposes too many restrictions on my project.  With Cocoa I'm actually using very little of the functionality - just didFindService and netServiceDidResolveAddress really.  All I want to do is find the devices of a given type and get their IP addresses.
Can anyone suggest another way around this that will work with an MFC front end on Windows?

A: From what I have been able to gather from researching this topic just goto http://www.opensource.apple.com/source/mDNSResponder/mDNSResponder-333.10/ and grab the source. There is a VC project file which will let you build the dll how you want.


text:
Q: Is it possible to retrieve private photos from facebook after logging in? I have on my website login with facebook.
After logging in I get a permit for access to information.
Can I retrieve private photos after logging in?

A: My guess is that it can't. Best way to find out for sure is to set up a test user, and see if your access token will let you find private pictures in the Graph Explorer.


text:
Q: Is the ribbon cable that connects screen and keyboard in a laptop changeable? I'm not sure if the word changeable even exsists, but it summarizes my question pretty well. I want to know if the ribbon cable connecting the keyboard to the displayer can be replaced.

A: In a laptop the screen and keyboard are connected to the mainboard. There is no cable between the display and the keyboard. Also the ribbon cable of the screen and the keyboard cannot be replaced. If you want to do that you have to replace the whole keyboard and/or screen.


text:
Q: Another python script puking ValueError: too many values to unpack I'm using python and the .py script is puking. Here is my output below:
reading file 'ConstantVel_Grid1.txt'...
Traceback (most recent call last):
  File "velocity.py", line 199, in <module>
    main(sys.argv)
  File "velocity.py", line 79, in main
    (timeInMyrs, moveFileName) = line.split()
ValueError: too many values to unpack

Here is some of the code it is referencing.
Line 199 and context (the last line of the script):
if __name__ == "__main__":
    main(sys.argv)

Line 79 and context:
allFiles = []

    while True:
        line = inputFile.readline().strip()
        if not line: # no more input left in file
            break

        (timeInMyrs, moveFileName) = line.split()
        allFiles.append((float(timeInMyrs), moveFileName))

    inputFile.close()

Here is a sample of the .txt file it is reading, which goes on for about 40 lines:
23.0 Grid1_Step0.dat
22.42 Grid1_Step1a.dat
21.84 Grid1_Step1b.dat
21.63 Grid1_Step1c.dat
20.68 Grid1_Step1d.dat

The .dat files are also space separated.
Any advice? The many other questions that have been answering this ValueError aren't making much sense for this as I am a noob and knee deep in python for the second time ever. Thanks!

A: It's telling you exactly what the problem is - "too many values to unpack".
When you .split() a string, it splits on whitespace and returns a list of items.
Somewhere you have a line with 3 or more pieces (maybe a filename with a space in it?), so you are effectively trying to
timeInMyrs, moveFileName = ["21.63", "my", "file.dat"]

and it crashes because you can't fit three values into two variables. To find the problematic line,
try:
    timeInMyrs, moveFileName = line.split()
except ValueError:
    print("Couldn't parse line '{}'".format(line.rstrip()))

And to solve the problem, either (a) avoid filenames with spaces in them, (b) enclose filenames in quotation-marks and use the 'csv' module to read the input file, or (c) use more tolerant line processing like
timeInMyrs, moveFileName = line.rstrip().split(None, 1)

which is guaranteed not to return more than two pieces.

A: The most likely cause for your problem is the the line.split() call is not resulting in the expected number of result substrings. Either the string you are splitting is the wrong string (bad input?) or there is a coding error...

A: try this
timeInMyrs, moveFileName = line.split()


text:
Q: Mesh generation algorithm gives visual artifacts Right now I am trying to implement terrain generation. I am using msvc visual studio 2019. And when I got to decreasing level of details in my function, generation started to be very glitchy. Everything is fine when I am not using any of level of details decreasing values. But everything changes after 1 and more - generation starts to be glitchy and generates atifacts. Here is some examples.
This one is correct as it should be. In my function this stands for parameter 0 in LevelOfDetails.

And Incorect examples. LevelOfDetails=1:

LevelOfDetails=3-6:

This is a function for generating meshes:
static void
GenerateTerrainMesh(world* World, noise_map* NoiseMap, float HeightMultiplier, int LevelOfDetail)
{
    int Width  = NoiseMap->Width;
    int Height = NoiseMap->Height;
    //float TopLeftX = (Width - 1)  / (-2.0f);
    //float TopLeftZ = (Height - 1) / ( 2.0f);

    if(LevelOfDetail < 0) LevelOfDetail = 0;
    if(LevelOfDetail > 6) LevelOfDetail = 6;

    int SimplificationInc = (LevelOfDetail == 0) ? 1 : (LevelOfDetail * 2);
    int VerticesPerLineX  = (Width  - 1) / SimplificationInc + 1;
    int VerticesPerLineY  = (Height - 1) / SimplificationInc + 1;

    InitializeMeshTerrain(World, VerticesPerLineX, VerticesPerLineX);

    int VertIndex = 0;
    int TrigIndex = 0;
    for(int Y = 0; Y < Height; Y += SimplificationInc)
    {
        for(int X = 0; X < Width; X += SimplificationInc)
        {
            World->Terrain.Vertices[VertIndex] = V3((float)X, HeightMultiplier * HeightFlatten(World->NoiseMap.Values[Y*World->NoiseMap.Width + X]).y * HeightMultiplier, (float)Y);
            World->Terrain.UVs[VertIndex]      = V2(X/(float)Width, Y/(float)Height);

            if((X < (Width - 1)) && (Y < (Height - 1)))
            {
                AddTriangle(World, &TrigIndex, VertIndex, VertIndex + VerticesPerLineX + 1, VertIndex + VerticesPerLineX);

                AddTriangle(World, &TrigIndex, VertIndex + VerticesPerLineX + 1, VertIndex, VertIndex + 1);
            }

            VertIndex += 1;
        }
    }
}

And helper functions, but there should not be any errors:
static void
InitializeMeshTerrain(world* World, int Width, int Height)
{
    World->Terrain.VerticesCount = Width * Height;
    World->Terrain.FacesCount    = (Width - 1)*(Height - 1)*2;
    World->Terrain.UVCount       = Width * Height;

    World->Terrain.Faces    = (face*)malloc(sizeof(face)*World->Terrain.FacesCount);
    World->Terrain.Vertices = (v3*)malloc(sizeof(v3)*World->Terrain.VerticesCount);
    World->Terrain.UVs      = (v2*)malloc(sizeof(v2)*World->Terrain.UVCount);
}

static void
AddTriangle(world* World, int* Index, int a, int b, int c)
{
    World->Terrain.Faces[*Index].a = a;
    World->Terrain.Faces[*Index].b = b;
    World->Terrain.Faces[*Index].c = c;

    *Index += 1;
}

What problem could be there? Thank you.
UPD: I added some additional data to work with such as Mesh Data and Vertices Data for each LevelOfDetail:
Correct:
LevelOfDetail=0
Incorect 1:
Incorect LevelOfDetail=1
Incorect 4:
Incorect LevelOfDetail=4
Incorect 6:
Incorect LevelOfDetail=6

A: Like PaulMcKenzie mentioned, seams that I just used Even Numbers instead of Odd numbers and that was entirely of the problem. And even more, sometimes It couldn't work correctly, because I used too small numbers for generating mesh grid like 90 or 100. So, for correct working of this mesh algorithm Width should be divisible on 1, 2, 4, 6, 8, 10 and 12, and then It should work pretty fine


text:
Q: how to add format plain text to Outlook command line parameters in my code . i'm using cmd to start outlook:
cmd /c start outlook /c ipm.note /m "onakajima@a-i-s.co.jp;?cc=;&subject=【依頼】見積依頼について&body=aaa"
start outlook with command line
But it start with format html
outlook init with mode format html
I want to sart cmd with this code and auto  open outlook start with mode: plain/text
can anyone help me pass agrument to cmd to open open outlook start and auto select with mode: plain/text ?
start init out look with plain text

A: The Outlook command line doesn't provide all the options as command line switches. Instead, you may try using the mailto protocol which opens a client's e-mail system and begins a new email message. For example, the following example shows a link that will prepare an e-mail message:

    Contact Us


text:
Q: Get Jacoco coverage report in xml format I want to get the jacoco code coverage report in an xml format.
Ex:
My app:
package pac1
Class Class1{
public void method1(){}
}

My test:
@Test
public void test1(){
Class1 class1=new Class1();
class1.method1();
}

I want to get the coverage report like this:
<package=pac1>
<class=class1>
<method=mehtod1>
</package>

Please let me know if there is a way of getting this.
My setup:
The app code is deployed on one box and it is instrumented. The test suite runs on a CI job.
Thanks
Kiran


text:
Q: Regex to search and replace a character in a string C# I'm trying to search for a comma in a string, and then "delete" it (replaced it with "", I'm assuming). I'm really bad with regular expressions though, and am needing a little help coming up with a general way to do this. I believe Regex has a Replace method, right? Any leads?

A: Why not just normal string.Replace()?
var result = str.Replace(",", string.Empty);

A: If you still want to use regular expression, try this
        static void Main(string[] args)
    {
        Regex regex = new Regex(@"\,");
        Console.WriteLine(regex.Replace("sample, text", string.Empty));
        Console.ReadLine();
    }


text:
Q: EXC_BAD_ACCESS with worldweatheronline API In my iOS app I'm using the weather APIs of worldweatheronline.com but I get a random  "EXC_BAD_ACCESS" error oh this row (not always but sometimes) :
temperature.text = [NSString stringWithFormat:@"%@ °C", tempC];

Here is my code:
- (void)showWeatherFor:(CLLocation *)newLocation
{
NSString *myRequestString = [[NSString alloc] initWithFormat:@"http://api.worldweatheronline.com/free/v1/weather.ashx?q=%f,%f&format=json&num_of_days=5&key=ydvgep8jn5m846upd8kb2qp6", newLocation.coordinate.latitude, newLocation.coordinate.longitude];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:myRequestString]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *JsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *theDictionary = [NSDictionary dictionaryWithJSONString:JsonString error:&error];
NSDictionary *data = [theDictionary objectForKey:@"data"];
NSArray *currentDictionary = [data objectForKey:@"current_condition"];
NSDictionary *temp = [currentDictionary objectAtIndex:0];

if ([temp objectForKey:@"temp_C"] == nil || [temp objectForKey:@"temp_F"] == nil)
{
    return;
    termometro.alpha = 0;
}
else
{
    if (temp != nil)
    {
        if ([mainDelegate.gradi isEqualToString: @"°C"])
        {
            NSNumber *tempC = [temp objectForKey:@"temp_C"];
            temperature.text = [NSString stringWithFormat:@"%@ °C", tempC];
            mainDelegate.temperature = [[temp objectForKey:@"temp_C"]intValue];
        }
        else
        {
            NSNumber *tempF = [temp objectForKey:@"temp_F"];
            temperature.text = [NSString stringWithFormat:@"%@ °F", tempF];
            mainDelegate.temperature = [[temp objectForKey:@"temp_F"]intValue];
        }
        termometro.alpha = 1;
    }
}

}


text:
Q: Get MIME Type via PHP I have local access to files, which I need to get their MIME types. Working in WAMP/LAMP, CodeIgniter, and Zend libraries. What's the best way to get MIME type information?

A: There's no easy way. You could try:
http://www.php.net/manual/en/function.finfo-file.php
// return mime type ala mimetype extension
$finfo = finfo_open(FILEINFO_MIME_TYPE);

Of course, this assumes you can install PECL extensions.

A: I think you need head. Quickest way is to do a head request, or in PHP under apache you can use apache_lookup_uri or in PHP 5.3 you can use FileInfo (I'd still recommend apache_lookup_uri or a simple head request though).

A: Its never a good idea to try and find the mime type based on the file extension, as this can obviously be renamed by the used whos uploading - from .exe to .jpg
Real mime type detection is part of your overall security measures.

A: Parse your Apache's mime.types file.

A: Try CI's built in function "get_mime_by_extension($file)".  You can find it in the "system/helpers/file_helper.php" file


text:
Q: Tensorflow shared queue in PS server with reader in workers I am running a distributed Tensorflow program with large input files (150 MB per example).
I wish to have a shared input queue for file names in the PS in order for the workers to work on different examples.
I want the CPU of each worker to then read the shared input queue and generate data for the GPU to process.
The code below is only run by the workers:
with tf.Graph().as_default():

    with tf.device('/job:ps/replica:0/task:0'):
        file_queue =tf.train.string_input_producer(file_paths, shared_name='train_queue')

    with tf.device('/cpu:0'):
        input_tensors = model.input_fn(file_queue, ...)

    # sets variables to PS and ops default to GPU
    with tf.device(tf.train.replica_device_setter(cluster=cluster_spec)):
        output_tensors = model.model_fn(input_tensors, ...)

However, the Reader() for file_queue (which is inside model.input_fn()) is being placed in the PS instead of in the workers' CPUs, as treid to specify using tf.device().
This causes 150 MB messages being sent between the PS and the workers, which slows down training (I only notice this because google-cloud ml engine raises a warning when large messages are being sent).
Why is the Reader() not being placed on the workers' CPU?
Is it mandatory for a queue and its reader to be on the same device?
Here is a link to my previous context which might provide more context.
Here is the code for input_fn():
def input_fn(file_queue, ...):

    reader = tf.TFRecordReader()
    _, example = reader.read(file_queue)

    image, ground_truth = my_decoder(example)
    image, ground_truth = tf.train.shuffle_batch([image, ground_truth], ...)
    return image, ground_truth

The problem is tf.TFRecordReader() is being placed in the PS. All the other ops (decoder and batch) are correctly placed in the workers' CPUs.


text:
Q: How to build Instant Messenger in iPhone? I'm looking into building an IM-type application for iPhone using Objective-C. I'd be interested to see any information/advice on how applications like Skype/AIM/MSN work, as well as any technologies/APIs that might be relevant.

A: The main protocol used to connect to those services (or even your own) is XMPP (also known as Jabber.
It connects to a Jabber/XMPP server that manages the sessions.
XMPP works with Skype, Google Talk, Facebook chat and many more.
I've successfully implemeted a google chat app using this open source XMPP library that fits in very well into iPhone:
http://code.google.com/p/xmppframework/wiki/iPhone
Update

Library now moved to GitHub: github.com/robbiehanson/XMPPFramework as Raspu pointed out
You should be able to rather easily get that up and running. It even comes with a Google talk example.

A: You can use Kik API to build your mobile app on top of Kik's instant messaging transport and infrastructure. The API is available for Android & iPhone and lets your app to transfer rich content and files in between mobile app users. It is also very easy to use - only 5 lines of code are needed to integrate, in simpler scenarios. There's more info on Kik API website: http://www.kik.com/dev or http://apiblog.kik.com
Disclaimer: I'm one of the developers behind Kik API :)

A: Are you set on building your own instant messenger or are you looking for the code to put into your app?
I came across an interesting article from someone who seems to have been looking for the same thing as you, he looks at the problems different open source instant messenger codes have and how to try to pull them together:
my-quest-make-messaging-app-ios
There are also chat components available to buy ready-made which have the advantage of not requiring the time to develop and bug test. For example:
chat-messaging-sdk-for-ios


text:
Q: Microphone array support in Windows. Info on performance and compatible hardware? It is officially claimed by Microsoft (Audio Device Technologies for Windows), that Windows Vista has an integrated system-level support of microphone arrays for improved sound capturing by isolating a sound source in target direction and rejecting ambient noise and reverberation. In more technical terms, an implementation of an adaptive beamformer.
Theoretically, microphone arrays with 2-4 mics can substantially improve SNR under some conditions like speaker in front of the laptop in noisy environment (airport, cafe). Surprisingly, though, I find very little information about commercially-available products supporting these new features. I mean products like portable usb micropone arrays or laptops or flat screens with integrated mic arrays. I could only find info about two laptop models having "noise cancelling digital array microphone". These are  Dell Latitude and Eee PC 1008P-KR.
Now my questions:

*

*Do you have any experience with the Windows beamformer implementation? For instance, in the above mentioned laptops. How well does it work? Are there any tests results available in the net or in print (papers?)?

*Do you know about other microphone array hardware?

*What could be the reason why mic array technology didn't get sucess

*Is there mic arrays support in 'Windows 7'?

A: My motherboard Asus P5B Deluxe came with SoundMax SuperBeam directional mic. I'm not a sound engineer to know 100% that it's really a "directional array" microphone. However, it works well enough for Skype and other voice chat.
It looks like this

While Windows 7 does not natively recognize it as an "array" mic, there are drivers for it that add some of this functionality:

Their website at http://andreaelectronics.com has some more various (supposedly) directional array mics.

A: Just so you know , Microsoft Kinect has a 4 microphone array and it's compatible with windows 7 , you can easily get the direction of the sound from Microsoft Kinect SDK .


text:
Q: merging two owl files and eliminate common classes in one file I am very new to web ontology languages, I have created owl files using protege and I have to write a program that should merge these files into one. Is it possible with jena? Can anyone help with how to proceed?Can I do that in java using owl API?
thanks in advance.

A: I was able to solve it with protege and it works. Thanks for all the comments and contributions. It helped a lot. :-)


text:
Q: How to obtain the $dC_d/dC_l^2$ value from the drag polar of an airfoil? I'm currently trying to do an initial design for a propeller. In order to do this I'm trying to use Xrotor. Xrotor allows the user to enter certain information about both the propeller geometry, flight conditions and the airfoil lift and drag data after which it performs its calculations. Xrotor requires the following values for the lift and drag data (example values are given):
========================================================================
1) Zero-lift alpha (deg):   0.00       7) Minimum Cd           : 0.0070
2) d(Cl)/d(alpha)       :  6.280       8) Cl at minimum Cd     : 0.150
3) d(Cl)/d(alpha)@stall :  0.100       9) d(Cd)/d(Cl**2)       : 0.0040
4) Maximum Cl           :  2.00       10) Reference Re number  : 2000000.
5) Minimum Cl           : -1.50       11) Re scaling exponent  : -0.2000
6) Cl increment to stall:  0.200      12) Cm                   : -0.100
                                      13) Mcrit                :  0.620
========================================================================

This information can be obtained from the drag polars of the airfoil.
$\alpha,C_l$ plot">
$C_d,C_l$ plot">
[
The 360 degree polar was made using JBlade. The only value that Xrotor requests that I am not sure on how to calculate is the d(Cd)/d(Cl^2) figure. I'm fairly confident that this can be obtained using the $C_d,C_l$ drag polar, but I'm not completely confident on how I should go about it. What is the correct way of determining this value?

A: This value can be found by performing analyses at multiple $\alpha$, after which the $C_d$ and $C_l$ values at those $\alpha$ can be found. Then you can plot the $C_d$ on the $y$-axis and the $C_l^2$ on the $x$-axis and then the slope of the graph represents the $dC_l/dC_l^2$ value. This should be constant across the linear part of the lift slope and is in the order of magnitude of $0.004$.

A: First, get the best fit for
$$C_D=C_{D0}+k_1\cdot C_L+k^2 C_L^2 \tag{1}$$
 using the limits of the linear zone of the lift curve for $c_l$.
Then, $d(C_d)/d(C_l^2)$ is just the coefficient $b$ of the equation:
$$C_D=C_{Dmin}+b(C_{Lo}-C_L)^2, \tag{2}$$
which is just another form of (1). So, to find $b$, just expand (2), equal the equations and solve for $b$. The results are:
$C_{Dmin}=C_{D0}-\frac{k_1^2}{4k_2}$;
$C_{Lo}=-\frac{k_1}{2k_2}$ and $b=k_2$


text:
Q: Socket server in Java, The last client connected is the only can read the socket I have a problem with a socket server that I'm developing.
Firstly, the socket server has then follow class:

*

*Class Main_Servidor (Execute the server)

*Class EjecutarServidor (Basically waiting for new connections and then run them as a sub-process)

*Class ManejoConexion (receives a socket object from home, and writes and reads in the socket)

*Class Panel_mensajes (Shows info about the socket connections in a jpanel)

*The client is a little program written in adobe air
The problem is when two or more clients are connected, only the last connected client can read the socket. I've already used the eclipse's debugger for check step by step, but I can't found the error.
Here is my code:
Main_Servidor Class:
public class Main_Servidor {

    public static void main(String[] args) {

        Panel_mensajes PanelMensajes = new Panel_mensajes();
        PanelMensajes.setVisible(true);

        EjecutarServidor ejectuarservidor = new EjecutarServidor();

        ejectuarservidor.ejecutar();

    }

}

EjecutarServidor Class:
public class EjecutarServidor {

    private static final int puerto = 1025;
    private static final int conexionesMaximas = 3;

    private ExecutorService iniciarThread;
    private static ServerSocket listener;
    private static Socket socket;
    private static boolean EsperarConexiones = true;

    public EjecutarServidor()
    {
        //Crea la pila de sub-procesos y se la asigna al objeto iniciarThread
        iniciarThread = Executors.newFixedThreadPool(conexionesMaximas);
    }

    public void ejecutar()
    {

        Panel_mensajes.MostrarMensaje("ESPERANDO CONEXIONES...\n\n");

        try{

            listener = new ServerSocket(puerto); //Esta a la escucha de nuevas conexiones
                                                 //en el puerto especificado.

            GregorianCalendar fecha = new GregorianCalendar(); //Genera la fecha incluyendo la hora

            while(EsperarConexiones){ //Mientras EsperarConexiones sea TRUE esperará por
                                      //nuevas conexiones.
                socket = null;
                socket = listener.accept(); //Acepta la nueva conexión y la asigna a un objeto socket

                //Muesta en pantalla los datos de la nueva conexión
                Panel_mensajes.MostrarMensaje("NUEVA CONEXION " +
                        socket.getInetAddress().toString().replace("/", "") + ":"
                        + socket.getPort() + ", "
                        + fecha.getTime() + "\n" + "\n"
                    );

                //Se crea un nuevo objeto ManejoConexion al cual se le pasa como parametro
                //el objeto socket llamado 'socket' que contiene la nueva conexión
                ManejoConexion con_nva = new ManejoConexion(socket);

                //Ejecuta el nuevo objeto ManejoConexion como un nuevo sub-proceso.
                iniciarThread.execute(con_nva);

            }

        } catch (IOException ioe) {
            Panel_mensajes.MostrarMensaje("IOException en socket!: * " + ioe);
        }
    }

    //Deja de escuchar nuevas peticiones
    public static void cerrarServidor()
    {
        try
        {
            EsperarConexiones = false;
            listener.close();
            socket.close();

        }catch(SocketException SoE)
        {
            Panel_mensajes.MostrarMensaje("SocketException por cerrar servidor, todo OK");
            //SoE.printStackTrace();

        }catch(IOException ioe)
        {
            Panel_mensajes.MostrarMensaje("IOException por cerrar servidor, todo OK");
            //ioe.printStackTrace();
        }finally
        {
            System.exit(0);
        }

    }

}

ManejoConexion Class:
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

public class ManejoConexion implements Runnable {

    private Socket server;
    private String line;
    private DataInputStream in;
    private static PrintWriter out;
    private static Protocolo proto;
    private static Boolean ACTIVO = true;

    ManejoConexion(Socket server) throws IOException {

        //Recibe un objecto Socket e inicializa la variable server
        this.server = server;

    }

    //Hace que se ejecute un objeto de esta clase como un sub-proceso
    public void run () {

        try {

            //Recibe las tramas de datos desde el servidor
            in = new DataInputStream (server.getInputStream());

            //Envia tramas de datos al servidor
            out = new PrintWriter(server.getOutputStream());

            this.responderPeticiones("+OK");

            //Mantiene abierto el flujo de datos desde el servidor mientras no se cumplan las
            //condiciones.
            Panel_mensajes.MostrarMensaje(Thread.currentThread() + "\n");

            while((line = in.readLine()) != null && !line.equals("TERM")) {

                //Panel_mensajes.MostrarMensaje("CLIENTE " + server.getInetAddress().toString().replace("/", "") + " DICE -> " + line + "\n");
                //proto.entrada(line);

                this.responderPeticiones(line);

                if(!ACTIVO) break;

            }

            this.responderPeticiones("\n" + "CONEXION TERMINADA: " + server.getInetAddress().toString().replace("/", ""));

            Panel_mensajes.MostrarMensaje("\n" + "CONEXION TERMINADA: " + server.getInetAddress().toString().replace("/", "") + "\n" + "\n");
            server.close();

        } catch (IOException ioe) {
            Panel_mensajes.MostrarMensaje("\nIOException AL RECIBIR PETICION: " + ioe.getMessage());
            //ioe.printStackTrace();
        }

    }

    //Se encarga de responder peticiones a los clientes
    public void responderPeticiones(String s) throws IOException
    {
        String input = s;
        String direccion = server.getInetAddress().toString().replace("/", "");

        out.write("SERVIDOR DICE A " + direccion + " -> " + input + "\n");
        out.flush();

    }

    public static void TerminarConexion()
    {
        ACTIVO = false;
        proto = null;

    }

}

(I didn't add the Panel_mensajes class, because is not much relevant)

A: In your ManejoConexion class, you have 3 static variables that shouldn't be. Especially the PrintWriter, which will be set to the Socket's output stream of the LAST instance, thus the first instance will suddenly start talking to the last one.
Actually, I'm not sure what proto and ACTIVO are for, but the out static variable should definitely not be static.

A: It's not easy to understand your code (I guess it's portuguese or spanish). The problem seems to be in EjecutarServidor, you have 3 static attributes:
private static ServerSocket listener;
private static Socket socket;
private static Boolean EsperarConexiones

If a new client connects you simply reset the reference to the client former socket by:
socket = null;
socket = listener.accept();

This may not work when several clients connect concurrently as the reference to socket may break between
socket = listener.accept();

and
ManejoConexion con_nva = new ManejoConexion(socket);

Defining listener as a static attribute is definitely not a good practive, but should work given your samples. But defining the static socket is definitely an error and may lead to unexpected results. You should move the Socket declaration into EjecutarServidor.ejecutar() like:
       while(EsperarConexiones){

            Socket socket = listener.accept(); //<-- fix HERE

            Panel_mensajes.MostrarMensaje("NUEVA CONEXION " +
                    socket.getInetAddress().toString().replace("/", "") + ":"
                    + socket.getPort() + ", "
                    + fecha.getTime() + "\n" + "\n"
                );

            ManejoConexion con_nva = new ManejoConexion(socket);
            iniciarThread.execute(con_nva);
        }

Fix this and see if it changes your app's behaviour.

A: Pay attention to private static PrintWriter out; in ManejoConexion - it should not be static.


text:
Q: onSaveInstanceState doesn't work when screen rotates ...  Toast print nothing !
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    String a  = savedInstanceState.getString("hello");
    Toast.makeText(MainActivity.this, a, Toast.LENGTH_SHORT).show();

}

@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    super.onSaveInstanceState(outState, outPersistentState);
    String a = "WTF";
    outState.putString("hello",a);
}

}
I declared everything nicely,, where is the bummer in this simple code !?

A: I think you've fallen into a really common trap many devs have since the Android OS team overloaded the onSaveInstanceState() method.
You are overriding the wrong method. The one you want is:
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    String a = "WTF";
    outState.putString("hello",a);
}

Personally, I think Craig Mautner should be forced to donate money every time an Android developer makes this mistake - source

A: Same problem
Try to change to this
    @Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    String a = "WTF";
    outState.putString("hello",a);
}


text:
Q: PHP won't echo HTML with Checkbox Array Results I am stumped!!! I'm get the results beautifully, but I cannot get the associated text to show up "ONLY" when something is selected by the user. As it is now, the text is static and shows ALL the time, with or without a selected answer from the user.
Ex. "What Kind of Animal:" Is on the results page, even if the user does not select an answer for it! That's what needs to not show if there's no related answer.
My HTML:

What Kind of Animal

What kind of animal has your pet bitten? Check all that apply:

    <input class="form_style" type="checkbox" value="Wild" id="Wild" name="whatKindofAnimal[5]" />Wild

    <input class="form_style" type="checkbox" value="Bird" id="Bird" name="whatKindofAnimal[4]" />Bird

    <input class="form_style" type="checkbox" value="Cat" id="Cat" name="whatKindofAnimal[3]" />Cat

    <input class="form_style" type="checkbox" value="Dog" id="Dog" name="whatKindofAnimal[2]" />Dog

    <input class="form_style" type="checkbox" id="Other-Animal" name="whatKindofAnimal[1]" onclick="if(!this.checked) document.getElementById('otherKindofAnimal').value='' " />Other

    <input class="form_style" type="text" placeholder="Please Specify" id="otherKindofAnimal" name="whatKindofAnimal[1]" />

PHP:

    <?php if (isset($_POST['whatKindofAnimal'])) {echo 'What Kind of Animal: '; $name = $whatKindofAnimal = implode(', ', array_filter($_POST['whatKindofAnimal'])); echo htmlspecialchars($whatKindofAnimal);} ?>

I have been using the first part of this PHP code for the radio buttons throughout my whole page and it works perfectly! This is how I have it set elsewhere for radio buttons... and the associated text only shows up when the user as actually selected an answer.

    <?php if (isset($_POST['bite-reported-human'])) {echo 'Bite Reported: '; echo htmlspecialchars($_POST['bite-reported-human']);} ?>

In this case, "Bite Reported:" Remains invisible on results page unless an answer has been selected for it.
Please help????
Thank You in Advance,
Tracy

A: Dude the problem is the input field
<input class="form_style" type="text" placeholder="Please Specify" id="otherKindofAnimal" name="whatKindofAnimal[1]" />

Even though this field is empty it will send a data through $_POST, you can test it by print_r($_POST) an empty string will be at $_POST['whatKindofAnimal'][1] so try this
replace
if (isset($_POST['whatKindofAnimal']))

with
if (count($_POST['whatKindofAnimal'])>1)

because isset($_POST['whatKindofAnimal']) will be always true cause there will be always a value in $_POST['whatKindofAnimal'][1]

A: As the 'Other-Animal' is a text field, it gets submitted even when empty, making $_POST['whatKindofAnimal'] == array([1]=>''), so the isset code will run.
There are probably lots of solutions, but a quick one is to change the name of the Other-Animal field and display that if Other is checked
/*form adjustments*/
<input class="form_style" type="checkbox" id="Other-Animal" name="whatKindofAnimal[1]" value="Other: " />Other

<input class="form_style" type="text" placeholder="Please Specify" id="otherKindofAnimal" name="textForOther" />

/*addition to your if(isset) php*/
if(array_key_exists(1,$_POST['whatKindofAnimal']))
        echo $_POST['textForOther'];

This will have the results displayed as Other: {input} if other is selected, and won't show up at all if none of the checkboxes are clicked.


text:
Q: WordPress homepage too slow, posts work fine? Framework issue? I have been searching solution for the issue of slow server response for my wordpress website https://www.pointmovies.com/
Homepage is taking 6 to 7 seconds to load, but the posts do not take that long. There is no late server response for posts.  I have made some tests:
For homepage: https://tools.pingdom.com/#!/cxw0LG/http://www.pointmovies.com/
For Posts: https://tools.pingdom.com/#!/dF8QGr/https://www.pointmovies.com/movie/dangal-2016/
Is this any framework issue, caused by theme? or something else?

A: You have a LOT of images on the homepage. A quick glance at gtMetrix shows that compressing those images could save megabytes on the home page load time.
I'd also recommend a WordPress caching plugin. I prefer Comet Cache, but try a few and see which one fits your skill level and performs best for you.


text:
Q: Sticky session behind proxy for two apps He have two web apps: app A and app B. They are both installed in server 1 and server 2 (so one instance of A in server 1, one instance of A in server 2. same for app B). App A navigates to app B via SSO.
We use F5 load balancer to distribute the requests, and we are not sure on how to implement the sticky session in that case, as first, we cannot do IP based, as the are behind a reverse proxy, hence, the IP would always be the same.
Also, seems like the cookie option does not working when navigating from app A to app B.
(I am not a load balancer specialist... hopefully, I provided all info required).
Any advice on this would be greatly appreciated.
Design as below
 ---------------             server 1
| load balancer | ---->      App A ->(SSO)-> App B
 ---------------
                             server 2
                             App A ->(SSO)-> App B

Thank you in advance!


text:
Q: Replacing every nth occurence of old I am trying to replace every nth occurrences of old with new with lst as a list that can be list of atoms or list of lists. I am having trouble replacing the nth occurrence of old with new when lst is a list of lists.
(define (replace lst n old new)
  (cond ((null? lst) '())
        ((and (= n 1) (eq? (car lst) old)) (cons new (cdr lst)))
        ((not (atom? (car lst)))
          (cons (replace (car lst) n old new) (replace (cdr lst) n old new)))
        ((and (atom? (car lst)) (eq? (car lst) old)) (cons old (replace (cdr lst) (- n 1) old new)))
        (else (cons (car lst) (replace (cdr lst) n old new)))))

Calling the function above
(replace '(a b c a d e f g a t y a g) '3 'a 'o)

give me (a b c a d e f g o t y a g), but when I input a list of lists I am unable to get the correct output
(replace '((a a) b c a d e f g a t y a g) '3 'a 'o)

This is probably because when my function goes into the list (a a) my n counter that got decremented does not get returned. Is there a way to pass the n counter?

A: When you replace an old value with a new value, you return (cons new (cdr lst)).
The problem is that you don't replace any remaining occurences in (cdr lst).
Try something like (cons new (replace (cdr lst) original-n old new ).
You will need the original n, so you can do something like this:
(define (replace lst n old new)
  (replace-helper lst n n old new))

(define replace-helper lst original-n n old new)
    ...your existing solution where replace has been
       renamed to replace-helper...))

A: In order to pass the current n from processing the car to the cdr you need either have the helper return both the result and the current n.
As an example here is something that replaces every match in a tree with its item number:
(define (replace-with-index haystack needle)
  (define  (result n value) value)
  (let loop ((lst haystack) (n 0) (k result))
    (if (null? lst)
        (k n '())
        (let ((a (car lst)) (d (cdr lst)) (nn (+ n 1)))
          (cond ((equal? needle a)
                 (loop d nn (lambda (cn r) (k cn (cons n r)))))
                ((not (pair? a))
                 (loop d nn (lambda (cn r) (k cn (cons a r)))))
                (else
                 (loop a n (lambda (cn ar)
                             (loop d cn (lambda (cn dr)
                                          (k cn (cons ar dr))))))))))))

(replace-with-index '(a (a b (h e)) (c d (h e) l l)) '(h e))
; ==> (a (a b 3) (c d 6 l l))

The technique is called continuation passing style. You could do it without by having it return both the current n and result:
(define (replace-with-index haystack needle)
  (define (helper lst n)
    (if (null? lst)
        (values n '())
        (let ((a (car lst)) (d (cdr lst)) (nn (+ n 1)))
          (cond ((equal? needle a)
                 (let-values ([(cn r) (helper d nn)])
                   (values cn (cons n r))))
                ((not (pair? a))
                 (let-values ([(cn r) (helper d nn)])
                   (values cn (cons a r))))
                (else
                 (let*-values ([(an ar) (helper a n)]
                               [(dn dr) (helper d an)])
                   (values dn (cons ar dr))))))))
  (let-values ([(n r) (helper haystack 0)])
    r))

The difference between this and the CPS version is just style. As many Scheme implementations actually turn the code into CPS the code executed would be almost identical. As a last example I've removed the multiple values and used encapsulation in forms of cons.
(define (replace-with-index haystack needle)
  ;; abstraction
  (define nrbox cons)
  (define nrbox-n car)
  (define nrbox-r cdr)

  (define (helper lst n)
    (if (null? lst)
        (cons n '())
        (let ((a (car lst)) (d (cdr lst)) (nn (+ n 1)))
          (cond ((equal? needle a)
                 (let ((nr (helper d nn)))
                   (nrbox (nrbox-n nr) (cons n (nrbox-r nr)))))
                ((not (pair? a))
                 (let ((nr (helper d nn)))
                   (nrbox (nrbox-n nr) (cons a (nrbox-r nr)))))
                (else
                 (let* ((anr (helper a n))
                        (dnr (helper d (nrbox-n anr))))
                   (nrbox (nrbox-n dnr) (cons (nrbox-r anr) (nrbox-r dnr)))))))))
  (nrbox-r (helper haystack 0)))

Basically this cons a lot of temporary pairs while the multiple value and CPS version keeps the values on the stack. Thus the difference is in performance. In form of abstraction they are completely the same code.


text:
Q: can not ping by host name for some computers I have 11.04 installed.
It is joined to a domain. I am able to ping some of my computers by their name, but some I can't.
Those I can't are our NAS machines (Readynas Netgear). I can ping them only by IP from my Ubuntu machine. But I can ping them regularly by host name, from any other windows machine.
Please advise what should I check?

A: Just add WINS to the hosts: line in the /etc/nsswitch.conf file:
# /etc/nsswitch.conf
#
# Example configuration of GNU Name Service Switch functionality.
# If you have the `glibc-doc-reference' and `info' packages installed, try:
# `info libc "Name Service Switch"' for information about this file.

passwd:         compat lsass
group:          compat lsass
shadow:         compat

hosts:          files mdns4_minimal [NOTFOUND=return] wins dns mdns4
networks:       files

protocols:      db files
services:       db files
ethers:         db files
rpc:            db files

This tells the system to use WINS in order to lookup netbios. The winbind package has to be installed for this to work.

A: For a more hackish method then the one listed by @Saariko you could edit your hosts file. This is not a robust solution and has to be updated manually, if your network set up changes.
It can also hide network problems if names don't resolve correctly through other tools like wins and dns
Host file on Ubuntu and many other *nix is found

/etc/hosts

In windows the hosts file is usually found

C:\WINDOWS\system32\drivers\etc\hosts
  %systemroot%\system32\drivers\etc\hosts

To make changes in Ubuntu edit the file and put in the ip address and hostnames you want.

sudo vi /etc/hosts
  192.168.1.1  servername
  192.168.1.2  server2name

In my host file I add all the web severs I set up for my web development

127.0.0.1 local.home
  127.0.0.1 local.site1

Then I can ping

$ ping local.home
PING local.home (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.037 ms


text:
Q: How does Google Photos face recognition use user-provided labels? I'm working on a toy project which I think is analogous to the problem of detecting faces and assigning names to them in Google Photos, so I've been thinking about how that process might work.
From a user perspective, I know Google Photos presents me with groups of faces which it thinks are the same person and asks me to name / label them. It later shows me new groups of faces and may ask me if these new faces are the same person as a previous group.
A naive way I could imagine this working:

*

*Train a model (object detection) to find faces in images, using a training set of images labeled with bounding boxes around faces

*Given an input set of images, find the faces using the model created in step 1

*Run a clustering algorithm (unsupervised learning) on the faces found in step 2, to find likely groups of the same face

*Present the groups from step 3 to the user one by one, asking for names / labels

After that, I'm shaky on what would happen next - maybe the new labels are applied to the images, and you could train a classification model using the now-labeled images to try and find other faces for that same person in new photos? But it seems like the data volume would potentially be low (since it's per user), and it seems expensive to train a customized model per user. Or maybe nothing happens next, and it's simply "find faces, cluster them, get the user to label en-masse by presenting clusters to the user".
I don't necessarily expect anyone to know exactly how the system works, but any pointers on areas to research, or educated guesses, would be interesting.


text:
Q: Multiple forms on one page, using ajax to post data, specify which input fields from the selected form I have a page that dynamically creates multiple forms and js code (20+). When the user selects an item from a select dropdown, (change trigger) it posts data to another script via ajax.
Form names are like: form1, form2, form3, etc.

Is there a way to specify which field input data to pass based on which select was changed?
For example, with: adId: $('input[name$="ad_id"]').val()
Need to specify which form to select from to obtain the desired data.
If changeCat2 select changed, pass the ad_id value from that specific form (form2).

EDIT - More code:
<script type="text/javascript">
            $(document).ready(function() {
                $('select.changeCat2').change(function(){
                $.ajax({
                type: 'POST',
                url: 'cat_update.php',
                data: {selectFieldValue: $('changeCat').val(), mlsId: $('input[name$="mls_id"]').val(), adId: $('input[name$="ad_id"]').val(), imageId: $('input[name$="image_id"]').val(), photoUrl: $('input[name$="photo_url"]').val()},
                dataType: 'html'
                     });
                });
            });
        </script>

<form method="post" action="" name="form2">
<input type="hidden" name="mls_id" value="W7631557">
<input type="hidden" name="ad_id" value="107">
        <select name="changeCat2">
            <option value="Living Room">Living Room</option>
            <option value="Dining Room">Dining Room</option>
            <option value="Family Room">Family Room</option>
            <option value="Den/Office">Den/Office</option>
            <option value="Kitchen">Kitchen</option>
            <option value="Exterior">Exterior</option>
            <option value="Bedrooms">Bedrooms</option>
            <option value="Bathrooms">Bathrooms</option>
            <option value="Pool/Patio">Pool/Patio</option>
            <option value="Great Room">Great Room</option>
            <option value="Balcony/Porch/Lanai">Balcony/Porch/Lanai</option>
        </select>
        <input type="hidden" name="image_id" value="2">
        <input type="hidden" name="photo_url" value="http://myimages/">
        </form>

A: It's hard to tell exactly what you want from the question, but the answer is yes, you can micromanage the data you send with your ajax call in whatever way you want.
The recipient of the ajax call may expect certain data, but that's out of the scope of the question. The example below should give you an idea of how to do any manipulations you want.

$(document).ready(function() {
  $('select[name="changeCat2"]').change(function(){
    // stop here - you can define your own data,
    // and access whatever you need from the current state of the form
    var myData = { // start with what you need for sure
      'mls_id': $('input[name="mls_id"]').val(),
    };
    var category = $('select[name="changeCat2"]').val();
    // optionally add some data
    if (category === 'Living Room') {
      myData['changeCat2'] = category;
      myData['ad_id'] = $('input[name="ad_id"').val();
    }
    console.log(myData);
    return; // just for this example so the ajax doesn't really run
    $.ajax({
      type: 'POST',
      url: 'cat_update.php',
      data: myData, // only the data you chose to include
      dataType: 'html'
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form method="post" action="" name="form2">
  <input type="hidden" name="mls_id" value="W7631557">
  <input type="hidden" name="ad_id" value="107">
  <select name="changeCat2">
     <option value="Living Room">Living Room</option>
     <option value="Dining Room">Dining Room</option>
     <option value="Family Room">Family Room</option>
     <option value="Den/Office">Den/Office</option>
     <option value="Kitchen">Kitchen</option>
     <option value="Exterior">Exterior</option>
     <option value="Bedrooms">Bedrooms</option>
     <option value="Bathrooms">Bathrooms</option>
     <option value="Pool/Patio">Pool/Patio</option>
     <option value="Great Room">Great Room</option>
     <option value="Balcony/Porch/Lanai">Balcony/Porch/Lanai</option>
   </select>
   <input type="hidden" name="image_id" value="2">
   <input type="hidden" name="photo_url" value="http://myimages/">
</form>


text:
Q: Display different category template if custom field is checked I am a big fan of Advanced Custom Field by Elliot Condon
http://www.advancedcustomfields.com/
This is what I am trying to chive without success so far:
I have a website with posts and archive.php displays my archive posts page.
Now, I would like to display different template for certain categories.
I don't have the name of the category which I want to display this template for, I would like to do it dynamically so whenever my user creates a post he can choose a special custom field from within that post (true, false preferably) e.g - this post belongs to "projects" category and if the checkbox is checked - archive.php will call different layout using include file.
if this option is unchecked. archive.php show the regular template
I was thinking about simply creating a custom field called "is_project_category"
and assign it to a post page but when I tried to use it in archive.php it didn't work at all
I used this code:
<?php
 $is_projects_category = get_field('is_projects_category');
 if('is_projects_category' == true){?>

// include the special category template for projects

<?php } else{ ?>

// display normal archive template

<?php } ?>

it didn't work..
any idea how to use it outside the loop of single.php and show it in archive.php (or anywhere in the theme)?
Thanks

A: I achieved this recently with the following code in archive.php
add_action('genesis_loop', 'blah_search_results');
function blah_search_results() {
 while (have_posts()) : the_post();
  if (is_category('in-the-news')) {
   // Get article URL
   $article_url = get_field('original_article_url');
   // rest of theme goes here
  }
 endwhile;
}


text:
Q: Resolving local LAN hostnames on Windows 10 In a gist, this is my issue:
My router's hostname is 'thecenter'. (If I leave hostname empty, I can't resolve local hostnames at all)
Computer1 resolves all hostnames without problem, i.e. http://livingroom/
Computer2 will only resolve hostnames if you add the router's hostname after, i.e. http://livingroom.thecenter/
Both are running Windows 10. Both wired, connected to the same switch, which is connected to the central router.
What could be causing this inconsistency?

A: Routers do not normally resolve hostnames in Windows 10 and you see this in your post.
For very small systems and networks like yours (and mine) use the Windows HOSTS file (c:\windows\system32\drivers\etc) for keeping host names.
If you need to edit this file (HOSTS) and save the edits, you need to open Notepad with Run as Administrator, navigate the the HOSTS file, edit it and save, to keep the results.

A: I found the cause of my problem.
If I view network properties (Start Menu -> "View your network properties"), I find that the "problem" computer is missing the DNS Domain Name and DNS Suffix properties, where my working computer is not missing those properties.
I was able to fix this by switching to manual IP, then back to automatic DHCP.

A: This was driving me nuts. In my case I fixed it by going into my routers LAN config and setting "RT-AX53U's Domain Name" from "" (nothing) to "home".
I found a post that said they could ping the host if they added a single dot . to the end of the hostname and that made me think that the hostname for local domain was missing. and so it


text:
Q: How did the summation operation come into use? So we've been using summations at least since the dawn of calculus.  I'm wondering how the process of summing a function came to be known?  Are there events that led to the invention of the summation operation?  Can we attribute summations to a particular person, or persons?
How did mathematics evolve to include summation?
Less importantly, but still interesting, is how the summation symbol, $\sum$, came to be used.

A: according to this source, the summation symbol $\Sigma$ was first used by Leonhard Euler in 1755:
Quemadmodum ad differentiam denotandam usi sumus signo $\Delta$, ita summam indicabimus signo $\Sigma$.
In the same way that we use the symbol $\Delta$ to denote a difference, we will indicate a sum by the symbol $\Sigma$.
[Institutiones calculi differentialis chapter I, paragraph 26.]

in a similar way one has [...], so that, if for $\sum x^2$, $\sum x$ and $\sum 1$ we substitute the values obtained previously, one finds that [...].

A: According to http://en.wikipedia.org/wiki/Binomial_theorem, a special case of the binomial theorem (i.e. for the exponent 2), was already known to Euclid as early as the 4th century B.C. and, as binomial coefficients surface when switching between the product- and the sum-formulation of polynomials, it seems reasonable to claim that summation as a representation of functions is tied to investigations on polynomials.
Other milestones were Newton's 1665 generalization of the binomial theorem to non-integral exponents and later James Gregory's and Brook Taylor's discovery, that certain functions can be converted into a series via a combination of interpreting the function as an infinite polynomial with repeated differentiationg and evaluation at 0.

A: We've been adding things up since the dawn of arithmetic.  The Pythagoreans knew all about figurate numbers, and how these were built up from gnomons: all they lacked was our current terminology and notation.


text:
Q: Use Google Font with R's Reactable Table Following the example here (Custom fonts) I chose a font that is different enough I could easily see whether it was working or not. Redressed.
Why isn't the body of this table using Google's 'Redressed' font?
library("reactable")

# Add a custom font from Google Fonts
# https://fonts.google.com/specimen/Redressed?selection.family=Redressed&query=redress&preview.text=1234567890&preview.text_type=custom
# https://glin.github.io/reactable/articles/cookbook/cookbook.html

htmltools::tags$link(href = "https://fonts.googleapis.com/css?family=Redressed:400&display=fallback",
                     rel = "stylesheet")

reactable(
  iris[1:5, ],
  style = list(fontFamily = "Redressed", fontSize = "44px"),
  defaultSorted = "Species"
)