text:
Q: PHP Soapclient modify Envelope We are currently working in a PHP & SOAP integration. With 6 other requests, all our code is working great because our evelope is the same, but we are having problems with our last request, wich have its evelope different than others.
Normal envelope (6 other one):
<soap:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://xxx.ws.xxx.com/">

New envelope (last request):
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns2="http://xxx.ws.xxx.com/">

We have tried using SoapVar and SoapParam classes to change the envelope, but we currently have not got any progress. ¿How can we do it?
Furthermore, we also need in this new request to change some other parameters:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns2="http://xxx.ws.xxx.com/">
                               <soap:Body>
                                  <PackagePre xmlns="http://xxx.ws.xxx.com/">
                                     <PreBookRQ locale="es_ES" xmlns="">
                                        <Authentication user="XXX" password="XXX"/>
                                        <Booking>
                                           <ProductList xsi:type="ns2:myproduct" address="null 0" categoryCode="CAT34"...

So we need to:

*

*Change envelope.

*Add Packagepre xmlns (same as ns1 in envelope).

*ProductList: add xsi:type="ns2:myproduct"

Any help is welcome :-).
Regards.


text:
Q: Grails GSP view won't output variable I got view like this
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
    <ns2:${servicename}Response xmlns:ns2="http://ws/">
          <g:each in="${result}" var="record">
            <return>
          <g:each in="${parameters}" var="parameter">
              <${parameter.name}>${record[parameter.name]}</${parameter.name}>
          </g:each>
            </return>
          </g:each>
    </ns2:${servicename}Response>
</S:Body>
</S:Envelope>

And it renders like this:
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
    <ns2:${servicename}Response xmlns:ns2="http://ws/">

            <return>

              <column1>updated</column1>

              <column2>update</column2>

              <id>1</id>

            </return>

    </ns2:${servicename}Response>
</S:Body>
</S:Envelope>

as you can see, servicename variable is not replaced inside of element name with namespace. i tried to hack it several ways like passing the whole ns:servicename as variable, but nothing helped, there were always some undesirable side effects. How can i do this? i just want to replace the variable without additional validation/processing...

A: <?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
    <%= """<ns2:${servicename}Response xmlns:ns2="http://ws/">""" %>
          <g:each in="${result}" var="record">
            <return>
          <g:each in="${parameters}" var="parameter">
              <${parameter.name}>${record[parameter.name]}</${parameter.name}>
          </g:each>
            </return>
          </g:each>
    <%= """</ns2:${servicename}Response>""" %>
</S:Body>
</S:Envelope>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Im having trouble with a vectors question Im not sure how the rules relating to this are but since the problematic question builds up on a paper with diagrams, i would like to show an image of the question.
image of the question: http://imgur.com/8n2Pa6K
I would really appreciate some help, thanks a lot!


text:
Q: Bootstrap Carousel jQuery 1 of 5 slider number not updating until clicked Below my Bootstrap 4 Carousel, I have an indicator saying the current slide number and the total amount of sliders, so 1 of 5, 2 of 5, 3 of 5, etc.
Using the Bootstrap hook, my counter should increment when the next slide is clicked, which it does, but not until two slides have been clicked so it will stay on 1 of 5 for two slides before updating to 2 of 5 and functionally normally, but because it doesn't start, the order is incorrect:
First: 1/5
Second: 1/5
Third: 2/5
Forth: 3/5
Fifth: 4/5
First(again): 5/5
Whereas it should start at 1/5 then on click, go to 2/5, then 3/5 etc according to the actual slide number.
Here is my jQuery code
jQuery(function($) {
    var totalItems = $('.carousel-item').length;
    var currentIndex = $('div.active').index() + 1;

    $('#carousel-number').html('
'+currentIndex+' of '+totalItems+'
');
    $('#brands-carousel').on('slide.bs.carousel', function () {

        currentIndex = $('div.active').index() + 1;
        $('#carousel-number').html('
'+currentIndex+' of '+totalItems+'
');

    });
});

I added + 1 to the index as it started at 0. (0 of 5 instead of being 1 of 5)
And my HTML / PHP Carousel
<?php
        if( have_posts() ) :
            $count = 0;
            $counti = 0;
            $content = apply_filters( 'the_content', get_the_content() );
            ?>

                        <?php
                        while( have_posts()) : the_post(); ?>
                            <li id="carousel-number" data-target="#brands-carousel" data-slide-to="<?php echo $counti; ?>" class="<?php echo ($counti == 0 ? 'active' : 'hide'); ?>">

                            <?php
                        endwhile;
                        ?>

                        Previous

                        Next

                        <?php
                        while(have_posts()) : the_post();
                            ?>
                            <div class="carousel-item <?php echo ($count == 0 ? 'active' : '') ?>">

The Difference

<?php the_title(); ?>

The benefit to you

                                                <?php echo apply_filters( 'the_content', get_the_content() ); ?>

                            <?php
                            $count++;
                        endwhile;
                        ?>

        <?php
        endif;
        ?>

Any help would be greatly appreciated

A: Please remove data-interval="false" or make it true from your html section then know me.


text:
Q: OracleHelper: How to read data from Oracle OUT SYS_REFCURSOR SProc parameter into a dataset? I get following error when I try to pass the result from store procedure to the dataset. The OracleHelper class is similar to SqlHelper, just that it is referencing Oracle.
I am using ODP.NET managed driver.
I do have sample data in the ACCOUNTS table.
Error:
ORA-06550: line 1, column 7:

PLS-00306: wrong number or types of arguments in call to 'GET_ACCOUNT_DETAILSV2'

ORA-06550: line 1, column 7:

c#:
public DataSet GetUserData(string PHONE_NUMBER)
    {
        return (DataSet)OracleHelper.ExecuteDataset(GetConnectionString(), "GET_ACCOUNT_DETAILSV2", PHONE_NUMBER););
    }

Store procedure:
CREATE OR REPLACE PROCEDURE GET_ACCOUNT_DETAILSV2 (
   PHONE_NUMBER   IN ACCOUNTS.PHONE%TYPE,
   o_rc     OUT         SYS_REFCURSOR)
IS
BEGIN
      OPEN o_rc FOR
         SELECT ID,
                STATUS,
                EMAIL
           FROM ACCOUNTS
          WHERE PHONE = PHONE_NUMBER;
END GET_ACCOUNT_DETAILSV2;
/

Any help will be appreciated.

A: Something like that:
        using (OracleConnection conn = new OracleConnection("User Id=marketing;Password=SECRET;Data Source=dashworks-db"))
        {
            conn.Open();
            using (OracleCommand cmd = new OracleCommand("GET_ACCOUNT_DETAILSV2", conn))
            {
                cmd.BindByName = true;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("PHONE_NUMBER", "416-123-4567");
                cmd.Parameters.Add("o_rc", OracleDbType.RefCursor, ParameterDirection.Output);
                using (OracleDataAdapter adapter = new OracleDataAdapter(cmd))
                {
                    DataSet ds = new DataSet("result");
                    ds.Locale = CultureInfo.InvariantCulture;
                    adapter.Fill(ds);
                }
            }
        }


text:
Q: What is the type of the actions parameter in the alert modifier? Say I wanted to create a property such that it can be passed directly to the actions parameter of the alert(_:isPresented:actions:message:) modifier and can hold multiple buttons. What type would I use to declare that property?
Button<Text> works, but I'd like it to hold multiple buttons.

A: If it is not a single view then it should be view builder generating some view (because we talk about generics), like in below demo
struct DemoView<Content, Actions>: View where Content: View, Actions: View {
    @Binding var showAlert: Bool

    var actions: () -> Actions    // << here !!
    var content: () -> Content

    init(isPresented: Binding<Bool>, @ViewBuilder actions: @escaping () -> Actions, @ViewBuilder content: @escaping () -> Content) {
        self._showAlert = isPresented
        self.actions = actions         // << here !!
        self.content = content
    }

    var body: some View {
        content()
            .alert("Alet", isPresented: $showAlert, actions: actions)
    }
}

Tested with Xcode 13.4 / iOS 15.5


text:
Q: Will a Mule Flow stop processing a message after some arbitrary default number of exceptions thrown? I have a flow that inserts objects in a Mongo database using the Mongo connector, which uses the MongoClientImpl provided by the connector.  This client has a line that tries to cast the _id to an ObjectId prior to returning that value as a string to the user after the insert has been submitted to the database.  As far as I can tell, this line does not impact whether the object is inserted, but it does throw an exception when trying to cast a string to an ObjectId.
My flow is throwing hundreds of ClassCastExceptions.  It also does not appear to be processing nearly as many inserts as I would expect.  I expect to see tens of thousands, but instead the flow is only inserting 136 documents.
Is there a limit to the number of exceptions that can be thrown and captured by Mule's DefaultMessagingExceptionStrategy before the flow will stop processing a given message?

A: The answer is no, but you can implement some custom logic and stop the flow. Probably you would need afterwards to manually start it, this is how I would do it:

*

*Use the object store module, for counting the incidences of a given exception.

*Upon a defined number of incidences stop programatically the flow, one option to do this would be something like #[groovy:<flowName>.stop()] given that groovy has direct access to the registry.

*Send an email notification so you can be aware of the errors (specially useful for production).


text:
Q: SWT: how to compute correct size of wrapped text I have a Label component which can contain a very long text. Label support wrapping:
Label label = new Label( composite, SWT.WRAP | SWT.LEFT );

So when I decrease the width of the parent Composite - just resize it with mouse - the text is wrapped correctly, but the height of the parent Composite is not changed so some part of my Label get hidden.

I tried to add a resize listener to parent composite:
expandBar.addListener( SWT.Resize, new Listener() {
  public void handleEvent( Event e ) {
    Point p = label.computeSize( SWT.DEFAULT, SWT.DEFAULT ) // compute size of the text
    int h = p.y; // ! THIS value doesn't change
                      // despite text in label became wrapped
    // now set expandBar current item's height = h;
  }
} );

Is there a way to compute the height of the component with regards to wrapping?
If no, are there SWT components/layouts which change its size dynamically if the child is getting wrapped?


text:
Q: Two Linux Installs Two Swap Spaces I have two linux installs on my computer.  Linux Mint 18 for general use and Subgraph OS because I think the concept sounds cool.  I also have a Windows 10 partition for playing games that require recent versions of direct x
(Subgraph OS is still in alpha and using tor for everything makes it really slow online so I don't think I will use this much for now)
I want to have the linux mint install and the subgraph OS install use different swap partitions.  How do I set this up?  They both try to read each other's swap at the moment and it makes booting linux mint hang sometimes.

A: I bet your problem is that you hibernate (suspend to disk) one kernel and then boot the other. This wouldn't work. Don't try to solve it by using different swap partitions for different systems. This will corrupt your filesystem(s) badly once the hibernated OS wakes up and tries to write some files after the other OS had manipulated the filesystem. You only can do it without risk of data loss if you make sure that you will not mount a filesystem already mounted by a hibernated kernel.
That being said, the partitions used for swap are configured in /etc/fstab.


text:
Q: Count HTTP connections when using BaseHTTPRequestHandler I have an HTTP Server like this
from http.server import BaseHTTPRequestHandler, HTTPServer
from datetime import datetime
import datetime as dt

numberOfTests = 1
timestamp = datetime.now()

class S(BaseHTTPRequestHandler):

    def formatResponse(self, vhod):
        global numberOfTests, timestamp
        timestamp = datetime.now()
        if (numberOfTests == 1):
            print("Test "+str(numberOfTests)+" has started")
            numberOfTests =+ 1
            return

        if (numberOfTests > 1):
            print("Test "+str(numberOfTests)+" has started")
            numberOfTests =+ 1

    def log_message(self, format, *args): #Silence internal log output
        return

    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_POST(self):
        content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
        post_data = self.rfile.read(content_length) # <--- Gets the data itself

        self.formatResponse(post_data.decode('utf-8'))

        self._set_response()

def run(server_class=HTTPServer, handler_class=S, port=8080):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()

I would like that every time a connection is made I would like increment a counter
the problem is that my counter always resets after a new connection is made (like that BaseHTTPRequestHandler is initiated again) so I cannot realy count
ultimatly I would like to mesure time between POST requests and if time is x do something (but I need to figure out how to persist a variable between requests first (as would like to use time.time() as my stopwatch, since time never stops)
if anyone has any idea how to persist a variable between POST requests (to counte them for instance), please let me know
Thanks for Anwsering and Best Regards

A: You could decorate do_POST and do_GET counting the requests in a class variable.
from http.server import BaseHTTPRequestHandler, HTTPServer
from datetime import datetime
import datetime as dt
from functools import wraps

def count(fn):
    @wraps(fn)
    def wrapper(*args, **kw):
        cls = args[0]
        _http_method = fn.__name__[3:]  # Format method

        # Count via HTTP method
        if _http_method not in cls.counts:
            cls.counts[_http_method] = 0
        cls.counts[_http_method] += 1
        return fn(*args, **kw)

    return wrapper

class S(BaseHTTPRequestHandler):
    counts = {}

    def formatResponse(self, vhod):
        print(f"Counter: {self.counts}")

    def log_message(self, format, *args):  #Silence internal log output
        return

    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    @count
    def do_POST(self):
        content_length = int(
            self.headers['Content-Length']
        )  # <--- Gets the size of data
        post_data = self.rfile.read(content_length)  # <--- Gets the data itself

        self.formatResponse(post_data.decode('utf-8'))

        self._set_response()

    @count
    def do_GET(self):
        self.formatResponse('123')
        self._set_response()

def run(server_class=HTTPServer, handler_class=S, port=8080):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()
    httpd.server_close()

run()

Out:
Counter: {'GET': 1}
Counter: {'GET': 2}
Counter: {'GET': 3}
Counter: {'GET': 4}
....

A: When the HTTP server receives a new request it creates a new instance of handler, so an instance variable would always reset. You can configure a class variable, then increment it every time the do_GET or do_POST is invoked. Class variables would change in every instance so it won't reset.
from http.server import BaseHTTPRequestHandler, HTTPServer
from datetime import datetime
import datetime as dt

numberOfTests = 1
timestamp = datetime.now()

class S(BaseHTTPRequestHandler):
    counter = 0 #class variable here

    def formatResponse(self, vhod):
        global numberOfTests, timestamp
        timestamp = datetime.now()
        if (numberOfTests == 1):
            print("Test "+str(numberOfTests)+" has started")
            numberOfTests =+ 1
            return

        if (numberOfTests > 1):
            print("Test "+str(numberOfTests)+" has started")
            numberOfTests =+ 1

    def log_message(self, format, *args): #Silence internal log output
        return

    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_POST(self):
        S.counter +=1
        content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
        post_data = self.rfile.read(content_length) # <--- Gets the data itself

        self.formatResponse(post_data.decode('utf-8'))

        self._set_response()

def run(server_class=HTTPServer, handler_class=S, port=8080):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()


text:
Q: Want to Update the existing listView in fragment by clicking menuitems I am creating an app for finding nearby blood donors. In this app I am using three fragments for swipe navigation. Inn one fragment, the available donor list is shown, but I want to change the list from a menu list by on a clicking particular blood group The 1st list is but when I click the items it shows nothing.
Java code:
public class DonorsFragment extends Fragment {

    SwipeMenuListView listView;
    FirebaseListAdapter adapter;
    TextView fullName,bloodGroup,gender,age,address;
    Query query;
    View rootView;

    FirebaseListOptions<DonorAdapterClass> options;

    public DonorsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

         rootView =inflater.inflate(R.layout.fragment_donors, container, false);

        listView = rootView.findViewById(R.id.listview);

Toast.makeText(getActivity(),"oncreateview",Toast.LENGTH_SHORT).show();

         query =FirebaseDatabase.getInstance().getReference().child("Users");

         setQuery(query);

        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {

                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(170);
                // set a icon
                deleteItem.setIcon(R.drawable.ic_phone);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };

        listView.setMenuCreator(creator);

        listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        // open

                        Toast.makeText(getActivity(),"Item Clicked",Toast.LENGTH_SHORT).show();
                        break;
                }
                // false : close the menu; true : not close the menu
                return false;
            }
        });

        // Inflate the layout for this fragment
        return rootView;

    }

    @Override
    public void onStart() {
        super.onStart();
        adapter.startListening();
    }

    @Override
    public void onStop() {
        super.onStop();
        adapter.stopListening();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.blood_group_menu,menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){

            case R.id.a_pos: {
                Toast.makeText(getActivity(),"A+",Toast.LENGTH_SHORT).show();
                query=FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("canGive_A_Pos").equalTo("yes");
                setQuery(query);
                break;
            }

            case R.id.a_neg: {
                Toast.makeText(getActivity(),"A-",Toast.LENGTH_SHORT).show();
                query=FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("canGive_A_Neg").equalTo("yes");
                setQuery(query);
                break;
            }

            case R.id.b_pos: {
                Toast.makeText(getActivity(),"B+",Toast.LENGTH_SHORT).show();
                query=FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("canGive_B_Pos").equalTo("yes");
                setQuery(query);
                break;
            }

            case R.id.b_neg: {
                Toast.makeText(getActivity(),"B-",Toast.LENGTH_SHORT).show();
                query=FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("canGive_B_Neg").equalTo("yes");
                setQuery(query);
                break;
            }

            case R.id.ab_pos: {
                Toast.makeText(getActivity(),"AB+",Toast.LENGTH_SHORT).show();
                query=FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("canGive_A_Pos").equalTo("yes");
                setQuery(query);
                break;
            }

            case R.id.ab_neg: {
                Toast.makeText(getActivity(),"AB-",Toast.LENGTH_SHORT).show();
                query=FirebaseDatabase.getInstance().getReference().child("Users");
                setQuery(query);
                break;
            }

            case R.id.o_pos: {
                Toast.makeText(getActivity(),"O+",Toast.LENGTH_SHORT).show();
                query=FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("canGive_O_Pos").equalTo("yes");
                setQuery(query);
                break;
            }

            case R.id.o_neg: {
                Toast.makeText(getActivity(),"O-",Toast.LENGTH_SHORT).show();
                query=FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("canGive_O_Neg").equalTo("yes");
                setQuery(query);
                break;
            }

            case R.id.list_all: {
                Toast.makeText(getActivity(),"All",Toast.LENGTH_SHORT).show();
                query=FirebaseDatabase.getInstance().getReference().child("Users");
                setQuery(query);
                break;
            }

        }
        return super.onOptionsItemSelected(item);
    }

    public void setQuery(Query query){

        listView = rootView.findViewById(R.id.listview);

        options = new FirebaseListOptions.Builder<DonorAdapterClass>()
                .setLayout(R.layout.donor_list)
                .setQuery(query,DonorAdapterClass.class)
                .build();

        adapter = new FirebaseListAdapter(options) {

            @Override
            protected void populateView(@NonNull View v, @NonNull Object model, int position) {
                DonorAdapterClass donors = (DonorAdapterClass) model;

                if(donors.getIsDonor().toString().equals("yes")){

                    fullName = v.findViewById(R.id.fullName_list);
                    bloodGroup = v.findViewById(R.id.bloodGroup_list);
                    gender = v.findViewById(R.id.gender_lis);
                    address = v.findViewById(R.id.address_list);
                    age = v.findViewById(R.id.age_list);

                    fullName.setText(donors.getFullName().toString());
                    bloodGroup.setText(donors.getBloodGroup().toString());
                    gender.setText(donors.getGender().toString());
                    address.setText(donors.getAddress().toString());
                    age.setText(donors.getAge().toString());

                }

            }
        };

        listView.setAdapter(adapter);

    }
}

all firebase query and adapter is set in setQuery() method..when it is called from onCreateView() it is working...but when it is called from switch case in onOptionsItemSelected it shows nothing and previous list view also hides
Thanks in Advance :)

A: This is my first answer in centuries so please bear with me. This is not an answer but just pointer to the path towards solution.
Put a break-point at the following points

*

*onOptionsItemSelected

*case R.id.a_pos

*setQuery()

*setQuery::listView inittialization statement

*setQuery::populateView::donor initialization statement

Run the app. Attach the process with debugger. Now when you click "A+" from options, does it get a response from the server or does it throw an exception?


text:
Q: View active MySQL connections per user I need a query that will give me the active or open number of connections to a certain database for a certain user. I have been searching for hours and have come up with nothing so far. I am close, so here is what I have tried.

*

*SHOW STATUS WHERE `variable_name` = 'Threads_connected';

*SHOW STATUS LIKE '%onn%';

*SELECT * FROM information_schema.processlist WHERE USER='database_user';
I work for a web hosting company, and one of our clients keeps hitting his max_user_connections limit, so in troubleshooting why I need to know how many connections his user is using right now since he is no a shared server. I am currently using MySQL (InnoDB) version 5.5.36. Any help would be greatly appreciated!

A: What you need is a breakdown by user and hostname along with a total
SELECT IFNULL(usr,'All Users') user,IFNULL(hst,'All Hosts') host,COUNT(1) Connections
FROM
(
    SELECT user usr,LEFT(host,LOCATE(':',host) - 1) hst
    FROM information_schema.processlist
    WHERE user NOT IN ('system user','root')
) A GROUP BY usr,hst WITH ROLLUP;

This will handle host address that have a colon separating hostname and port number
I hope everybody is not logging in as root

A: There was a discussion in detail for this: https://dba.stackexchange.com/a/47160/385
In short, the queries you need are
SELECT max_user_connections FROM mysql.user
WHERE user='db_user' AND host='localhost';
and
SHOW VARIABLES LIKE 'max_user_connections';
UPDATE
Maybe this is not direct answer to your question, but according to http://dev.mysql.com/doc/refman/5.5/en/user-resources.html MySQL allows you to limit the number of access per hour. So, maybe that answers why a certain user hits limit while the number of connections of them are small according to process list. Unfortunately, I cannot find reference on how to get the access counter.


text:
Q: How to handle "this can never happen" style of errors in C? I'm developing a large project in C with other team members and we have a disagreement on how "this can never happen" style of errors should be handled. By this I mean error cases that the code currently can never reach, but somebody can modify the code and after the modification it is possible the error case will be reached.
For example, let's say I have a function that returns either 0 on success or -EINVAL if it's given a NULL argument. What I naturally do is:
int err;
struct myctx ctx;
err = callFunction(&ctx);
if (err != 0)
{
  abort();
}

or even:
int err;
struct myctx ctx;
err = callFunction(&ctx);
if (err == -EINVAL)
{
  abort();
}
else if (err != 0)
{
  abort();
}

...to distinguish between the two cases of -EINVAL and unknown error code.
The benefits of this error handling approach are that it is simple to program (few lines of code) and leaves behind a core file that can be used to quickly debug the situation.
However, some team members disagree with this error handling approach because I'm doing an unclean exit and while the code currently can never reach the abort() line it is possible that in the future somebody modifies the code and it reaches the abort() line then. According to them, I should try to do a controlled exit and print the reason to the user. So, I guess instead of this I should do:
int err;
struct myctx ctx;
err = callFunction(&ctx);
if (err == -EINVAL)
{
  fprintf(stderr, "Argument was NULL in file %s line %d\n", __FILE__, __LINE__);
  exit(1);
}
else if (err != 0)
{
  fprintf(stderr, "Error was %d in file %s line %d\n", err, __FILE__, __LINE__);
  exit(1);
}

This second error handling strategy has a downside that it does not leave behind a core file that can be used to debug this situation. Also it results in code that has more lines of code.
So, the question is, which strategies exist in C to handle "this can never happen" style of errors? What are their pros and cons? How to decide which to use? Should I do an abort or a controlled exit with a descriptive error message?

A: On principle, you should always handle errors and generate the most explanatory description possible to the user. That is the proper thing to do, what they would call honte in Japan.
However, in practice, your unexplained abort() in the first example is what most everyone does because it is faster to write. The consequence of this is that most applications, when they fail, exit miserably. For example, when Microsoft Word crashes, the message to the user is "Word has encountered a problem and will now exit." or something to that effect. Many applications give no message at all but simply terminate.
Proper programming is to fully code what is called the negative path. Not only should every possible failure generate a meaningful text message, but as the failure returns and percolates backwards through the call chain, each calling function should add its context and any relevant parameters to the front of the message. So the end message to user should be something like this:

While attempting to initialize: while attempting to load configuration
  file at [c:\user\data\configuration.ini]: failed to read line 453:
  invalid parameter value 'NumRedirects' (out of bounds): -43

In this error message what we see is each function as it is receiving the error inserts its context at the beginning of a string followed by a colon and then returns failure to the function that called it. The net result shows all the important information (the file that was being read, the line that was being parsed, the parameter that was being loaded, the invalid value that was supplied for the parameter). This fully explains to the user (or developer) what the problem was.

A: I think this is what assertions are for. The return value is checked unless the code is compiled with NDEBUG defined.
#include <assert.h>
...
int err;
struct myctx ctx;
err = callFunction(&ctx);
assert(err != -EINVAL);
assert(err == 0);

The idea is that bugs usually lead to the unexpected. Also, assert statements increase the readability of the code. When the assertion fails the automatic error message helps the programmer to identify the failed assertion. The release version can be built with -DNDEBUG to reduce the number of branches.


text:
Q: How is a software backdoor implemented? The wikipedia article on Limewire says that "LimeWire 5.5.11 and newer have been disabled using a backdoor installed by the company".
How are such backdoors implemented? Is it as simple as the the program going out and checking a web service and disabling itself? If it's in fact so simple, it has to be stored somewhere on the user's drive (in a plist, or in the registry for example). It's hard to imagine no one has in fact figured out a way to turn that flag off and use the program.

A: In the case of Borland's Interbase (now called Firebird), there was a hidden super-user that the system required in order to work. This hidden super-user could not be disabled, and it had a known password that could not be changed (until a patch became available to do so). This would allow anyone who knew the hardcoded username/password combination to access any installation. Disabling this account breaks the system because it can no longer authenticate users.
CERT advisory on Interbase.

Is it as simple as the the program going out and checking a web service and disabling itself?

This is generally how many forms of license management work. Some simply check to see if "my serial number" is in use, and if so, they exit. Some use a form of PKI and revoke local certificates if the license is invalid. For example, Adobe Reader pings crl.adobe.com when it starts to see if any licenses have been revoked, as the key to enable plugins to work in the free reader require a digital key. If a plug-in does things that violate the licence, the cert enabling it will be revoked. License management is a very complicated process because you've got to stay one step ahead of the crackers, and even minor bugs in your licensing code will cause major customer problems.

A: The typical concept of a back door in software is one which allows the creator undisclosed and unwanted access to installations of his software. The simplest method would be to hard-code additional credentials to the system.
There is an important distinction between this meaning and a piece of software that routinely checks for updates, even though they function entirely the same. The user knows and wants it to happen. It's only a cultural shift that turns the outrageous transgression of altering my machine into a typical and daily occurrence that happens with today's software. But at least they're usually nice enough to ask first.


text:
Q: Making javascript synchronous code from nested asychronous calls with a modal library? So, this might be a bit confusing. A while back when Chromium decided to kill their modal support, our place found a library that seemed to work great (and yes, they want it parsed out between webkit/non-webkit [basically we have two versions of this thing running in either Firefox or Chrome])
function AddToConfig(){
....
....
....

if(/ipad|android|webkit/i.test(navigator.userAgent)){
    $.showModalDialog({
    url: "get_required.php?maxSelect="+max+"&forceReload="+Math.random(),
    dialogArguments: window,
    height: 270,
    width: 510,
    position: 'top',
    onClose: function(){ numReq = this.returnValue; return retAction(numReq); }
    });
}else{
    numReq = window.showModalDialog ("get_required.php?maxSelect="+max+"&forceReload="+Math.random(),             window, "dialogHeight:250px; dialogWidth:500px; center:yes; help:no; resizable:no; scroll:no; status:no; edge:raised");
    return numReq;
}

(Lifted/more info here)
http://extremedev.blogspot.com/2011/03/windowshowmodaldialog-cross-browser-new.html
For a while, it worked fine. All the code replacement thus far has been situations where user clicks button, popup (now modal) happens, it does its thing and returns a value that 99% of the time requires a iFrame or something to be refreshed, so timing wasn't a issue. Great, awesome.
The situation I'm in right now, this modal call is in the middle of a bunch of other calculations. It fires if it reaches down this chain of ifthens. However, the code above seems to be making it a issue. I've tried doing callbacks like below (and maybe I'm just writing them wrong) and that hasn't worked. Hell, the comments in that URL above say doing this is a little tricky. Here's kinda (what I hope) is enough.
So, I want to hit AddToConfig(), ClearSelections(), printText() which seems simple in and of itself, but the GetRequired asynch-y call is throwing everything off.
Main code in question (Original):
//What kicks it off
<input type=button class="button3" id=btnAdd onClick='AddToConfig()' value='Add' onMouseDown="this.className='button3down'" onMouseUp="this.className='button3over'" onMouseOver="this.className='button3over'" onMouseOut="this.className='button3'">

  function AddToConfig(){
    ....
    ...
    if (meowmeowmeowmeow)
    {
       ....
    }
    else
    {
        //Modal - NEEDS TO PAUSE
        var requiredCount = GetRequired(arrConfigSet[--lenS][2]);
        //Modal - NEEDS TO PAUSE

        arrConfigSet[lenS][1] = requiredCount;
        arrConfigSet[lenS][2]++;
    }

    arrConfigItem[lenI] = new Array ();
    ...
    ...
    ClearSelections();
}

 function GetRequired(max)
 {
        //This is modal and dumb and makes me cry

        var numReq = '';

    if(/ipad|android|webkit/i.test(navigator.userAgent)){
        $.showModalDialog({
        url: "get_required.php?maxSelect="+max+"&forceReload="+Math.random(),
        dialogArguments: window,
        height: 270,
        width: 510,
        position: 'top',
        onClose: function(){ numReq = this.returnValue; return numReq; }
    });
}else{
    //This is fine, because it pops up a new window.
    numReq = window.showModalDialog ("get_required.php?maxSelect="+max+"&forceReload="+Math.random(),             window, "dialogHeight:250px; dialogWidth:500px; center:yes; help:no; resizable:no; scroll:no; status:no; edge:raised");
        return numReq;
    }
}

function ClearSelections(){
    //various UI resetting of values
    printText();
}

Main code in question (My callback version):
<input type=button class="button3" id=btnAdd onClick='AddToConfig(function(){ClearSelections();})' value='Add' onMouseDown="this.className='button3down'" onMouseUp="this.className='button3over'" onMouseOver="this.className='button3over'" onMouseOut="this.className='button3'">

if (meowmeowmeowmeow)
{
   ....
}
else
{
var requiredCount = GetRequired(arrConfigSet[--lenS][2]);

//So, here's my problem, that line above works fine with Firefox/non webkit because
    //Popup windows make things work fine and great. With this modal thing we found
    //on the internet (in getRequired()) this line of code keeps going and runs stuff below
    // the line and keeps going. I need this to
    //stop here. I've tried to do something like put that requiredCount in a while loop, but
    //then it says Uncaught TypeError: Cannot read property '2' of undefined on that var requiredCount.
    //For the record, this is all done from a onClick event on a button if it makes a difference.
    //
    //
    //alert('test:' + arrConfigSet[--lenS][2]);  //Returns a value!
    //      var requiredCount;
    //      while(typeof variable_here === 'undefined'){
    //          requiredCount = GetRequired(arrConfigSet[--lenS][2]);
    //      }

    //This keeps running when in Webkit, I need that requiredCount to be set and finalized with
    //the modal window gone before this continues.

    arrConfigSet[lenS][1] = requiredCount;
    arrConfigSet[lenS][2]++;
}

arrConfigItem[lenI] = new Array ();
...
...
callback();
}

 function GetRequired(max)
 {
        //This is modal and dumb and makes me cry

        var numReq = '';

    if(/ipad|android|webkit/i.test(navigator.userAgent)){
        $.showModalDialog({
        url: "get_required.php?maxSelect="+max+"&forceReload="+Math.random(),
        dialogArguments: window,
        height: 270,
        width: 510,
        position: 'top',
        onClose: function(){ numReq = this.returnValue; return numReq; }
    });
}else{
    //This is fine, because it pops up a new window.
    numReq = window.showModalDialog ("get_required.php?maxSelect="+max+"&forceReload="+Math.random(),             window, "dialogHeight:250px; dialogWidth:500px; center:yes; help:no; resizable:no; scroll:no; status:no; edge:raised");
        return numReq;
    }
}

function ClearSelections(){
    //various UI resetting of values
    printText();
}

Does anyone have any ideas on how I can get the JS to stop in its tracks until the script gets that return value? It gets it fine, but by the time it does, the rest of the code after it ran.
Note, we're running jQuery 1.4, so promise() is out of the question and I'm not in any position to push for anything newer. The code is kinda a rat's nest as it.

A: You can implement your own simple deferred library, or simply pass in a function that get's called when everything is complete. Simple example:
var whenDone = function(res) { alert('I\'m Done: ' + res); };

doComplexTask(whenDone);

And the doComplexTask:
function doComplexTask(completeFn) {
    //Do some crazy work here that takes a long time (Or is asynchronous)
    var res = crazyWork();
    completeFn(res);
}

A simple jfiddle can be found here.


text:
Q: Python - Hard time understanding this recursion code example I am trying to understand how this piece of code works. It is basic recursion, but I am having a hard time grasping the concept.
The code comes from the sololearn app and I have read their tutorials on the topic but have failed to understand the concept. You will get a boolean value every time you print out the return value of the functions, but I dont understand how the functions are getting to that results. Like I can run the code and see the output, but I need to know HOW it works. Love ya!!
def is_even(x):
        if x == 0:
            return True
        else:
            return is_odd(x-1)

def is_odd(x):
        return not is_even(x)

print(is_odd(1))

A: Try tracing the execution, the left-hand-side of a (=>) indicates a new call to one of the functions, the right-hand-sides indicate what steps are taken to determine the end result.
is_odd(1) => not is_even(1)
    is_even(1) => is_odd(0)
        is_odd(0) => not (is_even(0))
            is_even(0) => True
                  => not (True)
                  => False
               => False
          => not (False)
          => True

Or this might help more,
is_odd(1)
=> not is_even(1)
=> not (is_odd(0)
=> not (not (is_even(0))
=> not (not (True))
=> not (False)
=> True

FWIW, these functions are what's called "mutually recursive" (ie. more than 1 function calling into each other). If you're not comfortable with recursion, you should probably start with a simple single recursion, common examples would be fibonnaci numbers or factorial function.
def fact(n):
    if n == 0:
        return 1
    else:
        return n * fact (n-1)

def fib(n):
    if n == 0:
        return 1
    elif n == 1:
        return 1
    else:
        return fib (n-1) + fib (n-2)

A: I've added some useful print statements, hopefully this helps to understand what's actually being executed when is_odd is invoked:
def is_even(x):
    if x == 0:
        print("return True")
        return True
    else:
        print("return is_odd({0}-1)".format(x))
        return is_odd(x-1)

def is_odd(x):
    print("return not is_even({0})".format(x))
    return not is_even(x)

print(is_odd(1))
return not is_even(1)
return is_odd(1-1)
return not is_even(0)
return True
True

print(is_odd(2))
return not is_even(2)
return is_odd(2-1)
return not is_even(1)
return is_odd(1-1)
return not is_even(0)
return True
False

Also, consider using python debugger to interactively inspect your code as it's running.
References
Python Debugger: https://docs.python.org/3/library/pdb.html

A: So lets just break this down by steps.
def is_even(x):
        if x == 0:
            return True
        else:
            return is_odd(x-1)

def is_odd(x):
        return not is_even(x)

print(is_odd(1))

1) we say print -> is_odd(1).  So we're sending a 1 to is_odd() function
2) is_odd() recieves the 1 and before it can return a value, it must call is_even() and send that same 1.
3) is_even() now recieves that 1 and checks if its equal to zero, but it fails, so it then has to call is_odd() and send it 1 - 1.
4) is_odd checks the new value (zero in this case) and calls again is_even() sending that zero
5) is_even() now resovles at the if x == 0: line and returns True.
6) Now we've reached the end of the recursive loop and all the functions will resolve with their return statments.  Starting with the is_even() being True.

Here's a breakdown ->
print(is_odd(1)) ->
    print(NOT is_even(1))->
       print(NOT is_odd(1-1)) ->
         print(NOT NOT is_even(0)) ->
           print(is_even(0)) ->
               print(True) ->
                 True


text:
Q: Rails 4 application not overriding X-Frame-Options from SAMEORIGIN I have a rails 4 application that loads an iframe in one of the views. I'm testing my app on staging using safari (it works on Chrome and Firefox) and I'm experiencing an X-Frame-Options rejection error. Inside of my developer tools in Safari, when I load the iFrame view I am receiving:
Refused to display 'https://demo.docusign.net/Signing/(X(1)S(xxxxx))/SessionTimeout.aspx?fi=xxxx' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

I don't receive this error in Firefox or Chrome.
My rails code is as follows:
# application_controller.rb
def allow_iframe
  response.headers.delete('X-Frame-Options')
end

# iframe controller
before_filter :allow_iframe, only: [:show, :signing_response]

Any guidance on this issue would be appreciated.

A: The root cause here isn't your server or Rails configuration, or even intrinsically tied to Safari....its because the web browser is blocking 3rd party cookies.
In an embedded signing workflow, the DocuSign window within the iFrame will try to drop an authentication cookie on the signers machine.  Since its coming from demo.docusign.net, the browser considers this a 3rd party cookie (versus 1st party cookies which is what your server/domain drops directly). Safari blocks 3rd party cookies by default where almost all other browsers allow them by default.
If you look at the error URL, note the following:

*

*demo.docusign.net is whats refusing to be displayed in an iFrame because IT is what set the X-Frame-Options header, eg the header issue is from the DocuSign URL, NOT your server pages (including whatever you passed or set for returnURL).

*SessionTimeout.aspx? is on the URL not the normal SigningStart param...this is because the cookie was blocked and DocuSign has invalided the signing URL

You can reproduce the issue on Chrome for testing verification by following the instructions here: https://support.google.com/chrome/answer/95647?hl=en to set it to block 3rd party cookies.
Note you may see inconsistent results in testing because if a valid DocuSign cookie is already on the clients machine, the browser may not consider it 3rd party anymore and allow the new authentication cookie to drop, allowing the signing window to load successfully
Unfortunately there are no good, 'turn-key' solutions.  Your options are:

*

*If you can control or influence your client browsers' settings (like in a corporate network) you can set them all to allow 3rd party cookies or whitelist docusign

*Open the signing window in a new tab or popup.  This is probably the best approach but can complicate user experience and if you use the JS / popup route (vs target='blank' for a new window), it has the potential to get stuck in ad / popup blockers.  See here to help get around that if you go the JS route: Bypass popup blocker on window.open when JQuery event.preventDefault() is set

*some set of custom hack / workarounds to get the cookie placed first and then reload the signing window.  These have has varying degrees of success but the root issue is the same as a lot of Facebook apps:

More resources:

*

*Safari 3rd party cookie iframe trick no longer working?

*Alternative to iFrames with HTML5

*block third party cookies - workaround (facebook apps etc)


text:
Q: Web Service Receive Null Data iOS I had a very strange situation in using web service
Here is my Xcode Project File
https://dl.dropbox.com/u/9507586/FubonTest.zip
I got the response back from the server as below.
2013-03-04 15:56:18.473 FubonTest[1059:f803] 1: connection: didReceiveResponse
2013-03-04 15:56:18.473 FubonTest[1059:f803] 2: connection: didReceiveData
2013-03-04 15:56:18.699 FubonTest[1059:f803] 2: connection: didReceiveData
2013-03-04 15:56:18.699 FubonTest[1059:f803] 3: Done. Received Bytes: 1789
2013-03-04 15:56:18.700 FubonTest[1059:f803] Return (null)

I did receive bytes, but the xml tag file is null. The server side people told me they use utf-8 encoding, but it just returned null. If I use ascii encoding, the returning data is not null, but it's not the xml tag file I expected.
The correct returning xml tag files should be as below.
The returning xml tag file is using eclipse(window version) web service function.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<ns1:RegistResponse xmlns:ns1="http://service.fubon.com" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<RegistReturn xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="soapenc:string">该用户未投保</RegistReturn>
</ns1:RegistResponse>
</soapenv:Body>
</soapenv:Envelope>

Can someone help me to sort it out?

A: There is a misspelling. In your ViewController.m file, line 57:
Change forHTTPHeaderField: @"Contnet-Type"];
to forHTTPHeaderField: @"Content-Type"];


text:
Q: Tabulator: add class to class list, on cells when hidden by pagination I need to add and/or remove a class to all cells even when they are hidden by pagination. I am able to add a class, but only the cells on the active page are getting the class. I understand that is because it is only updating what is available in the DOM and the hidden rows are not active in the DOM at the time, I'm adding the class.
Is there a way that Tabulator handles this?
As you can see from below i'm getting the rows (not shown) and then looping over the rows and attempting to update the cell classList.
for (var i = 0; i < rows.length; i++) {
    if (rows[i] != this){
        var row = rows[i],
            cell = row.getCell(col),
            cellElement = cell.getElement();

        cellElement.classList.add('disable-cell');

        console.log(cell);

    }
}


text:
Q: Calling object's function in code don't work I've been doing a simple canvas animation using Sprites, everything is fine as long as I call objects functions from browser console, running coin.draw() in code and it works but it don't show image attached to this object and when I type coin.draw() in browser console it normally draws image, can you explain it to me?

<!DOCTYPE html>
<html>

<head>
    <title>flipcoin</title>
</head>

<body>
    <canvas id="myCanvas"></canvas>
    <script type="text/javascript">
    coins = new Image();
    coins.src = "coins.png";

    var canvas = document.getElementById('myCanvas');
    canvas.height = 500;
    canvas.width = 500;
    var ctx = canvas.getContext('2d');

    function Sprite(option) {

        var that = {};

        that.img = option;
        that.width = 44;
        that.height = 40;
        that.context = ctx;
        that.frameIndex = 0;
        that.fps = 60;
        that.time = 0;
        that.start = true;

        that.draw = function() {

            that.context.drawImage(
                that.img,
                0 + that.width * that.frameIndex,
                0,
                that.width,
                that.height,
                0,
                0,
                that.width,
                that.height);

            console.log("works");
        }

        that.update = function() {

            that.time++

                if (that.time > that.fps) {

                    that.time = 0;
                    //that.context.clearRect(0, 0, canvas.width, canvas.height);
                    that.draw();
                    that.frameIndex++;

                    if (that.frameIndex == (coins.width / that.width) - 1) {

                        that.frameIndex = 0;

                    }

                }
        }

        that.animate = function() {

            that.update()
            console.log(that.time);
            window.requestAnimationFrame(that.animate());

        }

        return that;
    }

    var coin = new Sprite(coins);
    coin.draw();
    </script>
</body>

</html>

A: I think the problem you have is because the image isn't loaded first time you run the script.  What you can do is make the Sprite() function check that and only execute after the image is loaded.
Change this bit...
var coin = new Sprite (coins);
coin.draw();

to this...
var coin = new Sprite (coins);

// coins may not be loaded - we need to check here before we use it
if (coins.complete) {
    coin.draw();
}
else {
    coins.addEventListener("load", function() {
        coin.draw();
    });
}

That checks to see if the image is already loaded (which it will be if it's cached) and executes draw() if it is.  If it's not it attaches an event handler to the load event, so once the image is loaded it will execute draw().
This does not cover the possibility of a load error.  You can add a separate event handler for that, if needed.


text:
Q: Update Draft on-the-go in with outlook addin I am working on  a outlook add-in. I want to be able to update the draft with a data on the go (body of email converted to encrypted format.). The goal is to protect the data of user , so that the orignal data is not stored in draft as the person is writing in compose mode.
I am using office.js(https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/apis). But i am not able to update draft using it , also cannot access attachment in read mode.
What could be a possible approch. Can i use Microsoft graph? or any suggestion how to solve the issue.

A: You should be able to update compose mails with any of the following apis:
https://learn.microsoft.com/en-us/javascript/api/outlook/office.messagecompose?view=outlook-js-preview
You can access attachments in Read Mode Via the Attachment APIs:
https://learn.microsoft.com/en-us/javascript/api/outlook/office.messageread?view=outlook-js-preview#attachments
https://learn.microsoft.com/en-us/javascript/api/outlook/office.messageread?view=outlook-js-preview#getAttachmentContentAsync_attachmentId__callback_


text:
Q: how to prevent mock GPS location (spoofing) from fake GPS app in Swift? I am making an app that using CLLocationManager, this app will be used to record the attendee of the employee. to validate the attendee of the employees, we will get GPS Coordinate.
as far as I know, in there is an app that usually used to get fake GPS. I want to prevent this mock GPS to be active when the user using my app.
If I am using Android, I can download a fake GPS app. and when let say I use tinder I can fake my location. let say actually I am in Bangkok, but because I use fake GPS app, I can set my tinder location to be in London, not in Bangkok anymore.
So Basically I want to prevent fake location that comes from that fake GPS when the user using my App. To be honest I don't really know whether iOS allow fake location or not
can I get that function in Swift?
here is the class LocationManager I use to get the coordinate
import UIKit
import CoreLocation

class LocationManager: NSObject {
    let manager = CLLocationManager()
    var didGetLocation: ((Coordinate?) -> Void)?

    override init() {
        super.init()

        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestLocation()
    }

    func getPermission() {
        // to ask permission to the user by showing an alert (the alert message is available on info.plist)

        if CLLocationManager.authorizationStatus() == .notDetermined {
            manager.requestWhenInUseAuthorization()
        }

    }
}

extension LocationManager : CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
            manager.requestLocation()
        }
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.first else {
            didGetLocation?(nil)
            return

        }
        let coordinate = Coordinate(location: location)
        if let didGetLocation = didGetLocation {
            didGetLocation(coordinate)

        }
    }
}

private extension Coordinate {
    init(location: CLLocation) {
        latitude = location.coordinate.latitude
        longitude = location.coordinate.longitude
    }
}

A: You can check if the app is jailbroken or not. If it already jailbroken, you can prevent the user to use the app with showing permanent dialog or something else.
If you wanna know how to detect the device is jailbroken or not, you can find it by yourself. There is so many literature that will tell you how.
Cheers :)

A: Only thing I can tell you and I've been in a similar situation is you need to have a backup method to get the user location. Use an IP location API/service (which is not 100% reliable) and create a logic in your app to compare the data.
PS: THIS IS NOT A SOLUTION TO YOUR PROBLEM it's just an idea you could try to work with. But this would only work best if spoofing the location is happening using different cities/states since IP location is not a high accuracy one. If GPS says you are in San Diego but your IP say you are in San Francisco, then you could block the UI/request until user confirms something.
PS2: in iOS the only way I know a user can spoof it's location is running an app through XCode, using the location feature and then opening your app. (used to do that a lot with pokemon go #notproud :))


text:
Q: What is the best way to use threading on a sorting algorithm, that when completed, creates a new activity and gives its data to the new activity? I will start this by saying that on iOS this algorithm takes, on average, <2 seconds to complete and given a simpler, more specific input that is the same between how I test it on iOS vs. Android it takes 0.09 seconds and 2.5 seconds respectively, and the Android version simply quits on me, no idea if that would be significantly longer. (The test data gives the sorting algorithm a relatively simple task)
More specifically, I have a HashMap (Using an NSMutableDictionary on iOS) that maps a unique key(Its a string of only integers called its course. For example: "12345") used to get specific sections under a course title. The hash map knows what course a specific section falls under because each section has a value "Course". Once they are retrieved these section objects are compared, to see if they can fit into a schedule together based on user input and their "timeBegin", "timeEnd", and "days" values.
For Example: If I asked for schedules with only the Course ABC1234(There are 50 different time slots or "sections" under that course title) and DEF5678(50 sections) it will iterate through the Hashmap to find every section that falls under those two courses. Then it will sort them into schedules of two classes each(one ABC1234 and one DEF5678) If no two courses have a conflict then a total of 2500(50*50) schedules are possible.
These "schedules" (Stored in ArrayLists since the number of user inputs varies from 1-8 and possible number of results varies from 1-100,000. The group of all schedules is a double ArrayList that looks like this ArrayList>. On iOS I use NSMutableArray) are then fed into the intent that is the next Activity. This Activity (Fragment techincally?) will be a pager that allows the user to scroll through the different combinations.
I copied the method of search and sort exactly as it is in iOS(This may not be the right thing to do since the languages and data structures may be fundamentally different) and it works correctly with small output but when it gets too large it can't handle it.
So is multithreading the answer? Should I use something other than a HashMap? Something other than ArrayLists? I only assume multithreading because the errors indicate that too much is being done on the main thread. I've also read that there is a limit to the size of data passed using Intents but I have no idea.
If I was unclear on anything feel free to ask for clarification. Also, I've been doing Android for ~2 weeks so I may completely off track but hopefully not, this is a fully functional and complete app in the iTunes Store already so I don't think I'm that far off. Thanks!

A: 1) I think you should go with AsynTask of Android .The way it handle the View into `UI
threadandBackground threadfor operations (Like Sorting` ) is sufficient enough to help
you to get the Data Processed into Background thread And on Processing you can get the
Content on UI Thread.
Follow This ShorHand Example for This:
Example to Use Asyntask
2) Example(How to Proceed):
a) define your view into onPreExecute()
b) Do your Background Operation into doInBackground()
c) Get the Result into onPostExceute() and call the content for New Activty
Hope this could help...

A: I think it's better for you to use TreeMap instead of HashMap, which sorts data automatically everytime you mutate it. Therefore you won't have to sort your data before start another activity, you just pass it and that's all.
Also for using it you have to implement Comparable interface in your class which represents value of Map.
You can also read about TreeMap class there:
http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html


text:
Q: Tower Won't Roll Back Commit I am trying to roll back to a particular commit using Tower v 1.4.16 with Mac 0SX v 10.6.8. When I right-click on the commit, the option to "Roll Back to This Commit" is greyed out. Why is this happening?

A: And problem solved - I did not have the (head) selected over in the left-had column. Once I clicked "master (HEAD)". The option to Roll Back to This Commit and Revert This Commit were available.


text:
Q: Removing Duplicate Items in an Array without Regex or filter I have been stumped on this problem for a few hours now and am making no progress.  I feel like this should be simple.  I am trying to Remove duplicate characters in a String without using methods such as Filter or a Reg ex.
Here is my current code:
var duplicate = function(string) {
  var newString = string.split("");
  var finalArrayWithNoDuplicates = []

  for (var i = 0; i < newString.length; i++){
    for (var=0; j < newString.length; i++){
      while(newString[i])
        if (newString[i] !== newString[j]){

        }
    }
  }

  return finalArrayWithNoDuplicates.join("");

};

I am able to filter one letter at a time but as I progress down the chain in the while statement I am adding letters that were filtered out originally.
All of the algorithm tutorials for this algorithm are in Java that I have been finding.  Is there a way to do this with only using a a for and while loops?

A: There are several things wrong with the proposed code:

*

*It has serious errors (the inner loop is written all wrong)

*You don't need to involve arrays at all, strings will do just fine

*The "if char !== other char" check will never provide enough information to act on

Here's an alternative version using for loops and the same basic idea:
function deduplicate(str) {
    var result = "";
    for (var i = 0; i < str.length; ++i) {
        var found = false;
        for (var j = 0; j < i; ++j) {
            if (str[i] == str[j]) {
                found = true;
                break;
            }
        }
        if (!found) result += str[i];
    }

    return result;
}

Each character str[i] in the input string is compared to all characters str[j] that precede it (there is no point in comparing to characters that follow it because we are going to process those when their turn comes up anyway). If the character is not equal to any of those that precede it then we know it's the first of its kind to appear and include it in the result.
Note that this algorithm has O(n²) performance, which is very poor compared to other possible approaches. Its main selling point is that it is straightforward and that everything happens "in front of your eyes".

A: Here is a slightly modified version of your function that uses an object to keep track of which letters have already been encountered:
var duplicate = function(string) {
  var finalArrayWithNoDuplicates = [];
  var seen = {};
  for (var i = 0; i < string.length; i++) {
    if (!seen[string[i]]) {
      finalArrayWithNoDuplicates.push(string[i]);
      seen[string[i]] = 1;
    }
  }
  return finalArrayWithNoDuplicates.join("");
};

A: *

*No need for two nested for-loops

*No need for "while" loop as well

*in the following line of code there are two errors: for (var=0; j < newString.length; i++){ first one is var=0 (compilation error) and second is theat you increment i instead of j

*It can be done by adding only unique elements (that don't appear twice) to finalArrayWithNoDuplicates
as follows:
var duplicate = function(newString) {

  var finalArrayWithNoDuplicates = []
  var x = 0;
  for (var i = 0; i < newString.length; i++){
        // if the char appears in another index
        // or if it's already in the result - don't add it
    if (newString.lastIndexOf(newString[i]) !== i || finalArrayWithNoDuplicates.indexOf(newString[i]) > -1){
            continue;
    }
    else{
      finalArrayWithNoDuplicates[x++] = newString[i];
    }

  }

  return finalArrayWithNoDuplicates.join("");

};

var arr = [1,2,3,4,5,4,5,6,7];
alert(duplicate(arr));

OUTPUT:

1234567


text:
Q: Periodically running a Callable via ScheduledExecutorService I have a Callable<String>. I want to run it periodically via ScheduledExecutorService.scheduleAtFixedRate(), and to get a list of all the Strings that were returned by the .call() invocations on my callable. As scheduleAtFixedRate does not take a  Callable (only Runnables) I need to roll out a custom Runnable that wraps my Callable, something along these lines:
final Callable<String> myCallable = ....;
final ConcurrentLinkedQueue<String> results
  = new ConcurrentLinkedQueue<String>();

Runnable r = new Runnable() {
  @Override public void run() {
    try {
      results.add(myCallable.call());
    } catch (Exception e) {
      results.add(null);  // Assuming I want to know that an invocation failed
    }
  }
};

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(r, 0, 1, TimeUnit.SECONDS);

Naturally, I'd like to avoid rolling out my own custom thingies (especially in multi-threaded code), so I wonder there is a JDK class that does this kind of aggregation?

A: What you are doing above is treating your Callable implementation as just another normal class. You are not submitting the callable to a ThreadPool executor. Calling Callable.call() doesn't utilize the ThreadPoolExecutor.
You need to submit your Task (Runnable/Callable/ForkJoinTask,etc..) to a ThreadPool to utilize the thread pooling.
You can use the Futures to collect the results once executed.
ForkJoinPool is one option you can try thats part of JDK 7. Fork the tasks and Join them using ForkJoinTask
Why not use Futures? They are exactly meant for knowing the state of Task and its result.
Did you look at this : Using Callable to Return Results From Runnables


text:
Q: Can we do image processing with Palantir Foundry? I'm exploring the Palantir Foundry platform and it seems to have ton of options for rectangular data or structured data. Does anyone have experience of working with Unstructured Big data on Foundry platform? How can we use Foundry for Image analysis?

A: Although most examples are given using tabular data, in reality a lot of use case are using foundry for both unstructured and semi-structured data processing.
You should think of a dataset as a container of files with an API to access and process the files.
using the file level API you can get access to the files in the dataset and process them as you like. If these files are images you can extract information from the file and use it as you like.
a common use case is to have PDFs as files in a dataset and to extract information from the PDF and store it as tabular information so you can do both structured and unstructured search over it.
here is an example of file access to extract PDF:
import com.palantir.transforms.lang.java.api.Compute;
import com.palantir.transforms.lang.java.api.FoundryInput;
import com.palantir.transforms.lang.java.api.FoundryOutput;
import com.palantir.transforms.lang.java.api.Input;
import com.palantir.transforms.lang.java.api.Output;
import com.palantir.util.syntacticpath.Paths;
import com.google.common.collect.AbstractIterator;
import com.palantir.spark.binarystream.data.PortableFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.UUID;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.Row;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

public final class ExtractPDFText {

    private static String pdf_source_files_rid = "SOME RID";
    private static String dataProxyPath = "/foundry-data-proxy/api/dataproxy/datasets/";
    private static String datasetViewPath = "/views/master/";

    @Compute
    public void compute(
        @Input("/Base/project_name/treasury_pdf_docs") FoundryInput pdfFiles,
        @Output("/Base/project_name/clean/pdf_text_extracted") FoundryOutput output) throws IOException {

        Dataset<PortableFile> filesDataset = pdfFiles.asFiles().getFileSystem().filesAsDataset();

        Dataset<String> mappedDataset = filesDataset.flatMap((FlatMapFunction<PortableFile, String>) portableFile ->
            portableFile.convertToIterator(inputStream -> {

                String pdfFileName = portableFile.getLogicalPath().getFileName().toString();
                return new PDFIterator(inputStream, pdfFileName);
            }), Encoders.STRING());

        Dataset<Row> dataset = filesDataset
                .sparkSession()
                .read()
                .option("inferSchema", "false")
                .json(mappedDataset);

        output.getDataFrameWriter(dataset).write();
    }

    private static final class PDFIterator extends AbstractIterator<String> {
        private InputStream inputStream;
        private String pdfFileName;
        private boolean done;

        PDFIterator(InputStream inputStream, String pdfFileName) throws IOException {
            this.inputStream = inputStream;
            this.pdfFileName = pdfFileName;
            this.done = false;
        }

        @Override
        protected String computeNext() {
            if (done) {
                return endOfData();
            }

            try {
                String objectId = pdfFileName;
                String appUrl = dataProxyPath.concat(pdf_source_files_rid).concat(datasetViewPath).concat(pdfFileName);
                PDDocument document = PDDocument.load(inputStream);

                PDFTextStripper pdfStripper = new PDFTextStripper();

                String text = pdfStripper.getText(document);
                String strippedText = text.replace("\"", "'").replace("\\", "").replace(""", "'").replace(""", "'").replace("\n", "").replace("\r", "");

                done = true;
                return "{\"id\": \"" + String.valueOf(UUID.randomUUID()) + "\", \"file_name\": \"" + pdfFileName + "\", \"app_url\": \"" + appUrl + "\", \"object_id\": \"" + objectId + "\", \"text\": \"" + strippedText + "\"}\n";
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

A: Indeed you can do image analysis on Foundry as you have access to files and can use arbitrary libraries (for example pillow or skimage for python). This can be done at scale as well as it can be parallelised.
A simple python snippet to stitch two pictures together should get you started:
from transforms.api import transform, Input, Output
from PIL import Image

@transform(
    output=Output("/processed/stitched_images"),
    raw=Input("/raw/images"),
    image_meta=Input("/processed/image_meta")
)
def my_compute_function(raw, image_meta, output, ctx):

    image_meta = image_meta.dataframe()

    def stitch_images(clone):
        left = clone["left_file_name"]
        right = clone["right_file_name"]
        image_name = clone["image_name"]
        with raw.filesystem().open(left, mode="rb") as left_file:
            with raw.filesystem().open(right, mode="rb") as right_file:
                with output.filesystem().open(image_name, 'wb') as out_file:

                    left_image = Image.open(left_file)
                    right_image = Image.open(right_file)

                    (width, height) = left_image.size

                    result_width = width * 2
                    result_height = height
                    result = Image.new('RGB', (result_width, result_height))

                    result.paste(im=left_image, box=(0, 0))
                    result.paste(im=right_image, box=(height, 0))

                    result.save(out_file, format='jpeg', quality=90)

    image_meta.rdd.foreach(stitch_images)

The image_meta dataset is just a dataset that has 2 file names per row. To extract filenames from a dataset of raw files you can use something like:
@transform(
    output=Output("/processed/image_meta"),
    raw=Input("/raw/images"),
)
def my_compute_function(raw, output, ctx):

    file_names = [(file_status.path, 1) for file_status in raw.filesystem().ls(glob="*.jpg")]

    # create and write spark dataframe based on array

A: As others have mentioned Palantir-Foundry's focus is on tabular data and doesn't currently provide GPU or other tensor processing unit access. So doing anything intense like an FFT transform or Deep Learning would be ill advised at best if not downright impossible at worst.
That being said you can upload image files into dataset nodes for read/write access. You could also store their binary information as a blob type into a Dataframe in order to store files in a given record field. Given that there are a multitude of Python image processing adjacent and matrix math libraries available on the platform and given that it's also possible to upload library packages to the platform manually through the Code Repo app, it is conceivable that someone could make use of simple manipulations on a somewhat large scale as long as it wasn't overly complex or memory intensive.

A: Note that Foundry seems to have no GPU support at the moment, so if you are thinking about running deep learning based image processing, this will be quite slow on CPUs.


text:
Q: Convert object containing 2D object array into string array I have a method which returns the following type and object:
object {object[,]}
test    {object[19, 2]}

Is it possible to convert this into 2d string array, or a datatable?

A: Looks akward, but I haven't found another way.
int firstDimensionSize = 19;
int secondDimensionSize = 2;

object[,] objectArray = new object[firstDimensionSize, secondDimensionSize];

string[,] stringArray = new string[objectArray.Length / secondDimensionSize, secondDimensionSize];

for (int i = 0; i < objectArray.Length / secondDimensionSize; i++)
{
    for (int j = 0; j < secondDimensionSize; j++)
    {
        stringArray[i, j] = objectArray[i, j].ToString();
    }
}

In case your second dimension is always the same you could leave out the inner loop, replacing it with static code.
See also https://www.dotnetperls.com/2d

A: I made this extension method, but you can aswell make it a normal method if you don't need it that often.
public static class Extensions
{
    public static string[,] ConvertToString2D(this object[,] arr)
    {
        int dim1 = arr.GetLength(0);
        int dim2 = arr.GetLength(1);
        string[,] strArray = new string[dim1, dim2];

        for (int i = 0; i < dim1; i++)
        {
            for (int j = 0; j < dim2; j++)
            {
                strArray[i, j] = Convert.ToString(arr[i, j]);
            }
        }

        return strArray;
    }
}

and then you can call it like this:
var result = objArr.ConvertToString2D();


text:
Q: Fetching Data from Firestore Collections snapshot.hasdata returns Null So I have been following a tutorial from YouTube and when I was trying to fetch the "username" from the collection named "users" through Stream snapshot, it returns null.
Aim: Display the available users when search button with username is clicked.
Here is the code below:
  bool isSearching = false;
  Stream? usersStream;

  TextEditingController searchUsernameEditingController =
      TextEditingController();

  onSearchBtnClick() async {
    isSearching = true;
    setState(() {});
    usersStream = await DatabaseMethods()
        .getUserByUsername(searchUsernameEditingController.text);

    setState(() {});
  }

  Widget searchUserList() {
    return StreamBuilder(
        stream: usersStream,
        builder: (context, AsyncSnapshot snapshot) {
          return snapshot.hasData
              ? ListView.builder(
                  itemCount: snapshot.data.docs.length,
                  itemBuilder: (context, index) {
                    DocumentSnapshot ds = snapshot.data.docs[index];
                    return Image.network(ds["imgUrl"]);
                  })
              : Center(child: Text("No Users Found"));
        });
  }

From DatabaseMethods():
Future<Stream<QuerySnapshot>> getUserByUsername(String username) async {
    return FirebaseFirestore.instance
        .collection("users")
        .where("username", isEqualTo: username)
        .snapshots();
  }

Always shows "No Users Found" Message

A: First confirm that new value for streambuilder is released when onSearchBtnClick is called.
Try this.
onSearchBtnClick() async {
  isSearching = true;
  setState(() {});
}

Widget searchUserList() {
  return StreamBuilder(
    stream: DatabaseMethods()
        .getUserByUsername(searchUsernameEditingController.text),
    builder: (context, AsyncSnapshot snapshot) {
      print('called');
      // confirm that print is called when onSearchBtnClick is called.
      return snapshot.hasData
          ? ListView.builder(
              itemCount: snapshot.data.docs.length,
              itemBuilder: (context, index) {
                DocumentSnapshot ds = snapshot.data.docs[index];
                return Image.network(ds["imgUrl"]);
              })
          : Center(child: Text("No Users Found"));
    },
  );
}


text:
Q: Rendering of SVG as canvas pattern in Chrome Well that's about it, I use an SVG image to create a pattern. The pattern displays in most browsers. Chrome however doesn't display the pattern.
if I put a png image as the source of my new Image() object, Chrome displays it.
I was trying to find out if that was normal, but can't find anything about in on the web.
Am I doing something wrong or is that a known issue?

A: The only solution I have found for the same problem in Chrome is to include the patterns inside the svg in base64 encoding:
<pattern  id="pat01" xlink:href="data:image/png;base64,iVBOR...CC " style="opacity:1;stop-opacity:1" /></pattern>
...
<circle cx="23" cy="153" r="18" style="opacity:1;fill:url(#pat01);fill-opacity:1;stop-opacity:1;stroke:#000000;stroke-miterlimit: 10;"></circle>

When you serialize it and paint in a canvas, the patterns are displayed properly.


text:
Q: How to validate a value without updating the binding target? I want to allow the user to input only text that is validated by the TextBox binding validation rules. I figured out a way of doing that:
public static void PreviewTextChanged(
    object sender,
    PreviewTextChangedEventArgs e)
{
    var textBox = e.Source as TextBox;
    var bindingExpression = textBox.GetBindingExpression(TextBox.TextProperty);
    if (!ReferenceEquals(null, bindingExpression))
    {
        // save original parameters for possible restoration
        var originalSelectionStart = textBox.SelectionStart;
        var originalSelectionLength = textBox.SelectionLength;
        var originalText = textBox.Text;

        // check validation
        textBox.Text = e.Text;
        if (!bindingExpression.ValidateWithoutUpdate())
        {
            // restore original values
            textBox.Text = originalText;
            bindingExpression.UpdateSource();
            textBox.SelectionStart = originalSelectionStart;
            textBox.SelectionLength = originalSelectionLength;
        }
        else
        {
            // correct the selection
            var selectionStart = originalSelectionStart +
                originalSelectionLength +
                e.Text.Length -
                originalText.Length;
            textBox.SelectionStart = Math.Max(selectionStart, 0);
            textBox.SelectionLength = 0;
        }

        e.Handled = true;
    }
}

The code above works. But it would be much simpler, and less bug-prone, if I could find a way to check if the new value is valid without updating the binding target. Is there one?

A: I think it's easier in this case to relay on Binding Converters.
The converter will be called every time the data should be assigned to the binded field.
Inside methods of it, you can validate the input of the data and based on validation result return or old data (cause validation fails) recovered from ModelView or accept it, in case when validation succeeded.
Hope this helps.


text:
Q: Can principal component analysis be applied to datasets containing a mix of Ordinal and binary variables? I'm going to build a PCA for a set of binary variables and a ordinal variable. The binary variables values are 0 & 1 ordinal variable value is in a scale of 1 to 50
Is it possible to do PCA with this data set?


text:
Q: Jquery not passing any parameters data My Code is as below for Javascript
  $.ajax({
         type: "POST",
         url: "page/rSales.aspx",
         data: { ListID: '1', ItemName: 'test' },
         dataType: "json",
         success: function (res) {
             alert('Success');
         },
         error: function (res) {
            alert('Fail');
         }
     });

I use http tracer tools to trace whether or not the parameter is passing on to my backend - and it is not. I have also tried adding  contentType: 'application/json; charset=utf-8', adjust parameter by adding colon, but none of it is working.
My Backend code C# :
Request.Params["ListID"].ToString();

It always returns null, due to the parameter not passing on. I am wondering what is causing this problem and how should I resolve it.

A: The Request.Params collection does not support JSON requests, so you have to parse response body manually (or send it as form data).
https://msdn.microsoft.com/en-us/library/system.web.httprequest.params(v=vs.110).aspx says "Gets a combined collection of QueryString, Form, Cookies, and ServerVariables items."

A: For firefox you declare var event; before your ajax call this is very well known issue in firefox.


text:
Q: Recent LDAP user list missing in greeter using lightdm I am switching our desktop manager from xfce to mate on centos 7.4.
This means that we are switching from gdm to lightdm.
For some reasons, it is impossible for our recent user authenticated via a freeipa to appear in the recent user lists, which means that our users needs to enter all their login infos each time they log in.
I have looked long and hard, and it does not seem to be a setting issues. I have tried to activate and deactivate all the relevant settings regarding sessions, with no luck.
For what i have been able to glean, a file need to be created in /var/lib/AccountsService for our users to appear in that list, but is not. Yet, this folder is still being read at lightdm startup. It reads org.freedesktop.Accounts which seem to be used to create this list.
Under GDM, that file is correctly created when a ldap user logs out.
User locally created do not experience this issue, and are directly present both in the user list and in /var/lib/AccountsService.
If anyone could nudge me in the right direction. I am out of ideas.


text:
Q: How to more easily access a ContentItem's fields in a CSHTML view? I have written a helper function (I'm quite proud of this it - look what I can do!) that does what I need. Is there a built in way, though, to access a ContentItem's fields without having first to get the "main" ContentPart? The word "main" here means the ContentPart with the same name as the ContentType.
@functions
{
    dynamic GetMainPartFromContentItem(ContentItem item)
    {
        var contentType = item.TypeDefinition.Name;
        var parts = item.Parts as List<Orchard.ContentManagement.ContentPart>;
        dynamic mainPart = parts.First(p => p.PartDefinition.Name.Equals(contentType));
        return mainPart;
    }
}

dynamic mainPart = GetMainPartFromContentItem(contentItem);
var shortTitle = mainPart.ShortTitle.Value; // access an InputField's value

A: If you have a ContentType called Page with a field called Topic you can do:
dynamic item = Model.ContentItem;

string topic = item.Page.Topic.Value;

Basically when you add fields directly to the content item, they are being added to a part on your content item called whatever your content type is, in this case Page


text:
Q: Recover USB Bluetooth dongle PIN (Acer BT-600) I found and old Acer BT-600 USB BlueTooth Dongle and wanted to use it to pair my Ubuntu 14.04 LTS laptop with my Nexus 5.
On pairing I my Nexus asks about the BlueTooth Dongle PIN, but I have no idea about it...
Is there a way to recover it somehow?


text:
Q: I cant see reskins in new update in Team Fortress 2 I can't see the new reskins in the new update. it says that DirectX
 8.0 is the reason. But how to I update DirectX to 9.0?

A: Use the launch option -dxlevel90 to launch in DirectX 9 (in Steam, right click TF2 > properties > set launch options)
If that doesn't work, check your autoexec.cfg file in your cfg folder (Steam\SteamApps\Common\Team Fortress 2\tf\cfg) and see if there's a command forcing you into DirectX 8, such as mat_dxlevel


text:
Q: Java - Recursively schedule a timer task Is there a way to run a timer task only after the method completes. The method could take 10 seconds but the timer is set to run every 5 seconds.  I want it to run again only after the 10 seconds are up.
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            longRunningMethod();
            timer.schedule(task, 0, 5000);
        }
    };
    timer.schedule(task, 0, 10000);

A: You can use ScheduledExecutorService which has a scheduleWithFixedDelay() method which does exactly that.
"Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next."
So you could do
ExecutorService.newScheduledExecutor()
    .submit(this::longRunningMethod, 0, 1000, ChronoUnit.MILLIS);

A: Removing the timer.schedule(task, 0, 5000); call will give you behavior you desire.
Your call of timer.schedule(task, 0, 10000); schedules repeating tasks every ten seconds.

A: You need to schedule one-shot timer tasks and create new TimerTask instance every time.
class MyTimerTask extends TimerTask {
    private final Timer timer;
    private final long nextScheduleDelay;

    MyTimerTask(Timer timer, long nextScheduleDelay) {
        this.timer = timer;
        this.nextScheduleDelay = nextScheduleDelay;
    }

    @Override
    public void run() {
        longRunningMethod();
        timer.schedule(new MyTimerTask(timer, nextScheduleDelay), nextScheduleDelay);
    }
}

Timer timer = new Timer();
timer.schedule(new MyTimerTask(timer, 1000), 0);


text:
Q: MultiLine EditText in Android with the cursor starting on top I know it seems it's an already thousand times answered issue but I haven't found anything that works for me.
I have a MultiLine EditText on Android that adapts to the view size by "playing" with the weight (1) and the height (0dip). I am using gravity "top" but it starts in the middle.
I guess the problem it's related with the weight. Here's the code (the parent is a LinearLayout):
    <EditText
        android:id="@+id/txtContacto"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_gravity="top"
        android:inputType="textMultiLine"
        android:weight="1">
    </EditText>

A: <EditText
        android:id="@+id/txtContacto"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:gravity="top"
        android:inputType="textMultiLine"
        android:weight="1">
    </EditText>

try the above code.. where layout gravity sets the edittext and gravity sets the content of edittext.


text:
Q: In Avengers, how plausible is Hawkeye's archery proficiency? In the Avengers, (my specifics below are from the film) Hawkeye is a mortal man who is extremely proficient with a bow and arrow. He frequently in the film

 hits targets without looking, makes perfect shots after correctly calculating for wind, and is able to reload his arrows with extreme speed.

How far off is this from actual professional archers? Can expert archers do anything relative to what Hawkeye is capable of? Or is even the normal human in the Avengers himself superhuman at something?

A: About the only shot that really strains credulity is

 when he shoots an arrow onto a computer console and two connectors pop out of the arrow and plug themselves into the console.

That one was a stretch.
If we accept Iron Man's armor and all of SHIELD's gadgets, Hawkeye's self-stringing bow and magical dial-an-arrow quiver are easy to buy. my beef wasn't with the fantastic elements, but the ordinary ones.
Shooting back without looking is a cool trick, and could be done with enough practice. But it's really just a party trick like flipping a spoon into a glass; the only reason to do it is self-satisfaction, and it makes Hawkeye look like a badass.
I think a world class field archer could do about 90-95% of Hawkeye's shots, in terms of target size and distance; the trick is doing them while jumping off buildings or sliding on your butt. They generally kept his shots pretty much within the realm of possibility, or would have if the guy had more believable form.

A: I'm no archer, but someone who is has deeply analyzed Hawkeye's skills in the movies.
Take a look at this link Is Hawkeye from The Avengers the world's worst archer?... it is FAR to long and in-depth to repeat it here.

A: According to the Ultimate Hawkeye mini series Clint Barton had several genetic enhancements to give him borderline superhuman abilities.  The rods and cones in his eyes where manipulated to give him superhuman visual accuity as well as the muscles around his eyes alowing for above average orb distortion (literal hawekeye vision) The producers of the Avengers film drew heavily from this version for Jeremy Rener's portrayal of him.

A: According to wikipedia, current estimates of the upper range of the English Longbow are 180 - 250 meters. Since he's trained his whole life as a marksman, none of his shots go an absurd distance, because he'd very likely have a strong enough pull to send an arrow that far. He doesn't display any of the hilariously-deformed musculature that archers had, but I'm sure Hollywood wouldn't take such a person even if they could find one! Additionally, most of his shots, besides party tricks like shooting backwards, are all very plausible shots for someone who's almost certainly hit the 10,000 hours expertise mark.

A: Hawkeye would be considered an exceptional archer even in the eyes of the world's best where a hit at a range of 150+ meters would be considered excellent shooting.
Most bow hunters shoot at targets averaging 35 to 75 meters away. Target archers can shoot at ranges of 100 -200 meters. (But targets don't move.) Was Clint Barton superhuman in his ability? Most of his shots made against targets within the interiors of buildings or onboard the helicarrier, were not extraordinary or outside of the realm of possibility.

The farthest accurate shot in archery under FITA conditions was 200 m (656 ft 2 in) by Peter Terry (Australia) at the Kalamunda Governor Stirling Archery Club, Perth, Western Australia, Australia on 15 December 2005. He hit 2 ouf of 6 on a FITA 122cm target. He used a 'compound bow'. --Guinness Book of Records

Where Hawkeye was at his most awesome was during his shots above the city. Were these shots impossible? No. But after a 150-200 meters, shooting targets moving in excess of fifty miles per hour, he starts becoming superhuman in his ability.
But if we consider the Marvel comics' history of the character Hawkeye, he has been training since he was six years old at a circus. He would learn to shoot from the most difficult angles and from the most difficult conditions, including shooting from the back of a bicycle, riding on a horse, shooting at tiny targets, shooting at moving targets. He was trained by both Trickshot, who was arguably one of the only archers better than Hawkeye and the Swordsman, another martial artist whose skills were legendary on Marvel Earth #616.
If we consider Hawkeye is about 20-30 in the Avenger's movie, he has been shooting daily for fifteen to twenty years. He practices everyday with weighted arrows (to familiarize himself with his arrow payloads) uses the finest bow technology money can buy, arrows balanced and made with the highest quality precision crafting.
Then consider he is a super-assassin who was likely given even MORE training, more discipline, military tactics, strategy and we can assume a highly trained individual who has used his weapon of choice on a battlefield against men with GUNS. His sense of the battlefield was excellent and was able to assist Iron Man by sharing the information about the limitations of the Chitauri vehicles.
In addition to all of his other skills he is a trained observer, so it would not be unreasonable to assume a certain level of what would appear to be superhuman proficiency. Although when he was making shots and not looking, I would just call that showing off.

A: I think Avenging Spider-man #4 addresses this really well - it's dramatic and a little tragic.
Enjoy these scans (© Marvel 2012):

*

*1

*2

*3

*4

A: The form thing isn't so important. Form is almost entirely about minimizing the effect of involuntary movements. Maybe that's his big gift: complete bodily control.
Aim is probably the easiest part of Archery, it doesn't take long to figure out where the arrow needs to appear in your field of vision relative to where you want it to land.
The RL shots referenced above were done with sights. Hawkeye didn't use one. So you might argue about his vision - but then - ever see that episode of Superhumans with the archer who could split an aspirin in free fall or shoot through a moving finger-ring. Apparently he had 50/20 vision and he was old.
The hardest part to buy is the 250lb draw-weight of his bow. While it is a lot of weight (about 5x normal for the type of bow he's using) it's still not outside the realm of possibility for someone at "peak human physical condition" to be able to pull that much. The biggest challenge with huge draw weight is keeping your arm steady - but that's another problem that has to do with involuntary movement. Aside from that the huge draw weight does make his shots a lot more plausible. A faster arrow is less likely to be thrown of course by winds etc. It also would make shooting moving targets easier - especially at a distance: The target would be much closer to where it was initially by the time the arrow were to arrive.
So if you were to take involuntary movement out of the picture, I don't see any reason he couldn't make the shots that he does.


text:
Q: Update a model value and update DOM from button in ng-repeat I have a button for each website state which shows state of each website on server (stopped or started).
The buttons are basically being treated as switcher so i can update value of state variable for each element of model.

{{website.Name}}

controller :
$scope.changeStatus = function (x) {
    alert(x.Name);
    //$scope[x].State == 'Stopped'

    //if ($scope.State== 'Started')
    //    $scope.State = "Stopped";
    //else
    //    $scope.State = "Started";
}

Requirement :
I need to update value if it is stopped than change it to start and vice versa.
So farth I could not find any solution. The alert Statement works fine. But I need to update model and the model should be bind to the element in html. So that when I change the button from "start" to "stop", model value should also be changed and hence button should go from start to stop on the basis of ng-if

A: *

*ng-model for  will not work

*there opened but not closed  element in your example

*argument you pass to changeStatus function is an object. So it is passing by reference.

angular.module('models', []).controller('websites',
  function($scope) {
    $scope.websites = [{
      Name: 'foo',
      State: 'Started'
    }, {
      Name: 'bar',
      State: 'Stoped'
    }];

    $scope.changeState = (website) => {
       if (website.State == 'Started') {
         website.State = 'Stoped';
       } else {
          website.State = 'Started';
       }
    };
  });

{{ website.Name }}

    <button ng-click="changeState(website)">
      {{ website.State }}
    </button>

    <button ng-if="website.State == 'Stoped'" ng-click="changeState(website)">
      Stoped
    </button>

    <button ng-if="website.State == 'Started'" ng-click="changeState(website)">
      Started
    </button>