text:
Q: Progress Bar PyQt5 style Minecraft Forge I have a request on PyQt5 to which I am looking for a solution. I'm creating a videogame in Pygame and for uploading resources (images, audio etc) I would like to use PyQt5. I have already created a window with progress bar by following this and modified it graphically (css, etc.).
My goal is to make the window in PyQt5 in the Minecraft Forge style, where, if you have, there is a white window with a progress bar, where mods, textures, etc. are loaded and the name is written under the loaded resource bar and the percentage (or in the case of Minecraft Forge the quantity, example: 74/1349)
The problem is that I can not understand how I should remove the button in the example and replace it so that every time a resource is loaded from the program, the progress bar is updated.
In my case, the "load class" is called when the "game class" is initialized.
To explain better, in PyQt5 I would like to create a window with the progress bar like this:

Where from the "game class" the resources are loaded and the progress bar for each resource loaded is updated, or otherwise something like that.
Edit for eyllanesc:

I tried with:
class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(30, 40, 200, 25)
        self.pbar.setFormat("%v/%m")
        self.pbar.setMaximum(150)
        self.pbar.setValue(0)
        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('QProgressBar')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

    while True:
        g = input("aggiornare?")
        if g is "y":
            w.pbar.setValue(w.pbar.value()+1)

class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(30, 40, 200, 25)
        self.pbar.setFormat("%v/%m")
        self.pbar.setMaximum(150)
        self.pbar.setValue(0)
        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('QProgressBar')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()

    while True:
        g = input("aggiornare?")
        if g is "y":
            w.pbar.setValue(w.pbar.value()+1)

        sys.exit(app.exec_())

class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(30, 40, 200, 25)
        self.pbar.setFormat("%v/%m")
        self.pbar.setMaximum(150)
        self.pbar.setValue(0)
        timer = QTimer(self)
        timer.start(1000)
        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('QProgressBar')
        self.show()
        self.run()

    def run(self):
        while True:
            g = input("aggiornare?")
            if g is "y":
                self.onTimeout()

    def onTimeout(self):
        self.pbar.setValue(self.pbar.value()+1)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    sys.exit(app.exec_())

I have also tried in other ways, but they are all similar to each other.

A: To set the text format you must use the setFormat() method, you must set the maximum value through setMaximum() and the current value through setValue(), in the following example I use QTimer to simulate the resource load:
Complete code:
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import  *

class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(30, 40, 200, 25)
        self.pbar.setFormat("%v/%m")
        self.pbar.setMaximum(150)
        self.pbar.setValue(1)
        timer = QTimer(self)
        timer.timeout.connect(self.onTimeout)
        timer.start(1000)
        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('QProgressBar')

    def onTimeout(self):
        self.pbar.setValue(self.pbar.value()+1)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

Output:

In pygame one is in charge of generating an infinite loop but in PyQt one calls that loop through app.exec_(), that is, that loop is internal. So the input() should not be used directly since it locks that loop and generates the GUI behaves inadequately, what you should do is create another thread and run it there for it use QRunnable and QThreadPool, in addition to QMetaObject::invokeMethod() to update the values as shown below:
import sys

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(30, 40, 200, 25)
        self.pbar.setFormat("%v/%m")
        self.pbar.setMaximum(150)
        self.pbar.setValue(0)
        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('QProgressBar')
        self.show()
        self.runnable = Runnable(self)
        QThreadPool.globalInstance().start(self.runnable)

    @pyqtSlot()
    def updateProgressBar(self):
        self.pbar.setValue(self.pbar.value()+1)

class Runnable(QRunnable):
    def __init__(self, w):
        QRunnable.__init__(self)
        self.w = w

    def run(self):
        while True:
            g = input("aggiornare?")
            if g is "y":
                QMetaObject.invokeMethod(self.w, "updateProgressBar", Qt.QueuedConnection)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    sys.exit(app.exec_())


text:
Q: Are there any "default" properties which hold for almost all topological spaces in analysis? What is the simplest/most general commonly used (type of) topological space in analysis?
For instance, every example I can think of in analysis is first-countable.
I don't think it can be metric spaces, since there are non-metrizable spaces (for example spaces of weak-* functionals) of use in analysis.
I was thinking perhaps separable topological vector spaces which are either T0, T1, or T2. (I'm not sure which separation axiom is most appropriate though.)
Finally, which connectedness/compactness properties would we want?
Would local path-connectedness (or even local connectedness) be too strong in general? What about local compactness or paracompactness? Local finiteness?
EDIT: Considering the points brought up by Calvin Khor and Qiyu Wen below, I changed "separable" to "first-countable".
Related, but different question: Measuring the set-theoretical complexity of sets/spaces encountered in general analysis
In contrast, I am asking about topological properties of spaces in analysis.
EDIT: See also: https://math.stackexchange.com/a/1843091/327486.
These questions are also (indirectly) related: Is Every (Non-Trivial) Path Connected Space Uncountable?, Why study non-T1 topological spaces?, What is the motivation behind the arbitrary union topological axiom?

A: For future reference of anyone who might have found this question accidentally and wants to know the answer: https://math.stackexchange.com/a/1843091/327486.

redpajama_set_name: RedPajamaStackExchange


text:
Q: DetailsView image updating problem I have DetailsView with users Info (Name, Email, Picture). That DetailsView control can be edited.
Values are from DataBase
 protected void DVUserInfoShow_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{

    FileUpload EditAvatar = (FileUpload)DVUserInfoShow.FindControl("EditAvatar");
    if (EditAvatar.HasFile)
    {
        string image_path = "~/images/user_images/" + EditAvatar.FileName;
        EditAvatar.SaveAs(Server.MapPath(image_path));
        e.NewValues["Avatar"] = EditAvatar.FileName;

    }

    else
    {
        e.NewValues["Avatar"] = e.OldValues["Avatar"];
    }

}

The problem is with e.NewValues["Avatar"] = e.OldValues["Avatar"];, when user updates his name and email, the picture value is set to null. And that code doesn't work. What I'm doing wrong?

A: OldValues collection is only available when DetailView is bounded with a declarative DataSource, otherwise OldValues collection will contain null in ItemUpadting event.
What you can do is inside DVUserInfoShow_ItemUpdating event, get current data from database and save in some local variables.


text:
Q: Symfony Form for ManyToMany Entity using a custom query builder The error message looks like this:

[Semantical Error] line 0, col 58 near 'events = :eventId':
  Error: Invalid PathExpression. StateFieldPathExpression or
  SingleValuedAssociationField expected.

Which is right, since it's a ManyToMany join, with a join table. But how do I have to load those entities?
The problem is in the activity form (at the end). I try to load town's which are assigned with a ManyToMany join to an specific event.
Code says more than 1000 words, so take a look (:
So I have three Entities in a Symfony app. Event, Town, Activity
The Event looks like this:
// ...

/**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=255)
 * @Gedmo\Versioned
 */
private $name;

/**
 * @ORM\ManyToMany(targetEntity="Town", inversedBy="events")
 * @ORM\JoinTable(name="Events_to_Towns")
 **/
private $towns;

/**
 * @ORM\OneToMany(targetEntity="Activity", mappedBy="event")
 */
private $activitys;

// ...

The Town looks like this:
// ...

/**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=255)
 * @Gedmo\Versioned
 */
private $name;

/**
 * @ORM\ManyToMany(targetEntity="Event", mappedBy="towns")
 */
private $events;

/**
 * @ORM\OneToMany(targetEntity="Activity", mappedBy="town")
 */
private $activitys;

// ...

The Activity looks like this:
// ...

/**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=255)
 * @Gedmo\Versioned
 */
private $name;

/**
 * @ORM\ManyToOne(targetEntity="Town", inversedBy="activitys")
 * @ORM\JoinColumn(name="town_id", referencedColumnName="id")
 */
private $town;

/**
 * @ORM\ManyToOne(targetEntity="Event", inversedBy="activitys")
 * @ORM\JoinColumn(name="event_id", referencedColumnName="id")
 */
private $event;

// ...

That's all working. However the problem is in the form for an Activity, when I'd like to assign a Town, or multiple. I try to only load towns that are mapped to the event.
// ...

public function __construct($eventId) {
    $this->_eventId = $eventId;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $eventId = $this->_eventId;

    $builder
        // ...

        // this work's as expected!
        ->add('category', 'entity', array(
            'required'      => true,
            'label'         => 'Kategorie',
            'class'         => 'FooEventBundle:Category',
            'property'      => 'name',
            'query_builder' => function(\Foo\EventBundle\Entity\CategoryRepository $er) use ($eventId) {
                return $er->createQueryBuilder('c')
                    ->select('c')
                    ->where('c.event = :eventId')
                    ->setParameter('eventId', $eventId)
                ;
            }
        ))

        // here's the problem!
        ->add('town', 'entity', array(
            'required'      => true,
            'label'         => 'Stadt',
            'class'         => 'FooEventBundle:Town',
            'property'      => 'name',
            'query_builder' => function(\Foo\EventBundle\Entity\TownRepository $er) use ($eventId) {
                return $er->createQueryBuilder('t')
                    ->select('t')
                    ->where('t.events = :eventId')
                    ->setParameter('eventId', $eventId)
                ;
            }
        ))

        // ...

    ;
}

// ...

A: Something like:
            $er->createQueryBuilder('t')
            ->select('t')
            ->join('t.events', 'e')
            ->where('e.id = :eventId')
            ->setParameter('eventId', $eventId)

Should work.


text:
Q: The nsupdate not updating the records nsupdate not update the records. Try to find where I'm wrong but I can't.
> server 192.168.1.117
> update delete _kerberos-master._tcp.example.com. SRV
> update add _kerberos-master._tcp.example.com. 3600 IN SRV 0 100 88 idmserver1.example.com.
> update delete _kerberos-master._udp.example.com. SRV
> update add _kerberos-master._udp.example.com. 3600 IN SRV 0 100 88 idmserver1.example.com.
> update delete _kerberos._tcp.example.com. SRV
> update add _kerberos._tcp.example.com. 3600 IN SRV 0 100 88 idmserver1.example.com.
> update delete _kerberos._udp.example.com. SRV
> update add _kerberos._udp.example.com. 3600 IN SRV 0 100 88 idmserver1.example.com.
> update delete _kerberos.example.com. TXT
> update add _kerberos.example.com. 3600 IN TXT "example.COM"
> update delete _kerberos.example.com. URI
> update add _kerberos.example.com. 3600 IN URI 0 100 "krb5srv:m:tcp:idmserver1.example.com."
> update add _kerberos.example.com. 3600 IN URI 0 100 "krb5srv:m:udp:idmserver1.example.com."
> update delete _kpasswd._tcp.example.com. SRV
> update add _kpasswd._tcp.example.com. 3600 IN SRV 0 100 464 idmserver1.example.com.
> update delete _kpasswd._udp.example.com. SRV
> update add _kpasswd._udp.example.com. 3600 IN SRV 0 100 464 idmserver1.example.com.
> update delete _kpasswd.example.com. URI
> update add _kpasswd.example.com. 3600 IN URI 0 100 "krb5srv:m:tcp:idmserver1.example.com."
> update add _kpasswd.example.com. 3600 IN URI 0 100 "krb5srv:m:udp:idmserver1.example.com."
> update delete _ldap._tcp.example.com. SRV
> update add _ldap._tcp.example.com. 3600 IN SRV 0 100 389 idmserver1.example.com.
> send
Reply from SOA query:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id:   3796
;; flags: qr aa ra; QUESTION: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0
;; QUESTION SECTION:
;_kerberos-master._tcp.example.com. IN      SOA

;; AUTHORITY SECTION:
example.com.                86400   IN      SOA     ns1.example.com. root.example.com. 14 3600 1800 604800 86400

Found zone name: example.com
The master is: ns1.example.com
Sending update to 192.168.1.117#53
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:  63664
;; flags:; ZONE: 1, PREREQ: 0, UPDATE: 22, ADDITIONAL: 0
;; UPDATE SECTION:
_kerberos-master._tcp.example.com. 0 ANY    SRV
_kerberos-master._tcp.example.com. 3600 IN  SRV     0 100 88 idmserver1.example.com.
_kerberos-master._udp.example.com. 0 ANY    SRV
_kerberos-master._udp.example.com. 3600 IN  SRV     0 100 88 idmserver1.example.com.
_kerberos._tcp.example.com. 0       ANY     SRV
_kerberos._tcp.example.com. 3600    IN      SRV     0 100 88 idmserver1.example.com.
_kerberos._udp.example.com. 0       ANY     SRV
_kerberos._udp.example.com. 3600    IN      SRV     0 100 88 idmserver1.example.com.
_kerberos.example.com.      0       ANY     TXT
_kerberos.example.com.      3600    IN      TXT     "EXAMPLE.COM"
_kerberos.example.com.      0       ANY     URI
_kerberos.example.com.      3600    IN      URI     0 100 "krb5srv:m:tcp:idmserver1.example.com."
_kerberos.example.com.      3600    IN      URI     0 100 "krb5srv:m:udp:idmserver1.example.com."
_kpasswd._tcp.example.com.  0       ANY     SRV
_kpasswd._tcp.example.com.  3600    IN      SRV     0 100 464 idmserver1.example.com.
_kpasswd._udp.example.com.  0       ANY     SRV
_kpasswd._udp.example.com.  3600    IN      SRV     0 100 464 idmserver1.example.com.
_kpasswd.example.com.       0       ANY     URI
_kpasswd.example.com.       3600    IN      URI     0 100 "krb5srv:m:tcp:idmserver1.example.com."
_kpasswd.example.com.       3600    IN      URI     0 100 "krb5srv:m:udp:idmserver1.example.com."
_ldap._tcp.example.com.     0       ANY     SRV
_ldap._tcp.example.com.     3600    IN      SRV     0 100 389 idmserver1.example.com.

Reply from update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:  63664
;; flags: qr; ZONE: 1, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; ZONE SECTION:
;example.com.                       IN      SOA

> ```

Has you can see I got 0 update.


text:
Q: Is a continuous function vanishing at infinity always C_0? Let $f \colon \mathbb{R}^n \to \mathbb{R}$ be a continuous function with
$$ \lim_{|x| \to \infty} f(x) = 0. $$
Does that imply $f \in C_0$, i.e. is there a compact set $K_{\epsilon}$ for every $\epsilon > 0$, such that
$$ |f(x)| < \epsilon \qquad \forall x \in \mathbb{R}^n \setminus K_{\epsilon} $$
Note: It obviously is true for $n = 1$. The case I need to solve is $n = 2$ with $f \in C^2$.

A: The (usual) definition of the limit simply means that for every $\varepsilon > 0$, there is some $R_\varepsilon>0$ such that for all $x \in \Bbb{R}^n$ with $|x|>R_\varepsilon$, we have $|f(x)| < \varepsilon$.
EDIT: If you have a different definition of this limit, the proof might be slightly more involved.
Hence, we can simply take $K_\varepsilon = \{x \in \Bbb{R}^n \mid |x| \leq R_\varepsilon\}$, which is closed and bounded, hence compact (because we are in a finite-dimensional space, so that Heine-Borel is applicable).

A: In general,
$$
\lim_{g(x)\to \infty}f(x)=0
$$
means that
$$
\forall \epsilon>0,\; \exists M_\epsilon:g(x)>M_\epsilon\implies |f(x)|<\epsilon
$$
In this case, as stated before, you just need to take $K_\epsilon=\{x:g(x)\le M_\epsilon\}$.

A: For any sequence $\{a_n\} \subset \mathbb{R}$, $a_n \to \infty$ means $\forall_{R>0} \exists_{N \in \mathbb{N}} \forall_{n\geq N} \ a_n > R$.
The statements of arney are actually equivalent. We have for $f: \mathbb{R}^n \to \mathbb{R}$ continuous
$$\forall_{\{x_n\} \subset \mathbb{R}^n: |x_n| \to \infty} \ f(x_n) \to 0 \;\iff\; \forall_{\epsilon > 0} \exists_{K_\epsilon \subset \mathbb{R}^n\, \text{compact}} \forall_{x\in \mathbb{R}^n\setminus K_\epsilon}\ |f(x)| < \epsilon. $$
I will drop the irritating subscript $\epsilon$, since the dependences will be clear from context.
Prf: "$\Leftarrow$": Take $\{x_n\}$ with $|x_n| \to \infty$. Take $\epsilon > 0$. Take $K$ from the right hand-side. $K$ is compact and $\mathbb{R}^n$ is a metric space, thus $K$ is bounded. Thus there exists $R>0$ with $|x| \leq R$ for all $x \in K$. Since $|x_n| \to \infty$ there exists $N$ with $|x_n| > R$ for all $n \geq N$. Thus $\forall_{n\geq N} |f(x_n)| < \epsilon$ by the right hand side.
"$\Rightarrow$": Take $\epsilon>0$. Set $K := \{x \in \mathbb{R}^n: |f(x)| \geq \epsilon\}$. We want to evoke Heine-Borel, then the statement holds by construction. Clearly $K \subset \mathbb{R}^n$ is closed since $f$ is continuous. Suppose that $K$ is not bounded. Then, there exists a sequence $\{x_n\} \subset K$ with $|x_n| \to \infty$. But $|f(x_n)| \geq \epsilon$ for all $n$, so clearly we cannot have $f(x_n) \to 0$, contradicting the left hand side.


text:
Q: How can I scrape for certain html classes in python I'm trying to scrape a random site and get all the text with a certain class off of a page.
from bs4 import BeautifulSoup
import requests
sources = ['https://cnn.com']

for source in sources:
    page = requests.get(source)

    soup = BeautifulSoup(page.content, 'html.parser')
    results = soup.find_all("div", class_='cd_content')
    for result in results:
        title = result.find('span', class_="cd__headline-text vid-left-enabled")
        print(title)

From what I found online, this should work but for some reason, it can't find anything and results is empty. Any help is greatly appreciated.

A: Upon inspecting the network calls, you see that the page is loaded dynamically via sending a GET request to:
https://www.cnn.com/data/ocs/section/index.html:homepage1-zone-1/views/zones/common/zone-manager.izl

The HTML is available within the html key on the page

import requests
from bs4 import BeautifulSoup

URL = "https://www.cnn.com/data/ocs/section/index.html:homepage1-zone-1/views/zones/common/zone-manager.izl"
response = requests.get(URL).json()["html"]
soup = BeautifulSoup(response, "html.parser")

for tag in soup.find_all(class_="cd__headline-text vid-left-enabled"):
    print(tag.text)

Output (truncated):
This is the first Covid-19 vaccine in the US authorized for use in younger teens and adolescents
When the US could see Covid cases and deaths plummet
'Truly, madly, deeply false': Keilar fact-checks Ron Johnson's vaccine claim
These are the states with the highest and lowest vaccination rates


text:
Q: Boundedness for feasible sets in solving an optimization problem. How to check if the feasible set is bounded? I am struggling with the concept of boundedness in solving several optimization problems. When I go through the theory I understand what it means. However when I look at an example I am struggling to figure out where to begin from. For example in the following optimisation problem there are two constraints and I am trying to maximize the objective function.
$\max(x,y,z) x + 2y − 3z$;
such that $x^2 − 3xy + z^2 \le 5$;
$4x^2 − 2xy + y^2 + 4xz + 10z^2 = 100$
To figure out if the constraints are bounded I tried to solve the equations and came up with the following bounds
$0 < x \le 6,$
$0 < y \le 10,$
$-\sqrt{5} \le z \le 0.$
I have gotten a feeling these are not right as I think my understanding of how to find the bounds are not clear. It would be much appreciated if I can get some ideas or information on bounds including any resource materials that might help me to better understand the concept.
Thanks.


text:
Q: create chain of views in navigation item without showing them actually How can i create a chain of viewcontrollers and push them into navigation item without showing them? On the other side is it possible to move backward on the viewcontrollers stack of the navigation item without activating and showing viewcontrollers?
Thanks,
Nava

A: You can push a viewController onto a navController using -pushViewController:animated: and setting the animated argument to NO. In this way, you can push a series of view controllers, and only animate the last one. Is this what you're trying to do? You can also pop them off with the animated flag set to NO.


text:
Q: Как удалять либо скрывать объекты? Пытаюсь cкрыть либо удалить элемент (кнопку)
Вот код:
    //при нажатии на  кнопку  пытаюсь удалить кнопку button2
    Button {
        id: button2
        text: qsTr("DRINA")

        ToolTip.visible: hovered
        ToolTip.text: qsTr("Save the active project")
    }
    Button {
        id: button3
        text: qsTr("delete")

        ToolTip.visible: hovered
        ToolTip.text: qsTr("delete the active project")
        clicked: button2. // увы но он не предлагает варианты типа delete и hide
    }

Также я хочу скрыть либо удалить элемент типа ColumnLayout (надеюсь это делается также как с элементом Button)

A: Для сокрытия кнопки предлагаю использовать её свойство visible, которое унаследовано от класса Item.
Для того, чтобы написать обработчки к сигналу signalName() нужно использовать слот onSignalName. В данном случае это onClicked.
    Button {
        id: button3
        text: qsTr("delete")

        ToolTip.visible: hovered
        ToolTip.text: qsTr("delete the active project")
        onClicked: {
            button2.visible = false
        }
    }

Для удаления объекта предлагаю ознакомиться с Qml Loader

A: visible Чтобы скрыть кнопку, надо установить сигналу значение false. Также я допустил ошибку: clicked неправильный вызов сигнала. Самому сигналу ничего не следует назначать. Вместо этого я определяю onClicked обработчик сигнала. Код должен выглядеть так:
Button {
    id: button3
    text: qsTr("delete")

    ToolTip.visible: hovered
    ToolTip.text: qsTr("delete the active project")
    onClicked: button2.visible = false
}

Я не могу удалить элемент QML, который был определен статически, как я показываю. Но я могу только "скрыть" его. Также если я изменю код на динамическое создание кнопок (например, с помощью Loader), то эти кнопки можно будет удалить.
Component {
    id: dynamicBtn
    Button {
        // Кнопка, которую можно удалить
    }
}

Loader {
    id: btnLoader
    sourceComponent: dynamicBtn
}

Button {
    // Выгрузить (удалить) другую кнопку
    onClicked: btnLoader.sourceComponent = undefined
}

этот ответ является вольным переводом от сюда :3 (спасибо jarmen-y)


text:
Q: Symfony4.3 Uncaught Error: The route "xxxx" does not exist I have the problem for fosJsRouteBundle in symfony 4.3 i have error in console Uncaught Error: The route "xxx" does not exist.
Uncaught Error: The route "app_autocompleted" does not exist.
    at r.value (router.min.js:1)
    at r.value (router.min.js:1)
    at HTMLDocument.<anonymous> (_search.js:12)
    at mightThrow (jquery.js:3557)
    at process (jquery.js:3625)

Router Controller
/**
 * @Route("/{_locale}/app_autocompleted", name="app_autocompleted", options={"expose": true})
 */

php bin/console fos:js-routing:debug
| Name                     | Method | Scheme | Host | Path
| app_autocompleted.pl     | ANY    | ANY    | ANY  | /{_locale}/app_autocompleted                                 |
| app_autocompleted.en     | ANY    | ANY    | ANY  | /{_locale}/app_autocompleted

I search the solutions here but i don't find greate id and i think problem is with this https://symfony.com/blog/new-in-symfony-4-1-internationalized-routing


text:
Q: "As far as I can remember." Does it need comma if put at the end of a sentence?
I've always been interested in music, as far as I can remember.
I've always been interested in music as far as I can remember.

What's the correct option? Or at least the most common one?

A: The sentence does need a comma there because the dependent clause as far as I can remember adds nonessential information following an independent clause.
Note the main rule about a dependent clause following an independent clause in a complex sentence, and (pertinant here), the exception to the rule that follows.

Rule: If the independent clause comes before the dependent clause, omit the comma.
   You shouldn't be driving if you can't see without your glasses.
   Our flight has been delayed because of the thunderstorm.
Exception to the rule: If the dependent clause is not essential to the meaning of the sentence, it should be set off with a comma.
   I cannot agree with his position on that issue, though I don't doubt    his sincerity. (Not doubting his sincerity is not the reason I cannot agree with his position; it is    merely an additional piece of information.)

From The Punctuation Guide


text:
Q: Corrupt video file - HEX trails off to zeors Have an mp4 mov file that is 3.32GB and should be 5+ min long. Filmed with GH4 cam. The file is on the computer and the SD card cannot be restored because it was formatted and used about 20 times after. The file plays fine for about 17 seconds and then stops. As you can see in the attached screenshot, the HEX shows good data until line 0EC00000, which is very close to the beginning (probably the good 17 seconds). After that, and all the way to end of the file - there are only ZEROS. Does this mean that there is NO data to fix? Is the last 4.5 minutes lost forever?

A: Your only hope is a file system recovery program.  i.e. you're hoping the full file still exists on the SD somewhere.
Note formatting generally does NOT remove all possibility of recovering files, in simple terms it just tells the system it can use all this space, it doesn't physically clear every byte.  continued usage of the SD will decrease the chances of recovery, esp with large files like movies.
Here is one such utility: EaseUS
You can't 'recreate' the missing data, you've no information left to base it on...


text:
Q: BHO OnDocumentComplete for the top frame only? I'm developing a BHO in CSHARP and I have  an issue in onDocumentComplete method.
It runs on every IFRAME that the main document loads. How can I avoid it? I only want to handle events in the main window.
public void OnDocumentComplete(object pDisp, ref object URL)
  {
      document = (HTMLDocument)webBrowser.Document;
      document.body.style.backgroundColor = "red";
  }

A: Compare this.site with pDisp. If they're equal, then the code is running in the main frame:
public void OnDocumentComplete(object pDisp, ref object URL)
{
    if (pDisp != this.site) {
        // Ignore subframes
        return;
    }
    document = (HTMLDocument)webBrowser.Document;
    document.body.style.backgroundColor = "red";
}


text:
Q: How to import Stanford POS Tagger I'm attempting to make use of the Stanford POS Tagger in Python.
home = 'U:/ManWin/My Documents/Research Project'
from nltk.tag.stanford import StanfordPOSTagger as POS_Tag
_path_to_model = home + '/stanford-postagger/models/english-bidirectional-distsim.tagger'
_path_to_jar = home + '/stanford-postagger/stanford-postagger.jar'
st = POS_Tag(path_to_model=_path_to_model, path_to_jar=_path_to_jar)

Have copied the last line from the answer here: Python NLTK pos_tag not returning the correct part-of-speech tag
Getting the following error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "U:\Python35\site-packages\nltk\tag\stanford.py", line 136, in __init__
    super(StanfordPOSTagger, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'path_to_model'

What do I need to change?

A: It seems the name of the parameter path_to_model has changed to model_filename. So, replace the last line with:
st = POS_Tag(model_filename=_path_to_model, path_to_jar=_path_to_jar)
Or since the parameters are in order, just write:
st = POS_Tag(_path_to_model, _path_to_jar)


text:
Q: Javascript: InnerHtml dynamically I want to replace the content of a div with the content of second one. I want to get the name of the second one dynamically over the alt tag of an image(works) and load the content of it (doesn't work)...
Does anyone know how the following code has to be changed to get the content of the div?
$img = $(this).find('img');
var NewDiv = $img.attr('alt');

document.all.old.innerHTML = document.all.NewDiv.innerHTML;


text:
Q: D3.js line chart not displaying on screen D3.js line chart not displaying in window
Hi I'm fairly new to javascript and going by a few examples I mocked up this implementation of a d3.js linechart. For some reason it is not drawing the graph on the window, instead giving me a blank screen.
var chartdata = [{
    time: "1-May-12",
    emissionrate: "58.13"
}, {
    time: "30-Apr-12",
    emissionrate: "53.98"
}, {
    time: "27-Apr-12",
    emissionrate: "67.00"
}, {
    time: "26-Apr-12",
    emissionrate: "89.70"
}, {
    time: "25-Apr-12",
    emissionrate: "99.00"
}];
//regular single compound chart
function chart (width,height,data) {
    var margin = {
    top: 30,
    right: 20,
    bottom: 30,
    left: 50
    },vis = d3.select('#chartvis');

  var w = width - margin.left - margin.right;
  var h = height - margin.top - margin.bottom;

  var parseDate = d3.timeParse("%d-%b-%y");

    data.forEach(function (d){
    d.time=parseDate(d.time);
    d.emissionrate=+d.emissionrate;
  });

  var xmin = d3.min(data,function(d){
    return d.time;
  });
  console.log(xmin);
  var xmax = d3.max(data,function(d){
    return d.time;
  });

  var ymax = d3.max(data,function(d){
    return d.emissionrate;
  });
  console.log(ymax);

  var xLine =  d3.scaleTime().domain([xmin, xmax]).range([0, w]);
  var yLine = d3.scaleLinear().domain([0, ymax]).range([h, 0]);

  var lineFunc =  d3.line()
                                    .x(function(d) {
                                    return xLine(d.time);
                    })
                    .y(function (d) {
                    return yLine(d.emissionrate);
                    });

    vis.append('g')
            .attr("width", w + margin.left + margin.right)
            .attr("height", h + margin.top + margin.bottom)
            .attr("transform",
                "translate(" + margin.left + "," + margin.top +     ")");

     vis.append('g')
            .attr("id", "xAxis")
            .attr("transform", "translate(0," + h + ")")
            .call(d3.axisBottom(xLine));

     vis.append('g')
            .attr("id", "yAxis")
            .attr("transform", "translate(" + w + ", 0)")
            .call(d3.axisLeft(yLine));

     vis.append("path")
            .data(data)
            .style("fill", "none")
            .attr("stroke", "steelblue")
            .attr("stroke-width","1.5")
            .attr("d", lineFunc);

}

chart(400,500,chartdata);

I expect any kind of graphical output, but instead am getting a blank screen. Inspecting in the dev tools is not giving me any errors either.
I have attached the JsFiddle here as well
https://jsfiddle.net/Lwbogd94/2/

A: There were 2 major issues. First, it seems there is a bug on jsfiddle when using d3v5. I decide to use plain js and load d3v5 using script tags. After that I start seeing the elements inside the <svg> when using the browser tools. I had to adjust the size of the <svg> element to see the axis.
The second major issue is the data function is for the Enter-Update-Exit pattern. In your case you should use the datum method.
Here is the updated jsfiddle:
https://jsfiddle.net/75uh2La0/


text:
Q: decode windows 1256 to utf-8 in android I have a string which is decoded by windows-1256 like this

A0C8E5CFC7CF2DC7DDDEE5ED

I want to encode that to UTF-8 in android.
I tried to encode like this
String input = "A0C8E5CFC7CF2DC7DDDEE5ED";
    try {
        String message = new String(input.getBytes(), "windows-1256");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

but I didn't see what expected expression.
I wrote some codes in C# for this purpose ,like this
int index = 0;
while (response[index] != 0x00)
    result = result + Encoding.GetEncoding("windows-1256").GetString(response, index++, 1);

it works fine.
does anyone have any idea how to solve it?
Thanks in advance

A: First you convert your hex string into byte array. See this post.
Then, convert the byte array byte[] into UTF-8 using
String str = new String(byte[], "windows-1256");

UTF-8 is the native android encoding. Hope it helps.


text:
Q: Boyd & Vandenberghe, example 5.6 — formulation of norm approximation problem In Example 5.6 of Boyd & Vandenberghe's Convex Optimization, the problem is
$$ \text{minimize} \quad \Vert Ax - b\Vert,$$
where $\Vert \cdot \Vert$ is any norm. Reformulating by introducing a new variable, we get:
$$ \text{minimize} \,\, \Vert y\Vert \quad s.t. \, Ax-b=y$$
The Lagrange dual of this problem he claims is:
$$ \text{maximize} \,\, b^T\nu \quad s.t. \Vert \nu\Vert_{*} \leq 1 \quad\text{and} \quad A^T\nu=0$$
My question is, is this correct? For my dual formulation I am getting:
$$ g(\nu)=\text{inf}_y \{ \Vert y\Vert - y^T \nu \} - b^T\nu,$$
taking into account that $A^T\nu=0$.
Using the fact that the dual of norm is the indicator, I get the dual as:
$$ \text{maximize} \,\, -b^T\nu \quad s.t. \Vert \nu\Vert_{*} \leq 1 \quad\text{and} \quad A^T\nu=0$$
That has a negative sign. I cannot seem to understand where I am making a mistake. Any help would be appreciated. Thanks.

A: Informally: $\min_x \|Ax-b\| = \min_x \sup_{\|\nu\|_* \le 1} \nu^T(Ax-b)
= \sup_{\|\nu\|_* \le 1} \inf_x \nu^T(Ax-b)$.
Note that if $\nu^TA \neq 0$ we can pick $x$ so that $\nu^T(Ax-b)$ is unbounded below, so
$\sup_{\|\nu\|_* \le 1} \inf_x \nu^T(Ax-b) = \sup_{\|\nu\|_* \le 1, \nu^TA = 0} \inf_x \nu^T(-b) = \sup_{\|\nu\|_* \le 1, \nu^TA = 0}  -\nu^Tb$ and hence
$\min_x \|Ax-b\| = \max_{\|\nu\|_* \le 1, \nu^TA = 0} \nu^Tb$.
Elaboration:
Note that
$\max_{\|\nu\|_* \le 1, \nu^TA = 0} -\nu^Tb = \max_{\|-\nu\|_* \le 1, (-\nu)^TA = 0} -\nu^Tb = \max_{\|\nu\|_* \le 1, \nu^TA = 0} \nu^Tb $.


text:
Q: SQL Server adding two time columns in a single table and putting result into a third column I have a table containing two time columns like this:
Time1       Time2
07:34:33    08:22:44

I want to add the time in both these columns and put the result of addition into a third column may be Time3
Any help would be appreciated..Thanks

A: If the value you expect as the result is 15:57:17 then you can get it by calculating for instance the number of seconds from midnight for Time1 and add that value to Time2:
select dateadd(second,datediff(second,0,time1),time2) as Time3
from your_table

I'm not sure how meaningful adding two discrete time values together is though, unless they are meant to represent duration in which case the time datatype might not be the best as it is meant for time of day data and only has a range of 00:00:00.0000000 through 23:59:59.9999999 and an addition could overflow (and hence wrap around).
If the result you want isn't 15:57:17 then you should clarify the question and add the desired output.

A: The engine doesn't understand addition of two time values, because it thinks you can't add two times of day. You get:
Msg 8117, Level 16, State 1, Line 8
Operand data type time is invalid for add operator.

If these are elapsed times, not times of day, you could take them apart with DATEPART, but in SQL Server 2008 you will have to use a CONVERT to put the value back together, plus have all the gymnastics to do base 60 addition.
If you have the option, it would be best to store the time values as NUMERIC with a positive scale, where the unit of measure is hours, and then break them down when finally reporting them. Something like this:
DECLARE
    @r NUMERIC(7, 5);

SET @r = 8.856;

SELECT FLOOR(@r) AS Hours, FLOOR(60 * (@r - FLOOR(@r))) AS Minutes, 60 * ((60 * @r) - FLOOR(60 * @r)) AS Seconds

Returns
Hours    Minutes    Seconds
8        51         21.60000

There is an advantage to writing a user-defined function to do this, to eliminate the repeated 60 * @r calculations.


text:
Q: e-signing my pdf file in ios limits my pdf content Am trying to sign my pdf file which is multiple paged, I could fetch the signature drawn in UIView to my pdf file, but the problem i face is, after signing the pdf, i could view only the single page of file which is signed, not rest of the pages in my webview.(for eg; if page 3 of my pdf file is signed, i could view only page 3 in my webview).
Codes used for fetching the e-sign in my pdf file
- (void)viewWillAppear:(BOOL)animated
{
webView= [[UIWebView alloc] initWithFrame:CGRectMake(0,44, 320, 460)];
path1 = [[NSBundle mainBundle] pathForResource:@"typo_tips" ofType:@"pdf"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
                                                     NSUserDomainMask, YES);
NSString *documentDirectoryPath;
NSURL *targetURL;
documentDirectoryPath  = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"typo_tips.pdf"];
[fileManager copyItemAtPath:path1 toPath:documentDirectoryPath error:&error];

targetURL = [NSURL fileURLWithPath:documentDirectoryPath];

if (entered==1)//entered assigned 1, after save button clicked in UIView
{

    CFURLRef url;
    url = (CFURLRef)CFBridgingRetain([NSURL fileURLWithPath:documentDirectoryPath]);
    CGPDFDocumentRef myDocument;
    myDocument = CGPDFDocumentCreateWithURL(url);

    CGContextRef pdfContext = CGPDFContextCreateWithURL(url, NULL, NULL);
    CGPDFContextBeginPage(pdfContext, NULL);
    UIGraphicsPushContext(pdfContext);

    int totalPages = (int)CGPDFDocumentGetNumberOfPages(myDocument);
    NSLog(@"no. of pages in pdf is %d \n",totalPages);

   CGContextDrawPDFPage(UIGraphicsGetCurrentContext(),CGPDFDocumentGetPage(myDocument,page));
    //"page" is current pdf page to be signed, which can be fetched from user during runtime the pdf file is clicked.

    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];// image is the e-sign saved in doc. directory

    image = [[UIImage alloc] initWithContentsOfFile:filePath];
    CGRect imageRect = CGRectMake(50, 50, image.size.width, image.size.height);

    //  CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, image.size.height);
    //   CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);
    CGContextDrawImage(UIGraphicsGetCurrentContext(), imageRect, image.CGImage);

    // Clean up
    UIGraphicsPopContext();
    CGPDFContextEndPage(pdfContext);
    CGPDFContextClose(pdfContext);

}

NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];

}
I could guess the cause of problem, because after the image is merged with pdf file, the single page of pdf which is got signed remains in the document directory, so that i could not display rest of pages in pdf file. Can any one help me to recover from this problem.

A: Your code does not sign the original file, it creates a copy of a single page and then signs that page. This is why you see only one page.
What you can do is to copy the source file to another file (copy each page the same way you copy the current one) and then sign the page you want.


text:
Q: Download multiple files from NodeJS Server I am trying to support download of multiple files from my Node js server to the client. With the below logic implemented in my NodeJS server, I can support sending of single file to the client.
res.download('group_documents/sample1.pdf','sample1.pdf', function(err){
  if (err) {
    console.log(err);
  } else {
    // decrement a download credit etc
  }
});

How can i rewrite the above server logic to support downloading multiple files using single request from the client (browser or curl request)?

A: On web browser you can not download multiple files at a time.
But you can download archived file of all required files.
Using express-zip npm package you can do it easily.
https://github.com/thrackle/express-zip
Install express-zip.
npm install express-zip

Use following code :
res.zip(files);

files is an array of objects.
Each object should be :
{ path : 'path/to/file', name : 'fileName'}

A: if your target clients are web browsers, then you can't, as the http protocol does not allow for multiple downloads for a single request.
If you really need to do this, then you'd need to either write a custom client application, or (more simply) zip the files into some archive before transmitting them.


text:
Q: I have many friends,who all or all of whom are students which is correct "I have many friends,who all are University students" or "I have many friends,all of whom are University students"?

A: Both are acceptable, but the second is much more frequently used. I enter ", who all" into COCA https://www.english-corpora.org/coca/, and it returns 248 results. 1536 example sentences with ", all of whom" are found in the corpus.


text:
Q: openquery apears to be rolled back when done I'm using the following query.
select * from OPENQUERY(EXITWEB,N'SET NOCOUNT ON;
                       declare @result table (id int);
                           insert into [system_files] ([is_public], [file_name], [file_size], [content_type], [disk_name], [updated_at], [created_at])
                    output inserted.id into @result(id)
                    values (N''1'',N''7349.jpg'',N''146921'',N''image/jpeg'',N''5799dcc8a1eb1413195192.jpg'',N''2016-07-28 10:22:00.000'',N''2016-07-28 10:22:00.000'')

                       declare @id int = (select top 1 id from @result)
                       select * from system_files where id = @id
                       insert into linkToExternal (id, id_ext) values(@id, 47)
                       --select @id
                       ')

when I perform a select from within the query it works just fine:

But when I go to check my database when the call has finished, the record is no longer there.
So I'm suspecting a transaction is rolled back. My question is: why. What can I do to prevent the transaction to be rolled back if that's the case.

A: Well, as always, after days of struggling and me post a question on stackoverflow I find the solution: http://www.sqlservercentral.com/Forums/Topic1128997-391-1.aspx#bm1288825

I was having the same problem as you and almost gave up on it but have
  finally found an answer to the problem. Reading an article about
  sharing data between stored procedures I discovered that OPENQUERY
  issues an Implicit Transaction and that it was Rolling back my insert.
  So I had to add an explicit Commit to my stored procedures, in
  additional I discovered that if I use it in a query that has a Union
  it has to be Commited twice. Since I'm doing my insert inside a BEGIN
  TRY I can always just commit twice and not worry about whether it is
  being used in a UNION. I'm returning different values if there is an
  error but that was just apart of my debugging.

SELECT TOP 5 *
FROM mm
JOIN OPENQUERY([LOCALSERVER], 'EXEC cms60.dbo.sp_RecordReportLastRun ''LPS'', ''Test''') RptStats ON 1=1

ALTER PROCEDURE [dbo].[sp_RecordReportLastRun]
-- Add the parameters for the stored procedure here
@LibraryName varchar(50),
@ReportName varchar(50)

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
BEGIN TRY
INSERT INTO cms60.dbo.ReportStatistics (LibraryName, ReportName, RunDate) VALUES (@LibraryName, @ReportName, GETDATE())
--
COMMIT; --Needed because OPENQUERY starts an Implicit Transaction but doesn't commit it.
COMMIT; --Need second Commit when used in a UNION and although it throws an error when not used in a UNION doesn't cause a problem.
END TRY
BEGIN CATCH
SELECT 2 Test
END CATCH
SELECT 1 Test
END

In my case, adding a ;COMMIT; after the inserts solved it, and made sure it got written into the database.


text:
Q: data coming from custom fetch hook and local state I want to have a local setter to update data I'm extracting from custom fetch hook:
  function ContactList(props) {
  const contacts =useFetch(fetchUrl, []);**//contain data**
  const [data,setData] = useState(contacts);**//remains empty**

  return (

      <Navbar />

        <ContactItem contacts={contacts} setContacts={setData} />

  );
}

fetchHook looks like this:
export const useFetch = (url, initialValue) => {
    const [result, setResult] = useState(initialValue);
    useEffect(() => {
        const fetchData = async () => {
            const result = await axios(url);
            setResult(result.data.contact);
        };
        fetchData();

    }, []);

return result
}

so I need the contactList to have a setter which I currently don't manage to achieve because state remain an empty array.

A: const contacts =useFetch(fetchUrl, []);

useFetch is asynchronous and makes the call and gives the result after the componentMounts, since I'm assuming you put that in a useEffect with empty dependency in your hook.
So, the data won't be available on the first render, making it initialize to empty.
EDIT:
To understand better, follow the console.log in the following example:
https://codesandbox.io/embed/friendly-ives-xt5k0
You'll see that it is empty first and then it gets the value.
Now, the same is the case in your code. On the first render it's empty and that is when you set the state of result. Instead, you can just use the value of contacts in your case.
EDIT 2:
After seeing what you need, all you have to do is to also return the setResult from the hook:
export const useFetch = (url, initialValue) => {
    const [result, setResult] = useState(initialValue);
    useEffect(() => {
        const fetchData = async () => {
            const result = await axios(url);
            setResult(result.data.contact);
        };
        fetchData();

    }, []);

return {result, setResult}
}

function ContactList(props) {
  const {result, setResult} =useFetch(fetchUrl, []);

  return (

      <Navbar />

        <ContactItem contacts={result} setContacts={setResult} />

  );
}


text:
Q: Cannot install kubernetes helm chart Error: cannot re-use a name that is still in use Cannot install the helm chart but when I use raw file generated by helm, I am able to install via kubectl apply.
Following error is displayed when i use helm install myChart . --debug
Error: cannot re-use a name that is still in use
helm.go:88: [debug] cannot re-use a name that is still in use
helm.sh/helm/v3/pkg/action.(*Install).availableName
        helm.sh/helm/v3/pkg/action/install.go:442
helm.sh/helm/v3/pkg/action.(*Install).Run
        helm.sh/helm/v3/pkg/action/install.go:185
main.runInstall
        helm.sh/helm/v3/cmd/helm/install.go:242
main.newInstallCmd.func2
        helm.sh/helm/v3/cmd/helm/install.go:120
github.com/spf13/cobra.(*Command).execute
        github.com/spf13/cobra@v1.1.3/command.go:852
github.com/spf13/cobra.(*Command).ExecuteC
        github.com/spf13/cobra@v1.1.3/command.go:960
github.com/spf13/cobra.(*Command).Execute
        github.com/spf13/cobra@v1.1.3/command.go:897
main.main
        helm.sh/helm/v3/cmd/helm/helm.go:87
runtime.main
        runtime/proc.go:225
runtime.goexit
        runtime/asm_amd64.s:1371

Installing raw file generated by helm with the following command works great but when I run helm install myChart . it gives the above error
helm install myChart . --dry-run > myChart.yaml
kubectl apply -f myChart.yaml

A: Another option could be:

*

*List the available helm charts: helm list. E.g.:

*Delete the required helm chart helm delete phoenix-chart. E.g.:

A: Use upgrade instead install:
helm upgrade -i myChart .

The -i flag install the release if it doesn't exist.

A: Removing a sh.helm.release.v1.<chart>.v1 kubesecret and trying again was what I had to do.
I searched for the impacting secret with
kubectl get secrets -n <chart-namespace> or
kubectl get secrets --all-namespaces

A: works for me - helm uninstall /<chart_name>


text:
Q: Open folder for a given path in Mac OS X Let's say I have a path to a folder in a text document or in the clipboard, for example:
/Users/Joe/Documents/workspace/test

How can I quickly open this folder in Mac OS X?
In Windows I could open the Run-dialog, paste the path into the input box and the folder would open.
Is there a similar way in Mac OS X?

A: If it is a network path, go to finder and click CMD + K then type smb://servername/drive/file

A: If you are working at the command line try
$ open <path>

with the bonus that it also opens files in the default application that is set for them.

A: Yes, there are. If you are already in Finder you can use one of them:

*

*In the Go menu, choose Go to Folder… option

*Press ⇧ + ⌘ + G
If you want to do it from Dock - press and hold left mouse on Finder icon and choose Go to Folder….
Just paste in modal window your path and press Enter
It will throw an error if the folder does not exist, or the path points to a file. Note also that it opens in your current window, so if you want to Go in a new window you will have to open that window first.


text:
Q: Can't implement post.processing with EffectComposer in Three.js Im trying to implement post-processing effects in Three.js through this example here:
https://threejs.org/docs/#manual/en/introduction/How-to-use-post-processing
With the following code:
import * as THREE from 'three';
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js';
import { GlitchPass } from 'three/examples/jsm/postprocessing/GlitchPass.js';

var scene, camera, renderer, box, composer;

init();

function init() {
  scene = new THREE.Scene();
  scene.background = new THREE.Color("#333333");
  const geometry = new THREE.BoxGeometry(1, 1, 1);
  const material = new THREE.MeshStandardMaterial({ color: new THREE.Color('skyblue') });
  box = new THREE.Mesh(geometry, material);

  scene.add(box);

  const light = new THREE.DirectionalLight();
  light.position.set(0, 1, 2);
  scene.add(light);

  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
  camera.position.z = 3;
  renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement);

  // add EFFECT
  composer = new EffectComposer(renderer);
  composer.addPass(new RenderPass(scene, camera));
  const filmPass = new FilmPass(0.35, 0.025, 648, false,);
  filmPass.renderToScreen = true;
  composer.addPass(filmPass);

  window.addEventListener('resize', onResize, false);

  update();
}

function update() {
  requestAnimationFrame(update);
  box.rotation.y += 0.01;
  composer.render(scene, camera);
}

function onResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  composer.setSize(window.innerWidth, window.innerHeight);
}

This gives me error that it cant find /node_modules/three/examples/jsm/postprocessing/
This is indead true. The file does not exist anymore for some reason in my version of three
I found this:
https://www.npmjs.com/package/postprocessing
and did try to install and use that instead but without success:
npm install three postprocessing

And the following code:
import * as THREE from 'three';
import { BloomEffect, EffectComposer, EffectPass, RenderPass } from "postprocessing";

var scene, camera, renderer, box, composer;

init();

function init() {
  scene = new THREE.Scene();
  scene.background = new THREE.Color("#333333");
  const geometry = new THREE.BoxGeometry(1, 1, 1);
  const material = new THREE.MeshStandardMaterial({ color: new THREE.Color('skyblue') });
  box = new THREE.Mesh(geometry, material);

  scene.add(box);

  const light = new THREE.DirectionalLight();
  light.position.set(0, 1, 2);
  scene.add(light);

  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
  camera.position.z = 3;
  renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement);

  // add EFFECT
  composer = new EffectComposer(renderer);
  composer.addPass(new RenderPass(scene, camera));
  // const filmPass = new BloomEffect());
  // filmPass.renderToScreen = true;
  composer.addPass(new BloomEffect());

  window.addEventListener('resize', onResize, false);

  update();
}

function update() {
  requestAnimationFrame(update);
  box.rotation.y += 0.01;
  composer.render(scene, camera);
}

function onResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  composer.setSize(window.innerWidth, window.innerHeight);
}

This render my scene all black.
What am I doing wrong? How do I implement EffectComposer in Three.js


text:
Q: Peoplecode, SQLEXEC not retrieving correct data <-------PeopleCode------>
Hi,
I have a SQL query that i have tried executing using both SQLEXEC and SQL.fetch() but the problem is, when I am passing the values to parameters (:1,:2...) it does not return a row but when I hardcode the values in the where clause of the query itself, it retrieves the correct value.
Can anybody help?
My query looks similar to the following sample query :
Select * from PS_rec1 where emplid=:1 and plan_type=:2
it returns no data till i hardcode the values.
I have checked the values at the back end and some data is there to be fetched. Moreover, the same query retrieves data when ran in TOAD.

A: Have you tried outputting your binds to a log file just before you use them in your SQL statement?
If the binds aren't working, but literals are, then perhaps your binds don't contain the values that you expect them to.
You could also try explicitly setting the binds to the values that you're expecting just before the SQL statement.  This will prove that the way you're passing in the binds is working correctly.

A: It required another update to the same record to get the values fetched in SQL exec.
M not sure what was the problem but i guess it might be that the previous update did not write the changes to the db even after an explicit commit.

A: Ok, you need to put your exact SQLExec statement in the question.
But, do you really have "Select * ..." in a SQLExec?  How many columns are in your table? Since you mention the where clause, is your statement
SQLExec("select * from PS_rec where emplid=:1 and plan_type=:2", &var1, &var2, &vartocontainthewholerow);

Which will work in a SQL tool (toad) but probably does not work in AE or any type of Peoplecode program.
Now if your table has three columns, should you not have something like this:
SQLExec("select emplid, plan_type, column3 from PS_rec where emplid = :1 and plan_type=:2", &emplidIn, &plan_typeIn, &emplidOut, &plan_typeOut, &column3Out);

Notice that with three columns in the table that emplid and plan_type are two of them, you need to list all the columns you want, not asterisks '*'.  Kind of silly to select the emplid and plan_type though.


text:
Q: SqlBulkCopy error (There is already an open DataReader...) I am trying to make an exact copy from one sql table to another. Both tables reside in the same database. I am trying to use SqlBulkCopy but receive a "There is already an open DataReader associated with this Command which must be closed first." error.
I have found many similar problems and tried the solutions contained therein with no success. I am very new to this so any help with this (or any of the code below) is appreciated.
SqlCommand readLocal = new SqlCommand("Select CompanyNumber,CompanyName,AccessNumber,TruckName,TransferStartTime,TransferEndTime,TransferVolume FROM TransfersNew", conLocal);

try
{
    conLocal.Open();
    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conLocal))
    {
        bulkCopy.DestinationTableName = "dbo.TransfersHistory";

        try
        {
            using (SqlDataReader readerLocal = readLocal.ExecuteReader())
            {
                while (readerLocal.Read())
                {
                    bulkCopy.WriteToServer(readerLocal);
                }
            }
        }
        catch (Exception ex)
        {
            Globals.infoString = ex.Message;
            Globals.infoStringColor = true;
            var newForm = new pagePopupInfo();
            newForm.ShowDialog();
        }
        finally
        {
            conLocal.Close();
        }
    }
}
catch (Exception ex)
{
    Globals.infoString = ex.Message;
    Globals.infoStringColor = true;
    var newForm = new pagePopupInfo();
    newForm.ShowDialog();
}
finally
{
    conLocal.Close();
}

I'm wide open to suggestions. Thanks
Matheus' suggestion worked. My additional issue regarding not copying the data turned out to be that it was just not copying the first record. I changed my code to this to correct that issue:
try
        {
            conLocal.Open();
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conLocal))
            {
                bulkCopy.DestinationTableName = "dbo.TransfersHistory";
                SqlDataReader readerLocal = readLocal.ExecuteReader();
                bulkCopy.WriteToServer(readerLocal);
            }
        }

A: The reason that you have two Using, one inside the another, so it is considered as two connections.
You can try something like this :
                   using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conLocal))
                   using (SqlDataReader readerLocal = readLocal.ExecuteReader())
                    {
                        while (readerLocal.Read())
                        {
                            bulkCopy.WriteToServer(readerLocal);
                        }
                    }


text:
Q: How to extend the timeout of a SQL query This is not a connection timeout as a connection to the database is made fine.  The problem is that the stored procedure that I'm calling takes longer than, say, 30 seconds and causes a timeout.
The code of the function looks something like this:
SqlDatabase db = new SqlDatabase(connectionManager.SqlConnection.ConnectionString);
return db.ExecuteScalar(Enum.GetName(typeof(StoredProcs), storedProc), parameterValues);

The ExecuteScalar call is timing out.  How can I extend the timeout period of this function?
For quick stored procedures, it works fine.  But, one of the functions takes a while and the call fails.  I can't seem to find any way to extend the timeout period when the ExecuteScalar function is called this way.

A: I think this might be a better way to do this (as of Enterprise Library 6.0):
SqlDatabase db = new SqlDatabase(connectionManager.SqlConnection.ConnectionString);
System.Data.Common.DbCommand cmd = db.GetStoredProcCommand(storedProc, parameterValues);
cmd.CommandTimeout = 600;
return db.ExecuteScalar(cmd);

A: Try this one
SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder(connection.ConnectionString);
connectionStringBuilder.ConnectTimeout = 180;
connection.ConnectionString = connectionStringBuilder.ConnectionString;

connection.Open();
SqlCommand command = new SqlCommand("sp_ProcedureName", connection);
command.CommandType = CommandType.StoredProcedure;
command.CommandTimeout = connection.ConnectionTimeout;
command.ExecuteNonQuery();
connection.Close();

A: If you are using the EnterpriseLibrary (and it looks like you are) try this:
 Microsoft.Practices.EnterpriseLibrary.Data.Database db = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase("ConnectionString");
 System.Data.Common.DbCommand cmd = db.GetStoredProcCommand("StoredProcedureName");
 cmd.CommandTimeout = 600;
 db.AddInParameter(cmd, "ParameterName", DbType.String, "Value");

 // Added to handle paramValues array conversion
 foreach (System.Data.SqlClient.SqlParameter param in parameterValues)
 {
     db.AddInParameter(cmd, param.ParameterName, param.SqlDbType, param.Value);
 }

 return cmd.ExecuteScalar();

Edited to handle the paramValues array directly based on the comments. I also included your ConnectionString value:
Microsoft.Practices.EnterpriseLibrary.Data.Database db = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase(connectionManager.SqlConnection.ConnectionString);
System.Data.Common.DbCommand cmd = db.GetStoredProcCommand("StoredProcedureName", parameterValues);
cmd.CommandTimeout = 600;
return cmd.ExecuteScalar();

A: you do this by setting the SqlCommand.CommandTimeout property

A: Mladen is right but if you have to do this you probably have a bigger problem with the proc itself. Under load it might take much longer than your new timeout. Might be worth spending some quality time with the proc to optimize.

A: Timeout can occur due to a Microsoft issue. Seems to still occur on my Windows 8 system.
http://support.microsoft.com/kb/2605597?wa=wsignin1.0


text:
Q: Canonical Pyramid Polynomials In a canonical polyhedron, all edges are tangent to a unit sphere with the origin at the center of gravity of the points of tangency.
I've been working on exact forms of canonical polyhedra, and the regular pyramid turned out to be an interesting case. For a base with $n$ sides, that polygon has $z$ coordinates of $-tan(\frac{\pi}{2n})$, and the apex is at $(0,0,cot(\frac{\pi}{2n}))$. Here are some examples, each pyramid with its dual. The edges are perpendicular to each other at points tangent to the unit sphere.

The base regular polygon needs a scaling factor that is the root of a particular polynomial.  For bases with 3 to 12 sides, here are the roots and their polynomials.
$\begin{array}{ccc}
 3 & 1.6329931618554520655 & 2 \sqrt{\frac{2}{3}} \\
 4 & 1.2871885058111652495 & x^4+8 x^2-16 \\
 5 & 1.1690009178779524258 & 5 x^4+40 x^2-64 \\
 6 & 1.1124766546017998270 & 3 x^4+48 x^2-64 \\
 7 & 1.0806190099881630969 & 7 x^6-448 x^2+512 \\
 8 & 1.0607630605786609417 & x^8+32 x^6+64 x^4-1024 x^2+1024 \\
 9 & 1.0475038619623609305 & 3 x^6+72 x^4+384 x^2-512 \\
 10 & 1.0381901644398379801 & 5 x^8+240 x^6+960 x^4-5120 x^2+4096 \\
 11 & 1.0313884014418166375 & 11 x^{10}+88 x^8-2112 x^6-11264 x^4+45056 x^2-32768 \\
 12 & 1.0262650635674814921 & x^8+64 x^6+128 x^4-4096 x^2+4096 \\
\end{array}$
Here's code for calculating the pyramids.
pyramid[basesides_] := Module[{k = Abs[basesides], poly,
  sign = Sign[basesides], g},
  poly = RootReduce[g /. Last[Solve[myNorm[Mean[Table[{g Cos[2 Pi n/k],
        g Sin[2 Pi n/k], -Tan[Pi/(2 k)]}, {n, 0, 1}]]] == 1]]];
  {Append[Table[{RootReduce[poly Cos[2 Pi n/k + (sign - 1) Pi/k/2]],
  RootReduce[poly Sin[2 Pi n/k + (sign - 1) Pi/k/2]], -sign Tan[
    Pi/(2 k)]}, {n, 0, k - 1}], {0, 0, sign Cot[Pi/(2 k)]}],
  Polygon[Prepend[Sort[Append[RotateLeft[Append[Reverse[#], k + 1], 1] & /@
    Partition[Range[k], 2, 1], {1, k, k + 1}]], Range[k]]]}]

I use Solve in that.  Is there a more direct way for generating these polynomials?  Is it a known class?
Here are factored forms of the coefficients.

A: Let $h$ be the height of the pyramid, $r$ the radius of its base and $x$ the distance from the center $O$ of the tangent unit sphere to the base. The apothem of the base is then $rc$, where I introduced the shortcut $c=\cos(\pi/n)$.
The condition that the distance from $O$ to a lateral edge is $1$ gives the equation
$$r^2(h-x)^2=r^2+h^2.$$
The condition that the distance from $O$ to a base edge is $1$ gives the equation
$$x^2+r^2c^2=1.$$
Finally, the condition that $O$ is the barycenter of the tangency points gives the equation
$$h-2x=hc.$$
These three equations can be solved for the unknowns $r$, $h$ and $x$, here's the result:
$$
r=\sqrt{2\over c(1+c)},\quad
h=2\sqrt{1\over 1-c^2},\quad
x=\sqrt{1-c\over 1+c}.
$$
Your scaling factor is of course the value of $r$, which can be calculated from the above formula, without solving complicated polynomial equations:
$$
r=\sqrt{2\over \cos(\pi/n)(1+\cos(\pi/n))}.
$$
I suspect your equations may arise from the search of an exact value for $\cos(\pi/n)$, but have little to do with canonical pyramids.


text:
Q: Android BackStack issue I am having trouble fixing a problem that I have with the BackStack. I have 3 fragments that are managed by an Activity:

The navigation between the fragments I using this code:
private void showFragment(BabysitFragment babysitFragment, UserRequest userRequest) {
   FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
   switch (babysitFragment) {
      case CHILDREN_OVERVIEW:
        toolbar.setVisibility(View.VISIBLE);
        Fragment childrenSpecification = ChildrenOverviewFragment.newInstance(userRequest);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.fragment_container, childrenSpecification, BabysitFragment.CHILDREN_OVERVIEW.getSimpleName()).commit();
        break;
      case CHILD_SPECIFICATION:
        toolbar.setVisibility(View.VISIBLE);
        Fragment childSpecification = ChildSpecificationFragment.newInstance(userRequest);
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.fragment_container, childSpecification, BabysitFragment.CHILD_SPECIFICATION.getSimpleName()).commit();
        break;
   }
}

//Gets called by FinalizeFrag and ChildSpecificationFrag
@Override
public void onChildrenOverviewNeeded(UserRequest userRequest) {
    showFragment(BabysitFragment.CHILDREN_OVERVIEW, userRequest);
}

//Gets called by ChildrenOverviewFrag
@Override
public void onChildSpecificationNeeded(UserRequest userRequest) {
    showFragment(BabysitFragment.CHILD_SPECIFICATION, userRequest);
}

I want the user  to be able to go back to the FinalizeFrag using the backbutton from the other 2 fragments. This works with the current code but In 1 flow I do have a problem:

*

*The users saves the new 'Child' in the ChildSpecificationFrag (save icon in the toolbar)

*User gets redirected to the ChildrenOverviewFrag

*User presses back button

*Stays on the ChildrenOverviewFrag (SHOULD redirect to the FinalizeFrag)

NOTE: when I press the button again it does redirect to the FinalizeFrag
Code when clicking the close button (ChildSpecificationFragment):
if (id == android.R.id.home) {
  getActivity().onBackPressed();
}

Code when clicking the save button (ChildSpecificationFragment):
...
userRequest.getFamilyDetails().getChildren().add(child);
getActivity().getSupportFragmentManager().popBackStackImmediate();
onChildrenOverviewNeededListener.onChildrenOverviewNeeded(userRequest, this);

As you can see I am removing the Fragment from the BackStack. What am I doing wrong? Thanks in advance!

A: Don't call addToBackStack, before doing "User gets redirected to the ChildrenOverviewFrag",

A: i think
fragmentTransaction.addToBackStack(null);

will  add fragment to back stack.
public abstract boolean popBackStackImmediate (String name, int flags)

just returns true if there was something popped, else false.


text:
Q: Proving partial sums $A_n = o(|z_k|^\rho)$, where $|z_k|\to\infty$ is increasing The following is a question in Lang's Complex Analysis, fourth edition, Chapter XIII $\S 4$, problem $5a$:

Let $\{ a_k \} , \{ z_k \}$ be sequences of complex numbers such that $|z_k| \to \infty$ and $|z_k| \le |z_{k+1}|$.  Let $\rho > 0$ such that $$\sum_{k=1}^\infty \frac{|a_k|}{|z_k|^\rho} < \infty$$  Let $A_n$ denote the partial sums of $|a_k|$.  Prove that $A_n = o(|z_n|^\rho)$.

I am having difficulty proving the little-oh part of it.  It's very easy to prove $A_n = O(|z_n|^\rho)$, since
$$\lim_{n\to\infty} \frac{A_n}{|z_n|^\rho} \le \sum_{k=1}^\infty \frac{|a_k|}{|z_k|^\rho} < \infty$$
However, it's not so clear why the limit should go to $0$.  My attempt so far has been to assume that the conclusion does not hold so that $A_n \ge \epsilon |z_n|^\rho$ for infinitely many $n$.  We can rewrite the sum as:
$$\sum_{k=1}^\infty \frac{|a_k|}{|z_k|^\rho} = \sum_{k=1}^\infty \left( \frac{1}{|z_k|^\rho} - \frac{1}{|z_{k+1}|^\rho} \right) A_k \approx \epsilon \sum_{k} 1 - \left( \frac{|z_k|}{|z_{k+1}|}\right)^\rho$$
The last sum seems like it might diverge (although I have my own doubts) but I'm stuck at this point.

A: Let $c_k=|a_k|/|z_k|^\rho \text { and } b_k=|z_k|^\rho$
Then
$$\lim_{n\to\infty} \frac{1}{b_n}\sum_{k=1}^n c_kb_k=0$$
Why the $\lim_{n\to\infty} \frac{1}{b_n}\sum_{k=1}^n c_kb_k=0$:
Let $a_n$ be a sequence of complex numbers such that $\sum a_n$ converges. Let $b_n$ be a sequence of real numbers which is increasing, i.e., $b_n \le b_{n+1}$ for all $n$, and $b_n\rightarrow\infty$ as $n\rightarrow\infty$
Given $\epsilon>0$, if we select a positive integer $n_0$ such that for all $m>n_0$ we have $\left|\sum_{n=n_0+1}^m a_n\right|<\epsilon$ and $b_{n_0}\ge0$. Then for $N>n_0$ splitting the sum we obtain:
$$\left|\frac{1}{b_N}\sum_{n=1}^N a_nb_n\right|\le\left|\frac{1}{b_N}\sum_{n=1}^{n_0} a_nb_n\right|+\left|\frac{1}{b_N}\sum_{n=n_0+1}^N a_nb_n\right|$$
The first sum will be $\le\epsilon$ for all large N. For the second sum we use summation by parts to obtain, after some elementary computations,
$$\sum_{n=n_0+1}^N a_nb_n=b_N(A_N-A_{n_0})-\sum_{k=n_0+1}^{N-1} (A_k-A_{n_0})(b_{k+1}-b_k)$$
where $A_n=\sum_{k=1}^n a_k$ are the partial sums. Therefore by the triangle inequality the fact that $\left|A_k-A_{n_0}\right|<\epsilon$ for all $k\ge n_0$ and that $b_k$ increases we get:
$$\left|\sum_{n=n_0+1}^N a_nb_n\right|\le\left| b_N\right|\epsilon+\epsilon(b_N-b_{n_0})$$
Hence for all large $N$ we have:
$$\left|\frac{1}{b_N}\sum_{n=n_0+1}^N a_nb_n\right|\le 3\epsilon$$
which concludes our proof.
However if we only assume that the partial sums of $\sum a_n$ are bounded, we cannot conclude that the limit is $0$.


text:
Q: Multiple string check in oracle db Say I want to check if a title name contains "stack" or contains "over" or contains "flow". Can I shorten the below code?
select name
from Title
where name like '%stack%' or name like '%over%' or name like '%flow%'
;

Thanks!

A: You could use REGEXP_LIKE, however that may have performance implications, so you may want to test it for your specific use case;
SELECT name
FROM Title
WHERE REGEXP_LIKE(name, '.*(stack|over|flow).*')

...or if you want the match case insensitive you can pass i as a third parameter;
SELECT name
FROM Title
WHERE REGEXP_LIKE(name, '.*(stack|over|flow).*', 'i');

A regex101 explaining the regex itself.


text:
Q: What is the expected time to get over SO addiction? I joined Stack Overflow slightly more than a month back. I have become very addicted to it (it is more useful than most social network addictions, I agree). But I know I must reduce my visits to SO.
I am just wondering — can the "reputed" people here tell whether they ever overcame their "addiction" after few months?

A: Yes. I started messing around SO early last year and was busy for a few months solid.
Once I got to the 3K mark, the urge to come and build the rep disappeared for me (it was already shrinking after the 2K mark).
I'll come, read through some interesting questions, and might answer one or two sporadically.
In general, though, most questions are answered very quickly and there was very little value I could provide by adding a repeat of a solid answer. There were times when I would answer at about the same exact time as another person on a new question and it was almost vertabim (with the same Reflector code snippet and all! (My SO Answer, Doppelgänger SO Answer).  That also contributed to the decline in addiction.
One other thing for me was the "Enthusiast" badge.  When I saw it, it felt like a misnomer. It really meant "Addicted" and was a reminder to not let it become an addiction.

A: There's an academic paper coming out that shows a slight drop off at 10,000 rep.
We're working on addressing that bug.

A: 6 to 8 weeks? That's just sort of... err... off the top of my head.

A: Just pick some high-rep users and check reputation graphs; you can see if they suddenly level off

A: Never.


text:
Q: Blackberry not able to fetch Latitude and longitude I need to get the users latitude and longitude to display data in increasing order of distance.
I am using 2 phones in 2 different countries to test the app. It works fine  with a bb bold 9700 when used in south asia. But does not with a bb 9650 when used in nyc.
I  tried using the bb gps api based classes and also google tower based gps classes.
Both don't seem to work in nyc with bb 9650.I used other location based apps like yelp etc which work perfectly.
Attaching both the codes
Phone GPS
public class GPS_Location
{
        private String log;
        double longi;
        double lati;
    public GPS_Location()
    {
            new LocationTracker();
    }
    public boolean onClose()
    {
            Application.getApplication().requestBackground();
            return false;
    }

    class LocationTracker extends TimerTask
    {

            private Timer timer;
            private LocationProvider provider;
            Criteria cr;

            public LocationTracker()
            {
                    timer = new Timer();
                    cr= new Criteria();
                    resetGPS();

                    timer.schedule(this, 0, 60000);
            }

            public void resetGPS()
            {

                    try
                    {
                            provider = LocationProvider.getInstance(cr);
                            if(provider != null)
                            {
                                    /*provider.setLocationListener(null, 0, 0, 0);
            provider.reset();
            provider = null;*/
                                    provider.setLocationListener(new MyLocationListener(), 3, -1, -1);
                            }

                            //provider = LocationProvider.getInstance(null);

                    } catch(Exception e)
                    {

                    }
            }

            public void run()
            {
                    System.out.println("********************");
            }

            private class MyLocationListener implements LocationListener
            {
                    public void locationUpdated(LocationProvider provider, Location location)
                    {
                            if(location != null && location.isValid())
                            {
                                    QualifiedCoordinates qc = location.getQualifiedCoordinates();

                                    try
                                    {
                                            lati = location.getQualifiedCoordinates().getLatitude();
                                            System.out.println("********************latitude :: "+lati);
                                            longi = location.getQualifiedCoordinates().getLongitude();
                                            System.out.println("********************longitude ::"+longi);
                                            CustomSession.getInstance().setLatitude(lati);
                                            CustomSession.getInstance().setLongitude(longi);
                                    }
                                    catch(Exception e)
                                    {

                                    }
                            }

                    }

                    public void providerStateChanged(LocationProvider provider, int newState)
                    {
                            //LocationTracker.this.resetGPS();
                            if(newState == LocationProvider.TEMPORARILY_UNAVAILABLE)
                            {
                                    provider.reset();
                                    provider.setLocationListener(null, 0, 0, -1);
                            }
                    }
            }
    }

}
cell tower google service
public class JsonGenerator {
    public void locating() throws IOException{
            byte[] postData = getGPSJsonObject().toString().getBytes();
            JSONObject jsonObject = null;
            HttpConnection gpsConnection;
            DataOutputStream os;
            DataInputStream dis;
            String gpsString = retrunURLString("http://www.google.com/loc/json");
            try {
                    gpsConnection = (HttpConnection) Connector.open(gpsString);
                    gpsConnection.setRequestMethod(HttpConnection.POST);
                    gpsConnection.setRequestProperty(
                                    HttpProtocolConstants.HEADER_CONTENT_LENGTH, String
                                                    .valueOf(postData.length));
                    gpsConnection.setRequestProperty(
                                    HttpProtocolConstants.HEADER_CONTENT_TYPE,
                                    "application / requestJson");
                    os = gpsConnection.openDataOutputStream();
                    os.write(postData);
                    int rc = gpsConnection.getResponseCode();
                    if (rc != HttpConnection.HTTP_OK) {
                            return;
                    }
                    dis = gpsConnection.openDataInputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int j = 0;
                    while ((j = dis.read()) != -1) {
                            baos.write(j);
                    }
                    byte[] data = baos.toByteArray();
                    String jsonString = new String(data);
                    try {
                            jsonObject = new JSONObject(jsonString);
                    } catch (JSONException e) {
                            e.printStackTrace();
                    }
                    JSONObject locationObject = jsonObject.getJSONObject("location");
                    if (locationObject.getDouble("latitude") != 0.0
                                    && locationObject.getDouble("longitude") != 0.0) {
                            System.out.println("Latitute is =================::::"+locationObject.getDouble("latitude"));
                            System.out.println("Llongitude is =================::::"+locationObject.getDouble("longitude"));
                            CustomSession.getInstance().setLatitude(locationObject.getDouble("latitude"));
                            CustomSession.getInstance().setLongitude(locationObject.getDouble("longitude"));

//                              Global.horizontal_accuracy = locationObject
//                                              .getDouble("accuracy");
//                              Global.locAvailable = true;
                        }
                } catch (JSONException e) {
                        // TODO: handle exception
                        e.printStackTrace();
                }
    }

    public JSONObject getGPSJsonObject() {
            JSONObject jsonString = new JSONObject();

            try {
                    jsonString.put("version", "1.1.0");
                    jsonString.put("host", "maps.google.com");
                    int x = RadioInfo.getMCC(RadioInfo.getCurrentNetworkIndex());
                    jsonString.put("home_mobile_country_code", Integer.parseInt(Integer
                                    .toHexString(x)));
                    jsonString.put("home_mobile_network_code", RadioInfo
                                    .getMNC(RadioInfo.getCurrentNetworkIndex()));

                    int radio = RadioInfo.getNetworkType();
                    if(radio==RadioInfo.NETWORK_CDMA){
                            jsonString.put("radio_type", "cdma");
                    }
                    else{
                            jsonString.put("radio_type", "gsm");
                    }
                    jsonString.put("carrier", RadioInfo.getCurrentNetworkName());
                    jsonString.put("request_address", true);
                    jsonString.put("address_language", "en_GB");

                    CellTower cellInfo = new CellTower(Integer.toHexString(x), GPRSInfo
                                    .getCellInfo().getLAC(), GPRSInfo.getCellInfo().getRSSI(),
                                    GPRSInfo.getCellInfo().getCellId(), 0, RadioInfo
                                                    .getMNC(RadioInfo.getCurrentNetworkIndex()));
                    Hashtable map = new Hashtable();
                    map.put("mobile_country_code", new Integer(Integer
                                    .parseInt(cellInfo.mobileCountryCode)));
                    map.put("location_area_code",
                                    new Integer(cellInfo.locationAreaCode));
                    map.put("signal_strength", new Integer(cellInfo.signalStrength));
                    map.put("cell_id", new Integer(cellInfo.cellID));
                    map.put("age", new Integer(0));
                    map.put("mobile_network_code", new Integer(
                                    cellInfo.mobileNetworkCode));

                    JSONArray array = new JSONArray();
                    array.put(0, map);

                    jsonString.put("cell_towers", array);
            } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
            }
            return jsonString;
    }

    public static String retrunURLString(String url) {
            String urlString = null;
            if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
                    // WIFI
                    urlString = url + ";interface=wifi";
            } else {
                    int coverageStatus = CoverageInfo.getCoverageStatus();
                    ServiceRecord record = getWAP2ServiceRecord();
                    if (record != null
                                    && (coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
                            // WAP 2.0
                            urlString = url + ";deviceside=true;ConnectionUID="
                                            + record.getUid();
                    } else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
                            // BES/MDS
                            urlString = url + ";deviceside=false";
                    } else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
                            // Direct TCP/IP
                            urlString = url + ";deviceside=true";
                    } else if ((coverageStatus & CoverageInfo.COVERAGE_BIS_B) == CoverageInfo.COVERAGE_BIS_B) {
                            // BIS
                            urlString = url + ";deviceside=false;ConnectionUID="
                                            + record.getUid();
                    }
            }
            return urlString;
    }

    protected static ServiceRecord getWAP2ServiceRecord() {
            ServiceBook sb = ServiceBook.getSB();
            ServiceRecord[] records = sb.getRecords();
            for (int i = 0; i < records.length; i++) {
                    String cid = records[i].getCid().toLowerCase();
                    String uid = records[i].getUid().toLowerCase();
                    if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1
                                    && uid.indexOf("mms") == -1) {
                            return records[i];
                    }
            }
            return null;
    }

    private class CellTower {
            public String mobileCountryCode;
            public int locationAreaCode;
            public int signalStrength;
            public int cellID;
            public int age;
            public int mobileNetworkCode;

            private CellTower(String mcc, int lac, int ss, int ci, int a, int mnc) {
                    mobileCountryCode = mcc;
                    locationAreaCode = lac;
                    signalStrength = ss;
                    cellID = ci;
                    age = a;
                    mobileNetworkCode = mnc;
            }
    }

}

A: Ideally you should be using multiple fix methods (your Criteria) to gather GPS information. Using just the default will not work in all circumstances, so you need to have fallback options. Here are the Criteria, in preferred order, that I use in the States and seems to do well. You just have to loop through them until you have a set that works.
    //Speed optimal
    BlackBerryCriteria speed = new BlackBerryCriteria();
    speed.setHorizontalAccuracy(50);
    speed.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
    speed.setCostAllowed(true);
    speed.setPreferredResponseTime(10000);

    //MS-Based
    BlackBerryCriteria msBased = new BlackBerryCriteria();
    msBased.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_MEDIUM);
    msBased.setHorizontalAccuracy(50);
    msBased.setVerticalAccuracy(50);
    msBased.setCostAllowed(true);
    msBased.setPreferredResponseTime(10000);

    //Assisted mode
    BlackBerryCriteria assisted = new BlackBerryCriteria();
    assisted.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_HIGH);
    assisted.setHorizontalAccuracy(50);
    assisted.setVerticalAccuracy(50);
    assisted.setCostAllowed(true);
    assisted.setPreferredResponseTime(10000);

    //Autonomous
    BlackBerryCriteria autonomous = new BlackBerryCriteria();
    autonomous.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_MEDIUM);
    autonomous.setHorizontalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
    autonomous.setVerticalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
    autonomous.setCostAllowed(true);
    autonomous.setPreferredResponseTime(180000);

    //Cell site
    BlackBerryCriteria cell = new BlackBerryCriteria();
    cell.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_LOW);
    cell.setHorizontalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
    cell.setVerticalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
    cell.setCostAllowed(true);
    cell.setPreferredResponseTime(180000);


text:
Q: How to read the file after sending a file using "GDServiceClient sendTo:" method as attachment? I'm Using two native iOS Apps to implement Good Dynamic Framework app kinetics, for now I'm successfully able to send a consumer request, received it at producer end and send a reply form producer , received at consumer end. using
sendTo (GDServiceClient) >>>>>>>>>>>>>>> GDServiceDidReceiveFrom
GDServiceClientDidReceiveFrom <<<<<<<<<<< replyTo (GDService).

problem arise when I try to send a pdf file from producer to consumer and read it at the consumer end.
I use the "GDServiceClient sendTo" method to send the file as its attachment. seems like file received by the consumer end successfully. I can see the good
console Xcode log
GTICCConnection: Number of attachments: 1
GTICCConnection: Finished reading data from all attachments 1/1. Last file size: 273459

I received the file path from attachment as "Inbox/BundleID/....../myfile.pdf"
But the Problem is GDFileManger contentsAtPath:fileInboxPath become nil and cannot read the file.
Questions
1.Can any one help me to resolve this issue. Is there a special way to read the file from GD Inbox?

*Why GDFileManager always need a valid NSFilePath when create a new file using createFileAtPath: ? it says it encrypt the file and file won't be at the physical path.

A: I found it. I will reply with a detailed answer in few days. until that,
Before read the file content I use check for file existence like this.
if ([[GDFileManager defaultManager] fileExistsAtPath:fileInboxPath]){
        NSData   *fileData = [[GDFileManager defaultManager] contentsAtPath:fileInboxPath];
        NSLog(@"Filedata: %@",fileData);
        NSString *content  = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
    }

but This if condition fails. After I commented out the line
[[GDFileManager defaultManager] fileExistsAtPath:fileInboxPath]
it starts working.


text:
Q: how do i create a proper in statement with sql? ****Edited, I forgot my teacher changed the tables a little, the primary key for both author and bookauthor is author_id and only author has ssn, not bookauthor****
My professor has given us a practice assignment for the IN statement for mysql and I can not, for the life of me, understand how to use the in statement and it is driving me crazy.
This is his question:
"Using a subquery, list the author's names for all books that have more than one author."
there is a database system with four tables, but really we only need two I think but i will put three down anyways
book table with
isbn (primary), title, type, pub_id, price, advance, ytd_sales, pub_date
bookauthor table(which is in between book and author) with, author_id(primary), isbn, author_order, royaltyshare
author table with, author_id(primary), ssn, lastname, firstname, phone, address, city, state, zip
the best I could come up with is
select lastname, firstname, isbn
from author where isbn in
(select isbn
from bookauthor
having count(author_id) > 1)

but it isn't working, and honestly, i don't really understand the in statement, I have read a lot of different websites, but they only seem to give basic info and it's driving me crazy. how does it work?

A: This is probably more simply written as a JOIN with a derived table (subquery) which counts the authors for each book:
SELECT firstname, lastname
FROM author a
JOIN bookauthor ba ON ba.author_id = a.author_id
JOIN (SELECT isbn
      FROM bookauthor
      GROUP BY isbn
      HAVING COUNT(author_id) > 0) c ON c.isbn = ba.isbn

If you have to use IN, you can just replace the last JOIN with a WHERE ... IN expression:
SELECT firstname, lastname
FROM author a
JOIN bookauthor ba ON ba.author_id = a.author_id
WHERE ba.isbn IN (SELECT isbn
                  FROM bookauthor
                  GROUP BY isbn
                  HAVING COUNT(author_id) > 0)

The IN expression works by comparing each ba.isbn value with the list of isbn values returned by the subquery - in this case, all those with more than one author. If ba.isbn is in this list, the row is displayed.


text:
Q: how to lauch external application using hot key through vb.net I have a windows program which is launched after pressing certain key combination (if its already running). Now i want to do this triggering through vb.net code? How can it be done?

A: You can do this by pinvoking RegisterHotKey.  Search this site or the web for that name to find sample code.  Here's one for example.
Do beware that this is probably not a good investment of your time, Windows already supports it.  Create a shortcut to the program.  Right-click it, Properties, Shortcut tab.  Click the "Shortcut key" text box and press the keystroke combination you want to use.

A: You need to watch the keydown event on your form. I am including a link from the msdn on examples:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown.aspx
here is a code snippet i found that someone posted:
http://www.daniweb.com/forums/thread114278.html

A: check the following posting it shows you how:
http://social.msdn.microsoft.com/forums/en-US/vssmartdevicesnative/thread/edb00219-530a-4506-acf1-0bea8e73a32d


text:
Q: How to insert result to table with "WITH AS" clause I have WITH AS clause in my code
DECLARE @MyTable TABLE(Field_1 INT, Field_2 INT)
INSERT @MyTable VALUES
(1,2),
(2,2)

WITH x AS ( SELECT Field_1, Field_2  FROM @MyTable)
SELECT * FROM x

How can I insert result of above code to the same table?
I'm tring to insert like:
DECLARE @MyTable TABLE(Field_1 INT, Field_2 INT)
INSERT @MyTable VALUES
(1,2),
(2,2)
WITH x AS ( SELECT Field_1, Field_2  FROM @MyTable)

INSERT INTO @MyTAble (SELECT * FROM x)
SELECT * FROM @MyTable

But it does not work. Management Studio mark @MyTAble like Invalid object name @MyTable
How can I do it? I'm using SQL Server 2008 R2.

A: Maybe you meant this (semi-colons and other little syntax things are important!),
DECLARE @MyTable TABLE(Field_1 INT, Field_2 INT);
------------------------------------------------^

INSERT @MyTable VALUES
(1,2),
(2,2);
-----^

WITH x AS ( SELECT Field_1, Field_2  FROM @MyTable)
------------------------------------------^
INSERT INTO @MyTAble  SELECT * FROM x ;
---------------------^---------------^^

SELECT * FROM @MyTable;
--------------^-------^

...but I don't think this will work in MySQL.