text:
Q: Connecting to MongoDB from Maven exec fails but not from the jar The command below resolves all required dependencies to execute my program:
mvn exec:java -Dexec.mainClass='com.cnrg.cdproc.App'
but I can't connect to MongoDB with it, when it's possible to execute the same code from the jar using this command: java -jar target/cdproc-1.0.0-SNAPSHOT-shaded.jar.
Here's the error I'm getting starting the app via maven:
[Thread-1] INFO org.mongodb.driver.cluster - Cluster created with settings {hosts=[localhost:9032], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
[cluster-ClusterId{value='5fc969c67d495439ce9a3796', description='null'}-localhost:9032] INFO org.mongodb.driver.cluster - Exception in monitor thread while connecting to server localhost:9032
com.mongodb.MongoInterruptedException: Interrupted acquiring a permit to retrieve an item from the pool
    at com.mongodb.internal.connection.ConcurrentPool.acquirePermit(ConcurrentPool.java:203)
    at com.mongodb.internal.connection.ConcurrentPool.get(ConcurrentPool.java:140)
    at com.mongodb.internal.connection.ConcurrentPool.get(ConcurrentPool.java:123)
    at com.mongodb.internal.connection.PowerOfTwoBufferPool.getByteBuffer(PowerOfTwoBufferPool.java:82)
    at com.mongodb.internal.connection.PowerOfTwoBufferPool.getBuffer(PowerOfTwoBufferPool.java:77)
    at com.mongodb.internal.connection.SocketStream.getBuffer(SocketStream.java:93)
    at com.mongodb.internal.connection.InternalStreamConnection.getBuffer(InternalStreamConnection.java:684)
    at com.mongodb.internal.connection.ByteBufferBsonOutput.getByteBufferAtIndex(ByteBufferBsonOutput.java:93)
    at com.mongodb.internal.connection.ByteBufferBsonOutput.getCurrentByteBuffer(ByteBufferBsonOutput.java:82)
    at com.mongodb.internal.connection.ByteBufferBsonOutput.writeByte(ByteBufferBsonOutput.java:77)
    at org.bson.io.OutputBuffer.write(OutputBuffer.java:150)
    at org.bson.io.OutputBuffer.writeInt32(OutputBuffer.java:56)
    at com.mongodb.internal.connection.RequestMessage.writeMessagePrologue(RequestMessage.java:158)
    at com.mongodb.internal.connection.RequestMessage.encode(RequestMessage.java:137)
    at com.mongodb.internal.connection.CommandMessage.encode(CommandMessage.java:59)
    at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:269)
    at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83)
    at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33)
    at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:107)
    at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:62)
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:144)
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188)
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.InterruptedException
    at java.base/java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1343)
    at java.base/java.util.concurrent.Semaphore.acquire(Semaphore.java:318)
    at com.mongodb.internal.connection.ConcurrentPool.acquirePermit(ConcurrentPool.java:199)
    ... 23 more

What's the difference between starting the program through the jar and starting the program through maven? How to troubleshoot that issue if possible and start the program from maven?


text:
Q: PHP Api Object Query I'm having a bit of an issue with an API document I'm currently working with. The code I've been testing just doesn't seem to work, and I've been looking at it for that long now, I just cannot see where I'm going wrong.
API Documentation Screenshot here: https://ibb.co/CW4HRR9
// POST /package/{id}/web/ftpusers
$args = [
    'update' => [
        'ftp' => [
            'id' => '12345',
            'user' => ['Password' => 'Password123']
        ],
    ],
];
$response = $services_api->postWithFields("/package/".$test_domain_id."/web/ftpusers", $args);
echo '<pre>';
print_r($response);
echo '</pre>';

It just doesn't seem to work, and I'm guessing I'm doing something wrong where it states object and object[]

A: Looks like I was missing an array object as I've now got this working (extra array within 'ftp'
$args = [
    'update'=> [
        'ftp' => [
            [
            'id' => $info[0]->Id,
            'user' => [
                'Enabled' => true,
                'Password' => 'Password123'
                ],
            ]
        ],
    ],
];

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make a more efficient request in React to improve peformance? so I put a console.log('rendering') in my <Router /> component and it's logging 10 times, seems a lot. I noticed this is causing 6 re-renders
  useEffect(() => {
    fetchRESTCountries()
  }, [])

this just makes a call to here: https://restcountries.eu/rest/v2/all
which is returning an array of size 250, which isn't massive but not too small either. I was wondering how I can make this more efficient? I'm not sure why it's causing 6 re-renders.
I was thinking of using a react memo, but not sure how that would be beneficial here?
any advice on how to reduce the number of re-renders would be great as it isn't helping performance
thanks
this is my component code:
// the different fetchDatas is fetching different pieces of information
export const MainRouter = ({
        fetchData1,
        fetchData2,
        fetchData3,
        fetchData4,
    }) => {
        const [loaded, setLoaded] = useState(false)
        const authenticatedUser = JSON.parse(localStorage.getItem('authUser'))

        useEffect(() => {
            firebaseApp.auth().onAuthStateChanged((user) => {
                if (user) {
                    localStorage.setItem('authUser', JSON.stringify(user))
                    setLoaded(true)
                    fetchData1(user)
                    fetchData2(user)
                    fetchData3(user)
                    fetchData4(user)
                } else {
                    localStorage.removeItem('authUser')
                    setLoaded(true)
                }
            })
        }, [])

        useEffect(() => {
            fetchRESTCountries()
        }, [])

        const logUserOutFirebaseAndRedux = async () => {
            try {
                await firebaseApp.auth().signOut()
            } catch (e) {
                console.err(e)
            }
        }

        const ProtectedRoute = ({ component: Component, ...rest }) => {
            return authenticatedUser ? <Component {...rest} /> : <Redirect from="" to="/login" noThrow />
        }

        const PublicRoute = ({ component: Component, ...rest }) => <Component {...rest} />

        const notSharedMap = /^(?!.*(\/shared-map)).*$/
        const GlobalStyle = createGlobalStyle`
            html {
                overflow: ${({ location }) => (location.includes('visited') ? 'hidden' : 'auto')};
            }
            body {
                background: ${({ location }) => (location.includes('random-stats') ? '#041a24' : '#fff')};
            }
        `
        console.log('re render')

        return (
            <Router>
                <GlobalStyle location={window.location.pathname} />

                <PublicRoute
                    path={notSharedMap}
                    component={CONNECTED_Nav}
                    logUserOut={logUserOutFirebaseAndRedux}
                    location={window.location.pathname}
                />

                    <ProtectedRoute exact component={AccountContainer} path="/account" />
                    // many more routes like this
                </Switch>
            </Router>
        )
    },
)

A: Just like your loaded state, also add an indicator once fetchRESTCountries() is already called. Something like this:
const [areCountriesFetched, setAreCountriesFetched] = useState(false);

useEffect(() => {
  if (!areCountriesFetched) {
    fetchRESTCountries();
    setAreCountriesFetched(true);
  }
}, [areCountriesFetched, setAreCountriesFetched]); // these two, I think, are required to be added on the dependencies array by eslint

It's a common practice. But, it all depends on the logic you're implying.


text:
Q: Why does my physical volume appear full? I am using Ubuntu 14.04 as my dom0 for Xen hypervisor installed on my server. During Ubuntu installation I used set up LVM option. Now, I see that i have 3 partitions sda1, sda2 and sda5, of which sda5 is set as LVM physical volume. I have a few questions regarding that:

*

*Why is the physical volume full ? I have not installed anything on my server except Xen.

*Of the two logical volumes root and swap_1 which one can be expanded or shrunk ?

*How do I create a new logical volume when the 2 logical volumes appear to have taken up all the space (magically)?

*I want to install 4 VMs. Do i need a separate LV for each VM ?

Here are the screenshots of the system:

A:
Why is the physical volume full ? I have not installed anything on my
  server except Xen.

I see that when installing the Ubuntu 14.04 server you allocated 144.1G from the ubuntu-vg volume group for the dom0 root partition, but also allocated 128G for swap space, assigning all the available space on it (which is why it says allocatable (but full).
Are you sure you intended to have such a large swap?

Of the two logical volumes root and swap_1 which one can be expanded
  or shrunk ?

In the actual situation none of the volumes can be expanded, without shrinking the other. I suggest you reduce the swap to a more suitable size, 8G for instance.
To do that, first make sure to stop using the swap space:
root@ubuntu# swapoff /dev/mapper/ubuntu--vg-swap_1

then use LVM2 tools to resize the logical volume:
root@ubuntu# lvreduce -L 8G /dev/mapper/ubuntu--vg-swap_1

(more examples of shrinking logical volumes at https://www.rootusers.com/lvm-resize-how-to-decrease-an-lvm-partition/)

How do I create a new logical volume when the 2 logical
  volumes appear to have taken up all the space (magically)?

After you do the previous step, you should now have ~120G available on volume group ubuntu-vg,

I want to install 4 VMs. Do i need a separate LV for each VM ?

It depends on what you find more flexible:
You can create xen domains with storage based on images, which are standard files inside dom0 root filesystem (in this case you may want to expand the root volume).
or,
You can create xen domains with storage based on LVM volumes.
More info on this and examples in https://www.howtoforge.com/using-xen-with-lvm-based-vms-instead-of-image-based-vms-debian-etch


text:
Q: Is it possible to have a Spring managed CacheLoader in a Scheduled Refresh scenario in EHCache 2.x? The idea is to request information from a slow third party webservice every 5 minutes and have it stored in EHCache so the user does not have to spend up to 30s waiting.
Enter "Scheduled Refresh in EHCache", which is a way to make EHCache itself update its own caches through a CacheLoader that is managed by a EHCache Quartz job.
The problem manifests itself as these CacheLoaders when defined in ehcache.xml, cannot deal with dynamic properties eg ${webservice.url}, ${webservice.header}, these being the URL the web service is at for that environment, and the HTTP Auth header it must send along to be able to retrieve the information,. The "properties" one can pass along all must be hardcoded, which is not a solution for me.

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true"
         monitoring="autodetect"
         dynamicConfig="true"
         name="cacheManager">

    <diskStore path="java.io.tmpdir" />

    <cache name="myCache"
           maxEntriesLocalHeap="10"
           maxEntriesLocalDisk="10"
           eternal="false"
           diskSpoolBufferSizeMB="20"
           timeToIdleSeconds="3000"
           timeToLiveSeconds="6000"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">

        <persistence strategy="localTempSwap" />
        <!--
        <bootstrapCacheLoaderFactory class="com.project.ManualsBootstrapCacheLoader"/>
        -->
        <cacheLoaderFactory class="com.project.cache.ManualsCacheLoader" properties="key=test,url=test"/>
        <cacheExtensionFactory class="net.sf.ehcache.constructs.scheduledrefresh.ScheduledRefreshCacheExtensionFactory"
                               properties="batchSize=100,quartzJobCount=2,cronExpression=0 0/5 * * * ?" />
    </cache>
</ehcache>

On the other hand, when I define the caches as Spring managed beans, I do not know of a way to pass in and register my custom CacheLoaders and how to activate the Quartz jobs correctly.

<beans xmlns = "http://www.springframework.org/schema/beans"
       xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context = "http://www.springframework.org/schema/context"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-4.3.xsd
   http://www.springframework.org/schema/util
   http://www.springframework.org/schema/util/spring-util-4.3.xsd
   http://www.springframework.org/schema/cache
   http://www.springframework.org/schema/cache/spring-cache-4.3.xsd">

    <context:component-scan base-package="com.project" />
    <cache:annotation-driven cache-manager="cacheManager" />
    <context:annotation-config/>

    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
          p:cache-manager-ref="ehcache" name="cacheManager" />
    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
          p:config-location="classpath:manuals_ehcache.xml" p:shared="false" name="ehcache" p:cacheManagerName="cacheManager"/>

    <bean id="manualsCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean" name="manualsCache">
        <property name="cacheManager" ref="ehcache"/>
        <property name="maxEntriesLocalHeap" value="10"/>
        <property name="maxEntriesLocalDisk" value="10"/>
        <property name="eternal" value="false"/>
        <property name="diskSpoolBufferSizeMB" value="20"/>
        <property name="timeToIdleSeconds" value="3000"/>
        <property name="timeToLiveSeconds" value="6000"/>
        <property name="memoryStoreEvictionPolicy" value="LRU"/>
        <property name="transactionalMode" value="off"/>
    </bean>

    <bean id="manualCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean" name="manualCache" >
        <property name="cacheManager" ref="ehcache"/>
        <property name="maxEntriesLocalHeap" value="100"/>
        <property name="maxEntriesLocalDisk" value="100"/>
        <property name="eternal" value="false"/>
        <property name="diskSpoolBufferSizeMB" value="20"/>
        <property name="timeToIdleSeconds" value="3000"/>
        <property name="timeToLiveSeconds" value="6000"/>
        <property name="memoryStoreEvictionPolicy" value="LRU"/>
        <property name="transactionalMode" value="off"/>
    </bean>
</beans>

If the above is not possible, I was thinking of extending the (Spring or EHCache) CacheManager bean with the dynamically resolvable 'url' and 'header' properties and that when the "createCacheLoader" call is made, which gets the EHCache instance as a parameter, I could call the EHCache instance's getCacheManager method and could retrieve the URL and Header from the CacheManager bean. But that feels pretty dirty.
Any ideas? Or should I look elsewhere?


text:
Q: How to print to console in pytest? I'm trying to use TDD (test-driven development) with pytest.
pytest will not print to the console when I use print.
I am using pytest my_tests.py to run it.
The documentation seems to say that it should work by default: http://pytest.org/latest/capture.html
But:
import myapplication as tum

class TestBlogger:

    @classmethod
    def setup_class(self):
        self.user = "alice"
        self.b = tum.Blogger(self.user)
        print "This should be printed, but it won't be!"

    def test_inherit(self):
        assert issubclass(tum.Blogger, tum.Site)
        links = self.b.get_links(posts)
        print len(links)   # This won't print either.

Nothing gets printed to my standard output console (just the normal progress and how many many tests passed/failed).
And the script that I'm testing contains print:
class Blogger(Site):
    get_links(self, posts):
        print len(posts)   # It won't get printed in the test.

In unittest module, everything gets printed by default, which is exactly what I need. However, I wish to use pytest for other reasons.
Does anyone know how to make the print statements get shown?

A: According to the pytest docs, pytest --capture=sys should work. If you want to capture standard out inside a test, refer to the capsys fixture.

A: This is the cleanest way I know to print a single statement to sys.stdout (without artificially making your test fail or enabling the -s option) - you get to see the specific output you want and nothing more:

*

*Add the in-built parameter capsys to your test function. (This means that you add capsys to the list of parameters, e.g.

def test_function(existing_parameters, capsys):

*In your code, simply insert:

with capsys.disabled():
   print("this output will not be captured and go straight to sys.stdout")

See https://buildmedia.readthedocs.org/media/pdf/pytest/latest/pytest.pdf (2.11 How to capture stdout/stderr output).

A: By default, py.test captures the result of standard out so that it can control how it prints it out. If it didn't do this, it would spew out a lot of text without the context of what test printed that text.
However, if a test fails, it will include a section in the resulting report that shows what was printed to standard out in that particular test.
For example,
def test_good():
    for i in range(1000):
        print(i)

def test_bad():
    print('this should fail!')
    assert False

Results in the following output:
>>> py.test tmp.py
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items

tmp.py .F

=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________

    def test_bad():
        print('this should fail!')
>       assert False
E       assert False

tmp.py:7: AssertionError
------------------------------- Captured stdout --------------------------------
this should fail!
====================== 1 failed, 1 passed in 0.04 seconds ======================

Note the Captured stdout section.
If you would like to see print statements as they are executed, you can pass the -s flag to py.test. However, note that this can sometimes be difficult to parse.
>>> py.test tmp.py -s
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items

tmp.py 0
1
2
3
... and so on ...
997
998
999
.this should fail!
F

=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________

    def test_bad():
        print('this should fail!')
>       assert False
E       assert False

tmp.py:7: AssertionError
====================== 1 failed, 1 passed in 0.02 seconds ======================

A: I originally came in here to find how to make PyTest print in VSCode's console while running/debugging the unit test from there. This can be done with the following launch.json configuration. Given .venv the virtual environment folder.
    "version": "0.2.0",
    "configurations": [
        {
            "name": "PyTest",
            "type": "python",
            "request": "launch",
            "stopOnEntry": false,
            "pythonPath": "${config:python.pythonPath}",
            "module": "pytest",
            "args": [
                "-sv"
            ],
            "cwd": "${workspaceRoot}",
            "env": {},
            "envFile": "${workspaceRoot}/.venv",
            "debugOptions": [
                "WaitOnAbnormalExit",
                "WaitOnNormalExit",
                "RedirectOutput"
            ]
        }
    ]
}

A: You can also set this via the Pycharm GUI: go to Run > Edit Configurations. There, select the test you want to enable print statements for and add -s to the Additional Arguments field.
I do it like this, because while I primarily use the Pycharm debugger to debug my pytest functions (i.e. via the GUI), my specific use case also requires me to know what's going on elsewhere in my code and print statements can come in handy for that.

A: Use the -s option:
pytest -s

Detailed answer
From the docs:

During test execution any output sent to stdout and stderr is captured. If a test or a setup method fails its according captured output will usually be shown along with the failure traceback.

pytest has the option --capture=method in which method is per-test capturing method, and could be one of the following: fd, sys or no. pytest also has the option -s which is a shortcut for --capture=no, and this is the option that will allow you to see your print statements in the console.
pytest --capture=no     # show print statements in console
pytest -s               # equivalent to previous command

Setting capturing methods or disabling capturing
There are two ways in which pytest can perform capturing:

*

*file descriptor (FD) level capturing (default): All writes going to the operating system file descriptors 1 and 2 will be captured.

*sys level capturing: Only writes to Python files sys.stdout and sys.stderr will be captured. No capturing of writes to filedescriptors is performed.
pytest -s            # disable all capturing
pytest --capture=sys # replace sys.stdout/stderr with in-mem files
pytest --capture=fd  # also point filedescriptors 1 and 2 to temp file

A: I generally use this command:-
pytest -v -rs --html=report.html --self-contained-html test_Suite.py -s

the above command also generates a report.html file where all the print statements are getting captured and saved. And the -s at the last will show the print statements into the terminal too.

A: I needed to print important warning about skipped tests exactly when PyTest muted literally everything.
I didn't want to fail a test to send a signal, so I did a hack as follow:
def test_2_YellAboutBrokenAndMutedTests():
    import atexit
    def report():
        print C_patch.tidy_text("""
In silent mode PyTest breaks low level stream structure I work with, so
I cannot test if my functionality work fine. I skipped corresponding tests.
Run `py.test -s` to make sure everything is tested.""")
    if sys.stdout != sys.__stdout__:
        atexit.register(report)

The atexit module allows me to print stuff after PyTest released the output streams. The output looks as follow:
============================= test session starts ==============================
platform linux2 -- Python 2.7.3, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /media/Storage/henaro/smyth/Alchemist2-git/sources/C_patch, inifile:
collected 15 items

test_C_patch.py .....ssss....s.

===================== 10 passed, 5 skipped in 0.15 seconds =====================
In silent mode PyTest breaks low level stream structure I work with, so
I cannot test if my functionality work fine. I skipped corresponding tests.
Run `py.test -s` to make sure everything is tested.
~/.../sources/C_patch$

Message is printed even when PyTest is in silent mode, and is not printed if you run stuff with py.test -s, so everything is tested nicely already.

A: Using -s option will print output of all functions, which may be too much.
If you need particular output, the doc page you mentioned offers few suggestions:

*

*Insert assert False, "dumb assert to make PyTest print my stuff" at the end of your function, and you will see your output due to failed test.

*You have special object passed to you by PyTest, and you can write the output into a file to inspect it later, like
def test_good1(capsys):
    for i in range(5):
        print i
    out, err = capsys.readouterr()
    open("err.txt", "w").write(err)
    open("out.txt", "w").write(out)

You can open the out and err files in a separate tab and let editor automatically refresh it for you, or do a simple py.test; cat out.txt shell command to run your test.
That is rather hackish way to do stuff, but may be it is the stuff you need: after all, TDD means you mess with stuff and leave it clean and silent when it's ready :-).

A: There are already a lot of good answers, but I want to share why I wasn't able to get logs when I ran pytest.
One important note is that each test case must start with the test_ prefix when you write the functions. Without that, there will be no print statements when using pytest.
As for the command, I use the following one to get very comprehensive logs:
python -m pytest -v -rs <particular_file.py> -s -o log_cli-level=DEBUG

By making sure you have the right function names and using my command, you should be able to see console logs for sure.

A: If you are working with pytest.ini, consider using:
[pytest]
...
addopts = --capture=no
...

This works well if you are running your tests from an IDE extension which is based on you pytest.ini

A: without artificially making your test fail or enabling the -s option
import warnings

text = "asdf"

warnings.warn(UserWarning("{}".format(text)))


text:
Q: How does std:set check if there is an equivalent element in set during the insertion? Let's use the following code as an example.
auto cmp = [](ll a, ll b) {
    return gcd(12, a) < gcd(12, b);
};
set<ll, decltype(cmp)> s(cmp);
for(ll i = 0; i < 2; i++){
    ll x;
    cin >> x;
    s.insert(x);
    cout << "Success! \n";
}

I defined new comparator that compares numbers by their greatest common divisor with 12.
First I successfully inserted 5. And then I tried to insert 7, but it was not successful.
I know that gcd(12, 5) = gcd(12, 7) = 1.
But I am failing to understand how does std::set check if 5 is equivalent to 7.
It can find out that gcd(12, 7) is not less than gcd(12, 5) using comparator comp I gave it, but how does it figure out that gcd(12, 7) is equal to gcd(12, 5)?

A: It calls the comparator twice, with different order of arguments.
If cmp(x, y) and cmp(y, x) are both false, then x and y are considered to be equivalent.


text:
Q: access property of new window opened with window.open I have to send some coordonates to another window that opens a map adress by
winMap=window.open('${mapServerUrl}','_blank','modal=true');

but when I'm trying to acces the propperties of the map window,
if (typeof winMap.atlas != 'undefined' && typeof winMap.atlas.map != 'undefined' && winMap.atlas.map.isMapLoaded())

.......
the browser gives me "Error: Permission denied to access property 'atlas'".
I know that this case enters to the case of "cross-site scripting" but how can I send the coords to the map windows to show them to the user?
Thanks


text:
Q: Building static library using Code::Block with MinGW I am using Code::Blocks with MinGW32 on a Windows machine. And I am trying to build a static library.

I created a dummy hello world project. There is one single main.c file in the project. However, when I build it, I got the following message. It seems that there is no errors or warnings. It is just that no lib file is generated.
mingw32-gcc.exe -Wall -g  -c C:\Users\yzhong52\Desktop\hello_static_lib\main.c -o obj\Debug\main.o
cmd /c if exist bin\Debug\libhello_static_lib.a del bin\Debug\libhello_static_lib.a
mingw32-gcc-ar.exe -r -s bin\Debug\libhello_static_lib.a obj\Debug\main.o
sorry - this program has been built without plugin support
Process terminated with status 1 (0 minute(s), 0 second(s)) 0 error(s), 0 warning(s) (0 minute(s), 0 second(s))

It says, sorry - this program has been built without plugin support. What does that mean? Am I missing sth?
BTW, I also tried building a dynamic library using pretty much the same method and it works fine. The .dll and the lib.a are generated.
Edit:
After switching from mingw32-gcc-ar.exe to ar.exe, everything works just fine. I still don't understand why though.


text:
Q: Popup Window InputEventReceiver Error - Android I dont like errors. I'm using a Popup Window to display a little hint above a TextView. the hint is for explanation of what the TextView is saying, for example RBI, will popup a hint saying "Runs batted in" I keep getting this error W/InputEventReceiver﹕ Attempted to finish an input event but the input event receiver has already been disposed. everytime i click outside of the popup hint to remove the popup, which is the way i want it to be setup, i get that error. I've tried setting the input to INPUT_METHOD_NOT_NEEDED and nothing
i have multiple hints to be shown, so i put everything in an TextView array and
i have a listener on each TextView item
method to run the popup
public void displayPopupWindow(View anchorView, String text) {
    final PopupWindow popup = new PopupWindow(getApplicationContext());
    View layout = getLayoutInflater().inflate(R.layout.test_popup, null);
    ((TextView) layout.findViewById(R.id.popup_text)).setText(text);
    popup.setContentView(layout);
    // Set content width and height
    popup.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
    popup.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
    // Closes the popup window when touch outside of it - when looses focus
    popup.setOutsideTouchable(true);
    popup.setTouchable(false);
    popup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
    // Show anchored to button
    popup.setBackgroundDrawable(new BitmapDrawable());
    popup.showAsDropDown(anchorView, 0, -225);
}

i create a listener
View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String text = "";
            ...
            //a bunch of code that just decides what the variable text should be
            ...
            displayPopupWindow(v, text);
        }
    };

and the array of TextViews listeners is set to the listener object
//inside a for loop
TextViews[i].setOnClickListener(listener);

anyone know of anyway to rid of that error. i wouldnt want the logcat to fill up with those errors. anyone have any ideas how to fix this?

A: your error is a common error if you search on google,
you have to call your displaypopup method with an handler.
You can find more help here or here.
Hope i helps you


text:
Q: how to Defining custom settings in Odoo http://ludwiktrammer.github.io/odoo/custom-settings-odoo.html
in this article he did
class YourSettings(models.TransientModel):
_inherit = 'res.config.settings'
_name = 'your.config.settings'

company_name = fields.Char()
company_phone = fields.Char()

@api.model
def get_default_company_values(self, fields):

    company = self.env.user.company_id
    return {
        'company_name': company.name,
        'company_phone': company.phone,
    }

@api.one
def set_company_values(self):
    company = self.env.user.company_id
    company.name = self.company_name
    company.phone = self.company_phone

i want to make company_name = fields.Char()    to be company_name = fields.many2one('res.partner','company name')
but the result in employee like res.partner(9,) how to make it show the name of the company
second
i create custom field person height ,person weight i want to add this 2 fields to this custom settings


text:
Q: Best Practices to deploy serverless app (s3, api gateway, lambda, cognito...) with AWS CDK I started to build an App using the serverless services of AWS and I am now on the point where I want to put it all into AWS CDK. I also want to create a CICD pipeline using CodePipeline to automatically deploy the infrastructure by changes.
To use the API gateway interfaces, I generated the SDK for Javascript from the AWS console, and included it into the website folder manually.

*

*Is it possible to generate the SDK and include it in the project or maybe some random bucket automatically with CDK?

*Are there some best practices regarding the provisioning of such a Infrastructure in an automated way using a CICD Pipeline?

A:
Is it possible to generate the SDK and include it in the project or maybe some random bucket automatically with CDK?

Based on the documentation, you can generate the SDK two ways. Through the AWS console or using AWS CLI (Reference: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-generate-sdk.html)
You could write a script that generates the SDK using AWS CLI and upload it to the website folder or bucket.

Are there some best practices regarding the provisioning of such a Infrastructure in an automated way using a CICD Pipeline?

This is a very general question. This article talks about Best practices using CDK (https://aws.amazon.com/blogs/devops/best-practices-for-developing-cloud-applications-with-aws-cdk/).
aws-samples Github repo is also useful and includes samples like this one: https://github.com/aws-samples/aws-serverless-app-sam-cdk

A: Add a Custom Resource to your CDK stack.  As the CloudFormation docs say,

Custom resources enable you to write custom provisioning logic ... that AWS CloudFormation runs anytime you create, update (if you changed the custom resource), or delete stacks.

In other words, you can natively extract the API client SDKs to a bucket each time the stack's API definition changes.
You define a lambda that uses the apigateway and s3 SDK clients to generate the API client .zip output and saves it to a bucket.  You then
integrate this into the stack lifecycle events with custom resource logic.
CloudFormation handles calling the lambda on create-update-delete and the responses.
(Note: the term "Custom Resource" can be confusing.  Yes, they can help fill in CDK/CloudFormation's gaps
to actually create infrastructure resources using API calls.  But a CustomResource does not
have to create any infrastructure at all.  They are used for lookups, running tests and seeding initial data.  What you can do is up to your lambda.)
aws-cdk-samples has an example of a custom resource implementation.  Here is a skeleton of the custom resource plumbing for your use case:
export class ExportApigCustomResource extends Construct {
  constructor(scope: Construct, id: string, props: ExportApigCustomResourceProps) {
    super(scope, id);

    // the provider handles the orchestration
    // https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html#custom-resource-providers
    const provider = new cr.Provider(this, 'Provider', {
      // CloudFormation will call this lambda on create-update-delete
      onEventHandler: new lambda.NodejsFunction(this, 'ExportApigLambda', {
          entry: path.join(__dirname, 'exportApi.ts'),
          role: new iam.Role(this, 'CrLambdaRole', {...add the right policies});
        })
    });

    // information for the getSdk call that is passed to the lambda in the triggered lifecycle events
    // use a strongly typed input type for safety
    const properties: ExportApigCustomResourceProperties = {
      restApiId: props.api.restApiId,
      bucketName: props.bucket.bucketName,
      stageName: 'prod',
      sdkType: 'javascript',
    };

    // the actual custom resource
    // https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CustomResource.html
    new cdk.CustomResource(this, 'Resource', {
      resourceType: 'Custom::ExportApi',
      serviceToken: provider.serviceToken,
      properties,
    });
  }
}

Custom Resources are fiddly to set up.  But they are well-supported in the CDK and an elegant way to keep provisioning logic in the same place as your infrastructure code.


text:
Q: PHP Apache Authorization Header I'm having trouble retrieving the Authorization Header sent by Angular to Wamp Apache PHP.
Here is a snapshot of my chrome dev tools:

After a lot of research I was able to get the $_SERVER["HTTP_AUTHORIZATION"] variable to appear in PHP by adding any of those to the .htaccess file:
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last]

The following variations didn't work for me (PS: they may be viable for other people):
CGIPassAuth On

SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0

RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

My issue is that the Header is now present in PHP but EMPTY.

An example of API endpoint being use

Here is my setup:

*

*PHP 7.2.1

*APACHE 2.4.35

*WAMP 3.1.4

A: I think you should try $_SERVER['Authorization']


text:
Q: Git shallow fetch of a new tag If I clone a repository with max depth of 1 at a tag, it works and pulls down just that.  If I then want to do a fetch with or without depth of 1 for a new tag, it does some processing, but the tag never shows up under 'git tag'.  If I supply the --tags option, it downloads the whole repository rather than just the new information.  I don't mind the repository getting more history, I just want to avoid the download times.  Is there any way to get a new tag without getting all tags from a shallow cloned repository?
git clone --branch 1.0 --depth 1 repositoryPath
git fetch --depth 1 origin tags/1.1 # Does processing but no new tags
git fetch --tags origin tags/1.1 # Pulls down the rest of the repository and adds all tags
git fetch --depth 1 --tags origin tags/1.1 # Same as above

Now, I have noticed this in the documentation:
"--depth ...
Tags for the deepened commits are not fetched."
Is this what I'm running into?  Is there no way to do this besides downloading all tags?

A: You can use the full <refspec> format:
git fetch --depth 1 origin refs/tags/1.1:refs/tags/1.1

Or, as specified in git-fetch options (under <refspec>):

tag <tag> means the same as refs/tags/<tag>:refs/tags/<tag>; it
  requests fetching everything up to the given tag.

So the short form answer to your question would be
git fetch --depth 1 origin tag 1.1


text:
Q: Python disk writing speed different on two computers I am trying to run a python script to take data from an input .csv file and print it to an output .csv file, using an ID and column headers to cross reference.
They are very large files so I've included multiprocessing and the first step is to split the output file into parts so they can be processed in parallel.
I tried executing this on Computer A and the disk speed to split up the output file is 0 mb/s (or a very slow trickle) and the program never get executed. Meanwhile on Computer B the program runs correctly and the disk speed splits the output file into parts at a rate of ~40mb/s.
It is the same exact files and the same exact code, why is Computer A not responding properly? Is it an operating system error? Am I missing a driver on Computer A? Something else?
The input and output files are located on the WD 4TB external HDD.
Computer A specs: Windows 10 Pro 64-bit, Intel i9 7920X 12-core, 8 x 8GB Geil Evo Potenza RAM, Samsung 850 Evo 500GB local SSD, WD 4TB external HDD, ASRock X299 Killer motherboard
Copmuter B specs: Windows 10 Pro 64-bit,
Intel i7 6700K 4-core, 2 x 16GB Geil Evo Forza RAM, PNY CS1311 240GB SSD, WD 4TB external HDD, MSI B250M Gaming Pro motherboard
# std lib imports
import csv
import multiprocessing
import os
import os.path
import shutil
import sqlite3
import sys
import tempfile
import timeit

# third party imports

# our imports

buffer_size = 8192000  # 8.192 MB, 10x the default (io.DEFAULT_BUFFER_SiZE)
# working_dir = tempfile.gettempdir()
working_dir = "E:\\temp_files"

def return_csv_header(filename):
    """
    Returns the first column of the csv file filename
    as a list.
    """
    with open(filename, "r", newline="", encoding="utf-8") as csvfile:
        reader = csv.reader(csvfile)
        return next(reader)

def return_input_mapping(input_file, identifier):
    """
    Returns a {identifier:record} dictionary where
        identifier is the value of the identifier column
         for each row in the input file.
        record is a dictionary of {column:value}
         representing a row in a csv file.
    """
    to_ret = dict()
    with open(input_file, "r", newline="", encoding="utf-8") as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            key = row[identifier]
            to_ret[key] = row

    return to_ret

def return_csv_contents(input_file):
    """
    Returns a list of lists representing the rows
    in a csv file.
    """
    to_ret = list()
    with open(input_file, "r", newline="", encoding="utf-8") as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            to_ret.append(row)

    return to_ret

def create_db_and_table(csv_contents, identifier):
    """
    Creates a sqlite3 database and table.
    Creates the identifier table column along with more
    table columns named from col0 to colN. We do this because
    the csv column headers can be all sorts of weird stuff. And
    we only really care about the order of the columns, and the
    identifier so we can set it as the primary key.
    No rows are added.
    Returns the database path and table name as a tuple.
    """
    # assert that the identifier is in the csv_contents header
    header = csv_contents[0]
    assert(identifier in header)

    db_path = os.path.join(working_dir, "csv_input.sqlite")
    tablename = "data"

    # delete the database if it already exists
    if os.path.exists(db_path):
        os.remove(db_path)

    # create the database, table, and columns
    with sqlite3.connect(db_path) as conn:
        cursor = conn.cursor()

        # prepare the table's columns - it will look like this
        # (col1 text, col2 text, col3 text primary key, ...)
        name = "col"
        counter = 0
        column_names = "("
        for column in header:
            if column == identifier:
                column_names += "%s text primary key," % identifier
            else:
                column_names += "%s text," % (name + str(counter))

            counter += 1

        # remove the last comma and space
        if column_names.endswith(","):
            column_names = column_names[0:-1]
        column_names += ")"

        # prepare the sql statement
        sql = "CREATE TABLE %s %s" % (tablename, column_names)

        # some performance tweaks for the database
        cursor.execute("PRAGMA synchronous=OFF")
        cursor.execute("PRAGMA cache_size=20000")  # 20,000*1024 = 20.48MB
        cursor.execute("PRAGMA journal_mode=off")   # dont keep journal of operations
        cursor.execute("PRAGMA temp_store=memory")  # store temp files in memory
        # execute the statement
        cursor.execute(sql)
        conn.commit()

    return db_path, tablename

def delete_db(db_path):
    """
    Deletes the sqlite3 database file at the given db_path.
    """
    assert(os.path.exists(db_path) is True)
    os.remove(db_path)
    assert(os.path.exists(db_path) is False)

def load_db_content(db_path, table, contents):
    """
    Loads the database table with the given contents.
    Skips the first element in contents as that is the
    header aka the database column names.
    """
    header = contents[0]
    num_of_cols = len(header)
    assert(num_of_cols != 0)
    contents = contents[1:] # remove the header from the contents

    # connect to the database
    with sqlite3.connect(db_path) as conn:
        # only commit once versus after every statement
        cursor = conn.cursor()
        cursor.execute("BEGIN IMMEDIATE")

        # insert into the database in chunks if needed
        limit = 999
        remaining = num_of_cols
        beginning = 0
        while remaining > limit:  # sqlite column limit
            # prepare the sql statement
            # this makes the string (?, ?, ?, ...)
            columns = "(" + "?," * limit
            columns = columns[:-1]  # remove last comma
            columns += ")"

            # prepare the columns to insert
            to_insert = []
            for i in range(len(contents)):
                to_insert.append(contents[i][beginning:beginning+limit])

            sql = "INSERT INTO %s VALUES %s" % (table, columns)
            cursor.executemany(sql, to_insert)
            remaining -= 999
            beginning += 999

        columns = "(" + "?," * remaining
        columns = columns[:-1]  # remove last comma
        columns += ")"

        to_insert = []
        for i in range(len(contents)):
            to_insert.append(contents[i][beginning:beginning+remaining])

        sql = "INSERT INTO %s VALUES %s" % (table, columns)
        cursor.executemany(sql, to_insert)

        # commit the changes
        conn.commit()

def get_na_dict(columns, identifier):
    """
    Returns a dict with the given columns as keys, and
    "n/a" as the values.
    Skip over the identifier because we want to keep
    that piece of data as it is.
    """
    to_ret = dict()
    for column in columns:
        if column == identifier:
            continue
        else:
            to_ret[column] = "n/a"

    return to_ret

def run_vlookup(input_file, output_file, identifier, db_path, table):
    """
    Completes the output file with data from the input file
    that matches the record identifier and the header columns.
    See the description at the top of this file for an example.
    Returns the path of the new output file.
    """
    # header of input file
    input_header = return_csv_header(input_file)

    # fill in the output file with data from the input file
    output_file_name = os.path.basename(output_file)
    temp_file = os.path.join(working_dir, output_file_name + ".tmp")

    with open(output_file, "r", newline="", buffering=buffer_size, encoding="utf-8") as inputcsv:
        with open(temp_file, "w", newline="", buffering=buffer_size, encoding="utf-8") as tempcsv:
            reader = csv.DictReader(inputcsv)

            # set restval to "" which will write empty values for columns
            #  in the output file that are not in the input file
            # set extrasaction to "ignore" which will skip over columns
            #  from the input file that are not in the output file
            writer = csv.DictWriter(tempcsv,
                                    fieldnames=reader.fieldnames,
                                    restval="",
                                    extrasaction="ignore")
            writer.writeheader()

            # open databse connection
            with sqlite3.connect(db_path) as conn:
                cursor = conn.cursor()

                for row in reader:
                    key = row[identifier] # get the value for the lookup

                    # fetch the key from the database
                    sql = "SELECT * FROM %s where %s = '%s'" % (table, identifier, key)
                    cursor.execute(sql)
                    result = cursor.fetchone()

                    # update the output file with "n/a" if the item
                    # does not exist in the database
                    if result is None:
                        lookup_values = get_na_dict(input_header, identifier)

                    # otherwise update it with the values from the database
                    else:
                        lookup_values = dict(zip(input_header, result))

                    row.update(lookup_values) # merge the two dictionaries

                    writer.writerow(row)

    return temp_file

def split_file(output_file, cpu_count):
    """
    Splits the output_file into cpu_count number of
    temporary files.
    Returns the names of the temporary files as a list.
    """
    # generate the temp file names
    output_file_name = os.path.basename(output_file)
    tempdir = working_dir
    temp_files = []
    for i in range(cpu_count):
        temp_file = os.path.join(tempdir, "%s_%s" % (output_file_name, i))
        temp_files.append(temp_file)

    # create the files
    with open(output_file, "rb", buffering=0) as outfile:
        # calculate size of the file
        size = outfile.seek(0, 2)
        outfile.seek(0, 0)

        # read the header in (at the same time moving the file pointer forward)
        header = return_header_bytes(outfile)

        # calculate the size of the smaller files (excluding the header)
        chunk_size = (size - len(header)) / cpu_count

        for file in temp_files:
            create_temp_file(file, chunk_size, outfile, header)

    return temp_files

def create_temp_file(file, chunk_size, outfile, header):
    """
    Creates file with the given header plus chunk_size data
    from the given outfile.
    Header is a byte string.
    If chunk_size is bigger than 100MB we read/write it in
    chunks of 100MB.
    After reading chunk_size amount of data, if the last byte
    does not end with a newline, we keep reading until
    it does. That way we dont write a file with truncated data.
    If we reach the end of outfile then we stop reading and we
    finish our last write.
    """
    # start the file with the header
    data = header

    memory_safe_chunk = 100000000  # bytes, so 100MB

    # read in chunk_size data from outfile
    if isinstance(chunk_size, float):
        chunk_size = int(chunk_size)

    # write the data to the temp file
    with open(file, "wb", buffering=0) as fp:
        # safe to read/write chunk in one go
        if chunk_size < memory_safe_chunk:
            data += outfile.read(chunk_size)

        # need to read/write chunk in chunks, go figure
        else:
            remaining = chunk_size
            while remaining > memory_safe_chunk:
                data += outfile.read(memory_safe_chunk)
                fp.write(data)
                data = b""
                remaining -= memory_safe_chunk

            data += outfile.read(remaining)

        # keep reading 1 byte until we reach a newline
        # or the end of the file
        while not data.endswith(b"\n"):
            char = outfile.read(1)

            # reached EOF
            if char == b"":
                break
            else:
                data += char

        fp.write(data)

    del data    # free up memory

def return_header_bytes(file_pointer):
    """
    Returns a string starting from the file_pointer until
    the first newline character.
    """
    to_ret = file_pointer.read(1)
    while not to_ret.endswith(b"\n"):
        to_ret += file_pointer.read(1)

    return to_ret

def merge_files(files):
    """
    Returns a file that has the contents of files merged
    together in one.
    Keeps only the header from the first file, and discards
    the rest as they are duplicates.
    """
    chunk_size = 100000000 # bytes, so 100MB
    master_file = os.path.join(working_dir, "temp.csv")

    with open(files[0], "rb") as fpointer:
        header = return_header_bytes(fpointer)

    # open master file for writing
    with open(master_file, "wb", buffering=0) as master_fp:
        master_fp.write(header)

        # loop through each file copying over the contents minus
        # the header
        for file in files:
            # read the temp file in chunks
            # and write it to the master file
            with open(file, "rb", buffering=0) as temp_fp:
                temp_fp.seek(len(header))

                data = temp_fp.read(chunk_size)
                while data != b"":
                    master_fp.write(data)
                    data = temp_fp.read(chunk_size)

                del data    # free up memory

    return master_file

def launch_processes(input_file, output_file, identifier):
    """
    Splits the output file into N temporary files.
    Launches a process to run the vlookup on each temp file.
    Merges the temp files back into one.
    Moves the final temp file to the output_file location.
    Deletes the N temp files.
    """
    # create temporary files equal to the amount of cpu cores
    cpu_count = multiprocessing.cpu_count()
    files = split_file(output_file, cpu_count)
    temp_files = []

    # load the input file into memory; this is a memory-hungry operation,
    # see note at top of file
    contents = return_csv_contents(input_file)

    # create sqlite3 database to store input mapping
    db_path, table = create_db_and_table(contents, identifier)
    load_db_content(db_path, table, contents)
    del contents    # free up memory

    # run vlookup with N processes equal to CPU count
    with multiprocessing.Pool(processes=cpu_count) as pool:
        results = []

        # launch asynchronous processing of each file
        for file in files:
            res = pool.apply_async(run_vlookup, (input_file, file, identifier, db_path, table))
            results.append(res)

        # wait for the processes to finish
        for result in results:
            res = result.get()
            temp_files.append(res)

        # collect the processes
        pool.close()
        pool.join()

    # delete input mapping db
    delete_db(db_path)

    # delete the small files
    for i in range(len(files)):
        os.remove(files[i])

    # merge temp files
    temp_file = merge_files(temp_files)

    # delete temp files
    for i in range(len(temp_files)):
        os.remove(temp_files[i])

    # replace original output file with merged temp file
    shutil.move(temp_file, output_file)

if __name__ == "__main__":
    print(timeit.default_timer())
    input_file = sys.argv[1]
    output_file = sys.argv[2]
    identifier = sys.argv[3]
    launch_processes(input_file, output_file, identifier)
    print(timeit.default_timer())


text:
Q: Does "Wordcount" program differs for MRv1(mapreduce) and MRv2(YARN) Does "Wordcount" program differs for different Hadoop(Mapreduce) versions.
atleast for MRv1(mapreduce) and MRv2(YARN)?
or
Programming is same but needed packages for wordcount is varying.......?

A: If you are talking about the WordCount example on Hadoop wiki, then there is no difference. You could either compile and run with MRv1 and MRv2 without modify any single line of the source code. All you need is to include correct class path as below:
javac -cp `hadoop classpath` WordCount.java

One thing to keep in mind is WordCount is just a HelloWorld example for Hadoop, which means you could implement it in various ways as you want. In fact, you could see the implementations in Hadoop 2.1.0 is already different from what you see on the Hadoop wiki


text:
Q: Ionic 5, login con facebook, solo funciona con mi mail de facebook Desarrollo app Ionic con login facebook
(Ionic CLI: 6.10.0 - Ionic Framework: @ionic/angular 5.6.11
Cordova CLI: 9.0.0 (cordova-lib@9.0.1) - Cordova Platforms: android 8.1.0)

(está en modo producción en developers facebook), y sucede lo siguiente:
Cuando la pruebo en mi móvil (Samsung A50, Android 11), con mi mail de facebook, funciona perfecto.
Cuando instalo apk en otro móvil (también Samsung A50, Android 11) y otro usuario/mail de facebook, si borro chaché y datos de la aplicación facebook en el móvil, la app Ionic hace login y da error buscando datos en getUserDetail. Si no borro caché y datos de la aplicación facebook en el móvil, da error en el login directamente (error: 4201 User cancelled dialog).
Adjunto código (variables ya definidas antes), les agradeceré la ayuda que me puedan brindar, muchísimas gracias
...
import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook/ngx';
...

constructor(
    ...
    private fb: Facebook,
    ...
) {}

fbLogin() {
    this.fb.login(['public_profile', 'email'])
      .then(res => {
        if (res.status === 'connected') {
          this.isLoggedIn = true;
          this.getUserDetail(res.authResponse.userID);
        } else {
          this.isLoggedIn = false;
        }
      })
      .catch(e => console.log('Error logging into Facebook', e));
  }
  getUserDetail(userid: any) {
    this.fb.api('/' + userid + '/?fields=id,email', ['public_profile'])
      .then(res => {
        this.users = res;
        this.global.email = this.users.email;
        this.router.navigate(["/menu", this.users.email]);
      })
      .catch(e => {
        alert("Error getUserDetail");
      });
  }


text:
Q: In Python (2.7), why is os.remove not identical to os.unlink? >>> import sys
>>> sys.version
'2.7.3 (default, Mar 13 2014, 11:03:55) \n[GCC 4.7.2]'
>>> import os
>>> os.remove is os.unlink
False
>>> os.remove == os.unlink
True

Why is that? Isn't os.unlink supposed to be an alias of os.remove?

A: To answer this question we have to dive a bit into the details of how the python interpreter works.  It might be different in other python implementations.
First let's start where the os.remove and os.unlink functions are defined.  In Modules/posixmodule.c they are registered as:
{"unlink",          posix_unlink, METH_VARARGS, posix_unlink__doc__},
{"remove",          posix_unlink, METH_VARARGS, posix_remove__doc__},

Note that the function pointers both point to posix_unlink in their ml_meth member.
For method objects, the == equality operator is implemented by meth_richcompare(...) in Objects/methodobject.c.
It contains this logic, which explains why the == operator returns True.
a = (PyCFunctionObject *)self;
b = (PyCFunctionObject *)other;
eq = a->m_self == b->m_self;
if (eq)
    eq = a->m_ml->ml_meth == b->m_ml->ml_meth;

For built-in functions m_self is NULL so eq starts out true.  We then compare the function pointers in ml_meth (the same posix_unlink referenced from the struct above) and since they match eq remains true.  The end result is that python returns True.
The is operator is simpler and stricter.  The is operator only compares the PyCFunctionObj* pointers.  They will be different -- they came from different structs and are distinct objects, so the is operator will return False.
The rationale is likely that they are separate functions objects (recall their docstrings are different) but they point to the same implementation, so the difference in behavior between is and == is justifiable.
is brings a stronger guarantee, and is meant to be fast and cheap (a pointer comparison, essentially).  The == operator inspects the object and returns True when its content matches.  In this context, the function pointer is the content.


text:
Q: WinSock error occured while downloading mail message as MSG file My environments are
Server Machine: DocuShare Server 6
Client Machine: Windows XP where DocuShare client 6, DocuShare outlook client 3, MS outlook 2007 and our C# application are installed.
We have a C# application to download mail message from DocuShare server using DocuShare API.
The application successfully downloads docushare mail messages as MSG file. But when the mail message has attachment with long name (in my case the attachment file name is
"New Tzunami Outlook Attachment Extractor User Guide 20100902.docx"), the application throws Windows Socket error while downloading. If the attachment file name is short, mail messages are downloaded successfully.
Here are the codes:
private void btnDownloadMails_Click(object sender, EventArgs e)
{
    MailArgument mailArg = new MailArgument();
    mailArg.server = textServer.Text;
    mailArg.user = textUser.Text;
    mailArg.password = textPwd.Text;
    DownloadMailAsMsg(mailArg);
}

void DownloadMailAsMsg(object s)
{
    MailArgument mailArg = s as MailArgument;
    long status = 0;

    DSServerMap.Server dsserver = new DSServerMap.Server();

    if (!SelectMappedServer(ref dsserver, mailArg.server))
        return;

    dsserver.DocuShareAddress = mailArg.server;
    dsserver.UserName = mailArg.user;
    dsserver.Password = mailArg.password;
    dsserver.Domain = "DocuShare";
    status = dsserver.Logon();

    if (status == 0)
    {
        IItemObj objParentItem;
        string[] emailHan = { "MailMessage-2919", "MailMessage-2924", "MailMessage-2925", "MailMessage-2926", "MailMessage-2926", "MailMessage-15", "MailMessage-30", "MailMessage-31" };
        foreach (string handnum in emailHan)
        {
            objParentItem = (IItemObj)dsserver.CreateObject(handnum);
            DSGATEWAYLib.IGatewayHandler gateway = (DSGATEWAYLib.IGatewayHandler)dsserver.Open();
            objParentItem.AttachGateway(gateway, true);
            objParentItem.Name = @"D:\emtest\" + handnum + ".msg";
            int flag = objParentItem.DSDownload(0);
        }
    }
}

Where I stuck is at the line: int flag = objParentItem.DSDownload(0); while downloading email which have attachment file named "New Tzunami Outlook Attachment Extractor User Guide 20100902.docx".
For checking, we trimmed the attachment file name to "ANew Tzunami OutAttachmen 01.docx" but we still got the same error.
The code objParentItem.DSDownload(0) return -300 value and at the same time DocuShare error dialog box pops up with following message
"Winsock error 123"

A: When DsAxess console is used to download the same mail message, we got the same WinSock error, so nothing can be done;).
We used WorldClient mail application for sending emails. We sent email with the attachment having "ANew Tzunami OutAttachmen 01.docx" file name using WorldCLient, which we failed to download. For the sake of tesing we used another application to send the email with the same attachment. This time we used MS word to send email with the same attachment and we succeeded downloading email using C# app and DsAxess console as well.
If you have anything about this, please share with us.
thank you.
Prakash


text:
Q: Exception Handler Not Working: Commiting to SQL Database with SQLAlchemy in Python I am trying to commit entries to a MySQL database using SQLAlchemy in Python. The function below was meant to allow me to commit a batch of entries, even if one or two of them contained errors that the database would not accept. However, when it gets to an entry that it cannot commit it does not skip it and go to the next one, it tries to commit the same entry over and over and over again, getting the same error message for that entry a thousand times. Why doesn't the trycatch in my function work?
def commitentry(database, enginetext, verbose = False):
    """
    Takes a database object and text string that defines the SQL
    engine and adds all entries in the database list to the SQL
    database.
    """

    engine = create_engine(enginetext)
    Session = sessionmaker()
    Session.configure(bind=engine)
    session = Session()
    counter = 0
    for entry in database:
        try:
            session.add(entry)
            session.commit()

        except Exception, e:
            print("Commit Error")

            if verbose:
                print(e)

        finally:
            counter += 1
            if verbose:
                print(counter, counter/float(len(database)))

    if verbose:
        print("Entries saved!")
    session.close()

A: When a commit fails it does not delete the object from memory like a successful commit. So when the next object is added to the session it is not alone, the object that just failed is still there. Adding session.rollback() to the except block will remove the object that cannot be saved to the database from the session, allowing the next object to be saved.
def commitentry(database, enginetext, verbose = False):
    """
    Takes a database object and text string that defines the SQL
    engine and adds all entries in the database list to the SQL
    database.
    """

    engine = create_engine(enginetext)
    Session = sessionmaker()
    Session.configure(bind=engine)
    session = Session()
    counter = 0
    for entry in database:
        try:
            session.add(entry)
            session.commit()

        except Exception, e:
            print("Commit Error")
            session.rollback()

            if verbose:
                print(e)

        finally:
            counter += 1
            if verbose:
                print(counter, counter/float(len(database)))

    if verbose:
        print("Entries saved!")
    session.close()


text:
Q: How do I define a macro with variadic method in objective-C? The method I am trying to call is;
- (void)addLogWithLevel:(MDCLogLevel)logLevel logContent:(NSString *)logContent, ...
{
    va_list args;
    va_start(args, logContent);
    NSString *message = [[NSString alloc] initWithFormat:logContent
                                               arguments:args];
    va_end(args);
    MDCLog *log = [MDCLog logWithContent:message content:logLevel];
    [self.deviceLogs addObject:log];
}

I have defined the macro as;
#define MDCLogDebug(format, ...) [[MDCLogController sharedController] addLogWithLevel:MDCLogLevelDebug logContent:(__VA_ARGS__)];

I have tried various formats of this macro, but nothing seems to work.
If I am to call;
MDCLogDebug(@"Test:%@", @"Hey");

All I see in the console is;

Hey

Where am I going wrong? I'm new to using Variadic methods and my C isn't so great!

A: Actually, your problem is not really related to Objective-C directly, but to C itself, as macros are plain C preprocessor directives.
In a macro, __VA_ARGS__ represents the arguments that are placed instead of the ....
So in your call to MDCLogDebug(@"Test:%@", @"Hey"), the format argument is @"Test:%@" and __VA_ARGS__ represents the rest of the arguments afterwards, namely simply @"Hey" in your case.
If you want to pass both the @"Test:%@" and @"Hey" as arguments to logContent:, you have to explicitly tell it so, using:
#define MDCLogDebug(format, ...) [[MDCLogController sharedController] addLogWithLevel:MDCLogLevelDebug logContent:format, __VA_ARGS__]

Note: An even better solution would be to use the ## prefix before __VA_ARGS__ so that the comma won't be added if __VA_ARGS__ is empty (namely if you only pass a format argument but nothing afterwards, like MDCLogDebug(@"Foo")):
#define MDCLogDebug(format, ...) [[MDCLogController sharedController] \
                                  addLogWithLevel:MDCLogLevelDebug \
                                       logContent:format, ## __VA_ARGS__]

(Note: I use backslashes in this last macro definition above to allow the macro to be written on multiple lines, instead of writing it on one single big long line)
For more information, see the official GCC documentation about Variadic Macros here.


text:
Q: ntop: Which HTTP downloads (URLs) caused the traffic? My server causes too much traffic, so I have installed ntop to monitor it.
On the Summary -> Traffic page in the Global TCP/UDP Protocol Distribution table I can see the traffic is periodically caused by HTTP.
On the All Protocols -> Traffic page in the first row there is the traffic (94,4%). But the first column (Host) shows my own server. Why is this?
When clicking there, I can see that the traffic in the Host Traffic Stats table. It is all in the Tot. Traffic Rcvd column. Therefore I think, one of my applications ist periodically downloading something big, or a lot.
But how to find out, what was downloaded? What are the downloaded URLs or at least the hosts that caused the most traffic?

A: Ntop is a network interface tool - it shows you the traffic going over various ports and protocols, but that's where it ends. What you need to look at now is to target the application that's processing that traffic, in this case Apache.
The easiest way to do this is to install a web usage tool, like webalizer (there are many others, awstats was the 'best' a while back, not sure what's king now). This will run through your logs and generate pages of statistics that you can use to see where the traffic was going, where it was coming from and who was doing it. For Example.

A: Fix the systematic Issue:
Having your application logs that make requests be unknown and all over the place is problem. This is going to bite you in the ass again and again, so I would set aside some time to address this problem. Find some way to index or aggregate them. This is larger problem project that you should raise.
The Problem at Hand:
For the problem at hand, I would recommend wireshark / tcpdump. Once you have a traffic capture, you can use all sorts of techniques to try to find it. In wireshark you could use "statistics / conversations", sort by bytes, and then drill down into the captures from there. Riverbed's non-free Cascade Pilot does have "Web Bandwidth by Object" view for captures that would be good at this -- you could request a trial.
If you are not familiar with wireshark, now is a good time learn. It is a tool most sysadmins use on a regular basis.
If you know the server taking the bandwidth, and it is a Linux server, you might try Nethogs (nethogs) to identify the process using the bandwidth.

A: You should examine your webservers access log, where all serviced requests are listed. You could filter for your webservers IP address and localhost and check most requested files. There are several tools for this but it depends on whatever webserver software you are using.


text:
Q: How to draw this graph using the tikz `graphdrawing` library? I tried many times but failed to draw the graph below using the tikz graphdrawing library. I am quite confused, especially by its "layouts" concepts.
Problem: How to draw the graph below using graphdrawing.

Code with graphdrawing stuff commented:
\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{positioning}
% \usetikzlibrary{graphs, graphdrawing}
% \usegdlibrary{layered, force}

\begin{document}
\begin{tikzpicture}[node distance = {1.0cm and 1.5cm}, v/.style = {draw, circle}]
  % \graph [spring layout, nodes = {}, horizontal = A to C]
  % {
  %   A -- C -- E,
  %   B -- {D -- F}
  % };

  \node (a) [v] {A};
  \node (c) [v, right = of a] {C};
  \node (e) [v, right = of c] {E};

  \draw (a) to node[above] {1} (c);
  \draw (c) to node[above] {3} (e);

  \node (b) [v, below = of a] {B};
  \node (d) [v, right = of b] {D};
  \node (f) [v, right = of d] {F};

  \draw (b) to node[below] {1} (d);
  \draw (d) to node[below] {4} (f);

  \draw (a) to node[left] {2} (b);
  \draw (c) to node[below] {2} (b);
  \draw (c) to node[right] {2} (d);
  \draw (e) to node[below] {3} (d);
  \draw (e) to node[right] {1} (f);
\end{tikzpicture}
\end{document}

A: I think you're trying to use graphdrawing when you actually should be using the normal graph instead. The graphdrawing library is for when you have stuff that follows a structural logic but the graph itself is not of a fixed nature. Quoting Till Tantau:

You do not specify where, exactly, the nodes and edges should be. This is something you leave to a graph drawing algorithm. The algorithm gets your description of the graph as an input and then decides where the nodes should go
  on the page.

The graph you're proposing, to me, looks like you want to specify where the nodes are, but you want to do it in a concise and powerful way. Quoting Till again:

There is nothing in the graph library that you cannot do using the normal \node and the edge commands. Rather, its purpose is to offer a concise and powerful way of specifying which nodes are present and how they are connected.

Here it is how you draw your graph using the graph library (no need for Lua):
\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{graphs, graphs.standard, quotes}% quotes library is for the [""] edges

\begin{document}
\begin{tikzpicture}[node distance = {1.0cm and 1.5cm}, v/.style = {draw, circle}]
  \graph[nodes={circle, draw}, grow right=2.25cm, branch down=1.75cm]{
    A -- ["1"] C -- ["3"] E,
    B -- ["1",swap] D -- ["4",swap] F,
    B -- ["2"] A,
    C -- ["2"] {D,B},
    D -- ["3",swap] E -- ["1"] F
  };
\end{tikzpicture}
\end{document}


text: Q: DCEF3 on C++ Builder, how to get ICefCookieManager I compiled DCEF3 in Rad Studio XE for C++. It works perfectly, but I don't know how to work with cookies. I read in delphi that I have to  create variable with type ICefCookieManager, but how can I get that class in C++ Builder? Thanks for help.


text:
Q: porque marca error con la etiqueta record Estoy añadiendo una pestaña a la vista del modelo de odoo que estoy modficando pero a la hora de actualizar el modulo me manda un error de que hay un record extra
Adjunto codigo:
```<?xml version="1.0" encoding="utf-8"?>

  <odoo>

<record id="view_mti_bascula_form" model="ir.ui.view">
    <field name="name">Formulario Bascula</field>
    <field name="model">mti_bascula</field>
    <field name="arch" type="xml">
        <form>
            <sheet>
                <group style="display:flex;">
                <field name="Proovedor_id" domain="[('category_id', 'in', [categoria_Proovedor_id])]"
                        options="{'no_create': True, 'no_open': True}"/>
                <field name="categoria_Proovedor_id" invisible="1"/>
                </group>
                <group style="display:flex;">
                    <field name="Operador"/>
                    <field name="Placas_Trac"/>
                </group>
                <group style="display:flex;">
                    <field name="Carta_porte" />
                    <field name="Destino" />
                    <field name="Via" required="1" />
                </group>
                 <group style="display:flex;">
                     <field name="Remitente"/>
                     <field name="Consignado"/>
                 </group>
                <div style="display:flex;">
                    <group>
                        <field name="Recibe"/>
                        <field name="Ejecutivo"/>
                        <field name="Mercancia"/>
                        <field name="Peso_bruto"/>
                    </group>
                </div>
                <button string="Traer Peso" type="object" name="traer_peso" class="oe_highlight"/>

                 <separator string="Detalles"/>

                <notebook>
                    <page string="detalles_bascula">
                        <group>
                            <field name="peso_id">
                                <tree editable="botom">
                                    <field name="Ancho"/>
                                    <field name="Alto"/>
                                    <field name="Volumen"/>
                                    <field name="Peso_Bruto"/>
                                    <field name="Descripcion"/>
                                    <field name="Palletizado" required="1" />
                                    <field name="Emplayado" required="1" />
                                    <field name="Flejado" required="1" />
                                    <field name="Sello" required="1" />
                                </tree>
                            </field>
                        </group>
                    </page>
                </notebook>
            </sheet>
        </form>
    </field>
</record>

<record id="mti_bascula" model="ir.actions.act_window">
    <field name="name">Bascula</field>
    <field name="res_model">mti_bascula</field>
    <field name="view_mode">tree,form</field>
</record>

<menuitem id="mti_menu_bascula" name="Bascula" parent="stock.menu_stock_root"  sequence="1"/>
<menuitem  action="mti_bascula" parent="mti_menu_bascula" id="bascula_menu" name="Bascula"   sequence="2"/>

             </odoo>```

la verda dno se porque manda ese error estoy batallando mucho con esa pestaña como le podria hacer o de que forma puedo resolver ese error porque en la terminal arroja quie hay un record extra antes mandaba otros errores con el modelo epro los pude resolver pero siempre que ya no hay erro me regresa al mismo de que hay una etiqueta record extra pero reviso el codigo y no hay nada


text:
Q: Deployment failed because the application specification file specifies an unsupported operating system Using AWS code deploy service to deploy application on Linux server on ec2 instance. Keep getting error message

The deployment failed because the application specification file specifies an unsupported operating system (). Specify either "linux" or "windows" in the os section of the AppSpec file, and then try again.

I have created appspec.yml file and clearly mentioned
version: 0.0
os: linux

However, still keep getting this error on BeforeInstall event on code deploy.
I have verified code deploy agent on the ec2 server. The service is up and running.
Any help is appreciated. Thanks in advance!

A: Are you editing that file from a Windows box? I have seen problems with Windows line endings cause similar issues. Make sure you are using proper Linux line endings in that file.


text:
Q: The Irish weather or Irish weather The \ no article Irish weather is normally cool and wet in October.
I thought it should be the Irish weather because there is only one Irish weather. However, I have found the following examples from Cambridge dictionary which confuse me.
The weather is expected to remain clear for the next few days.
The rescue operation has been complicated by (zero article) bad weather.
(zero article) Fair weather was forecast for the following day.
The weather was good at the start of the week.

A: Both

Irish weather is normally cool and wet in October.

and

The Irish weather is normally cool and wet in October.

are perfectly normal and grammatical. Without the article, "Irish weather" means "all weather in Ireland". There might be multiple weather patterns, but the speaker is saying that they share this characteristic. In this case the meaning is unchanged.
In general at the start of a sentence "The weather" is more common, but can be replaced by an adjective indicating what whether is meant, such as "Irish weather"

The weather is expected to remain clear for the next few days.

When speaking of weather in general or in a particular area (often implied by context) an article is usual in this construction. However

Clear weather is expected to persist for the next few days.

would not use an article, and is perfectly normal. Tis is much like your example:

Fair weather was forecast for the following day.

This could be recast as

The weather was forecast to be fair for the following day.

About the rescue example in the question:

*

*The rescue operation has been complicated by bad weather.

*The rescue operation has been complicated by the bad weather.

The meaning is not much different between these two. The first might refer to multiple instances of bad weather, or bad weather in several different places.  The second emphasized "the bad weather" as a unitary thing to a greater degree. Both are grammatical and common.

A: Definite Article is used when you refer to a specific thing in context. However, there are some situations in which you can not use definite article such are:
countries, places, widely-known things...
Ex:
Wrong:The Brazil is very hot;
Correct: Brazil is very hot;
Definite Article explains itself why it can't be used with such contexts mentioned above: Definite Article is used to specify and unicalize something, a country doesn't need to receive such highlight since it is already a specific and unique thing.

The weather is expected to remain clear for the next few days.

In the example above, definite article was used probably because the speaker was referring to a specific weather (hot, cold, sunny...) not to the word weather itself that refers to the climatic conditions.


text:
Q: Error/warning message in PHP "PHP Notice: Undefined offset: 1" I am using the below PHP code but it is generating an error/warning message:

PHP Notice:  Undefined offset: 1

The code runs as expected.
while(1) {
    while($data = fgets($irc, 128)) {

        $ex = explode(' ', $data);

        if($ex[0] == "PING"){
            fputs($irc, "PONG ".$ex[1]."\n");
        }

        if($ex[1] == "265"){
            $lusers = str_replace(',', '', $ex[8]);
            $gusers = $ex[10];
        }

    }
}

I cannot see what is wrong in the code. It is running as expected so why is the error/warning message being generated?
Suggestion to use print_r($ex) shows:
Array
(
    [0] => SeIKVfMCuzNTGjZ

)
PHP Notice:  Undefined offset: 1

Should I just add a check that $ex > 0 or is there a better way?
I updated code so it only runs if $ex > 0:
while(1) {
    while($data = fgets($irc, 128)) {

        $ex = explode(' ', $data);

        if($ex[0] == "PING"){
            fputs($irc, "PONG ".$ex[1]."\n");
        }

        if(count($ex) > 0){

            if($ex[1] == "265"){
                $lusers = str_replace(',', '', $ex[8]);
                $gusers = $ex[10];
            }

        }

    }
}
?>

but I still get the error/warning message. How is it possible?

A: This should work for you:
if(isset($ex[1]) && $ex[1] == "265") {
    //do stuff

} else {
    echo "Index doesn't exist!";
}


text:
Q: ASP:DropDown Post Back I Have a and ASP.NET GridView which is set so
<asp:GridView ID="GridView1" runat="server"
            AutoGenerateColumns="False"
            CellPadding="4"
            DataKeyNames="Pric_PricingID"
            DataSourceID="CRMDataSource1"
            EnableModelValidation="True"
            GridLines="None"
            AllowPaging="True"
            AllowSorting="True"
            Width="100%"
            CssClass="GRIDHEAD"
            onselectedindexchanged="GridView1_SelectedIndexChanged">

One of the fields I need to be a drop down value when the row is edited the user will select a value and click update this will then set the column value of price_c_alfsupreq to the select value I believe that this is done using a post back? I am new to this so any help would be fantastic.
Thanks

A: You can try to add a commandfield in your gridview. This will set a "Edit"-button. When this button is clicked, you will get the EditItemTemplates which you see below.
<asp:CommandField ShowEditButton="True" CancelText="Cancel" EditText="Edit"
        UpdateText="Save">
    </asp:CommandField>

And then add a templatefield with a editTemplate inside - here the dropdownlist is enabled, so you can chose from it.
<asp:TemplateField HeaderText="Dropdown">
        <ItemTemplate>
            <asp:Dropdownlist ID="ddl1" runat="server"
                Enabled="false" />
        </ItemTemplate>
        <EditItemTemplate>
            <asp:Dropdownlist ID="ddl1Edit" runat="server"
                Enabled="true" />
        </EditItemTemplate>
    </asp:TemplateField>

and in your datasource add a UpdateCommand, which evaluates the value in the ddl1Edit.


text:
Q: Windows Phone link from Tile error I have a list of theaters and I created a secondary tile from my application to navigate directly to specific theater. I pass the id of the theater in query string :
I load the theaters from a WCF service in the file "MainViewModel.cs"
In my home page, I have a list of theaters and I can navigate to a details page.
But when I want to navigate from the tile, I have an error...
The Tile :
ShellTile.Create(new Uri("/TheaterDetails.xaml?selectedItem=" + theater.idTheater, UriKind.Relative), tile, false);

My TheaterDetails page :
 public partial class TheaterDetails : PhoneApplicationPage
{

    theater theater = new theater();

    public TheaterDetails()
    {
        InitializeComponent();

    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {

        if (!App.ViewModel.IsDataLoaded)
        {
            App.ViewModel.LoadData();

        }

        if (DataContext == null)
        {

            string selectedIndex = "";
            if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
            {
                int index = int.Parse(selectedIndex);

                    theater = (from t in App.ViewModel.Theaters
                               where t.idTheater == index
                               select t).SingleOrDefault();

                    DataContext = theater;

....
....
....

The error :
https://dl.dropboxusercontent.com/u/9197067/error.png
Like if the data were not loaded...
Do you have an idea where the problem come from ?
The solution could be easy but I am a beginner... Maybe it's because I load the data asynchronously and the application doesn't wait until it's done...
Thanks
EDIT :
My LoadData() method :
 public void LoadData()
    {

        client.GetTheatersCompleted += new EventHandler<ServiceReference1.GetTheatersCompletedEventArgs>(client_GetTheatersCompleted);
        client.GetTheatersAsync();

 // Other get methods...

        this.IsDataLoaded = true;
        }

private void client_GetTheatersCompleted(object sender,       ServiceReference1.GetTheatersCompletedEventArgs e)
    {
        Theaters = e.Result;
    }

A: You should check to see which variable is actually null. In this case it looks to be Theaters (otherwise the error would have thrown earlier).
Since Theaters is populated from a web call it is most likely being called asynchronously, in other words when you return from LoadData() the data is not yet there (it's still waiting for the web call to come back), and is waiting for the web service to return its values.
Possible solutions:

*

*Make LoadData() an async function and then use await LoadData(). This might require a bit of rewriting / refactoring to fit into the async pattern (general introduction to async here, and specific to web calls on Windows Phone here)

*A neat way of doing this that doesn't involve hacks (like looping until the data is there) is to raise a custom event when the data is actually populated and then do your Tile navigation processing in that event. There's a basic example here.

A: So the solution that I found, thanks to Servy in this post : Using async/await with void method
I managed to use async/await to load the data.
I replaced my LoadData() method by :
    public static Task<ObservableCollection<theater>> WhenGetTheaters(ServiceClient client)
    {
        var tcs = new TaskCompletionSource<ObservableCollection<theater>>();
        EventHandler<ServiceReference1.GetTheatersCompletedEventArgs> handler = null;
        handler = (obj, args) =>
        {
            tcs.SetResult(args.Result);
            client.GetTheatersCompleted -= handler;
        };
        client.GetTheatersCompleted += handler;
        client.GetTheatersAsync();
        return tcs.Task;
    }

    public async Task LoadData()
    {

        var theatersTask = WhenGetTheaters(client);
        Theaters = await theatersTask;

        IsDataLoaded = true;

    }

And in my page :
    protected override async void OnNavigatedTo(NavigationEventArgs e)
    {
        if (!App.ViewModel.IsDataLoaded)
        {
           await App.ViewModel.LoadData();
        }


text:
Q: Strange behavior in shiny RMarkdown I'm having some very strange behavior when knitting a shiny RMarkdown HTML document. In the MWE below I simply (1) include a slider input, (2) include a column in the df as the value of the input and then (3) return the df. The MWE below returns the error Error in : Column "b" must be length 1 (the number of rows), not 0. If I take out the multiplication of the input value when I assign a value to b, the document knits with no problem. MWE:
---
output: html_document
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
```

Testing

```{r eruptions, echo=FALSE}
# Input slider
sliderInput("test", "Test", value = 0.5, min = 0, max = 1, width = "100%")

# Pre-define df
output <- reactiveValues(data = data.frame(a = 20))

observe({

  output$data <- output$data %>%
    # Manipulate df
    mutate(b = input$test * 2)

})

# Return df
renderDataTable({output$data})

```

Does anyone know what could be causing this strange behavior?

A: Here's what I suspect is going on ---
I think that the first time your observe is run through, that input$test is NULL.
If your mutate sets a column to NULL, it would just remove that column.
If you use input$test * 2 that will return an empty vector numeric(0). Trying to add a column with an empty vector would give the error.
If you add req(input$test) at the beginning of your observe function, does it work?


text:
Q: Convert Month Year function to Time Ago PHP
Possible Duplicate:
PHP How to find the time elapsed since a date time?

I have the following which produces MONTH YEAR.
<?php echo date('F Y', strtotime($video['Video']['posted_date'])); ?>

I'd like this to output to "Time" ago. i.e 3 hours ago, 6 months ago, 2 years ago.
Any help will be very much appreciated.
Thanks
Andy

A: $now            = new DateTime(date("Y-m-d H:i:s"));
$videoPosted    = new DateTime($video['Video']['posted_date']);
$interval       = $now->diff($videoPosted);

echo $interval->format('%h hours, %m month and %d days ago');

Use only if PHP version > 5.3

A: If you use php 5.3+, you are looking for DateInterval::format()

A: this will help you to calculate date difference: How to calculate the difference between two dates using PHP?
and after that you can convert the result using strtotime()


text:
Q: How to speed up SVG morphing I am building a filtering menu for a shop, and I am using svg morphing to animate some svg's, it works well when an svg is accessed by getElementById, but everything gets performance hits when in a loop.
This is my js:
var iconNodes = document.querySelectorAll(".button-filter");

iconNodes.forEach(item => {
  item.addEventListener('click', event => {
    if (item.classList.contains("open")) {
      item.classList.remove("open");
      item.getElementsByClassName('anim-up')[0].beginElement();
      item.getElementsByClassName("button-text")[0].innerHTML = "Open";
    } else {
      item.classList.add("open");
      item.getElementsByClassName('anim-down')[0].beginElement();
      item.getElementsByClassName("button-text")[0].innerHTML = "Close";
    }
  })
});

And html:
<button type="button" class="button-filter">

Discount
        <svg id="dropdown" viewBox="0 0 194.6 185.1" class="inline-block w-10 h-10">
            <polygon fill="#A2A7AA" points="53.4,65.1 96.6,65.1 75,90.1 75,90.1">
                <animate class="anim-up" begin="indefinite" fill="freeze" attributeName="points" dur="500ms" to="75,65.1 75,65.1 96.6,90.1 53.4,90.1"/>
                <animate class="anim-down" begin="indefinite" fill="freeze" attributeName="points" dur="500ms" to="53.4,65.1 96.6,65.1 75,90.1 75,90.1"/>
            </polygon>
        </svg>

</button>

How could I change my approach?


text:
Q: Samba share is accesable only for one user, but should be accesable for two I want to share folder for myself and another user with samba. I have created smb.conf like this:
[global]
        workgroup = WORKGROUP
        server role = standalone server
        map to guest = never
        usershare allow guests = no
        hosts allow = 192.168.0.0/16
        hosts deny = 0.0.0.0/0

[movies-library-share]
        comment = share of movies in local network
        path = /media/user1/multimedia/video/movies-library
        browseable = yes
        writeable = yes
        valid users = user1,user2

user1 is me and I can access to this share and see everything and I can write so it works fine, but user2 can only log in, everything else is not accessible, even reading files. My question is how to make it readable and writable for user2? I assume that this could be related with permissions to access movies-library folder for user2. I'm not sure how should I assign proper permissions or group.

A: Your two users are by default in their own groups: user1:user1 and user2:user2.
The files are likely owned by user1:user1 with no access to 'other' users.
Solutions range from simplest to most robust:

*

*Pretend everyone is user1 by adding force user = user1 to the share.

*

*user2 now has all the rights and permissions that user1 has.

*As per @DeeJayh's comment, you will also want to add valid users = user1 user2 so that user3 and 4, etc cannot browse the share.

*

*Pretend everyone is group user1 by adding force group = user1 to the share.

*

*Same caveat as above but you can remove group write access with chmod g-w ...

*

*Grant EVERYONE read/execute access.

*

*This including user2

*Everyone on the system will have access to the files as they exist now, though not via samba.

*Future additions will need this run each time.

*chmod -R o+rx /media/user1/multimedia/video/movies-library

*

*Share group

*

*Create a group that user1 and user2 are both members of and set ownership of the files to that group.

*Add that group to both users.

*Set the group ownership of the share to that group.

*Make sure everything in that directory is group accessible.

*SetGID on the directory so future additions inherit the group.

*

sudo usermod -a -G media-share user1
sudo usermod -a -G media-share user2
chown -R user1:media-share /media/user1/multimedia/video/movies-library
chmod -R g+rx /media/user1/multimedia/video/movies-library
chmod -R g+s /media/user1/multimedia/video/movies-library```

*

*If you add files via samba then you can set the directory and file mask to ensure group permissions by adding create mask = 0750 and directory mask = 0770 to the share.


text:
Q: Boostrap Textarea allow select text how can I allow the users to select text of a readonly bootstrap textarea.
Thats my current code:
   <div class="form-group">
   <textarea class="form-control" id="exampleTextarea" rows="3" readonly style="height: 200px; max-width: 100%;"></textarea>
   </div>

CSS:
    .form-control[disabled],
.form-control[readonly],
fieldset[disabled] .form-control {
    background-color: #F5F5F5;
    color: #888888;
}

Thank you
With best regards


text:
Q: Log out user after inactivity with JWT Access and Refresh tokens I implement autentication mechanism in web application with Angular 2.
I going to use JSON Web Token. Two types of token, Access token (short-lived) and Refresh token (long-lived) which are described here: https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/
I want to obtain result which is common when session/cookies are used. After a period time of user inactivity, the user is logged out. Which basiclly means that the browser displays the login page and in case of using JWT, the tokens are removed from browser localStorage or storage cookies.
I do not see the way how to do this, relaing only on Access and Refresh tokens.
When Access token is expired (eg. each 10 minutes), the new one is requested using Refresh token (which expires each 8 hours). But what when the user is inactive for eg. 1 hour? Refresh token is still valid so next user interaction will cause obtain new Access token and the user sill can use th app.
Maybe there are some Angular2 or JavaScript mechanisms which in case of user inactivity, perform some action or redirect to login page?

A: Just cache timestamp of last user activity (for users you want to run periodic check) and revoke refresh token when it cross your threshold + remove user from that cache. If you really really need that behaviour. If you accept server side solution.
If you mean Angular client side solution, just forget the token pair after given inactivity period.

A: If you want to use token as flag to terminate session just don't refresh it, just set a short time of life and when server replies with 401 sign out the user. For this approach you have to generate a new token after each user interaction.

A: You Can Implement some client side rule i.e Whenever access token going to expire redirect them to login page or you can lock user's screen to provide enter credential again.Please look features of angular2 JWT


text:
Q: "Out of" OR just "of" Which one is most correct way of describing the number? Should it say:

reported that 414 (which is 78%) of (the) 530 people.

or is it:

reported that 414 (which is 78%) OUT of (the) 530 people.

A: Either is correct, and you will see both.
The problem comes from the fact that it is quite idiomatic to say "414 out of 530" but not at all idiomatic to say "78% out of 530." With the sentence constructed as you currently have it, some will find awkward whatever you say.
I might advise rewriting along the lines of "414 out of 530 (78%) ..." or just "78% of 530 ..."
EDIT: When talking about inferences from samples, it is important to know the size of the sample to estimate the reliability of any inferences being made. But what we are usually interested in are the proportions shown by the sample because we want to extrapolate to the overall population that the sample is presumed to represent. Thus, upon reflection, saying "78% of a sample of 530" is probably best if the 530 are a sample. That is, your English should make clear whether you are dealing with descriptive statistics or inferential statistics.


text:
Q: Server error in ASP.NET application when I am trying to connect to the server I have a problem with my first ASP.NET webforms app. I'm following a Microsoft tutorial. When I'm running the application to create the database for first time, this error appears in the browser:

Server Error in '/' Application.
  Invalid value for key 'attachdbfilename'.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Invalid value for key 'attachdbfilename'.

I'm not sure if my connection string is fine
DESKTOP-6ANEE4G\MSSQLSERVER01 this is the name of my database.
Tutorial: https://learn.microsoft.com/es-es/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/ui_and_navigation
<connectionStrings>
    <add name="DefaultConnection"
         connectionString="Data Source=(DESKTOP-6ANEE4G\MSSQLSERVER01)\v11.0;Initial Catalog=aspnet-WingtipToys;Integrated Security=True"
         providerName="System.Data.SqlClient" />
    <add name="WingtipToys"
         connectionString="Data Source=(DESKTOP-6ANEE4G\MSSQLSERVER01)\v11.0;AttachDbFilename=|DataDirectory|\wingtiptoys.mdf;Integrated Security=True"
         providerName="System.Data.SqlClient" />
</connectionStrings>