text:
Q: Google Apps Script GmailApp from Web Page I am trying to access Google Apps Script Gmail service with Angular 5.  This is a simple Send an Email function
My GAS code is as follows:
function doGet(e){
    var addressee = e.parameters.addressee;
    var subject = e. parameters.subject;
    var body = e.parameters.body;
    sendEmailNA(addressee, subject, body);
}
function sendEmailNA(addressee, subject, body) {
    GmailApp.sendEmail(addressee, subject, body);
}

My Angular Service:
sendGoogleEmailNoAttach(addressee: string, subject: string, body: string){
return this.http.get('https://script.google.com/macros/s/[script ID here]/exec?addressee='+addressee+'&subject='+subject+'&body='+body);
}

My Angular Component:
sendGoogleEmail(){
    for(var i = 0; i < this.addressees.length; i++){
     this.dataService.sendGoogleEmailNoAttach(this.addressees[i].email, this.message.subject, this.message.body)
    .subscribe((data: any) =>{
        console.log(data);
        this.addressees = [];
        this.message.attachments = [];
   })
   }
}

I then publish it as User accessing the web app and Anyone.
I get no error in Stackdriver Logging.  I simply get a CORS error on the local console which to me historically means an error elsewhere.
Any thoughts or ideas is appreciated.  Thank you.

A: There are a few possible problems that can be happening here. As I do not have enough reputation to comment and ask for more information, as your answer was asked in 2018 and you might have patched it, I will list it down below.
Getting a CORS error has a few reasons which for you, which could be:

*

*Your script ran and returned nothing, though it is unclear whether you have patched it. If your script returned nothing, google script will serve a HTML page saying that the code returned nothing which will trigger a CORS error.

*Your script has encountered an error, which will also cause google script to return a HTML page and also cause a CORS error.

You can test it using hurl.it to see what your script returns, and you can test your script inside the google script editor and set it to possible values.
Hope this is not too late!


text:
Q: SimpleDateFormat Parsing on Android I am trying to parse the following date/time:
Wed, 29 Aug 2018 12:56:00 +0200

Currently, I am using the following code which works on my Android emulator but on my actual phone I get a "java.text.ParseException: Unparseable date"
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
this.pubDate = sdf.parse(s_pubDate);

A: You need to explicitly set the formatter locale, otherwise it would try to pars it based on phone locale and that may cause an error. I think that the cause in your case.
Your emulated device has one locale, while your phone has the one, that can't pars date in such format.
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z",
                    **YOUR DESIRED LOCALE**);

A: java.time
    String dateTimeString = "Wed, 29 Aug 2018 12:56:00 +0200";
    OffsetDateTime dateTime = OffsetDateTime.parse(
            dateTimeString, DateTimeFormatter.RFC_1123_DATE_TIME);
    System.out.println(dateTime);

Output from this snippet is:

2018-08-29T12:56+02:00

The format of the string you want to parse is RFC 1123. This format is built into Java, so spares you the trouble of building your own formatter for parsing. Furthermore RFC 1123 is always in English, so there is no risk that your phone's default locale (or any other locale) interferes.
I am using java.time, the modern Java date and time API. The SimpleDateFormat that you tried to use is not only long outdated, it is also notoriously troublesome.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

*

*In Java 8 and later and on newer Android devices (from API level 26, I'm told) the modern API comes built-in.

*In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).

*On (older) Android use the Android edition of ThreeTen Backport. It's called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

*

*Oracle tutorial: Date Time explaining how to use java.time.

*Java Specification Request (JSR) 310, where java.time was first described.

*ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

*ThreeTenABP, Android edition of ThreeTen Backport

*Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSV read write in Python I have this CSV with me called task2.csv. The header is :Item and Description.
I am trying to add " i", " ink" to this csv using following csv python script. but it is adding to a wrong column and modify the last field.
Please help me make my script start from a fresh new row.
Things I tried:

*

*save the csv with pointer to the new row

*wrote twice ( the second time write function was called it worked correctly. the first write still modifies the last row but second write writes to the new row.

*checked stack overflow and modified the according to few suggestions ( Use dictReader and dictWriter) still did not work

My Code:
import csv

def readCsv(file):
    dict = {}
    with open(file) as csvdata:
        csvReader = csv.DictReader(csvdata)
        for row in csvReader:
            print row['item'], row['description']

def writeCsv(file, field):
    fieldnames = ['item', 'description']
    with open(file, 'a') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writerow({'item': 'i', 'description': 'ink'})

writeCsv("task2.csv", "a")
readCsv("task2.csv")

ORGINAL CSV:

MODIFIED CSV:

A: I could reproduce the issue.
Reason : Your CSV last row is not complete ; The last line is not ended with 'new line` character i.e \n
and to be on safer side chanage writer = csv.DictWriter(f, fieldnames=fieldnames) to

writer = csv.DictWriter(f, fieldnames=fieldnames,
  lineterminator="\n")

Open csv in notepad, press Enter after hati and Save
Run the program then, it should fix the issue.


text:
Q: JPQL Insert by selecting query not working I have two below entity. One is MatchTable another is MatchLog.
@Entity
public class MatchTable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @ManyToOne
    private Integer primaryID;

    @ManyToOne
    private Integer suspectedID;

    @Column(nullable=false)
    private Integer status;

    //getter and setter

}

@Entity
public class MatchLog {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @OneToOne
    private MatchTable referenceID;

    @Column(nullable=false)
    private Long primaryID;

    @Column(nullable=false)
    private Long suspectedID;

    @Column(nullable=false)
    private Integer status;

    //getter and setter
}

If status of MatchTable change,these row will be inserted into MatchLog. I have tried with the below JPQL query.
@Query("INSERT INTO MatchLog (referenceID.id,primaryID,suspectedID,status) SELECT id,primaryID,suspectedID,status from MatchTable where (primaryID = :ID or suspectedID = :ID)")
int updateMatchLogTable(@Param("ID") long ID);

But this JPQL query is not working. Please suggest me what will be the JPQL query to insert change rows from MatchTable to MatchLog.

A: Unless I'm mistaken, JPA does not support "insert into select". You can change as native query.


text:
Q: Spring Boot does not serve a html pages I am developing single page angular application, right now i need to serve the static html index page to my client, this is what i have done:
I am using this configuration:
    @Configuration
    @EnableAutoConfiguration
    @EnableWebMvc
    @EnableCaching
    @ComponentScan(basePackages = "com.example.*")
    public class DemoJPAConfig extends WebMvcConfigurerAdapter {

        @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
                                 registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
.
.
.

Controller:
 */
    @Controller
    public class MainController {
    //mapping for index html template
    @RequestMapping("/")
    public String getIndexPage() {
           return "static/app/index.html";
    }
    //mapping for all other templates
    @RequestMapping("/templates/{name}/{component}")
        public String getPage(@PathVariable("name") String name,
                              @PathVariable("component") String component) {
            return "/static/"+name + "/"+component+".html";
     }

I use spring boot 1.3.2
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.2.RELEASE</version>
        <relativePath/>
        <!-- lookup parent from repository -->
    </parent>

I recive 500 server error status with this message

Could not resolve view with name 'static/app/index.html' in servlet
  with name 'dispatcherServlet'

A: Got it! The problem was in @EnableWebMvc annotation
Here is a link to the reference in the documentation.


text:
Q: Huge spacing when using "clear:both"? I'm using so many styles that I don't know of a simple way to post it, but it's basically like this:
I have an image floating to the right and some text to the left. I tried adding "clear:both" to the H2 tags that separate the major text sections, but that went weird so I tried an HR tag instead (which also uses clear:both). In both cases I end up with a ridiculous amount of spacing which I didn't expect.
The page is here:
http://www.goodpricescome.com/this_site.php
You can see the weird spacing right after the first image/text section. Even in the inspector, I just don't see what's happening here.

A: #content is not floated and its previous sibling #sidebar is floated. In this case, the clearing element inside #content takes #sidebar into account. Here is the expected result when (i) sidebar is shorter than pre-clear content (ii) sidebar is taller than pre-clear content:
content content content content sidebar sidebar
content content content content sidebar sidebar
content content content content content content
content content content content content content
----- clearing hr  ----

content content content content sidebar sidebar
content content content content sidebar sidebar
                                sidebar sidebar
                                sidebar sidebar
----- clearing hr  ----

Use one of the following solutions:

*

*preferably add float: left to #content

*add overflow: hidden to #content

A: 1) #sidebar is floated but #content is not floated hence you are getting so much space so you need to add #content{ float: left; }
2) as in #content you image is floated but p is not floated hence margin of HR is not taking effect hence best way here is on hr add float:left but keep width: 100% so it will cover full width of #content
CSS
#content{
float: left;
}

hr{
float: left;
width: 100%;
/*clear:both*/
}


text:
Q: Why $\sum_{k=1}^\infty \left\lfloor\frac{n}{p^k}\right\rfloor≤\frac{n}{p-1}$? I need some help: can someone tell me why
$$\sum_{k=1}^\infty \left\lfloor\frac{n}{p^k}\right\rfloor≤\frac{n}{p-1}$$
I found this inequality in Wikipedia, and I want to know if it's true, thanks!

A: $$\left\lfloor\frac{n}{p^k}\right\rfloor\leq \frac{n}{p^k} $$
and:
$$\sum_{k\geq 1}\frac{1}{p^k}=\frac{1}{p-1}.$$


text:
Q: How can I get HTML elements by class in JavaScript? I'm trying to manipulate the HTML through getElementsByClass() but for some reason it doesn't work. When I use document.getElementByID() it works? Why is this?

Welcome to the site.

A: Try:
document.getElementsByClassName('boldStuff')[0]

A: getElementsByClassName returns a NodeList. you will have to use
document.getElementsByClassName('boldStuff')[0].innerHTML
refer the docs at mdn

A: Here's a widely supported solution:
function getElementsByClassName( root, clss ) {

    var result = [], els, i;

    if( arguments.length < 2 || !root || !clss || root.nodeType !== 1 ) {
        return result;
    }

    clss = clss + '';

    if( root.getElementsByClassName ) {
        result = root.getElementsByClassName( clss );
    } else if( root.querySelectorAll ) {
        result = root.querySelectorAll( '.' + clss );
    } else {
        els = root.getElementsByTagName('*');
        clss = " " + clss + " ";
        for( i = 0; i < els.length; ++i ) {
            if( ( " " + els[ i ].className + " " ).indexOf( clss ) !== -1 ) {
                result.push( els[ i ] );
            }
        }
    }
    return result;
}

Then use it like this:
var bold = getElementsByClassName( document, "boldStuff" );

for( var i = 0; i < bold.length; ++i ) {
    bold[ i ].innerHTML = 'Fred Flinstone';
}

The benefit to this is that it uses the native methods wherever possible.

*

*It first tries getElementsByClassName because it is generally fastest.

*Then it tries querySelectorAll, which will bring in support for IE8.

*Finally, it does a manual filtering of all elements under the provided root.

A: It returns an array so set the first element of the array's innerHTML
document.getElementsByClassName('boldStuff')[0].innerHTML = 'Fred Flinstone';

A: The correct method to call is getElementsByClassName(), and it will give you an array of elements.
document.getElementsByClassName('boldStuff')

Anyway this is not compatible with older IE version. Check the compatibility here.


text:
Q: What is the best way to set up multiple iPod / iPhones on the same computer? I have an iPod sync and my wife just got an iPhone.  Before I set up her iPhone, I want to make sure I don't mess anything up.  I have a few questions:

*

*Should I create a separate Apple ID for her, or have her use my id?

*Is there anything else I need to worry about to make sure it recognizes her account and sync info and mine and doesn't get confused?

I see a few horror stories on the web and just want to make sure I do this right.

A: You can do the Apple ID any way you like. If you use the same ID on both devices, then you can sync all the Purchased apps to both devices.
I'm using my iTunes to manage and backup the iPhone of my girlfriend and my iPhone. We have separate ID's and iTunes never got confused.
Update
Oh and remember, if you setup up separate ID's then you still can sync all apps from both accounts, but you can't update the apps from your Wife's account on your iPhone, because your phone is set to your account.
This can be avoided by updating all apps through iTunes, though.

A: While there are (too) many ways to setup multiple iDevices on the same machine, the simplest way and most headache free is having a single account on all devices synced to the same machine. That way you can sync everything everywhere easily.
If you want to have separate accounts, set separate users on the machine and then you can setup different iTunes/Apple accounts on each computer user. But that will give issues with syncing contents. Apple is not very good with sharing content with other people - but they're trying to get better on it at least with family members.

A: For me, the least confusing way is to setup both separate iTunes accounts and separate computer logins for both people. That way "your" iTunes will only see your iPad and know about your iTunes account, applications, data, etc. and "her" iTunes will only see her iPhone and know about her iTunes account, applications, data, etc.
This also gives both of you your own space on the computer -- not to keep secrets, right -- but so you can have your stuff organized and she can have her stuff organized.


text:
Q: How to get known properties of an object nested in another object? Keys of books object are automatically generated by Firebase.
{
  books: {
    -LKsSspLai8tTppJjSiE: {
      author: 'Author 1',
      name: 'Book 1'
    },
    -LKsS15TMhGRQXlZZlkE: {
      author: 'Author 2',
      name: 'Book 2'
    },
    {}, {}...
  }
  timestamp: 1535579350
}

I have no problem with accessing first level properties, but how can I create an array from books object for further looping over authors and names?

A: You can use Object.values(books), then loop through that array.
Object.values(books).forEach( (book) => {
    // now you have book.author and book.name
});

A: If you want to convert an object's values into an array (as you asked), you could use lodash:

const a = {
  books: {
    "-LKsSspLai8tTppJjSiE": {
      author: 'Author 1',
      name: 'Book 1'
    },
    "-LKsS15TMhGRQXlZZlkE": {
      author: 'Author 2',
      name: 'Book 2'
    },
  },
  timestamp: 1535579350
}

console.log( _.values(a.books) )
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>


text:
Q: How to persist all versions of an entity by JPA? I am working on auditing the changes of an entity, say PersonEntity.
Existing codes support creating or editing a person's profile and persisting the corresponding PersonEntity. If editing, it will update the PersonEntity in database. It also supports get query of the persons based on a few properties like age. Furthermore, it also provides API to set the "created by", "updated by" and "updated time" - generally it is quite auditable.
My work is to make it even more auditable by persisting all the old versions of a PersonEntity. I think I have two options:

*

*Persist a new PersonEntity even if editing. In that way, all versions of PersonEntity are in the database. I should also, 1) add a property in the PersonEntity to indicate whether it is the up-to-date one; 2) when creating or updating PersonEntity, I need to set that flag; 3) change all the query methods to only get PersonEntity that is up-to-date.

In my view that is not a good option since 3) will cause a bunch of code change, and will slow down the query as well.

*Creating a new class with the same property as PersonEntity, say PersonAuditEntity. When creating or updating PersonEntity, always persist one new PersonAuditEntity.

But in that way, two similar classes are existing in the same time. My initial solution is to simply wrap a PersonEntity into PersonAuditEntity, but it seems that JPA does not support embed an entity in another entity. Is that right?
Any other suggestions will be highly appreciated.

A: Did you take a look at Hibernate ORM Envers? This supports auditing the entities like for eg:
@Audited
private String name;

Will record changes to name atribute for the entity.

A: Another option.
Add a new column which gets set to inactive when the row is replaced with a new one. Only add new rows and never update a row.
All selects need to use an additional where clause "and inactive = false"


text:
Q: With PyMongo how do I import indexes using create_index() that were exported with index_information()? What do you need to do to the output of index_information() such that it can then be re-imported using create_index() or create_indexes() ?
>>> from pymongo import MongoClient
>>> client = MongoClient("mongodb://host1")
>>> db = client.MYDB
>>> collection = db.MYCOLLECTION
>>> index = db.provisioning.index_information()
>>> index
{u'_id_': {u'ns': u'MYDB.MYCOLLECTION', u'key': [(u'_id', 1)], u'v': 1}, u'Name_1': {u'unique': True, u'key': [(u'Name', 1)], u'v': 1, u'ns': u'MYDB.MYCOLLECTION', u'background': False}, u'MongoType_1': {u'key': [(u'MongoType', 1)], u'ns': u'MYDB.MYCOLLECTION', u'background': False, u'v': 1}}
>>> client2 = MongoClient("mongodb://host2")
>>> db2 = client2.MYDB
>>> collection2 = db2.MYCOLLECTION
>>> collection2.create_index(index)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/site-packages/pymongo/collection.py", line 1161, in create_index
    keys = helpers._index_list(keys)
  File "/usr/lib64/python2.6/site-packages/pymongo/helpers.py", line 55, in _index_list
    raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list
>>> collection2.create_indexes(index)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/site-packages/pymongo/collection.py", line 1046, in create_indexes
    raise TypeError("indexes must be a list")
TypeError: indexes must be a list

A: Try this basic code, this will iterate and add all index from one collection to other collection,
from pymongo import MongoClient

client = MongoClient("mongodb://host1")
db = client.MYDB
collection = db.MYCOLLECTION
index = db.provisioning.index_information()

client2 = MongoClient("mongodb://host2")
db2 = client2.MYDB
collection2 = db2.MYCOLLECTION
for i in index.keys():
    name_index = index[i]['key'][0][0]
    order = index[i]['key'][0][1]
    collection2.create_index([(name_index, order)])


text:
Q: Showing that the absolute value of |X| converges almost surely. Here is my question and my solutions. I am just curious if this makes sense.

If something is wrong, then it will be nice if you can correct it for me or provide another solution. Please and thank you!

A: To elaborate on copper.hats comment, if $\mathbb P(X>10)>0$ then there exists some integer $m$ such that $\mathbb P\left(X>10+\frac1m\right)$. But this implies that $\mathbb P\left(|X-X_m|\geqslant \frac1m\right)$, and contradicting the assumption that
$$
\lim_{n\to\infty}P\left(|X-X_n|\geqslant \frac1n\right) = 0.
$$


text:
Q: emacs dispatch help window from original buffer Whenever I do apropos, describe-key, or some other help function in emacs, it displays the help in my other window. In order to get rid of it, I must change windows/buffers to go there, type "q", and then change back to my original working buffer.
Is there a way I can do this in code somehow?  I know how to save-excursion, switch buffers, etc, but I don't know how to send the "q" to the minibuffer/emacs while I'm over in the other buffer. Thanks

A: The help-window-select variable might be exactly what you want.
If you set its value to true (setq help-window-select t) then the help window will automatically be selected when you open it via one of the help commands. You can then press q to quit out of it and go back to your original buffer. There are many other options so you should check those out too.
For the apropos window or any window that uses display-buffer you can use.
(add-to-list 'display-buffer-alist
         '("*Apropos*" display-buffer-same-window))

display-buffer-same-window is one options of many; it opens the buffer in the current window. The other possible options can be seen by looking up the docs on the display-buffer function.

A: I suggest putting (winner-mode 1) in your init file, and then using C-c<left> to call winner-undo (repeatedly, if necessary) to return to a previous window configuration.

A: Here's my solution to this problem.  I bind this command to C-c q:
(defvar my/help-window-names
  '(
    ;; Ubiquitous help buffers
    "*Help*"
    "*Apropos*"
    "*Messages*"
    "*Completions*"
    ;; Other general buffers
    "*Command History*"
    "*Compile-Log*"
    "*disabled command*")
  "Names of buffers that `my/quit-help-windows' should quit.")

(defun my/quit-help-windows (&optional kill frame)
  "Quit all windows with help-like buffers.

Call `quit-windows-on' for every buffer named in
`my/help-windows-name'.  The optional parameters KILL and FRAME
are just as in `quit-windows-on', except FRAME defaults to t (so
that only windows on the selected frame are considered).

Note that a nil value for FRAME cannot be distinguished from an
omitted parameter and will be ignored; use some other value if
you want to quit windows on all frames."
  (interactive)
  (let ((frame (or frame t)))
    (dolist (name my/help-window-names)
      (ignore-errors
        (quit-windows-on name kill frame)))))


text:
Q: how to solve java.lang.NoSuchFieldError: RETURN_NULL_AND_BLANK in java public class SpreadsheetGenerator {
void dailyreport( Connection con) throws SQLException, IOException {
    Statement statement = con.createStatement();
    ResultSet resultSet = null;
    try {
        resultSet = statement.executeQuery("select * from ssa_msg_daily");
    } catch (Exception e) {

    } finally {
        ResultSet resultSet = statement.executeQuery("select * from ssa_msg_daily");
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet spreadsheet = workbook.createSheet("employe db");

        XSSFRow row = spreadsheet.createRow(1);
        XSSFCell cell;
        cell = row.createCell(1);
        cell.setCellValue("id");
        cell = row.createCell(2);
        cell.setCellValue("Sender");
        cell = row.createCell(3);
        cell.setCellValue("Service");
        cell = row.createCell(4);
        cell.setCellValue("Message_identifier");
        cell = row.createCell(5);
        cell.setCellValue("Date");
        cell = row.createCell(6);
        cell.setCellValue("Incoming");
        cell = row.createCell(7);
        cell.setCellValue("Outgoing");
        int i = 2;

        while (resultSet.next()) {
            row = spreadsheet.createRow(i);
            cell = row.createCell(1);
            cell.setCellValue(resultSet.getInt("id"));
            cell = row.createCell(2);
            cell.setCellValue(resultSet.getString("Sender"));
            cell = row.createCell(3);
            cell.setCellValue(resultSet.getString("Service"));
            cell = row.createCell(4);
            cell.setCellValue(resultSet.getString("Message_identifier"));
            cell = row.createCell(5);
            cell.setCellValue(resultSet.getDate("Date"));
            cell = row.createCell(6);
            cell.setCellValue(resultSet.getString("Incoming"));
            cell = row.createCell(7);
            cell.setCellValue(resultSet.getString("Outgoing"));
            i++;
        }

        FileOutputStream out = new FileOutputStream(new File("exceldatabase.xlsx"));
        workbook.write(out);
        out.close();
        System.out.println("exceldatabase.xlsx written successfully");
    }
    }

}

here ssa_msg_daily contains blank or null values in the table,so
while compiling i am getting error as
Exception in thread "main" java.lang.NoSuchFieldError: RETURN_NULL_AND_BLANK
occurs @ XSSFWorkbook workbook = new XSSFWorkbook();
how can i handle this situation and
i am using the resultset to convert to spreedsheet  using apache poi

A: You've got a classpath issue. You have a mix of versions of the Apache POI project on your classpath. This mix of versions is causing a newer version of one of the classes to try to talk to one of the older ones and they aren't compatible.
The solution is to check your classpath (so, if you're using maven, gradle, or some other dependency system, the chain of dependencies), and fix it up. Possibly it's as simple as running a 'clean' command on your build system.
NB: Your code is very bad style - don't put a ton of code in finally blocks. Furthermore, 99.9% of your paste is a red herring. This one-liner will cause your problem already:
XSSFWorkbook workbook = new XSSFWorkbook();

The rest is irrelevant.

A: Maybe you will try with "try" and "catch".
public class SpreadsheetGenerator {
void dailyreport( Connection con) throws SQLException, IOException {
Statement statement = con.createStatement();
ResultSet resultSet = null;
try {
    resultSet = statement.executeQuery("select * from ssa_msg_daily");
} catch (Exception e) {

}
    //ResultSet resultSet = statement.executeQuery("select * from ssa_msg_daily");
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet spreadsheet = workbook.createSheet("employe db");

    XSSFRow row = spreadsheet.createRow(1);
    XSSFCell cell;
    cell = row.createCell(1);
    cell.setCellValue("id");
    cell = row.createCell(2);
    cell.setCellValue("Sender");
    cell = row.createCell(3);
    cell.setCellValue("Service");
    cell = row.createCell(4);
    cell.setCellValue("Message_identifier");
    cell = row.createCell(5);
    cell.setCellValue("Date");
    cell = row.createCell(6);
    cell.setCellValue("Incoming");
    cell = row.createCell(7);
    cell.setCellValue("Outgoing");
    int i = 2;

    if(resultSet!=null){
    while (resultSet.next()) {
        row = spreadsheet.createRow(i);
        cell = row.createCell(1);
        cell.setCellValue(resultSet.getInt("id"));
        cell = row.createCell(2);
        cell.setCellValue(resultSet.getString("Sender"));
        cell = row.createCell(3);
        cell.setCellValue(resultSet.getString("Service"));
        cell = row.createCell(4);
        cell.setCellValue(resultSet.getString("Message_identifier"));
        cell = row.createCell(5);
        cell.setCellValue(resultSet.getDate("Date"));
        cell = row.createCell(6);
        cell.setCellValue(resultSet.getString("Incoming"));
        cell = row.createCell(7);
        cell.setCellValue(resultSet.getString("Outgoing"));
        i++;
    }}

    FileOutputStream out = new FileOutputStream(new File("exceldatabase.xlsx"));
    workbook.write(out);
    out.close();
    System.out.println("exceldatabase.xlsx written successfully");
}
}

}


text:
Q: Change text value by clicking drop down list - JQuery http://jsfiddle.net/ZbcVH/1/
HTML

United Kingdom

France

Germany

<input tpye="text" id="location" />

Jquery
$('#locationselect').click(function() {
    $('#location').html($(this).val());
});

As demonstrated in the link above, I basically want to select the value from the unordered list items, id="locationselect" and then put the selected list item's value into the id="location" text box. I'm not too sure where I'm going wrong.
I'm sure it's something simple. I've tried looking at other questions to help, but it doesn't seem to be clicking.
Thanks for any help!

A: You need .text instead of .val to retrieve the value, .val instead of .html to set the value, and you need to bind onto the li instead of the parent div:
$('#locationselect li').click(function() {
    $('#location').val($(this).text());
});

A: Try this code. In the input, use val() to change the value. And get text() on your li.
jsFiddle here
$('document').ready(function(){
    $('#locationselect li').click(function() {
        $('#location').val($(this).text());
    });
});

or with .on
$('document').ready(function(){
    $('#locationselect li').on('click',function() {
        $('#location').val($(this).text());
    });
});

A: Place the listener on the li element itself and then fetch the text from that.
Try this solution:

United Kingdom

France

Germany

<input tpye="text" id="location" />

$('#locationselect li').click(function() {
    $('#location').val($(this).text());
});

See updated JSFiddle: http://jsfiddle.net/WYUSn/

A: As you can see from http://jsfiddle.net/ZbcVH/8/ there were two mein errors:
You need to use li instead of #locationselect and you should use .text() instead of .val().


text:
Q: Finding if a value falls within a range, using bitwise operators in C So i am working on this method, but am restricted to using ONLY these operators:
<<, >>, !, ~, &, ^, |, +
I need to find if a given int parameter can be represented using 2's complement arithmetic in a given amount of bits.
Here is what I have so far:
int validRange(int val, int bits){
    int minInRange = ~(1<<(bits + ~0 ))+1;   //the smallest 2's comp value possible with this many bits
    int maxInRange = (1<<(bits+~0))+~0;  //largest 2's comp value possible
    ..........
}

This is what I have so far, and all I need to do now is figure out how to tell if minInRange <= val <=maxInRange. I wish I could use the greater than or less than operator, but we are not allowed. What is the bitwise way to check this?
Thanks for any help!

A: Two's complement negative numbers always have a '1' in their high bit.
You can convert from negative to positive (and vice versa) by converting from FF -> 00 -> 01. That is, invert the bits, add 1. (01 -> FE -> FF also works: invert the bits, add 1)
A positive number can be represented if the highest set bit in the number is within your range. (nbits - 1: 7 bits for an 8 bit signed char, etc.)
I'm not sure if your constraints allow you to use arrays. They would speed up some things but can be replaced with loops or if statements.
Anyway, if 1 << (NUM_INT_BITS-1) is set on your input, then it's negative.
Invert, add one.
Now, consider 0. Zero is a constant, and it's always the same no matter how many bits. But if you invert 0, you get "all the bits" which changes by architecture. So, ALL_BITS = ~0.
If you want to know if a positive number can be represented in 2 bits, check to see if any bits greater than or equal to bit 2 are set. Example:
two_bits = 0b00000011
any_other_bits = ~two_bits # Result: 0b11...11100
if positive_number & any_other_bits
    this number is too fat for these bits!

But how do you know what ~two_bits should be? Well, it's "all set bits except the bottom however-many". And you can construct that by starting with "all set bits" and shifting them upwards (aka, "left") however-many places:
any_other_bits = ~0 << 2  # where "2" is the number of bits to check

All together now:
if (val & ((unsigned)INT_MAX + 1))
    val = ~val + 1;

mask = ~0 << bits;
too_wide = val & mask;
return !too_wide;

A: To test if a number can be represented in a N-bit 2s compliment number: Simply test that either

*

*The number bitwise-and'ed with the compliment of a word with the low (N-1) bits set is equal to zero

*OR The high InputBitWidth-(N-1) bits of the number are 1s.

 mask=(1<<(bits-1))-1; return ( !(val&mask) | !((val&~mask)^~mask) );


text:
Q: Trying to load pickled data to a list isn't appending properly I'm writing a to-do list application, and to store the class objects task I'm pickling a list of the objects created. However, when I load the data, the list appears empty. The way I structured it is to create an empty list each session, then append the contents of the pickle file. When new tasks are created, they are appended and the whole list is then appended and then reloaded.
This is my first real software project, so my code looks pretty rough. I reviewed it and can't find any glaring errors, but obviously I am doing something wrong.
Here is the relevant code:
import _pickle as pickle
import os.path
from os import path
from datetime import datetime

#checks if data exists, and creates file if it does not
if path.exists('./tasks.txt') != True:
    open("./tasks.txt", 'wb')
else:
    pass

#define class for tasks
class task:
    def __init__(self, name, due, category):
        self.name = name
        self.due = datetime.strptime(due, '%B %d %Y %I:%M%p')
        self.category = category
    def expand(self): # returns the contents of the task
        return str(self.name) + " is due in " + str((self.due - datetime.now()))

data = []
# load data to list
def load_data():
    with open('tasks.txt', 'rb') as file:
        while True:
            data = []
            try:
                data.append(pickle.load(file))
            except EOFError:
                break
...

# returns current task list
def list_tasks():
    clear()
    if not data:
        print("Nothing to see here.")
    else:
        i = 1
        for task in data:
            print("%s. %s" % (i, task.expand()))
            i = i+1

#define function to add tasks
def addTask(name, due, category):
    newTask = task(name, due, category)
    data.append(newTask)
    with open('./tasks.txt', 'wb') as file:
        pickle.dump(data, file)
    load_data()
    list_tasks()

...

load_data()
list_tasks()
startup()
ask()

A: data = []
# load data to list
def load_data():
    with open('tasks.txt', 'rb') as file:
        while True:
            data = []
            try:
                data.append(pickle.load(file))
            except EOFError:
                break

That second data = [] doesn't look right. Having data = [] both inside and outside of the function creates two data objects, and the one you're appending to won't be accessible anywhere else. And even if it was accessible, it would still be empty since it's being reset to [] in every iteration of the while loop. Try erasing the inner data = []. Then the data.append call will affect the globally visible data, and its contents won't be reset in each loop.
Additionally, going by the rest of your code it looks like that data is supposed to be a list of tasks. But if you pickle a list of tasks and then run data.append(pickle.load(file)), then data will be a list of lists of tasks instead. One way to keep things flat is to use extend instead of append.
data = []
# load data to list
def load_data():
    with open('tasks.txt', 'rb') as file:
        while True:
            try:
                data.extend(pickle.load(file))
            except EOFError:
                break

I think it may also be possible to load the data with a single load call, rather than many calls in a loop. It depends on whether your tasks.txt file is the result of a single pickle.dump call, or if you appended text to it multiple times with multiple pickle.dump calls while the file was opened in "append" mode.
def load_data():
    with open('tasks.txt', 'rb') as file:
        return pickle.load(file)
data = load_data()


text:
Q: First build with Azure Devops I'm running builds with AzureDevops piplines. When I'm creating new pipline I'm not queueing it and just saving. If CI trigger is selected pipline will run if anything is checked in.
But on the very first run/chack-in pipline will be liked (associated) to ALL check-ins (changesets/commits) that happened before the current one and to all workitems of those chack-ins.
This behaviour is not desired for me. Is there a way to disable it?
On all subsequent check-ins build will be associated only with the one that triggered the pipline. And this is what I want for the first build as well, for it to be associated only with the chack-in that triggered it.

A: Without seeing exactly what's happening, it's hard to provide advice.  It could also behave differently if you're using Git or TFSVC variants.  Here's a few things to try:

*

*Disable the CI trigger, do your first check-in, then re-enable the trigger.  That might skip the change-set and work item affiliation one time.

*Delete the offending build after it runs or do the laborious task of manually deleting all links in it.

*If you're using Git, you can also limit the CI trigger by using a Pull Request with Squash merge.  This will consolidate the commits down to one.

A: There isn't the way to disable it. It would compare previous run, then include all changesets between them. So, for first run, it must includes all previous changesets.
You may create a new branch for a folder, then configure build for that branch. Learn about branching strategies for Team Foundation Version Control (TFVC) and how to select an effective strategy


text:
Q: File upload service using WCF along with jquery(AJAX) and html client I would like to know how to upload a file using WCF by making an AJAX call using jquery.

A: You can use some ready-to-use JQuery plugin. For example, AjaxFileUpload


text:
Q: Modify sed so as to assign unique fileparts into variable I have a folder with several different filenames, each with a common pattern such as the following :
SampleA-1.txt
SampleA-2.txt
SampleA-3.txt
SampleB-1.txt
SampleB-2.txt
SampleB-3.txt
etc
I want to use sed in order to get only the unique filename before the "-number.txt" part. In other words I want the following result :
SampleA
SampleB
SampleC
etc
And I want to assign the above in a variable (e.g SAMPLE) inside a for loop. So I have the following :
    for FILE in $HOME_PATH/*.txt
do
    SAMPLE=`basename $FILE | sed s/\.1.txt//`

which does exactly what I want but obviously only when I have the Sample*-1.txt files, not the-2 or -3s inside the $HOME_PATH. Essentially I want to delete everything after the "-" and assign the unique names into the variable. Can you please suggest modifications to my sed ? I am sure it is something easy to do but I tried several variations with no success so I am missing something obvious here.
Thanks in advance for the effort!

A: VAR="$(
    for f in $HOME_PATH; do
        basename $f | sed -n "s/\-[0-9]\+\.txt//p";
    done | sort | uniq )"
echo "$VAR"

This loops through all the files as your previous example did, and truncates the -1.txt sections (except the [0-9]\+ matches any number at the back).
This only prints filenames that match the pattern: the -n means don't print anything by default, and the /p at the end of the sed statement tells it to print if it does find a match
At this point, you have a list that looks like: SampleA SampleA SampleA SampleB SampleB SampleB
It then pipes the output to sort (in case they're out of order), and then to uniq, which removes any duplicate entries (note -- uniq requires sorted input).   This give you the output
 SampleA
 SampleB

This is then assigned to $VAR

A: No sed needed, using only parameter expansion:
for file in "$dir"/*.txt; do
    sample=${file##*/}
    sample=${sample%-*}
done


text:
Q: How to determine if two lists share any objects with Hibernate I have this example SQL query that I created that tries to find all REPORTs that have an associated REPORT_PERMISSION object with one of the USER_GROUPs that the current user also has.  So there are many REPORT_PERMISSION objects that tie a report to a group, and a user can have many groups, just one of those have to match up to allow the user to view the report. I'm just not sure how to write this in HQL
SELECT * FROM REPORT r
JOIN REPORT_PERMISSION rp
    on r.id = rp.report_id and rp.user_group_id in
        (SELECT l.user_group_id FROM USER_GROUP_LINK l where l.user_id = 2)
where r.type = 'GENERAL';

A: it should be something like :
Query reportQuery = entityManager.createQuery
   ("select distinct rep from Report rep
                         join rep.reportPermissions per
                         join per.userGroups gr
                         join gr.users u
                         where u.id = :userId and rep.type = 'GENERAL'");
reportQuery.setParameter("userId" , user.getId());

example mapping (names that are used in hql , and fileds name in mappings ) :
rep.reportPermissions -- Collection < ReportPermission> reportPermissions in Report;
per.userGroups        -- Collection < UserGroup> userGroups in ReportPermission;
gr.users             -- Collection < User> users in UserGroup;
u.id                 -- @Id Long id; in user class


text:
Q: jQuery Issue with animate and Chrome here is another thread for jQuery and positions in Chrome :D. I read some, but i couldnt figure out a solution.
function sliderCarousel(){

var count = $('#liste2').children().length; // Numbers of Elements in the Slider
var jump = $('#liste2 li:first').outerWidth(true); // Width of a single Element, including Margin(!)
var resultWidth = count * jump; // Width of all Elements in the Slider.
$('#liste2').width(resultWidth); // Sets the width of the ul to the calculated. Because the slider should work with a various number of Elements
                                 // you cant set a default width.
var unseenElementsNumber = Math.round((-1)*(resultWidth - $('#ein').width())/jump) - 1; // calculates the number of Sliderelements, which are hidden
var unseenElementsWidth = unseenElementsNumber * jump; // calculates the widht of unseen elements

    if(unseenElementsNumber >= 0)
    {
        $('#go').click(function() //rotate left
        {
            if(parseInt($('#liste2').css("left").replace("px","")) + 80 <= 0) // needed to prevent "overscrolling"
            {
                $('#liste2').animate({
                "left": "+="+jump+"",
                }, 500 ); // speed of rotation
            }
        });

        $('#back').click(function() // rotate right
        {
            if(parseInt($('#liste2').css("left").replace("px","")) - 80 >= unseenElementsWidth) // needed to prevent "overscrolling"
            {
                $('#liste2').animate({
                "left": "-="+jump+"",
                }, 500 ); // speed of rotation
            }
        });

        $('#start').click(function() //Return to start
        {
            $('#liste2').animate({
                "left": "0px",
                }, 500 ); // speed of rotation
        });
    }

}
So this is my code. It works well with FF but not in Chrome. Any ideas?


text:
Q: Unzip File On Google Drive Using PHP I'm developing a web app where users could upload .zip file and storing it in the Google Drive. The upload part was easy but I have no clue how to unzip the file uploaded.
I found this but it's in Javascript and am still trying to find out how to unzip the file using PHP. Anyone knows how to accomplish this?

A: I guess you can use the ZipArchive class, i.e.:
$zip = new ZipArchive;
$res = $zip->open('myfile.zip');
if ($res === TRUE) {
  $zip->extractTo('/extract/path/');
  $zip->close();
  echo 'ok!';
} else {
  echo 'error!';
}

A: Didn't find a solution, I don't think unzipping files on Drive using PHP is possible by now. So instead of uploading .zip, I extract the zip to temp folder then loop to read the files. Here are the steps I do :
    loop items in folderId as item
        if item == folder
            create folder on Drive
            fetch folder id as folderId
            loop(folderId)
        else if item == file
            file.parent = folderId
            upload file
        endif
    endloop


text:
Q: Вывод данных из БД при загрузке JSP Мне нужно, чтобы в начальной login.jsp,
 <welcome-file>login.jsp</welcome-file>

выводился список товаров, который берется из базы данных, и который в свою очередь получается после обработки контроллера по адресу
/controller?command=MainPageCommand

Другими словами, перед тем, как загрузилась первая страница я должен загрузить на неё список товаров.
Возможно, нужно в welcome-file записать адресс, я пробовал, но чего-то не выходит, подскажите каким образом без js можно осуществить это всё.


text:
Q: How to block some of http user agent using php there have a way to block some of user agent via php script? Example on mod_security
SecFilterSelective HTTP_USER_AGENT "Agent Name 1"
SecFilterSelective HTTP_USER_AGENT "Agent Name 2"
SecFilterSelective HTTP_USER_AGENT "Agent Name 3"

Also we can block them using htaccess or robots.txt by example but I want in php. Any example code?

A: You should avoid using regex for this as that will add a lot of resources just to decide to block a connection.  Instead, just check to see if the string is there with strpos()
if (strpos($_SERVER['HTTP_USER_AGENT'], "Agent Name 1") !== false
 || strpos($_SERVER['HTTP_USER_AGENT'], "Agent Name 2") !== false
 || strpos($_SERVER['HTTP_USER_AGENT'], "Agent Name 3") !== false) {
    exit;
}

A: I like @Nerdling's answer, but in case it's helpful, if you have a very long list of user agents that need to be blocked:
$badAgents = array('fooAgent','blahAgent', 'etcAgent');
foreach($badAgents as $agent) {
    if(strpos($_SERVER['HTTP_USER_AGENT'],$agent) !== false) {
        die('Go away');
    }
}

Better yet:
$badAgents = array('fooAgent','blahAgent', 'etcAgent');
if(in_array($_SERVER['HTTP_USER_AGENT'],$badAgents)) {
    exit();
}


text:
Q: Is it possible to edit the maven build process within a plugin to change the behavior of other plugins? New to Maven and I probably won't explain this correctly but here goes...
If I have the following project structure:
Project A ---> Library 1 ---> Library 2

Where Project A depends on Library 1 (Library 1 is a dependency in Project A's pom) and Library 1 depends on Library 2.
Is it possible in a maven plugin to change the build process so any plugins executed later in the process won't have access to the same structure?
As an example, lets say I want to remove Library 1 as dependency of Project A and instead replace it with Library 2. So after my plugin runs, any future plugins see the project structure as:
Project A --> Library 2

If that is possible, can the solution be adapted to a structure where Library 1 depended on Library 2-10 and they all were included in the project structure while still removing Library 1?
My actual use case is I want a dependency to be included during compile time, but not during run time, and yet I want all of it's transitive dependencies to still be included. <scope>provided</scope> accomplishes the first part but also excludes transitive dependencies.
And before someone answers with "change your project structure" - it can't be done. Either I figure out a way to make this work nicely with maven, or I have to script the deletes of the deployable (this sucks).


text:
Q: What is meant by .delegate=self? Could anyone explain the meaning of someViewController.delegate = self and self.delegate? Where do they help us?

A: Delegates send messages to you.
For example: if you use the accelerometer delegate, you will get messages about the accelerometer.
If you use that new neutrino-detection delegate, you will get messages about any neutrinos detected in the area.
If you use PopUps, PopUps send you messages. And the way that is done, is with the PopUp's delegate.  There are many, many examples.
So, delegates send messages.
It's that simple.
You might ask, "WHERE does it send these messages?"
The answer is this: it sends the messages to where you set the ".delegate" thingy.
When you "set the delegate," what you are doing is saying where you want the messages to go.
Hence,
blah.delegate = amazingPlace will send the messages to "amazingPlace".
blah.delegate = somewhereElse will send the messages to "somewhereElse".
blah.delegate = self will send the messages ......  to you.
Very often, you want the messages to come to "you", so you just say "blah.delegate = self"
It is a very common mistake, to forget that line of code.
If you forget that line of code, you are stuffed. The messages go nowhere, and you are left scratching your head trying to figure out what went wrong.
Something else you have to do: when you use a delegate, you have to announce beforehand, that, you want to use the delegate.
How to do that?
It's very easy...
In the old days with Objective-C...
// old days!
@interface AppDelegate_Pad : NSObject <UIApplicationDelegate>
@interface BigTop : UIViewController <ASIHTTPRequestDelegate,
                                        UIPopoverControllerDelegate>
@interface Flying : UIViewController <UIAccelerometerDelegate>

You can see that 'BigTop' wants to use two delegates, namely the ASIHTTPRequestDelegate and the UIPopoverControllerDelegate. Whereas 'Flying' only wants to use one delegate - it wants to use the accelerometer.
In Swift...
 class YourClass:UIViewController, SomeDelegate, AnotherDelegate

You can't really do much on the iPhone without using delegates all over the place.
Delegates are used everywhere and all the time in iOS.
It is perfectly normal that a class might use a dozen delegates. That is to say, your class will want to get messages from a dozen delegates.
Nowadays with Swift you simply type
  blah.delegate = self

and that's all there is to it.
So that's what you're doing. Delegates send messages. You have to say where you want the messages to go. Very typically, you want them to go to "you," so in that case you simply say blah.delegate=self.

A: If in any case Bourne's answer doesn't help .. a delegate is basically the reaction of an event on an object and saying ".delegate=self" means those protocols have been adopted in self ... for eg.. what happens when a row is selected in tableview is told by tableview's delegate method "didSelectRowAtIndexPath" ... and if a viewcontroller has a tableview ..
and "didSelectRowAtIndexPath" is defined in that viewcontroller only then we will say ... tableview.delegate = self"...
and "self.anything" is used to say that "anything" is a property of self..
for eg.
NSString* anything;
@property(nonatomic,retain) NSString* anything;
then "self.anything"

A: Delegate is used to pass/communicate data/message b/w two objects of classes. Here, tableView(Sender) sends data/message to viewController(Receiver).
Consider example of implementing UITableView in custom viewController
Here, UITableViewDataSource & UITableViewDelegate are actually protocols. Unfortunately, UIKit Framework is not open source. But I will assure this what internally happens after referring many articles.
Protocol is like basketball coach with some requirements in it. He/She tells players like class, struct, enum what to do? by using those requirements. But He/She doesn't knows how to do?by themself. So, the class or struct which conforms that protocol should provide implementation to those requirements while achieving to dunk the ball.
protocol UITableViewDelegate {
 func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
}

A Protocol is said to be DataSource protocol then it always contains required functions with "return type" as shown below.
protocol UITableViewDataSource {
 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
 func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
}

Implementing UITableView inside custom viewController
class viewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let tableView = UITableView()

    override func viewDidLoad {
      tableView.delegate = self
      tableView.dataSource = self
    }

Here, tableView acts as Delegator(sender) & viewController object i.e (self) as Delegate(receiver).
In order to get UITableView in viewController.It should to conform to both the Protocols.
So, viewController class object has implemented all those required functions of both the protocols. Now self can be used either as UITableViewDelegate type or UITableViewDataSource type because Protocol can be used as type for an object of class which conforms to it.
Now, both properties of tableView i.e delegate & dataSource are assigned to self because its having same respective protocol types.
The non-optional functions of both Protocols are implemented in viewController class object as below
Protocol UITableViewDelegate functions
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Do further processes like pushing or poping another viewController
}

Protocol UITableViewDataSource functions
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
 }

func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    return UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
 }

1) When the user select a row in a section then tableview(Sender) i.e UItableView() calls the UITableViewDelegate func below shown by passing data to parameters tableView & indexPath which resides in viewController object(Receiver) through its delegate property. Now viewController uses those passed data to do further processes like pushing or poping to new custom viewController.
tableView.delegate?.tableView(UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)

2) Functions inside UITableViewDatasource protocol provides custom data to tableview(Sender). The tableview asks the viewController object by calling Datasource functions with passing data to parameters tableView & indexPath which resides in viewController object(Receiver) through its datasource property. Now viewController uses those passed data & returns custom data back tableview. Now tableview uses those data to create "10" cells in a section & kind of  "cell" at indexpath
tableView.dataSource?.tableView(UITableView, numberOfRowsInSection section: Int) -> returns "10"

tableView.dataSource?.tableView(UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> returns "cell"

Finally, whole UIKit Framework uses delegate & datasource design patterns in all its classes such as UIApplication, UITableView, UICollectionView, UITextField & so on to communicate data. Unfortunately, UIKit Framework is not open source.


text:
Q: How would I cancel a specific event in javascript? I added 2 different events each called touchstart and mousedown in the on method like this:

this.$el.on('touchstart mousedown', (e) => { this.start(e); })

My main goal is to cancel a mousedown event only which belongs to the on method at the end of called end function.
If I run a touchstart event 2 different events are always firing together. See this picture:

This problem causes undesired event block at Firefox. And also the code runs twice which is unnecessary. I want to redirect the website when I click or touch the element, prevent when I drag or swipe.
I searched about how to prevent a specific event on google but haven't found any of info so I've tried few ways by myself. However, all of the cases didn't work.

*

*Add return false; line

*

*Sadly, return false makes stop all of the remained events after end function has ended. My goal is to cancel the mousedown only, not the entire of the events. Therefore I can't just put the line into the function.

*Add mousedown event into the off method

*

*This also doesn't work. The events which belongs to the off method still remains as it's turned off. So if I try to drag after I swiped the element, nothing happens because mousedown event is now turned off.

*Add preventDefault() or stopPropagation()

*

*Those can't use as the same reason of case 1.

*Using RegExp to separate and make a new function for Firefox

*

*The problem was firing the undesired event, not the browser.

Are there any ways to cancel a specific event in this code?

class Evt {
  constructor($el) {
    this.$el = $el;
  }
  start(e) {
    console.log('start Function');
    this.$el.off('click');
    this.$el.on({
      ['touchmove mousemove']: (e) => this.eventmove(e),
      ['touchend mouseup']: (e) => this.end(e)
    });
  }
  eventmove(e) {
    e.preventDefault();
    console.log('move function');
    this.$el.on('click', (e) => {e.preventDefault();});
    return false;
  }
  end(e) {
    console.log('end function');
    this.$el.on('click');
    this.$el.off('touchmove touchend mousemove mouseup');
  }
  apply() {
    this.$el.on('touchstart mousedown', (e) => {
      this.start(e);
    })
  }
}
var thatEvt = new Evt($('#link'));
thatEvt.apply();
      a {
        width: 100%;
        height: 200px;
        border-radius: 10px;
        background-color: brown;
        font-family: Helvetica;
      }

      Click/Touch and Drag/Swipe

A: As I hear it, your intention is to have the link not redirect when the mouse is moved within a click.
Firstly, I assume you do not want the link to be draggable, so add the draggable="false" tag.  This will prevent events that may effect code outside what you have sent (such as redirecting/dropping links).

  Click/Touch and Drag/Swipe

If that does not solve your issue I have put together this code below, it may be more complicated, but it should be a little more robust.
class Evt {
  constructor($el) {
    this.$el = $el;
    this.active = false;
    this.preventRedirect = false;
  }
  start(e) {
    console.log('start Function');
    this.active = true;
    this.preventRedirect = false;
  }
  eventmove(e) {
    if (this.active) {
      console.log('move function');
      this.preventRedirect = true;
    }
  }
  end(e) {
    if (this.active) {
      console.log('end function');
      this.active = false;
    }
  }
  apply() {
    this.$el.on({
      ['touchstart mousedown']: (e) => this.start(e),
      ['click']: (e) => { //preventing onclick only if preventRedirect is set
        if (this.preventRedirect) {
          e.preventDefault();
          return false;
        }
      }
    });
    $("html").on({ //so that the mouse can move outside the element and still work.
      ['touchmove mousemove']: (e) => this.eventmove(e),
      ['touchend mouseup']: (e) => this.end(e)
    });
  }
}
var thatEvt = new Evt($('#link'));
thatEvt.apply();


text:
Q: Symfony: Get data from subform (CollectionType) I have a ManyToOne relation between two entities Parent and Child so in the FormType I have used CollectionType as described below:
class ParentType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('childs', CollectionType::class, array(
                'entry_type' => ChildType::class,
            ));
    }
}

And in the ChildType class I want to get the embeded object using EventListener:
class ChildType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('lastName');

        $builder->addEventListener(
            FormEvents::POST_SET_DATA,//---after setting data
            function (FormEvent $event) {
                die(var_dump($event->getData()));//---this gives me null
            }
        );
    }
}

The result I get is null although I have passed a full object to the form in the controller:
$parent = new Parent('Test');
$childs = array(
    'test1' => 'test1',
    'test2' => 'test2',
);
foreach ($childs as $key => $value){
    $c = new Child($key, $value);
    $parent->addChild($c);
}

$form = $this->createForm(ParentType::class, $parent);

class Parent:
class Parent{
   /**
     * @var ArrayCollection*
     * @ORM\OneToMany(targetEntity="Child", mappedBy="parent", cascade={"persist", "remove"})
     * @ORM\JoinColumn(nullable = true)
     */
    private $childs;

    /**
     * Constructor
     */
    public function __construct()
    {
         $this->childs= new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add child
     *
     * @param \AppBundle\Child $child
     *
     * @return Parent
     */
    public function addChild(\AppBundle\Child $child)
    {
        $this->childs[] = $child;

        return $this;
    }

    /**
     * Remove child
     *
     * @param \AppBundle\Child $child
     */
    public function removeChild(\AppBundle\Child $child)
    {
        $this->childs->removeElement($child);
    }

    /**
     * Get childs
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getChilds()
    {
        return $this->childs;
    }
}


text:
Q: Setting is not working in Visual Studio CMake configuration I am building Opencv with visual studio 2019 and opencv-3.4.16 source files
I selected File->Open->Cmake and loaded CMakeLists.txt from root of project
Once project loaded, I did right click on CMakeLists.txt->CMake Settings for OpenCV
I made sure I am on x64-Release configuration both in Visual Studio and in CMake settings.
I scrolled down and checked box BUILD_opencv_world as shown in image.
Saved file CMakeSettings.json, Cmake automatically re-scanned and re-loaded.
When I build the project I don't see opencv_world.dll or opencv_world.lib in the x64-Release output folder. I see all the other DLL's, which means this checkbox setting did not work
I tried doing CMakeLists.txt->Cache->Delete
I also tried adding set(BUILD_opencv_world ON) to the top of CMakeLists.txt
Nothing worked and the Opencv_world libraries are not getting built
What step am I missing?


text:
Q: String gets mangled when passed from Grunt to CasperJS I have a Gruntfile that can be executed from the command line with a string in Thai.

grunt --data=นี่คือการทดสอบ

When I echo the string, I can see, that the string is intact:

นี่คือการทดสอบ

I then spawn a CasperJS script with the string
grunt.util.spawn({
    cmd: '/usr/local/bin/casperjs',
    args: [
        '--engine=slimerjs',
        '--ssl-protocol=any',
        '--text=' + str,
        'test.js'
    ],
},
function(error, result, code)
{
    grunt.log.writeln(error + ' | ' + result + ' | ' + code);
    done();
});

But echoing it now gives me a mess:

à¸<99>ีà¹<88>à¸<84>ือà¸<81>ารà¸<97>à¸<94>สอà¸<9a>

The plot thickens: I'm running this all from cloud-init via userdata on an AWS instance.
However, when I run the same Grunt command via the shell, the scripts work fine. - Any ideas?

A: Figured this out.
The bytes encoding changed coming into Casper from Grunt.
Ran them through utf8to16 from http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
All good to go.


text:
Q: different length permutations
Possible Duplicate:
Algorithm to return all combinations of k elements from n

What I want to do is generate all 1-9 permutations of different length. For example all permutations of length one would simply be
{1}, {2}, {3}, {4} .. and so on.
Permutations of length two would be: {1,2}, {1,3}, {1,4} ..
So far I've been using std::next_permutation(), however it won't do the job in this case.
Is there any way to solve this problem without using recursion? If not and you're providing any code I would really appreciate if you would explain to me, because I'm really struggling with recursion right now, especially with implementing recursive solutions myself. Thanks in advance.

A: The approach I would use starts from hakmem 175 and that is finding the next higher number with the same number of bits.
So let's say that you code in one int you 10 numbers (from bit 0 to bit 9)
That means that you have to loop from 1 to 10 and prime your start int with the first number that will approximate your pair.
ex: for {1},{2} ... the start int would be 2^0
    for {1,2} {1,3} ... the start int would be 2^0+2^1
and so on.
after that you have to make a method that would interpret the number (check if a bit is set then the corresponding number will appear in the sequence).
after that call hakmems method for the next number:
unsigned nexthi(unsigned a) {
  unsigned c = (a & -a);
  unsigned r = a+c;
  return (((r ^ a) >> 2) / c) | r);
}

and continue the loop until no numbers remain.
and go to the next number of bits (1->10)
I suggest looking to hakmem method for you to understand how it works, the implementation is easy if you know a few things about bits.

A: void permute(std::vector<int>& digits, int length) {
    if (length == 0) {
        std::cout << "{";
        for (int i = 0; i < digits.length; i++) {
            std::cout << digits[i] << ",";
        }
        std::cout << "}" << std::endl;
        return;
    }

    for (int i = 0; i < 9; i++) {
        std::vector<int> newDigits(digits);
        newDigits.push_back(i);
        permute(newDigits, length -1);
    }
}

Call this within main as
std::vector<int> digits;
permute(digits, 10); // For 10 digit permutations.

Now if you want to get permutations of length 1,2 ... n, then all you have to do is put the permute function inside a loop.
Note that this is not the most efficient of implementations. But I suppose this should illustrate the recursion clearly.


text:
Q: How to open the actual folder a library subfolder refers to? When I open a library subfolder in explorer, it is displayed as subfolder of that library. However, I want to open the actual subfolder without explorer remembering I got there via a library (e.g. the customization feature is otherwise not available). How can that be achieved?

A: The only workaround I found so far is copy-pasting the path from the address bar (which is expanded correctly on clicking) and pasting it into a different explorer window or the start menu's text field. But that is tedious if repeated often, and spams my ClipX clipboard history.

A: put the following line in a .bat file and run it from the folder you want to open:
%SystemRoot%\explorer.exe %~dp0

this opens explorer in batch file location.


text:
Q: How to use "extern struct" to share variables in c programming and compile with gcc? I want some shared variables should be accessed among source files, main.c and second.c and  my header file is all.h defined the shared data type,
#ifndef ALL_H
#define ALL_H
struct foo {
    double v;
    int i;
};

struct bar {
    double x;
    double y;
};
#endif

main.c is given below
/* TEST*/
#include "all.h"
#include "second.h"

int main(int argc, char* argv[])
{
    struct foo fo; // should be accessed in second.c
    fo.v= 1.1;
    fo.i = 12;

    struct bar ba; // should be accessed in second.c
    ba.x= 2.1;
    ba.y= 2.2;

    sec(); // function defined in second.c

    return 0;
}

second.h is given below
#include <stdio.h>
#include "all.h"

int sec();

second.c is given below
#include "second.h"

extern struct foo fo;
extern struct bar ba;

int sec()
{
    printf("OK is %f\n", fo.v+ba.x);

    return 0;
}

I thought i have all the declaration and include the headers. But when i compile
    gcc -o main main.c second.c

or

    gcc -c second.c
    gcc -c main.c
    gcc -o main main.o second.o

It will give some error like
second.o: In function `sec':
second.c:(.text+0x8): undefined reference to `fo'
second.c:(.text+0xe): undefined reference to `ba'
collect2: ld returned 1 exit status

I think somewhere of the use of extern was wrong or i use the gcc incorrectly?

A: The problem is with the scope. Your variables (fo & ba)  have local scope as they are declared within main.So, their visibility is restricted to within main function. Please make them global variables and it should work.

A: The error message indicates that the linker is unable to find fo and ba.  With the extern declaration you have told the compiler that the variables will exist in some other translation unit, but they don't.
You need to move the struct foo fo; and struct bar ba; outside of the main() function.  Right now, they are function local variables.  They need to be global variables for this to work.

A: main.h:
typedef struct
{
    double v;
    int i;
} Foo;

extern.h:
extern Foo fo; // "fo is a global variable stored somewhere else"

main.c:
#include "main.h"
#include "extern.h"
//use fo.v here

second.c:
#include "second.h"
#include "main.h"
#include "extern.h"
Foo fo; // "store the data of fo here"
//use fo.v here

Just include #include "main.h" and #include "extern.h" in all .c files you want to use fo.
Notice that Foo fo is only in second.c, nowhere else.


text:
Q: Java: Extend SimpleDateFormat with new pattern letters Java's SimpleDateFormat is used to format a Date object to a string. The formatter supports various pattern letters, which denote textual representation of a Date field. For example, yy is two-letter year, yyyy is four-letter year, and E is day of week.
For example, A SimpleDateFormat initialized with yyyy.MM.dd G 'at' HH:mm:ss z will format a date to something like 2001.07.04 AD at 12:08:56 PDT.
I would like to add some pattern letters to SimpleDateFormat. For example, want C to denote Hebrew weekday (יום ראשון, יום שני, ...).
What's the right way to extend SimpleDateFormat with these new pattern letters? The only online example I could find seems somewhat complicated. I can live with formatting only, without parsing.

A: E can already be used to get the day of the week. If you want it in hebrew, then initialize the SimpleDateFormat instance with the hebrew locale.

A: From what I can tell SDF was not build to be extendable so each Calendar field formatting is hardcoded into one method : (. What I would do is I would create a wrapper object and detect special (handled by me chars) and format output by my own in mixed formats i would divide format into whats before and after my format char, and pass them to original SDF and then glue the results together.

A: java.time
The modern DateTimeFormatter years ago supplanted SimpleDateFormat, with the adoption of JSR 310.
Study that class JavaDoc to see its many formatting codes. While largely similar to the codes used in the SimpleDateFormat class, there are some differences.
This class can automatically localize for you. So you may not need to define any formatting pattern.
If you want just the name of the day of the week localized, use DayOfWeek::getDisplayName method.


text:
Q: Jenkins how to catch error in script What I am trying to do is once source .... command is executed if there is an error I want to put it into temp file. I tried several ways but no luck.
    def responseValue = sh(script: """#!/bin/bash
    set +x
    source /etc/runScript.sh> /dev/null 2>&1 >temp.txt
    echo \${${someVar}}
    """, returnStdout: true)
     def foundValue =  readFile(file: "temp.txt").trim()
     echo "value is ${foundValue}"
     //also tried source /etc/runScript.sh  2>&1> /dev/null >temp.txt

A: The order of redirection matters.
source /etc/runScript.sh> /dev/null 2>&1 >temp.txt

>/dev/null redirects standard output to the bit bucket.
2>&1 redirects standard error to the same as standard output, also to the bit bucket.
>temp.txt redirects standard output to the file temp.txt, leaving standard error directed to the bit bucket.
I think a safe way to accomplish your goal would be to save each stream to a different file.
source /etc/runScript.sh >/dev/null 2>temp.txt

Which will send the standard output to /dev/null and save the standard error in temp.txt.


text:
Q: in early am or at early am (time)
Sexy, let's go to AC for the whole night this or the following Friday night. We can leave around 8-9 pm and come back in early am.

Is this correct?

A: I've heard it used as "in the early am". But it really isn't that much longer to use the much less awkward "early in the morning".

A: In casual conversation (and since they called you sexy, I'll assume this is pretty casual), am (or a.m.) is used to mean morning.
So yes, this is correct.

A: I agree with other posters - "a.m." can be used, jocularly, as an exact substitute for "morning".  So if you want to use it like this, check that your sentence still sounds right if you swap out "a.m." and swap in "morning".
It's all very slangy of course :D


text:
Q: Memory issues when working with media thumbnails I'm trying to find an effective way of working with media thumbnails returned from the MediaStore. Actually, there are two kinds of thumbnails: MICRO_KIND which is square and has 96x96 size independent of the device or platform; and MINI_KIND which is around 512x384 for a landscape image, and around 288x512 for a portrait image, also device- and platform-independent. Now, I'm using all the best practices for asynchronous Bitmap loading, recycling and caching, and actually my application works just fine when I use MICRO_KIND. Anyway, this is not what I want, especially for tablets, where such small images look poor. I've tried using MINI_KIND, but it exceeds memory limit pretty quickly, nevermind the implementation. Another trouble is that portrait images have portrait thumbnails, and I need them all to be rectangle landscape. I've tried cropping and resizing Bitmaps keeping the aspect ratio, but it gives me even more headache, since for every operation with a Bitmap a copy is created and nevermind I'm always using the Bitmap.recycle() method, OutOfMemory kills me over and over again. I'm looking for an elegant and memory efficient way of creating thumbnails of strictly specified size and orientation, using those queried from MediaStore. Would highly appreciate any help and references.

A: As you are saying, you have used everything from cropping to recycling, now try with WeakReferences as well.
If this also does not help, then you may have memory leak in your code.
Please see my answer on same issue: bitmap size exceeds Vm budget error android
Its a generic answer, try with all methods that I have mentioned. One of them should work for you :)
Thank you.


text:
Q: How is a "false tone," e.g. on a tuba, formed Apparently a tuba, as well as maybe other brass instruments, can produce a false tone a fourth above the fundamental, that is a tone with frequency $\frac{4}{3}f_0$. I heard one man do this with his voice too - that is, start on a tone and drop to a subharmonic an octave and a fifth below.
How does this happen? It can't be a combination tone of two harmonics, because the frequency then could only be an integer multiple of $f_0$.
Thanks!

A: From the player's point of view it is useful to describe brass instrument harmonics as having the simple frequency relationship 1:2:3:4:... etc (with some practical instrument-dependent corrections to the intonation made by the player, of course) but the underlying physics is somewhat more complicated.
A cylindrical bore instrument (e.g. a trombone, where the bore must be exactly cylindrical because of the slide) with no bell would actually have harmonics in the ratio 1:3:5:... etc. A uniform conical bore with no bell produces 1:2:3:... etc. This is basically the same as for woodwind instruments with reeds - for example compare clarinet (cylindrical bore) which overblows at the 12th (3x the fundamental frequency) with saxophone (conical bore) which overblows at the octave (2x).
The bell tends to lower the frequency of all the resonances, and therefore tends to convert the ratios 3:5:7:... into 2:4:6:... which are the same as 1:2:3... from a tube of half the length. This is the origin of the classification of instruments into "full-tube" and "half-tube", and explains why the some instruments can not produce the fundamental frequency as a "pedal note" - or at best, it is so out of tune as to be useless musically.
But of course real instruments do not have a uniform taper over the whole bore, and the changes in taper are also used to tweak the frequencies of the harmonics and improve the intonation.
Because of their physical size the tubas and euphoniums are likely to be the furthest away from the simple "theoretical" models, and the most obvious way to find out what this "false tone" really is (at least to an engineer!) would be to compare the measured the frequency response curves of instruments that have it, and with those that don't.
I'm not sure if anybody has published the results from that type of investigation specifically into "false tones", but the final plot in Figure 10 in https://www.grc.com/acoustics/an-introduction-to-horn-theory.pdf seems to show a (weak) resonance peak at about the right frequency above the fundamental. If that is the case for real instruments, there is no need to speculate about difference tones, subharmonic excitation, or other nonlinear effects - this is just a real resonant frequency of the system, but one that doesn't match the over-simplified theory of pipe acoustics taught in high school physics!
The original source of Fig 10 is apparently https://secure.aes.org/forum/pubs/journal/?elib=5981 - unfortunately behind a paywall, so I haven't had chance to read it. But the fact that the paper is from ISVR Southampton is a pretty good recommendation that it's not likely to be nonsense.


text:
Q: file_get_contents giving garbage for Russian content I am trying my best to describe my problem. For a client PC, I am reading a file (Via ::ReadFile) and uploading i tto a PHP server (HTTP upload). I am receiving this string in that PHP via following file code and saving in hard disk:
<?php
// body contains sent data here
    $body = file_get_contents('php://input',FILE_TEXT);
    echo "<script language= 'JavaScript'>alert(' . $body . ');</script>";
        $today = date("dmY-Gis");
        $name = $today . ".log";
        //$body = utf8_encode($body);
        //$body = "\xEF\xBB\xBF".$body;
        $f = fopen($name, "wb");
        fwrite($f, $body);
        fclose($f);
php?>

Now, I have a string sending as follows: выфпвыфп  Notepad
But this PHP script is saving it as ???????? Notepad
Seems english strings are captured correctly, but non - English string is not collected
Can any one have idea.

*

*file_get_contents not working with utf8

*php: file_get_contents encoding problem
Above two are same problem but none gave any solutions that worked for me.

A: add this
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">

to your page


text:
Q: Rails routes do not contain id in that I use rails 5 and setting route, type rake routes in console and result is:
Prefix Verb   URI Pattern                      Controller#Action
new_report_templates GET    /report_templates/new(.:format)  report_templates#new
edit_report_templates GET    /report_templates/edit(.:format) report_templates#edit
report_templates GET    /report_templates(.:format)      report_templates#show
                  PATCH  /report_templates(.:format)      report_templates#update
                  PUT    /report_templates(.:format)      report_templates#update
                  DELETE /report_templates(.:format)      report_templates#destroy
                  POST   /report_templates(.:format)      report_templates#create

It's so weird to see that result routes do not have id in url template. My route:
Rails.application.routes.draw do
  resource :report_templates
end

I use gem 'rails', '~> 5.1.6'. So my question is: why my result routes do not contain id in that ?

A: It's because your are using singular resources:

Sometimes, you have a resource that clients always look up without referencing an ID.

Change your routes to use resources for certain routes to contain the id:
Rails.application.routes.draw do
  resources :report_templates
end


text:
Q: finding $x$ when it is the power in both the numerator and denominator I have an equation and I've simplified it to this:
$$\frac {24}{19}=\frac {1.01583^{12x}}{1.01583^{12x}-1}$$
I'm having trouble finding $x$? I realize I have to find the log at some point, but am struggling as to when and where I do so?

A: let $$a=1.01583^{12x}$$ then we have to solve $$\frac{24}{19}=\frac{a}{a-1}$$ from here we get $$24a-24=19a$$ thus we have $$a=\frac{24}{5}$$
can you proceed?
from here we get
$$\ln(a)=12x\ln(1.01583)$$ thus $$x=\frac{\ln(a)}{12\ln(1.01583)}$$

A: Generalize the problem, solve $x$ when all the variables are real and positive:
$$\text{a}=\frac{\text{b}^{\text{c}x}}{\text{b}^{\text{c}x}-\text{d}}\Longleftrightarrow\text{a}=\frac{\frac{\text{b}^{\text{c}x}}{\text{b}^{\text{c}x}}}{\frac{\text{b}^{\text{c}x}}{\text{b}^{\text{c}x}}-\frac{\text{d}}{\text{b}^{\text{c}x}}}\Longleftrightarrow$$
$$\text{a}=\frac{1}{1-\frac{\text{d}}{\text{b}^{\text{c}x}}}\Longleftrightarrow\frac{1}{\text{a}}=1-\frac{\text{d}}{\text{b}^{\text{c}x}}\Longleftrightarrow$$
$$\frac{1}{\text{a}}-1=-\frac{\text{d}}{\text{b}^{\text{c}x}}\Longleftrightarrow1-\frac{1}{\text{a}}=\frac{\text{d}}{\text{b}^{\text{c}x}}\Longleftrightarrow$$
$$\frac{\text{d}}{1-\frac{1}{\text{a}}}=\text{b}^{\text{c}x}\Longleftrightarrow\frac{\log_{\text{b}}\left(\frac{\text{d}}{1-\frac{1}{\text{a}}}\right)}{\text{c}}=x$$
So, for your prolem we get:
$$x=\frac{\log_{1.01583}\left(\frac{1}{1-\frac{1}{\frac{24}{19}}}\right)}{12}=\frac{\log_{1.01583}\left(\frac{24}{5}\right)}{12}\approx8.322799606$$


text:
Q: Wordpress child theme and files in folders I've got a qustion - my footer.php file includes such a function:
<?php adios_footer_template(adios_get_opt('footer-template')); ?>

as I assumed the code was calling some internal function. When I've digged into the theme code I've found out that this function has a following code:
function adios_footer_template($layout) {
    if(class_exists('ReduxFramework') && !adios_get_opt('footer-enable-switch')) { return; }
    switch ($layout) {
      case 'footer-style5':
        get_template_part('templates/footer/footer-style5');
        break;
      case 'footer-style4':
        get_template_part('templates/footer/footer-style4');
        break;
      case 'footer-style3':
        get_template_part('templates/footer/footer-style3');
        break;
      case 'alternative':
        get_template_part('templates/footer/alternative');
        break;
      case 'default':
      default:
        get_template_part('templates/footer/default');
        break;
    }
  }

What I'm trying to achieve is to OR add one more case via child theme and makes it work or simply have at least an option to edit those footer styles. What I've tried is to copy entire templates/footer directory into child theme and then add changes (without success; on frontend nothing has changed). THen I even tried to rename the function and paste it into my own functions.php, but again - didnt change anything. Is it even doable?

A: Have you tried renaming the function entirely in your child theme?
function adios_child_footer_template($layout) {
  # Line about adios_get_opt removed
  switch ($layout) {
    case 'footer-style5':
      get_template_part('templates/footer/footer-style5');
      break;
    case 'footer-style4':
      get_template_part('templates/footer/footer-style4');
      break;
    case 'footer-style3':
      get_template_part('templates/footer/footer-style3');
      break;
    case 'alternative':
      get_template_part('templates/footer/alternative');
      break;
    case 'default':
    default:
      get_template_part('templates/footer/default');
      break;
  }
}

And then calling it like:
<?php adios_child_footer_template('alternative'); ?>

My guess is that adios_get_opt is choosing a switch case that you didn't expect. Of course, this is only a shortcut. A better choice would be to find a way to properly extend the function AND add your footer style to adios_get_opt.


text:
Q: Set sample rate in fmod How do I set up the sample rate in Fmod?
I initiate my event system with the following code. Can I add the sample rate into this method?
result = eventSystem->init(32, FMOD_INIT_NORMAL | FMOD_INIT_ENABLE_PROFILE, NULL, FMOD_EVENT_INIT_NORMAL);

A: No, to specify the sample rate for the system you need to use System::setSoftwareFormat.
To do this with the EventSystem, you must create an EventSystem object, then call EventSystem::getSystemObject, with that System object you can call System::setSoftwareFormat specifying the sample rate. All of this happens before you init the EventSystem object.


text:
Q: Count number of writes to different tables I have recently setup Continuous Archiving for Point-in-Time Recovery in a postgresql DB, but the archive is growing at an unexpectedly high pace (tens of gigabytes per day). The DB is a couple of GB, most of it static. It seems to me that we may have some part of the application which is writing a bit too aggressively to the database, possibly updating large number of rows frequently, causing needless diskload.
Is there some way to either ask the DB, or to analyze the WAL files, to find out which tables most writes (row delete, add or updates) are made to, preferably counted in bytes? That would be a big help in figuring out the source of the disk load.

A: This information is available through the Statistics Collector.
The information you are looking for is stored in pg_stat_bgwriter or pg_stat_database. Maybe you are also interested in the values from pg_stat_all_tables that shows how many tuples have been inserted, updated or deleted.
Pay attention to the configuration properties listed in the section Statistics Collection Configuration
All those views show values since the instances has been started or since the last time pg_stat_reset() has been called.
If you want to monitor the change over time, you need to sample those views and store the values somewhere (e.g. a text file or just another table that has a timestamp to indicate when the sample was taken).


text:
Q: About continuity of the distribution function of $X+Y$ when they are independent and one has continuous distribution. I want to prove that if $X, Y$ are independent random variables and the distibution function of $X$ is continuous (it doesn't really matter wether this is for $Y$) then the distribution function of $X+Y$ is continuous. I have thought of using that $F$ continuous $\Leftrightarrow$ $F^{-1}$ is strictly increasing but cannot get to anything correct.
This is part of an exercise from my Probability Theory class.


text:
Q: PHP strict standards error text added to results on the page This is the error message generated:

Strict Standards: call_user_func_array() expects parameter 1 to be a
  valid callback, non-static method
  ModCareercoachoccupationsHelper::getRelated() should not be called
  statically in
  /customers/f/0/0/studiomitchell.agency/httpd.www/libraries/joomla/cache/controller/callback.php
  on line 152

<?php
/**
 * @package     Joomla.Platform
 * @subpackage  Cache
 *
 * @copyright   Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE
 */

defined('JPATH_PLATFORM') or die;

/**
 * Joomla! Cache callback type object
 *
 * @since  11.1
 */
class JCacheControllerCallback extends JCacheController
{
    /**
     * Executes a cacheable callback if not found in cache else returns cached output and result
     *
     * Since arguments to this function are read with func_get_args you can pass any number of arguments to this method
     * as long as the first argument passed is the callback definition.
     *
     * The callback definition can be in several forms:
     * - Standard PHP Callback array see <https://secure.php.net/callback> [recommended]
     * - Function name as a string eg. 'foo' for function foo()
     * - Static method name as a string eg. 'MyClass::myMethod' for method myMethod() of class MyClass
     *
     * @return  mixed  Result of the callback
     *
     * @since   11.1
     */
    public function call()
    {
        // Get callback and arguments
        $args     = func_get_args();
        $callback = array_shift($args);

        return $this->get($callback, $args);
    }

    /**
     * Executes a cacheable callback if not found in cache else returns cached output and result
     *
     * @param   mixed    $callback    Callback or string shorthand for a callback
     * @param   array    $args        Callback arguments
     * @param   mixed    $id          Cache ID
     * @param   boolean  $wrkarounds  True to use wrkarounds
     * @param   array    $woptions    Workaround options
     *
     * @return  mixed  Result of the callback
     *
     * @since   11.1
     */
    public function get($callback, $args = array(), $id = false, $wrkarounds = false, $woptions = array())
    {
        // Normalize callback
        if (is_array($callback))
        {
            // We have a standard php callback array -- do nothing
        }
        elseif (strstr($callback, '::'))
        {
            // This is shorthand for a static method callback classname::methodname
            list ($class, $method) = explode('::', $callback);
            $callback = array(trim($class), trim($method));
        }
        elseif (strstr($callback, '->'))
        {
            /*
             * This is a really not so smart way of doing this... we provide this for backward compatability but this
             * WILL! disappear in a future version.  If you are using this syntax change your code to use the standard
             * PHP callback array syntax: <https://secure.php.net/callback>
             *
             * We have to use some silly global notation to pull it off and this is very unreliable
             */
            list ($object_123456789, $method) = explode('->', $callback);
            global $$object_123456789;
            $callback = array($$object_123456789, $method);
        }

        if (!$id)
        {
            // Generate an ID
            $id = $this->_makeId($callback, $args);
        }

        $data = $this->cache->get($id);

        $locktest             = new stdClass;
        $locktest->locked     = null;
        $locktest->locklooped = null;

        if ($data === false)
        {
            $locktest = $this->cache->lock($id);

            if ($locktest->locked == true && $locktest->locklooped == true)
            {
                $data = $this->cache->get($id);
            }
        }

        $coptions = array();

        if ($data !== false)
        {
            $cached                = unserialize(trim($data));
            $coptions['mergehead'] = isset($woptions['mergehead']) ? $woptions['mergehead'] : 0;
            $output                = ($wrkarounds == false) ? $cached['output'] : JCache::getWorkarounds($cached['output'], $coptions);
            $result                = $cached['result'];

            if ($locktest->locked == true)
            {
                $this->cache->unlock($id);
            }
        }
        else
        {
            if (!is_array($args))
            {
                $referenceArgs = !empty($args) ? array(&$args) : array();
            }
            else
            {
                $referenceArgs = &$args;
            }

            if ($locktest->locked == false)
            {
                $locktest = $this->cache->lock($id);
            }

            if (isset($woptions['modulemode']) && $woptions['modulemode'] == 1)
            {
                $document = JFactory::getDocument();
                $coptions['modulemode'] = 1;
                if (method_exists($document, 'getHeadData'))
                {
                    $coptions['headerbefore'] = $document->getHeadData();
                }
            }
            else
            {
                $coptions['modulemode'] = 0;
            }

            ob_start();
            ob_implicit_flush(false);

            $result = call_user_func_array($callback, $referenceArgs);
            $output = ob_get_clean();

            $coptions['nopathway'] = isset($woptions['nopathway']) ? $woptions['nopathway'] : 1;
            $coptions['nohead']    = isset($woptions['nohead']) ? $woptions['nohead'] : 1;
            $coptions['nomodules'] = isset($woptions['nomodules']) ? $woptions['nomodules'] : 1;

            $cached = array(
                'output' => ($wrkarounds == false) ? $output : JCache::setWorkarounds($output, $coptions),
                'result' => $result,
            );

            // Store the cache data
            $this->cache->store(serialize($cached), $id);

            if ($locktest->locked == true)
            {
                $this->cache->unlock($id);
            }
        }

        echo $output;

        return $result;
    }

    /**
     * Generate a callback cache ID
     *
     * @param   callback  $callback  Callback to cache
     * @param   array     $args      Arguments to the callback method to cache
     *
     * @return  string  MD5 Hash
     *
     * @since   11.1
     */
    protected function _makeId($callback, $args)
    {
        if (is_array($callback) && is_object($callback[0]))
        {
            $vars        = get_object_vars($callback[0]);
            $vars[]      = strtolower(get_class($callback[0]));
            $callback[0] = $vars;
        }

        return md5(serialize(array($callback, $args)));
    }
}

The site retrieves the data but with this text error also above
the listing.

The callback.php line 152 is as follows:
$result = call_user_func_array($callback, $referenceArgs);

Any help would be great. Thanks

A: You'll get this error if you define the method non-statically:
class Foo {
    public function bar() {
    }
}

And then define $callback as either a string:
$callback = 'Foo::bar';

Or an array of strings:
$callback = ['Foo', 'bar'];

And then use it as an argument to call_user_func_array():
call_user_func_array($callback, []);

To avoid this, you can either define the method statically:
public static function bar() { ... }

Or use an instantiated object in your callback:
$callback = [new Foo(), 'bar'];


text:
Q: is there a way to wait a async method result in webflux code I use Spring webflux to develop with Intellij idea, and now I meet a problem is that in my method, I need to get a ip(String) from reactive mongo, than i will forward my request。
so i wrote this code
@Autowird
private XXRepository repository;

public Mono<Void> xxxx(ServerWebExchange exchange, String symbol) {
    StringBuilder builder = new StringBuilder();
    String ip = repository.findBySymbol(symbol)
                          .map(xxxxx)
                          .subscribe(builder::append)
                          .toString();
    WebClient.RequestBodySpec forwardRequestInfo = webClient.method(httpMethod)
                .uri(ip);

    xxxxxxx //setting http msg
    WebClient.RequestHeadersSpec<?> forwardRequest;
    return forwardRequest.exchange();
}

my question is that this code will execute on other thread, i can not get this ip in my method,
because my method will not Waiting for this mongo execution
String ip = repository.findBySymbol(symbol)
                          .map(xxxxx)
                          .subscribe(builder::append)
                          .toString();

so is there any way i can get ip immediately in my method ?

A: your construction is a very dirty hack, don't do that and try to avoid any side effect operations in the reactive streams.
So, you just need to chain your operators like this:
return repository.findBySymbol(symbol)
                      .map(xxxxx)
                      .map(ip -> webClient.method(httpMethod).uri(ip))
                      ...
                      flatMap(param -> forwardRequest.exchange())


text:
Q: Error adding an index to a view I have created a view using the following code
CREATE VIEW dbo.two_weeks_performance WITH SCHEMABINDING
AS
  SELECT dbo.day_dim.date_time AS Date,
         dbo.order_dim.quantity AS Target_Acheived
    FROM dbo.day_dim
    JOIN dbo.order_fact ON dbo.day_dim.day_id = dbo.order_fact.day_id
    JOIN dbo.branch_dim ON dbo.order_fact.branch_id = dbo.branch_dim.branch_id
    JOIN dbo.order_dim ON dbo.order_fact.order_id = dbo.order_dim.order_id
GROUP BY dbo.order_dim.quantity, dbo.day_dim.date_time`

Now when I use:
CREATE UNIQUE CLUSTERED INDEX two_weeks_performance_I ON two_weeks_performance (Date)

I am getting an error:

Cannot create index because its select list does not use the correct usage of COUNT_BIG(). Consider adding COUNT_BIG(*) to the select.

Please help me solve this issue.

A: The error tells you exactly what you have to do - add COUNT_BIG(*) to your select list.
From Creating Indexed Views:

If GROUP BY is specified, the view
  select list must contain a
  COUNT_BIG(*) expression, and the view
  definition cannot specify HAVING,
  ROLLUP, CUBE, or GROUPING SETS.

CREATE VIEW dbo.two_weeks_performance WITH SCHEMABINDING
AS
  SELECT dbo.day_dim.date_time AS Date,
         dbo.order_dim.quantity AS Target_Acheived,
         COUNT_BIG(*) as Cnt
    FROM dbo.day_dim
    JOIN dbo.order_fact ON dbo.day_dim.day_id = dbo.order_fact.day_id
    JOIN dbo.branch_dim ON dbo.order_fact.branch_id = dbo.branch_dim.branch_id
    JOIN dbo.order_dim ON dbo.order_fact.order_id = dbo.order_dim.order_id
GROUP BY dbo.order_dim.quantity, dbo.day_dim.date_time
GO
CREATE UNIQUE CLUSTERED INDEX two_weeks_performance_I ON two_weeks_performance (Date)