text:
Q: I'm trying to make app cloner which can make multiple clones of app I want to know...
What should I do for making clones of app and how to launch clone apps from our app
There is many apps available in play store which I want to make
like,Clone app, multi parallel, multiple app, app cloner etc.
What should I use?
Package, dependency, other resources??


text:
Q: Dynamics NAV 2016 Web Service: Parameter * in method * in service * is null I try to get a single contact from my Dynamics Nav Web Service (Dynamics Nav 2016). I do this with a SOAP-request in PHP.
The web service is a codeunit which contains two functions:
fGetContact(iContactNumber : Text[20]) oContact : Text[250]
IF rContact.GET(iContactNumber) THEN BEGIN
  oContact := '';
  oContact := rContact."No." + ';' +
              rContact."Company Name" + ';' +
              rContact."First Name" + ';' +
              rContact.Surname + ';' +
              rContact."E-Mail";
END;
EXIT(oContact);

fGetContacts() oContacts : Text[250]
IF rContact.GET('KT100190') THEN BEGIN
  oContacts := '';
  oContacts := rContact."No." + ';' +
               rContact."Company Name" + ';' +
               rContact."First Name" + ';' +
               rContact.Surname + ';' +
               rContact."E-Mail";
END;
EXIT(oContacts);

The second function, fGetContacts, works fine.
But when I call fGetContact with a contact number as parameter, it returns the following error:
Parameter iContactNumber in method FGetContact in service MyService is null!

I use the NTLMSoapClient like the following:
<?php
ini_set('soap.wsdl_cache_enabled', '0');

require_once 'ntlmstream.php';
require_once 'ntlmsoapclient.php';

$url = 'http://localhost:7047/DynamicsNAV90/WS/CRONUS/Codeunit/MyService';

$options = array(
    'uri' => $url,
    'location' => $url,
    'trace' => true,
    'login' => 'my_user',
    'password' => 'my_password'
);

// we unregister the current HTTP wrapper
stream_wrapper_unregister('http');

// we register the new HTTP wrapper
stream_wrapper_register('http', 'MyServiceProviderNTLMStream') or die("Failed to register protocol");

// so now all request to a http page will be done by MyServiceProviderNTLMStream.
// ok now, let's request the wsdl file
// if everything works fine, you should see the content of the wsdl file
$client = new MyServiceNTLMSoapClient(null, $options);

// should display your reply
try {
    $params = array('iContactNumber' => 'KT100190');

    echo '
';
    echo $client->FGetContacts(); // works
    echo $client->FGetContact($params); // doesn't work
    echo '
';
} catch (SoapFault $e) {
    echo '
';
    var_dump($e);
    echo '
';
}

// restore the original http protocole
stream_wrapper_restore('http');

I also tried to call the function like this:
echo $client->FGetContact('KT100190');

The return error is the same as before.
I tested my function with SoapUI and the return value is exactly what it shuold be.
Request:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:new="urn:microsoft-dynamics-schemas/codeunit/MyService">
   <soapenv:Header/>
   <soapenv:Body>
      <new:FGetContact>
         <new:iContactNumber>KT100190</new:iContactNumber>
      </new:FGetContact>
   </soapenv:Body>
</soapenv:Envelope>

Response:
<Soap:Envelope xmlns:Soap="http://schemas.xmlsoap.org/soap/envelope/">
   <Soap:Body>
      <FGetContact_Result xmlns="urn:microsoft-dynamics-schemas/codeunit/MyService">
         <return_value>KT100190;Add-ON Marketing;Chris;McGurk;chris.mcgurk@cronuscorp.net</return_value>
      </FGetContact_Result>
   </Soap:Body>
</Soap:Envelope>

So what am I doing wrong that this error appears and how can I fix it?

A: For what it's worth, I had this issue and solved it by adding "cache_wsdl" => WSDL_CACHE_NONE to the soap client's options.
Some fields were missing because of a cache issue after updating the WSDL.

A: I made a workaround and it works for me now.
I changed the $request variable in the class NTLMSoapClient, because the soap envelope that php sent to my service was absolutely useless.
So basically I just did this before the curl actions:
$request = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:new="urn:microsoft-dynamics-schemas/codeunit/MyService">
               <soapenv:Header/>
               <soapenv:Body>
                  <new:FGetContact>
                     <new:iContactNumber>'.$this->iContactNumber.'</new:iContactNumber>
                  </new:FGetContact>
               </soapenv:Body>
            </soapenv:Envelope>';

(If someone have the same problem, try var_dump($request) and view source in browser. You will see what a mess PHP did there...)

redpajama_set_name: RedPajamaStackExchange


text:
Q: bug with wrapping angle by using wrapToPi() I found a bug in my code which affects the subsequent calculations. I have two state vectors, one for the actual robot's movement and the second one for the estimated state vector. For the robot
robot = [101.3203; % x
         170.6334; % y
          2.1103]; % theta in radian

From this position, the robot makes an observation to a beacon located at <200,0> (i.e. <x,y>). Now, the range and angle between the robot and beacon is computed as following
sigma_phi = (degtorad(1))/2; % noise of the angle
  sigma_r = (0.001)/2;       % noise of the range

% range with some noise from robot to beacon
qr     = sqrt((200 - robot(1))^2   + (0 - robot(2))^2) + sigma_r*randn();
% angle with some noise in radian from the robot to beacon
phi = wrapToPi(atan2(0 - robot(2), 200 - robot(1)) - robot(3) + sigma_phi*randn());

the angle is now phi = 3.1285 in radian. For the estimated state vector, I have
Mu = [101.2143; % x
      171.0308; % y
        2.094]; % theta in radian

From this estimated position, the estimated state vector makes an observation to a beacon at <200,0> (i.e. <x,y>). Now, the range and angle between the estimated state vector and beacon is computed with no noise as following
    q = sqrt((200 - Mu(1))^2 + (0 - Mu(2))^2);
theta = wrapToPi(atan2(0 - Mu(2), 200 - Mu(1)) - Mu(3));

the angle is now theta = -3.1410 in radian. My question is why phi is in the opposite direction of theta even though the robot and the estimated state vector have close values??

A: You say theta = -3.1410, measured in radians. That's very close to -pi radians. Add a little noise to your estimation, and you can easily obtain an angle that is slightly less
than (more negative than) -pi radians.
If you give wrapToPi an angle slightly less than -pi radians, it will return an angle
that is slightly less than pi radians instead.
That is, as far as wrapToPi is concerned, there is not much difference between
your angles phi and theta.  If you compute wrapToPi(phi - theta), which is what
you should do if you really want to know how different two directional angles are,
the result will be a relatively small number (something less than 0.02, I think).


text:
Q: I want to add functionality in Quicksearch box to search using any data column not just name I want to quicksearch using any column name(like description, Status) current search is being performed using Name only
class ApplicationList(APIView):
    permission_classes = (IsAuthenticated,)
# parser_classes = (JSONParser,)

def post(self, request, format=None):
    # Get a list of fields dynamically
    fields = list()
    for f in Application._meta.fields:
        if f.is_relation:
            continue
        fields.append(f.name)

    queryset = Application.objects_with_sprint_name.all()

    # Looking for a specific bubble?
    if 'bubble' in request.data:
        if request.data['bubble'] == '4-1':
            queryset = queryset.filter(assessment_phase__id=request.data['bubble']).exclude(attributes__contains={'application_disposition':'Removed'})
        else:
            queryset = queryset.filter(assessment_phase__id=request.data['bubble'])

    # Providing a search query?
    if 'search' in request.data:
        q_search = request.data['search']

        # Build the query
        q = get_query(q_search, fields)
        queryset = queryset.filter(q)

    if 'filter' in request.data:
        q = get_filter(request.data['filter'])
        if q:
            queryset = queryset.filter(q)

    page = int(request.data.get('page', 1))
    per_page = int(request.data.get('per_page', 25))

    # Sorting
    sort_by = request.data.get('sort_by', 'name') or 'name'
    sort_dir = request.data.get('sort_dir', 'asc') or 'asc'

    if sort_dir == 'desc':
        sort_dir = '-'
    else:
        sort_dir = ''

    # Is this an actual field or do we need to sort by the attributes__*?
    if sort_by not in fields:
        sort_by = 'attributes__' + sort_by

    queryset = queryset.order_by('{0}{1}'.format(sort_dir, sort_by))

    # Do a little data massaging
    untreated_data = queryset.values()

    data = list()
    for app in untreated_data:
        this_app = {}
        for k, v in app.items():
            if k == 'attributes':
                continue
            if k == 'sprint_name':
                this_app[k] = v
                this_app['sprint'] = v
                continue

            this_app[k] = v
        this_app.update(app['attributes'])

        data.append(this_app)

    start = (page-1) * per_page
    end = (page) * per_page

    response = {
        'total_rows': len(data),
        'data': data[start:end],
    }
    return Response(response)

def get_query(query_string, search_fields):
    ''' Returns a query, that is a combination of Q objects. That combination
        aims to search keywords within a model by testing the given search fields.
'''
query = None  # Query to search for every search term
terms = normalize_query(query_string)
for term in terms:
    or_query = None  # Query to search for a given term in each field
    for field_name in search_fields:
        q = Q(**{"%s__icontains" % field_name: term})
        if or_query is None:
            or_query = q
        else:
            or_query = or_query | q
    if query is None:
        query = or_query
    else:
        query = query & or_query
return query

def get_filter(filter_dict):
    available_fields = [ field.name for field in Application._meta.fields ] \
                       + ApplicationManager.annotated_fields
query = None
if filter_dict is None:
    return query

for field_name, val in filter_dict.items():
    query_field = field_name

    # Quicksearch box
    if field_name == '_quicksearch_':
        q = Q(name__icontains=val)

        if query is None:
            query = q
        else:
            query = query & q

        continue

    # Figure out if this field is part of the model
    # or in the attributes json field
    if query_field not in available_fields:
        query_field = 'attributes__{0}'.format(query_field)

    if isinstance(val, list):
        q = None
    #
    #     # Are we looking for null or blank?
        if '#is_null_or_blank#' in val:
            val.remove('#is_null_or_blank#')
            q = Q(**{"%s__isnull" % query_field: True}) | \
                Q(**{query_field: ''}) | \
                Q(**{query_field: []})
    #
    #     # Loop through the list and create some "OR" expressions
        for v in val:
            tmp = Q(**{"%s__contains" % query_field: v})
            if q is None:
                q = tmp
            q = q | tmp

    elif val.startswith('#bool#'):
        bval = val[6:].lower() == 'true'
        q = Q(**{"%s" % query_field: bval})
    else:
        q = Q(**{"%s__icontains" % query_field: val})

    # # Add to our master query of all fields
    if query is None:
        query = q
    else:
        query = query & q

return query

A: # Quicksearch box
    if field_name == 'quicksearch':
        q = Q(name__icontains=val) | Q(attributes__icontains=val), I got the field wrong which I corrected and for foreign key relationship django foreignkey contains query helped


text:
Q: Netlify Deployment stuck and will not deploy I have no clue what it wrong... someone please check it out! Here is the last few lines of the deployment log:
5:10:16 PM: ────────────────────────────────────────────────────────────────
5:10:16 PM:   1. Build command from Netlify app
5:10:16 PM: ────────────────────────────────────────────────────────────────
5:10:16 PM:
5:10:16 PM: $ npm start --force
5:10:17 PM: npm WARN using --force Recommended protections disabled.
5:10:17 PM: > frontend_base_dapp@0.1.0 start
5:10:17 PM: > react-scripts start
5:10:19 PM: ℹ 「wds」: Project is running at http://10.4.210.17/
5:10:19 PM: ℹ 「wds」: webpack output is served from
5:10:19 PM: ℹ 「wds」: Content not from webpack is served from /opt/build/repo/public
5:10:19 PM: ℹ 「wds」: 404s will fallback to /
5:10:19 PM: Starting the development server...
5:10:19 PM:
5:10:40 PM: Compiled with warnings.
5:10:40 PM:
5:10:40 PM: src/App.js
5:10:40 PM:   Line 2:8:  'logo' is defined but never used  no-unused-vars
5:10:40 PM: src/Mint.js
5:10:40 PM:   Line 1:38:    'useRef' is defined but never used                                                                                no-unused-vars
5:10:40 PM:   Line 97:6:    React Hook useEffect has a missing dependency: 'getData'. Either include it or remove the dependency array                                                                             react-hooks/exhaustive-deps
5:10:40 PM:   Line 128:39:  Expected '===' and instead saw '=='                                                                                eqeqeq
5:10:40 PM:   Line 136:19:  Using target="_blank" without rel="noreferrer" (which implies rel="noopener") is a security risk in older browsers: see https://mathiasbynens.github.io/rel-noopener/#recommendations  react/jsx-no-target-blank
5:10:40 PM: src/redux/blockchain/blockchainActions.js
5:10:40 PM:   Line 47:23:  Expected '===' and instead saw '=='  eqeqeq
5:10:40 PM: Search for the keywords to learn more about each warning.
5:10:40 PM: To ignore, add // eslint-disable-next-line to the line before.
5:38:33 PM: Build exceeded maximum allowed runtime
5:38:36 PM: Failed to compile.
5:38:36 PM:
5:38:36 PM: ./src/index.js
5:38:36 PM: Error: ENOENT: no such file or directory, open '/opt/build/repo/src/index.js'

Any help will be greatly appreciated.My deployment in netlify just gets stuck and says "
Deploy in progress"
Also, I can start a local server with yarn start and it works fine. This only occurs when deploying to netlify. (using react)

A: Build of your application stucks because you have errors in your code, in the log above there are printed specific lines on  which you have errors, along with description where the issues comes from. Try to fix them, then if your deployment is still stuck kill the pipeline and then deploy the new fixed version. Should work then.


text:
Q: Automatically replicate table data into another table Is there a way to automatically replicate the table into another table where in if table A has changes, then it will also change the data in the 2nd table.

A: You  can use triggers or replication,but replication will be a overkill for a single table..See below example for more details
Changes in Table A,should replicate to table B
CREATE TABLE [dbo].[a](
    [id] [int] NULL,
    [name] [char](2) NULL
)

CREATE TABLE [dbo].[b](
    [id] [int] NULL,
    [name] [char](2) NULL
)

Now create trigger which replicates only data changes
ALTER trigger [dbo].[trg_test]
on [dbo].[a]
for insert,update,delete
as

begin

set nocount on

--updated
if exists(select 1 from inserted) and exists(select 1 from deleted)
begin

update b
set b.id=i.id,
    b.name=i.name
    from b
    join
    inserted i
    on b.id<>i.id and b.name<>i.name
    join deleted d
    on b.id=d.id and b.name=d.name
return

end

--inserted
if exists(select 1 from inserted)
begin

insert into b
select * from inserted
end

--deleted
if exists(select 1 from deleted)
begin

delete b
from
deleted d
join
b
on b.id=d.id

end

end

now do some random datachanges
--inserts

    insert into a
    select 1,'d'
    union all
    select 3,'c'

--updates
update
a
set id=4

--deletes
delete from a

you can check at each stage to see data replication to b


text:
Q: Resizing an image on the fly using CodeIgniter I am working on a script that downloads a file from Dropbox, supposed to resize that image and then shoot it up to an S3 bucket.
For some reason, I can't get the image to resize.
I keep getting the following error:
The path to the image is not correct.
Your server does not support the GD function required to process this type of image.
Code Base:
public function resize_test() {
            $postcard_assets = $this->conn->getPostcardDirContent("folder_name", "Photos", TRUE);

            foreach($postcard_assets['contents'] as $asset) {
                $file = pathinfo($asset['path']);
                $original_file = $this->conn->downloadFile($asset['path']);

                $raw_file = sha1($file['basename']);
                $s3_file_name = "1_{$raw_file}.{$file['extension']}";
                $this->resize_photo($original_file);
                $this->s3->putObject($s3_file_name, $original_file, 's3-bucket-name', 'public-read');

                $s3_check = $this->s3->getObjectInfo($s3_file_name, 's3-bucket-name');

                if($s3_check['content-length'] > 0) {
                    krumo($s3_check);
                    exit();
                }
            }
        }

private function resize_photo($photo) {
            $config['image_library'] = 'imagemagick';
            $config['source_image'] = $photo;
            $config['maintain_ratio'] = TRUE;
            $config['width']     = 640;
            $config['height']   = 480;

            $this->load->library('image_lib', $config);

            if(!$this->image_lib->resize()) {
                exit($this->image_lib->display_errors());
            }
        }

Dropbox API DownloadFile:
    public function downloadFile($file) {
        $this->setTokens();
        return $this->conn->getFile($file);
    }

Anyone know what I might be doing wrong?

A: I'm doing image resizing with CI using ImageMagick just like you are. You need the following to get this to work:

*

*imagemagick should be installed. You can test it from the command line using the 'convert' command

*imagick needs to be installed, this is the PHP library that binds to imagemagick

*ImageMagick itself depends on various other libraries such as libjpeg and libpng. Make sure those are installed as well

Simpy do a phpinfo() and scroll down to 'imagick'. Check whether it is there and then check the 'supported file formats' heading to see if the file type you are wanting to resize is there.
If all of the above are correct and it still does not work, you should not forget to include the path to imagemagick in your code:
$config['library_path'] = '/usr/local/bin';

I went through all this pain before so I hope this helps you :)

A: For Multiple resize below code worked for me.
    $config['create_thumb'] = FALSE; //to avoid _thumb prefixing
    $config['maintain_ratio'] = TRUE;
    $config['width'] = 250;
    $config['height'] = 250;
    $config['new_image'] = 'thumb_250x250_'.$file_name; // new name
    $CI->load->library('image_lib', $config, 'abc'); //abc to avoid instance caching.
    $CI->abc->resize();
    unset($CI->abc); //unsetting instance.
    $config['width'] = 100;
    $config['height'] = 100;
    $config['new_image'] = 'thumb_100x100_'.$file_name; // new name
    $CI->load->library('image_lib', $config, 'xyz'); // xyz to avoid instance caching.
    $CI->xyz->resize();
    unset($CI->xyz); // unsetting instance.

A: Dont load image_lib multiple times. Add image_lib in autoload libs and change
$this->load->library('image_lib', $config);

to
$this->image_lib->initialize($config);

A: You need to use $config['new_image'] = '/path/to/new_image.jpg'; in your resize_photo function.
Read http://codeigniter.com/user_guide/libraries/image_lib.html

A: Actually you are trying to load the image library twice. Since you also initialize the config array on the very same line, the array never gets loaded into the library.
Change your code to this:
    //this
    $this->load->library('image_lib', $config);

    //to this
    $this->load->library('image_lib');
    $this->image_lib->initialize($config);

and it will work perfectly.

A: See if you can actually open the original saved image before you try to resize it. I was decoding a base64 uploaded image while using a preg_replace. For some reason, which I still can't track down... it was removing like so
$file = preg_replace('/data.*base64,/', '', chunk_split($this->post('myimg'));

it would return this: [removed]/9....etc. which when base64 decoded... obviously isnt a valid image file.. so the resize wouldnt work. I had to add a
$file = substr($file,9);

to then remove the [removed]. extra work and took me while to figure out, but now I can resize images.
Side Question... Why is preg_replace adding [removed]??? Sigh... php.

A: //Make controller named "image.php"

class Image extends CI_Controller {

 public function index($width, $height, $image_path)
    {
        $config['image_library'] = 'gd2';
        $config['source_image'] = './uploads/'.$image_path;
        $config['dynamic_output'] = TRUE;
        $config['maintain_ratio'] = TRUE;
        $config['width'] = $width;
        $config['height'] = $height;

        $this->load->library('image_lib', $config);
        $this->image_lib->initialize($config);
        echo $this->image_lib->resize();
    }
}

?>
//Call from view page
<img src="<?php echo ("index.php/image/index/150/150/".$luserdata[0]'profile_image']);?>"      alt="resized mage1"/>


text:
Q: How to have an app centered on and/or fill the screen? I am new to Xcode and I have a very simple layout with a square ImageView with two buttons below it. I wrap these in a UIView called Box (as a subview target for viewForZoomingInScrollView), which is wrapped in a ScrollView.
I tried building it in two different ways with the SingleView template. In the first way I changed the ViewController's view to a ScrollView, like this.

Second, I also tried it with the Scrollview inside the ViewController's view like this.

Everything works fine or as expected, in both cases, except: In both cases, the entire ViewController, stays pinned to the top left corner of the screen, regardless of orientation or zoom level.
* Omg, I solved all my resource management and action issues in one day and now I have spent nearly a week fighting with Layout *
When I have no constraints, like this:

The App opens like this. View is Black, ScrollView is purple, Box is DKGray, and ImageView is LTGray

When I pinch it, the image stays (after bouncing) pinned to the top left.

If I add centering constraints to ScrollView and Box,

ScrollView's constraints are respected but Box's are not. (Actually when the app opens Box fills ScrollView, it is only after pinching that Box goes up into the top left. Can scrolling destroy the constraints...? Do I have to put constraints in scrollViewDidEndZooming?)

Here are my current sub-questions. When Layout doesn't have enough constraints, it must add them. Does the constraints it adds have priority over mine? Is there a way to see what constraints it adds? I get these warnings with the constraints above.

Over Arching Question: How do I get it to be in the center of the iOS screen, or to fill the screen? I imagine there is an Interface Builder solution and a code solution, either or both would be of interest.
Thanks for reading.

A: Changing the element alignment
Each element needs to have constraints to outline where it should display in it's parent. i.e. right now you have an image, inside a view, inside a scroll view. So each of those three elements needs to have constraints set.
For each element:

*

*Click the element

*Click the 'Add new alignment contraints' button at the bottom right

*Check the 'Horizontally in container' and 'Vertically in container' checkbox and then click the 'Add 2 constraints' button

Run your app and you should now see that the image is centre aligned, both horizontally and vertically.
Changing the element size dynamically
This is also easy to do through the storyboards. This video shows you how to do it: https://www.youtube.com/watch?v=aSsR1NlQvMA
The only extra thing is that you'll need to do this with each element, as per above.

A: Try to select your scrollView and in Pin menu of autoLyout try to add these constraints.


text:
Q: How to save and fetch a data from the Couchbase database and display it on ListView? I'm a in the process of understanding CouchBase Lite for android application,as far i only know how to create a manager, database, document and view.However i want to load data from the documents and show it in the app but failed after trying several times and following some tutorials.Is there a way i can save and load this data and manipulate it in Listview? The code i used til now is the following:
public class MainActivity extends AppCompatActivity {

final String dbname = "userdils";
private String docId = "2";
private Manager manager;
private Database couchDb;

private TextView tvLogWindow;
private EditText u_id;
private EditText pwd;
Button btn_login,btn_login1;
TextView version;
private String TAG = "CouchBaseLiteLoginPage";
String email;
String password;
private UserDetails ud,udd;
private ArrayList<UserDetails> ud1;
String doc_id;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //tvLogWindow = (TextView) findViewById(R.id.tv_log_window);
    u_id = (EditText) findViewById(R.id.user_id);
    pwd = (EditText) findViewById(R.id.password);
    btn_login = (Button) findViewById(R.id.btn_login);
    btn_login1 = (Button) findViewById(R.id.btn_login1);

    /*tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nStart Couchbase App!");
    if (!Manager.isValidDatabaseName(dbname)) {
        tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nBad couchbase db name!");
        return;
    }*/

    createManager();
    createCouchdb();

    btn_login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            Log.d(TAG, "Create: " + 1);
            login();

        }
    });

    btn_login1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v)
        {
            Log.d(TAG, "View: " + 2);
            docView();
           // retrieveMovie(manager,couchDb,docId);

        }
    });

    //createDocument(docId);

    //Document retrievedDocument = retrieveDocument();
    /*updateDocument(retrievedDocument);
    deleteDocument(retrievedDocument);*/

    //tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nEnd the App!");
}

public void createManager() {
    try {
        manager = new Manager(new AndroidContext(getApplicationContext()), Manager.DEFAULT_OPTIONS);

    } catch (IOException e) {

        return;
    }
}

public void createCouchdb() {
    try {
        couchDb = manager.getDatabase(dbname);

    } catch (CouchbaseLiteException e) {

        return;
    }
}

public Document retrieveDocument(String docId) {
        Document retrievedDocument = couchDb.getDocument(docId);
    Log.d(TAG, "Retrieved Data:- " + String.valueOf(retrievedDocument.getProperties()));
    // Let's find the documents that have conflicts so we can resolve them:
        Query query = couchDb.createAllDocumentsQuery();
        query.setAllDocsMode(Query.AllDocsMode.ALL_DOCS);
    try {
        QueryEnumerator result = query.run();
        for (Iterator<QueryRow> it = result;
             it.hasNext(); ) {
            QueryRow row = it.next();
            Object movieObj = row.getDocument().getProperties().get("user_det");
            Gson gson = new Gson();
            String jsonString = gson.toJson(movieObj, Map.class); //Convert the object to json string using Gson
            UserDetails movie = gson.fromJson(jsonString, UserDetails.class); //convert the json string to Movie object
            if(movie.getUser_pwd().equals("000000")) {
                Log.i("getMovieFromDocument", "movie>>>" + movie.getUser_nm());
            }

            Log.d(TAG, "Document Data ID:- " + row.getDocumentId());

        }
    }
    catch (CouchbaseLiteException e) {

    }

       // Log.d(TAG, "User Name:- " +(String)retrievedDocument.getProperty("user_det"));
        return retrievedDocument;
}

public void login() {

    Log.d(TAG, "validate: " + 4);
    email = u_id.getText().toString().trim();
    password = pwd.getText().toString().trim();

    Log.d(TAG, "login: " + 5);

    btn_login.setEnabled(false);

    ud = new UserDetails();
    udd = new UserDetails();

    ud1 = new ArrayList<UserDetails>();

    ud.setUser_nm(email);
    ud.setUser_pwd(password);

    udd.setUser_nm("NAME_007");
    udd.setUser_pwd("PWD_007");

    ud1.add(ud);
    ud1.add(udd);

    createDocument(docId,ud1);

}

public void createDocument(String docId,ArrayList<UserDetails> ud) {
    // create some dummy data
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Calendar calendar = GregorianCalendar.getInstance();
    String currentTimeString = dateFormatter.format(calendar.getTime());
    //Movie movie = new Movie("Star War", "The force awakens!", 120);

    // put those dummy data together
    Map<String, Object> docContent = new HashMap<String, Object>();
    docContent.put("message", "Hey Couchbase Lite");
    docContent.put("creationDate", currentTimeString);
    docContent.put("user_det", ud);
    //docContent.put("movie", movie);

    Log.d(TAG, "userDetails: " + String.valueOf(docContent));

      // create an empty document, add content and write it to the couchDb
      //Document document = new Document(couchDb,docId);
      //Document document = couchDb.createDocument();
    Document document = new Document(couchDb,docId);

    try {
        document.putProperties(docContent);
        //doc_id = document.getId();
       // Document retrieveDoc = retrieveDocument(docId);

        Log.d(TAG, "Document Count couchDb : " + couchDb.getDocumentCount());

    } catch (CouchbaseLiteException e) {

    }
}

public void docView() {

   // Document retrievedDocument = retrieveDocument(docId);
    Document retrievedDocument = retrieveDocument(docId);

}

private void retrieveMovie(Manager manager, Database couchDb, String docId) {
    Document retrievedDocument = couchDb.getDocument(docId); // Retrieve the document by id
    Object movieObj = retrievedDocument.getProperties().get("user_det");
    Gson gson = new Gson();
    String jsonString = gson.toJson(movieObj, Map.class); //Convert the object to json string using Gson
    UserDetails movie = gson.fromJson(jsonString, UserDetails.class); //convert the json string to Movie object
    Log.i("getMovieFromDocument", "jsonString>>>" + jsonString);
    Log.i("getMovieFromDocument", "movie>>>" + movie.getUser_nm());
    }

}

A: Not clear what tutorials you followed and what errors you observed. Anyways, check out this blog that discusses how you can load documents within a RecyclerView with Couchbase Lite as a data source.  The recommended pattern can be easily applied to ListView or just use a RecyclerView instead of a ListView in your app.


text:
Q: Pandoc: does not include input files I have a LaTeX root file that refers to many other single files. Those files are included/referenced by
\input{somefolder/somefile}

But somehow Pandoc is generating the output just from the main tex file (the entry point) and does not follow the inputs. What am I doing wrong?

pandoc main.tex -t docx -o main.docx

Remark: I'm trying to import the LaTeX to Adobe Indesign by converting it to Docx first and then to Indesign.
Update: I created a minimum working example. Seems that the input file are correctly referenced but still I get tons of other errors that seem to be related to the corporate layout that uses Tkiz drawings. The Pandoc version is 1.19.2.1 on MacOS 10.12.4 (Sierra). The Pandoc command is:

pandoc booklet2016.tex -t docx -o booklet2016.docx

A: Pandoc does include input files

If you have a structure like this
.
├── main.tex
└── somefolder
    └── somefile.tex

with the following two files
1: main.tex
% !TeX program = XeLaTeX

\documentclass{article}
\begin{document}

\section*{Test}

    Input somefolder/somefile.tex:
    \input{somefolder/somefile}

\end{document}

and
2: somefile.tex
This is somefile

then
pandoc main.tex -t docx -o main.docx

will give you a word document, which contains the contents of somefolder/somefile.tex
3: main.docx

Bottom line: It works. If the structure of your project and/or code is more complicated then you should do some preprocessing first.

Update: Your MWE produces a docx file

As you can see, it contains the content from the included files. The trouble is that pandoc can't parse the elaborate macros (\newcommand) you are using, so there is a lot of noise and not a lot of signal.

A: I answered this question before here:
I know that this is an old question, but I have not seen any answers to this effect: Essentially, if you are using markdown and pandoc to convert your file to pdf, in your yaml data at the top of the page, you can include something like this:
---
header-includes:
- \usepackage{pdfpages}
output: pdf_document
---

\includepdf{/path/to/pdf/document.pdf}

# Section

Blah blah

## Section

Blah blah

Since pandoc using latex to convert all of your documents, the header-includes section calls the pdfpages package. Then when you include \includepdf{/path/to/pdf/document.pdf} it will insert whatever is include in that document. Furthermore, you can include multiple pdf files this way.
As a fun bonus, and this is only because I often use markdown, if you would like to include files other than markdown, for instance latex files. I have modified this answer somewhat. Say that you have a markdown file markdown1.md:
---
title: Something meaning full
author: Talking head
---

And two addtional latex file document1, that looks like this:
\section{Section}

Profundity.

\subsection{Section}

Razor's edge.

And another, document2.tex, that looks like this:
\section{Section

Glah

\subsection{Section}

Balh Balh

Assuming that you want to include document1.tex and document2.tex into markdown1.md, you would just do this to markdown1.md
title: Something meaning full
author: Talking head
---

\input{/path/to/document1}
\input{/path/to/document2}

Run pandoc over it, e.g.
in terminal pandoc markdown1.md -o markdown1.pdf

A: I had the same problem and the solution might be of interest to others. The working directory of my console / terminals was not identical to the base directory of the LaTeX project. I thought that was not a problem because I had worked with absolute paths. In fact, processing LaTeX files works fine as soon as the working directory matches the basic directory of the LaTeX project.


text:
Q: How to get two functions to activate at the same time + Timer questions I'm trying to code an attack for a text based adventure game, where the player can do damage with a sword. A random number is shown in the console and the player must type in that number as fast as possible. The faster they do it, the more damage they deal. So far I have this:
import random
import time
from threading import Timer

def damage(timeAmount, baseDamage):
    damageTotal = baseDamage - timeAmount

def sword():
    t = 0
    timerAmount = 0
    randomNumber = random.randint(0, 1000000)
    print('Type the following as fast as you can: \n' + str(randomNumber))
    swordAttack = input('> ')
    while t == 0:
        timerAmount = timerAmount + 1
        time.sleep(1)
        if swordAttack == randomNumber:
            t = 1
            damage(timerAmount, 10)
            print(timerAmount)

sword()

First issue is that I can't figure out how to get a timer to count up and then get that final time for use in the damage formulas. Timer function from threading only counts down, and I couldn't figure out how exactly to work time it, although if you could explain it to me in simple terms that might work.
Second issue is that I also need to make it so the timer activates as soon as the input is shown on screen, but when the input statement runs, it stops the code until an input is given.

A: Ok So I'm going to give this a go in a way that uses the timer count down. If you have the damage of the sword be 10 anyways there is no need to go over 10 into 'negatives' it would just be 0 so just count down from whatever the swords damage is. So if they type it in 2 seconds then that would be 8 damage in this case. Here is some code I got to work using a countdown. All you have to do is set the timer to whatever the swords damage is.
import random
import time
from threading import Timer

def damage(timeAmount, baseDamage):
    damageTotal = baseDamage - timeAmount
    print(format(damageTotal, '.0f'))

def sword():
    user_sword_max_damage = 10
    randomNumber = random.randint(0, 10)
    timeout = user_sword_max_damage
    t = Timer(timeout, print, ['Damage dealt = 0'])
    start_time = time.time()
    t.start()
    while True:
        try:
            prompt = int(input('Enter ' + str(randomNumber) + ' as fast as you can: '))
            if prompt == randomNumber:
                t.cancel()
                final_time = time.time()-start_time
                print(format(final_time, '.0f'))
                damage(final_time, user_sword_max_damage)
                break
            elif prompt != randomNumber:
                continue
        except:
            continue
sword()

This could also potentially point you in the right direction if you add more damage items later on. The only part I didn't add is the logic to set the damageTotal to 0 if the time runs out which you should be able to put inside the if statement within the while loop(be kind this is my first time attempting an answer ha but I do hope this helps)


text:
Q: Cannot call method 'then' of undefined - $.ajax I use $.ajax in my angularjs controller to save an order. After I updated to AngularJS 1.2.2 i get the error TypeError: Cannot call method 'then' of undefined when $.ajax is called. I cannot find any information about that anything has changed. Am I doing something wrong? Here is my code for the ajax call:
$scope.saveOrder = function () {

  $.ajax({
     type: 'POST',
     url: $scope.saveOrderUrl,
     data: $scope.order,
     async: false,
     dataType: 'json',
     success: function (result) {
         $scope.order = result;
         $scope.isNewOrder = false;
         if ($scope.order.OrderId === 0) {
             alert("No order id was returned from the server. The order will not be opened in view mode.");
             window.location.href = appUrl + "/Order/Index/" + $scope.patientId;
         } else {
             window.location.href = appUrl + "/Order/Details/?personId=" + $scope.patientId + "&orderId=" + $scope.order.OrderId;
         }
     },
     error: function (xhr, status, error) {
         alert("Error when saving order. Status: " + status);
     }
 });

}

A: $.ajax is jQuery's (or Angular's jQuery lite implementation) ajax method. To get Angular's Promises you need to use $http (note the absense of . after $)


text:
Q: HTML Listbox width when length is zero I am trying to fill options into a listbox dynamically. I want to set a fixed width even there is no elements in it. Any help is appreciated.

A: Use CSS to do this, since there's no html attribute that changes auto width of this object:
<select style="width: 300px">

Simple example.


text:
Q: Mayavi mesh with common color scheme I am plotting two mayavi meshes in the same figure. I'm supplying surface vertex scalars to guide the coloring. It seems that mayavi uses a per-mesh color scale. What I would like, however, is a commonized color scale, so that the cube I draw with these six meshes, for example
mlab.mesh(x_0, y_0, z_0, scalars=1 * np.ones_like(x_0), colormap='jet')
mlab.mesh(x_1, y_1, z_1, scalars=2 * np.ones_like(x_0), colormap='jet')
mlab.mesh(x_2, y_2, z_2, scalars=3 * np.ones_like(y_0), colormap='jet')
mlab.mesh(x_3, y_3, z_3, scalars=4 * np.ones_like(y_0), colormap='jet')
mlab.mesh(x_4, y_4, z_4, scalars=5 * np.ones_like(z_0), colormap='jet')
mlab.mesh(x_5, y_5, z_5, scalars=6 * np.ones_like(z_0), colormap='jet')

doesn't turn out all dark blue for each face.
I'm trying to visualize a 3D scalar field on the surface of a cuboid, but the colors don't match up at the edges/corners. Can't find anything in the documentation.
The common color scaling doesn't necessarily have to be automatic. If there was a way to set the lower and upper value limit for each map like with clim in matplotlib, I could set that the same for all mesh commands.

A: Finally found it documented for another function, but mlab.mesh also understands the parameters vmin and vmax that determine the lower and upper level to use for the color scale, so above calls would be:
mlab.mesh(x_0, y_0, z_0, scalars=1 * np.ones_like(x_0), colormap='jet', vmin=0, vmax=1)


text:
Q: Search lines of textfile between two words, that contains a keyword I have to extract lines from a textfile that contains a keyword, delimited by two words.
I've already found only the line that contains keyword (with contains(string)) , but I need to have also a pair of lines before and after this, maybe not counting the lines, but searching the first and the last word of this group of lines.
How I can do that?

A: You could store the lines in a java.util.List in the first step and then iterate over the list with an index.
List<String> lines = new ArrayList<String>();
while(reader.ready()){
  lines.add(reader.readLine());
}

for(int i = 0; i<lines.size();i++){
  if(lines.get(i).contains(string)){
    String lineMinusTwo = lines.get(i-2);
    String lineMinusOne = lines.get(i-1);
    String line = lines.get(i);
    String linePlusOne = lines.get(i+1);
    String linePlusTwo = lines.get(i+2);
  }
}

A: How about implementing a "VERY ROUGH" lexer that reads the lines and maps them into a HashMap. The integer would be the line number and the string the whole line.
Process the whole file and then loop through the map when you find a line that has the keyword you can go look up the previous n lines that you need based on the current line number and the next n lines as well.


text:
Q: how to change color of an element with javascript I am taking a beginners javascript class.  My teacher wants me to change the color of an element in my page, but I can't figure out how to do it.  Here is the page:
// JavaScript Document

function myPar() {

    pge = new Array ()

    //I would need to change the color of JUST pge[4]

    pge[4] = "So have you reverse engineered this document?"

    pge[3] = "This first instance a button creation will create multiple buttons with no purpose. They will not be linked to any site in this lecture video. The first need to become familiar with the process and with the required syntax for setting a series of attributes. When the button construction sequence is completed the process will then append the button to the body tag as it did for the paragraph tag."

    pge[2] = "The same process that was used to create paragraphs dynamically will be used to create buttons dynamically. This first instance of button creation will be design to create a button each time the function trigger is pressed."

    pge[5] = "So this build of page content can happen in any sequence that is seen fit and then modified by changing index vaues."

    pge[0] = "It was the best of times, it was the worst of times"

    pge[1]= "There's no way that we can work out a way to colonize Mars in the next 50 years.  Think of the logistical obstacles to such a plan.  You'd need food, water, medicine.  You'd need engineers, doctors, nurses, endless oxygen, of which mars has none."

    pge[6] = "So what is such a big deal here?"

    for (i=0;i<=pge.length-1;i++) {
        var pgp = document.createElement("p");
        var txt = document.createTextNode(pge[i]);

        pgp.appendChild(txt);
        pgp.setAttribute("class","mine");

        pgp.appendChild(document.createElement("br"));

        pgp.setAttribute("style","color:#605;font-size:1.5em;");

        document.body.appendChild(pgp);
        txt = "";
    }

}

A: In your loop, check the value of i.  If it's 4 then it's the one you want to change.  So you can do something like this:
var len = pge.length;
for (var i=0; i< len;i++) {
 if (i==4) { pgp.classList.add('redBG'); }
}

And have a CSS class:
.redBG {background-color:red; }

The best way to update the class is not using setAttribute.  Its by modifying the classList (for modern browsers).  In older broswers, you have to manually manipulate className as a string.
Also, you should ALWAYS var your variables.


text:
Q: Insert request.session in class based Generic view in Django I'm trying to use request.session to create a 'recent' session key and add the product pages visited by the user to make it accesible in the template, here is my view, what would you guys recommend, I can't seem to go about doing this
class ProductDetail(DetailView):
    model = Producto
    template_name = 'productos/product_detail.html'

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(ProductDetail, self).get_context_data(**kwargs)
        # Add in a QuerySet of featured products
        context['product_list'] = Producto.objects.filter(featured=True).exclude(pk=self.object.pk)
        return context

Thanks for your help!

A: thanks to Daniel Roseman for the clarification on how to call session from the class based generic view
class ProductDetail(DetailView):
    model = Producto
    template_name = 'productos/product_detail.html'

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(ProductDetail, self).get_context_data(**kwargs)
        if not 'recent' in self.request.session or not self.request.session['recent']:
            self.request.session['recent'] = [self.object.pk]
        else:
            recentList = self.request.session['recent']
            recentList.append(self.object.pk)
            self.request.session['recent'] = recentList
        # Add in a QuerySet of featured products
        context['product_list'] = Producto.objects.filter(featured=True).exclude(pk=self.object.pk)
        context['recent_list'] = Producto.objects.filter(pk__in=recentList)
        return context


text:
Q: Is it possible to add database backup file along with Custom Setup (.exe) application I have a .exe Setup file which i created using Microsoft Setup and Deployment application.Now as per my requirement i have to add my database backup file also along with the setup So that while installing backup file should also be stored in the database.
I have the tested codes of the restoring mysql database using c# but that is from the hardcoded path to find the backup.If it is in Setup what filepath name i can give to restore .
Please help me..

A: You can add the database file to the project as an existing item and then set "Copy to Output Directory" to "Copy if newer".
I think the safest approach to locate the folder where all files are stored is:
System.Reflection.Assembly.GetExecutingAssembly().CodeBase

which returns path to the directory where your assembly (.exe) is running in.


text:
Q: C# - Why doesn't time and date save in mysql database? I have the following code:
private void saveDT()
    {

        MySqlConnection myConn = new MySqlConnection(Common.myConnection);
        myConn.Open();
        string sLastLogin = DateTime.UtcNow.ToString("dd.MM.yyyy HH:mm:ss");
        MySqlCommand mySqlCmd = new MySqlCommand("UPDATE ha_system.tblaccounts SET lastlogin='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' WHERE name='" + Common.ActiveUser + "'", myConn);
        try
        {
            mySqlCmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Fehler: " + ex.Message);
        }
        finally
        {
        }
    }

But time and date is only saved after the second login in the database column "lastlogin".
Why? What can I do to fix this?

A: beside the other comments about avoiding SQL injection, you do not need to get a DateTime value from .NET into the MySQL server, you can use built in function and have a query like this:
"UPDATE ha_system.tblaccounts SET lastlogin=NOW() WHERE ..."

A: If you write the datetime literal in a valid format, it should work fine.
dd.mm.yyyy hh:mm:ss is not a valid format for a MySQL datetime literal.  It's also ambiguous, at any rate.  Try yyyy-mm-dd hh:mm:ss, with the appropriate capitalization of H and M in the right places for the function you're using.
http://dev.mysql.com/doc/refman/5.6/en/date-and-time-literals.html
And, seriously, don't build queries by concatenating strings.


text:
Q: Webpack JS Template Strings to generate Inline CSS style for background image: url() I have the following template string in JS:
`<div class="card-img center-auto" alt="Image of ${data.title}" class="${data.imgClass}" style="background-image: url(images/${data.imageName}.JPG)"></div>`

The background image is an inline style which file path name gets loaded in with data.imageName on run.
Images load in DEV, and if I open PROD environment locally images are there but when I push it up to Github pages the images are error 404. I've waited while as I know it can sometimes take time to upload to GitHub pages but still nothing.
Images folder is called "Images" in same root as the index.html
How do I get Webpack to load these images? I've tried file-loader, url-loader and either I have configured wrong or should be using something else? Thanks
Webpack config DEV:
const path = require("path");

module.exports = {
  mode: "development",
  entry: {
    app: "./src/scripts/script.js"
  },
  devtool: "eval-source-map",
  devServer: {
    contentBase: "./dev"
  },
  output: {
    filename: "[name].bundle.js",
    path: path.resolve(__dirname, "dev")
  },
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 8192
            }
          }
        ]
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        use: [
          "file-loader",
          {
            loader: "image-webpack-loader",
            options: {
              mozjpeg: {
                progressive: true,
                quality: 65
              },
              // optipng.enabled: false will disable optipng
              optipng: {
                enabled: false
              },
              pngquant: {
                quality: "65-90",
                speed: 4
              },
              gifsicle: {
                interlaced: false
              }
            }
          }
        ]
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
      }
    ]
  }
};

Webpack Prod Config:
const webpack = require("webpack");
const path = require("path");
const UglifyJSPlugin = require("uglifyjs-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");

module.exports = {
  mode: "production",
  entry: {
    app: "./src/scripts/script.js"
  },
  devtool: "source-map",
  plugins: [
    new UglifyJSPlugin({
      cache: true,
      sourceMap: true
    }),
    new OptimizeCSSAssetsPlugin({}),
    new webpack.DefinePlugin({
      "process.env.NODE_ENV": JSON.stringify("production")
    }),
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  ],
  output: {
    filename: "[name].bundle.js",
    path: path.resolve(__dirname, "docs")
  },
  module: {
    rules: [
      {
        test: /\.(html)$/,
        use: {
          loader: "html-loader",
          options: {
            attrs: [":data-src", "img:src"],
            minimize: true
          }
        }
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"]
      },
      {
        test: /\.svg$/,
        loader: "svg-inline-loader"
      }
    ]
  }
};

A: Figure it out for some reason GitHub was remembering .jpg for images even tho I had changed it to .JPG and pushed up the changes, I re did the images in Prod re added and republished and it worked.


text:
Q: Redirect to a particular YouTube video link if a person opens any YouTube page I want to redirect all the users in my WiFi network who ever open YouTube or any YouTube video to a particular YouTube video.
It might require editing the URL. I don't know if we can call it URLSpoofing. How can I achieve that?

A: What you want is to perform DNS manipulation. In order to do that (for both http and https) you'll need to run their DNS traffic through a device that you control.
There are lots of ways to do such a thing. Your router may support web site redirects in the administration page. Another way will be to set up a DNS server on your network and configure it to bypass everything except youtube.com. You'll also need to configure your DHCP server to use your new DNS server as the default.
There's a device that will handle this for you, although it may be tricky for you to set up if you're green.
http://hakshop.myshopify.com/collections/wifi-pineapple-kits


text:
Q: node nssm http-server...service won't start I have successfully used nssm to create a node service that runs in the background.  I have done this, however, with .js files where you set the path to node.exe, then set the startup directory, then set the .js file you want to run in the arguments.  Works great.
I'm trying to get http-server to run in the background, and I can't quite make it happen.  The difference is, to run http-server, you don't run node.exe, just the 'http-server' command with a path after it.  So, I'm scratching my head as to what I place in nssm for the path, startup directory, and arguments.
I've tried to place http-server "C:\path...etc." into a .bat file and run that with nssm, but when starting the service, I get the "Windows could not start the service on local computer..." error, and the service does not start.  I've also tried to convert the .bat to a .exe and run into the same error.
Any help would be greatly appreciated!


text:
Q: Recursive integer solution of the equation: $a^2-2b^2=\pm 1$
Consider $a_0=a_1=1$ and $a_k=2a_{k-1}+a_{k-2}$ for $k\ge2$.
  Similarly $b_0=0,b_1=1$ and $b_k=2b_{k-1}+b_{k-2}$ for $k\ge 2$.

I want to prove that for every natural $k$ the pair $(a_k,b_k)$ is an integer solution of the equation $a^2-2b^2=\pm 1$ where $a,b\in \mathbb Z$. Of course you can find other recursions for other indices (even/odd). This would be ok for me.
Now the idea is to prove it by induction. I tried, but I had some difficulties since by even $k$ we have the solution for $+1$ and for odd $k$ the one for $-1$ and I should prove also this by induction. However I cannot see how since the $a_k,b_k$ are too dependent on the others. Making computations you can see what I mean.

Another idea was to consider two distinct recursions: one for even values of $k$ and another one for odd $k$ and proving by induction the two recursions separately. However I cannot see these recursions. Anyone does?

Does anyone know how to do the induction here?

A: Hint
You can prove the following claim by induction. Note that this claim is one claim containing 4 equations. We will prove these equations simultaneously.
Claim
\begin{align}
a_{2m}^2 - 2b_{2m}^2 &= 1\\
a_{2m+1}^2 - 2b_{2m+1}^2 &= -1\\
a_{2m}a_{2m+1} - 2b_{2m}b_{2m+1} &= -1\\
a_{2m-1}a_{2m} - 2b_{2m-1}b_{2m} &= 1\\
\end{align}
Sketch of the proof the claim

*

*First step: You can easily show this for $m=1$.

*Then try to prove this claim for $m+1$ i.e.
\begin{align*}
a_{2m+2}^2 - 2b_{2m+2}^2 &= 1\\
a_{2m+3}^2 - 2b_{2m+3}^2 &= -1\\
a_{2m+2}a_{2m+3} - 2b_{2m+2}b_{2m+3} &= -1\\
a_{2m+1}a_{2m+2} - 2b_{2m+1}b_{2m+2} &= 1\\
\end{align*}
This should be straight forward.
Comment on the straightforwardness
Let me prove the first line:
\begin{align*}
a_{2m+2}^2 - 2b_{2m+2}^2 &= (2a_{2m+1} - a_{2m})^2 - (2b_{2m+1} - b_{2m})^2\\
&= 4a_{2m+1}^2 + a_{2m}^2 -4a_{2m+1}a_{2m} - 8b_{2m+1}^2 - 2b_{2m}^2 + 4b_{2m+1}a_{2m}\\
&= 4(a_{2m+1}^2 -2b_{2m+1}^2) + (a_{2m}^2 -2 b_{2m}^2) - 4(a_{2m}a_{2m+1} - b_{2m}a_{2m+1})\\
&= - 4 + 1 -4\\
&=1
\end{align*}
Note
Sometimes it is hard to do induction over one claim. In cases like this, proving a stronger claim makes the proof easier.
Edit
There were couple of typos about the negative signs. I have fixed them.

A: We can use the fact that
$$a_n=\frac{1}{2} \left(\left(1-\sqrt{2}\right)^n+\left(1+\sqrt{2}\right)^n\right)
\qquad
\text{and}
\qquad
b_n=-\frac{\left(1-\sqrt{2}\right)^n-\left(1+\sqrt{2}\right)^n}{2 \sqrt{2}}.$$
These expressions can be proved by induction (there are also well-known methods to derive the general term of a linear recursive relation. You can read about it for example in Wikipedia.)
Therefore, we have
$$a_n^2=\frac{1}{4}\left\{\left(1-\sqrt{2}\right)^{2 n}+\left(1+\sqrt{2}\right)^{2 n}+2\left(\left(1-\sqrt{2}\right) \left(1+\sqrt{2}\right)\right)^n\right\}
$$
and
$$2b_n^2=\frac14\left\{\left(1-\sqrt{2}\right)^{2 n}+\left(1+\sqrt{2}\right)^{2 n}-2\left(\left(1-\sqrt{2}\right) \left(1+\sqrt{2}\right)\right)^n\right\}
$$
so
$$a_n^2-2b_n^2=\frac14\left\{4\left(\left(1-\sqrt{2}\right) \left(1+\sqrt{2}\right)\right)^n\right\}
=(-1)^n.$$
EDIT (a method to derive $a_n$): let us define
$$F(x):=\sum_{n\geq0}a_n\frac{x^n}{n!}.$$
Then clearly $F^{(n)}(0)=a_n$. Now,
$$F''(x)=\sum_{n\geq0}a_{n+2}\frac{x^n}{n!}
=\sum_{n\geq0}a_{n}\frac{x^n}{n!}+2\sum_{n\geq0}a_{n+1}\frac{x^n}{n!}
=\sum_{n\geq0}a_{n}\frac{x^n}{n!}+2\sum_{n\geq1}a_{n}\frac{x^{n-1}}{(n-1)!}
=F(x)+2F'(x).$$
So $F$ is a function that satisfies the linear second order ODE
$$F''(x)-2F'(x)-F(x)=0$$
and the initial conditions $F(0)=1,F'(0)=1$. Solving the differential equation we obtain
$$F(x)=\frac{1}{2} \left(e^{\left(1-\sqrt{2}\right) x}+e^{\left(1+\sqrt{2}\right) x}\right),$$
so the general form of $a_n$ is achieved after $n$-fold differentiation.

A: I should emphasize that this is just the continued fraction for $\sqrt 2.$
Usually it is not so pretty to combine the $1$ and $-1$ cases in Pell $x^2 - n y^2.$ However: If $$ x^2 - 2 y^2 = \delta  $$ with all integers, then
$$ (x+2y)^2 - 2 (x+y)^2 = - \delta.  $$
That is, take the column vector of integers
$$
\left(
\begin{array}{c}
x \\
y
\end{array}
\right)
$$
The matrix of transformation is
$$
A =
\left(
\begin{array}{rr}
1 & 2 \\
1 & 1
\end{array}
\right)
$$
The fact you are trying to prove is just Cayley-Hamilton for this matrix. The trace is $2$ while the determinant is $-1.$ The characteristic equation is then $\lambda^2 - 2 \lambda - 1,$ or  $\lambda^2 = 2 \lambda + 1.$
$$
\left(
\begin{array}{c}
x_{n+1} \\
y_{n+1}
\end{array}
\right) =
\left(
\begin{array}{rr}
1 & 2 \\
1 & 1
\end{array}
\right)
\left(
\begin{array}{c}
x_n \\
y_n
\end{array}
\right),
$$
$$
\left(
\begin{array}{c}
x_{n+2} \\
y_{n+2}
\end{array}
\right) =
\left(
\begin{array}{rr}
1 & 2 \\
1 & 1
\end{array}
\right)
\left(
\begin{array}{c}
x_{n+1} \\
y_{n+1}
\end{array}
\right),
$$
while $A^2 = 2A + I.$


text:
Q: Wireless Power Transfer Circuit Theory I made this circuit, and it is working fine. But didn't understood the theory in it. How is it putting a frequency in the coil? It did not match with any of the oscillator circuits. And also it is not working in LTSpice.

A: This is a basic LC oscillator where the two haves of the coil are coupled inductors. Here is a simplified version...

There is a good explanation of LC oscillators like this one here...
http://www.electronics-tutorials.ws/oscillator/oscillators.html

simulate this circuit – Schematic created using CircuitLab


text:
Q: Wiremock variable substitution in JSON response I am trying to configure Wiremock mappings to return a JSON response with a value from the request.
The request is simply
{ "clientTag": "123" }

And the mapping for it is:
{
  "priority": 4,
  "request": {
    "method": "POST",
    "urlPattern": "/test"
  },
  "response": {
    "status": 200,
    "body": "{ \"loginId\": \"${loginId}\" }",
    "headers": {
      "Content-Type": "application/json"
    }
  },
  "captures" : [ {
            "source" : "BODY",
            "target" : "loginId",
            "pattern" : "$..clientTag",
            "captureGroup" : 1
  } ]
}

I receive the response:
{ "loginId": "" }

while the expected one is:
{ "loginId": "123" }

If I switch to XML requests, everything works fine with the pattern <clientTag>(.*?)</clientTag>, but I would like to stick to JSON.
Unfortunately Wiremock documentation is scarce hence the question. Any ideas?
UPDATE: If someone is reading this later, you'd do best to use the transforms in the code, which are available in the later Wiremock versions.

A: This seems like a perfect use-case for OpenTable's Wiremock Body Transformer.
It can be easily integrated with the Standalone Server like this:
java -cp "wiremock-body-transformer-1.1.6.jar:wiremock-2.3.1-standalone.jar" com.github.tomakehurst.wiremock.standalone.WireMockServerRunner --verbose --extensions com.opentable.extension.BodyTransformer
This extension allows you to easily specify a variable in the request that you would want to match in the response.
{
    "request": {
        "method": "POST",
        "urlPath": "/transform",
        "bodyPatterns": [
            {
                "matchesJsonPath": "$.name"
            }
        ]
    },
    "response": {
        "status": 200,
        "body": "{\"responseName\": \"$(name)\"}",
        "headers": {
            "Content-Type": "application/json"
        },
        "transformers": ["body-transformer"]
    }
}

It also easily allows you to generate a random integer in the response as seen here:
{
    "request": {
        "method": "POST",
        "urlPath": "/transform",
    },
    "response": {
        "status": 200,
        "body": "{\"randomInteger\": \"$(!RandomInteger)\"}",
        "headers": {
            "Content-Type": "application/json"
        },
        "transformers": ["body-transformer"]
    }
}

A: Unless you've added an extension you haven't mentioned, this can't work - there's no "captures" element in the JSON API, and no way (without extensions) to do variable substitution in responses.

A: WireMock.Net does support this now.
When sending a request like:

{
    "username": "stef"
}

And using mapping like:

{
  "Request": {
    "Path": {
      "Matchers": [
        {
          "Name": "WildcardMatcher",
          "Pattern": "/test"
        }
      ]
    },
    "Methods": [
      "post"
    ]
  },
  "Response": {
    "StatusCode": 200,
    "BodyAsJson": {
      "path": "{{request.path}}",
      "result": "{{JsonPath.SelectToken request.bodyAsJson \"username\"}}"
    },
    "UseTransformer": true,
    "Headers": {
      "Content-Type": "application/json"
    }
  }
}

The response will be like:

{
    "path": "/test",
    "result": "stef"
}

Note that this functionality is currently in preview mode, see NuGet package version 1.0.4.8-preview-01.
If you have any questions, just create an issue on this github project.


text:
Q: Why do elementary steps of elimination appear to fail for a system of equations with each term of degree 2? I apologise in advance if this is irritating due to its simplicity - I have only done High School Mathematics.
Given:
(1) $(a+1)^2$ = $(b+2)^2$+$(c+3)^2$
(2) $(a+3)^2$ = $(b+1)^2$+$(c+2)^2$
(3) $(a+4)^2$ = $(b+3)^2$+$(c+1)^2$
(4) $(a+2)^2$ = $(b+4)^2$+$(c+4)^2$
Subtracting pairs of equations:
$(2)-(1)=(5)$-->$4a+8 = -2b-3 + -2c-5$
$(3)-(2)=(6)$-->$2a+7 = 4b+8 + -2c-3$
$(4)-(3)=(7)$-->$-4a-12 = 2b+7 + 6c + 15$
Upon simplification this is:
$$\begin{align}2a+b+c&= -8 \\
a-2b+c &= -1 \\
-2a-b-3c &= 17 \\
\end{align}
$$
Which, when solved, gives:
$a=-0.7$
$b=-2.1$
$c=-4.5$
Unless I have made a calculation error, none of these values when re-substituted into (1), (2), (3), or (4) results in a correct statement. Yet, apart from a general sense that the existence of degree 2 terms invalidates some part of the reasoning, or the fact that the system is overdetermined, I can't pinpoint which step is false or contains an incorrect assumption. Can anyone shed light on this for me? Alternatively, if someone has a method for solving equations (1),(2),(3) without the overdetermining (4) could you explain that or point me in the direction of an explanation.

Edit: For anyone interested in the specific worked solution, I followed Ted's advice (after learning about general solutions here) and looked to solve (1), (2), (3) with the result:
$$\begin{align}
a&=-3.4 -0.6t\\
b&=-1.2 +0.2t \\
c&=t\\
\end{align}
$$
Substitution of these into equation (1) yielded $0.68t^2 +3.44t + 3.88$
This quadratic equation appeared twice more after substitution into (2) and (3) respectively (meeting the criteria that the solution(s) for t be common to all three if solutions for a,b,c are to be found).
Using the ordinary quadratic formula, the two solutions for the parameter t were therefore: $t = \frac{-43}{17}+\frac{25}{34}\sqrt{1.28} \approx -1.698$  or $t = \frac{-43}{17}-\frac{25}{34}\sqrt{1.28} \approx -3.361$
Finally using those approximations,
$a \approx -2.381 $ or $a \approx -1.383$
$b \approx -1.540 $ or $b \approx -1.872$ and
$c \approx -1.698$ or $c \approx -3.361$
For confirmation, I re-substituted corresponding results for a,b,c into the original equations (1), (2), and (3). This generated three correct statements with LHS = RHS.
Thank you to Ted and to anyone else who considered this.
I hope this post is useful to someone else.

A: The fact that the system is overdetermined is the whole problem.  It has nothing to do with the fact that the equations have degree 2.  The same thing can happen with an overdetermined linear system.  Let's take an even simpler example with only 2 variables and 3 equations:
$$x+y=0, x-y = 0, x+2y=1$$
Now proceeding as you did above, if we add the first 2 equations we get $x=0$, and if we subtract the third equation from the second, we get $y=1/3$.  Now plug these values back into the original system.  Nothing works.  The system was overdetermined and there was no reason to expect a solution.
If you just want to solve your original equations (1), (2), (3)  (without the overdetermining (4)), you can proceed as you did above, ending up with a linear system of 2 equations in 3 variables.  You can solve this linear system; the general solution of the linear system will give $a$, $b$, $c$ in terms of a single parameter $t$.
Then you plug in these expressions for $a$, $b$, $c$ in terms of $t$ into the original 3 equations, getting 3 quadratic equations in $t$.  If there is a common value (or values) of $t$ that solves all 3 quadratic equations, then you can get solutions for $a$, $b$, $c$ using the common value(s) of $t$.  If there is no common value of $t$, then there is no solution.


text:
Q: Is firebase's sort by a child O(n) for large data sets and is there a way to optimize it? Sorry if the title is unclear but I'm not clear as to what I'm asking specifically either.
I have a dataset like so
messages: {
   message_key1: {
       timeStamp: 1610236700000,
       message: message,
   }
   message_key2: {
       timeStamp: 1610236746542,
       message: message,
   }
   message_key3: {
       timeStamp: 1610236790000
       message: message,
   }
   message_key4: {
       timeStamp: 1610236810000
       message: message,
   }
   message_key5: {
       timeStamp: 1610236800000
       message: message,
   }
}

and I wanted to grab the data from the data from 1610236746542 to 1610236810000. Imagine we have tens of thousands of messages. That would require a sort then a fetch which would be extremely inefficient on a large scale. Can I tell firebase to sort the message_key's based off timeStamp and search based off that same time stamp?
I'm using Firebase Realtime Database.

A: You can do this with firestore like this:
firebase
  .firestore()
  .collection('messages')
  .orderBy('timestamp')
  .startAt(1610236746542)
  .endAt(1610236810000)
  .get();

A: Once you define an index on timeStamp, a sort/filter action will be performed on Firebase's servers and thus not need to download all data to your application code.
The time this takes on the server is dependent on the amount of data in the index, but it's not O(n) - it's typically much better. In general most of the performance of your queries will depend on the bandwidth needed to transfer the data to your application, much more than the size of the list.
There is a scalability impact of the size of the list, but that's not explicitly defined (and has improved over the years). I typically recommend not ordering/sorting lists of more than a couple of hundreds of thousands of nodes, although I've seen cases over 1m or more nodes also work (depending on the data size).
If you want a solution where the amount of data in the location has no impact on the performance of queries, consider using Cloud Firestore. This database guarantees that the time it takes to get data only depends on the size of the data you retrieve, not on the amount of data that is considered. So that's O(1) performance, which is pretty uncommon.


text:
Q: $1+x+\ldots+x^n$ perfect square Let $p$ be the polynomial $p(x)=1+x+\ldots+x^n$.
For which couples $(a, n)\in\mathbb{N}^2$, $p(a)$ is a perfect square? I'm particularly interested in $p(3)$.

A: If $a=3$,then $n=0,1,4$ are all the solutions.
$p(3)=1+3+…+3^n=\frac{3^{n+1}-1}{3-1}=y^2,3^{n+1}-1=2y^2$
Denote $m=n+1,t=\sqrt{-2}$, then $$3^m=1+2y^2$$
$$(1+yt)(1-yt)=(1+t)^m(1-t)^m$$
We get $$1+yt=±(1+t)^m,1-yt=±(1-t)^m$$
so $$1=±\frac{(1+t)^m+(1-t)^m}{2},y=±\frac{(1+t)^m-(1-t)^m}{2t}$$
We get $m=1,2,5$, and $|y|=1,2,11$.

A: The Diophantine equation $f_n(x)=1+x+x^2+\cdots+x^{n-1}=y^2$.
Ribenboim's book on Catalan's conjecture has a detailed
analysis of this Diophantine equation. Except the cases noted below, there are no more non-trivial solutions.
Here are some of the easy cases:

*

*There are always the two trivial solutions  $x=0$ and $x=-1$.

*If $n$ is a square, then $x=1$ is a third solution.

*For $n=3$, if $x\not=0$, then $-2|x|<x<2|x|$ implies
$(|x|-1)^2<1+x+x^2<(|x|+1)^2$ so $f_3(x)$ can only be the square  $x^2$.
This gives the other trivial solution $x=-1$.

*For $n=4$,  look at Monthly problem 11203 (Feb. 2006) or Exercise 1.10
in Edward's book Fermat's Last Theorem. The only solutions are  $x=-1,0,1,7$.

*For $n=5$,  see Ed Burger's book Exploring The Number Jungle (Exercise 12.11). By comparing $4f_5(x)$
with $(2x^2+x)^2$ and $(2x^2+x+1)^2$, we find that the only solutions are  $x=-1,0,3$.

*For $n=6$, we factor $f_6(x)=f_2(x^3)f_3(x)$.
By the formula $2=f_2(x^3)-(x-1)f_3(x)$ we see that
$\gcd(f_2(x^3),f_3(x))$ divides 2. But $f_3(x)$ is always odd, so the gcd equals 1.
This forces $f_3(x)$ to be a square so we end up with the trivial solutions $x=0,-1$.

*For $n=7$, if $x>5$ we have
$$(16x^3+8x^2+6x+5)^2< 256 f_7(x)< (16x^3+8x^2+6x+6)^2,$$
while
for $x<-4$ we get  $$(16x^3+8x^2+6x+5)^2< 256 f_7(x)< (16x^3+8x^2+6x+4)^2.$$
Check the values between and you find that there are only trivial solutions.
By this stage, elementary methods get tougher to push through.

A: There're lots of pairs:
$$\,p(1,n^2)\,,\,\,\forall\,n\in\Bbb N\;,$$
$$\,p(3,1)=2^2\;,\;p(3,4)=11^2\;,\ldots$$


text:
Q: user has many images using paperclip in rails 3 i have been using paperclip with model as user has_many :images and image belongs_to:user.now i want to get the polymorphism working for the image model such that user,post has many images and image belongs to imageable polymorphic=>true.i am working on it but i am not confident as im not clear with the concepts of paperclip as such.Now these are the changes that i did but what further changes do i need to make to get an association as user has many images and images belongs to imageable ,polymorphic =>true.Below is what i have done but not getting any result.any help will be appreciated....I JUST NEED polymorphism of image such as user has many images,post has many images.....etc where image belongs to imageable,:polymorphic =true.
image.rb
belongs_to :imageable,:polymorphic=>true
has_attached_file :avatar, :url  => "/assets/images/#{imageable_type}/#{imageable_id}/:style/:basename.:extension",
             :path => ":rails_root/public/assets/images/#{imageable_type}/#{imageable_id}/:style/:basename.:extension", :default_url => 'dashboard/default_avatar.jp

g'
user.rb
has many:images ,:as=>imageable,:dependent=>destroy

migration file to images
class CreateImages < ActiveRecord::Migration
  def change
    create_table :images do |t|
      t.string :name
      t.references :site
      t.string :image_file_name, :null => true
      t.string :image_content_type, :null => true
      t.integer :image_file_size, :null => true
      t.timestamps
    end
  end
end

migration for user.rb
class CreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      t.string :first_name
      t.string :last_name
      t.string :username
      t.string :mobile_number
      t.string :email
      t.references :image
      t.timestamps
    end

my view form where i will allow user to upload image or edit image
profile.html.erb.....using remotipart gem
<%= form_for(@user,:url=>'add_image_to_user_path',:html => {:multipart => true},:remote=>true) do |f |%>
<%= f.file_field :images, :multiple => true %>
<%= f.submit "Add image" %>
<%end%>

users_controller.rb
    ##now how i should update the users image who has already logged in
    ##i tried @user.update_attribute(params[:user]) but i cannot see any update query in the log
 -   ##i can only see --->paperclip saving attachment
    def add_image_to_user
       @user=User.new
    end

A: Sounds to me like you need a has_many :through association. This will allow you to keep your image, user and post models all separate
I think your problem is that you're limiting the association of the images to specific objects, which you'd like to assign to either post or user

Has_Many Through
In our company, we only make images belong_to :user (for authorization purposes). For everything else, we use join models with has_many :through associations, as this allows you to create as many associations as you desire
Here's how we do it:
#app/models/image.rb
Class Image < ActiveRecord::Base
    has_many :image_posts, :class_name => 'ImagePost'
    has_many :posts, :class_name => 'Post', :through => :image_posts

    has_many :user_images, :class_name => 'UserImage'
    has_many :users, :class_name => 'User', :through => :user_images
end

#app/models/user.rb
Class User < ActiveRecord::Base
    has_many :user_images, :class_name => 'UserImage'
    has_many :images, :class_name => 'Image', :through => :user_images
end

#app/models/post.rb
Class Post < ActiveRecord::Base
    has_many :image_posts, :class_name => 'ImagePost'
    has_many :images, :class_name => 'Image', :through => :image_posts
end

#app/models/ImagePost.rb
Class ImagePost < ActiveRecord::Base
    belongs_to :image
    belongs_to :post
end

   #app/models/UserImage.rb
   Class UserImage < ActiveRecord::Base
        belongs_to :image
        belongs_to :user
   end

The join models will look like this in the database:
user_images
id | user_id | image_id | extra | attributes | created_at | updated_at

image_posts
id | post_id | image_id | extra | attributes | created_at | updated_at

This means you'd use accepts_nested_attributes_for to assign the image_id for either user or post. Because the join model is handling the association, the image remains untouched. I can post how to do this if you feel it applicable

A: Your problem has nothing to do with paperclip, it's all about polymorphic association. Now, polymorphic association is very similar to regular association - the only difference, looking from the point of view of DB schema, is existence of another column in "belonging" model (in your case, it's imageable_type), that contains class of associated record. So, firstly, you should remove t.references :image from create_users migration, as it's unnecessary there. Secondly, you should add your foreign key column and association type column to create_images migration. You can do it with single 'directive', like this:
t.references :imageable, polymorphic: true

and this should be enough.


text:
Q: xslt 1.0 Updating the right header The request XML I have is given below and the XSLT transformation I am using is also given.
Unfortunately the ordertotal element is repeating twice after transformation. How can I update the ordertotal element instead of repeating it?
Request XML is
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <ns2:fetchOrderListResponse xmlns:ns2="http://impl.lob.wipro.com/">
         <return>
            <customerOrderNumber>1</customerOrderNumber>
            <orderDetails>
               <itemPrice>50.0</itemPrice>
               <itemQty>2</itemQty>
               <itemUnit>0</itemUnit>
               <orderDetailsId>37516016-D71B-4790-951F-55D00B0CC159</orderDetailsId>
               <camelAddedDtlField>0.1</camelAddedDtlField>
            </orderDetails>
            <orderDetails>
               <itemPrice>39.0</itemPrice>
               <itemQty>3</itemQty>
               <itemUnit>0</itemUnit>
               <orderDetailsId>6095ABC7-0D0D-4B2E-92E5-80F24E9092B8</orderDetailsId>
               <camelAddedDtlField>0.1</camelAddedDtlField>
            </orderDetails>
            <orderId>84EC371D-40CA-455E-A0FA-7EA733E9BFD3</orderId>
            <ordertotal>0.0</ordertotal>
            <camelAddedHdrField>0.0</camelAddedHdrField>
         </return>
         <return>
            <customerOrderNumber>1</customerOrderNumber>
            <orderId>54712493-2172-4ADB-814B-BC7AA0BB72C3</orderId>
            <ordertotal>0.0</ordertotal>
            <camelAddedHdrField>0.0</camelAddedHdrField>
         </return>
         <return>
            <customerOrderNumber>1</customerOrderNumber>
            <deliverydate>2013-02-06T00:00:00+05:30</deliverydate>
            <orderDetails>
               <itemPrice>565.0</itemPrice>
               <itemQty>1</itemQty>
               <itemUnit>0</itemUnit>
               <orderDetailsId>9A5030BE-F95F-4C62-B5A2-41FF85423218</orderDetailsId>
               <camelAddedDtlField>0.1</camelAddedDtlField>
            </orderDetails>
            <orderDetails>
               <itemPrice>4.0</itemPrice>
               <itemQty>90</itemQty>
               <itemUnit>0</itemUnit>
               <orderDetailsId>65A8B3BE-D407-43D8-8754-EA1E26AA56E4</orderDetailsId>
               <camelAddedDtlField>0.1</camelAddedDtlField>
            </orderDetails>
            <orderId>0BDCB222-0117-47A9-8813-DF03A1D19E5E</orderId>
            <ordertotal>0.0</ordertotal>
            <camelAddedHdrField>0.0</camelAddedHdrField>
         </return>
         <return>
            <customerOrderNumber>1</customerOrderNumber>
            <orderId>8E4220DC-884B-47BC-A565-E26B80BA5249</orderId>
            <ordertotal>0.0</ordertotal>
            <camelAddedHdrField>0.0</camelAddedHdrField>
         </return>
         <return>
            <customerOrderNumber>1</customerOrderNumber>
            <deliverydate>2013-02-06T00:00:00+05:30</deliverydate>
            <orderDetails>
               <itemPrice>10.0</itemPrice>
               <itemQty>4</itemQty>
               <itemUnit>0</itemUnit>
               <orderDetailsId>5A2DF895-BB0F-4039-80DB-F44CED31697B</orderDetailsId>
               <camelAddedDtlField>0.1</camelAddedDtlField>
            </orderDetails>
            <orderDetails>
               <itemPrice>20.0</itemPrice>
               <itemQty>3</itemQty>
               <itemUnit>0</itemUnit>
               <orderDetailsId>8034FBF4-B573-4B19-BDF5-FAF6C4247A55</orderDetailsId>
               <camelAddedDtlField>0.1</camelAddedDtlField>
            </orderDetails>
            <orderId>60161E3E-3C4A-4CE6-AAC3-E4D2BC240046</orderId>
            <ordertotal>0.0</ordertotal>
            <camelAddedHdrField>0.0</camelAddedHdrField>
         </return>
      </ns2:fetchOrderListResponse>
   </soap:Body>
</soap:Envelope>

XSLT is

<xsl:output method="xml" indent="yes" />

<xsl:template match="*|@*">
    <xsl:copy>
        <xsl:apply-templates select="*|@*" />
    </xsl:copy>
</xsl:template>

<xsl:template match="return">
    <xsl:copy>
        <xsl:copy-of select="@*|*" />
        <ordertotal><xsl:call-template name="calculate-total" /></ordertotal>
    </xsl:copy>
</xsl:template>

<!-- Recursive template -->
<xsl:template name="calculate-total">
    <!-- Select by default the set of orderDetails from the current context -->
    <xsl:param name="orderDetails"
               select="orderDetails" />
    <!-- Param which is going to keep track of the result step by step -->
    <xsl:param name="total"
               select="'0'" />

    <xsl:choose>
        <!-- If we have remaining order details, recurse -->
        <xsl:when test="$orderDetails">
            <xsl:call-template name="calculate-total">
                <!-- Remove the current element for the next step -->
                <xsl:with-param name="orderDetails"
                                select="$orderDetails[position() > 1]" />
                <!-- Do the partial operation for the current element, and continue to the next step -->
                <xsl:with-param name="total"
                                select="$total + ($orderDetails[1]/itemPrice * $orderDetails[1]/itemQty)" />
            </xsl:call-template>
        </xsl:when>
        <!-- Output the result -->
        <xsl:otherwise>
            <xsl:value-of select="$total" />
        </xsl:otherwise>
    </xsl:choose>

</xsl:template>

Response XML Is showing with duplicate tag is
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <ns2:fetchOrderListResponse xmlns:ns2="http://impl.lob.wipro.com/">

         <return>
            <customerOrderNumber>1</customerOrderNumber>
            <orderDetails>
               <itemPrice>50.0</itemPrice>
               <itemQty>2</itemQty>
               <itemUnit>0</itemUnit>
               <orderDetailsId>37516016-D71B-4790-951F-55D00B0CC159</orderDetailsId>
               <camelAddedDtlField>0.1</camelAddedDtlField>
            </orderDetails>
            <orderDetails>
               <itemPrice>39.0</itemPrice>
               <itemQty>3</itemQty>
               <itemUnit>0</itemUnit>
               <orderDetailsId>6095ABC7-0D0D-4B2E-92E5-80F24E9092B8</orderDetailsId>
               <camelAddedDtlField>0.1</camelAddedDtlField>
            </orderDetails>
            <orderId>84EC371D-40CA-455E-A0FA-7EA733E9BFD3</orderId>
            <ordertotal>0.0</ordertotal>
            <camelAddedHdrField>0.0</camelAddedHdrField>
            <ordertotal>217</ordertotal>
         </return>
         <return>
            <customerOrderNumber>1</customerOrderNumber>
            <orderId>54712493-2172-4ADB-814B-BC7AA0BB72C3</orderId>
            <ordertotal>0.0</ordertotal>
            <camelAddedHdrField>0.0</camelAddedHdrField>
            <ordertotal>0</ordertotal>
         </return>
         <return>
            <customerOrderNumber>1</customerOrderNumber>
            <deliverydate>2013-02-06T00:00:00+05:30</deliverydate>
            <orderDetails>
               <itemPrice>565.0</itemPrice>
               <itemQty>1</itemQty>
               <itemUnit>0</itemUnit>
               <orderDetailsId>9A5030BE-F95F-4C62-B5A2-41FF85423218</orderDetailsId>
               <camelAddedDtlField>0.1</camelAddedDtlField>
            </orderDetails>
            <orderDetails>
               <itemPrice>4.0</itemPrice>
               <itemQty>90</itemQty>
               <itemUnit>0</itemUnit>
               <orderDetailsId>65A8B3BE-D407-43D8-8754-EA1E26AA56E4</orderDetailsId>
               <camelAddedDtlField>0.1</camelAddedDtlField>
            </orderDetails>
            <orderId>0BDCB222-0117-47A9-8813-DF03A1D19E5E</orderId>
            <ordertotal>0.0</ordertotal>
            <camelAddedHdrField>0.0</camelAddedHdrField>
            <ordertotal>925</ordertotal>
         </return>
         <return>
            <customerOrderNumber>1</customerOrderNumber>
            <orderId>8E4220DC-884B-47BC-A565-E26B80BA5249</orderId>
            <ordertotal>0.0</ordertotal>
            <camelAddedHdrField>0.0</camelAddedHdrField>
            <ordertotal>0</ordertotal>
         </return>
         <return>
            <customerOrderNumber>1</customerOrderNumber>
            <deliverydate>2013-02-06T00:00:00+05:30</deliverydate>
            <orderDetails>
               <itemPrice>10.0</itemPrice>
               <itemQty>4</itemQty>
               <itemUnit>0</itemUnit>
               <orderDetailsId>5A2DF895-BB0F-4039-80DB-F44CED31697B</orderDetailsId>
               <camelAddedDtlField>0.1</camelAddedDtlField>
            </orderDetails>
            <orderDetails>
               <itemPrice>20.0</itemPrice>
               <itemQty>3</itemQty>
               <itemUnit>0</itemUnit>
               <orderDetailsId>8034FBF4-B573-4B19-BDF5-FAF6C4247A55</orderDetailsId>
               <camelAddedDtlField>0.1</camelAddedDtlField>
            </orderDetails>
            <orderId>60161E3E-3C4A-4CE6-AAC3-E4D2BC240046</orderId>
            <ordertotal>0.0</ordertotal>
            <camelAddedHdrField>0.0</camelAddedHdrField>
            <ordertotal>100</ordertotal>
         </return>
      </ns2:fetchOrderListResponse>
   </soap:Body>
</soap:Envelope>

A: You have to follow the same idea from the question that you posted here: XSLT - Updating the Header
Instead of matching result, match ordertotal and change the XPath expression to select the
orderDetails elements.
So, change this:
<xsl:template match="return">
    <xsl:copy>
        <xsl:copy-of select="@*|*" />
        <ordertotal><xsl:call-template name="calculate-total" /></ordertotal>
    </xsl:copy>
</xsl:template>

To:
<xsl:template match="ordertotal">
    <xsl:copy>
        <xsl:call-template name="calculate-total">
            <xsl:with-param name="orderDetails"
                            select="../orderDetails" />
        </xsl:call-template>
    </xsl:copy>
</xsl:template>

Then you can remove from the calculate-total template the default value for the first parameter, removing the select="orderDetails" attribute.
Besides because you are not using the copy-of element, you have to change the identity template to:
<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
</xsl:template>

So the complete stylesheet would be:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml" indent="yes" />

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="ordertotal">
        <xsl:copy>
            <xsl:call-template name="calculate-total">
                <xsl:with-param name="orderDetails"
                                select="../orderDetails" />
            </xsl:call-template>
        </xsl:copy>
    </xsl:template>

    <xsl:template name="calculate-total">
        <xsl:param name="orderDetails" />
        <xsl:param name="total"
                   select="'0'" />

        <xsl:choose>
            <xsl:when test="$orderDetails">
                <xsl:call-template name="calculate-total">
                    <xsl:with-param name="orderDetails"
                                    select="$orderDetails[position() > 1]" />
                    <xsl:with-param name="total"
                                    select="$total + ($orderDetails[1]/itemPrice * $orderDetails[1]/itemQty)" />
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="$total" />
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

</xsl:stylesheet>


text:
Q: string passing error using json.decode in flutter I'm saving a string of this format "[{text: drding4disruption.com, quantity:10.0}, {text: google.com, quantity:6.0}]"
so reading some tutorials I got to know that we can use json.convert method to parse  a string but here i'm getting
I did try to use json.decode(the_string); but It shows this error
FormatException: Unexpected character (at character 3)
E/flutter (14216): [{text: 4 medium size potatoes (boiled, peeled), quantity: 4.0, measure: <u...
E/flutter (14216):   ^
E/flutter (14216):

how do I parse it so that I can access the map as well

A: Save the string in this format by adding double quote to fields and string values :
[
   {
      "text":"drding4disruption.com",
      "quantity":10
   },
   {
      "text":"google.com",
      "quantity":6
   }
]

Finally decode it:  json.decode(the_string);
To consume it as YAML syntax take a look to this yaml package

A: Use the import 'dart:convert' library and do it as following:
From JSON list to String
final String listAsString = jsonEncode(list);

From String to JSON list, simply reverse
final List list = jsonDecode(listAsString);

Make sure your JSON map keys and values are quoted like this
var list = [{"text": "drding4disruption.com", "quantity":10.0}, {"text": "google.com", "quantity":6.0}];


text:
Q: Organizar el ID de un conjunto de elementos añadidos dinámicamente al eliminar uno de ellos con Jquery / Javascript necesito su ayuda, tengo la siguiente funcion que esta asociada a un boton que tiene onclick="addPageNew()" esta funcion crea elementos con su respectivo ID dinámicamente uno abajo del otro con Jquery, codigo:
function addPageNew(){

let idPageNew = generarID();

//aqui cuento la cantidad de elementos en el dom que tienen la clase '.page-edit' para poder crear un id consecutivo.

let contador = $('.page-edit').length + 1;

//template
let newPageHTML = `

Página ${contador} -

Agregar título

`;

contentPageMain.append(newPageHTML);

}

Y elimino esos elementos con la siguiente funcion:
function deletePage(idDeletePage){

let deletePage = $('#'+idDeletePage);

$(deletePage).animate({
    opacity: 0,
  }, 'fast', 'linear', function() {
    $(this).remove();
  });

  }

El problema es el siguiente:

Si agrego 3 elementos dinamicamente entonces pasaria esto:

elemento 1 con id: page1 y nombre pagina 1
elemento 2 con id: page2 y nombre pagina 2
elemento 3 con id: page3 y nombre pagina 3

Todo bien hasta ahi.
Pero:
Si elimino el segundo elemento con id: page2
entonces la secuencia de paginas quedaria de la siguiente manera:

elemento 1 con id: page1 y nombre pagina 1
elemento 3 con id: page3 y nombre pagina 3

Conclusion:
Como podria hacer yo para que cada que vez se elimine un elemento, la enumacion de id se vuelva a poner en un orden ascendente? 1, 2, 3, 4 ,5, etc.
Ojala me puedan ayudar! gracias.

Lo de arriba ya lo pude resolver gracias a Alvaro!

EDIT:
resulta que yo guardo el contenido de cada pagina, y yo lo hacia con esta funcion:
function autoGuardado(){

   var countPagesAutoguardado = $('.page-edit').length;

   var contentPagesArrayAutoguardado = [];
   var objeto = {};

   for(var i = 1; i <= countPagesAutoguardado; i++) {

       contentPagesArrayAutoguardado.push({
          "pagina" : $('#page'+i).html()
       });

   }
   objeto.datos = contentPagesArrayAutoguardado;

   let dataInformeAutoguardado = new FormData($("#formInforme")[0]);
   dataInformeAutoguardado.append("numPages", countPagesAutoguardado);
   dataInformeAutoguardado.append("contentPagesArray", JSON.stringify(objeto));

}

Como se pueden dar cuenta, guardo el contenido de cada pagina, mediante un for(){} y recorro cada pagina con su id mas el iterador, osea: page1, page2, page3

El problema ahora es:

Si yo tengo 3 elementos:

elemento 1 con id: page1 y nombre pagina 1
elemento 2 con id: page2 y nombre pagina 2
elemento 3 con id: page3 y nombre pagina 3
Y elimino el 2, entonces ya no existiria la pagina con el id, page1.
por lo que el contador solo va a encontrar 2 elementos con la clase .page-edit y el contenido de la pagina 3 se va a quedar excluido, por que la pagina 3 pasaria a ser la 2, alguna recomendacion?

A: Como te ponía en los comentarios, los IDs no deben usarse para dar sentido a un elemento, deberían ser cadenas "opacas" como se especifica en el estándar HTML (enlace en inglés). En tu caso estás intentado usar el ID para dar sentido a un elemento, especificando su orden.
Una alternativa a esto sería usar los contadores CSS para especificar el número de página. Para ello resetearías el contador al principio y por cada página (con la clase .page-edit-full) incrementas el contador y lo usas en el ::before o ::after para mostrar el valor.
Aquí puedes ver un ejemplo funcionando:

Nota: he creado mi propia función que genera IDs "aleatorios" y he borrado las referencias a los contadores.

function generarID() {
  return "id" + Math.floor(Math.random() * 1000000);
}

function deletePage(idDeletePage) {
  let deletePage = $('#' + idDeletePage);

  $(deletePage).animate({
    opacity: 0,
  }, 'fast', 'linear', function() {
    $(this).remove();
  });

}

function addPageNew() {

  let idPageNew = generarID();

  //aqui cuento la cantidad de elementos en el dom que tienen la clase '.page-edit' para poder crear un id consecutivo.

  const contentPageMain = $("#contentPageMain");

  //template
  let newPageHTML = `

Página

Agregar título

            Borrar

`;

  contentPageMain.append(newPageHTML);
}
body {
  counter-reset: pagina;
}

.page-edit-full {
  counter-increment: pagina;
}

.page-number-label::after {
  content: counter(pagina);
}

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<button onclick="addPageNew()">Add New Page</button>


text:
Q: To get OpenCV VideoWriter work across platforms consistently for MP4 container with H264 encoding I am trying to get OpenCV VideoWriter work across platform consistently for MP4 container with H246 encoding.
Target platforms in order of importance - Ubuntu, Raspbian, OSX
Basically, my shortcoming at this point is not understanding the relationship of FourCC code (as a parameter to OpenCV VideoWriter) to the FFMPEG backend and its requirements. I am interested to understand the game in play rather than discussing a piece of code.
What I want to know is when I specify 'X264' as FourCC code trying to write an x.MP4 file (FFMPEG backend) and the request is marshalled to FFMPEG what requirements/dependencies need to be satisfied by the OS for it to success.
So far I have got my python stack writing MP4 video files across Raspbian/Ubuntu/OSX, with a hack.
On my Raspbian stretch installation, I use 0x00000021 as the fourCC code.
On Ubuntu (VM on OSX) and on OSX, AVC1 works.
Days of Googling only delivered those hacks, not a good understanding of the problem.
The x264 as FourCC code leads to one of - failure, non-portable video file + annoying FFMPEG warning.
I am trying to get to the bottom of it.
The code,
    #self.__fourCC = cv2.VideoWriter_fourcc('x', '2', '6', '4')
    self.__fourCC = cv2.VideoWriter_fourcc('a', 'v', 'c', '1')
    if PlatformUtils.isRunningOnRaspberryPi():
        self.__fourCC = 0x00000021

I have control over the version both OpenCV and FFMPEG (if required GStreamer too). I can and have built them for Ubuntu/Raspbian.


text:
Q: How to prevent down button in Listbox in C#? I have a form with a Listbox listing files. I added a KeyPress event with two shortcuts: 'd' (delete), which deletes the file (on disk) and 'k' (keep) which keeps the file (on disk). Both shortcuts remove the selected entry from the list. As a last statement, I added the following in my code to select the first index:
if (lstEntries.Items.Count > 0)
{
    lstEntries.SelectedIndex = 0;
}

Everything works fine, except when I press 'd', the SelectedIndex changes to 1 instead of 0, which I found very odd. I changed the shortcut to 'r' (for 'remove' instead of 'delete') and now everything works perfectly (the first item gets selected as expected).
Without the Keypress event, I noticed that everytime I press 'd' on my ListBox, it drops down one index. Is this default behaviour? There is nothing in my code to handle a 'd' keypress anymore.
If I set a breakpoint on the selectedindexchanged event, I notice when I press 'd' that the call to change the selectedindex does not originate from within my code, but from the controls, which leads me to believe this is some kind of default behaviour.
So basically: how can I prevent button 'd' from moving the index one down?
Thanks!


text:
Q: When I add items to my cart I can only add 9 items and item added to fire base but not shown in my cart page
When I add items to my cart I can only add 9 items and item added to fire base are not shown in my cart page