text:
Q: How do I call another function in lisp; My program is supposed to convert a given temperature from Fahrenheit to Centigrade or the other way around.  It takes in a list containing a number and a letter.  The letter is the temperature and the letter is the unit we are in.  Then I call the appropriate function either F-to-C or C-to-F.  How do I call the functions with the given list that was first checked in my temperature-conversion function. Here is my code.
 (defun temperature-conversion (lst)
  (cond
  ((member 'F lst) (F-to-C))
  ((member 'C lst) (C-to-F))
  (t (print "You didn't enter a valid unit for conversion"))
  )
)
(defun F-to-C ()
;;(print "hello")
 (print (temperature-conversion(lst)))
)
(defun C-to-F ()
(print "goodbye"))
;;(print (temperature-conversion '(900 f)))
(setf data1 '(900 f))

A: You have infinite recursion: temperature-conversion calls F-to-C which calls temperature-conversion again.
I would do this:
(defun c2f (c) (+ 32 (/ (* 9 c) 5)))
(defun f2c (f) (/ (* 5 (- f 32)) 9))
(defun temperature-conversion (spec)
  (ecase (second spec)
    (C (c2f (first spec)))
    (F (f2c (first spec)))))
(temperature-conversion '(32 f))
==> 0
(temperature-conversion '(100 c))
==> 212
(temperature-conversion '(100))

*** - The value of (SECOND SPEC) must be one of C, F
      The value is: NIL
The following restarts are available:
ABORT          :R1      Abort main loop

A: I think this example is generally used to demonstrate how functions are first-class values.
With a little modification to sds's answer, you can have an ECASE statement that selects the appropriate function, which is then used by a surrounding FUNCALL.
(defun temperature-conversion (spec)
  (destructuring-bind (temperature unit) spec
    (funcall
      (ecase unit (C #'c2f) (F #'f2c))
      temperature)))

I added a DESTRUCTURING-BIND in case you don't know yet what it is.


text:
Q: Allow DBMS User Connection only through specific Application I am developing a multi-user-application windows desktop application.
For User Management i use the DMBS (Oracle, MySQL, MSSQL, Postgre).
So each user has an database user account.
I do not want the user to connect to the database directly and read / write data.
The data should only be accessible connection should only be valid if they use my application.
I found this website by SQLDUDE where he describes some techniques.
One way to access the data only through a specific application is a logon trigger that checks for application_name.
However he also describes that this method can easily be spoofed as the user can specify the application_name once he knows it in the connection string.
(detailed explanation here - see Solution for Scenario #2)
He also mentions Application Roles.

A more secure approach you could use for this is called "Application
  Roles". When connecting from an application you assume a particular
  role and only that role is granted privileges required in the
  database.

So basically the user logs in with his login credentials but has no rights at all (only connect).
Then inside the application i call sp_setapprole with a password, once the connection is established so the application rules are granted.

Once this call succeeds then the connection gets the privileges of the
  application role and loses privileges of the actual user, which is
  what we want. So if someone tried to connect to the database from SSMS
  or SQLCMD, they will access the DB using their credentials, which
  won't have the required permissions on the tables, since only the
  application role has the rights on the tables. This is more secure &
  reliable approach, but one that requires application code change and
  as a DBA you will have to create the application role in SQL Server.

So Application Roles sounds like the way to go.
My question is:
Are application roles DMBS standard and available to most DBMS systems?
Is there way to trace the sp_setapprole login (e.g. with WireShark)?
Of course someone could reverse-engineer the application and get the credentials for the application role - but i guess that's unavoidable :)

A: I've seen one simpler solution in place and it worked fine. Here it is:

*

*The application is responsible for creating users at the database

*Before creating the user, the application hashed/encrypted their password, so if you  chose password "123456" it would be created as "RRU2992191910" (just an example)

*If the user tried to connect to the database with "123456" it wouldn't be successful

*Only the application was able to connect to database, because it hashed/encrypted the password informed by the user

This is not the most secure solution in the world, but it's very simple and does what you want. And it could be ported to different RDBMS's with no extra cost.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Basic Login with SESSIONS I'm having issues with a simple login using php and mysql.
Here is my code:
LOGIN.PHP
 <?php

    //include 'core/init.php';
    include 'functions.php';

    //JH check if user is logged in already
    if (loggedin()) {
        header("location: userarea.php");
        exit();
    }

    if ($_POST['login']) {
        $user = $_POST['user'];
        $pass = $_POST['pass'];
        $remember = $_POST['remember'];
        $password_encrip = hash('md5', $pass);

    if ($user&&$pass) {
        $login = mysql_query("SELECT * FROM users WHERE user='$user'");
        while  ($row = mysql_fetch_assoc($login))
        $db_pass = $row['pass']; {

        if ($password_encrip==$db_pass)
            $login_ok = TRUE;
        else
            $login_ok = FALSE;
        }

        if ($login_ok==TRUE) {

            if ($remember=="on")
                setcookie("user", $user, time()+7200);

            else if ($remember=="")
                $_SESSION['user']=$user;

            header("Location: userarea.php");
            exit();

        } else
            echo "ERROR: Username/Password combination incorrect!";

        } else
            die("ERROR: Hit back and enter username and password!");
    }

    ?>

    <form action="login.php" method="POST">
    Log in

    Username: <input type="text" name="user"/>

    Password: <input type="password" name="pass"/>

    <input type="checkbox" name="remember" />Remember me

    <input type="submit" name="login" value="Log in"/>
    </form>

FUNCTIONS.PHP
  <?php

    // REPORT ERRORS?
    //error_reporting(E_ALL);

    // SESSIONS CHECK
    session_start();

    //CONNECT TO DATABASE/CONNECT
    mysql_connect("localhost","MYSQL","PASS") or die();
    mysql_select_db('DB') or die();

    // LOGIN CHECK FUNCTION
    function loggedin()
    {
        if (isset($_SESSION['$user']) || isset($_COOKIE['$user']))
        {
            $loggedin = TRUE;
            return $loggedin;
        }
    }

    ?>

USERAREA.PHP
        <?php

    //include 'core/init.php';
    include 'functions.php';

    //JH check if user is logged in already
    if (!loggedin())
    {
        header("location: login.php");
        exit();
    }

    ?>

Welcome! You're Logged in
 Logout

    <?php
        echo "Welcome SESS: ".$_SESSION['user']. "
";
        echo "Welcome Cookie: ".$_COOKIE['user']. "
";
    ?>

Can anyone please help?

A: At the top of the PHP, put session_start(); (the first page you have posted).

A: Give this a shot one big thing is you always want to sanitize user inputs before there added to queries and also if $_post values are not set they don't return false so doing if($_POST['something']) would return an error
----------------------------------- LOGIN.PHP

<?php

    //include 'core/init.php';
    include 'functions.php';

    //JH check if user is logged in already
    if (loggedin()) {
        header("location: userarea.php");
        exit();
    }

    if ($_POST['login']) {
        $user = mysql_real_escape_string($_POST['user']);
        $pass = mysql_real_escape_string($_POST['pass']);
        $remember = mysql_real_escape_string($_POST['remember']);
        $password_encrip = hash('md5', $pass);

        if (!empty($user) && !empty($pass)) {
            $login = mysql_query("SELECT * FROM users WHERE user='$user' AND pass = '$password_encrip'");

            while ($row = mysql_fetch_assoc($login)) {

                if (count($row) > 0) {
                    $login_ok = TRUE;
                } else {
                    $login_ok = FALSE;
                }
            }

            if ($login_ok) {

                if ($remember == "on") {
                    setcookie("user", $user, time() + 7200);
                } else if ($remember == "") $_SESSION['user'] = $user;

                header("Location: userarea.php");
                exit();

            } else {
                echo "ERROR: Username/Password combination incorrect!";
            }

        } else {
            die("ERROR: Hit back and enter username and password!");
        }
    }

?>

<form action="login.php" method="POST">
    Log in

    Username: <input type="text" name="user"/>

    Password: <input type="password" name="pass"/>

    <input type="checkbox" name="remember"/>Remember me

    <input type="submit" name="login" value="Log in"/>
</form>

------------------------------------------ FUNCTIONS.PHP

<?php

    // REPORT ERRORS?
    //error_reporting(E_ALL);

    // SESSIONS CHECK
    session_start();

    //CONNECT TO DATABASE/CONNECT
    mysql_connect("localhost", "MYSQL", "PASS") or die();
    mysql_select_db('DB') or die();

    // LOGIN CHECK FUNCTION
    function loggedin() {
        if (isset($_SESSION['$user']) || isset($_COOKIE['$user'])) {
            $loggedin = TRUE;
            return $loggedin;
        }
    }

?>

---------------------------------------------- USERAREA.PHP

<?php

    //include 'core/init.php';
    include 'functions.php';

    //JH check if user is logged in already
    if (!loggedin()) {
        header("location: login.php");
        exit();
    }

?>

Welcome! You're Logged in
 Logout

<?php
    echo "Welcome SESS: " . $_SESSION['user'] . "
";
    echo "Welcome Cookie: " . $_COOKIE['user'] . "
";
?>


text:
Q: Pasting X selection (not clipboard contents) with keyboard I'd like to be able to paste the X selection using the keyboard.  Currently I have to use the middle mouse button to do this.
I gather that faking a middle mouse button press is fairly easy to do, but such a solution would also require moving the mouse pointer to the location of the text caret.
Is there a better way to do this?

A: xdotool click 2

This simulates the mouse button click directly, and does not require to use xsel / xdotool type ....

A: I am using Ubuntu 12 and was having a problem pasting text from xterm in gedit (and any other app). Also, I use a laptop with no middle mouse button like many people (there really is no clipboard mercy for linux users without middle buttons, and no: right-click+left_click is not working as a substitute).
While I think the "xsel | xvkbd -xsendevent -file -" method is pretty cool. I found the simplest solution was to run the preinstalled "gnome-terminal" instead of "xterminal". "gnome-terminal" supports a right-click copy to clip-board command. I could then "Edit Menu->Paste" into gedit or use shift-insert. "gnome-terminal" came preinstalled with Ubuntu 12. Other debian/gnome installations should be able to install it via:
sudo apt-get install gnome-terminal

In Ubuntu, add it to the left launcher by clicking "Dash Home" button at the top of the launcher bar. In the resulting search box, type terminal. You can drag the "Terminal" icon to the launcher bar.

A: Apparently Shift+Insert may not work properly on some installations of GTK 3, at least on FreeBSD.  The issue is described as:

Shift-Insert is not pasting primary selection. Instead, it is bound to
  paste the clipboard (for which Control-V is already used). Hence,
  there is no keyboard-only way to insert primary selection. One must
  drag the mouse to there and middle click. This makes interaction
  between terminals and GTK uncomfortable.

A recent (as of this writing) bug report and patch are available:
http://www.freebsd.org/cgi/query-pr.cgi?pr=188264

A: On some default linux setups, Shift+Insert will perform an X-selection-paste. As you noted, this is distinctly different from the X-clipboard-paste command, the binding for which often varies by application. If that doesn't work here are a couple other keys to try:

*

*Ctrl+V

*Ctrl+Shift+V

*Ctrl+Shift+Insert
No go? Your Desktop Environment or Window Manager probably doesn't have them configured, and it's complicated because —even under the banner of one DE or WM— each toolkit (e.g. GTK, Qt, Etc.) may well have different default bindings. Some programs (e.g. gvim) even have their own internal copy registers that are not necessarily synced to the graphical environment they run in. To top it off, even when a program does use the X-clipboard system, X has multiple systems to choose from. The two most basic are the selection buffer —which always has whatever the last thing selected was (execpt when it doesn't)— and the copy buffer —which things usually need to be specifically copied into. To do an explicit copy into the latter system you can try any of these on for size:

*

*Ctrl+C

*Shift+Ctrl+C

*Ctrl+Insert

If none of that is just magically working for you, there are two ways you can go.

*

*There's an app for that!™ Use one of the various clipboard manager programs to handle this for you. The most popular seem to be Parcellite and Glippy, but you can check out other alternatives here. See also this question about advanced clipboard managers

*Hack it yourself.
So lets say you want to hack it.
Short of writing your own code and tapping into the X api, the hacker tools for the job are a couple of little command line utilities that give you a window into the mind of X. Just a small window mind you, the whole view too scary.
The first tool is xsel. This little jobber will spit out whatever is in X's selection buffer at any given time.
Now you need to get that into your program. There are two options for this. One is xdotool which allows you to mimic sending events to the Xorg input system. You can use it's type method like xdotool type foo_bar to mimic typing 'foo_bar' at the cursor. Combined, you get something like this:
$ xdotool type $(xsel)

The other one is xvkbd which sends keyboard events from a lower subsystem. You can pipe keystrokes into it on STDIN. Combined with xsel, you get something like this:
$ xsel | xvkbd -xsendevent -file -

Great. Now for that keybinding to run this stuff. If you run Gnome-2, you can add a custom shortcut in System -> Preferences -> Keyboard shortcuts. If you use a different DE or WM this excersize is left up to the reader.
The last note is that when binding commands to keyboard shortcuts it is often necessary to only have one command, not two commands connected with a pipe like we use above. You can accomplish this by invoking your piped command as a command string argumetn to a new shell like this:
sh -c 'xsel | xvkbd -xsendevent -file -'
sh -c 'xdotool type "$(xsel)"'

A: On my 20.04 Alt+Shift+Insert paste the same as middle click


text:
Q: How to log SQLite queries on iPhone I'm doing an iPhone application, and I'm using SQLite.
The problem is that I had some issues with the query (I did bad binding) so, this is my question:
How can I log in my iPhone application the effective SQL query/statement with the bindings that SQLite receives?
Thanks.

A: Easiest way would be to create a wrapper to your call to sql functions and add log functionality to it.
I'm not sure the file written by the PRAGMA journal_mode is readable, but I couldnt use this pragma.
You can also have a look at an excellent existing wrapper from Gus Mueller: fmdb

A: I don't think this is possible.
As far as I know, prepared statements aren't built into "full SQL" strings before they get to the database engine. The parameter values aren't escaped, quoted, and inserted into the SQL string only to be parsed and decoded in the next step: the values bypass the query parsing entirely and go straight into the data engine.


text:
Q: count number of rows between rows where value is 1 in mysql I have the following data:
client, visit page 2
1,0
2,0
3,1
4,0
5,1
6,0
7,0
8,1

now I want to know how many clients have been since the last client visited page 2. So the outcome would be:
client 3, 3; client 5, 2; client 8,3

eventually I only need to numbers of occurrences of the gaps so here I would have as an ultimate answer:
gap,# occurrences
1,0
2,1
3,2
4,0

Is this possible in mysql and best would be without a for loop?
The data is to large to load it completely in python/php.
One way would be to use python/php and select all rows where 'visit page 2' is 1 and then do a for loop with a select query with count(rows) between succes n-1 and succes n. But this takes to much time.

A: Creates the effect of a row_number with the @rn variable, and maintains the prior row number where vp2=1 occurred in variable @lastWas.
The cross-join facilitates not having to do set @rn:= etc stuff at the top. And that is the sole purpose of it.
Note the derived table named inr. All derived tables require an alias name even if not used explicitly by name. One can run the innards of the derived table separately. This is used at the beginning of development for a sanity check, then several of the columns there can be ignored in the query on the outside that wraps it. Certainly as seen here. See inr-only at bottom of answer for a view of just that derived table.
Schema
create table x
(   id int auto_increment primary key,
    client int not null,
    vp2 int not null
);

insert x(client,vp2) values
(1,0),(2,0),(3,1),(4,0),
(5,1),(6,0),(7,0),(8,1);

Query
select client,rn-lastWas as gap from
(   select id,
    client,
    vp2,
    @lastWas as lastWas,
    greatest(@rn:=@rn+1,@lastWas:=if(vp2=1,@rn,@lastWas)) as junk, -- forces recalc immediacy inside greatest() function, caring not at all of results
    @rn as rn
    from x
    cross join (select @rn:=0 as r,@lastWas:=0 as l) as blahJunk
    order by id
) inr
where vp2=1

Results
+--------+------+
| client | gap  |
+--------+------+
|      3 |    3 |
|      5 |    2 |
|      8 |    3 |
+--------+------+

Advanced Mysql User Variable Techniques

inr-only:
This is a view of just the inr derived table, to help visualize the above.
+----+--------+-----+---------+------+------+
| id | client | vp2 | lastWas | junk | rn   |
+----+--------+-----+---------+------+------+
|  1 |      1 |   0 | 0       | 1    |    1 |
|  2 |      2 |   0 | 0       | 2    |    2 |
|  3 |      3 |   1 | 0       | 3    |    3 |
|  4 |      4 |   0 | 3       | 4    |    4 |
|  5 |      5 |   1 | 3       | 5    |    5 |
|  6 |      6 |   0 | 5       | 6    |    6 |
|  7 |      7 |   0 | 5       | 7    |    7 |
|  8 |      8 |   1 | 5       | 8    |    8 |
+----+--------+-----+---------+------+------+

brownie points section below
More schema
create table bon
(   -- bunch of numbers
    i int not null
);
insert bon(i) values (1),(2),(3),(4);

Brownie points query
select bon.i as gap,ifnull(qry.rowCount,0) as occurrences
from bon
left join
(   select gap,count(*) as rowCount from
    (   select client,rn-lastWas as gap from
        (   select id,
            client,
            vp2,
            @lastWas as lastWas,
            greatest(@rn:=@rn+1,@lastWas:=if(vp2=1,@rn,@lastWas)) as junk, -- forces recalc
            @rn as rn
            from x
            cross join (select @rn:=0 as r,@lastWas:=0 as l) as blahJunk
            order by id
        ) inr -- derived table alias
        where vp2=1
    ) xxx -- every derived table requires an alias
    group by gap
) qry -- derived table alias
on qry.gap=bon.i

results
+-----+-------------+
| gap | occurrences |
+-----+-------------+
|   1 |           0 |
|   2 |           1 |
|   3 |           2 |
|   4 |           0 |
+-----+-------------+

A: One approach, keep a total of the current gap and reset on each visit.
select v, count(*) from(
    select client,
           case when visit = 0 then @v := @v + 1
                else @v := @v + 1 end v,
           case when visit = 1 then @v := 0 end gap
    from table join (select @v := 0) v
    order by client
) q
where gap is not null
group by v
;


text:
Q: Passing data between Fragments in the same Activity Am working in a project with an Activity that host many fragments. Now I need to share some data (integers, strings, arraylist) between these fragments.
First time i used static fields but I think it's a bad way
then I found this solution.
but in my case there is no button to click i have just to navigate between fragments
is there any simple way to make sharing data between fragments

A: I think the best solution for you is to have the variables inside the main activity and access them from fragments. I mean, if you have to do THE SAME in all fragments, you can write the code inside the activity and just call the method you need.
You need to use an interface for this purpose
public interface DataCommunication {
    public String getMyVariableX();
    public void setMyVariableX(String x);
    public int getMyVariableY();
    public void setMyVariableY(int y);
}

Then, implement it inside your activity
public class MainActivity extends Activity implements DataCommunication {

    private String x;
    private int y;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
    }

    ...

    @Override
    public String getMyVariableX(){
        return x;
    }

    @Override
    public void setMyVariableX(String x){
        //do whatever or just set
        this.x = x;
    }

    @Override
    public int getMyVariableY(){
        return y;
    }

    @Override
    public void setMyVariableY(int y){
        //do whatever or just set
        this.y = y;
    }

    ...

Then, attach the activity in ALL your fragments:
public class Fragment_1 extends Fragment{

    DataCommunication mCallback;

 @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (DataCommunication) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement DataCommunication");
        }
    }

    ...

And finally, when you need to use a variable inside a fragment, just use get and se methods you've created

https://developer.android.com/training/basics/fragments/communicating.html

A: The easiest way to do this is to use Bundle. You do something like this:
Fragment A:
Bundle b = new Bundle();
b.putString("Key", "YourValue");
b.putInt("YourKey", 1);

FragmentB fragB = new FragmentB();
fragB.setArguments(b);
getFragmentManager().beginTransaction().replace(R.id.your_container, fragB);

Fragment B:
Bundle b = this.getArguments();
if(b != null){
   int i = b.getInt("YourKey");
   String s =b.getString("Key");
}

This is the easiest way that I have found to send data from one fragment to another. Hope it helps someone.

A: You have some options:
Options 1: If you need to share information between fragments, you can use the SharedPreferences to store the information. This is an example:
SharedPreferences settings = context.getSharedPreferences("Preferences", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("string1", var);
    editor.putBoolean("bool1", var);
    ...
    editor.commit();

Option 2: If you have instantiated a fragment, you can create a set method to store some kind of information in the fragment. For example, if you want to pass an array of string, you can create an array variable in the fragment (with setter method). Later, when you have instantiated this fragment, you can use the setter method to pass this array to the fragment.

A: You can create a Application class ( i mean extend Application ) then take some variable what you need , make getter and setter method. set value to variable and get value when and where you need. if you wish i can give you some demo code for it .

A: We can share the Data between fragments in 2 ways.

*

*By Using Bundle

*By using Persistence Storage
By Using Bundle:-
Bundle bundle=new Bundle();
bundle.putString("firstName",Fist);
bundle.putString("LastName",lastN);

Second Persistence Storage :-
this you can check how to store Data in Persistence Storage.
Hope it will work for you

A: Use a SharedViewModel proposed at the official ViewModel documentation
First implement fragment-ktx to instantiate your viewmodel more easily
dependencies {
implementation "androidx.fragment:fragment-ktx:1.2.2"
}

Then, you just need to put inside the viewmodel the data you will be sharing with the other fragment
class SharedViewModel : ViewModel() {
    val selected = MutableLiveData<Item>()

    fun select(item: Item) {
        selected.value = item
    }
}

Then, to finish up, just instantiate your viewModel in each fragment, and set the value of selected from the fragment you want to set the data
Fragment A
class MasterFragment : Fragment() {

    private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        itemSelector.setOnClickListener { item ->
        model.select(item)
      }

    }
}

And then, just listen for this value at your Fragment destination
Fragment B
class DetailFragment : Fragment() {

        private val model: SharedViewModel by activityViewModels()

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            model.selected.observe(viewLifecycleOwner, Observer<Item> { item ->
                // Update the UI
            })
        }
    }

This answer can help you, https://stackoverflow.com/a/60696777/6761436

A: 1.Use BroadCastReceiver (a little complicated)
2.Use SharePreference
3.save data into MyApplication extends Application


text:
Q: Setting up Salesforce to receive Leads from third party via Webservice I am setting up my organization's Salesforce instance to accept Leads from a third party system via web-service. Following  are the steps I took till now

*

*Created an Integration user in Salesforce.

*Added third party's domain in Remote Site Setting.

*Under Setup -> Build -> Create -> Apps I added a new Connected Apps and generated Client Key and Client Secret.

They are asking for endpoint URL. I gave them following URL
https://test.salesforce.com
They are still not able to make an authentication connection to Salesforce. Am I missing some other setup step? Is this the correct URL to use as the endpoint URL?

A: For Production endpoint is https://login.salesforce.com and for sandbox endpoint is https://test.salesforce.com/. If you are using OAuth for authentication then you have to send a request for authorization at https://login.salesforce.com/services/oauth2/authorize and then after authorization you need to send token request at  https://login.salesforce.com/services/oauth2/token for production. Same will be the case for test environment except the endpoint will change.


text:
Q: Jasper Reports generating blank cells for an instance and populate value if rerun for same instance again I am using jasper reports 4.1.1 when i am exporting the report in excel some cells appears blanks for the same data set and when the report is rerun again the data gets populated.
The above problem is occurring randomly.
JasperPrint print=JasperFillManager.fillReport(jrXmlPathList.get(i),parameters,conn);
list.add(print); OutputStream output = new FileOutputStream(new File(reportVO.getxFilePath()));
JRXlsxExporter exporterXLS = new JRXlsxExporter();
exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE,Boolean.TRUE);
exporterXLS.setParameter(JRXlsExporterParameter.SHEET_NAMES, sheetnames);
exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT_LIST, list);
exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, output);
exporterXLS.exportReport();

A: Try this:
File xlsx = new File("C:/Users/Sadagopan/Documents/sample.xlsX");
JRXlsxExporter Xlsxexporter = new JRXlsxExporter();
Xlsxexporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
Xlsxexporter.setParameter(JRExporterParameter.OUTPUT_FILE, xlsx);
Xlsxexporter.exportReport();


text:
Q: How do I split a .txt file into a multidimensional array or dictionary in Swift? The body of my txt file that I need to parse in in this format:
Name: LittleX
Package: com.ioscreatix.littlex
Description: iPhone X features for Non-X devices on iOS 11, and iPad Dock and PiP for All iOS 11 Devices on iOS 11

Name: InteliX
Package: com.ioscreatix.intelix
Description: Grouped Notifications for iOS 11

I want my array to have each package separately in an array listed by their name values with a dictionary for  description and package. How would I accomplish this?
This is the code i have so far:
var unfilteredPackagesArray = [String]()
    var secondFilteredPackagesArray = [String]()
    var finalFilteredPackagesArray = [String]()

if let startWordsURL = Bundle.main.url(forResource: "Packages", withExtension: "") {
            if let startWords = try? String(contentsOf: startWordsURL) {
                unfilteredPackagesArray = startWords.components(separatedBy: "\n\n")

                print(unfilteredPackagesArray)
                secondFilteredPackagesArray = startWords.components(separatedBy: "\n")

                finalFilteredPackagesArray = startWords.components(separatedBy: ":")

                print(secondFilteredPackagesArray)

What is the best way to do this? Create Package objects and make an array of them?

A: Yes, go ahead!
Yes, I think you should create a Package struct and then generate an array of Package(s).
Here's the code.
1. Define the Package struct
struct Package {
    let name: String
    let package: String
    let description: String
}

2. Load the file
guard
    let url = Bundle.main.url(forResource: "Packages", withExtension: "txt"),
    let content = try? String(contentsOf: url)
else { fatalError() }

3. Extract the lines
let lines = content
    .components(separatedBy: CharacterSet.newlines)
    .filter { !$0.isEmpty }
    .compactMap { $0.components(separatedBy: ": ").last }

4. Extract the 3 arrays
let nameLines = lines.enumerated().filter { $0.offset % 3 == 0 }.map { $0.element }
let packageLines = lines.enumerated().filter { $0.offset % 3 == 1 }.map { $0.element }
let descriptionLines = lines.enumerated().filter { $0.offset % 3 == 2 }.map { $0.element }

5. Generate an array of Package(s)
let packages = zip(nameLines, zip(packageLines, descriptionLines))
    .map { (name: $0, package: $1.0, description: $1.1) }
    .map (Package.init)

6. Test
print(packages)

[
    Package(name: "LittleX",
            package: "com.ioscreatix.littlex",
            description: "iPhone X features for Non-X devices on iOS 11, and iPad Dock and PiP for All iOS 11 Devices on iOS 11"
    ),
    Package(name: "InteliX",
            package: "com.ioscreatix.intelix",
            description: "Grouped Notifications for iOS 11"
    )
]


text:
Q: Is it possible to cause a interpreter infinite loop? I'm considering a possible denial of service attack scenario, where a script cause a system resource outage by recursively invoking itself as interpreter.
The principle is as follow:
The script specifies at its first line, in the form of a #! shabang, the absolute path of itself, as its own interpreter.
The system kernel will, depend on its support, automatically invoke the interpreter during the execve system call, prepending the interpreter, to the vector of arguments.
Such invocation will exhaust the limit on the size of program arguments ({ARG_MAX}) set in the system, thus causing a (possibly isolated) failure.
Experiment
I've created 2 different set of attack vectors,

*

*The first one, invoking itself
#!/usr/local/bin/recurse

*The second one, invoking each other.
#!/usr/local/bin/recurse-1

#!/usr/local/bin/recurse-2

I've tested these 2 attack vectors on macOS Big Sur 11.5.2. And when I check the exit status using echo $?, it shows 0, which means the processes completed successfully.
Question.
Had modern operating systems been patched against such attack? Are there research papers on this?

A: On Linux, I get the following:
A script with a nonexisting interpreter on the hashbang line (execve() gives ENOEXEC):
$ cat brokenhashbang.sh
#!/bin/nonexisting
echo hello
$ ./brokenhashbang.sh
bash: ./brokenhashbang.sh: /bin/nonexisting: bad interpreter: No such file or directory

A script with recursive hashbang (ELOOP):
$ cat /tmp/recursivehashbang.sh
#!/tmp/recursivehashbang.sh
echo hello
$ /tmp/recursivehashbang.sh
bash: /tmp/recursivehashbang.sh: /tmp/recursivehashbang.sh: bad interpreter: Too many levels of symbolic links

A script with an existing but non-executable interpreter (EACCESS):
$ cat noexechashbang.sh
#!/etc/passwd
echo "hello?"
$ ./noexechashbang.sh
bash: ./noexechashbang.sh: /etc/passwd: bad interpreter: Permission denied

It's not just Bash: Dash, ksh and zsh give similar errors.
If the script doesn't have a hashbang, or the hashbang points to an otherwise non-executable file (which needs to have +x, you get ENOEXEC), then the behavior differs a bit. Bash runs the file itself as a shell script, while zsh seems to look inside to see if there's a hashbang line, and then either tries to start that interpreter, or runs it with /bin/sh. Running the script via the shell on ENOEXEC is the POSIX-specified behaviour for the shell and for the execlp()/execvp() functions.
(For the case with a nonexisting interpreter, Dash just gives the confusing dash: 1: ./brokenhashbang.sh: not found, as if the script itself didn't exist. But I think it's the same error from the underlying system call and Dash is just too simple to check which file is missing.)
In any case, I can't see what the attack here would be, since if they're running a command of your choosing, you can already do whatever you like. Not by having a nonexisting interpreter for the script, but a working one.

A: NOTE The following is tested on macOS Big Sur 11.5.2.
According to the standard (as well as existing practice), the shell will attempt to interpret the file and execute the commands within if the exec function call returns with failure.
Here's a 3rd attack vector:
#!/usr/local/bin/recurse

eval 'printf "%s\n" xxx'

After naming this file as /usr/local/bin/recurse and executing it, the string xxx was printed on standard output, despite the interpreter loop is supposed to prevent the command from being evaluated.
If using a C program to invoke the script with the execv function, the errno value set by the function call is ENOEXEC.


text:
Q: Как определить иной массив строк для TextView Уважаемые разработчики. Пишу своё первое полноценное приложение на android, что-то вроде текстовой игры. Столкнулся с небольшой проблемой.
Есть TextView, при нажатии на который выводится следующий текст. При появлении текста с определенным индексом выводится список вариантов ответа (ещё два TextView).
Проблема заключается в том, что после нажатие на один один из вариантов ответа не могу определить другой массив строк для основного TextView.
Возможно написал не совсем понятным языком, да и сам код возможно не очень, но буду рад помощи. Заранее спасибо.
        mMainTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //индексация массива
            mCurrentIndex = (mCurrentIndex + 1) % mainTextArray.meetingTextsArray.length;

             //массив строк с изменением индекса при клике
            int text = mainTextArray.meetingTextsArray[mCurrentIndex].getTextResId();
            mMainTextView.setText(text);
            //при нужном индексе всплывают варианты ответа(ещё 2 textview)
            if(mCurrentIndex == 1) {
                showChoiceButtons(R.string.meeting_left_text, R.string.meeting_right_text,
                        mMainTextView);

                leftChoiceButtonPressed();
            }
        }
    });

}

private void leftChoiceButtonPressed() {

 //первый вариант ответа, затем нужно изменить массив строк для основного
 //textview
    mLeftChoiceTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mMainTextView.setText("Тестим");
        }
    });
}

    private void showChoiceButtons(int leftButton, int rightButton, View view) {
    //показать всплывающие варианты ответа
    mLeftChoiceTextView.setVisibility(View.VISIBLE);
    mRightChoiceTextView.setVisibility(View.VISIBLE);
    mLeftChoiceTextView.setText(leftButton);
    mRightChoiceTextView.setText(rightButton);
    view.setClickable(false);
}

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    tools:context=".BookActivity"
    tools:layout_editor_absoluteY="81dp">

<TextView
    android:id="@+id/main_text"
    android:layout_width="218dp"
    android:layout_height="217dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="144dp"
    android:gravity="center_horizontal|center_vertical"
    android:textSize="15sp"
    android:textStyle="bold"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/left_choice_text"
    android:layout_width="114dp"
    android:layout_height="113dp"
    android:layout_marginBottom="16dp"
    android:layout_marginStart="32dp"
    android:textSize="15sp"
    android:textStyle="bold"
    android:textColor="@color/light"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<TextView
    android:id="@+id/right_choice_text"
    android:layout_width="114dp"
    android:layout_height="113dp"
    android:layout_marginBottom="16dp"
    android:layout_marginEnd="32dp"
    android:textSize="15sp"
    android:textStyle="bold"
    android:textColor="@color/light"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent" />

A: Если я правильно понял, вы хотите менять массив, текст главного textView и текст на остальных 2 textView при клике на, например, левый textView.
Я бы сделал так:
changeTextArrays(0); // 0 - начальное значение
mMainTextView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // отсюда перенесено несколько строк в метод changeTextArrays
        //при нужном индексе всплывают варианты ответа(ещё 2 textview)
        if(mCurrentIndex == 1) {
            showChoiceButtons(R.string.meeting_left_text, R.string.meeting_right_text,
                    mMainTextView);

            //leftChoiceButtonPressed(); // тут только устанавливается действие клика. Поэтому его можно вызвать 1 раз, поэтому написал после mMainTextView.setOnClickListener
        }
    }
});
leftChoiceButtonPressed();
}

private void leftChoiceButtonPressed() {
    mLeftChoiceTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mMainTextView.setText("Тестим");// поменяли главный текст, да?

            //по логике надо ещё названия левой и правой текстов поменять на те,
            //что должны отобразиться при выборе левого клика:
            showChoiceButtons(R.string.left_text_новый, R.string.right_text_новый,
                    mMainTextView);

            //на счёт смены массива. Предложу такой вариант:
            changeTextArrays(1); // в аргументах к методу можно передать условие для смены массива
        }
    });
}

// этот метод можно вызвать до mMainTextView.setOnClickListener(...
// так как я перенёс строки с индексами из mMainTextView.setOnClickListener
private void changeTextArrays(int type){

// у нас будет временный массив, куда будем присваивать другие массивы в зависимости от условий (например, type)
// tempTextArray - массив, с типом, как у mainTextArray
if(type == 0){
        tempTextArray = mainTextArray; // начальный массив, без изменений
    } else if(type == 1){
        //тут меняем массив
        tempTextArray = mainTextArray2; // массив, который должен работать после клика
    } else if(type == 2){
        //тут меняем массив
        tempTextArray = mainTextArray3; // массив 3й и так далее
    }

    //индексация массива
        mCurrentIndex = (mCurrentIndex + 1) % tempTextArray.meetingTextsArray.length;

        //массив строк с изменением индекса при клике
        int text = tempTextArray.meetingTextsArray[mCurrentIndex].getTextResId();
        mMainTextView.setText(text);
}

Но этот пример также нуждается в доработке, например, клик по левому textView будет вызывать метод с одним и тем же значением changeTextArrays(1); поэтому можно заменить цифру 1 на глобальную переменную, которая будет также изменяться, как и массив в методе changeTextArrays


text:
Q: Change the color of static text C++ I created the dialog form for MFC class by editing .rc file with form designer as follows,

I want to change the color of above Namodaya Balaarachchi text field.
But there is no any property in following properties window.

Can anyone help me to change the color of above static text?

A: I am using visual studio 2017 and create a Dialog based MFC project. After that choose "Resource View" and double click to open the dialog. Right click and choose Class Wizard, at Message, double click WM_CTLCOLOR, and select OnCtlColor, and Edit Code, add following "switch" section.
HBRUSH CMFCApplication1Dlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
    HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);

    // TODO:  Change any attributes of the DC here
    switch (nCtlColor)
    {
    case CTLCOLOR_STATIC:
        pDC->SetTextColor(RGB(255, 0, 0));
        return (HBRUSH)GetStockObject(NULL_BRUSH);
    }
    // TODO:  Return a different brush if the default is not desired
    return hbr;
}

F5 run, and the text change to red:


text:
Q: Retrieve SQL query using python every few seconds I am trying to retrieve an ongoing insert script from SQL Server using python and output the data one by one every 3seconds. Please help a noobie here!
However, I am getting the error message:

Nothing in database
  name 'prev_id' is not defined

Any ideas why?
import time
sql_conn = connectSQLServer('ODBC Driver 13 for SQL Server', 'DESKTOP\SQLEXPRESS', 'display')

mycursor = sql_conn.cursor()
global prev_id
a = 0
d = { 'x': [], 'y': [] ,'z': []  , 'a':[] }
while True:
    try:
        time.sleep(3)
        a=a+1
        print(a)
        sql = "SELECT ID,position ,action ,sync FROM dbo.data2 WHERE ID > %s" % (prev_id)
        mycursor.execute(sql)
        myresult = mycursor.fetchall()
        #d = { 'x': [], 'y': [] }
        for x in myresult:
            print(x)
            prev_id = x[0]
            d['x'].append(x[0])
            d['y'].append(x[1])
            d['z'].append(x[2])
            d['a'].append(x[3])
        df = pd.DataFrame(d)

    except Exception as error:
        print("Nothing in database\n")
        print(error)
sql_conn.commit()

A: You are getting the error message because you have not assigned any value to the prev_id variable before you use it the first time. Presumably you would want to assign it to 0 or something equivalent.


text:
Q: How to deserialize xml namespace into POJO property with jackson? Here are my xml:
<request xmlns="https://blabla">
</request>

I want to get its xmlns attribute with jackson. Here is my POJO:
@JacksonXmlRootElement(localName="request")
@Data
public class Request{
    @JacksonXmlProperty(localName = "xmlns",isAttribute=true)
    private String xmlns
}

but I get null for request.xmlns.It seems jackson ingored this property as if xmlnsis not an attribute of my POJO.
I need to deserialize this property into POJO property, Could anyone helps?


text:
Q: How to insert new function without adding inside the self object in JS I have the following JS code, how could I insert new function without adding inside the self object?
Function select(selector){
Var self = {
Print: ()=>{},
Delete: ()=>{}
};
Return self;
}

//I want to add new function here so I can call it by using select("something").newFunc()
Is there any ways to do that? I tried something as below, but I'm wondering if there's another way to do it.
After several hours of testing, I tried to assign all the methods inside a variable prototype's method (A), and then set A's prototype back to the variable's prototype. Then I can call it using the variable.
var myScript = function(selector){
return new myScript.prototype.init(selector);
}
var init = myScript.prototype.init = function(selector){
var self = {
//codes
};
return self;
}
init.prototype = myScript.prototype;
(function(mS){
mS.prototype.newFunc = function(){
return "Coding is Fun";
}
})(myScript);

After that, I can use myScript("something").newFunc()
That's what I've tried, please share if you know another way, thanks.

A: Constructor functions do not require the 'self' object you designed. In your case

*

*You return the self object from the constructor

*You use arrow functions that do not change the value of this. Arrow functions are cool, but they are not interchangeable with regular functions (at least not in every case - and inside a constructor function is such a case)
Look at the two constructor functions below (Select1 is based on your code, Select2 is based on a "how to do it"):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

// adding a self object - arrow functions
function Select1(selector) {
  this.selector = selector
  var self = {
    print: () => {
      return 'Select1 print: ' + this.selector
    },
    delete: () => {
      return 'Select1 delete: ' + this.selector
    }
  }
  return self
}

// no self object - regular functions
function Select2(selector) {
  this.selector = selector
  this.print = function() {
    return 'Select2 print: ' + this.selector
  }
  this.delete = function() {
    return 'Select2 delete: ' + this.selector
  }
  return this
}

// instantiating the two different Objects
let select1 = new Select1('selector1')
let select2 = new Select2('selector2')

// calling the print method on both Objects
console.log(select1.print())
console.log(select2.print())

// logging both objects
console.log(select1)
console.log(select2)

// modifying the prototype of the constructor functions
// modifying Select1.self's prototype would throw an error
/*Select1.prototype.self.newFunc = () => {
  return 'Select1 newFunc: ' + this.selector
}*/
Select1.prototype.newFunc = function() {
  return 'Select1 newFunc: ' + this.selector
}
Select2.prototype.newFunc = function() {
  return 'Select2 newFunc: ' + this.selector
}

// logging the new function

// logging select1.newFunc() would throw an error, as you return 'self', that's not modified
// console.log(select1.newFunc())
console.log(select2.newFunc())

// logging the modified object
console.log(select1)
console.log(select2)

BUT

*

*You should use correct indentation - code is much more readable that way

*You should follow naming and casing conventions, so others can quickly see what is what in your code (constructor functions begin with a capital letter, but other reserved words do not (so casing is important too)
USAGE
And if you want to use it like myScript('selector').myFunc(), then you need to wrap it in another function (like you did in your second code sample):

function Select2(selector) {
  this.selector = selector
  this.print = function() {
    return 'Select2 print: ' + this.selector
  }
  this.delete = function() {
    return 'Select2 delete: ' + this.selector
  }
  return this
}

function myFunc(selector) {
  return new Select2(selector)
}

console.log(myFunc('s1').print())
console.log(myFunc('s2').print())

If you want to be able to set the selector, then you need a set() function:

function Select2(selector) {
  this.selector = selector
  this.print = function() {
    return 'Select2 print: ' + this.selector
  }
  this.delete = function() {
    return 'Select2 delete: ' + this.selector
  }
  // this.setSelector is the set() function
  this.setSelector = function(s) {
    this.selector = s
  }
  return this
}

function myFunc(selector) {
  return new Select2(selector)
}

// instantiating Select2
const selector2 = myFunc('s1')

console.log(selector2.print()) // expected: s1

// setting the 'selector' of the instantiated
// Select2 Object to a new value
selector2.setSelector('s2')
console.log(selector2.print()) // expected: s2


text:
Q: hyperlink in DataGridView's column
Possible Duplicate:
how to give hyperlink to Image Column in Datagridview

can i give hyperlink in DataGridView's column that contains Image.. and after clicking on image, specified url should open ??

A: you can use Dictionary<Image,string> to map links to image , and then handle click event on Image cell
Dictionary<Image,string> UrlDicationary = new Dictionary<Image, string>();
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
     if(e.ColumnIndex == your_image_column_index)
     {
         Image image = dataGridView1[e.ColumnIndex, e.RowIndex].Value as Image;
         if(image != null)
         {
               string url;
               if(UrlDicationary.TryGetValue(image, out url))
               {
                    Process.Start(url);
               }
         }
     }
}

You need to fill dictionary first


text:
Q: enviar post a Python desde JavaScript Iniciar archivo Python desde post por medio de JavaScript

No se inicia mi archivo Python.
Tengo un formulario que envía un post a un archivo Python.
El archivo Python no se ejecuta.
El post se envía correctamente pero no se inicia el archivo Python.

Explicación a fondo del programa:
Tengo un formulario:
<div id="agrrergar_panel" style="display: block;">
 <form method="post" id="Formulario">
   <input type="panel" id="panel_agregado" name="panel_add" value="Panel">
   <input type="submit" id="submit_boton" value="Crear">
 </form>
</div>

Al rellenar el formulario le daremos al botón "crear" el cual enviara un post con el valor de input que hemos escrito anteriormente.
<script>
$('#Formulario').submit(function(){
   event.preventDefault();
   $.post("Archivo_python.py", $(this).serialize());
   event.preventDefault();
   });
</script>

Al pulsar el botón se enviara el post y se activara el archivo Python como vemos en la imagen.

Pero el archivo Python no se ejecuta.
Se envía el valor del input pero no se ejecuta el programa Python.

Archivo Python
El archivo Python es el que vemos a continuación
El programa Python envía el valor del formulario a un Topic mqtt:
import paho.mqtt.publish as publish #libreria  mqtt
import cgi #libreria para recivir el post
form = cgi.FieldStorage()#cojemos el valor del post
name_cambiado = form["panel_add"].value#aqui guardamos el nombre del panel enviado desde el post

print(name_cambiado)#imprimimos para ver si se hizo correctamente la transferencia

#enviamos valor del formulario a un topic mqtt
broker_address = "localhost" #ip del mqtt

#topic a donde enviamos el valor del formulario
topic_id = "Panel/id" #topic de la id del panel
topic_name = "Panel/name" # topic del nombre del panel

nombre_pnale_nmsg = name_cambiado # mensaje del formulario que hemos seleccionado en el input
id_pnale_nmsg = "Panel prueba" #id del panel prueba

msgs = [{'topic': topic_id, 'payload': id_pnale_nmsg},#enviamos el al topic id la id de nuestro panel en este caso "Panel prueba"
(topic_name, nombre_pnale_nmsg, 0, False)] #enviamos al topic de nombre de panel el valor que hemos puesto en el input del formulario

publish.multiple(msgs, hostname=broker_address)# publicamos a los Topics

El post aunque se envía no se ejecuta el archivo Python

En respuesta de red del post veo que se ve igual que en el apartado de vista previa.

Hice varias pruebas para descartar errores.
Observe que el envió de valores a Topics se hacían correctamente.
El servido tiene instalado Python y sus respectivas librerías, no se cual podría ser el error del porque no se ejecuta el archivo Python.
Agradezco de antemano vuestra ayuda.


text:
Q: Spring-Kafka Concurrency Property I am progressing on writing my first Kafka Consumer by using Spring-Kafka. Had a look at the different options provided by framework, and have few doubts on the same. Can someone please clarify below if you have already worked on it.
Question - 1 : As per Spring-Kafka documentation, there are 2 ways to implement Kafka-Consumer; "You can receive messages by configuring a MessageListenerContainer and providing a message listener or by using the @KafkaListener annotation". Can someone tell when should I choose one option over another ?
Question - 2 : I have chosen KafkaListener approach for writing my application. For this I need to initialize a container factory instance and inside container factory there is option to control concurrency. Just want to double check if my understanding about concurrency is correct or not.
Suppose, I have a topic name MyTopic which has 4 partitions in it. And to consume messages from MyTopic, I've started 2 instances of my application and these instances are started by setting concurrency as 2. So, Ideally as per kafka assignment strategy, 2 partitions should go to consumer1 and 2 other partitions should go to consumer2. Since the concurrency is set as 2, does each of the consumer will start 2 threads, and will consume data from the topics in parallel ? Also should we consider anything if we are consuming in parallel.
Question 3 - I have chosen manual ack mode, and not managing the offsets externally (not persisting it to any database/filesystem). So should I need to write custom code to handle rebalance, or framework will manage it automatically ? I think no as I am acknowledging only after processing all the records.
Question - 4 : Also, with Manual ACK mode, which Listener will give more performance? BATCH Message Listener or normal Message Listener. I guess if I use Normal Message listener, the offsets will be committed after processing each of the messages.
Pasted the code below for your reference.
Batch Acknowledgement Consumer:
    public void onMessage(List<ConsumerRecord<String, String>> records, Acknowledgment acknowledgment,
          Consumer<?, ?> consumer) {
      for (ConsumerRecord<String, String> record : records) {
          System.out.println("Record : " + record.value());
          // Process the message here..
          listener.addOffset(record.topic(), record.partition(), record.offset());
       }
       acknowledgment.acknowledge();
    }

Initialising container factory:
@Bean
public ConsumerFactory<String, String> consumerFactory() {
    return new DefaultKafkaConsumerFactory<String, String>(consumerConfigs());
}

@Bean
public Map<String, Object> consumerConfigs() {
    Map<String, Object> configs = new HashMap<String, Object>();
    configs.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootStrapServer);
    configs.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
    configs.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, enablAutoCommit);
    configs.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, maxPolInterval);
    configs.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset);
    configs.put(ConsumerConfig.CLIENT_ID_CONFIG, clientId);
    configs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    configs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    return configs;
}

@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<String, String>();
    // Not sure about the impact of this property, so going with 1
    factory.setConcurrency(2);
    factory.setBatchListener(true);
    factory.getContainerProperties().setAckMode(AckMode.MANUAL);
    factory.getContainerProperties().setConsumerRebalanceListener(RebalanceListener.getInstance());
    factory.setConsumerFactory(consumerFactory());
    factory.getContainerProperties().setMessageListener(new BatchAckConsumer());
    return factory;
}

A: Q1:
From the documentation,

The @KafkaListener annotation is used to designate a bean method as a
  listener  for a listener container. The bean is wrapped in a
  MessagingMessageListenerAdapter configured with various features, such
  as converters to convert the data, if necessary, to match the method
  parameters.
You can configure most attributes on the annotation with SpEL by using
  "#{…} or property placeholders (${…}). See the Javadoc for more information."

This approach can be useful for simple POJO listeners and you do not need to implement any interfaces. You are also enabled to listen on any topics and partitions in a declarative way using the annotations. You can also potentially return the value you received whereas in case of MessageListener, you are bound by the signature of the interface.
Q2:
Ideally yes. If you have multiple topics to consume from, it gets more complicated though. Kafka by default uses RangeAssignor which has its own behaviour (you can change this -- see more details under).
Q3:
If your consumer dies, there will be rebalancing. If you acknowledge manually and your consumer dies before committing offsets, you do not need to do anything, Kafka handles that. But you could end up with some duplicate messages (at-least once)
Q4:
It depends what you mean by "performance". If you meant latency, then consuming each record as fast as possible will be the way to go. If you want to achieve high throughput, then batch consumption is more efficient.
I had written some samples using Spring kafka and various listeners - check out this repo

A: *

*@KafkaListener is a message-driven "POJO" it adds stuff like payload conversion, argument matching, etc. If you implement MessageListener you can only get the raw ConsumerRecord from Kafka. See @KafkaListener Annotation.

*Yes, the concurrency represents the number of threads; each thread creates a Consumer; they run in parallel; in your example, each would get 2 partitions.

Also should we consider anything if we are consuming in parallel.

Your listener must be thread-safe (no shared state or any such state needs to be protected by locks.

*It's not clear what you mean by "handle rebalance events". When a rebalance occurs, the framework will commit any pending offsets.

*It doesn't make a difference; message listener Vs. batch listener is just a preference. Even with a message listener, with MANUAL ackmode, the offsets are committed when all the results from the poll have been processed. With MANUAL_IMMEDIATE mode, the offsets are committed one-by-one.


text:
Q: IE11 not re-validating form after form reset I am using HTML form validation and have discovered a strange issue within IE11. The problem does not appear in Chrome, Firefox, Opera or Edge.
Basically, IE11 does not appear to perform a form reset correctly. I would expect a form reset to clear all validation errors and reset the form values back to their initial values. On the next submit, I would expect the form to re-validate.
What appears to happen during a form reset is only values are reset - validation error states (or even a successful validation) seem to remain unless a user changes the field.
The only workaround I can see for my web app is to reload the page rather than perform a form reset. Any other ideas?
The workflow is as follows:

*

*Using IE11, remove the text from a required input field.

*Click Submit, get validation error.

*Click Reset, input field value returns to initial value.

*Click Submit, get validation error yet the field has been filled in using the initial value.

    <!DOCTYPE html>
    <html>
    <head>
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
    </head>
    <body>
      <form id="theForm" name="theForm">
        <input type="text" name="textBox" value="test" required>
        <input type="submit">
        <input type="reset">
      </form>
    </body>
    </html>

A: I am able to produce the issue but unfortunately no any solution is available for this specific issue.
You can try to use work around like first setting the textbox value to empty and then reset the form using JS.

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">

function resetfrm()
{
document.getElementById("txt1").value='';
document.getElementById("theForm").reset();

alert("clear");
}
</script>
</head>
<body>
  <form id="theForm" name="theForm">
    <input type="text" name="textBox" id="txt1" value="test" required>
    <input type="submit">
    <input type="button" onclick="resetfrm()" value="Reset">
  </form>
</body>
</html>


text:
Q: How to refresh webView when app receives a message from GCM I can receive push notification with the below code successfully
public class GcmIntentService extends IntentService {

public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;

Toast toast;

public GcmIntentService() {
    super("GcmIntentService");
}

public static final String TAG = "GCM";

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
        /*
         * Filter messages based on message type. Since it is likely that GCM will be
         * extended in the future with new message types, just ignore any message types you're
         * not interested in, or that you don't recognize.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            sendNotification("Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            sendNotification("Deleted messages on server: " + extras.toString());
        // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            // This loop represents the service doing some work.
            for (int i = 0; i < 5; i++) {
                Log.i(TAG, "Working... " + (i + 1)
                        + "/5 @ " + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }
            }
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());

            String msg = extras.getString("message");
            sendNotification(msg);
            Log.i(TAG, "Received: " + msg);

        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
    mNotificationManager = (NotificationManager)
            this.getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.ic_stat_gcm)
    .setContentTitle("InnoProperty Notification")
    .setStyle(new NotificationCompat.BigTextStyle()
    .bigText(msg))
    .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG);
    toast.setGravity(Gravity.CENTER, 0, 0);
    toast.show();

     }
   }

And app has a webView in MainActivity.
I want to refresh webView when my app receives push message but I don't know how I can find webView in GCMIntentService class.

A: This is not tested, only logic and may have typos
put this is GcmIntentService
public GcmIntentService(View yourWebView) {
    super("GcmIntentService");
}

Call this constructor when you instantiate GcmIntentService class object.
The another solution i think can work is making a public class
public class myWebView extends WebView
{
 // Implement other methods..
..

public static void randomRefresh()
{
 //refresh you browser here
}
}

make a global class which extends Application
public class GlobalClass extends Application{

    private myWebView name;

    public myWebView getWebview() {

        return name;
    }

    public void setWebView(myWebView aName) {

       name = aName;

    }
}

just set webview as global and access it anywhere.
i don't know that is this a good implementation but this is all i have.
EDIT:
So, I think second solution is better and here is the code
make a class myWebview
public class myWebview extends WebView {
static WebView mWebView;
public myWebview(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
    mWebView=this;
}

public static void refreshView()
{
    mWebView.reload();
}

}
Create a class globalclass
public class globalclass extends Application {

    myWebview webview;

    private myWebview name;

    public myWebview getWebview() {

        return name;
    }

    public void setWebView(myWebview aName) {

       name = aName;

    }
}

Don't forget to edit android manifest
<application
        android:name="com.example.blabla.globalclass"
...
...
...

In MainActivity where the webview resides
final globalclass globalc = (globalclass) getApplicationContext();
        globalc.setWebView(YourWebviewHere);

Then in GCMIntentService where you want to refresh
final globalclass gc = (globalclass) getApplicationContext();
            gc.getWebview().reload();

this is the best i can help to make it understandable.
hope it will help.


text:
Q: How to verify that private generic method was called? I need to check whether private generic method was called with particular parameter type.

(Just stop thinking of telling me it's a bad practice to test private methods.)
Isolate.Verify.NonPublic.WasCalled()

has no overloads for specifying type parameters.
Is such verification possible?
Update
Since 7.5.2 API for this verification was added.
Here is the discussion.

A: Since Typemock v 7.5.2 API for this verification was added.
Here is the discussion.


text:
Q: Where do I place a file for bookmarks for all users With previous versions of Firefox I put my bookmarks.html file in /etc/firefox/profile and all new user accounts got automatically these bookmarks.
This folder doesn't exist on ubuntu 11.04; I tried to create it and put the bookmarks.html file in it but it doesn't seem to work...

A: As far as I understand, the default bookmarks are hidden in /usr/lib/firefox-n.n/omni.jar, you can modify this file to change default bookmarks for all users. Anyway this is not a good practise and I hope providing defaults will get easier in time.
A nicer way is to provide something in a default profile directory in order to let migration assistant do importing the bookmarks, when new Firefox profile is created. I think you have to provide profiles.ini in /etc/skel/.mozilla/firefox.
[General]
StartWithLastProfile=1

[Profile0]
Name=default
IsRelative=1
Path=5ge4y5n2.default
Default=1

And under /etc/skel/.mozilla/firefox/5ge4y5n2.default you can provide your files to be imported to a new profile, for example bookmarks.html or places.sqlite.
Only problem with this practise is that it allows only one Firefox profile per user and deleting the profile and creating new one loses the defaults.

A: Create /usr/lib/firefox/defaults/profile directory and put a customized bookmarks.html file inside.
It works on Ubuntu 12.04.

A: What you can do is use one profile as a regular one, and the other profile folders as symbolic links to the actual profile.


text:
Q: Two Consecutive Alert Views and then Segue I'm trying to figure out how to use two alert views consecutively, and THEN segue to the next controller.
The requestStartTime and requestEndTime are UIAlertViews.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

[self requestStartTime];

}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1)

{

    [self requestEndTime];

}{

[self performSegueWithIdentifier:@"report" sender:nil];
}
}

I need to segue after the second alert view has been clicked. My problem is that it segues and opens the requestEndTime in the second view controller. I need to add another
if (buttonIndex ==1)

statement somewhere? Would appreciate some guidance

A: You just need to store your UIAlerView somewhere and in [alertView:didDismissWithButtonIndex:] do simple if like this:
if (buttonIndex == 1 && alertView == self.firstAlertView)
{
    [self requestEndTime];
}
else if (buttonIndex == 1 && alertView == self.secondAlertView)
{
    [self performSegueWithIdentifier:@"report" sender:nil];
}


text:
Q: C# Static Class with Resharper Recommendations My first time posting! Long time lurker.
I'm creating a static class, and this answer was very helpful:
C# - Winforms - Global Variables
Here's the code from that answer for clarity:
static class Global
  {
    private static string _globalVar = "";

    public static string GlobalVar
    {
        get { return _globalVar; }
        set { _globalVar = value; }
    }
  }

However, in the process, ReSharper has recommended the code changes to this:
public static string value1 { get; set; } = "";

public static string value2 { get; set; } = "";

I don't think there's any difference, but I want to be 100% certain.
So my question is, is there any difference between the two, and if so, which one is the most desirable?

A: That's "syntactic sugar". The version
public static string value1 {get;set;} = "";

compiles almost exaclty the way the previous explicit version
private static string _value1 = "";
public static string value1 {
    get { return _value1; }
    set { _value1 = value; }
}

would compile. The compiler creates the backing field for you and initializes it.
So if you don't need to do special things in the getter or setter method, I'd prefer the shorter version (the so called auto-property), because there is less boiler-plate code.


text:
Q: How to read in multiple text-based scrabble boards, and place them into a 2D array? I'm currently attempting to make a scrabble solver, and I'm having a bit of an issue with the reading of the text files which represent the board. For example, I have a file like this:
15
3. .. .. .2 .. .. .. 3. .. .. .. .2 .. .. 3.
.. 2. .. .. .. .3 .. .. .. .3 .. .. .. 2. ..
.. .. 2. .. .. .. .2 .. .2 .. .. .. 2. .. ..
.2 .. .. 2.  l  a  u  d  a  t  o  r .. .. .2
.. .. .. .. 2. .. ..  h .. .. 2. .. .. .. ..
.. .3 .. .. .. .3 ..  o .. .3 .. .. .. .3 ..
.. .. .2 .. .. .. .2  t .2 .. .. .. .2 .. ..
3. .. .. .2 .. .. ..  i .. .. .. .2 .. .. 3.
.. .. .2 .. .. .. .2 .. .2 .. .. .. .2 .. ..
.. .3 .. .. .. .3 .. .. .. .3 .. .. .. .3 ..
.. .. .. .. 2. .. .. .. .. .. 2. .. .. .. ..
.2 .. .. 2. .. .. .. .2 .. .. .. 2. .. .. .2
.. .. 2. .. .. .. .2 .. .2 .. .. .. 2. .. ..
.. 2. .. .. .. .3 .. .. .. .3 .. .. .. 2. ..
3. .. .. .2 .. .. .. 3. .. .. .. .2 .. .. 3.
le*mdoe
7
3. .. .. 2. .. .. 3.
.. .3 .. .. .. .3 ..
.. ..  a  d .2 .. ..
2. ..  u  h .. .. 2.
.. ..  l  o .2 .. ..
..  m  a  t .. .3 ..
 r  e  S  i  d .. 3.
toloeri
21
4. .. .. .2 .. .. .. 3. .. .. .2 .. .. 3. .. .. .. .2 .. .. 4.
.. 2. .. .. .3 .. .. .. 2. .. .. .. 2. .. .. .. .3 .. .. 2. ..
.. .. 2. .. .. .4 .. .. .. 2. .. 2. .. .. .. .4 .. .. 2. .. ..
.2 .. .. 3. .. .. .2 .. .. .. 3. .. .. .. .2 .. .. 3. .. .. .2
.. .3 .. .. 2. .. .. .. .3 .. .. .. .3 .. .. .. 2. .. .. .3 ..
.. .. .4 .. .. 2. .. .. .. .2 .. .2 .. .. .. 2. .. .. .4 .. ..
.. .. .. .2 .. .. 2.  q  u  e  p .. .. .. 2. .. .. .2 .. .. ..
3. .. .. .. .. ..  l  i .. .. .. .. .. 2. .. .. .. .. .. .. 3.
..  g  l  i  t ..  a .. .3 .. .. .. .3 .. .. .. .3 .. .. 2. ..
.. ..  a .. .. .2  u ..  n .2 .. .2 .. .. .. .2 .. .. 2. .. ..
 d  a  w  d .. ..  d  h  o  t  i .. .. .. .2 .. .. 3. .. .. .2
.. ..  f  i  g  j  a  m  s .2 .. .2 .. .. .. .2 .. .. 2. .. ..
..  t  u  n  e ..  t ..  y .. .. .. .3 .. .. .. .3 .. .. 2. ..
 m  e  l  o  d  e  o  N .. .. .. .. .. 2. .. .. .. .. .. .. 3.
.. .. .. .2 .. ..  r .. .. .. .2 .. .. .. 2. .. .. .2 .. .. ..
..  v  e  z  i  r  s .. .. .2 .. .2 .. .. .. 2. .. .. .4 .. ..
.. .3 ..  o 2. .. .. .. .3 .. .. .. .3 .. .. .. 2. .. .. .3 ..
.2  b  a  r  f .. .2 .. .. .. 3. .. .. .. .2 .. .. 3. .. .. .2
.. ..  a  r  o  w .. .. .. 2. .. 2. .. .. .. .4 .. .. 2. .. ..
.. 2. ..  o  x  y .. .. 2. .. .. .. 2. .. .. .. .3 .. .. 2. ..
 k  e  p  s ..  n .. 3. .. .. .2 .. .. 3. .. .. .. .2 .. .. 4.
ntnbtoi
15
3. .. .. .2 .. .. .. 3. .. .. .. .2 .. .. 3.
.. 2. .. .. .. .3 .. .. .. .3 .. .. .. 2. ..
.. .. 2. .. .. .. .2 .. .2 .. .. .. 2. .. ..
.2 .. .. 2. .. .. .. .2 .. .. .. 2. .. .. .2
.. .. .. .. 2. .. .. .. .. .. 2. .. .. .. ..
.. .3 .. .. .. .3 .. .. .. .3 .. .. .. .3 ..
.. .. .2 .. .. .. .2 .. .2 .. .. .. .2 .. ..
3. .. .. .2 ..  c  a  t .. .. .. .2 .. .. 3.
.. .. .2 .. .. .. .2 .. .2 .. .. .. .2 .. ..
.. .3 .. .. .. .3 .. .. .. .3 .. .. .. .3 ..
.. .. .. .. 2. .. .. .. .. .. 2. .. .. .. ..
.2 .. .. 2. .. .. .. .2 .. .. .. 2. .. .. .2
.. .. 2. .. .. .. .2 .. .2 .. .. .. 2. .. ..
.. 2. .. .. .. .3 .. .. .. .3 .. .. .. 2. ..
3. .. .. .2 .. .. .. 3. .. .. .. .2 .. .. 3.
dgos*ie

The first line above the board is the number of rows/columns. Then, obviously, the board. Then the hand with which to place characters.
The thing that I am trying to implement is a way to separate each board from each other, and solve them independently. I'm unsure how to use a scanner to, for example, stop after reading the row/column number, create the corresponding 2D array, then read the board in and stop before the hand, and then read the hand and place them into the Hand object, and then continue with the next board. I'm not sure how to make the divisons, if that makes sense.
Here is my attempt, that only kind of works. I can only get it to work if I delete the first line, and have just a single board. The lines that are commented out at the top are my attempt to read just the first line, and create the corresponding array, but whenever I do this, for my input ArrayList, the first sysout is a blank list, and only then does it start reading the board itself, which doesn't make any sense to me.
public static void populateBoard(File file) throws FileNotFoundException {
        Scanner scan = new Scanner(file);
//        String NUMBER_ROWS = scan.next();
//        System.out.println(NUMBER_ROWS);

//        board = new String[NUMBER_ROWS][NUMBER_ROWS];
        board = new String[15][15];
        int actualLine = 0;

        while(actualLine < 15) {
            ArrayList<String> input = new ArrayList<>(Arrays.asList(scan.nextLine().split(" ")));
            // Removes blank characters which occur because of the letters on the board having a space instead
            // of a dot to their left.
            input.removeIf(string -> string.equals(""));
            System.out.println(input.toString());

            for(int i = 0; i < input.size(); i++) {
                board[actualLine][i] = input.get(i);
            }
            actualLine++;
        }

    }

I feel that I haven't explained this overly well, so if there is anything that I can clarify, please ask, and I will do so.

A: Yor are most of the way there, you just need to wrap it all inside another loop that finds the board size and creates each board one at a time.
We start by creating an ArrayList of boards that we can store each of the boards in ArrayList<String[][]> boards = new ArrayList<>();.
Assuming the file will always be laid out correctly then next we need to create a loop that finds the boards one at a time and based on their size currentBoardSize = Integer.parseInt(line); we can create them one at a time currentBoard = new String[currentBoardSize][currentBoardSize]; then we process the next number of lines to match the currentBoardSize and store each line into a 2D array we just created using your line split code ArrayList<String> input = new ArrayList<>(Arrays.asList(scan.nextLine().split(" ")));;
Finally, we store the complete board into the boards list boards.add(currentBoard);, and then we let the while loop start over again and find the next board size and create a new 2D array until there are no more boards left in the file.
A complete example might look like this:
//list of boards, store this outside of the method so that it can be accessed from other places like you main method etc
public static ArrayList<String[][]> boards = new ArrayList<>();

//Load the file into the boards array, or change "void" to "ArrayList<String[][]>" if you want to return the array directly from the method
public static void populateBoard(File file) throws FileNotFoundException {
    Scanner scan = new Scanner(file);
    int currentBoardSize = 0;
    String[][] currentBoard;

    //Get the very first board size so that the while loop works correctly
    String line = scan.nextLine();

    while(line != null) {
        //Check it the first line has no spaces and is a single number indicating a new board
        if(line.contains(" ") == false) {
            try {
                //Get the board size
                currentBoardSize = Integer.parseInt(line);
            }
            catch (NumberFormatException ex) {
                System.out.println("Error, unable to read board size: ");
                ex.printStackTrace();
                break;
            }
            currentBoard = new String[currentBoardSize][currentBoardSize];
            System.out.println("Created new board that is "+currentBoardSize + "x"+currentBoardSize);

            //populate the borad using the next number of lines based on the board size
            for (int row = 0; row < currentBoardSize; row++) {
                ArrayList<String> input = new ArrayList<>(Arrays.asList(scan.nextLine().split(" ")));
                // Removes blank characters which occur because of the letters on the board having a space instead
                // of a dot to their left.
                input.removeIf(string -> string.equals(""));
                System.out.println(input.toString());

                for (int column = 0; column < input.size(); column++) {
                    currentBoard[row][column] = input.get(column);
                }
            }

            //Lastly do whatever you want with the word below each board
            String wordToSolve = scan.nextLine();
            System.out.println("Word to solve: "+wordToSolve );

            //Add this board to the list of boards
            boards.add(currentBoard);

            //Get the next board size, or break the while loop
            try {
                line = scan.nextLine();
            }
            catch (NoSuchElementException ex) {
                break;
            }
        }
        else {
            System.out.println("Error unexpected board size found: "+line);
            break;
        }
    }
}

And the outputs can be gotten easily from the list like so:
///boards.get(board#) grabs the board, and [row#][col#] gets the row and column (remember they are 0 based, the first one is 0 not 1)
String value = boards.get(0)[2][6];
System.out.println("Value: "+value);

And this given output for the above is .2 as expected


text:
Q: Leaflet ionic position errors From some time on I am getting
[Log] PositionError (mapController.js, line 141)
code: 2
message: ""
__proto__: PositionErrorPrototype

in Safari on OSX and iOS when I run my Leaflet.js based app and the example that it's based on.
When I started the project, this was not the case. It happens when I try to get the current location by calling
$cordovaGeolocation.getCurrentPosition().then(function (position) {
...
}

Any ideas? Is it reproducible?
Edit:
I figured it's returning PositionError.POSITION_UNAVAILABLE as defined in the specs.
I added options to the request { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true } hoping it would extend the timeout span to 5sec., but I keep getting the error immediately after request...
Safari 8.0.6 OSX 10.10.3 XCode 6.3.2
It works fine with Chrome, but I plan to deploy this on iOS & Android


text:
Q: Explicit advise to comment on downvotes, but not for upvotes for lower rep users? As asked in the title, lower rep users (I don't actually know the considered trusted rep count that makes this disappear) are explicitly advised with a pop-up to leave a comment when downvoting a question, but not if an upvote is placed.
I've often reviewed questions, where upvotes were absolutely inadequate and seemingly more coming from a sentiment for new users, instead of judging the post contents, and how it fits for particular site's policies.
It seems for many cases we hit robo upvoters at the same rate as robo downvoters. As well both of these actions are considered important for the overall health of the system, and are already explained well with the reasonings appearing from the tooltip message given on both of these buttons.
So why do we have this kind of irrational imbalance of pop-up messages actually?

A: Downvotes are sometimes paired with comments because downvotes are often used on content that could be improved. Maybe it's a one-line answer. That's perfectly valid downvote fodder, but posting a comment to add details (particularly specifying which details are needed) is also useful. Of course, there are plenty of cases when a downvote says all that needs to be said, but new users may need to be informed that specifying what's wrong explicitly is also helpful.
By contrast, upvotes rarely need an explanation. What would you say with most upvotes? "+1: I agree" is pointless noise, as is "good question" or whatever. So new users don't need to be told to comment with their upvotes.

When I say "explanation", I'm talking about explaining why the vote is there, in an attempt to help improve the question/answer. I am not talking about an "explanation" that exists to justify your vote.
Each vote belongs entirely to the person who made it, and (outside of explicit vandalism), you should never feel that a person must justify their vote to you. If you believe that someone has upvoted a question/answer not in line with this site's policies, that their reason for doing so doesn't fit with your particular vision of Stack Exchange... deal with it.
You do not have the right to insist that someone justify themselves.


text:
Q: Subject in English I'm Japanese and I am studying English, in particular, reading English books. I have some questions about the subject.
We also use pronouns in Japanese. Then, a subject usually does not change from line to line. For example, if we say  the following sentence in Japanese,
"Lon wrote a letter. He sent it to Jacob. He was excited."
then the last "he" means Lon; whereas, if we say the above in English, the last "he" can mean both "Lon" and "Tom", as I studied.
In English, isn't it hesitated to change a pronoun from line to line?
Best

A: You are correct in thinking that this could cause confusion, as the second "he" could mean either of the two previously mentioned people. To avoid this, I would explicitly state the subject of the second one, like this:

"Lon wrote a letter. He sent it to Jacob. Jacob was excited."

Another way to disambiguate, as @Janus Bahs Jacquet mentioned, is to use relative clauses. In this case, the subject of the clause would be relative to the preceding subject:

"Lon wrote a letter and sent it to Jacob, who was excited."

or...

"Lon wrote a letter. He sent it to Jacob, who was excited."


text:
Q: Exception occurs while pressing a button on TouchScreen using a Stylus or a finger in a WPF app I have WPF app with an initial window which shows up as Splashscreen at Startup. During the Startup there is a background thread and we can cancel the this thread by clicking the button in splashscreen.
This all works fine while using mouse and clicking the button to cancel. However if I use the touchscreen to click on this button then occasionaly the app crashes and following is the stack trace. The app is a 64bit target running on windows 7 64bit.
Severity:
Fatal

Stack Trace:
Exception 0
Message: Object reference not set to an instance of an object.

StackTrace:

at MS.Internal.PointUtil.TryClientToRoot(Point point, PresentationSource presentationSource, Boolean throwOnError, Boolean& success)
at System.Windows.Input.StylusDevice.GetPosition(IInputElement relativeTo)
at System.Windows.Input.StylusDevice.ChangeStylusOver(IInputElement stylusOver)
at System.Windows.Input.StylusLogic.PreProcessInput(Object sender, PreProcessInputEventArgs e)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.PossiblyDeactivate(IntPtr hwndCapture, Boolean stillActiveIfOverSelf)
at System.Windows.Interop.HwndMouseInputProvider.Dispose()
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)

FromSubsystem:
PresentationCore
Help Link:
Not specified

Has anyone encountered this problem before?

A: Are you using Elo touch screen? I have a similar crash in StylusLogic OnDispatcherShutdown with Elo touch display. I have solved it, with disabling the RealTimeStylus for wpf (Disable the RealTimeStylus for WPF Applications). It seams to me, that the event is handled twice (in display driver and wpf stylus), but on the wpf Stylus handler the window is already destroyed. Also a little delay before calling close window has worked for me.

A: Based on Luz De Gan's answer, I found that delaying the closing of the window works the best without having to disable the RealTimeStylus.
In your cancel event handler, use this to delay the closing of the window:
Dispatcher.InvokeAsync(this.Close, DispatcherPriority.Input);

It needs to be DispatcherPriority.Input in order to ensure that the closing happens after the touch input events have been processed.


text:
Q: Dapper mapping MySql BIT(1) data type to ulong instead of boolean Please has anyone come across the above situation with Dapper and MySQL.  In all my tables in MySQL (5.1), where the data type is BIT(1) or BIT, Dapper simply return such field as ulong (UInt64).  I am using MySql.Data.MySqlClient and I have no such issue with EF which is what I am trying to convert from.
Thanks for any help.

A: In MySQL, the type Boolean is mapped to Tinyint(1) with MySQL. Perhaps you will have to cast it to Boolean (0=false/1=true), Convert.toBoolean(UInt64) may help you (see  http://msdn.microsoft.com/en-us/library/33f2zy48.aspx).
@Christian Droulers: The behaviour of SQLite is similar.

A: Why don't you do the casting in your sql query ?
cast(myField using TINYINT(1)) as myField

Not sure abot the type here, but that's the way I do when my db type doesn't match my object's.


text:
Q: How to properly Set RadGridView.IsBusy while grouping In my scenario Telerik Rad gridview becomes unresponsible for a couple of seconds while grouping certain amount of data. All I want to do is to show some kind of loading indicator for this period of time. I tried to simple leverage OnGrouping, OnGrouped events to set IsBusy like this:
OnGrouping(){  gridView.IsBusy = true;}
OnGrouped(){  gridView.IsBusy = false;}

But it does not work. It looks like Telerik GridView performs all grouping in UI thread without any chance for 'IsBusy = true' being proceed before grouping finishes.
Anybody knows to to achieve that?
Or more generally how to force layout update during 'OnGrouping' event?
Thanks in advance

A: I reckon that you do not have any option. UIElement, like RadGridView, must be created on UI so the way out, by creating it in background thread and then assign it to UI thread, does not come into play. In ordinary grouping it is made on CollectionView so I guess it may be carried out simultaneously but as you said in your case UIelement is responsible for it.

A: You could try putting your RadGrid inside a RadAjaxPanel. Then hook up a RadAjaxLoadingPanel to display an animated loading gif or some text while the grid updates.
Demo: http://demos.telerik.com/aspnet-ajax/ajax/examples/loadingpanel/loadingimages/defaultcs.aspx
Doco: http://www.telerik.com/help/aspnet-ajax/ajax-loadingpanel.html


text:
Q: Any $2$ elements of $S$ are elements of at least one of sets $A,B,C,D$ $S$ is the set of the first $n$ natural numbers.
$A, B, C, D$ are subsets of $S$ such that any $2$ elements of $S$ are elements of at least one of sets $A, B, C, D$.
What is the greatest value of $k$ such that at least one of
$|A|,|B|,|C|,|D|$ is greater than $k|S|$?
I don't know where to start solving

A: wait, this is incomplete.

We will show that $ k \geq \frac{1}{2}$.
Out of $2n-1$ elements, if the 4 subsets have at most $n-1$ elements in them, then they cover at least $ 4\times {n-1 \choose 2} $ pairs. However, there are ${2n-1 \choose 2}$ pairs that need to be covered, and since
$${2n-1 \choose 2} > 4\times {n-1 \choose 2},$$
hence one of the sets must have at least $n$ elements.

We will show that $k \leq \frac{3}{5}$.
For $n = 5$, the sets $ A = \{ 1, 2, 3 \}, B = \{ 1, 2, 4 \}, C = \{ 1, 2, 5 \}, D = \{ 3, 4, 5 \}$ satisfy the conditions. Hence $k \leq \frac{3}{5}$.
Conversely, we can create sets where $ A = \{ n | n \equiv 1, 2, 3 \pmod{5} \}$ and similar.

How can we tighten this further?
For a given $n$, suppose we had such sets which satisfy the conditions and minimizes $K=\max \{ |A|, |B|, |C|, |D|\}$. The previous construction shows that $K \leq \frac{3}{5} + \frac{3}{n}$.
If $A \cup B \cup C \neq S$, then for $s \in S - A - B - C$, $\forall t \in S$, we must have $ \{ s, t \} \in D$, so $ D = S$, which gives $k = 1$. So, in an attempt to do better, we consider $ A \cup B \cup C = S$.
If $a=c=g = 0$, then $b+e+d \leq K, b+e+f \leq K, d+e+f \leq K, b+d+f+e = N$ so $3K \geq 2N$ or that $ K \geq \frac{2}{3}N$. Again, we can do better.
If $a = 0, $ then
If $ |C - A\cup B | = g > 0$, let $s_c \in C - A\cup B $ and $s_{ab} \in A \cup B$, then $\{ s_c, s_{ab} \} \in D$ so $(A \cup B) \Delta C \subset D$. So $|D| \geq a+c+g$.


text:
Q: SNMP Extend not working I've got a server running Postgresql 9.1 replication.  I wrote a script which prints out the current replication lag (master inserts a unix timestamp every 60s, and the slave compares it to the current timestamp).
I've added
extend replag /usr/local/bin/check_lag_quietly.sh

to snmpd.conf, and restarted the snmpd service, but when I snmpwalk the host, either from localhost, or from another machine on the network, I  can see all of the other OIDs, but not this one.
If I do SNMP-Get as
tom.oconnor@charcoal-black:~$ snmpget -v2c -cpublic dns-2 UCD-SNMP-MIB::extTable
UCD-SNMP-MIB::extTable = No Such Object available on this agent at this OID

Then it can't find the OID there either.
Net-SNMP version 5.4.2.1, Ubuntu 10.04.

A: On Debian with 5.4.3 snmpd dosn't seem to load all it's modules by default, by adding:
-I interface,ifTable,ifXTable,cpu,cpu_linux,hw_mem,extend,versioninfo,snmp_mib,ip,at,system_mib

to the command line for snmpd (note the 'extend' in there), i can:
snmpwalk -Ou  -v 1 -c public localhost nsExtendOutput2Table

which returns the default 'extend' examples:
enterprises.netSnmp.netSnmpObjects.nsExtensions.nsExtendObjects.nsExtendOutput2Table.nsExtendOutput2Entry.nsExtendOutLine."test1".1 = STRING: Hello, world!
enterprises.netSnmp.netSnmpObjects.nsExtensions.nsExtendObjects.nsExtendOutput2Table.nsExtendOutput2Entry.nsExtendOutLine."test2".1 = STRING: Hello, world!
enterprises.netSnmp.netSnmpObjects.nsExtensions.nsExtendObjects.nsExtendOutput2Table.nsExtendOutput2Entry.nsExtendOutLine."test2".2 = STRING: Hi there

Which is close to what you want.
You can get a list of all the snmpd modules with:
snmpd -Dmib_init -H

I guess the real question here is "How do i get snmpd to load all it's modules by default"

A: We need to enable agent/extend module while configuring the pkg.
./configure --with-default-snmp-version=2 --with-logfile=/var/log/snmpd.log --with-sys-location= --with-sys-contact= --with-persistent-directory=/home/swuser/snmp --with-mibs=RFC1213-MIB --with-mibdirs= --disable-scripts --with-out-mib-modules=examples/ucdDemoPublic,mibII/system_mib --without-kmem-usage --disable-mibs --disable-mib-loading --disable-manuals --without-perl-modules --enable-shared --host=arm-none-linux-gnueabi --with-cc=arm-none-linux-gnueabi-gcc --target=arm-none-linux-gnueabi --disable-embedded-perl --with-ar=arm-none-linux-gnueabi-ar --with-mib-modules="ucd-snmp/dlmod"

Here if you can disable agent/extend module by --with-out-mib-modules=agent/extend or else by default it's enabled in net-snmp-5.7


text:
Q: Regular expression to find URLs but not include punctuation AFTER the URL Example: "My site is http://www.abcd.com, and yours is http://www.def.ghi/jkl. Is Fred's https://www.xyz.com? Or is it http://www.xxx.com?abc=def? (I thought his site was http://www.mmm.com), but clearly it's not."
This should extract
http://www.abcd.com
http://www.def.ghi/jkl
https://www.xyz.com
http://www.xxx.com?abc=def
http://www.mmm.com
Notes: it should assume that any punctuation following the url is NOT part of the url, e.g. the comma after http://www.abcd.com, is not part of the url. This includes trailing question marks, which I realize in actuality COULD be part of the url. Of course, if a question mark is followed by querystring data, it SHOULD be considered part of the url. Note that urls might be followed by multiple punctuation marks, as in the the case of (Is your url http://abcd.com)?
Urls (and their trailing punctuation, if any) will always be followed by a space, a newline/return character -- or they'll be the end of the string being tested.
The will be preceded by a whitespace character or, possibly, an open bracket or parenthesis, as in "Please visit my site (http://www.abcd.com)." Or they'll come at the beginning of the string.
This regexp should work for http, https and ftp.
This is for an Actionscript project. I believe that Actionscript uses the same regular-expression engine as Javascript.
Thanks!

A: Have a look here: http://www.regexguru.com/2008/11/detecting-urls-in-a-block-of-text/
EDIT: shanethehat and divillysausages also mentioned this link: http://gskinner.com/RegExr/ which I hadn't seen before and which features online evaluation (in other words, you can tune your regex without firing up your coding IDE, which is awesome). Thanks!

A: First off, rolling your own regexp to parse URLs is a terrible idea. You must imagine this is a common enough problem that someone has written, debugged and tested a library for it, according to the RFCs. There are a ton of edge cases when it comes to parsing URLs: international domain names, actual (.museum) vs. nonexistent (.jpg) URLs, weird punctuation including parentheses, punctuation at the end of the URL etc.
I've looked at a ton of libraries, and they all have their downsides. See a comparison of JavaScript URL parsing libraries here.
If you want a regular expression, the one in Component is quite comprehensive.


text:
Q: Wordpress Edit Image Button Disappeared Have a UGC app being run by WP 3.7.1 (I know I need to upgrade to 3.8.1).  Users upload images, admin can approve/reject, all good.  Admin also HAD the ability to edit an image (rotate being the biggest need) directly in the WP Media Edit screen.  All of sudden this button has disappeared.
I have seen this as a fairly common bug from a few years past, but common solutions don't seem to be working.
I have confirmed that PHP GD is running on the server and I have disabled a number of plugins.  These are the two common solutions I've seen listed before.  Neither have resolved this issue for me.
Any thoughts to why this button would have disappeared or ways to ensure it is enabled?

A: Check is dir '/wp-content/uploads' writable.


text:
Q: Difference between 2 records timestamp sql I have this table:
CREATE TABLE result (
  id bigint(20) NOT NULL AUTO_INCREMENT,
  tag int(11) NOT NULL,
  timestamp timestamp NULL DEFAULT NULL,
  value double NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY nasudnBBEby333412dsa (timestamp, tag)
) ENGINE=InnoDB AUTO_INCREMENT=115 DEFAULT CHARSET=utf8mb4;

I would like to calculate the difference between two consecutive days that have the same column tag. For example, in timestamp:
|   1 |   1 | 2017-06-18 00:00:00 |    7.3 |
|   2 |   1 | 2017-06-17 00:00:00 |    7.4 |

I want to result: -0.1
Which query should i write?

A: First, if you want to store date values, you can use date, so there is no time component.
Second, you can do this with join:
select r.*, (r.value - rprev.value) as diff
from results r left join
     results rprev
     on r.tag = rprev.tag and
        r.timestamp = rprev.timestamp + interval 1 day;

A: You can try this
1) Use join to select value of next consecutive day.
2) then calculate difference
SELECT r1.id, r1.tag, r1.value AS CURRENT_VALUE, r2.value AS NEXT_VALUE, (
r1.value - r2.value
) AS DIFF, r1.timestamp
FROM  `result` r1
LEFT JOIN result r2 ON r2.tag=r1.tag AND r2.`timestamp` = r1.`timestamp` + INTERVAL 1
DAY WHERE r2.value IS NOT NULL
GROUP BY r1.timestamp

Output