问:
ImportError Python: Cannot Import Name Viewkeys
So I created this web scraper in python and I'm building it in Pycharm with Anaconda. My script was working, but somehow I think I messed something up in my computer and now I'm getting this error.

ImportError: cannot import name viewkeys

Also I can't seem to be able to install the module "mechanize" onto the anaconda directory.

Below is my code. If anyone can help resolve this that'd be great!

```<code>from bs4 import BeautifulSoup
import urllib
import numpy as np
#import selenium.webdriver as webdriver
import urllib
import requests
import mechanize
import urlparse
import lxml
import sys
import re

def get_Sample_URL(Sample_Name):
    br = mechanize.Browser()
    br.open("https://www.lpi.usra.edu/meteor/")

    "SELECTING THE FORM"
    br.select_form(nr=0)
    # Entering in the sample name
    br.form['sea'] = '%s' %Sample_Name
    br.submit()

    Link_List = list()
    for i in br.links():
        # Append the Base URL and the URL of the Sample
        new_url = urlparse.urljoin(i.base_url, i.url)
        # Insert URL's into a list
        Link_List.append(new_url)

    br.close()

    if len(Link_List)>9999999999:
       # print len(Link_List
        print ("Can't find data for: "), Sample_Name, "Perhaps try searching this one manually"
        #Manual_Search_File = np.loadtxt("/Users/edenmolina/Desktop/Metiorite_Manual_Search.txt", dtype='string', unpack=True
        Sample_URL = 0
        return Sample_URL
    #9 is the mumber of links for a sample that is not in the online database#
    elif len(Link_List)<=9:
        #print len(Link_List)
        #print ("No results found on database for: "), Sample_Name
        Sample_URL = 0
        return Sample_URL
    else:
        #print len(Link_List)
        #print len(Link_List), Sample_Name
        Sample_URL = Link_List[-4]
        return Sample_URL

"""Get the Classification"""
def get_Classification(URL):
    source = urllib.urlopen("%s"%URL).read()
    soup = BeautifulSoup(source, "html.parser")

    Classification_List = []
    for k, td in enumerate(soup.find_all("td", {'class', 'inside'})):
        Classification = td.find_all("b")
        Classification_List.append(Classification)
    #print Classification_List[3]
    print (Classification_List[3][1].text)

"Define a fucntion that get the name, weathering, and shock stage of the sample"
def get_Name_Weathering_Shock(url):
    "Get the source code from the website"
    source = urllib.urlopen("%s" % url).read()

    # Convert the data to a Beautiful Soup object
    soup = BeautifulSoup(source, "html.parser")

    """
    Print out the title of the webpage"""
    #print soup.title.string

    """"Getting the name"""
    Name_List = []
    for i, td in enumerate(soup.find_all("th", {'class', 'insidehead'})):
        Name = td.find_all("b")
        Name_List.append(Name)
    print ("Name Check: ", Name_List[0][0].text)

    # Get the data in the td subsections from the website
    data = soup.find_all('tr')

    # Getting the website data
    Website_Data = list()
    for tr in data:
        td = tr.find_all('td')
        row = [i.text for i in td]
        Website_Data.append(row)

    Weathering_Grade = [w for w in Website_Data if "Weathering grade:" in w]
    Shock_Stage = [s for s in Website_Data if "Shock stage:" in s]

    #Prints out the weathering and shock stage of the sample

    try:
        print (Weathering_Grade[1][1])
        np.savetxt("/Users/edenmolina/Desktop/Meteorite Data/%s.txt" % (Name[0][0].text), Weathering_Grade[1][1])
    except:
        print ("No Weathering")
    try:
        print (Shock_Stage[1][1])
    except:
        print ("No Shock Stage")

def get_Info(url, weatheringOrshock):
    "Get source code of website"
    source = urllib.urlopen("%s" % url).read()

    # Convert the data to a Beautiful Soup object
    soup = BeautifulSoup(source, "html.parser")

    data = soup.find_all('tr')

    data = list()
    for tr in data:
        td = tr.find_all('td')
        row = [i.text for i in td]
        data.append(row)

    information = [w for w in data if "%s" %weatheringOrshock in w]

    try:
        print (information[1][1])
        return information[1][1]
    except:
        print ("No %s" %weatheringOrshock)

#get_SampleData("https://www.lpi.usra.edu/meteor/metbull.php?sea=NWA+001&sfor=names&ants=&falls=&valids=&stype=contains&lrec=50&map=ge&browse=&country=All&srt=name&categ=All&mblist=All&rect=&phot=&snew=0&pnt=Normal%20table&code=17011")

#AllData("NWA 002")

#LOAD THE SAMPLE NAMES FROM A TEXT FILE#
SampleNames_Text = np.loadtxt("/Users/edenmolina/Desktop/MetioriteNames.txt",delimiter="\n", dtype=np.str)
Number_of_Loops = len(SampleNames_Text)

"""FOR SAVING THE DATA"""

#Iterates through each of the samples in the text file and outputs the name, weathering, and the shock stage (if applicable)
for i in range(Number_of_Loops):
    print (SampleNames_Text[i])
    Sample_URL = get_Sample_URL("%s" % SampleNames_Text[i])

    if Sample_URL == 0 or len(Sample_URL) < 80.0:
        print ("")
    elif len(Sample_URL)<80.0:
        print ("Try Searching This Manually")

    else:
        Weathering = get_Info(Sample_URL, "Weathering grade:")
        Shock = get_Info(Sample_URL, "Shock stage:")
        Classification = get_Classification(Sample_URL)
    URL = get_Sample_URL("%s" %SampleNames_Text[i])
    print ("\n")
</code>```

Stack Trace of the Error

```<code>Traceback (most recent call last):
  File "/Users/edenmolina/PycharmProjects/Meteorite/DataBase_Data_Extractor_V3.py", line 163, in <module>
    Sample_URL = get_Sample_URL("%s" % SampleNames_Text[i])
  File "/Users/edenmolina/PycharmProjects/Meteorite/DataBase_Data_Extractor_V3.py", line 34, in get_Sample_URL
    br.select_form(nr=0)
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/mechanize/_mechanize.py", line 619, in select_form
    global_form = self._factory.global_form
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/mechanize/_html.py", line 260, in global_form
    self.forms()
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/mechanize/_html.py", line 267, in forms
    self._current_forms, self._current_global_form = self._get_forms()
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/mechanize/_html.py", line 282, in _get_forms
    if self.root is None:
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/mechanize/_html.py", line 247, in root
    response, verify=False))
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/mechanize/_html.py", line 145, in content_parser
    from html5lib import parse
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/html5lib/__init__.py", line 16, in <module>
    from .html5parser import HTMLParser, parse, parseFragment
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/html5lib/html5parser.py", line 2, in <module>
    from six import with_metaclass, viewkeys, PY3
ImportError: cannot import name viewkeys
</code>```

答:
If you're using version control, then go back to your previous commits and see if you can get the application to work. This way you can isolate the change that caused the issue you're having.

One common reason for this type of error is circular imports in Python. I don't see it in the stack trace you pu but here. Google it anyway and see if that's what's happening here.

Another thing you can and should do is to have a virtual environment for your Python application. You can create one using the conda command. Once you have an environment, then install all the libraries you need for this application and try to run the app again.

I see six is being used by one of the libraries you're using. six is used to write code that's compatible with Python 2 and Python 3. So, maybe you changed your interpreter or environment and that's causing this error.

Let me know if you got the app working, I'd like to know what was causing the error. Thanks.

Body:
So I created this web scraper in python and I'm building it in Pycharm with Anaconda. My script was working, but somehow I think I messed something up in my computer and now I'm getting this error.

ImportError: cannot import name viewkeys

Also I can't seem to be able to install the module "mechanize" onto the anaconda directory.

Below is my code. If anyone can help resolve this that'd be great!

from bs4 import BeautifulSoup
import urllib
import numpy as np
#import selenium.webdriver as webdriver
import urllib
import requests
import mechanize
import urlparse
import lxml
import sys
import re

def get_Sample_URL(Sample_Name):
    br = mechanize.Browser()
    br.open("https://www.lpi.usra.edu/meteor/")

    "SELECTING THE FORM"
    br.select_form(nr=0)
    # Entering in the sample name
    br.form['sea'] = '%s' %Sample_Name
    br.submit()

    Link_List = list()
    for i in br.links():
        # Append the Base URL and the URL of the Sample
        new_url = urlparse.urljoin(i.base_url, i.url)
        # Insert URL's into a list
        Link_List.append(new_url)

    br.close()

    if len(Link_List)>9999999999:
       # print len(Link_List
        print ("Can't find data for: "), Sample_Name, "Perhaps try searching this one manually"
        #Manual_Search_File = np.loadtxt("/Users/edenmolina/Desktop/Metiorite_Manual_Search.txt", dtype='string', unpack=True
        Sample_URL = 0
        return Sample_URL
    #9 is the mumber of links for a sample that is not in the online database#
    elif len(Link_List)<=9:
        #print len(Link_List)
        #print ("No results found on database for: "), Sample_Name
        Sample_URL = 0
        return Sample_URL
    else:
        #print len(Link_List)
        #print len(Link_List), Sample_Name
        Sample_URL = Link_List[-4]
        return Sample_URL

"""Get the Classification"""
def get_Classification(URL):
    source = urllib.urlopen("%s"%URL).read()
    soup = BeautifulSoup(source, "html.parser")

    Classification_List = []
    for k, td in enumerate(soup.find_all("td", {'class', 'inside'})):
        Classification = td.find_all("b")
        Classification_List.append(Classification)
    #print Classification_List[3]
    print (Classification_List[3][1].text)

"Define a fucntion that get the name, weathering, and shock stage of the sample"
def get_Name_Weathering_Shock(url):
    "Get the source code from the website"
    source = urllib.urlopen("%s" % url).read()

    # Convert the data to a Beautiful Soup object
    soup = BeautifulSoup(source, "html.parser")

    """
    Print out the title of the webpage"""
    #print soup.title.string

    """"Getting the name"""
    Name_List = []
    for i, td in enumerate(soup.find_all("th", {'class', 'insidehead'})):
        Name = td.find_all("b")
        Name_List.append(Name)
    print ("Name Check: ", Name_List[0][0].text)

    # Get the data in the td subsections from the website
    data = soup.find_all('tr')

    # Getting the website data
    Website_Data = list()
    for tr in data:
        td = tr.find_all('td')
        row = [i.text for i in td]
        Website_Data.append(row)

    Weathering_Grade = [w for w in Website_Data if "Weathering grade:" in w]
    Shock_Stage = [s for s in Website_Data if "Shock stage:" in s]

    #Prints out the weathering and shock stage of the sample

    try:
        print (Weathering_Grade[1][1])
        np.savetxt("/Users/edenmolina/Desktop/Meteorite Data/%s.txt" % (Name[0][0].text), Weathering_Grade[1][1])
    except:
        print ("No Weathering")
    try:
        print (Shock_Stage[1][1])
    except:
        print ("No Shock Stage")

def get_Info(url, weatheringOrshock):
    "Get source code of website"
    source = urllib.urlopen("%s" % url).read()

    # Convert the data to a Beautiful Soup object
    soup = BeautifulSoup(source, "html.parser")

    data = soup.find_all('tr')

    data = list()
    for tr in data:
        td = tr.find_all('td')
        row = [i.text for i in td]
        data.append(row)

    information = [w for w in data if "%s" %weatheringOrshock in w]

    try:
        print (information[1][1])
        return information[1][1]
    except:
        print ("No %s" %weatheringOrshock)

#get_SampleData("https://www.lpi.usra.edu/meteor/metbull.php?sea=NWA+001&sfor=names&ants=&falls=&valids=&stype=contains&lrec=50&map=ge&browse=&country=All&srt=name&categ=All&mblist=All&rect=&phot=&snew=0&pnt=Normal%20table&code=17011")

#AllData("NWA 002")

#LOAD THE SAMPLE NAMES FROM A TEXT FILE#
SampleNames_Text = np.loadtxt("/Users/edenmolina/Desktop/MetioriteNames.txt",delimiter="\n", dtype=np.str)
Number_of_Loops = len(SampleNames_Text)

"""FOR SAVING THE DATA"""

#Iterates through each of the samples in the text file and outputs the name, weathering, and the shock stage (if applicable)
for i in range(Number_of_Loops):
    print (SampleNames_Text[i])
    Sample_URL = get_Sample_URL("%s" % SampleNames_Text[i])

    if Sample_URL == 0 or len(Sample_URL) < 80.0:
        print ("")
    elif len(Sample_URL)<80.0:
        print ("Try Searching This Manually")

    else:
        Weathering = get_Info(Sample_URL, "Weathering grade:")
        Shock = get_Info(Sample_URL, "Shock stage:")
        Classification = get_Classification(Sample_URL)
    URL = get_Sample_URL("%s" %SampleNames_Text[i])
    print ("\n")

Stack Trace of the Error

Traceback (most recent call last):
  File "/Users/edenmolina/PycharmProjects/Meteorite/DataBase_Data_Extractor_V3.py", line 163, in <module>
    Sample_URL = get_Sample_URL("%s" % SampleNames_Text[i])
  File "/Users/edenmolina/PycharmProjects/Meteorite/DataBase_Data_Extractor_V3.py", line 34, in get_Sample_URL
    br.select_form(nr=0)
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/mechanize/_mechanize.py", line 619, in select_form
    global_form = self._factory.global_form
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/mechanize/_html.py", line 260, in global_form
    self.forms()
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/mechanize/_html.py", line 267, in forms
    self._current_forms, self._current_global_form = self._get_forms()
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/mechanize/_html.py", line 282, in _get_forms
    if self.root is None:
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/mechanize/_html.py", line 247, in root
    response, verify=False))
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/mechanize/_html.py", line 145, in content_parser
    from html5lib import parse
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/html5lib/__init__.py", line 16, in <module>
    from .html5parser import HTMLParser, parse, parseFragment
  File "/Users/edenmolina/Library/Python/2.7/lib/python/site-packages/html5lib/html5parser.py", line 2, in <module>
    from six import with_metaclass, viewkeys, PY3
ImportError: cannot import name viewkeys


来源: stackexchange

问:
C++ virtual functions implementation outside the class
I am new to C++. While trying sample polymorphism code, I found that base class virtual function definition in derived class is possible only when defined within the derived class or outside with declaration in derived class.

Following code gives error:

```<code>class B
{
public:
    virtual void f();
};

void B::f() {
    std::cout<<"B::f";
}

class D : public B
{
public:
    void f2() {int b;}
};

// error: no "void D::f()" member function declared in class "D"
void D::f() {
    std::cout<<"D::F";
}
</code>```

It works if I declare f() inside D. I was wondering why do I need to explicitly declare the function again when it is already declared in Base class. The compiler can get the signature from Base class right?

Thanks in advance..

答:
In C++, your class definition tells the compiler which functions the class implements. So if you want to write a function "D::f()", you must have f() in the class definition for D.

The fact that function "B::f()" has been defined in the base class is irrelevant. Each class definition must explicitly declare the functions that it implements.

ContentLicense: CC BY-SA 2.5

Body:
I am new to C++. While trying sample polymorphism code, I found that base class virtual function definition in derived class is possible only when defined within the derived class or outside with declaration in derived class.

Following code gives error:

class B
{
public:
    virtual void f();
};

void B::f() {
    std::cout<<"B::f";
}

class D : public B
{
public:
    void f2() {int b;}
};

// error: no "void D::f()" member function declared in class "D"
void D::f() {
    std::cout<<"D::F";
}

It works if I declare f() inside D. I was wondering why do I need to explicitly declare the function again when it is already declared in Base class. The compiler can get the signature from Base class right?

Thanks in advance..


问:
Lazy eval, dplyr "filter" and NAs
I am having some silly problem using lazy evaluation and dplyr.
I'm trying to filter some NAs and don't know why the lazyeval version doesn't work. Probably I'm missing something, but I can't find it. Is that so, or is it a bug?

Here is a minimum reproducible example:

```<code>library(dplyr)
library(lazyeval)

data(iris)
iris$t <- c(1:140, rep(NA, 10))

#This Works
temp <- filter(iris, !is.na(t))

#This doesn't
temp <- filter_(iris, interp(~(!is.na(x)), x="t"))
</code>```

Both codes run without throwing out an error.

答:
dplyr has switched over its NSE system from lazyeval to rlang (documented here), deprecating the *_ functions in favor of a new syntax:

library(dplyr)

data(iris)
iris <- iris %>% mutate(t = c(1, rep(NA, 149)))

# normal NSE
iris %>% filter(!is.na(t))
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species t
#> 1          5.1         3.5          1.4         0.2  setosa 1

# string-based SE; use `rlang::sym` to convert to quosure and !! to unquote
x <- "t"
iris %>% filter(!is.na(!!rlang::sym(x)))
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species t
#> 1          5.1         3.5          1.4         0.2  setosa 1

# program your own NSE with `quo` and friends
x <- quo(t)
iris %>% filter(!is.na(!!x))
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species t
#> 1          5.1         3.5          1.4         0.2  setosa 1

# both versions work across the tidyverse
iris %>% tidyr::drop_na(!!x)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species t
#> 1          5.1         3.5          1.4         0.2  setosa 1

# though tidyr::drop_na is happy with strings anyway
iris %>% tidyr::drop_na("t")
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species t
#> 1          5.1         3.5          1.4         0.2  setosa 1
```

ContentLicense: CC BY-SA 3.0

Title: Lazy eval, dplyr "filter" and NAs

Body:
I am having some silly problem using lazy evaluation and dplyr.
I'm trying to filter some NAs and don't know why the lazyeval version doesn't work. Probably I'm missing something, but I can't find it. Is that so, or is it a bug?

Here is a minimum reproducible example:

library(dplyr)
library(lazyeval)

data(iris)
iris$t <- c(1:140, rep(NA, 10))

#This Works
temp <- filter(iris, !is.na(t))

#This doesn't
temp <- filter_(iris, interp(~(!is.na(x)), x="t"))

Both codes run without throwing out an error.


问:
Scatterplot: Error in FUN(X[[i]], ...) : object 'Group' not found
I'm trying to plot some data using ggplot and I'm having some problems with the significant lines and asterisk.

This is the code I am using:

```<code>p <- ggplot(Hematoxilin_tumor_necrosis, aes(x=total, y=necro, colour = Group))+
  labs(y="Necrotic area",x="Total area")+
  theme_minimal()

path = data.frame(x=c(78,79,79,78),y=c(22,22,34,34))

p + geom_point(size=0.7)+
  geom_smooth(method=lm, se = F, size=0.8) +
  scale_color_manual(values=c("#999999","#333333"))+
  #Adding asterisks
  geom_path(data = path, aes(x = x,y = y)) +
  annotate("text",x = 80, y = 27, label="*", cex=7)
</code>```

Which gives me the following error:

Error in FUN(X[[i]], ...) : object 'Group' not found

I know that the problem is in the geom_path(data = path, aes(x = x,y = y)) but I am kind of lost. I am new in ggplot so I expect some simple problem.

Any advice?

答:
aesthetics are inherited by default. The geom_path is trying to look for the Group variable on the path dataset to get the color. You should use inherit.aes = FALSE on the geom_path:

```<code>  geom_path(data = path, aes(x = x,y = y), inherit.aes = FALSE )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to plot some data using ggplot and I'm having some problems with the significant lines and asterisk.

This is the code I am using:

p <- ggplot(Hematoxilin_tumor_necrosis, aes(x=total, y=necro, colour = Group))+
  labs(y="Necrotic area",x="Total area")+
  theme_minimal()

path = data.frame(x=c(78,79,79,78),y=c(22,22,34,34))

p + geom_point(size=0.7)+
  geom_smooth(method=lm, se = F, size=0.8) +
  scale_color_manual(values=c("#999999","#333333"))+
  #Adding asterisks
  geom_path(data = path, aes(x = x,y = y)) +
  annotate("text",x = 80, y = 27, label="*", cex=7)

Which gives me the following error:

Error in FUN(X[[i]], ...) : object 'Group' not found

I know that the problem is in the geom_path(data = path, aes(x = x,y = y)) but I am kind of lost. I am new in ggplot so I expect some simple problem.

Any advice?

Body:
aesthetics are inherited by default. The geom_path is trying to look for the Group variable on the path dataset to get the color. You should use inherit.aes = FALSE on the geom_path:

  geom_path(data = path, aes(x = x,y = y), inherit.aes = FALSE )


问:
There is no error in the code , but also it is not getting executed?
```<code>enrollments=[{'name':'Kinjal','account_key':4149},
            {'name':'Amruta','account_key':4162}]

unique_engagement_students={'name':'Amruta','account_key':4162}

for enrollment in enrollments:
    student = enrollment['account_key']
    if student in unique_engagement_students:
        print (enrollment)
</code>```

答:
replace:

```<code>if student in unique_engagement_students:
</code>```

by

```<code>if student in unique_engagement_students.values():
</code>```

you were never entering this if statement simply because you were comparing the dictionary's keys with an integer expected to be in the values of the dictionary.

Hope this helped.

Body:
replace:

if student in unique_engagement_students:

by

if student in unique_engagement_students.values():

you were never entering this if statement simply because you were comparing the dictionary's keys with an integer expected to be in the values of the dictionary.

Hope this helped.


问:
Exact website links from google through BeautifulSoup
I want to search google using BeautifulSoup and open the first link. But when I opened the link it shows error. The reason i think is that because google is not providing exact link of website, it has added several parameters in url. How to get exact url?

When i tried to use cite tag it worked but for big urls its creating problem.

The first link which i get using soup.h3.a['href'][7:] is:
'http://www.wikipedia.com/wiki/White_holes&sa=U&ved=0ahUKEwi_oYLLm_rUAhWJNI8KHa5SClsQFggbMAI&usg=AFQjCNGN-vlBvbJ9OPrnq40d0_b8M0KFJQ'

Here is my code:

```<code>import requests
from bs4 import Beautifulsoup
r = requests.get('https://www.google.com/search?q=site:wikipedia.com+Black+hole&gbv=1&sei=YwHNVpHLOYiWmQHk3K24Cw')
soup = BeautifulSoup(r.text, "html.parser")
print(soup.h3.a['href'][7:])
</code>```

答:
You could split the returned string:</p>

```<code>url = soup.h3.a['href'][7:].split('&')
print(url[0])
</code>```

Body:
I want to search google using BeautifulSoup and open the first link. But when I opened the link it shows error. The reason i think is that because google is not providing exact link of website, it has added several parameters in url. How to get exact url?

When i tried to use cite tag it worked but for big urls its creating problem.

The first link which i get using soup.h3.a['href'][7:] is:
'http://www.wikipedia.com/wiki/White_holes&sa=U&ved=0ahUKEwi_oYLLm_rUAhWJNI8KHa5SClsQFggbMAI&usg=AFQjCNGN-vlBvbJ9OPrnq40d0_b8M0KFJQ'

Here is my code:

import requests
from bs4 import Beautifulsoup
r = requests.get('https://www.google.com/search?q=site:wikipedia.com+Black+hole&gbv=1&sei=YwHNVpHLOYiWmQHk3K24Cw')
soup = BeautifulSoup(r.text, "html.parser")
print(soup.h3.a['href'][7:])

Body:
You could split the returned string:

url = soup.h3.a['href'][7:].split('&')
print(url[0])


答:
You want

```<code>enrollments=[{'name':'Kinjal','account_key':4149},
            {'name':'Amruta','account_key':4162}]

unique_engagement_students=[4162]

for enrollment in enrollments:
    student = enrollment['account_key']
    if student in unique_engagement_students:
        print (enrollment)
</code>```

I'll update to add an explanation.

Title: There is no error in the code , but also it is not getting executed?

Body:
enrollments=[{'name':'Kinjal','account_key':4149},
            {'name':'Amruta','account_key':4162}]

unique_engagement_students={'name':'Amruta','account_key':4162}

for enrollment in enrollments:
    student = enrollment['account_key']
    if student in unique_engagement_students:
        print (enrollment)

Body:
You want

enrollments=[{'name':'Kinjal','account_key':4149},
            {'name':'Amruta','account_key':4162}]

unique_engagement_students=[4162]

for enrollment in enrollments:
    student = enrollment['account_key']
    if student in unique_engagement_students:
        print (enrollment)

I'll update to add an explanation.


问:
$base64 encoded string from angular is not able to decode in C#
Client side code (angularjs controller)

```<code>var p="gemüse8";

var pb= $base64.encode(p); // pb= Z2Vt/HNlOA==
</code>```

from server side(C#)

```<code>string b64="Z2Vt/HNlOA==";

byte[] data = Convert.FromBase64String(b64);

string decodedString = Encoding.UTF8.GetString(data);
</code>```

result showing "gem�se8"

How can i properly decode this string?

答:
Whatever $base64.encode is seems to be using ISO-8859-1 (or similar) encoding rather than UTF - which probably needs addressing.

As it stands use:

```<code>string decodedString = Encoding.GetEncoding("iso-8859-1").GetString(data);
</code>```

Body:
Client side code (angularjs controller)

var p="gemüse8";

var pb= $base64.encode(p); // pb= Z2Vt/HNlOA==

from server side(C#)

string b64="Z2Vt/HNlOA==";

byte[] data = Convert.FromBase64String(b64);

string decodedString = Encoding.UTF8.GetString(data);

result showing "gem�se8"

How can i properly decode this string?

Body:
Whatever $base64.encode is seems to be using ISO-8859-1 (or similar) encoding rather than UTF - which probably needs addressing.

As it stands use:

string decodedString = Encoding.GetEncoding("iso-8859-1").GetString(data);


问:
Building AOSP Apps and customizing them
Ok sort of a n00b question but recently I was interested in ROM development for my device, the herolte (Galaxy S7) and wanted to build it off of LineageOS (vanilla Android basically). I already have all the source code and builds working perfectly on my virtual machine and installation is smooth too! Unfortunately, there is this one thing that has been constantly bugging me, customization!

I wanted to customize the Dialer app for example but realized that when I try to open it in Android Studio it doesn't show all the files under the project structure only showing "R", "Manifest", "BuildConfig". No drawables folder or anything (although the source code / directory in my folder shows it). So I am assuming I am missing something but not sure what it is exactly, so any help would be appreciated. I do understand that the apps like Dialer or Contacts come heavily tied into the Android Framework it is using like how the Samsung Dialer is tied down with TouchWiz.

I essentially wanted to modify some parameters of the original apps and then have them built with LineageOS. Any help is appreciated, thank you!

答:
The AOSP is built via a custom build system based on "make". When you open the AOSP in Android studio you get a nice representation of project sources and some resources but you should always keep in mind that eventually the app's compilation will be made by the 'make' build system with its 'mk' files.

In the case of the 'Dialer' app, you can find a hint to where are the app's resources if you take a look at its Android.mk file. Note that resources are getting imported from:

```<code>> res_dirs := res \
>     $(incallui_dir)/res \
>     $(contacts_common_dir)/res \
>     $(contacts_common_dir)/icons/res \
>     $(phone_common_dir)/res
</code>```

Digging deeper into those definitions will resolute in the following directory:     /packages/apps/PhoneCommon/res/

Title: Building AOSP Apps and customizing them

Body:
The AOSP is built via a custom build system based on "make". When you open the AOSP in Android studio you get a nice representation of project sources and some resources but you should always keep in mind that eventually the app's compilation will be made by the 'make' build system with its 'mk' files.

In the case of the 'Dialer' app, you can find a hint to where are the app's resources if you take a look at its Android.mk file. Note that resources are getting imported from:

> res_dirs := res \
>     $(incallui_dir)/res \
>     $(contacts_common_dir)/res \
>     $(contacts_common_dir)/icons/res \
>     $(phone_common_dir)/res

Digging deeper into those definitions will resolute in the following directory:     /packages/apps/PhoneCommon/res/


问:
Import wizard with subqueries
I want to import 100k+ rows on to a SQL Server table.

I have my insert like this (observe the 6th value that is a subquery):

```<code>INSERT INTO BD_S3I.dbo.AGENDA
(COD_UNDFBR, COD_DCPLNA, COD_TECNCA, COD_ATVIDE, DAT_PROGM_AGENDA, NUM_SQNCL_AGENDA, DAT_FINAL_AGENDA, COD_OCORR, COD_ROTA, NUM_SEMAN_PRGINS, NUM_DIAIN_PRGINS, DAT_INIC_PRGINS, MRC_SITUA_AGENDA, DAT_SUSPN_AGENDA, DAT_CONCL_AGENDA, DAT_REPRG_AGENDA, DCR_SITUA_AGENDA, DCR_AGENDA, MRC_AVISO_AGENDA, MRC_NEGLG_AGENDA, NUM_PERIO_PRGINS, DAT_DIAIN_PRGINS, DAT_JUSTN_AGENDA, COD_MTVNVS, MRC_ERP_AGENDA, COD_USUS3I_JUSTN)

VALUES

(1, 290, 2, 6, '2017-09-11 00:00:00.000', (SELECT CASE WHEN MAX(AGENDA.NUM_SQNCL_AGENDA) + 1 IS NULL THEN 1 ELSE MAX(AGENDA.NUM_SQNCL_AGENDA) + 1 END FROM AGENDA WHERE AGENDA.COD_UNDFBR = 1 AND AGENDA.COD_DCPLNA = 290 AND AGENDA.COD_TECNCA = 2 AND AGENDA.COD_ATVIDE = 6 AND AGENDA.DAT_PROGM_AGENDA = '2017-09-11 00:00:00.000'), '2017-09-17 00:00:00.000', NULL, 492, NULL, NULL, '2017-07-24 08:30:00.000', 'P', NULL, NULL, NULL, NULL, NULL, 'S', 'S', 7, '2017-07-24 00:00:00.000', NULL, NULL, 'N', NULL);
</code>```

I put al the 100k inserts below each other and start the import. It is working fine, but thakes too much time to execute all the 100k+ rows.

I was thinking to use the import wizard (the time is better?).

The problem is that when I choose the excel file with my data, the import wizard do not understand the subquery on the value. It calls it a longtext.

答:
Select atleast one return type that's needs to be inserted into 6th column.
Just like

```<code>( SELECT x = CASE .... )
</code>```

Or use return type along with subquery at the end.

Title: Import wizard with subqueries

Body:
I want to import 100k+ rows on to a SQL Server table.

I have my insert like this (observe the 6th value that is a subquery):

INSERT INTO BD_S3I.dbo.AGENDA
(COD_UNDFBR, COD_DCPLNA, COD_TECNCA, COD_ATVIDE, DAT_PROGM_AGENDA, NUM_SQNCL_AGENDA, DAT_FINAL_AGENDA, COD_OCORR, COD_ROTA, NUM_SEMAN_PRGINS, NUM_DIAIN_PRGINS, DAT_INIC_PRGINS, MRC_SITUA_AGENDA, DAT_SUSPN_AGENDA, DAT_CONCL_AGENDA, DAT_REPRG_AGENDA, DCR_SITUA_AGENDA, DCR_AGENDA, MRC_AVISO_AGENDA, MRC_NEGLG_AGENDA, NUM_PERIO_PRGINS, DAT_DIAIN_PRGINS, DAT_JUSTN_AGENDA, COD_MTVNVS, MRC_ERP_AGENDA, COD_USUS3I_JUSTN)

VALUES

(1, 290, 2, 6, '2017-09-11 00:00:00.000', (SELECT CASE WHEN MAX(AGENDA.NUM_SQNCL_AGENDA) + 1 IS NULL THEN 1 ELSE MAX(AGENDA.NUM_SQNCL_AGENDA) + 1 END FROM AGENDA WHERE AGENDA.COD_UNDFBR = 1 AND AGENDA.COD_DCPLNA = 290 AND AGENDA.COD_TECNCA = 2 AND AGENDA.COD_ATVIDE = 6 AND AGENDA.DAT_PROGM_AGENDA = '2017-09-11 00:00:00.000'), '2017-09-17 00:00:00.000', NULL, 492, NULL, NULL, '2017-07-24 08:30:00.000', 'P', NULL, NULL, NULL, NULL, NULL, 'S', 'S', 7, '2017-07-24 00:00:00.000', NULL, NULL, 'N', NULL);

I put al the 100k inserts below each other and start the import. It is working fine, but thakes too much time to execute all the 100k+ rows.

I was thinking to use the import wizard (the time is better?).

The problem is that when I choose the excel file with my data, the import wizard do not understand the subquery on the value. It calls it a longtext.

Body:
Select atleast one return type that's needs to be inserted into 6th column.
Just like

( SELECT x = CASE .... )

Or use return type along with subquery at the end.


问:
How can I check to see if an http request has no query strings in ASP.Net Core web API
I am working on an ASP.Net Core web API using REST verbs with optional query string parameters.

For example, the API call looks like this;

```<code>http://localhost:5010/servicetypecode?stc=123
</code>```

or
    http://localhost:5010/servicetypecode?mailclasscode=fc

I am using code like this to set up the query strings

```<code>    public IActionResult Get([FromQuery] string mailclasscode, [FromQuery] string stc) { ... }
</code>```

So, in my method body, I am evaluating each string individually like this...

```<code>    if (!string.IsNullOrEmpty(mailclasscode)) { ... }

    if (!string.IsNullOrEmpty(stc)) { ... }
</code>```

However, I would like to allow my users to just make a straight up GET to the API with no query string parameters provided and return a list of all records, unfiltered.

So a call like this;

```<code>http://localhost:5010/servicetypecode
</code>```

But I would prefer not to have to do this in my method body, especially if I were to have a lot of query string parameters;

```<code>if (string.IsNullOrEmpty(mailclasscode) && string.IsNullOrEmpty(stc)) { ... }
</code>```

Is there a way to simply determine if no query string parameters were provided without evaluating every possible query string parameter?

Also, is there a better way to evaluate query string parameters than testing every possible parameter, in the case where I were to pass a lot of different query string parameters?

Thanks in advance for any help you can provide.

答:
You can check the incoming request.

```<code>if (this.HttpContext.Request.QueryString.HasValue)
</code>```

Also as a note, if you have a lot of query string parameters, you can use a single class instead of multiple parameters in the method signature.

Body:
I am working on an ASP.Net Core web API using REST verbs with optional query string parameters.

For example, the API call looks like this;

http://localhost:5010/servicetypecode?stc=123

or
    http://localhost:5010/servicetypecode?mailclasscode=fc

I am using code like this to set up the query strings

    public IActionResult Get([FromQuery] string mailclasscode, [FromQuery] string stc) { ... }

So, in my method body, I am evaluating each string individually like this...

    if (!string.IsNullOrEmpty(mailclasscode)) { ... }

    if (!string.IsNullOrEmpty(stc)) { ... }

However, I would like to allow my users to just make a straight up GET to the API with no query string parameters provided and return a list of all records, unfiltered.

So a call like this;

http://localhost:5010/servicetypecode

But I would prefer not to have to do this in my method body, especially if I were to have a lot of query string parameters;

if (string.IsNullOrEmpty(mailclasscode) && string.IsNullOrEmpty(stc)) { ... }

Is there a way to simply determine if no query string parameters were provided without evaluating every possible query string parameter?

Also, is there a better way to evaluate query string parameters than testing every possible parameter, in the case where I were to pass a lot of different query string parameters?

Thanks in advance for any help you can provide.

Body:
You can check the incoming request.

if (this.HttpContext.Request.QueryString.HasValue)

Also as a note, if you have a lot of query string parameters, you can use a single class instead of multiple parameters in the method signature.


问:
Restart Delphi Application Programmatically
It should not be possible to run multiple instances of my application. Therefore the project source contains:

```<code>CreateMutex (nil, False, PChar (ID));
if (GetLastError = ERROR_ALREADY_EXISTS) then
  Halt;
</code>```

Now I want to restart my application programmatically. The usual way would be:

```<code>AppName := PChar(Application.ExeName) ;
ShellExecute(Handle,'open', AppName, nil, nil, SW_SHOWNORMAL) ;
Application.Terminate;
</code>```

But this won't work in my case because of the mutex. Even if I release the mutex before starting the second instace it won't work because shutdown takes some time and two instance cannot run in parallel (because of common resources and other effects).

Is there a way to restart an application with such characteristics? (If possible without an additional executable)

Thanks in advance.

答: Your ReleaseMutex is probably failing since you're passing 'False' for 'bInitialOwner' while calling CreateMutex. Either have the initial ownership of the mutex, or call CloseHandle instead of 'ReleaseMutex' passing your mutex handle.

Body:
It should not be possible to run multiple instances of my application. Therefore the project source contains:

CreateMutex (nil, False, PChar (ID));
if (GetLastError = ERROR_ALREADY_EXISTS) then
  Halt;

Now I want to restart my application programmatically. The usual way would be:

AppName := PChar(Application.ExeName) ;
ShellExecute(Handle,'open', AppName, nil, nil, SW_SHOWNORMAL) ;
Application.Terminate;

But this won't work in my case because of the mutex. Even if I release the mutex before starting the second instace it won't work because shutdown takes some time and two instance cannot run in parallel (because of common resources and other effects).

Is there a way to restart an application with such characteristics? (If possible without an additional executable)

Thanks in advance.


问:
Javascript code doesn't work. Why?
The values of the buttons should change when you click on them

```<code><html>
<head>

</head>

<body>

<input type = "button" value ="1" onclick="click(this);">
<input type = "button" value ="0" onclick="click(this);">
<input type = "button" value ="1" onclick="click(this);">

<script>

function click(objekt) {

if(objekt.value == 1)
    objekt.value = 0;
    else
        objekt.value = 1;

}

</script>

</body>
</html>
</code>```

Please explain how to get the value on onclick event?

答:
Here you go with the solution https://jsfiddle.net/o0zxqq0u/</p>

```<code>clickFunc = function(objekt) {
    if(objekt.value == 1)
        objekt.value = 0;
    else
        objekt.value = 1;
}

**HTML**
<input type="button" value ="1" onclick="clickFunc(this);" />
<input type="button" value ="0" onclick="clickFunc(this);" />
<input type="button" value ="1" onclick="clickFunc(this);" />
</code>```

Title: Javascript code doesn't work. Why?

Body:
The values of the buttons should change when you click on them

<input type = "button" value ="1" onclick="click(this);">
<input type = "button" value ="0" onclick="click(this);">
<input type = "button" value ="1" onclick="click(this);">

Please explain how to get the value on onclick event?

Body:
Here you go with the solution https://jsfiddle.net/o0zxqq0u/

clickFunc = function(objekt) {
    if(objekt.value == 1)
        objekt.value = 0;
    else
        objekt.value = 1;
}

**HTML**
<input type="button" value ="1" onclick="clickFunc(this);" />
<input type="button" value ="0" onclick="clickFunc(this);" />
<input type="button" value ="1" onclick="clickFunc(this);" />


问:
Waiting until all promises have resolved while recursively walking a directory
I'm trying to recursively walk a directory tree and gather all the file names. In the following code, however, the console.log() at the end runs too early, not waiting for the promises generated by the function's recursive cacheDir call to resolve:

```<code>function cacheDir(dir) {
  return fs.readdir(dir).then(items => {
    const readDirPromises = []

    for (let item of items) {
      const fullPath = path.join(dir, item)
      const lstat = fs.lstat(fullPath)
      readDirPromises.push(lstat)

      lstat.then(stats => {
        if (stats.isFile()) {
          return fullPath
        } else {
          return cacheDir(fullPath)
        }
      })
    }

    return Promise.all(readDirPromises)
  })
}

cacheDir("../someDir/")
  .then(results => console.log('done!', results))
</code>```

What am I doing wrong? It seems to me that readDirPromises will be an array of  strings and promises, each promise of which will itself resolve to an array of strings and promises.

答:
The promise you wait on with Promise.all() needs to be lstat.then(), not just lstat.  Remember that lstat.then() returns a new promise and that new promise tracks any promises returned from within the .then() handler which you need because of your recursion.

Here's a version that does that (and gets rid of some temporary variables):

```<code>function cacheDir(dir) {
  return fs.readdir(dir).then(items => {
    const readDirPromises = [];

    for (let item of items) {
      const fullPath = path.join(dir, item);

      readDirPromises.push(fs.lstat(fullPath).then(stats => {
        if (stats.isFile()) {
          return fullPath;
        } else {
          return cacheDir(fullPath);
        }
      }));
    }

    return Promise.all(readDirPromises)
  })
}
</code>```

Body:
I'm trying to recursively walk a directory tree and gather all the file names. In the following code, however, the console.log() at the end runs too early, not waiting for the promises generated by the function's recursive cacheDir call to resolve:

function cacheDir(dir) {
  return fs.readdir(dir).then(items => {
    const readDirPromises = []

    for (let item of items) {
      const fullPath = path.join(dir, item)
      const lstat = fs.lstat(fullPath)
      readDirPromises.push(lstat)

      lstat.then(stats => {
        if (stats.isFile()) {
          return fullPath
        } else {
          return cacheDir(fullPath)
        }
      })
    }

    return Promise.all(readDirPromises)
  })
}

cacheDir("../someDir/")
  .then(results => console.log('done!', results))

What am I doing wrong? It seems to me that readDirPromises will be an array of  strings and promises, each promise of which will itself resolve to an array of strings and promises.

Body:
The promise you wait on with Promise.all() needs to be lstat.then(), not just lstat.  Remember that lstat.then() returns a new promise and that new promise tracks any promises returned from within the .then() handler which you need because of your recursion.

Here's a version that does that (and gets rid of some temporary variables):

function cacheDir(dir) {
  return fs.readdir(dir).then(items => {
    const readDirPromises = [];

    for (let item of items) {
      const fullPath = path.join(dir, item);

      readDirPromises.push(fs.lstat(fullPath).then(stats => {
        if (stats.isFile()) {
          return fullPath;
        } else {
          return cacheDir(fullPath);
        }
      }));
    }

    return Promise.all(readDirPromises)
  })
}


问:
Added new method to the controller doesn't work in codeigniter
I am working on an existing project developed by codeigniter 2.1.4. When I add a new method to a controller and run it to the browser, it shows nothing. Even other methods under that controller also don't run if new method added to that controller. These controllers extends the following controller:

```<code><?php
class MY_Controller extends CI_Controller {

public $data = array();
public $allowedUrl = array(
"super admin" => array("case_controllerler/deleteSingleCase","case_controller/quickPendingCaseSearch","case_controller/checkUniqueCaseNumber","case_controller/kharijCase","admin/index","case_controller/viewSatalementKhatianCopyApplication", "admin/saveAdmin","admin/addUser", "admin/allAdmin", "admin/suspendUser", "admin/activeUser", "admin/CustomSearchGL","admin/showMethod","admin/CustomSearchAction","admin/deleteUser","admin/showAllComplain","admin/singleAdminInfo","admin/updateAdminInfo","admin/successfullyUpdated","case_controller/downloadPendingCase",
        "case_controller/addCase", "case_controller/store_data", "case_controller/caseSuccessfullyAdded", "case_controller/createCalender",
        "case_controller/workingDaysCalender", "case_controller/editPendingCase","case_controller/saveEditedPendingCase","case_controller/EditmissCase","case_controller/UpdateMisccase",
        "case_controller/pending", "case_controller/allCase", "case_controller/searchCase", "case_controller/singleCase","case_controller/testAjax","case_controller/DeleteLandData","case_controller/SaveNEwLandInfo","case_controller/DeleteApplicantinfo",
        "case_controller/nextDateFromGivenDate","case_controller/downloadArchiveCase","case_controller/sendSms","case_controller/secondSms","case_controller/thirdSms","case_controller/fourthSms","case_controller/fiveSms","case_controller/CustomSms","case_controller/monthAllreadyExit",
        "register_control/AddTohsil","register_control/TohsilEntry","register_control/EditTohsil","register_control/updatetohsil",
        "register_control/AddMouja","register_control/MoujaEntry","register_control/EditMouja","register_control/updateMouja",
        "register_control/AddMutationAsistant","register_control/MutationAsistantEntry","register_control/EditMutationAsistant","register_control/updateMutationAsistant",
        "register_control/AddKhotiyan","register_control/moujaquery","register_control/saveKhotiyan","register_control/saveKhotiyanFile",
        "register_control/FindKhotiyan","register_control/SearchKhotiyan","register_control/DeleteKhotiyan","register_control/Editkhotiyan",
        "register_control/AddNewKhotiyanUnderKhotiyanId","register_control/saveNewKhotiyan","register_control/UpdateKhotiyan","register_control/Getjolmohol",
        "register_control/Tamil","register_control/EntryTamilFormat","register_control/createcellfortamil","register_control/editTamil","register_control/UpdateTamil","register_control/DeleteTamil","register_control/Imgdownload",
        "dashboard/DashboardHome","dashboard/viewFullreport","dashboard/tohsilviewlist","dashboard/tohsilviewlistoverdate","dashboard/namjariviewlist","dashboard/namjariviewlistoverdate","dashboard/kanongopendingviewlist","dashboard/kanongooverdateviewlist","dashboard/aclandPendingeviewlist","dashboard/aclandoverdateviewlist","dashboard/waitingpendingviewlist","dashboard/waitingooverdateviewlist",
        "admin/DeleteComplains","admin/fullviewcomplains", "register_nine/Newentry","register_nine/SaveData","register_nine/Search","register_nine/viewapplication",
    "register_nine/editapplication","register_nine/Deleteapplication","register_nine/Preview","register_nine/UpdateApplication",
    "register_nine/SearchForPreview","register_nine/paginationData","admin/GovLandEntry","admin/savegovtLandInfo","admin/GovLandQuery","admin/govtLandInfoQuery","admin/EditGovtLand",
    "admin/UpdategovtLandInfo","admin/DeleteGovtLandInfo","admin/govtLandInfoQueryByType",
    "case_controller/AddmissCase","case_controller/SaveMissCase","case_controller/MIssCassUpdate","case_controller/UpdateInfoMissCase","case_controller/MiscSmsToplaintiff",
    "case_controller/EditMIssCaseUpdate","case_controller/UpdateStatus","case_controller/DeletemissCasestatus","case_controller/CheckGovtLand",
    "case_controller/FinishMisscase","case_controller/DeletemissCase","case_controller/ArchivemissCase","case_controller/ViewMIssCassUpdate","case_controller/SearchActionByNameOrNId","case_controller/SearchActionBydag",
    "case_controller/SearchmissCase","case_controller/SearchMisscaseAction","case_controller/viewPorcaApplication","case_controller/DeletePorcaapplication","case_controller/ArchivePorcaApplication","case_controller/approvalsms",
    "case_controller/ApprovePoRcaApliCation","case_controller/fullviewPrcaApplication","register_control/RemoveKhotiyanFile","case_controller/SaveMissCaseAttchment",
    "register_control/DeleteKHotiyanFile","register_control/ViewTamil","register_control/NewAddKhotiyanFile","register_control/TamilDownload","register_control/RegisterONe","register_control/FileInventory"
    ,"other_registers/EntryDailyIncome","other_registers/SaveDailyINcome","other_registers/inqueryAndSubmit","other_registers/SearchActionOfInquery","other_registers/DeliveryToBank","other_registers/deliverySuccess",
    "other_registers/searchCashRegister","other_registers/SearchActionregisterthree","other_registers/SearchActionregisterthreebyStauts","other_registers/registerseventeenOfTohsil","other_registers/DemandRegister","other_registers/miscellenousPaymentRegister",
        "other_registers/registerseventeenOfAcland","admin/showAllOpinion","admin/Deleteopinion","admin/fullviewopinion","mutation_controller/DownloadMutationApplication","mutation_controller/AllMutationApplications","mutation_controller/DetailsMutationAppliCation",
   "mutation_controller/accecptApplicationSms","mutation_controller/DeleteMutationApplication","dashboard/TohsilPieChart","other_registers/SavedemandRegisterSix","other_registers/SearchAndDelivaryRegisterSix"
    ,"other_registers/SearchActionOfInqueryRegisterSix","other_registers/RegisterSixDelivery","other_registers/registerSixdeliverySuccess","other_registers/SavePaymentRegisterSeven",
    "other_registers/SearchAndDelivaryRegisterSeven","other_registers/SearchActionOfInqueryRegisterSeven","other_registers/RegisterSevenDelivery","other_registers/registerSevendeliverySuccess","case_controller/ChangeMutationAsistant",
    "case_controller/ActionChangeMutationAsistant","case_controller/FeedbackMiscCaseUpdate","case_controller/FeedbackUpdateInfoMissCase","admin/EditUser","admin/updateAdminInfobySuperAdmin", "case_controller/EditMIssCaseUpdateFeedback",
    "case_controller/UpdateStatusFeedback","case_controller/PrintMIsscassInformation","case_controller/viewArchiveCase","case_controller/deleteArchiveSingleCase","case_controller/RuningMiscCase","dashboard/CaseCounter",
    "other_registers/deleteDailyEntryRegisterThree","other_registers/deleteDailyEntryRegistersix","other_registers/deleteDailyEntryRegisterseven","case_controller/fullviewArchivePrcaApplication","case_controller/OrderSheet","case_controller/SaveOrderInfo","case_controller/PrintOrderSheet",
    "case_controller/ViewLedger","case_controller/ProposalView","case_controller/SaveProposalInfo","case_controller/PrintProposalView","case_controller/CaseNotice","case_controller/PrintNoticeView","case_controller/SecondPagePrintProposalView",
    "case_controller/UpdateCaseLandInfo","case_controller/SaveScratchMap","case_controller/UpdateCaseApplicantInfo","case_controller/TohsilWisePendingCaselist"),

    "admin" => array("case_controller/addCase","case_controller/organizeDateFormat","case_controller/createCalender","case_controller/EditmissCase","case_controller/UpdateMisccase","case_controller/DeleteLandData","case_controller/SaveNEwLandInfo","case_controller/DeleteApplicantinfo",
                        "case_controller/assendingCalender","case_controller/monthAllreadyExit","case_controller/changeDateFromat","case_controller/testAjax","case_controller/nextDateFromGivenDate",
                        "case_controller/store_data","case_controller/caseSuccessfullyAdded","case_controller/allCase","case_controller/searchCase","case_controller/singleCase",
                        "case_controller/pending","case_controller/quickPendingCaseSearch","case_controller/kharijCase","case_controller/editPendingCase","case_controller/saveEditedPendingCase",
                        "case_controller/downloadArchiveCase","case_controller/downloadPendingCase","case_controller/sendSms","case_controller/secondSms","case_controller/thirdSms",
                        "case_controller/fourthSms","case_controller/fiveSms","case_controller/CustomSms","case_controller/checkUniqueCaseNumber","case_controller/AddmissCase","case_controller/MiscSmsToplaintiff","case_controller/ViewLedger","case_controller/CaseNotice",
                        "case_controller/SaveMissCase","case_controller/MIssCassUpdate","case_controller/UpdateInfoMissCase","case_controller/EditMIssCaseUpdate","case_controller/UpdateStatus",
                        "case_controller/FinishMisscase","case_controller/ArchivemissCase","case_controller/ViewMIssCassUpdate","case_controller/RuningMiscCase","case_controller/SaveMissCaseAttchment",
                        "case_controller/SearchmissCase","case_controller/SearchMisscaseAction","case_controller/viewPorcaApplication","case_controller/ArchivePorcaApplication",
                        "case_controller/ApprovePoRcaApliCation","case_controller/fullviewPrcaApplication","case_controller/SearchActionByNameOrNId","case_controller/SearchActionBydag",
                        "case_controller/approvalsms","case_controller/ChangeMutationAsistant","case_controller/ActionChangeMutationAsistant","case_controller/FeedbackMiscCaseUpdate",
                        "case_controller/FeedbackUpdateInfoMissCase","case_controller/EditMIssCaseUpdateFeedback","case_controller/UpdateStatusFeedback","case_controller/PrintMIsscassInformation",
                        "case_controller/viewArchiveCase","case_controller/RuningMiscCase","case_controller/viewSatalementKhatianCopyApplication","case_controller/fullviewArchivePrcaApplication",
                        "dashboard/DashboardHome","dashboard/viewFullreport","dashboard/tohsilviewlist","dashboard/tohsilviewlistoverdate","dashboard/namjariviewlist",
                        "dashboard/namjariviewlistoverdate","dashboard/kanongopendingviewlist","dashboard/kanongooverdateviewlist","dashboard/aclandPendingeviewlist",
                        "dashboard/aclandoverdateviewlist","dashboard/waitingpendingviewlist","dashboard/waitingooverdateviewlist","dashboard/TohsilPieChart","dashboard/CaseCounter",
                        "mutation_controller/AllMutationApplications","mutation_controller/DetailsMutationAppliCation","mutation_controller/DownloadMutationApplication",
                        "mutation_controller/accecptApplicationSms","mutation_controller/DeleteMutationApplication","mutation_controller/MutationForm",
                        "other_registers/EntryDailyIncome","other_registers/SaveDailyINcome","other_registers/inqueryAndSubmit","other_registers/SearchActionOfInquery",
                        "other_registers/searchCashRegister","other_registers/SearchActionregisterthree","other_registers/SearchActionregisterthree","other_registers/SearchActionregisterthreebyStauts",
                        "other_registers/registerseventeenOfTohsil","other_registers/DemandRegister","other_registers/miscellenousPaymentRegister","other_registers/registerseventeenOfAcland",
                        "other_registers/SavedemandRegisterSix","other_registers/SearchAndDelivaryRegisterSix","other_registers/SearchActionOfInqueryRegisterSix","other_registers/RegisterSixDelivery",
                        "other_registers/registerSixdeliverySuccess","other_registers/SavePaymentRegisterSeven","other_registers/SearchAndDelivaryRegisterSeven",
                        "other_registers/SearchActionOfInqueryRegisterSeven","other_registers/RegisterSevenDelivery","other_registers/registerSevendeliverySuccess",
                        "register_control/moujaquery","register_control/getmoujaAndMObile","register_control/AddKhotiyan","register_control/saveKhotiyan","register_control/saveKhotiyanFile",
                        "register_control/NewAddKhotiyanFile","register_control/FindKhotiyan","register_control/SearchKhotiyan","register_control/Editkhotiyan","register_control/UpdateKhotiyan",
                        "register_control/Tamil","register_control/createcellfortamil","register_control/EntryTamilFormat","register_control/editTamil","register_control/UpdateTamil",
                        "register_control/ViewTamil","register_control/Imgdownload","register_control/TamilDownload","register_control/RegisterONe","register_control/Getjolmohol",
                        "admin/index","admin/singleAdminInfo","admin/updateAdminInfo","admin/successfullyUpdated","admin/GovLandEntry","admin/savegovtLandInfo","admin/GovLandQuery","admin/govtLandInfoQuery",
                        "admin/EditGovtLand","admin/UpdategovtLandInfo","admin/govtLandInfoQueryByType","admin/allAdmin","admin/CustomSearchGL","admin/showMethod","admin/CustomSearchAction",
                        "register_nine/Newentry","register_nine/Search","register_nine/viewapplication","register_nine/editapplication","register_nine/UpdateApplication",
                        "register_nine/Preview","register_nine/SearchForPreview","register_nine/paginationData","case_controller/UpdateCaseLandInfo","case_controller/SaveScratchMap","case_controller/UpdateCaseApplicantInfo"),

    "general user" => array("case_controller/quickPendingCaseSearch","case_controller/kharijCase","case_controller/pending", "case_controller/allCase", "case_controller/searchCase", "case_controller/singleCase", "admin/index","case_controller/downloadPendingCase","admin/singleAdminInfo","admin/updateAdminInfo","admin/successfullyUpdated",)
);

public function __construct() {
    parent::__construct();
    $this->isLoggedIn();
    $this->isPermitedToAccess();
}

public function isLoggedIn() {

    if ($this->session->userdata('logged_in') === FALSE) {
        redirect('login/index');
    }
}

//end of the is logged in

public function isPermitedToAccess() {
    $userType = $this->session->userdata("type");
    $currentUrl = $this->uri->segment(1) . "/" . $this->uri->segment(2);
    if (array_search($currentUrl, $this->allowedUrl[$userType]) === FALSE) {
        redirect("admin/index");
    }
}

}
</code>```

I tried to add my new method to $allowedUrl variable. But it didn't work. Can any one please give me any idea to solve this problem. I am stuck on it.

答: Did you try to assign the value for $allowedUrl inside __construct function, I think it will work!</p>

Body:
I am working on an existing project developed by codeigniter 2.1.4. When I add a new method to a controller and run it to the browser, it shows nothing. Even other methods under that controller also don't run if new method added to that controller. These controllers extends the following controller:

<?php
class MY_Controller extends CI_Controller {

public $data = array();
public $allowedUrl = array(
"super admin" => array("case_controllerler/deleteSingleCase","case_controller/quickPendingCaseSearch","case_controller/checkUniqueCaseNumber","case_controller/kharijCase","admin/index","case_controller/viewSatalementKhatianCopyApplication", "admin/saveAdmin","admin/addUser", "admin/allAdmin", "admin/suspendUser", "admin/activeUser", "admin/CustomSearchGL","admin/showMethod","admin/CustomSearchAction","admin/deleteUser","admin/showAllComplain","admin/singleAdminInfo","admin/updateAdminInfo","admin/successfullyUpdated","case_controller/downloadPendingCase",
        "case_controller/addCase", "case_controller/store_data", "case_controller/caseSuccessfullyAdded", "case_controller/createCalender",
        "case_controller/workingDaysCalender", "case_controller/editPendingCase","case_controller/saveEditedPendingCase","case_controller/EditmissCase","case_controller/UpdateMisccase",
        "case_controller/pending", "case_controller/allCase", "case_controller/searchCase", "case_controller/singleCase","case_controller/testAjax","case_controller/DeleteLandData","case_controller/SaveNEwLandInfo","case_controller/DeleteApplicantinfo",
        "case_controller/nextDateFromGivenDate","case_controller/downloadArchiveCase","case_controller/sendSms","case_controller/secondSms","case_controller/thirdSms","case_controller/fourthSms","case_controller/fiveSms","case_controller/CustomSms","case_controller/monthAllreadyExit",
        "register_control/AddTohsil","register_control/TohsilEntry","register_control/EditTohsil","register_control/updatetohsil",
        "register_control/AddMouja","register_control/MoujaEntry","register_control/EditMouja","register_control/updateMouja",
        "register_control/AddMutationAsistant","register_control/MutationAsistantEntry","register_control/EditMutationAsistant","register_control/updateMutationAsistant",
        "register_control/AddKhotiyan","register_control/moujaquery","register_control/saveKhotiyan","register_control/saveKhotiyanFile",
        "register_control/FindKhotiyan","register_control/SearchKhotiyan","register_control/DeleteKhotiyan","register_control/Editkhotiyan",
        "register_control/AddNewKhotiyanUnderKhotiyanId","register_control/saveNewKhotiyan","register_control/UpdateKhotiyan","register_control/Getjolmohol",
        "register_control/Tamil","register_control/EntryTamilFormat","register_control/createcellfortamil","register_control/editTamil","register_control/UpdateTamil","register_control/DeleteTamil","register_control/Imgdownload",
        "dashboard/DashboardHome","dashboard/viewFullreport","dashboard/tohsilviewlist","dashboard/tohsilviewlistoverdate","dashboard/namjariviewlist","dashboard/namjariviewlistoverdate","dashboard/kanongopendingviewlist","dashboard/kanongooverdateviewlist","dashboard/aclandPendingeviewlist","dashboard/aclandoverdateviewlist","dashboard/waitingpendingviewlist","dashboard/waitingooverdateviewlist",
        "admin/DeleteComplains","admin/fullviewcomplains", "register_nine/Newentry","register_nine/SaveData","register_nine/Search","register_nine/viewapplication",
    "register_nine/editapplication","register_nine/Deleteapplication","register_nine/Preview","register_nine/UpdateApplication",
    "register_nine/SearchForPreview","register_nine/paginationData","admin/GovLandEntry","admin/savegovtLandInfo","admin/GovLandQuery","admin/govtLandInfoQuery","admin/EditGovtLand",
    "admin/UpdategovtLandInfo","admin/DeleteGovtLandInfo","admin/govtLandInfoQueryByType",
    "case_controller/AddmissCase","case_controller/SaveMissCase","case_controller/MIssCassUpdate","case_controller/UpdateInfoMissCase","case_controller/MiscSmsToplaintiff",
    "case_controller/EditMIssCaseUpdate","case_controller/UpdateStatus","case_controller/DeletemissCasestatus","case_controller/CheckGovtLand",
    "case_controller/FinishMisscase","case_controller/DeletemissCase","case_controller/ArchivemissCase","case_controller/ViewMIssCassUpdate","case_controller/SearchActionByNameOrNId","case_controller/SearchActionBydag",
    "case_controller/SearchmissCase","case_controller/SearchMisscaseAction","case_controller/viewPorcaApplication","case_controller/DeletePorcaapplication","case_controller/ArchivePorcaApplication","case_controller/approvalsms",
    "case_controller/ApprovePoRcaApliCation","case_controller/fullviewPrcaApplication","register_control/RemoveKhotiyanFile","case_controller/SaveMissCaseAttchment",
    "register_control/DeleteKHotiyanFile","register_control/ViewTamil","register_control/NewAddKhotiyanFile","register_control/TamilDownload","register_control/RegisterONe","register_control/FileInventory"
    ,"other_registers/EntryDailyIncome","other_registers/SaveDailyINcome","other_registers/inqueryAndSubmit","other_registers/SearchActionOfInquery","other_registers/DeliveryToBank","other_registers/deliverySuccess",
    "other_registers/searchCashRegister","other_registers/SearchActionregisterthree","other_registers/SearchActionregisterthreebyStauts","other_registers/registerseventeenOfTohsil","other_registers/DemandRegister","other_registers/miscellenousPaymentRegister",
        "other_registers/registerseventeenOfAcland","admin/showAllOpinion","admin/Deleteopinion","admin/fullviewopinion","mutation_controller/DownloadMutationApplication","mutation_controller/AllMutationApplications","mutation_controller/DetailsMutationAppliCation",
   "mutation_controller/accecptApplicationSms","mutation_controller/DeleteMutationApplication","dashboard/TohsilPieChart","other_registers/SavedemandRegisterSix","other_registers/SearchAndDelivaryRegisterSix"
    ,"other_registers/SearchActionOfInqueryRegisterSix","other_registers/RegisterSixDelivery","other_registers/registerSixdeliverySuccess","other_registers/SavePaymentRegisterSeven",
    "other_registers/SearchAndDelivaryRegisterSeven","other_registers/SearchActionOfInqueryRegisterSeven","other_registers/RegisterSevenDelivery","other_registers/registerSevendeliverySuccess","case_controller/ChangeMutationAsistant",
    "case_controller/ActionChangeMutationAsistant","case_controller/FeedbackMiscCaseUpdate","case_controller/FeedbackUpdateInfoMissCase","admin/EditUser","admin/updateAdminInfobySuperAdmin", "case_controller/EditMIssCaseUpdateFeedback",
    "case_controller/UpdateStatusFeedback","case_controller/PrintMIsscassInformation","case_controller/viewArchiveCase","case_controller/deleteArchiveSingleCase","case_controller/RuningMiscCase","dashboard/CaseCounter",
    "other_registers/deleteDailyEntryRegisterThree","other_registers/deleteDailyEntryRegistersix","other_registers/deleteDailyEntryRegisterseven","case_controller/fullviewArchivePrcaApplication","case_controller/OrderSheet","case_controller/SaveOrderInfo","case_controller/PrintOrderSheet",
    "case_controller/ViewLedger","case_controller/ProposalView","case_controller/SaveProposalInfo","case_controller/PrintProposalView","case_controller/CaseNotice","case_controller/PrintNoticeView","case_controller/SecondPagePrintProposalView",
    "case_controller/UpdateCaseLandInfo","case_controller/SaveScratchMap","case_controller/UpdateCaseApplicantInfo","case_controller/TohsilWisePendingCaselist"),

    "admin" => array("case_controller/addCase","case_controller/organizeDateFormat","case_controller/createCalender","case_controller/EditmissCase","case_controller/UpdateMisccase","case_controller/DeleteLandData","case_controller/SaveNEwLandInfo","case_controller/DeleteApplicantinfo",
                        "case_controller/assendingCalender","case_controller/monthAllreadyExit","case_controller/changeDateFromat","case_controller/testAjax","case_controller/nextDateFromGivenDate",
                        "case_controller/store_data","case_controller/caseSuccessfullyAdded","case_controller/allCase","case_controller/searchCase","case_controller/singleCase",
                        "case_controller/pending","case_controller/quickPendingCaseSearch","case_controller/kharijCase","case_controller/editPendingCase","case_controller/saveEditedPendingCase",
                        "case_controller/downloadArchiveCase","case_controller/downloadPendingCase","case_controller/sendSms","case_controller/secondSms","case_controller/thirdSms",
                        "case_controller/fourthSms","case_controller/fiveSms","case_controller/CustomSms","case_controller/checkUniqueCaseNumber","case_controller/AddmissCase","case_controller/MiscSmsToplaintiff","case_controller/ViewLedger","case_controller/CaseNotice",
                        "case_controller/SaveMissCase","case_controller/MIssCassUpdate","case_controller/UpdateInfoMissCase","case_controller/EditMIssCaseUpdate","case_controller/UpdateStatus",
                        "case_controller/FinishMisscase","case_controller/ArchivemissCase","case_controller/ViewMIssCassUpdate","case_controller/RuningMiscCase","case_controller/SaveMissCaseAttchment",
                        "case_controller/SearchmissCase","case_controller/SearchMisscaseAction","case_controller/viewPorcaApplication","case_controller/ArchivePorcaApplication",
                        "case_controller/ApprovePoRcaApliCation","case_controller/fullviewPrcaApplication","case_controller/SearchActionByNameOrNId","case_controller/SearchActionBydag",
                        "case_controller/approvalsms","case_controller/ChangeMutationAsistant","case_controller/ActionChangeMutationAsistant","case_controller/FeedbackMiscCaseUpdate",
                        "case_controller/FeedbackUpdateInfoMissCase","case_controller/EditMIssCaseUpdateFeedback","case_controller/UpdateStatusFeedback","case_controller/PrintMIsscassInformation",
                        "case_controller/viewArchiveCase","case_controller/RuningMiscCase","case_controller/viewSatalementKhatianCopyApplication","case_controller/fullviewArchivePrcaApplication",
                        "dashboard/DashboardHome","dashboard/viewFullreport","dashboard/tohsilviewlist","dashboard/tohsilviewlistoverdate","dashboard/namjariviewlist",
                        "dashboard/namjariviewlistoverdate","dashboard/kanongopendingviewlist","dashboard/kanongooverdateviewlist","dashboard/aclandPendingeviewlist",
                        "dashboard/aclandoverdateviewlist","dashboard/waitingpendingviewlist","dashboard/waitingooverdateviewlist","dashboard/TohsilPieChart","dashboard/CaseCounter",
                        "mutation_controller/AllMutationApplications","mutation_controller/DetailsMutationAppliCation","mutation_controller/DownloadMutationApplication",
                        "mutation_controller/accecptApplicationSms","mutation_controller/DeleteMutationApplication","mutation_controller/MutationForm",
                        "other_registers/EntryDailyIncome","other_registers/SaveDailyINcome","other_registers/inqueryAndSubmit","other_registers/SearchActionOfInquery",
                        "other_registers/searchCashRegister","other_registers/SearchActionregisterthree","other_registers/SearchActionregisterthree","other_registers/SearchActionregisterthreebyStauts",
                        "other_registers/registerseventeenOfTohsil","other_registers/DemandRegister","other_registers/miscellenousPaymentRegister","other_registers/registerseventeenOfAcland",
                        "other_registers/SavedemandRegisterSix","other_registers/SearchAndDelivaryRegisterSix","other_registers/SearchActionOfInqueryRegisterSix","other_registers/RegisterSixDelivery",
                        "other_registers/registerSixdeliverySuccess","other_registers/SavePaymentRegisterSeven","other_registers/SearchAndDelivaryRegisterSeven",
                        "other_registers/SearchActionOfInqueryRegisterSeven","other_registers/RegisterSevenDelivery","other_registers/registerSevendeliverySuccess",
                        "register_control/moujaquery","register_control/getmoujaAndMObile","register_control/AddKhotiyan","register_control/saveKhotiyan","register_control/saveKhotiyanFile",
                        "register_control/NewAddKhotiyanFile","register_control/FindKhotiyan","register_control/SearchKhotiyan","register_control/Editkhotiyan","register_control/UpdateKhotiyan",
                        "register_control/Tamil","register_control/createcellfortamil","register_control/EntryTamilFormat","register_control/editTamil","register_control/UpdateTamil",
                        "register_control/ViewTamil","register_control/Imgdownload","register_control/TamilDownload","register_control/RegisterONe","register_control/Getjolmohol",
                        "admin/index","admin/singleAdminInfo","admin/updateAdminInfo","admin/successfullyUpdated","admin/GovLandEntry","admin/savegovtLandInfo","admin/GovLandQuery","admin/govtLandInfoQuery",
                        "admin/EditGovtLand","admin/UpdategovtLandInfo","admin/govtLandInfoQueryByType","admin/allAdmin","admin/CustomSearchGL","admin/showMethod","admin/CustomSearchAction",
                        "register_nine/Newentry","register_nine/Search","register_nine/viewapplication","register_nine/editapplication","register_nine/UpdateApplication",
                        "register_nine/Preview","register_nine/SearchForPreview","register_nine/paginationData","case_controller/UpdateCaseLandInfo","case_controller/SaveScratchMap","case_controller/UpdateCaseApplicantInfo"),

    "general user" => array("case_controller/quickPendingCaseSearch","case_controller/kharijCase","case_controller/pending", "case_controller/allCase", "case_controller/searchCase", "case_controller/singleCase", "admin/index","case_controller/downloadPendingCase","admin/singleAdminInfo","admin/updateAdminInfo","admin/successfullyUpdated",)
);

public function __construct() {
    parent::__construct();
    $this->isLoggedIn();
    $this->isPermitedToAccess();
}

public function isLoggedIn() {

    if ($this->session->userdata('logged_in') === FALSE) {
        redirect('login/index');
    }
}

//end of the is logged in

public function isPermitedToAccess() {
    $userType = $this->session->userdata("type");
    $currentUrl = $this->uri->segment(1) . "/" . $this->uri->segment(2);
    if (array_search($currentUrl, $this->allowedUrl[$userType]) === FALSE) {
        redirect("admin/index");
    }
}

}

I tried to add my new method to $allowedUrl variable. But it didn't work. Can any one please give me any idea to solve this problem. I am stuck on it.


问:
Doctrine subquery on FROM statement, Symfony 3
New to Doctrine and trying to convert the MySQL query below to queryBuilder.

```<code>SELECT COUNT(t2.user_id) FROM(
    SELECT t2.* FROM logins t2
        WHERE t2.login_time >= DATE_SUB(NOW(),INTERVAL 5 HOUR)
        LIMIT 10
    ) t2
WHERE t2.is_success = 1
</code>```

I've seen a few examples of subquery on the WHERE clause here on SO and attempted to adapt it as per below, but that does not really work.

```<code>        $sub = $this->createQueryBuilder('l')
        ->select('l')
        ->where('l.loginTime >= :date
            and l.userId = :user_id')
        ->setParameters( $parameters )
        ->getDQL();

    $qb = $this->createQueryBuilder('a')
        ->select('count(a.id)')
        ->from( $sub, 'a' )
        ->where('a.isSuccess = 0');
    return $qb->getQuery()->getSingleScalarResult();
</code>```

Thanks

答:
Use this query,</p>

```<code>$date = new Doctrine_Expression('DATE_SUB(NOW() , INTERVAL 5 HOUR)');
$query
->select('count(t2.userId)')
->from('Login', 't2')
->where('t2.loginTime >= :date')
->andWhere('t2.isSuccess = 1')
->setParameter('date',$date);
->setMaxResults(10);
</code>```

Body:
New to Doctrine and trying to convert the MySQL query below to queryBuilder.

SELECT COUNT(t2.user_id) FROM(
    SELECT t2.* FROM logins t2
        WHERE t2.login_time >= DATE_SUB(NOW(),INTERVAL 5 HOUR)
        LIMIT 10
    ) t2
WHERE t2.is_success = 1

I've seen a few examples of subquery on the WHERE clause here on SO and attempted to adapt it as per below, but that does not really work.

        $sub = $this->createQueryBuilder('l')
        ->select('l')
        ->where('l.loginTime >= :date
            and l.userId = :user_id')
        ->setParameters( $parameters )
        ->getDQL();

    $qb = $this->createQueryBuilder('a')
        ->select('count(a.id)')
        ->from( $sub, 'a' )
        ->where('a.isSuccess = 0');
    return $qb->getQuery()->getSingleScalarResult();

Thanks

Body:
Use this query,

$date = new Doctrine_Expression('DATE_SUB(NOW() , INTERVAL 5 HOUR)');
$query
->select('count(t2.userId)')
->from('Login', 't2')
->where('t2.loginTime >= :date')
->andWhere('t2.isSuccess = 1')
->setParameter('date',$date);
->setMaxResults(10);


问:
Don't remove file from repo when is not in local
I'm using Hugo to generate a static website. I have two repos, one with the source of the web, and other with the content generated by Hugo, both hosted in Github.

In the source one I'm using CI to deploy the generated files to the other repos, while in the other I'm using Github pages with a custom domain.

The problem is that every time the script is executes, it deletes the CNAME file for using custom domains.

Here is the script:

```<code>#!/bin/bash
cd ./public

git init
git remote add upstream "https://github.com/user/my-repo.git"
git fetch upstream
git reset upstream/master
git add -A .
git commit -m "web updated"
git push -q upstream HEAD:master
</code>```

I took it from here.

How can I avoid to delete the CNAME file?

Thanks.

答:
First: Make sure CNAME file exists in your public folder before running the script.

Second: You are doing reset your public folder with upstream/master by git reset upstream/master command. So, if CNAME file does not exist in your upstream/master then it should be deleted.

Here, I updated the script, see if it works!

```<code>#!/bin/bash
cd ./public

git init
git remote add upstream "https://github.com/user/my-repo.git"
git fetch upstream
git add -A .
git commit -m "web updated"
git push -q -f upstream HEAD:master
</code>```

Body:
I'm using Hugo to generate a static website. I have two repos, one with the source of the web, and other with the content generated by Hugo, both hosted in Github.

In the source one I'm using CI to deploy the generated files to the other repos, while in the other I'm using Github pages with a custom domain.

The problem is that every time the script is executes, it deletes the CNAME file for using custom domains.

Here is the script:

#!/bin/bash
cd ./public

git init
git remote add upstream "https://github.com/user/my-repo.git"
git fetch upstream
git reset upstream/master
git add -A .
git commit -m "web updated"
git push -q upstream HEAD:master

I took it from here.

How can I avoid to delete the CNAME file?

Thanks.

Body:
First: Make sure CNAME file exists in your public folder before running the script.

Second: You are doing reset your public folder with upstream/master by git reset upstream/master command. So, if CNAME file does not exist in your upstream/master then it should be deleted.

Here, I updated the script, see if it works!

#!/bin/bash
cd ./public

git init
git remote add upstream "https://github.com/user/my-repo.git"
git fetch upstream
git add -A .
git commit -m "web updated"
git push -q -f upstream HEAD:master


问:
Kafka data types of messages
I was wondering about what types of data we could have in Kafka topics.
As I know in application level this is a key-value pairs and this could be the data of type which is supported by the language.
For example we send some messages to the topic, could it be some json, parquet files, serialized data or we operate with the messages only like with the plain text format?

Thanks for you help.

答: On the topic it's always just serialised data. Serialisation happens in the producer before sending and deserialisation in the consumer after fetching. Serializers and deserializers are pluggable, so as you said at application level it's key value pairs of any data type you want. </p>

Title: Kafka data types of messages


问:
Any benefit to starting an Activity via an intent one way versus another?
I know of two ways to start an Activity with an intent. Let's say I'm in Activity A and I want to start Activity B. I could do the following.

1)
In Activity B I have some static method:

```<code>public static Intent newIntent(Context packageContext){
    Intent intent = new Intent(packageContext, ActivityB.class);
    return intent;
}
</code>```

And from Activity A I can call:

```<code>startActivity(ActivityB.newIntent(this));
</code>```

2) The other method is the one I see more often:

From Activity A I do the following

```<code>Intent intent = new Intent(this, ActivityB.class);
startActivity(intent);
</code>```

Are there any benefits or drawbacks to using one versus the other? I think method 1 is a bit cleaner because it keeps the intent information in the class that will actually be started with the intent.

答:
The two approaches do exactly the same thing.

I think the first approach is indeed easier to understand and it's less code. But I think most people got used to the second approach and might be a little confused when they see it like that. This drawback isn't that significant though I don't think.

The thing is, if you use the first approach, you still need to use the second approach if you want to start an activity that you didn't create because you can't just add a static method to an already compiled .class file. This might make your code a little inconsistent.

Also, the name newIntent is kind of confusing. I don't know if it's just me, but doesn't it sound a bit like that you are going from Activity B to A? Maybe just intent?

Body:
I know of two ways to start an Activity with an intent. Let's say I'm in Activity A and I want to start Activity B. I could do the following.

1)
In Activity B I have some static method:

public static Intent newIntent(Context packageContext){
    Intent intent = new Intent(packageContext, ActivityB.class);
    return intent;
}

And from Activity A I can call:

startActivity(ActivityB.newIntent(this));

2) The other method is the one I see more often:

From Activity A I do the following

Intent intent = new Intent(this, ActivityB.class);
startActivity(intent);

Are there any benefits or drawbacks to using one versus the other? I think method 1 is a bit cleaner because it keeps the intent information in the class that will actually be started with the intent.


问:
UIViewController starting below navigation bar moves up after touch
My view (programmatically created) starts below the translucent navigation bar but slides into the desired position when the tableview is touched/scrolled.  My view hierarchy...

```<code>UINavigationController
-- UIViewController (Container)
---- UIPageViewController
------ UIViewController (Detail)
-------- UIImageView
-------- UITableView (with content offset)
</code>```

答:
Maybe there's a problem with UIViewController adjusting tableView insets. Usually when you manage your own insets on tables you should disable viewController from automatically adjusting it:

automaticallyAdjustScrollViewInsets = false

*Note that it's deprecated on iOS11 but for older iOS you should still keep an eye on it.

Body:
My view (programmatically created) starts below the translucent navigation bar but slides into the desired position when the tableview is touched/scrolled.  My view hierarchy...

UINavigationController
-- UIViewController (Container)
---- UIPageViewController
------ UIViewController (Detail)
-------- UIImageView
-------- UITableView (with content offset)


问:
Is there a way to use errno safely in a multi-threaded application?
If you are writing a multi-threaded application that uses system/library calls that make use of errno to indicate the error type, is there a safe way to use errno? If not, is there some other way to indicate the type of error that occurred rather than just that an error has occurred?</p>

答:
man errno says:

errno is defined by the ISO C standard
  to be  a  modifiable  lvalue  of type
  int,  and  must not be explicitly
  declared; errno may be a macro. errno
  is thread-local; setting it in one
  thread  does  not  affect  its value
  in any other thread.

OwnerDisplayName: Erik Öjebo

OwnerDisplayName: qrdl


问:
touchesbegan didn't detected in UIImageView
hi
i have 5 imageviews, all off them are subviews in a navigation bar. i want to get tapcounts from each imageview, so i think i have to use touchesBegan method. but actually, there's no touch event detected in every imageview. precisely, the touchesBegan detected in a toolbar.
the hierarchy are :

UIViewController -> UIToolbar

```<code>             -> UINavigationBar -> UIImageView
</code>```

this is my code :

```<code>-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
int indexSegment = _docSegmentedControl.selectedSegmentIndex;

CGRect frameTouch;

if (indexSegment == 0) {
    frameTouch = frame;
}else if (indexSegment == 1) {
    frameTouch = frame1;
}else if (indexSegment == 2) {
    frameTouch = frame2;
}else if (indexSegment == 3) {
    frameTouch = frame3;
}else if (indexSegment == 4) {
    frameTouch = frame4;
}

UITouch *touch = [touches anyObject];

//--image 0--
CGPoint gestureStartPoint0 = [touch locationInView:imageView];
if (CGRectContainsPoint(frame, gestureStartPoint0)) {
    [NSObject cancelPreviousPerformRequestsWithTarget:imageView selector:@selector(segmentItemTapped:) object:nil];
}else {
    [NSObject cancelPreviousPerformRequestsWithTarget:imageView selector:@selector(segmentItemTapped:) object:nil];
}

//--image 1--
CGPoint gestureStartPoint1 = [touch locationInView:imageView1];
if (CGRectContainsPoint(frame1, gestureStartPoint1)) {
    [NSObject cancelPreviousPerformRequestsWithTarget:imageView1 selector:@selector(segmentItemTapped:) object:nil];
}else {
    NSLog(@"false ");
}

//--image 2--
CGPoint gestureStartPoint2 = [touch locationInView:imageView2];
if (CGRectContainsPoint(frame2, gestureStartPoint2)) {
    [NSObject cancelPreviousPerformRequestsWithTarget:imageView2 selector:@selector(segmentItemTapped:) object:nil];
}else {
    NSLog(@"false ");
}

//--image 3--
CGPoint gestureStartPoint3 = [touch locationInView:imageView3];
if (CGRectContainsPoint(frame3, gestureStartPoint3)) {
    [NSObject cancelPreviousPerformRequestsWithTarget:imageView3 selector:@selector(segmentItemTapped:) object:nil];
}else {
    NSLog(@"false ");
}

//--image 4--
CGPoint gestureStartPoint4 = [touch locationInView:imageView4];
if (CGRectContainsPoint(frame4, gestureStartPoint4)) {
    [NSObject cancelPreviousPerformRequestsWithTarget:imageView4 selector:@selector(segmentItemTapped:) object:nil];
}else {
    NSLog(@"false ");
}
</code>```

}

```<code>-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
int indexSegment = _docSegmentedControl.selectedSegmentIndex;
int counter = [_docsegmentmodels count];
NSLog(@"index di touches ended : %d", indexSegment);

CGRect frameTouch;

if (indexSegment == 0) {
    frameTouch = frame;
}else if (indexSegment == 1) {
    frameTouch = frame1;
}else if (indexSegment == 2) {
    frameTouch = frame2;
}else if (indexSegment == 3) {
    frameTouch = frame3;
}else if (indexSegment == 4) {
    frameTouch = frame4;
}

UITouch *touch = [touches anyObject];

//--image 0--
CGPoint gestureEndPoint0 = [touch locationInView:imageView];
if (CGRectContainsPoint(frame, gestureEndPoint0)) { //mencari bagian yg berimpitan dari posisi tap dengan frame segmen
    if (counter>0){
        if (touch.tapCount <= 2) {
            [self performSelector:@selector(segmentItemTapped:) withObject:nil];
        }
    }else {
        [NSObject cancelPreviousPerformRequestsWithTarget:navBar selector:@selector(segmentItemTapped:) object:nil];
    }
}else {
    NSLog(@"CGRectContaintsPOint0 : %d", CGRectContainsPoint(frame, gestureEndPoint0));
}

//--image 1--
CGPoint gestureEndPoint1 = [touch locationInView:imageView1];
if (CGRectContainsPoint(frame1, gestureEndPoint1)) { //mencari bagian yg berimpitan dari posisi tap dengan frame segmen
    if (counter>0){
        if (touch.tapCount <= 2) {
            [self performSelector:@selector(segmentItemTapped:) withObject:nil];
        }
    }else {
        [NSObject cancelPreviousPerformRequestsWithTarget:navBar selector:@selector(segmentItemTapped:) object:nil];
    }
}else {
    NSLog(@"CGRectContaintsPOint1 : %d", CGRectContainsPoint(frame1, gestureEndPoint1));
}

//--image 2--
CGPoint gestureEndPoint2 = [touch locationInView:imageView2];
if (CGRectContainsPoint(frame2, gestureEndPoint2)) { //mencari bagian yg berimpitan dari posisi tap dengan frame segmen
    if (counter>0){
        if (touch.tapCount <= 2) {
            [self performSelector:@selector(segmentItemTapped:) withObject:nil];
        }
    }else {
        [NSObject cancelPreviousPerformRequestsWithTarget:navBar selector:@selector(segmentItemTapped:) object:nil];
    }
}else {
    NSLog(@"CGRectContaintsPOint2 : %d", CGRectContainsPoint(frame2, gestureEndPoint2));
}

//--image 3--
CGPoint gestureEndPoint3 = [touch locationInView:imageView3];
if (CGRectContainsPoint(frame3, gestureEndPoint3)) { //mencari bagian yg berimpitan dari posisi tap dengan frame segmen
    if (counter>0){
        if (touch.tapCount <= 2) {
            [self performSelector:@selector(segmentItemTapped:) withObject:nil];
        }
    }else {
        [NSObject cancelPreviousPerformRequestsWithTarget:navBar selector:@selector(segmentItemTapped:) object:nil];
    }
}else {
    NSLog(@"CGRectContaintsPOint3 : %d", CGRectContainsPoint(frame3, gestureEndPoint3));
}

//--image 4--
CGPoint gestureEndPoint4 = [touch locationInView:imageView4];
if (CGRectContainsPoint(frame4, gestureEndPoint4)) { //mencari bagian yg berimpitan dari posisi tap dengan frame segmen
    if (counter>0){
        if (touch.tapCount <= 2) {
            [self performSelector:@selector(segmentItemTapped:) withObject:nil];
        }
    }else {
        [NSObject cancelPreviousPerformRequestsWithTarget:navBar selector:@selector(segmentItemTapped:) object:nil];
    }
}else {
    NSLog(@"CGRectContaintsPOint4 : %d", CGRectContainsPoint(frame4, gestureEndPoint4));
}
</code>```

}

is there something i have to define to connect the touchesbegan to the imageviews??
help me please
regards
-Risma-

答:
Oh, man. You're write a lot of duplicated code. This will be scary moment when you will need to change something.

Touch in imageView will detected only if userInteractionEnabled == YES; And you always can use your own class (child of UIImageView) to handle and work with touches.

Body:
hi
i have 5 imageviews, all off them are subviews in a navigation bar. i want to get tapcounts from each imageview, so i think i have to use touchesBegan method. but actually, there's no touch event detected in every imageview. precisely, the touchesBegan detected in a toolbar.
the hierarchy are :

UIViewController -> UIToolbar

             -> UINavigationBar -> UIImageView

this is my code :

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
int indexSegment = _docSegmentedControl.selectedSegmentIndex;

CGRect frameTouch;

if (indexSegment == 0) {
    frameTouch = frame;
}else if (indexSegment == 1) {
    frameTouch = frame1;
}else if (indexSegment == 2) {
    frameTouch = frame2;
}else if (indexSegment == 3) {
    frameTouch = frame3;
}else if (indexSegment == 4) {
    frameTouch = frame4;
}

UITouch *touch = [touches anyObject];

//--image 0--
CGPoint gestureStartPoint0 = [touch locationInView:imageView];
if (CGRectContainsPoint(frame, gestureStartPoint0)) {
    [NSObject cancelPreviousPerformRequestsWithTarget:imageView selector:@selector(segmentItemTapped:) object:nil];
}else {
    [NSObject cancelPreviousPerformRequestsWithTarget:imageView selector:@selector(segmentItemTapped:) object:nil];
}

//--image 1--
CGPoint gestureStartPoint1 = [touch locationInView:imageView1];
if (CGRectContainsPoint(frame1, gestureStartPoint1)) {
    [NSObject cancelPreviousPerformRequestsWithTarget:imageView1 selector:@selector(segmentItemTapped:) object:nil];
}else {
    NSLog(@"false ");
}

//--image 2--
CGPoint gestureStartPoint2 = [touch locationInView:imageView2];
if (CGRectContainsPoint(frame2, gestureStartPoint2)) {
    [NSObject cancelPreviousPerformRequestsWithTarget:imageView2 selector:@selector(segmentItemTapped:) object:nil];
}else {
    NSLog(@"false ");
}

//--image 3--
CGPoint gestureStartPoint3 = [touch locationInView:imageView3];
if (CGRectContainsPoint(frame3, gestureStartPoint3)) {
    [NSObject cancelPreviousPerformRequestsWithTarget:imageView3 selector:@selector(segmentItemTapped:) object:nil];
}else {
    NSLog(@"false ");
}

//--image 4--
CGPoint gestureStartPoint4 = [touch locationInView:imageView4];
if (CGRectContainsPoint(frame4, gestureStartPoint4)) {
    [NSObject cancelPreviousPerformRequestsWithTarget:imageView4 selector:@selector(segmentItemTapped:) object:nil];
}else {
    NSLog(@"false ");
}

}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
int indexSegment = _docSegmentedControl.selectedSegmentIndex;
int counter = [_docsegmentmodels count];
NSLog(@"index di touches ended : %d", indexSegment);

CGRect frameTouch;

if (indexSegment == 0) {
    frameTouch = frame;
}else if (indexSegment == 1) {
    frameTouch = frame1;
}else if (indexSegment == 2) {
    frameTouch = frame2;
}else if (indexSegment == 3) {
    frameTouch = frame3;
}else if (indexSegment == 4) {
    frameTouch = frame4;
}

UITouch *touch = [touches anyObject];

//--image 0--
CGPoint gestureEndPoint0 = [touch locationInView:imageView];
if (CGRectContainsPoint(frame, gestureEndPoint0)) { //mencari bagian yg berimpitan dari posisi tap dengan frame segmen
    if (counter>0){
        if (touch.tapCount <= 2) {
            [self performSelector:@selector(segmentItemTapped:) withObject:nil];
        }
    }else {
        [NSObject cancelPreviousPerformRequestsWithTarget:navBar selector:@selector(segmentItemTapped:) object:nil];
    }
}else {
    NSLog(@"CGRectContaintsPOint0 : %d", CGRectContainsPoint(frame, gestureEndPoint0));
}

//--image 1--
CGPoint gestureEndPoint1 = [touch locationInView:imageView1];
if (CGRectContainsPoint(frame1, gestureEndPoint1)) { //mencari bagian yg berimpitan dari posisi tap dengan frame segmen
    if (counter>0){
        if (touch.tapCount <= 2) {
            [self performSelector:@selector(segmentItemTapped:) withObject:nil];
        }
    }else {
        [NSObject cancelPreviousPerformRequestsWithTarget:navBar selector:@selector(segmentItemTapped:) object:nil];
    }
}else {
    NSLog(@"CGRectContaintsPOint1 : %d", CGRectContainsPoint(frame1, gestureEndPoint1));
}

//--image 2--
CGPoint gestureEndPoint2 = [touch locationInView:imageView2];
if (CGRectContainsPoint(frame2, gestureEndPoint2)) { //mencari bagian yg berimpitan dari posisi tap dengan frame segmen
    if (counter>0){
        if (touch.tapCount <= 2) {
            [self performSelector:@selector(segmentItemTapped:) withObject:nil];
        }
    }else {
        [NSObject cancelPreviousPerformRequestsWithTarget:navBar selector:@selector(segmentItemTapped:) object:nil];
    }
}else {
    NSLog(@"CGRectContaintsPOint2 : %d", CGRectContainsPoint(frame2, gestureEndPoint2));
}

//--image 3--
CGPoint gestureEndPoint3 = [touch locationInView:imageView3];
if (CGRectContainsPoint(frame3, gestureEndPoint3)) { //mencari bagian yg berimpitan dari posisi tap dengan frame segmen
    if (counter>0){
        if (touch.tapCount <= 2) {
            [self performSelector:@selector(segmentItemTapped:) withObject:nil];
        }
    }else {
        [NSObject cancelPreviousPerformRequestsWithTarget:navBar selector:@selector(segmentItemTapped:) object:nil];
    }
}else {
    NSLog(@"CGRectContaintsPOint3 : %d", CGRectContainsPoint(frame3, gestureEndPoint3));
}

//--image 4--
CGPoint gestureEndPoint4 = [touch locationInView:imageView4];
if (CGRectContainsPoint(frame4, gestureEndPoint4)) { //mencari bagian yg berimpitan dari posisi tap dengan frame segmen
    if (counter>0){
        if (touch.tapCount <= 2) {
            [self performSelector:@selector(segmentItemTapped:) withObject:nil];
        }
    }else {
        [NSObject cancelPreviousPerformRequestsWithTarget:navBar selector:@selector(segmentItemTapped:) object:nil];
    }
}else {
    NSLog(@"CGRectContaintsPOint4 : %d", CGRectContainsPoint(frame4, gestureEndPoint4));
}

}

is there something i have to define to connect the touchesbegan to the imageviews??
help me please
regards
-Risma-


问:
How do I reduce the space below my element/text using padding/margin?
my website learning

Hi everybody.

Im martin.

So im learning to use html and CSS but i'm running through some trouble.
if you are able to see my website (practice) that im trying to create, i wish to reduce the space under the word 'I am ______| learner' and under 'contact'.
I have tried to using padding-bottom but i must be doing something wrong, and i have been playing around for way way too long to understand padding,margins and borders but my head is so confused right now!

Thank you everyone!

```<code>/****************************
CSS
*****************************/

#wrapper {
  margin:15% auto;
  padding:5px;
  max-width:1024px;
}
body {
  color:#988;
  background:white;
  font-family: 'oswald', monospace;
}

/****************************
LOGO/HEADING
****************************/
header {
  background:#a0a0a0;
}

#logo {
  text-decoration:none;

}

h1 {
  font-family:'oswald', monospace;
  font-size:2em;
  color:#fff;
  text-align:center;
  margin:1px;
  padding:7px;
  line-height:0.8em;

}
nav {
  font-size:1em;
  background:#d0d0d0;
  text-align:center;
  padding-top:0px;
  margin-bottom:5px;
  line-height: 1.1em;
  padding-bottom:1px;
}

/****************************
nav a links
*****************************/

nav a, nav a:visited {
  color:#FFF;
}

nav a.selected, nav a:hover {
  color:#131c1f;
}
</code>```

答:
Do You use bootstrap ? If Yes, then bootstrap add margin-bottom for every H1. Set:

```<code>h1{
  margin-bottom:0px !important;
}
</code>```

PS. Do not use things like normalize.css ... learn Yourself.

Body:
my website learning

Hi everybody.

Im martin.

So im learning to use html and CSS but i'm running through some trouble.
if you are able to see my website (practice) that im trying to create, i wish to reduce the space under the word 'I am ______| learner' and under 'contact'.
I have tried to using padding-bottom but i must be doing something wrong, and i have been playing around for way way too long to understand padding,margins and borders but my head is so confused right now!

Thank you everyone!

/****************************
CSS
*****************************/

#wrapper {
  margin:15% auto;
  padding:5px;
  max-width:1024px;
}
body {
  color:#988;
  background:white;
  font-family: 'oswald', monospace;
}

/****************************
LOGO/HEADING
****************************/
header {
  background:#a0a0a0;
}

#logo {
  text-decoration:none;

}

h1 {
  font-family:'oswald', monospace;
  font-size:2em;
  color:#fff;
  text-align:center;
  margin:1px;
  padding:7px;
  line-height:0.8em;

}
nav {
  font-size:1em;
  background:#d0d0d0;
  text-align:center;
  padding-top:0px;
  margin-bottom:5px;
  line-height: 1.1em;
  padding-bottom:1px;
}

/****************************
nav a links
*****************************/

nav a, nav a:visited {
  color:#FFF;
}

nav a.selected, nav a:hover {
  color:#131c1f;
}

Body:
Do You use bootstrap ? If Yes, then bootstrap add margin-bottom for every H1. Set:

h1{
  margin-bottom:0px !important;
}

PS. Do not use things like normalize.css ... learn Yourself.