问:
sending one by one message through python over tcp protocol?
Hi I am trying to send same message 10 times through python over tcp protocol.
here is python code.

```<code>import socket
import sys
import random

HOST = '192.168.1.29'   # Symbolic name meaning all available interfaces
PORT = 55555 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(1)
print 'Socket now listening at',HOST, PORT
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
count = 0;
while 1:
    if (count > 9):
        break
    else:
        count = count + 1
        data  = ("hello world....!")
        conn.send(data)
        print "",data
    if data == "exit":
        break

conn.close()
s.close()
</code>```

As per code, Here i am trying to send "hello world" 10 times to far end as a separate message. In short each packet should contain only one time "hello world". but in my surprise, First packet contains one hello world message,but second packet contains 9 times hello world message. will you please let me know why it is happening? Is there any bug in code? if its not the way then how to send 10 different packets each containing one time hello world through python over tcp ?

答:
Hi Thanks all to give prompt reply. i find answer of my question. At one far end (sender) Tcp stack stores the data into the buffer and wait till buffer will be full and time out to send message in one packet. So after one message, tcp stack should have to be timed out. If it doesnt time out then tcp stack will combine with next messages. Like before i was facing the problem. Here i am sending different four messages 10 times. in previous example hello world you can remove function call and prefix data = hello world it. </p>

<p>Here is code and its working fine. Verified it through wireshark. </p>

```<code>import socket
import sys
import random
import time

HOST = '192.168.1.29'   # Symbolic name meaning all available interfaces
PORT = 55555 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(1)
print 'Socket now listening at',HOST, PORT
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
count = 1;

var = 0
def read_data(var):
    if var == 1:
        data = "1 hi"
        return data
    elif var == 2:
        data = "2 how are you"
        return data
    elif var == 3:
        data = "3 where are you?"
        return data
    else:
        data = "4 what are you doing?"
        return data

while 1:
    if(count < 10):
        count = count + 1
        var = random.randint(1,4)
        read_data(var);
        msg = read_data(var);
        conn.send(msg)
        print "",msg
        time.sleep(5)
    elif(count==10):
        data = "exit"
        conn.send(data)
        print "",data
        time.sleep(5)
        break
    else:
        break

conn.close()
s.close()
</code>```

Body:
Hi I am trying to send same message 10 times through python over tcp protocol.
here is python code.

import socket
import sys
import random

HOST = '192.168.1.29'   # Symbolic name meaning all available interfaces
PORT = 55555 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(1)
print 'Socket now listening at',HOST, PORT
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
count = 0;
while 1:
    if (count > 9):
        break
    else:
        count = count + 1
        data  = ("hello world....!")
        conn.send(data)
        print "",data
    if data == "exit":
        break

conn.close()
s.close()

As per code, Here i am trying to send "hello world" 10 times to far end as a separate message. In short each packet should contain only one time "hello world". but in my surprise, First packet contains one hello world message,but second packet contains 9 times hello world message. will you please let me know why it is happening? Is there any bug in code? if its not the way then how to send 10 different packets each containing one time hello world through python over tcp ?

Body:
Hi Thanks all to give prompt reply. i find answer of my question. At one far end (sender) Tcp stack stores the data into the buffer and wait till buffer will be full and time out to send message in one packet. So after one message, tcp stack should have to be timed out. If it doesnt time out then tcp stack will combine with next messages. Like before i was facing the problem. Here i am sending different four messages 10 times. in previous example hello world you can remove function call and prefix data = hello world it.

Here is code and its working fine. Verified it through wireshark.

import socket
import sys
import random
import time

HOST = '192.168.1.29'   # Symbolic name meaning all available interfaces
PORT = 55555 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(1)
print 'Socket now listening at',HOST, PORT
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
count = 1;

var = 0
def read_data(var):
    if var == 1:
        data = "1 hi"
        return data
    elif var == 2:
        data = "2 how are you"
        return data
    elif var == 3:
        data = "3 where are you?"
        return data
    else:
        data = "4 what are you doing?"
        return data

while 1:
    if(count < 10):
        count = count + 1
        var = random.randint(1,4)
        read_data(var);
        msg = read_data(var);
        conn.send(msg)
        print "",msg
        time.sleep(5)
    elif(count==10):
        data = "exit"
        conn.send(data)
        print "",data
        time.sleep(5)
        break
    else:
        break

conn.close()
s.close()


来源: stackexchange

问:
Edit Microsoft-office .doc file in java using Apache POI
I'm writing java code to achieve the followings.

1.Read given Microsoft-office document(.doc) file.

2.Search for given string in the file.

3.Delete the given String located in any place.

4.Insert or replace any given string at specified position.

5.Write and save the updated file content into new .doc file.

I have written a code to read, search, insert or replace, delete and save the file and it's working good, but i couldn't able to preserve the text format(such as font color, font size, justification, left and right indent, styles etc) applied in the input file.

please anyone helps me to solve the issue.

Thank you

答:
You can use the following code:

```<code>public class EditingWord{

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String filename = "path to input file/file_input_name";
        List<String> paraList = new ArrayList<String>();
        try {

            XWPFDocument doc = new XWPFDocument(OPCPackage.open(new FileInputStream(filename)));
            List<XWPFParagraph> paragraphList = doc.getParagraphs();
            for (XWPFParagraph para : paragraphList) {
                if ((para.getStyle() != null) && (para.getNumFmt() != null)) {
                    for (XWPFRun run : para.getRuns()) {
                        String text = run.text();
                        text = text.replaceAll(text, "replacement" + text);
                        run.setText(text, 0);
                    }
                }
            }
            doc.write(new FileOutputStream("path to your file/output_File_name"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
</code>```

In case if you want to save your content to same file, you can change doc.write(new FileOutputStream("path to your inpufile/input_File_name"));

ContentLicense: CC BY-SA 3.0

Body:
You can use the following code:

public class EditingWord{

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String filename = "path to input file/file_input_name";
        List<String> paraList = new ArrayList<String>();
        try {

            XWPFDocument doc = new XWPFDocument(OPCPackage.open(new FileInputStream(filename)));
            List<XWPFParagraph> paragraphList = doc.getParagraphs();
            for (XWPFParagraph para : paragraphList) {
                if ((para.getStyle() != null) && (para.getNumFmt() != null)) {
                    for (XWPFRun run : para.getRuns()) {
                        String text = run.text();
                        text = text.replaceAll(text, "replacement" + text);
                        run.setText(text, 0);
                    }
                }
            }
            doc.write(new FileOutputStream("path to your file/output_File_name"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

In case if you want to save your content to same file, you can change doc.write(new FileOutputStream("path to your inpufile/input_File_name"));


问:
Class design and inheritance issue
So in my Monopoly game I have base class Field, derived class Property : public Field and Board which contains array of Field type.

```<code>class Field {
protected:
    int m_position;
public:
    Field() { }
    Field(int p_position) : m_position(p_position) { }
    virtual void showProperty() const { std::cout << "Actuall output"; };
};
</code>```

Next class is Property which derives from Field

```<code>class Property : public Field {
    float m_price;
public:
    Property(int, float);
    void showProperty() const;
};
</code>```

in property.cpp

```<code>Property::Property(int p_position, float p_price) : Field(p_position), m_price(p_price) { }

void Property::showProperty() const {
    std::cout <<
        "Position: " << m_position << "\n" <<
        "Price: " << std::to_string(m_price) << "\n";
}
</code>```

Now lets see board.h

```<code>constexpr int BOARD_SIZE = 40;

class Board {
    std::unique_ptr<Field[]> m_board;
public:
    Board();
    Field getField(int index) { return m_board[index]; }
};
</code>```

and its constructor

```<code>Board::Board() {
    m_board = std::make_unique<Field[]>(BOARD_SIZE);
    Property test(1, 100);
    m_board[0] = test;
}
</code>```

in main i create something like this

```<code>int main() {
    Board newBoard;
    newBoard.getField(0).showProperty();
}
</code>```

and I expect it to call Property::showProperty()but it calls Field::showProperty(). Why isnt it using derived class function?

答:
Because your pointer m_board is a pointer to the first element of an array of Field objects.

That means the assignment m_board[0] = test will slice the Property object.

You need an array of pointers to Field. For example

```<code>std::array<Field*, BOARD_SIZE> m_board;
</code>```

Of course, remember to make the pointers in the array actually point somewhere valid:

```<code>m_board[0] = new Property(1, 100);
</code>```

And also of course you need to modify the getField function return-type to be correct.

Title: Class design and inheritance issue

Body:
So in my Monopoly game I have base class Field, derived class Property : public Field and Board which contains array of Field type.

class Field {
protected:
    int m_position;
public:
    Field() { }
    Field(int p_position) : m_position(p_position) { }
    virtual void showProperty() const { std::cout << "Actuall output"; };
};

Next class is Property which derives from Field

class Property : public Field {
    float m_price;
public:
    Property(int, float);
    void showProperty() const;
};

in property.cpp

Property::Property(int p_position, float p_price) : Field(p_position), m_price(p_price) { }

void Property::showProperty() const {
    std::cout <<
        "Position: " << m_position << "\n" <<
        "Price: " << std::to_string(m_price) << "\n";
}

Now lets see board.h

constexpr int BOARD_SIZE = 40;

class Board {
    std::unique_ptr<Field[]> m_board;
public:
    Board();
    Field getField(int index) { return m_board[index]; }
};

and its constructor

Board::Board() {
    m_board = std::make_unique<Field[]>(BOARD_SIZE);
    Property test(1, 100);
    m_board[0] = test;
}

in main i create something like this

int main() {
    Board newBoard;
    newBoard.getField(0).showProperty();
}

and I expect it to call Property::showProperty()but it calls Field::showProperty(). Why isnt it using derived class function?

Body:
Because your pointer m_board is a pointer to the first element of an array of Field objects.

That means the assignment m_board[0] = test will slice the Property object.

You need an array of pointers to Field. For example

std::array<Field*, BOARD_SIZE> m_board;

Of course, remember to make the pointers in the array actually point somewhere valid:

m_board[0] = new Property(1, 100);

And also of course you need to modify the getField function return-type to be correct.


问:
Call JavaScript Function from Symfony Component
I have created a new JSON string (by converting a PHP array using json_encode) and stored it in $siteTree ... outputting it to the log shows the following

```<code>[
{
    "attr": {
        "id": "node_1",
        "rel": "folder"
    },
    "data": "New Title",
    "children": [
        {
            "attr": {
                "id": "node_2",
                "rel": "folder"
            },
            "data": "second document",
            "children": []
        }
    ]
}
</code>```

]

So I know the JSON is formed correctly. What I am trying to do is use that variable in a javascript function to create an object using the JSON data ... I am doing the following in the template

```<code><?php
    use_helper('JavascriptBase');
    echo javascript_tag('createTree('.$siteTree.')');
?>
</code>```

The following is shown on the output page

```<code>createTree([{"attr":{"id":"node_1","rel":"folder"},"data":"New Title","children":[{"attr":{"id":"node_2","rel":"folder"},"data":"second document","children":[]}]}])
</code>```

The function is called but the JSON has replaced the " with &quote;.  How can I stop this ?

Thanks for your help !

答:
Symfony automatically performs output escaping to help prevent several types of XSS attacks.

You can disable it by configuration, or depending on what version of the Symfony framework you're using, access the raw data in your view like this:

```<code>$sf_data->getRaw('siteTree')
</code>```

e.g.

```<code>echo javascript_tag('createTree(' . $sf_data->getRaw('siteTree') . ')');
</code>```

If that doesn't work for you, you should find the relevant references you need by consulting the Symfony documentation for your version of the framework, searching for "output escaping".

ContentLicense: CC BY-SA 2.5

Body:
I have created a new JSON string (by converting a PHP array using json_encode) and stored it in $siteTree ... outputting it to the log shows the following

[
{
    "attr": {
        "id": "node_1",
        "rel": "folder"
    },
    "data": "New Title",
    "children": [
        {
            "attr": {
                "id": "node_2",
                "rel": "folder"
            },
            "data": "second document",
            "children": []
        }
    ]
}

]

So I know the JSON is formed correctly. What I am trying to do is use that variable in a javascript function to create an object using the JSON data ... I am doing the following in the template

<?php
    use_helper('JavascriptBase');
    echo javascript_tag('createTree('.$siteTree.')');
?>

The following is shown on the output page

createTree([{"attr":{"id":"node_1","rel":"folder"},"data":"New Title","children":[{"attr":{"id":"node_2","rel":"folder"},"data":"second document","children":[]}]}])

The function is called but the JSON has replaced the " with &quote;.  How can I stop this ?

Thanks for your help !

Body:
Symfony automatically performs output escaping to help prevent several types of XSS attacks.

You can disable it by configuration, or depending on what version of the Symfony framework you're using, access the raw data in your view like this:

$sf_data->getRaw('siteTree')

e.g.

echo javascript_tag('createTree(' . $sf_data->getRaw('siteTree') . ')');

If that doesn't work for you, you should find the relevant references you need by consulting the Symfony documentation for your version of the framework, searching for "output escaping".


问:
Error:null value in entry: streamOutputFolder=null OR Error:null value in entry: streamOutputFolder=null
I am unable to run my app in emulator because of this Error:

Error:null value in entry: streamOutputFolder=null

or

gradle - Error:null value in entry: incrementalFolder=null

答:
```<code>Empty all "build" folders in your project
Copy all your project files and folders
Create a new folder and past it there
Open android Studio and import project
Wait Android Studio to download all dependecies.
</code>```

And i found another solution here: LINK

Removing the .gradle directory in the root project directory will fix the problem.

Hope this helps you.

Body:
Empty all "build" folders in your project
Copy all your project files and folders
Create a new folder and past it there
Open android Studio and import project
Wait Android Studio to download all dependecies.

And i found another solution here: LINK

Removing the .gradle directory in the root project directory will fix the problem.

Hope this helps you.


问:
PHP Regex Extract Substring with Quotes and Brackets
I have the following String examples:

```<code>new myProduct('', 'bbc_609'),
new myProduct('', '35857'),
</code>```

I want to be able to extract just the codes in the second set of single quotes:  bbc_609 or 35857

What I have tried:

```<code>$str = "new myProduct('', 'bbc_609'),";
preg_match('/ new myProduct('', '  ' (.*?) ''),/', $str, $match);
echo $match[1];
</code>```

I am getting a parse error so I am assuming that I am not escaping the quotes or brackets properly?

Any help appreciated.

Cheers

答:
You have to escape the brackets and the quotes otherwise they will be interpreted differently by php and regex. </p>

```<code>$str = "new myProduct('', 'bbc_609'),";
preg_match('/new myProduct\(\'\', \'(.*)\'\)/', $str, $match);
echo $match[1];
</code>```

Body:
I have the following String examples:

new myProduct('', 'bbc_609'),
new myProduct('', '35857'),

I want to be able to extract just the codes in the second set of single quotes:  bbc_609 or 35857

What I have tried:

$str = "new myProduct('', 'bbc_609'),";
preg_match('/ new myProduct('', '  ' (.*?) ''),/', $str, $match);
echo $match[1];

I am getting a parse error so I am assuming that I am not escaping the quotes or brackets properly?

Any help appreciated.

Cheers

Body:
You have to escape the brackets and the quotes otherwise they will be interpreted differently by php and regex.

$str = "new myProduct('', 'bbc_609'),";
preg_match('/new myProduct\(\'\', \'(.*)\'\)/', $str, $match);
echo $match[1];


问:
How to use django together with mongoengine?
I want to use a mongodb database together with the django framework. For that purpose I tried to set up a small test project using the mongoengine and this description: http://staltz.com/djangoconfi-mongoengine/#/8

Unfortunately, it is not working. The relevant parts of my settings.py, views.py and models.py are looking like this:

settings.py:

```<code># Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import mongoengine

[...]

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'testApp',
)
[...]

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': '',
    }
}

SESSION_ENGINE = 'mongoengine.django.sessions'

_MONGODB_USER = 'mongouser'
_MONGODB_PASSWD = 'test'
_MONGODB_HOST = 'localhost'
_MONGODB_NAME = 'testDb'
_MONGODB_DATABASE_HOST = \
  'mongodb://%s:%s@%s/%s' \
  % (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME)

mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST)

AUTHENTICATION_BACKENDS = (
    'mongoengine.django.auth.MongoEngineBackend',
)
</code>```

models.py

```<code>from mongoengine import *

# Create your models here.
class Choice(Document):
  choice_text = StringField(max_length=200)
</code>```

views.py

```<code>from django.shortcuts import render
from django.http import HttpResponse
from testApp.models import Choice
from django.contrib.auth import authenticate

def index(request):
  newChoice = Choice(choice_text="First test")
  newChoice.save()
  return HttpResponse("Test")

user = authenticate(username='mongouser', password='test')
assert isinstance(user, mongoengine.django.auth.User)
</code>```

When I start the testserver and open the testApp website, I get an "ImportError: No module named django.sessions". Therefore, I removed the SESSION_ENGINE part from my settings.py, which was marked as optional in above's description. Afterwards I get an "No module named django.auth" error.

Do you have an idea what is going wrong and how to set up django together with mongoengine in order to use a mongodb database?

答:
I want to use a mongodb database together with the django framework

If this is your goal there are several ways to accomplish it. Depending on the strategy you take, do factor in the trade offs.

Use a MongoDB compatible model framework (MongoEngine): You can completely avoid using the Django models in your project and use MongoEngine or Ming in you django projects. However will miss out on: 1500+ core contributors to the project, hourly fixes and ticket resolution, ramp down on the expertise of existing Django models and ramp up on the new model framework. Miss out on Django’s contrib models like Admin, Sessions, Users, Auth, etc., contrib modules for your project.

Django SQL to MongoDB transpiler — Djongo: Translate Django SQL query syntax generated by the Django ORM into pymongo commands. Djongo is one such SQL to MongoDB query compiler. It translates every SQL query string into a mongoDB query document. As a result, all Django models and related modules work as is.

Body:
I want to use a mongodb database together with the django framework. For that purpose I tried to set up a small test project using the mongoengine and this description: http://staltz.com/djangoconfi-mongoengine/#/8

Unfortunately, it is not working. The relevant parts of my settings.py, views.py and models.py are looking like this:

settings.py:

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import mongoengine

[...]

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'testApp',
)
[...]

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': '',
    }
}

SESSION_ENGINE = 'mongoengine.django.sessions'

_MONGODB_USER = 'mongouser'
_MONGODB_PASSWD = 'test'
_MONGODB_HOST = 'localhost'
_MONGODB_NAME = 'testDb'
_MONGODB_DATABASE_HOST = \
  'mongodb://%s:%s@%s/%s' \
  % (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME)

mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST)

AUTHENTICATION_BACKENDS = (
    'mongoengine.django.auth.MongoEngineBackend',
)

models.py

from mongoengine import *

# Create your models here.
class Choice(Document):
  choice_text = StringField(max_length=200)

views.py

from django.shortcuts import render
from django.http import HttpResponse
from testApp.models import Choice
from django.contrib.auth import authenticate

def index(request):
  newChoice = Choice(choice_text="First test")
  newChoice.save()
  return HttpResponse("Test")

user = authenticate(username='mongouser', password='test')
assert isinstance(user, mongoengine.django.auth.User)

When I start the testserver and open the testApp website, I get an "ImportError: No module named django.sessions". Therefore, I removed the SESSION_ENGINE part from my settings.py, which was marked as optional in above's description. Afterwards I get an "No module named django.auth" error.

Do you have an idea what is going wrong and how to set up django together with mongoengine in order to use a mongodb database?


问:
Can we use ternary operator within an if statement?
My teacher says we can't use a ternary operator within an if statement as it's an alternative for it... Can anyone please tell me if we can use ternary operators within an if statement in c++? </p>

答:
The basic answer is: Yes, you can.

As @Bathsheba already pointed out: It may not always make sense.

A more sensible example might be something like this:

```<code>if (use_locking ? readLocked() : readUnlocked())
{
   ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The basic answer is: Yes, you can.

As @Bathsheba already pointed out: It may not always make sense.

A more sensible example might be something like this:

if (use_locking ? readLocked() : readUnlocked())
{
   ...
}


问:
How to schedule a periodic task in Python?
How can I schedule a periodic task in python without blocking?

Here is a simple situation. Assume this ticket variable becomes invalid after 2 hours. So I need to fetch it from a serve.

```<code>ticket = 1 # It expires every 2 hours

def process_using_ticket(): # This function is called using a get request from flask server
    print('hello', ticket)
</code>```

How can I reset to 1 every two hours without blocking?

One way could be to start a thread and sleep for 2 hours and then reset the variable but I am wondering if there are better alternatives.

Note: Everything runs in a docker.

答:
Put it in a function with time.sleep(7200000). Like so:

```<code>import time

ticket = 1

def main_loop():
    while True:
        time.sleep(7200000)
        ticket = 1

def process_using_ticket():
    print('hello', ticket)
main_loop()
</code>```

Body:
How can I schedule a periodic task in python without blocking?

Here is a simple situation. Assume this ticket variable becomes invalid after 2 hours. So I need to fetch it from a serve.

ticket = 1 # It expires every 2 hours

def process_using_ticket(): # This function is called using a get request from flask server
    print('hello', ticket)

How can I reset to 1 every two hours without blocking?

One way could be to start a thread and sleep for 2 hours and then reset the variable but I am wondering if there are better alternatives.

Note: Everything runs in a docker.

Body:
Put it in a function with time.sleep(7200000). Like so:

import time

ticket = 1

def main_loop():
    while True:
        time.sleep(7200000)
        ticket = 1

def process_using_ticket():
    print('hello', ticket)
main_loop()


问:
How can I remove SID form URL in magento 2.1.7
I have made all setting from magneto backend that is "Session Validation Settings ->Use SID on Storefront   :no", clear all cache also. But still not able to remove SID from URL.

It's showing like this:

https://www.exapmle.com/?SID=fpej05jr1fhoi3p083m72fj062

How to remove the SID?

答:
I think you have not selected store or storeview.
and follow bellow step.

Go to the Store > Configuration > General > Web > Session Validation Settings > Use SID on Storefront and set its value to No

Or

Isn't ?SID automatically added by PHP if PHP is configured to not store sessions on the server or the browser doesn't accept cookies?

Note:

The SID is a "session ID". Magento uses this to track a user's activity within the same Magento installation. Normally, Magento powers one website and one store from one installation (database).

Magento could power multiple websites with multiple stores from one installation though. The SID allows users to stay logged in while navigating across these websites/stores.

I think if you have the function enabled, the SID is sent when accessing catalog URLs so Magento can update the session with the user's location/state for the current website/store.

If you're not running a multi-website or multi-store environment, it's safe to disable the SID on the frontend.


问:
How to dynamically add a scheduled task to Celery beat
Using Celery ver.3.1.23, I am trying to dynamically add a scheduled task to celery beat. I have one celery worker and one celery beat instance running.

Triggering a standard celery task y running task.delay() works ok. When I define a scheduled periodic task as a setting in configuration, celery beat runs it.

However what I need is to be able to add a task that runs at specified crontab at runtime. After adding a task to persistent scheduler, celery beat doesn't seem to detect the newly added new task. I can see that the celery-schedule file does have an entry with new task.

Code:

```<code>scheduler = PersistentScheduler(app=current_app, schedule_filename='celerybeat-schedule')
scheduler.add(name="adder",
          task="app.tasks.add",
          schedule=crontab(minute='*/1'),
          args=(1,2))
scheduler.close()
</code>```

When I run:

```<code>print(scheduler.schedule)
</code>```

I get:

```<code>{'celery.backend_cleanup': <Entry: celery.backend_cleanup celery.backend_cleanup() <crontab: 0 4 * * * (m/h/d/dM/MY)>,
'adder': <Entry: adder app.tasks.add(1, 2) <crontab: */1 * * * * (m/h/d/dM/MY)>}
</code>```

Note that app.tasks.add has the @celery.task decorator.

答:
I'm having a similar problem and a solution I thought about is to pre-define some generic periodic tasks (every 1s, every 5mins, etc) and then have them getting, from DB, a list of function to be executed.
Every time you want to add a new task you just add an entry in your DB.</p>

Body:
Using Celery ver.3.1.23, I am trying to dynamically add a scheduled task to celery beat. I have one celery worker and one celery beat instance running.

Triggering a standard celery task y running task.delay() works ok. When I define a scheduled periodic task as a setting in configuration, celery beat runs it.

However what I need is to be able to add a task that runs at specified crontab at runtime. After adding a task to persistent scheduler, celery beat doesn't seem to detect the newly added new task. I can see that the celery-schedule file does have an entry with new task.

Code:

scheduler = PersistentScheduler(app=current_app, schedule_filename='celerybeat-schedule')
scheduler.add(name="adder",
          task="app.tasks.add",
          schedule=crontab(minute='*/1'),
          args=(1,2))
scheduler.close()

When I run:

print(scheduler.schedule)

I get:

{'celery.backend_cleanup': <Entry: celery.backend_cleanup celery.backend_cleanup() <crontab: 0 4 * * * (m/h/d/dM/MY)>,
'adder': <Entry: adder app.tasks.add(1, 2) <crontab: */1 * * * * (m/h/d/dM/MY)>}

Note that app.tasks.add has the @celery.task decorator.


问:
How to read text file form particular directory in ios app?
I want to read text file in my ios app. test1 folder contains one.txt file. When I remove this "inDirectory:"test1""  my code works correctly. But I want to mention the folder name. How to do that ?

```<code>if let path = Bundle.main.path(forResource: "one", ofType: "txt" ,

 inDirectory:"test1" )

    {
        text2 = try! String(contentsOfFile: path, encoding:String.Encoding.utf8)
    }
    else
    {
        print("file not found")
    }
</code>```

答:
In macOS, create a folder name it test1, put the txt file inside it and drag it into Xcode. Make sure Create folder references is selected:

...then your code should work.

Body:
I want to read text file in my ios app. test1 folder contains one.txt file. When I remove this "inDirectory:"test1""  my code works correctly. But I want to mention the folder name. How to do that ?

if let path = Bundle.main.path(forResource: "one", ofType: "txt" ,

 inDirectory:"test1" )

    {
        text2 = try! String(contentsOfFile: path, encoding:String.Encoding.utf8)
    }
    else
    {
        print("file not found")
    }


问:
BundleID of an existing app on iOS 8.4.1
Is anybody knows how can I get BundleID of an existing app on iOS 8.4.1?

For example the messages app

Thanks

答:
Using this you can get the bundle id

NSString *bundleId = [[NSBundle mainBundle] bundleIdentifier];

NSLog("%@",bundleId);


问:
How to accept value from user and change particular value in XML file and launch browser?
```<code>@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set freePort=
set newPort=

REM Checking the default value in XML file located at the path
FOR /F tokens^=4^ delims^=^" %%A in (
'type %~dp0\wlp\usr\servers\defaultServer\server.xml ^| find "httpEndpoint host="'
) do (
     echo: Default Port in XML = %%A
     set /a startPort=%%A

)
echo myCurrent port %startPort%

:SEARCHPORT
netstat -o -n -a | find "LISTENING" | find ":%startPort% " > NUL
if "%ERRORLEVEL%" equ "0" (
  echo "port unavailable %startPort%"

 REM Here I want to ask user to enter a port number rather than hard-coded value ???
  set /a startPort=9080
  echo myNew port %startPort%
  GOTO :SEARCHPORT

) ELSE (
  echo "port available %startPort%"
  set freePort=%startPort%
  GOTO :FOUNDPORT
)

:FOUNDPORT
echo free %freePort%

REM here I want to change the value of the httpPort in XML and save the xml file, and then launch the default browser with https:\\localhost:<freePort>MyApp ???

)
@pause
</code>```

The server.xml content is:

```<code><server description="new server">

<!-- Enable features -->
<featureManager>
    <feature>webProfile-7.0</feature>
    <!-- <feature>localConnector-1.0</feature> -->
</featureManager>

<!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
<httpEndpoint host="27" httpPort="5357" httpsPort="9443" id="defaultHttpEndpoint"/>

<!-- Automatically expand WAR files and EAR files -->
<applicationManager autoExpand="true"/>

<applicationMonitor updateTrigger="mbean"/>
</code>```

答:
Processing an XML file with Windows command interpreter is awful. cmd.exe is designed for executing commands and applications and not for parsing XML files and modifying them. It would be definitely much better to write an executable with C, C++ or C# for this task instead of doing that with a batch file.

However, here is a commented batch file for replacing current port number of attribute httpPort by a new port number assigned to environment variable NewPort in the XML file server.xml which must be stored in same directory as the batch file. Please read the comments as this code has still some limitations like number for attribute httpsPort must be different to number of httpPort as otherwise two numbers are replaced at the same time.

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem First check if the file to modify exists in directory of batch file.
set "XmlFile=%~dp0server.xml"
if not exist "%XmlFile%" goto EndBatch

rem Define some environment variables which are needed later.
set "NewPort=47680"
set "LineNumber="
set "LineCount=0"
set "TmpFile=%TEMP%\%~n0.tmp"

rem Search for the line containing attribute httpPort and get its
rem line number and the line itself loaded into environment variables.

for /F "tokens=1* delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /L /N /C:httpPort= "%XmlFile%" 2^>nul') do (
    set "LineNumber=%%I"
    set "PortLine=%%J"
)

rem If no line with attribute httpPort found, exit this batch file.
if not defined LineNumber goto EndBatch

rem Determine current number of attribute httpPort independent on where
rem this attribute is specified in the XML line and replace this number
rem in the line with the new port number as defined before.

rem It is required for this type of number replace that the other port
rem number for httpsPort is not the same number as current number for
rem httpPort as in this case both numbers would be replaced by the new
rem number. The attribute name and the equal sign cannot be included in
rem the string substitution as used here.

setlocal EnableDelayedExpansion
set "PortNumber=!PortLine:*httpPort=!"
for /F %%I in ("!PortNumber:~1!") do set "PortNumber=%%~I"
set "PortLine=!PortLine:"%PortNumber%"="%NewPort%"!"
endlocal & set "PortLine=%PortLine%"

rem Make sure the temporary file used next does not already exist.
del "%TmpFile%" 2>nul

rem Copy all lines from XML file to a temporary file including empty
rem lines with the exception of the line containing attribute httpPort
rem which is copied to temporary file with the modified port number.
for /F "tokens=1* delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /R /N "^" "%XmlFile%" 2^>nul') do (
    set "XmlLine=%%J"
    set /A LineCount+=1
    setlocal EnableDelayedExpansion
    if not !LineCount! == %LineNumber% (
        echo/!XmlLine!>>"%TmpFile%"
    ) else (
        echo/!PortLine!>>"%TmpFile%"
    )
    endlocal
)

rem Overwrite original file with temporary file automatically deleted on success.
move /Y "%TmpFile%" "%XmlFile%" >nul

:EndBatch
endlocal
</code>```

Much better would be using for example JREPL.bat written by Dave Benham which is a batch file / JScript hybrid for replacing the value in the XML file using a regular expression.

```<code>@echo off
if not exist "%~dp0server.xml" goto :EOF
set "NewPort=47681"

call "%~dp0jrepl.bat" "(httpPort=[\x22']?)\d*([\x22']?)" "$1%NewPort%$2" /I /F "%~dp0server.xml" /O -
</code>```

By using jrepl.bat it does not matter what is the current value of attribute httpPort which could be even an empty string. The case-insensitive regular expression replace as used here would even handle the attribute httpPort with value enclosed in single instead of double quotes or not enclosed at all in quotes although that would not be valid for an XML file.

\x22 is the hexadecimal notation for " used here to avoid problems with Windows command interpreter because the search argument string itself is enclosed in double quotes.

Body:
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set freePort=
set newPort=

REM Checking the default value in XML file located at the path
FOR /F tokens^=4^ delims^=^" %%A in (
'type %~dp0\wlp\usr\servers\defaultServer\server.xml ^| find "httpEndpoint host="'
) do (
     echo: Default Port in XML = %%A
     set /a startPort=%%A

)
echo myCurrent port %startPort%

:SEARCHPORT
netstat -o -n -a | find "LISTENING" | find ":%startPort% " > NUL
if "%ERRORLEVEL%" equ "0" (
  echo "port unavailable %startPort%"

 REM Here I want to ask user to enter a port number rather than hard-coded value ???
  set /a startPort=9080
  echo myNew port %startPort%
  GOTO :SEARCHPORT

) ELSE (
  echo "port available %startPort%"
  set freePort=%startPort%
  GOTO :FOUNDPORT
)

:FOUNDPORT
echo free %freePort%

REM here I want to change the value of the httpPort in XML and save the xml file, and then launch the default browser with https:\\localhost:<freePort>MyApp ???

)
@pause

The server.xml content is:

<server description="new server">

<featureManager>
    <feature>webProfile-7.0</feature>

</featureManager>

<httpEndpoint host="27" httpPort="5357" httpsPort="9443" id="defaultHttpEndpoint"/>

<applicationManager autoExpand="true"/>

<applicationMonitor updateTrigger="mbean"/>

Body:
Processing an XML file with Windows command interpreter is awful. cmd.exe is designed for executing commands and applications and not for parsing XML files and modifying them. It would be definitely much better to write an executable with C, C++ or C# for this task instead of doing that with a batch file.

However, here is a commented batch file for replacing current port number of attribute httpPort by a new port number assigned to environment variable NewPort in the XML file server.xml which must be stored in same directory as the batch file. Please read the comments as this code has still some limitations like number for attribute httpsPort must be different to number of httpPort as otherwise two numbers are replaced at the same time.

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem First check if the file to modify exists in directory of batch file.
set "XmlFile=%~dp0server.xml"
if not exist "%XmlFile%" goto EndBatch

rem Define some environment variables which are needed later.
set "NewPort=47680"
set "LineNumber="
set "LineCount=0"
set "TmpFile=%TEMP%\%~n0.tmp"

rem Search for the line containing attribute httpPort and get its
rem line number and the line itself loaded into environment variables.

for /F "tokens=1* delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /L /N /C:httpPort= "%XmlFile%" 2^>nul') do (
    set "LineNumber=%%I"
    set "PortLine=%%J"
)

rem If no line with attribute httpPort found, exit this batch file.
if not defined LineNumber goto EndBatch

rem Determine current number of attribute httpPort independent on where
rem this attribute is specified in the XML line and replace this number
rem in the line with the new port number as defined before.

rem It is required for this type of number replace that the other port
rem number for httpsPort is not the same number as current number for
rem httpPort as in this case both numbers would be replaced by the new
rem number. The attribute name and the equal sign cannot be included in
rem the string substitution as used here.

setlocal EnableDelayedExpansion
set "PortNumber=!PortLine:*httpPort=!"
for /F %%I in ("!PortNumber:~1!") do set "PortNumber=%%~I"
set "PortLine=!PortLine:"%PortNumber%"="%NewPort%"!"
endlocal & set "PortLine=%PortLine%"

rem Make sure the temporary file used next does not already exist.
del "%TmpFile%" 2>nul

rem Copy all lines from XML file to a temporary file including empty
rem lines with the exception of the line containing attribute httpPort
rem which is copied to temporary file with the modified port number.
for /F "tokens=1* delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /R /N "^" "%XmlFile%" 2^>nul') do (
    set "XmlLine=%%J"
    set /A LineCount+=1
    setlocal EnableDelayedExpansion
    if not !LineCount! == %LineNumber% (
        echo/!XmlLine!>>"%TmpFile%"
    ) else (
        echo/!PortLine!>>"%TmpFile%"
    )
    endlocal
)

rem Overwrite original file with temporary file automatically deleted on success.
move /Y "%TmpFile%" "%XmlFile%" >nul

:EndBatch
endlocal

Much better would be using for example JREPL.bat written by Dave Benham which is a batch file / JScript hybrid for replacing the value in the XML file using a regular expression.

@echo off
if not exist "%~dp0server.xml" goto :EOF
set "NewPort=47681"

call "%~dp0jrepl.bat" "(httpPort=[\x22']?)\d*([\x22']?)" "$1%NewPort%$2" /I /F "%~dp0server.xml" /O -

By using jrepl.bat it does not matter what is the current value of attribute httpPort which could be even an empty string. The case-insensitive regular expression replace as used here would even handle the attribute httpPort with value enclosed in single instead of double quotes or not enclosed at all in quotes although that would not be valid for an XML file.

\x22 is the hexadecimal notation for " used here to avoid problems with Windows command interpreter because the search argument string itself is enclosed in double quotes.


问:
How can I get today's timestamp in PHP
I tried

```<code>$dtToday = DateTime::createFromFormat('Y-m-d', date('Y-m-d'));
</code>```

but when I output it

```<code>die($dtToday->format('d M Y g:i:s a'));
</code>```

I still get the time eg "22 Jan 2011 4:53:59 pm". Why is that?

UPDATE

Ah... many people misunderstood me, my bad, I forgot to point out the main point. I created the date with just the date portion, I don't want the time. So I'd expect something like

```<code>22 Jan 2011 12:00:00 am
</code>```

答:
You can call ->setTime(0, 0) to zero out the time portion:

```<code>$date = DateTime::createFromFormat('Y-m-d', '2011-01-22')->setTime(0, 0);
echo $date->format('d M Y g:i:s a');
// 22 Jan 2011 12:00:00 am
</code>```

Title: How can I get today's timestamp in PHP

Body:
I tried

$dtToday = DateTime::createFromFormat('Y-m-d', date('Y-m-d'));

but when I output it

die($dtToday->format('d M Y g:i:s a'));

I still get the time eg "22 Jan 2011 4:53:59 pm". Why is that?

UPDATE

Ah... many people misunderstood me, my bad, I forgot to point out the main point. I created the date with just the date portion, I don't want the time. So I'd expect something like

22 Jan 2011 12:00:00 am

Body:
You can call ->setTime(0, 0) to zero out the time portion:

$date = DateTime::createFromFormat('Y-m-d', '2011-01-22')->setTime(0, 0);
echo $date->format('d M Y g:i:s a');
// 22 Jan 2011 12:00:00 am


问:
Increasing JVM memory in solr cloud node
I am running solr in cloud mode, but since i have large index, my solr servers are getting switched off i need to increase the jvm memory for the solr node, kindly help me how to do it?</p>

答:
The reference guide has a page on JVM settings that are relevant for Solr.

The maximum heap size, set with -Xmx, is more critical. If the memory heap grows to this size, object creation may begin to fail and throw OutOfMemoryException. Setting this limit too low can cause spurious errors in your application, but setting it too high can be detrimental as well.

But .. if your server is disappearing and not giving OOM errors, that sounds like your process is being OOM killed by the underlying operating system. Check syslog (if you're on linux) for messages about the process being terminated.

You can change the settings by defining the SOLR_JAVA_MEM setting:

SOLR_JAVA_MEM="-Xms10g -Xmx10g"


问:
Working with Windows Phone 7, how do I create a global MediaElement?
I need to create a MediaElement that will keep playing when I navigate to different pages within my app. Any ideas on how to do this?</p>

答:
I actually just found a solution. As so often before once you write down a question you get an idea that works yourself :)

```<code>private MediaElement _mediaElement;

...

_mediaElement = new MediaElement {Volume = 1, AutoPlay = false};
var _pop = new Popup {Child = _mediaElement, IsOpen = true};
</code>```

This works - in case anybody else runs into the same problem...

Body:
I actually just found a solution. As so often before once you write down a question you get an idea that works yourself :)

private MediaElement _mediaElement;

...

_mediaElement = new MediaElement {Volume = 1, AutoPlay = false};
var _pop = new Popup {Child = _mediaElement, IsOpen = true};

This works - in case anybody else runs into the same problem...


问:
R: merge two lists of lists of dataframes
I have two lists of lists of dataframes like this:

```<code>L1 <- list(Q1=list(A=data.frame(X1=1:3),C=data.frame(X1=1:3)),
        Q2=list(B=data.frame(X1=1:3),C=data.frame(X1=1:3)))
L2 <- list(Q1=list(B=data.frame(X1=4:6),C=data.frame(X1=4:6)),
        Q2=list(A=data.frame(X1=4:6),C=data.frame(X1=4:6)))
</code>```

The names on the first level "Q1" and "Q2" are identical in both lists.

I want to merge both lists so that dataframes with same names (e.g. "$Q1$C") will be combined like with rbind, and new ones will be added to the list. The desired output should look like this:

```<code>> L3
$Q1
$Q1$A
  X1
1  1
2  2
3  3

$Q1$B
  X1
1  4
2  5
3  6

$Q1$C
  X1
1  1
2  2
3  3
4  4
5  5
6  6

$Q2
$Q2$A
  X1
1  4
2  5
3  6

$Q2$B
  X1
1  1
2  2
3  3

$Q2$C
  X1
1  1
2  2
3  3
4  4
5  5
6  6
</code>```

I tried some combinations using Map() and lapply() but I could not fix it, yet. E.g.:

```<code>L3 <- Map('rbind',lapply(L1,'['),lapply(L2,'['))
</code>```

Any help is appreciated!

答:
Using purrr: </p>

```<code>library(tidyverse)

f <- function(x) {
  map_df(map(x, bind_rows, .id = "id1"), bind_rows, .id = "id2")
}

list(L1, L2) %>%
  map_df(f) %>%
  split(list(.$id1, .$id2)) %>%
  map(select, X1)
</code>```

Body:
I have two lists of lists of dataframes like this:

L1 <- list(Q1=list(A=data.frame(X1=1:3),C=data.frame(X1=1:3)),
        Q2=list(B=data.frame(X1=1:3),C=data.frame(X1=1:3)))
L2 <- list(Q1=list(B=data.frame(X1=4:6),C=data.frame(X1=4:6)),
        Q2=list(A=data.frame(X1=4:6),C=data.frame(X1=4:6)))

The names on the first level "Q1" and "Q2" are identical in both lists.

I want to merge both lists so that dataframes with same names (e.g. "$Q1$C") will be combined like with rbind, and new ones will be added to the list. The desired output should look like this:

> L3
$Q1
$Q1$A
  X1
1  1
2  2
3  3

$Q1$B
  X1
1  4
2  5
3  6

$Q1$C
  X1
1  1
2  2
3  3
4  4
5  5
6  6

$Q2
$Q2$A
  X1
1  4
2  5
3  6

$Q2$B
  X1
1  1
2  2
3  3

$Q2$C
  X1
1  1
2  2
3  3
4  4
5  5
6  6

I tried some combinations using Map() and lapply() but I could not fix it, yet. E.g.:

L3 <- Map('rbind',lapply(L1,'['),lapply(L2,'['))

Any help is appreciated!

Body:
Using purrr:

library(tidyverse)

f <- function(x) {
  map_df(map(x, bind_rows, .id = "id1"), bind_rows, .id = "id2")
}

list(L1, L2) %>%
  map_df(f) %>%
  split(list(.$id1, .$id2)) %>%
  map(select, X1)


问:
Null object reference on API response after killing app. if app logout properly response will work
If app killed manually and try to sent update i am getting nullPointerException in API response. If I logout properly its working fine. I logged the input values everything is fine. anyone please look through this code

This is my API update.

```<code>private void updateFb(final String shop, final String phone,final String user_ids,final String lat, String lon,final String feedb) {

    Log.i("TAG", shop+","+phone+","+user_ids+","+lat+","+lon+","+feedb);
    new RetrofitHelper(MainActivity.this)
        .getApIs()
        .feedback(shop,phone,user_ids,lat,lon,feedb)
        .enqueue(new Callback<JsonElement>()
         {
                @Override
                public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
                    try {
                        JSONObject jsonObject=new JSONObject(response.body().toString());
                        String status=jsonObject.getString("status");
                        String date_time=jsonObject.getString("dt_time");
                        if (status=="Failed"){
                            Toasty.error(MainActivity.this, "Updating Failed", Toast.LENGTH_SHORT).show();
                        }
                        else {
                            shopName.setText("");
                            feedback.setText("");
                            phoneEdt.setText("");
                            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                            Toasty.success(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailure(Call<JsonElement> call, Throwable t) {

                }
            });

  // API interface
@FormUrlEncoded
    @POST("/web-api/insert_shop.php?")

    Call<JsonElement>feedback(@Field("shop_name") String shopName,@Field("phone")String phone, @Field("user_id") String user_id,
                              @Field("pos_lat") String pos_lat, @Field("pos_long") String pos_lon, @Field("feedback") String feedback);
</code>```

Response i got .

java.lang.NullPointerException: Attempt to invoke interface method 'retrofit2.Call com.example.user.comcubeassist.retrofit.APIs.feedback(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference

答:
Value of new RetrofitHelper(MainActivity.this).getApIs() is null, so when are you trying to access feedback method , it's throwing null reference. Verify getApIs() method and check why it is returning null.

Edit
I guess you are initializing your Refrofit client on login page, hence if you kill and reopen app , it’s returning null . Try to initialise the client on home screen

Body:
If app killed manually and try to sent update i am getting nullPointerException in API response. If I logout properly its working fine. I logged the input values everything is fine. anyone please look through this code

This is my API update.

private void updateFb(final String shop, final String phone,final String user_ids,final String lat, String lon,final String feedb) {

    Log.i("TAG", shop+","+phone+","+user_ids+","+lat+","+lon+","+feedb);
    new RetrofitHelper(MainActivity.this)
        .getApIs()
        .feedback(shop,phone,user_ids,lat,lon,feedb)
        .enqueue(new Callback<JsonElement>()
         {
                @Override
                public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
                    try {
                        JSONObject jsonObject=new JSONObject(response.body().toString());
                        String status=jsonObject.getString("status");
                        String date_time=jsonObject.getString("dt_time");
                        if (status=="Failed"){
                            Toasty.error(MainActivity.this, "Updating Failed", Toast.LENGTH_SHORT).show();
                        }
                        else {
                            shopName.setText("");
                            feedback.setText("");
                            phoneEdt.setText("");
                            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                            Toasty.success(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailure(Call<JsonElement> call, Throwable t) {

                }
            });

  // API interface
@FormUrlEncoded
    @POST("/web-api/insert_shop.php?")

    Call<JsonElement>feedback(@Field("shop_name") String shopName,@Field("phone")String phone, @Field("user_id") String user_id,
                              @Field("pos_lat") String pos_lat, @Field("pos_long") String pos_lon, @Field("feedback") String feedback);

Response i got .

java.lang.NullPointerException: Attempt to invoke interface method 'retrofit2.Call com.example.user.comcubeassist.retrofit.APIs.feedback(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference


问:
Wordpress customizer works perfectly in the customizer interface but doesnt in the actual design
I recently RESET customizer setting with wp customizer plugin, did this on purpose to know certain error theme users would get on a fresh install of the theme, and I found out that on the customizer interface everything works well but when I actually load my design, I get a total different result.

Here is what it looks like

Blog result after customizer resets

Here is the code i am using to change in settings from the customizer.php option ( dont think there is anything wrong with my settings pattern)

```<code>  $wp_customize->add_setting(
      'sq_hide_blog_info',
      array(
          'default'         => true,
      )
  );

     $wp_customize->add_control(
        new Toggle_Checkbox_Custom_control(
            $wp_customize,
            'sq_hide_blog_ctr',
            array(
                'description'    =>    __( 'Display Site name / Description' ),
                'label'    =>    __( 'Check here' ),
                'section'  => 'custom_footer_text',
                'settings' => 'sq_hide_blog_info',
                'type'     => 'checkbox',
                'section'  => 'sq_nav_design'
            )
        )
   );
</code>```

here is what i am using to change options in the actual code.

example

```<code> <?php if(get_theme_mod('nav_type_select') == 1): ?>
                <?php include get_template_directory() . '/template-parts/header/header-1.php'?>
                <?php else: ?>
               <?php include get_template_directory() . '/template-parts/header/header-2.php'?>
              <?php endif; ?>
</code>```

The above settings is a check box, and default output set to 1, and I meant that, if nav 1 is selected then output it else, output nav 2 as default, if nav 1, is not selected then output nav 2, things was working fine until i reset the customizer default, which i guess would pull same error when i get a fresh install.

i know the settings in the code doesn't tally with the one in the customizer.php just using this for reference purpose.

i am solely depending on the customizer default to output value in the theme, with no fallback .

my instinct is telling me that the issue is from the way i placed my if statement , cause i used that pattern through out my code.

Thanks in advance, i would truly appreciate your help.

To be clear: i need help in , checking if my if else pattern is correct, if yes, then any work around to make the customizer actually update the new settings in the default page.

答:
i was able to fix this

this worked for me, even if all settings was refreshed

if (  get_theme_mod('my_banner_setting', 1) == 1 ) {

```<code>// proceed
</code>```

}

Body:
I recently RESET customizer setting with wp customizer plugin, did this on purpose to know certain error theme users would get on a fresh install of the theme, and I found out that on the customizer interface everything works well but when I actually load my design, I get a total different result.

Here is what it looks like

Blog result after customizer resets

Here is the code i am using to change in settings from the customizer.php option ( dont think there is anything wrong with my settings pattern)

  $wp_customize->add_setting(
      'sq_hide_blog_info',
      array(
          'default'         => true,
      )
  );

     $wp_customize->add_control(
        new Toggle_Checkbox_Custom_control(
            $wp_customize,
            'sq_hide_blog_ctr',
            array(
                'description'    =>    __( 'Display Site name / Description' ),
                'label'    =>    __( 'Check here' ),
                'section'  => 'custom_footer_text',
                'settings' => 'sq_hide_blog_info',
                'type'     => 'checkbox',
                'section'  => 'sq_nav_design'
            )
        )
   );

here is what i am using to change options in the actual code.

example

 <?php if(get_theme_mod('nav_type_select') == 1): ?>
                <?php include get_template_directory() . '/template-parts/header/header-1.php'?>
                <?php else: ?>
               <?php include get_template_directory() . '/template-parts/header/header-2.php'?>
              <?php endif; ?>

The above settings is a check box, and default output set to 1, and I meant that, if nav 1 is selected then output it else, output nav 2 as default, if nav 1, is not selected then output nav 2, things was working fine until i reset the customizer default, which i guess would pull same error when i get a fresh install.

i know the settings in the code doesn't tally with the one in the customizer.php just using this for reference purpose.

i am solely depending on the customizer default to output value in the theme, with no fallback .

my instinct is telling me that the issue is from the way i placed my if statement , cause i used that pattern through out my code.

Thanks in advance, i would truly appreciate your help.

To be clear: i need help in , checking if my if else pattern is correct, if yes, then any work around to make the customizer actually update the new settings in the default page.

Body:
i was able to fix this

this worked for me, even if all settings was refreshed

if (  get_theme_mod('my_banner_setting', 1) == 1 ) {

// proceed

}


问:
Vue - Which is better? Extend a component or nested component?
I have a drop-down.vue component like this:

```<code><template>
    <div @mouseenter="handleEnter" @mouseleave="handleLeave" @click="handleClick" v-click-outside="hide">
        <slot name="dropdownBtn"  :visible="visible" ></slot>
        <slot v-if="visible" name="dropdownWrap"  :visible="visible"></slot>
    </div>
</template>
...
</code>```

it's a drop down component, then click or hover the dropdownBtn the dropdownWrap will apear/disapear.

now i have another component need the dropdown, so i can use the dropdown in two way:

first： use nested component

```<code>    <template>
        <ui-dropdown>
            <div name="dropdownBtn">...</div>
            <div name="dropdownWrap">...</div>
        </ui-dropdown>
    </template>
...
</code>```

second: use extend

```<code><template>
<!-- the handleEnter and handleLeave are extend from the dropdown component -->

<div>
    <div class="btn" @mouseenter="handleEnter" @mouseleave="handleLeave">...</div>
    <div class="popup" @mouseenter="handleEnter" @mouseleave="handleLeave">...</div>
</div>
<template>

<script>
import dropdown from '../dropdown';
export default {
    extend: dropdown,
    ...
}
</script>
</code>```

i think the first is better. but the second has one less component than the first, the performance will be better?

who can tell me which is better?

答:
Both ways work, and I can't really say that one way is correct and the other isn't, it depends on your requirements.

Extend

Extending a base component can get hairy if you want to modify the base component's template in some way (you can't really modify part of the base component's template, you either keep the base template or completely redefine it).

You need to make sure that the new template adheres to any requirements that the base component needs for it to work correctly (such as the presence of certain refs, using correct CSS class names, etc.

The base and extended components are tightly coupled.

Composition

I'd say this is more the "Vue way".

You can take advantage of slots.

There's no tight coupling between the child and parent components; they're completely separate. You can modify the child component's code as much as you like as long as its interface (props, events, slots, etc) are unchanged.

A disadvantage could be that the parent component is a completely separate component from the child; it won't inherit any props, events, slots (anything) from the child component.

You might want to have a look at functional components if you're concerned about the overhead of having an extra component with the composition approach.

I rarely extend components, but when I do, it's because I want to share a common blueprint for a set of related components (the base component isn't usually functional on its own, I've just extracted the common code out).

Body:
I have a drop-down.vue component like this:

<template>

        <slot name="dropdownBtn"  :visible="visible" ></slot>
        <slot v-if="visible" name="dropdownWrap"  :visible="visible"></slot>

</template>
...

it's a drop down component, then click or hover the dropdownBtn the dropdownWrap will apear/disapear.

now i have another component need the dropdown, so i can use the dropdown in two way:

first： use nested component

    <template>
        <ui-dropdown>

...

...

        </ui-dropdown>
    </template>
...

second: use extend

<template>

...

...

<template>

i think the first is better. but the second has one less component than the first, the performance will be better?

who can tell me which is better?


答:
This looks like a use case for cron, a simple utility found on all linux machines to schedule periodic tasks. A simple cron task could be created like:

```<code>$ crontab -e
</code>```

Within the cron, make an entry

```<code>0 */2 * * *  /home/username/ticket_script.py
</code>```

Make sure that your script has executable permissions. In case you are printing something in your script, make the cron entry to redirect its ouput like

```<code>0 */2 * * *  /home/username/ticket_script.py >> /home/username/ticket_script_runs.log
</code>```

For gotchas on running this in Docker, you can go through this thread ->  https://forums.docker.com/t/cronjobs-in-docker-container/2618/5 which says:

Most Docker containers only run the binary you specify (in this case /bin/bash), so there is no cron daemon running to trigger these jobs.

There are a number of ways you can deal with this - for small adhoc things, you can add the cron entry to your host's crontab, and trigger the job in the container using docker exec containername ...

You can replace the container entrypoint with a shell script that starts the cron, or if you have a need for several services, use something like supervisord to manage them.

And if you're going all in, you can make a cron container which you can then use to kick off tasks using docker exec.

The other approach is what you already have - go to sleep for 2 hours, or maintain a time_last_read timestamp, keep evaluating if its been 2 hours since your last read (time_now - time_last_read >= 2_HOURS), and re-read the value into memory once the condition is True and reset time_last_read.

Title: How to schedule a periodic task in Python?

Body:
This looks like a use case for cron, a simple utility found on all linux machines to schedule periodic tasks. A simple cron task could be created like:

$ crontab -e

Within the cron, make an entry

0 */2 * * *  /home/username/ticket_script.py

Make sure that your script has executable permissions. In case you are printing something in your script, make the cron entry to redirect its ouput like

0 */2 * * *  /home/username/ticket_script.py >> /home/username/ticket_script_runs.log

For gotchas on running this in Docker, you can go through this thread ->  https://forums.docker.com/t/cronjobs-in-docker-container/2618/5 which says:

Most Docker containers only run the binary you specify (in this case /bin/bash), so there is no cron daemon running to trigger these jobs.

There are a number of ways you can deal with this - for small adhoc things, you can add the cron entry to your host's crontab, and trigger the job in the container using docker exec containername ...

You can replace the container entrypoint with a shell script that starts the cron, or if you have a need for several services, use something like supervisord to manage them.

And if you're going all in, you can make a cron container which you can then use to kick off tasks using docker exec.

The other approach is what you already have - go to sleep for 2 hours, or maintain a time_last_read timestamp, keep evaluating if its been 2 hours since your last read (time_now - time_last_read >= 2_HOURS), and re-read the value into memory once the condition is True and reset time_last_read.


问:
captcha with sum of two numbers
how can I write captcha with sum of two numbers ?example:1+4
(please answer to this question completely,I don't know any thing about captcha!)</p>

答:
The purpose of a captcha is to tell apart real, live humans from automated software.

So captchas ask people to do stuff people are good at, but machines are not. Once machines get capable of something, captachas have to change and do something else. Simple text isn't working anymore, since OCR got good enough to automatically read it - hence, the distorted text you see often nowadays. Will probably be replaced by something else in the near future, like "what type of thing is shown in this picture" or such.

The easier the task for a computer, the less suited it is for a Captcha.

Adding two numbers is not a good idea for a captcha; in fact, its effectiveness is probably below zero.

Please check again what you want to do and why. If you want to write your own captcha instead of using something that's already there, put some thought in it first before implementation.

Maybe using ReCAPTCHA or something similar is the better way to go about it?

Title: captcha with sum of two numbers


问:
redirect user from one layout to another in same function - java thymeleaf spring
Hello all I am working on java using thymeleaf.

this is my method to load dashbaord page:

```<code>@Layout("layouts/default.html")
@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView Dashboard() {
    ModelAndView mav = null;
    if (session.getAttribute("loginStatus") != "1") {
        mav = new ModelAndView("index.html");
    } else {
        mav = new ModelAndView("dashbaord.html");
    }
    return mav;
}
</code>```

In above method if user is logged in it will load dashbaord.html page which is designed to render layouts/default.html BUT if user is not logged in and tries to load dashboard page, it should go to index.html

BUT in my case index page doesn't contain any layout and when user tries to load dashboard page without login it gives me rendering error for layouts/default.html because index page is not designed to render anything from layouts. it is a separate page with no layout.

I have followed this configuration for my layouts rendering.

Index Page RequestHandler:

```<code>@Layout(Layout.NONE)
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index() {
    ModelAndView mav = null;
    mav = new ModelAndView("index.html");
    return mav;
}
</code>```

Any idea, how can I set the layout conditionally ?

答:
try this:</p>

```<code>@Layout("layouts/default.html")
@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public String Dashboard() {
    ModelAndView mav = null;
    if (session.getAttribute("loginStatus") != "1") {
        return "redirect:/";
    } else {
        return "dashbaord.html";
    }

}
</code>```

Body:
Hello all I am working on java using thymeleaf.

this is my method to load dashbaord page:

@Layout("layouts/default.html")
@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView Dashboard() {
    ModelAndView mav = null;
    if (session.getAttribute("loginStatus") != "1") {
        mav = new ModelAndView("index.html");
    } else {
        mav = new ModelAndView("dashbaord.html");
    }
    return mav;
}

In above method if user is logged in it will load dashbaord.html page which is designed to render layouts/default.html BUT if user is not logged in and tries to load dashboard page, it should go to index.html

BUT in my case index page doesn't contain any layout and when user tries to load dashboard page without login it gives me rendering error for layouts/default.html because index page is not designed to render anything from layouts. it is a separate page with no layout.

I have followed this configuration for my layouts rendering.

Index Page RequestHandler:

@Layout(Layout.NONE)
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index() {
    ModelAndView mav = null;
    mav = new ModelAndView("index.html");
    return mav;
}

Any idea, how can I set the layout conditionally ?

Body:
try this:

@Layout("layouts/default.html")
@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public String Dashboard() {
    ModelAndView mav = null;
    if (session.getAttribute("loginStatus") != "1") {
        return "redirect:/";
    } else {
        return "dashbaord.html";
    }

}


问:
How to update customer data faster and more efficiently

I am writing a script to add values to a custom attribute for 10 thousand customers. I have two questions here.

when we update custom attribute values for product, we can use:

```<code>$resource = $product->getResource();
$product->setData($attribute, $value);
$resource->saveAttribute($product,$attribute);
</code>```

which is very fast. But as for customer, it does not have getResource() method. The only way I know is: $this->_customerRepository->save($customer); which is very very slow. so how can I update the customers values faster?

when I update these values in bulk, I wrote the script as followings, it was running fine at the first hundreds of customers data updating, but then throws exception:

```<code>(/chroot/home/.../html/vendor/magento/framework/Exception/FileSystemException.php): failed to open stream: Too many open files in /chroot/home/.../html/vendor/composer/ClassLoader.php on line 444
</code>```

I Googled this problem and someone says it is relevant to the settings of sever. However, since we rent the server and have no authorization to change it, how should I modify my code and make it use less resources?

```<code>protected function updateAttributes($customersListData,$output) {
  $time_start = microtime(true);
  $totalLength = sizeof($customersListData);
  foreach ($customersListData as $customerIndex => $singleCustomerData) {
    try {
      $id = $singleCustomerData['id'];
      $customer = $this->_customerRepository->getById($id);

      $arrayKeys = array_keys($singleCustomerData);
      array_shift($arrayKeys);
      foreach ($arrayKeys as $singleKey) {
        if (empty($singleCustomerData[$singleKey])) {
          $singleCustomerData[$singleKey] = "";
        }
        $time_now = microtime(true);
        $time_used = $time_now - $time_start;
        $finished_records = (int)$customerIndex + 1;
        $output->writeln("Updating attribute: ".$singleCustomerData[$singleKey].". " .$finished_records ."/".$totalLength." done. will finsih in: ". round($time_used / $finished_records * ($totalLength - $finished_records), 0). "s.");
        $customer->setData($singleKey, $singleCustomerData[$singleKey]);
      }
      $this->_customerRepository->save($customer);
      unset($customer);
    } catch (\Exception $e) {
      $output->writeln($e->getMessage());
      continue;
    }
  }
}
</code>```

答:
Use bellow  class in constructors

```<code>\Magento\Framework\App\Action\Context $context,
    \Magento\Framework\View\Result\PageFactory $resultPageFactory,
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface

public function execute()
  {
     $customerId = 2;
     if ($customerId) {

            $customer = $this->_customerRepositoryInterface->getById($customerId);
            $customer->setCustomAttribute('reward_barcode', $barcode);
            $this->_customerRepositoryInterface->save($customer);

   }
   $this->messageManager->addSuccess( __('Your membership successfully updated.') );
}
</code>```

Alternative  Faster  Option

You should use php programmatically out side magento and make database connection with that. Fetch data and update magento attributes. this will be  faster and easy to update attributes.

Body:
I am writing a script to add values to a custom attribute for 10 thousand customers. I have two questions here.

when we update custom attribute values for product, we can use:

$resource = $product->getResource();
$product->setData($attribute, $value);
$resource->saveAttribute($product,$attribute);

which is very fast. But as for customer, it does not have getResource() method. The only way I know is: $this->_customerRepository->save($customer); which is very very slow. so how can I update the customers values faster?

when I update these values in bulk, I wrote the script as followings, it was running fine at the first hundreds of customers data updating, but then throws exception:

(/chroot/home/.../html/vendor/magento/framework/Exception/FileSystemException.php): failed to open stream: Too many open files in /chroot/home/.../html/vendor/composer/ClassLoader.php on line 444

I Googled this problem and someone says it is relevant to the settings of sever. However, since we rent the server and have no authorization to change it, how should I modify my code and make it use less resources?

protected function updateAttributes($customersListData,$output) {
  $time_start = microtime(true);
  $totalLength = sizeof($customersListData);
  foreach ($customersListData as $customerIndex => $singleCustomerData) {
    try {
      $id = $singleCustomerData['id'];
      $customer = $this->_customerRepository->getById($id);

      $arrayKeys = array_keys($singleCustomerData);
      array_shift($arrayKeys);
      foreach ($arrayKeys as $singleKey) {
        if (empty($singleCustomerData[$singleKey])) {
          $singleCustomerData[$singleKey] = "";
        }
        $time_now = microtime(true);
        $time_used = $time_now - $time_start;
        $finished_records = (int)$customerIndex + 1;
        $output->writeln("Updating attribute: ".$singleCustomerData[$singleKey].". " .$finished_records ."/".$totalLength." done. will finsih in: ". round($time_used / $finished_records * ($totalLength - $finished_records), 0). "s.");
        $customer->setData($singleKey, $singleCustomerData[$singleKey]);
      }
      $this->_customerRepository->save($customer);
      unset($customer);
    } catch (\Exception $e) {
      $output->writeln($e->getMessage());
      continue;
    }
  }
}

Body:
Use bellow  class in constructors

\Magento\Framework\App\Action\Context $context,
    \Magento\Framework\View\Result\PageFactory $resultPageFactory,
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface

public function execute()
  {
     $customerId = 2;
     if ($customerId) {

            $customer = $this->_customerRepositoryInterface->getById($customerId);
            $customer->setCustomAttribute('reward_barcode', $barcode);
            $this->_customerRepositoryInterface->save($customer);

   }
   $this->messageManager->addSuccess( __('Your membership successfully updated.') );
}

Alternative  Faster  Option

You should use php programmatically out side magento and make database connection with that. Fetch data and update magento attributes. this will be  faster and easy to update attributes.


问:
Excel - Check if a date range overlaps only if a cell is a duplicate
We are using a spreadsheet to act as a booking sheet for some iPads at work.

I'd like to be able to easily check whether an iPad has been booked out on a date range. I can do this if the start date is the same by using this formula:

```<code>=IF(COUNTIFS($C$4:$C$1000,C4,$E$4:$E$1000,E4)>1,"Double Booked","")
</code>```

Column C is the ID of the iPads

Column E is the "Start Date"

However I'd like to extend this to check for any date between the start and end date.

Here is an image of how the spreadsheet is laid out, with the non relevant stuff redacted; is there a way to do this?

Screenshot of my spreadsheet with non relevant information redacted

答:
Assuming that column E (Start Date) is always less than or equal to column F (End Date), this will work. There may be a simpler way of doing this though.</p>

```<code>=IF(OR(COUNTIFS($C$4:$C$1000,C4,$E$4:$E$1000,"<="&E4,$F$4:$F$1000,">="&E4)>1,COUNTIFS($C$4:$C$1000,C4,$E$4:$E$1000,"<="&F4,$F$4:$F$1000,">="&F4)>1),"Double Booked","")
</code>```

Body:
We are using a spreadsheet to act as a booking sheet for some iPads at work.

I'd like to be able to easily check whether an iPad has been booked out on a date range. I can do this if the start date is the same by using this formula:

=IF(COUNTIFS($C$4:$C$1000,C4,$E$4:$E$1000,E4)>1,"Double Booked","")

Column C is the ID of the iPads

Column E is the "Start Date"

However I'd like to extend this to check for any date between the start and end date.

Here is an image of how the spreadsheet is laid out, with the non relevant stuff redacted; is there a way to do this?

Screenshot of my spreadsheet with non relevant information redacted

Body:
Assuming that column E (Start Date) is always less than or equal to column F (End Date), this will work. There may be a simpler way of doing this though.

=IF(OR(COUNTIFS($C$4:$C$1000,C4,$E$4:$E$1000,"<="&E4,$F$4:$F$1000,">="&E4)>1,COUNTIFS($C$4:$C$1000,C4,$E$4:$E$1000,"<="&F4,$F$4:$F$1000,">="&F4)>1),"Double Booked","")


问:
How to get this div text or this DOM's value?
I want to get text in
 or value of DOM property, the value is 保卫科,
but I alway get undefined or JS error.

I am new to JS. I am trying some ways to get the text of a div, but I have failed. I need help.

This HTML snippet is an org chart, and I now iterate through it to get the structure it represents and concatenate the resulting values into a json object, but I am unfamiliar with the JS DOM operation, which bothers me all day

function loop($chart) {
        // var that = this;
        //$chart是一个DOM
        var $tr = $chart.find('tr:first');
        //找到根结点 获取id id为1 拼接json
        // console.log($tr);
        console.log($tr.find('.node:first').innerText);
        var subObj = { 'id': $tr.find('.node')[0].id ,'name':$tr.find('.node')[0].value};
        //找到tr中的最后一个 记录子节点的tr 然后遍历
        $tr.siblings(':last').children().each(
          function () {
            //如果subObj没有子节点 则创建一个数组装子节点
            if (!subObj.subordinate) {
               subObj.subordinate = [];
              }
              //往数组中push东西
            subObj.subordinate.push(loop($(this)));
          });
        return subObj;
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="orgchart" class="orgchart view-state">
  <table>
    <tr>
      <td colspan="4">
        <div id="1512554614742741" value="保卫处" class="node">
          <div class="title">
            <i class="fa fa-th-large symbol"></i>保卫处</div>
          <i class="edge verticalEdge bottomEdge fa"></i>
        </div>
      </td>
    </tr>
    <tr class="lines">
      <td colspan="4">
        <div class="downLine"></div>
      </td>
    </tr>
    <tr class="lines">
      <td class="rightLine"> </td>
      <td class="leftLine topLine"> </td>
      <td class="rightLine topLine"> </td>
      <td class="leftLine"> </td>
    </tr>
    <tr class="nodes">
      <td colspan="2">
        <table>
          <tr>
            <td colspan="2">
              <div id="1512554614755264" data-parent="1" value="2部门" class="node">
                <div class="title">
                  <i class="fa fa-th-large symbol"></i>2部门</div>
                <i class="edge verticalEdge topEdge fa"></i>
                <i class="edge horizontalEdge rightEdge fa"></i>
                <i class="edge horizontalEdge leftEdge fa"></i>
                <i class="edge verticalEdge bottomEdge fa"></i>
              </div>
            </td>
          </tr>
          <tr class="lines">
            <td colspan="2">
              <div class="downLine"></div>
            </td>
          </tr>
          <tr class="lines">
            <td class="rightLine"> </td>
            <td class="leftLine"> </td>
          </tr>
          <tr class="nodes">
            <td colspan="2">
              <table>
                <tr>
                  <td>
                    <div id="1512554614762739" data-parent="2" value="6部门" class="node">
                      <div class="title">6部门</div>
                      <i class="edge verticalEdge topEdge fa"></i>
                    </div>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
        </table>
      </td>
      <td colspan="2">
        <table>
          <tr>
            <td>
              <div id="1512554614773842" data-parent="1" value="4部门" class="node">
                <div class="title">4部门</div>
                <i class="edge verticalEdge topEdge fa"></i>
                <i class="edge horizontalEdge rightEdge fa"></i>
                <i class="edge horizontalEdge leftEdge fa"></i>
              </div>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</div></code>```

答:
i tried it it works : </p>

```<code>function myFunction() {
   var x = document.getElementById("1512554614742741").getAttributeNode("value").value;
    //here you have 保卫科  in x variable but it doesn't show anywhere on the page
    //you choose what you want to do  with it for example show it in the html page
}
</code>```

Body:
I want to get text in
 or value of DOM property, the value is 保卫科,
but I alway get undefined or JS error.

I am new to JS. I am trying some ways to get the text of a div, but I have failed. I need help.

This HTML snippet is an org chart, and I now iterate through it to get the structure it represents and concatenate the resulting values into a json object, but I am unfamiliar with the JS DOM operation, which bothers me all day

function loop($chart) {
        // var that = this;
        //$chart是一个DOM
        var $tr = $chart.find('tr:first');
        //找到根结点 获取id id为1 拼接json
        // console.log($tr);
        console.log($tr.find('.node:first').innerText);
        var subObj = { 'id': $tr.find('.node')[0].id ,'name':$tr.find('.node')[0].value};
        //找到tr中的最后一个 记录子节点的tr 然后遍历
        $tr.siblings(':last').children().each(
          function () {
            //如果subObj没有子节点 则创建一个数组装子节点
            if (!subObj.subordinate) {
               subObj.subordinate = [];
              }
              //往数组中push东西
            subObj.subordinate.push(loop($(this)));
          });
        return subObj;
      }

            保卫处

                  2部门

6部门

4部门

Body:
i tried it it works :

function myFunction() {
   var x = document.getElementById("1512554614742741").getAttributeNode("value").value;
    //here you have 保卫科  in x variable but it doesn't show anywhere on the page
    //you choose what you want to do  with it for example show it in the html page
}


问:
UIAlertcontroller in TextfieldShouldBeginediting objective-c
I want to show alert before text enter in textfield after ok button click textfield will be editable but I am showing alert but textfield did not editable.

```<code>if(textField == contractValueField)
{
    [self showAlertWithTitle:@"Information" textfield:contractValueField];
    return YES;
}
</code>```

I search so many sites but I did not get right answer by using UIAlertView it is working but I want to use UIAlertController. I have more than 20 textfields in my project & every textfield I will show alert before edit begin.

```<code>- (void)showAlertWithTitle:(NSString *)title textfield:(UITextField*)textfield
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:@"Please enter Amount in Lakhs" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
    {
        [alert dismissViewControllerAnimated:YES completion:nil];
        [textfield becomeFirstResponder];
    }];

    [alert addAction:ok];
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}
</code>```

答:
Declare a UITextField which will reference the last selected textField:

```<code>@interface ViewController (){
    UITextField *lastSelectedTextField;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    // check to see if the textField is the last shown textField
    if (textField == lastSelectedTextField) {
        return true;
    }
    [self showAlertWithTitle:@"Information" textfield:textField];
    return false;
 }

- (void)showAlertWithTitle:(NSString *)title textfield:(UITextField*)textfield{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:@"Please enter Amount in Lakhs" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
        lastSelectedTextField = textfield;;
        [alert dismissViewControllerAnimated:YES completion:nil];
        [textfield becomeFirstResponder];
    }];

    [alert addAction:ok];
    [self presentViewController:alert animated:true completion:nil];
}
</code>```

This would be the better option, I didn't realise that you wanted to show the alert every even if the textField had been selected previously

Body:
I want to show alert before text enter in textfield after ok button click textfield will be editable but I am showing alert but textfield did not editable.

if(textField == contractValueField)
{
    [self showAlertWithTitle:@"Information" textfield:contractValueField];
    return YES;
}

I search so many sites but I did not get right answer by using UIAlertView it is working but I want to use UIAlertController. I have more than 20 textfields in my project & every textfield I will show alert before edit begin.

- (void)showAlertWithTitle:(NSString *)title textfield:(UITextField*)textfield
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:@"Please enter Amount in Lakhs" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
    {
        [alert dismissViewControllerAnimated:YES completion:nil];
        [textfield becomeFirstResponder];
    }];

    [alert addAction:ok];
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}

Body:
Declare a UITextField which will reference the last selected textField:

@interface ViewController (){
    UITextField *lastSelectedTextField;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    // check to see if the textField is the last shown textField
    if (textField == lastSelectedTextField) {
        return true;
    }
    [self showAlertWithTitle:@"Information" textfield:textField];
    return false;
 }

- (void)showAlertWithTitle:(NSString *)title textfield:(UITextField*)textfield{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:@"Please enter Amount in Lakhs" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
        lastSelectedTextField = textfield;;
        [alert dismissViewControllerAnimated:YES completion:nil];
        [textfield becomeFirstResponder];
    }];

    [alert addAction:ok];
    [self presentViewController:alert animated:true completion:nil];
}

This would be the better option, I didn't realise that you wanted to show the alert every even if the textField had been selected previously


问:
Oracle 11g - Temp Tablespace Segments don't get released (Oracle Bug?)
I am using Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production and i have a problem with the following query which i am executing in TOAD 12.6.0.53 (not a typical query, but it is only for demonstration):

```<code>with rownums
as (select distinct
    rownum rn
      from dual
   connect by level <=1000000
)
select rn from rownums
 union all
select rn from rownums;

--Edit: this Statement ist NOT showing the behaviour:
begin
    for cRow in (with rownums
                as (select distinct
                    rownum rn
                      from dual
                   connect by level <=1000000
                )
                select rn from rownums
                 union all
                select rn from rownums)
    loop
        return;
    end loop;
end;
</code>```

After executing this query, i can check the usage of the temp tablespace with this query:

```<code>SELECT S.sid, S.serial#, SUM (T.blocks) * TBS.block_size / 1024 / 1024 used_mb, T.tablespace
  FROM v$sort_usage T, v$session S, dba_tablespaces TBS
 WHERE T.session_addr = S.saddr
   AND T.tablespace = TBS.tablespace_name
   and s.sid = sys_context('userenv','sid')
 GROUP BY S.sid, S.serial#, TBS.block_size, T.tablespace;
</code>```

The result is, that every execution of the testquery from above needs about 12MB of Temp Tablespace which is not getting released until i disconnect the session.
If i do this to often, it leads too an ORA-1652: unable to extend temp segment.

What am i doing wrong? Or could this be an oracle bug?

答:
TEMP Tablespace has some limited Disk space. When you run query it began to use TEMP space more and more and untill it reaches its limit and gives an error can't extend TEMP , So possible are two solutions

Increase TEMP space better Using EM

Optimize Query that uses less    TEMP

Body:
I am using Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production and i have a problem with the following query which i am executing in TOAD 12.6.0.53 (not a typical query, but it is only for demonstration):

with rownums
as (select distinct
    rownum rn
      from dual
   connect by level <=1000000
)
select rn from rownums
 union all
select rn from rownums;

--Edit: this Statement ist NOT showing the behaviour:
begin
    for cRow in (with rownums
                as (select distinct
                    rownum rn
                      from dual
                   connect by level <=1000000
                )
                select rn from rownums
                 union all
                select rn from rownums)
    loop
        return;
    end loop;
end;

After executing this query, i can check the usage of the temp tablespace with this query:

SELECT S.sid, S.serial#, SUM (T.blocks) * TBS.block_size / 1024 / 1024 used_mb, T.tablespace
  FROM v$sort_usage T, v$session S, dba_tablespaces TBS
 WHERE T.session_addr = S.saddr
   AND T.tablespace = TBS.tablespace_name
   and s.sid = sys_context('userenv','sid')
 GROUP BY S.sid, S.serial#, TBS.block_size, T.tablespace;

The result is, that every execution of the testquery from above needs about 12MB of Temp Tablespace which is not getting released until i disconnect the session.
If i do this to often, it leads too an ORA-1652: unable to extend temp segment.

What am i doing wrong? Or could this be an oracle bug?


问:
How to sort a NSArray which contains NSDictionary?
I have a plist like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
 <key>highscores</key>
 <array>
  <dict>
   <key>highscoreInSeconds</key>
   <string>9</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
  <dict>
   <key>highscoreInSeconds</key>
   <string>12</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
 </array>
</dict>
</plist>
</code>```

Now I want to sort this by the highscoreInSeconds.

```<code>   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *plistDirectory = [paths objectAtIndex:0];
 NSString* fullPath = [plistDirectory stringByAppendingPathComponent:@"data.plist"];

 NSMutableDictionary* pData = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];
 NSMutableArray* highscores = [pData valueForKey:@"highscores"];
</code>```

How can I sort this now?

Thank you very much!
:)

Have a nice day.

PS: It should look like this at the end:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
 <key>highscores</key>
 <array>
  <dict>
   <key>highscoreInSeconds</key>
   <string>12</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
  <dict>
   <key>highscoreInSeconds</key>
   <string>9</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
 </array>
</dict>
</plist>
</code>```

You don't need to say me how to write a plist i knew that.

答:
```<code> NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *plistDirectory = [paths objectAtIndex:0];
 NSString* fullPath = [plistDirectory stringByAppendingPathComponent:@"data.plist"];

 NSMutableDictionary* pData = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];
 NSMutableArray* highscores = [pData valueForKey:@"highscores"];
</code>```

Now use...
You can user NSSortDescriptor for this & very easy to use.
just provide the key by which you want to sort the array..

```<code>NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"highscores" ascending:YES];
[highscores sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
[descriptor release];
</code>```

Hope will for you,

Body:
I have a plist like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
 <key>highscores</key>
 <array>
  <dict>
   <key>highscoreInSeconds</key>
   <string>9</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
  <dict>
   <key>highscoreInSeconds</key>
   <string>12</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
 </array>
</dict>
</plist>

Now I want to sort this by the highscoreInSeconds.

   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *plistDirectory = [paths objectAtIndex:0];
 NSString* fullPath = [plistDirectory stringByAppendingPathComponent:@"data.plist"];

 NSMutableDictionary* pData = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];
 NSMutableArray* highscores = [pData valueForKey:@"highscores"];

How can I sort this now?

Thank you very much!
:)

Have a nice day.

PS: It should look like this at the end:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
 <key>highscores</key>
 <array>
  <dict>
   <key>highscoreInSeconds</key>
   <string>12</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
  <dict>
   <key>highscoreInSeconds</key>
   <string>9</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
 </array>
</dict>
</plist>

You don't need to say me how to write a plist i knew that.

Body:
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *plistDirectory = [paths objectAtIndex:0];
 NSString* fullPath = [plistDirectory stringByAppendingPathComponent:@"data.plist"];

 NSMutableDictionary* pData = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];
 NSMutableArray* highscores = [pData valueForKey:@"highscores"];

Now use...
You can user NSSortDescriptor for this & very easy to use.
just provide the key by which you want to sort the array..

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"highscores" ascending:YES];
[highscores sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
[descriptor release];

Hope will for you,