text:
Q: Specify Google Task ID on insert I am working with Google Tasks, using the PHP library:
https://developers.google.com/tasks/v1/reference/tasks
I am trying to insert a task with a custom ID.
I found this topic:
Setting id to task using Google Task API returns 400 invalid value
which points to this topic:
Google tasks update error
They suggest to send the Task ID with the Task title. I think I have done that.
This is the code info from the Google API reference
$task = new Task();
$task->setTitle('New Task');
$task->setNotes('Please complete me');
$task->setDue(new TaskDateTime('2010-10-15T12:00:00.000Z'));

$result = $service->insertTasks('@default', $task);
echo $result->getId();

This is my code, I got setID() from the library itself.
$taskNew = new Google_Service_Tasks_Task();
$taskNew->setId('2013');
$taskNew->setTitle('Notify');
$taskNew->setDue(new TaskDateTime('2018-10-27T00:00:00.000Z'));

$results3 = $service->tasks->insert('.....', $taskNew);

I keep getting an error and it refuses to make the task.
Using this API tool:
https://developers.google.com/apis-explorer/#p/tasks/v1/tasks.tasks.insert
I can insert tasks successfully, so long as the system makes the ID. The Google Task API will insert the task, but assign its own ID.
If I specify a custom ID, then I get a 400 error "Invalid value".
I am making tasks to correspond to events saved in my program's database. I need to be able to find the task that matches a database event when I need to make changes to the due date or completed.
The reason I want to set my own ID, is so I can find the specific task and make changes.
I could add a new field to the database with the ID that google generates. But I would prefer to not have to change the database and the rest of the program as well.
Thanks so much for any help,
- Jon

A: Task Id is the read-only parameter.
I solved this question by using a prefix for the task`s Title.
For example: "[my_id] Task Title".


text:
Q: Naive Bayes Ticket Classification Python I currently have a CSV export from our ticketing system with two columns.
Short Description and Class.
Both are created by the agent when logging a ticket.
eg

*

*Data Backup is not working,Backup

*Email change in Groups,Notes

*backup directory not found,Backup

*Email > Global - Lotus Notes,Notes

I have been asked to write a Naive Bayes program using Python that will read the short description in a CSV file and then decide how it should be classified.
I have 329 tickets that have been classified into 6 different classes.
The following is a count of each:

*

*Class1 60

*Class2 77

*Class3 65

*Class4 16

*Class5 18

*Class6 93

I was thinking I would have to create 6 different dictionaries (one for each class) containing all the words used in the short description, excluding the usual !"£$%^&*()<>,./?:;@'#~][{}
Then when I run the program it will tokenize the short description using nltk and compare it to all the dictionaries and whatever one has the highest matches will determine the class.
Am I going about this the right way?
How many tickets should I be using for my sample?
The following is what I have at the moment. It basically runs through a csv file named after a class and then outputs another file with punctuation removed, all the words in lower case and in separate cells.
This data will then be used as a dictionary.
I'm not sure if I'm going about this whole thing the right way though.
import csv
from nltk.tokenize import RegexpTokenizer

#Read CSV
readFile = open ('Backup.csv', 'r')
csv.readFile = csv.reader(readFile)

resultFile = open ('result.csv', 'w')
wr = csv.writer(resultFile)

#removes punctuation
tokenizer = RegexpTokenizer(r'\w+')

#for every row in file tokenize and covert to lowercase
#write tokenized words to a .csv file.
for row in csv.readFile:
    wr.writerow(tokenizer.tokenize(row[0].lower()))

readFile.close()
resultFile.close()

EDIT:
I have now started using the following which takes in the data from my two column csv file:
from textblob.classifiers import NaiveBayesClassifier
from textblob import TextBlob

with open('train.csv', 'r') as fp:
     cl = NaiveBayesClassifier(fp, format="csv")

print(cl.classify("backup"))  # "Backup"
print(cl.classify("Lotus Notes."))   #"Lotus"
etc..

Pretty sure I just need to get a better sample size of training and test data and then I will feed in a csv of short descriptions then update it with the class that has been calculated.
From a functionality point of view it seems to work unless I've made any glaring mistakes?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pass value from button to the method in Dialog - React I have a dialog in React which displays some information and has 2 buttons Proceed and Cancel.
If the Cancel button is clicked the Dialog closes ( working fine)
But if the Proceed button is clicked I want to send the flag to the original method from where this dialog open command was sent to proceed and complete the action.
<Dialog {...reProps} ref={(x) => { this.restriced = x; }}>

   SOME INFORMATION

Do you want to apply profile to the rest of the devices.

        <button onClick={this.handleCancel}>
        Cancel
        </button>
        <button onClick={this.handleProceed}>
        Yes
        </button>

</Dialog>

onProfileApply(profileName, restrict) {
    if (!_.isEmpty(devices)) {
        _.forEach(devices, (device) => {
            if (restrictedDevices.length !== 0) {
                return this.setState({
                    restrictedDevices
                }, () => {
                    this.restriced.open();
                });
            }
        }
            const APIBody = {
            'devices': selectedDevices
        };

        return this.props.dispatch(actions.updateDevices(APIBody));
    }
    return null;
}

 handleCancel() {
    this.restriced.close();
}

handleProceed() {

}

I want this action to be executed when the user clicks Proceed button but the information is not available outside the onProfileApply function.
return this.props.dispatch(actions.updateDevices(APIBody));

Is there any chance I can go back to the function and execute this if the flag is true or something. Please help.


text:
Q: How to set the hostname and private key of an X509Certificate2 object? (.NET4.6) I have to consume an API that requires a mTLS certificate. There is a .crt, .key files and a hostname. The key is a private key that starts with "-----BEGIN PRIVATE KEY-----"...
In postman I did this and it did worked:
Postman print
My code is like this now:
string privateKey = File.ReadAllText(@"D:\privatekey.key");

var certificate = new X509Certificate2(@"D:\somefile.crt");

// Add the key and the hostname?

HttpClientHandler handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);

HttpClient client = new HttpClient(handler);

How/Where can I add the key and the "host-name.com"?


text:
Q: What is this red glowing thing I've found in Terraria? I just started playing Terraria, so forgive me if this is obvious. When mining, I found a cave with water, and at the bottom of the pool I found this strange red glowing block.

I don't think it's crimtane, as (correct me if I'm wrong) it only spawns in Crimson biomes. Could someone tell me what this is? I can't mine it, but I'm using a "candy cane pick" I found in my inventory. (Guessing christmas)

A: That's a Crimson Altar, the crimson alternative to the Demon Altar.
It's used as a crafting station to make most pre-hardmode boss items, and Night's Edge.
If you attempt to break it before defeating Wall of Flesh or with a hammer of lesser quality to the Pwnhammer, it will damage you for half of your health.


text:
Q: How to render ionic menu hover WebView? I want to render my app menu hover Web View
enter image description here
I can able to run web view as a js function window.open or Cordova.open
But its comes without App Menu, how to achieve it ?
Slider Menu with Window.open Webview?
I have directive menu , this angular js directive menu how to run on window.open method ?


text:
Q: Can RS485 be considered a multi-master bus? There are some electrical specifications specifically designed for multi-master protocols such as CAN, I2C, 1-Wire, etc. which are classified under CSMA/CD networks.
However, RS485 has a push pull output (with a current limit guard) so when two masters are started sending data at the same time, both frames will  be corrupted and the re-transmission should be handled by the protocol stack. RS485 can be classified under CSMA/CA networks.
Question
Is only protocols implemented on top of CSMA/CD networks considered as "multi master protocols" or can any protocol on CSMA/CA network that somehow implements handshake (ACK) and re-transmission features be considered as a "multi master protocol"?
Specifically, is implementing a multi-master protocol on top of RS-485 possible, or is it considered only a workaround because of the inability of collision detection nature of the bus?

A: RS485 is purely a physical layer specification. You need your own protocol for anything you run over it eg home made, or something like MODBUS. Normally I would have just one master that requests information from connected devices. For anything multimaster or more complex the use a different bus eg CAN or Ethernet


text:
Q: How to cast a dynamic object to a type and compare I have a model called products,
public class Product
{
    public string Name { get; set; }

    public string Sku { get; set; }

    public float Cost { get; set; }

    public string Description { get; set; }
}

I will get a list of objects as type dynamic from externel source as follows
string query = "SELECT Id,Name,KNDYCPQ__Description__c,KNDYCPQ__ProductCode__c FROM KNDY4__Product__c";
List<dynamic> products = new List<dynamic>();
products = await SalesforceSyncProvider.QueryAsync(query);
foreach (var x in products)
{
    Product product = new Product();
    if (db.Products.Where(a => a.Sku ==x.KNDYCPQ__ProductCode__c).FirstOrDefault() != null) {

    product.Name = x.Name;
    product.Sku = x.KNDYCPQ__ProductCode__c;
    product.Description = x.KNDYCPQ__Description__c;
    product.Cost = 2000;
    db.Products.Add(product);
    }
}

So, before adding to my db, I want to check the product code (KNDYCPQ__ProductCode__c) with my Sku for avoiding duplicates but the if condition is failing and showing the error that, an expression tree may not contain a dynamic operation.

A: Put x.KNDYCPQ__ProductCode__c in a strongly typed variable and use that in the expression.
string sku = x.KNDYCPQ__ProductCode__c;

if (db.Products.Where(a => a.Sku == sku).FirstOrDefault() != null) {

//...


text:
Q: Is it safe to use multiple ScanFilters with BluetoothLeScanner? Our Android app uses BluetoothLeScanner.startScan() to scan for a single GATT Service UUID using a single ScanFilter today. We are now about to update the app to scan for multiple UUIDs by using multiple ScanFilters, one per UUID.
According to the docs this should work just fine and we also didn't experience any issues when testing on some recent phones so far. However, it's known, that the Bluetooth stack differs significantly among different Android phones (vendors, models, versions) and that it's sometimes quite bugy, especially on older phones. So my question is: How likely is it, that the intended change will cause problems on any devices that successfully run our app today? Will we have to expect, that scanning for BLE devices will stop working on any of our customers phones? Are there any known issues? I'm aware, that it might not be possible to give a reasonable answer for devices running custom ROMs, but what about the broad majority of phones running official ROMs?
We're supporting Android devices with API level >= 21.


text:
Q: Magento 2, new widget with image chooser parameter, does not save picture I create a new widget and one of the parameters is a picture chooser, I just use this  code. Everything looks well. I can open media folder and choose the picture I want to use. When I choose the picture, the picture field on the form is filled with this value:

http://local.magento.com/admin/cms/wysiwyg/directive/___directive/e3ttZWRpYSB1cmw9Ind5c2l3eWcvcHVycGxlLmpwZyJ9fQ,,/key/4c150d984998702b74709bb8f05820aff2f85a968d47e50f9638b7d2a7b1ced3/

But when I save the form widget data, the picture field has this value:
{{media url=
nothing more. How can I solve this?

A: If you want to upload an image then why don't you use image selection button.?
If you like the editor then use it.But it is not a proper way to upload an image using an editor.You can use the button instead.                                                                   If you don't know how to do it.                                                   Let me explain.
Here is my code.
The below code is written in block file which creates a button.
$fieldset->addField(
        'image',
        'file',
        [
            'name' => 'image',
            'label' => __('Image'),
            'title' => __('Image'),
        ]
    );

Image is the database field name. In your case it's wysiwyg editor.I don't know the exact but once check in your database.
The below code is used to save the image in your table. Now put this code into your Controller.
<?php
namespace Vendor\Module\Controller\Adminhtml\Slider;

use Magento\Framework\App\Filesystem\DirectoryList;

class Save extends \Magento\Backend\App\Action

{

protected $_mediaDirectory;
protected $_fileUploaderFactory;

public function __construct(
    \Magento\Backend\App\Action\Context $context,
    \Magento\Framework\Filesystem $filesystem,
    \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory
)
{
    $this->_mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
    $this->_fileUploaderFactory = $fileUploaderFactory;
    parent::__construct($context);
}

public function execute()
{
    /*For Image Upload*/

    /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
    $resultRedirect = $this->resultRedirectFactory->create();

    try{
        $target = $this->_mediaDirectory->getAbsolutePath('imagefolder/');

        $targetOne = "imagefolder/";
        /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
        $uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']);
        /** Allowed extension types */
        $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png', 'zip', 'doc']);
        /** rename file name if already exists */
        $uploader->setAllowRenameFiles(true);
        /** upload file in folder "mycustomfolder" */
        $result = $uploader->save($target);
        /*If file found then display message*/
        if ($result['file'])
        {
            $this->messageManager->addSuccess(__('File has been successfully uploaded'));
        }
    }
    catch (Exception $e)
    {
        $this->messageManager->addError($e->getMessage());
    }
    /*For Image Upload Finished*/

    $data = $this->getRequest()->getPostValue();

    $data['image'] = $targetOne.$result['file'];

    if (!$data) {
        $this->_redirect('*/*/filenaem');
        return;
    }
    try {

        $rowData = $this->_objectManager->create('Vendor\Module\Model\Slider');

        $rowData->setData($data);

        if (isset($data['id']))
        {
            $rowData->setEntityId($data['id']);
        }
        $rowData->save();
        $this->messageManager->addSuccess(__('Row data has been successfully saved.'));
    }
    catch (Exception $e)
    {
        $this->messageManager->addError(__($e->getMessage()));
    }
    $this->_redirect('*/*/index');

    return $this->resultRedirectFactory->create()->setPath(
        '*/*/upload', ['_secure'=>$this->getRequest()->isSecure()]
    );
}

/**
 * Check Category Map permission.
 *
 * @return bool
 */
protected function _isAllowed()
{
    return $this->_authorization->isAllowed('Vendor_Module::Module_list');
}

}
After that you want to called it in phtml for the result..so bellow code write in phtml file.
Here is code.
    $collection = $block->getCollectionFor();
    $_objectManager = \Magento\Framework\App\ObjectManager::getInstance(); //instance of\Magento\Framework\App\ObjectManager
    $storeManager = $_objectManager->get('Magento\Store\Model\StoreManagerInterface');
    $currentStore = $storeManager->getStore();
//Base URL for saving image into database.
    $mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

getCollectionFor() is write in my block.so according to that, you should apply as your block file.
I hope this is helpful to you.     If you have any query let me know.

A: I have checked the code and found that the code to getting the image URL from the directory is not included. You have to work on it to solve this problem. The code to include the image URL is missing.

A: Looks like this is a known issue in Magento 2.1. Here is a link to their github for further info on the topic.  https://github.com/magento/magento2/issues/6138
It appears there might be a few different fixes to try.

A: By using jquery, we can save the image to a folder.
In script, write this code
<script>
    function file_up(id)
    {
        var up_id = 'uploadfiles'+id;
        var upremv_id = 'upload'+id;
        var files = document.getElementById(up_id).files;
        for (var i = 0; i < files.length; i++)
        {
            uploadFile(files[i],up_id,upremv_id);
        }
    }
    function uploadFile(file,up_id,upremv_id){
        var url = "<?php echo $baseurl ?>helloworld/index/upload";
        var xhr = new XMLHttpRequest();
        var fd = new FormData();
        xhr.open("POST", url, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                jQuery('#imgna'+up_id).val(xhr.responseText);
                console.log(xhr.responseText); // handle response.
                jQuery('#'+up_id).remove();
                jQuery('#'+upremv_id).remove();
                var img_va = '<img class="image" src="<?php echo $mediaUrl.'custom/'?>'+xhr.responseText+'">';
                jQuery('#pre'+up_id).html(img_va);
            }
        };
        fd.append('uploaded_file', file);

</script>

Then, in your custom controller:
Class Upload extends \Magento\Framework\App\Action\Action
{
public function __construct(\Magento\Framework\App\Action\Context $context)
{
    parent::__construct($context);
}

public function execute()
{
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    $fileSystem = $objectManager->create('\Magento\Framework\Filesystem');
    $mediaPath = $fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath();
    $media = $mediaPath . 'custom/';

    //  exit;

    $file_name = rand() . $_FILES['uploaded_file']['name'];
    $file_size = $_FILES['uploaded_file']['size'];
    $file_tmp = $_FILES['uploaded_file']['tmp_name'];
    $file_type = $_FILES['uploaded_file']['type'];

    if (move_uploaded_file($file_tmp, $media . $file_name)) {
        echo $file_name;
    } else {
        echo "File was not uploaded";
    }
}

}
please refer How to save a image upload to a folder in magento2?
And by using observer, you can get the value of the image in post..In the input field tag use data-form-part="product_form".

A: You can review last commit and create path for it on github and try to apply it
https://github.com/magento/magento2/commit/ba6612462c260da7cc534b6365623993a6fe4311


text:
Q: Should I never call HostingEnvironment.UnregisterObject? While trying to implement asyncronous email over smtp in my ASP.Net MVC 3 application I've come around SO SmtpClient.SendAsync blocking my ASP.NET MVC Request thread. There I found the article by Phil Haack: The Dangers of Implementing Recurring Background Tasks In ASP.NET which provides a way to avoid crashing of the background thread on AppDomain shutdown.
The article says to call HostingEnvironment.RegisterObject(this); on the constructor and call HostingEnvironment.UnregisterObject(this); only if IRegisteredObject.Stop Method is called.
In a general scenario, when requests arrive permanently, and the scope of the object implementing IRegisteredObject is request, dosn't this approach register objects within each request (utilizing the email functionality) and does not unregister any?
Is it OK? Or should I also unregister after the asynchronous operation completed?
P.S.: as suggested by Damian Edwards in the linked SO question, I use ThreadPool.QueueUserWorkItem to send the email beyond request scope.

A: I'm not sure what you mean by requests arrive permanently, scope of the object ... is request etc.
Request Scope, permanent, and ThreadPool.QueueUserWorkItem; these words together do not make sense at all. One uses ThreadPool.QueueUserWorkItem so that a request does not take forever. The time-consuming job is done in the background while your request returns immediately as Damian Edwards suggests.
I have used IRegisterObject to send bulk e-mails upon a request received. However, in my case, I have used a singleton object EmailSender that implements IRegisterObject. In that case, it is registered once in the constructor and unregistered once in Stop().
So, in short, please use a singleton.


text:
Q: Fast binary reading and writing issue regarding 'conflicting' binary formats I am struggling with the processing of binary (file) data (in c#). This is the situation:

*

*I have a binary file that can be as small as 1 MB and as large as 60 GB, hence impossible to fit in memory (assume slow laptop with 2 GB ram, both running 32 and 64 bit windows). This file contains data from, for example, 20 sources along a time base. The file's header does not inform me about the length of the signals, meaning that the length of each signal can (and most of the wime will) differ. Therefore I do not know the amount of bytes that one signal contains on forehand. Also note that the data is unevenly spaced along the file. Therefore I have to search for identifiers (2 bytes) in the file that matches the corresponding signal sample.

*Secondly I need to process and store this data in a new binary file. The file size will be roughly the same. But the binary format is completely different. In fact it is a Matlab binary file format.
These are the challenges:

*

*Since the Matlab binary requires the signal length (given as the number of bytes) in the header of the signal I need to know the length on forehand. Or alternatively seek back in the written binary at the end and store the length then.

*The performance needs to be really good. Target is approaching the hard-disks r/w speed, hence CPU time needs to be low.

*Since the data will not fit in internal memory I need some sort block wise processing. But how to limit the block size correctly such that I will get no memory overflow exceptions while not sacrificing performance to much at the same time?

I already tried memory mapping of the file to read, but I am stuck with this since I would need to search along the complete file to know the length of the signals.
What would be a good approach to accomplish the above?

A: I would repeatedly scan the entire input file sequentially. Each pass through the file, I would collect as many "signals" in memory as memory can hold. Once the working memory buffer is full I would write the collected "signals" into an output Matlab file and start again to collect more signals with the next pass. Once no more new signals were found the algorithm ends.
This algorithm requires multiple passes over the data for big files but at least it is sequential IO which is rather fast.

A: How about a signal splitter? I would scan once through the file and create a new file for each new signal. During reading the huge file I would write the data to the right signal file. Memory is a non issue since you are always reading only one chunk from disk (about 4KB) which does not get you neary any memory boundary.
If you need some correlation between the signals you would need to insert some timepoint markers into the split files to analyze it time based. That should also be rather easy to do.
As added bonus you do know the signal length by reading its file length or if you do time based stuff I would write a header with the final signal length found during the splitting process.


text:
Q: Appending an input to a form AND a rendered element I have a form whose elements are formatted neatly in a table that's nested within the form tags, and I want to add another row to that table with a new input. How can I append that new input to both the form element (so that it's present in document.forms.formName and will submit with the form) AND to the new row's cell (so that it's rendered inside the row)?
Calling the appendChild method on the cell and the form element both just appends it to the last one called, rather than giving it a kind of dual membership. Is there some sort of append I can call from the form that doesn't interfere with how the element is rendered?
Edit: Woops, had the form nested inside the table, not vice versa. This doesn't work in Firefox 3.6 but does work in Internet Explorer 8.

A: If you just want a copy of an existing table row, just clone the entire row and add it to the table. If the table is in a form, the input will automatically be added to the form.
A trivial example:
<form ...>

<input name="foo">

</form>

<button onclick="
  var table = document.getElementsByTagName('table')[0];
  var tBody = table.tBodies[0]
  var newRow = tBody.rows[0].cloneNode(true);
  tBody.appendChild(newRow);
">Add a row</button>

Note that you will probably need to update the input's name and value and do some other tidying up, the above just shows the strategy.


text:
Q: How can I get to know if an Element can be seen by the user with Google Closure? I would like to write a java script that allows me to see the table headings of each column when at least one column of the table is visible. So I want an "excel-like" effect, when the user scrolls down a big table.
So I have to be able to check if an element is at the screen of the user at the moment. When he scrolls down long enough, the element "disappears" from his screen. How do I check that?
The only function I found was goog.style.isElementShown, but thats not what I want.
In jQuery it seems to be .scrollTop().

A: Try goog.style.getVisibleRectForElement.
If you look at jQuery source code, you will see that .scrollTop() just unify access to element/window scrollTop https://github.com/jquery/jquery/blob/master/src/offset.js#L264
For elements, you can just use scrollTop.
But scrollTop is probably not what you are looking for.


text:
Q: Unexpected IOCTL sent to my uclinux (ARM) driver(s) Having written my character drivers to use .unlocked_ioctl and a user-space app to test them I am getting an unexpected call to the ioctl function when the devices are opened from user-space.
The driver and app both use the same header file where I define "my" identifying character to be '8'.  A dev-err output message from the driver shows that the unexpected ioctl identifying character is 'T' (see below).
When running the test app, which opens both drivers but only targets one based on the command line arguments, the unexpected ioctl call shows up for each driver.
I wondered about a 'debug' kernel configuration for ioctl but could not find any setting like that.
The header file has the following:
#define RLY_IOCTL_BASE  '8'
#define IOC_RLY_GETLAST _IOR(RLY_IOCTL_BASE, 0, u8)
#define IOC_RLY_SETRELAYS _IOW(RLY_IOCTL_BASE, 1, u8)

The driver source has this in their respective ioctl callback functions:
if (_IOC_TYPE(cmd) != RLY_IOCTL_BASE) {
    dev_err(&RLYspi->dev,
        "IOCTL: cmd is not for us! (Ty=%c, num=%d, size=%d, dir=%d)\n",
            _IOC_TYPE(cmd), _IOC_NR(cmd), _IOC_SIZE(cmd), _IOC_DIR(cmd));
    return -EINVAL;
}
dev_info(&RLYspi->dev, "IOCTL: cmd num-%d, size=%d, dir=%x\n",
                            _IOC_NR(cmd), _IOC_SIZE(cmd), _IOC_DIR(cmd));

switch (cmd)

And the user-space test application has this for opening the /dev/x drivers to get file handles and descriptors:
afe_fp = fopen(AFE_DEVICE_NAME, "r");
if (NULL == afe_fp) {
    printf ("Could not open device %s!\n", AFE_DEVICE_NAME);
    return 1;
}

afe_fd = fileno (afe_fp);       /* Gets the file descriptor from fp */

/* Open dev/ame_sq_rly */
rly_fp = fopen(RLY_DEVICE_NAME, "r");
if (NULL == rly_fp) {
    printf ("Could not open device %s!\n", RLY_DEVICE_NAME);
    return 1;
}

rly_fd = fileno (rly_fp);       /* Gets the file descriptor from fp */

The calls are like this from the test application based on the command line arguments (one command shown):
if (IOBase == 8) {
    /* driverapp r b (read_command) */
    else if ((argc == 3) && ((argv[1][0] == 'r') || (argv[1][0] == 'R'))){
        ret = ioctl(rly_fd, IOC_RLY_GETLAST, &RlyVal);
        if (ret < 0) {
            perror("ioctl('IOC_RLY_GETLAST')");
            exit (EXIT_FAILURE);
        }

        printf ("Relay shifter last value: 0x%02X\n", RlyVal);
        return 0;
    }
}

I expect to just get the output from the accepted command from the driver (dev_info) and then the output from the printf in the test application.
When the driverapp (test application) is run I get the following console output:
# driverapp r 8
<device A info>: IOCTL: cmd is not for us! (Ty=T, num=1, size=0, dir=0)
<device B info>: IOCTL: cmd is not for us! (Ty=T, num=1, size=0, dir=0)
<device B info>: IOCTL: cmd num-0, size=1, dir=2
Relay shifter last value: 0x00
#

Both drivers (shown as 'device A' and 'device B' above) are called with the unexpected ioctl call on device open.  I tested this by just opening one of the devices instead of both and I only get one unexpected ioctl call for the driver that was opened.
Where are the two unexpected 'T' ioctl commands coming from?
Many thanks for any information.


text:
Q: Bootstrap3 Typeahead - Calling a function in 'Remote' I upgraded to Bootstrap version 3.0 and I do see that the typeahead module does not exist. I am using web services and I had used the following method to call my function and populate my dataset. However, with the twitter typeahead.js, how do I call my function or how do I still use the old typeahead module? Your help is much appreciated. Thanks.
            $("#searchVendor").typeahead({
            source: function (query) {
                    vieModel.callWebServiceFunctionList(counter1, query, isListCleared);
       });

A: Typeahead.js doesn't have a way of directly using a function as the source. The standard way to pass a query value is with a URL string containing %QUERY in the remote property:
$("#searchVendor").typeahead({
            remote: '.../data.json?name=%QUERY'
});

However, this probably isn't enough in your case. remote can also be an object, with a url and a replace function that is applied to the URL.
So, make a function like callWebServiceFunctionList that just returns the URL instead of actually calling the web service.
$("#searchVendor").typeahead({
            remote: {
               url: '.../data.json?counter=%COUNTER&query=%QUERY&isListCleared=%ISLISTCLEARED',
               replace: function(url, query) {
                  return url.replace('%COUNTER', counter1).replace('%QUERY', query).replace('%ISLISTCLEARED', isListCleared);
               }
});

See the docs for the remote object.
Alternatively, you could get the JS for just the typeahead portion of Bootstrap 2.x, and while you might run into problems with the formatting, it seems to work fine by itself (JSFiddle demo).


text:
Q: Difference between Mule's jms:consume and jms:listener Using Mule 4.4 on premise along with Apache ActiveMQ. I am trying to get a better understanding of how Mule handles messaging.
I tried searching the internet but am not finding any details about the same.
I have a jms:listener:
<jms:listener doc:name="Listener" config-ref="JMS_Config" destination="Consumer.mine2.VirtualTopic.mine.test">
    <jms:consumer-type >
        <jms:queue-consumer />
    </jms:consumer-type>
</jms:listener>

and I have a jms:consume:
<jms:consume doc:name="Consume"  config-ref="JMS_Config" destination="Consumer.mine1.VirtualTopic.mine.test">
    <jms:consumer-type >
        <jms:queue-consumer />
    </jms:consumer-type>
</jms:consume>

To me both seem to be doing the same job i.e. consume messages from a queue / topic. So why do we have these two components in Mule?

A: jms listener is a source, so using it you can trigger a flow whenever there is a new message in queue.

jms consume is an operation, so you can use it anywhere within a flow's execution, i.e. like a http request component that you put in the middle of a flow.

Both of them will consume a message from the queue/topic. However, when you are using a listener you are basically saying that "There is a queue, I do not know when a new message will come in, but whenever it comes I need to perform these actions"
When you use a consume operation, you are saying "I am expecting some message soon and with that I will to these actions".
Now in both cases a message may not come at all, and both have there own way to deal with it. A listener, since it is a source, will just not simply trigger the flow and keep on waiting. A consume will block your execution until a message is there, or you can configure a time out to not be blocked fore ever.
A common use case can be reprocessing messages from a DLQ. Generally when you use a queue, you also have a DLQ so that the messages that failed during processing, from the "main" queue, can be sent to the DLQ and reprocessed later.
Now, in this architecture, you will typically use the jms listener only with the main queue for the processing of the messages. And you will have a separate flow that can have a http listener so that you can trigger an HTTP Endpoint whenever you are ready to reprocess the messages from the DLQ. This flow with http listener with consume all the messages (probably in a loop) from the DLQ and publish them back to the main queue


text:
Q: Unable to executing multiple functions using multiprocessing module from a TKinter GUI Hi I have a small GUI which has a button using which two functions must be executed in different processors. In reality these two functions are heavy calculations. I do not want to use multi threading. I want them to run on 2 different processors. When I try to execute the button, another instance of the GUI gets created and it says
File "C:\Python3.7\lib\multiprocessing\reduction.py", line 60, in dump.
ForkingPickler(file, protocol).dump(obj)
TypeError: can't pickle _tkinter.tkapp objects

My code is as follows.
from multiprocessing import Process
from tkinter import Button, Tk, Frame

class GUI(Frame):

    def __init__(self):
        super().__init__()
        self.button = Button(self, text="Start", command=self.execute)
        self.button.pack()
        self.pack()

    def F1(self):
        print("Hello")

    def F2(self):
        print("World")

    def execute(self):
        self.P1 = Process(target = self.F1)
        self.P2 = Process(target = self.F2)

        self.P1.start()
        self.P2.start()

        self.P1.join()
        self.P2.join()

Root = Tk()
Software = GUI()
Root.mainloop()

Please click here

A: The problem lies with pickling tkinter widgets. You simply cannot do it, as the Tcl interpreter does not understand the python pickle format.
Coming to your code, I tried the following and it prints as expected:
from multiprocessing import Process
from tkinter import Button, Tk, Frame

class GUI(Frame):

    def __init__(self):
        super().__init__()
        self.button = Button(self, text="Start", command=self.execute)
        self.button.pack()
        self.pack()

    @staticmethod
    def F1():
        print("Hello")

    @staticmethod
    def F2():
        print("World")

    def execute(self):
        self.P1 = Process(target = GUI.F1())
        self.P2 = Process(target = GUI.F2())

        self.P1.start()
        self.P2.start()

        self.P1.join()
        self.P2.join()

Root = Tk()
Software = GUI()
Root.mainloop()


text:
Q: Appropriate use of surrogate key? Say a particular country has many sights (monuments, parks, museums), and of course a particular sight can exist in many states.
In terms of a logical ERD model, a junction table should be used between the M:N relationship.
However, would it suffice to simply use the PKs of the two adjoining tables as the PK of the junction table?
That is, you have a COUNTRY, SIGHTS and SIGHT_TYPE table, where SIGHTS is the junction table.
Assuming a particular country can have multiple museums (i.e. MUSEUM is a SIGHT_TYPE), this would mean each record in the SIGHTS table could not be uniquely identified, wouldn't it?
i.e. assuming MUSEUM has SIGHT_TYPE_ID of 2 and GERMANY has a country_id of 22.
For multiple museums, wouldn't you have this occurring if the above was true?
22 2 - Museum A
22 2 - Museum B
Thus, is the use of a surrogate key, say, SIGHT_ID, absolutely essential in this case to serve as a unique identifier?
In other words, generally the use of the PKs of the two adjoining tables is used as the PK for the junction or composite table, however are cases like these exceptions to that?
Thank you

A: Composite keys for junction tables (made up of FKs)  are completely OK at the logical design level.  They guarantee uniqueness of rows in the junction table.  They also guarantee that all of the participants in a given instance of the relationship participate in only one instance of the relationship. If you are using some sort of app builder tool, that tool has to be capable of dealing with a composite PK.
Normally, that constraint is exactly what you want.  If you add an extra column to the junction box to serve as a primary key, you are either going to have to add a unique constraint on the two foreign keys or rely on the application(s) to prevent erroneous duplicates.  Most of the time, these solutions are not as good.
At the physical design level, it depends on what you are going to do with the data, what volume of data you are going to store, and on your particular DBMS.  I would tend to go without the extra surrogate key in an initial design, and add it only if it saves more than it costs.


text:
Q: Parse large JSON file with the bulk of the data inside a property of the root object I'm working on parsing a relatively large (1.01GB) JSON file using the JSON.NET framework that is structured like below:
{
  "Stores": [
    {
        "Number": 1234,
        "City": "Denver",
        "County": "Denver",
        "Departments": [
            {
                "Name": "Deli",
                "Description": "sliced lunchmeat"
            },
            {
                "Name": "Produce",
                "Description": "fruit and vegetables"
            }
        ],
        "Telephone": "555-1212"
    },
    {
        "Number": 5678,
        "City": "Parker",
        "County": "Douglas",
        "Departments": [
            {
                "Name": "Seafood",
                "Description": "creatures of the sea"
            },
            {
                "Name": "Meat",
                "Description": ""
            }
        ],
        "Telephone": "555-2323"
    }
  ]
}

I attempted to parse the whole JSON file at once, but ran into out-of-memory exceptions, so I am now trying to parse the file in chunks. I'm able to get it working using the code below, but only if I remove the root Stores object. The actual file that I have to parse has the root Stores object, so I need to figure out how to get this to work. I'm relatively new to JSON, so any help would be greatly appreciated. Thanks.
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (StreamReader sr = new StreamReader(fs))
using (JsonTextReader reader = new JsonTextReader(sr))
{
    while (reader.Read())
    {
        DepartmentInfo = "";

        if (reader.TokenType == JsonToken.StartObject)
        {
            dynamic obj = JObject.Load(reader);

            City = obj.City.ToString();
            County = obj.County.ToString();

            foreach (var Department in obj.Departments)
            {
                DepartmentInfo += Department.ToString();
            }
        }
    }
}

UPDATE: I updated the JSON to show the actual format I'm working with, it was missing a Description field in the Departments array. Also a little more context on what I'm doing - I'm loading this file into a database, and have a requirement to keep it looking as close to the source as possible so it can be tracked, and then further processing occurs in the database to normalize the data into another data model, so the DepartmentInfo is kind of gnarly by design. The final code is below.  Thanks!
string DepartmentInfo = "";

using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (StreamReader sr = new StreamReader(fs))
using (JsonTextReader reader = new JsonTextReader(sr))
{
    while (reader.TokenType != JsonToken.StartArray)
        reader.Read();

    while(reader.Read())
    {
        DepartmentInfo = "";

        if (reader.TokenType == JsonToken.StartObject)
        {
            dynamic obj = JObject.Load(reader);

            var StoreNumber = obj["Number"];
            var City = obj["City"].ToString();
            var County = obj["County"].ToString();
            var PhoneNumber = obj["Telephone"];

            foreach (var Department in obj.Departments)
            {
                DepartmentInfo += ("Name: " + Department.Name.ToString() + ", Description: " + Department.Description.ToString() + " ");
            }

        }
    }
}

A: You're on the right track.  You just need a little bit of code to advance the reader to the beginning of the Stores array, then process from there using the code you already have.  Here is the revised code:
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (StreamReader sr = new StreamReader(fs))
using (JsonTextReader reader = new JsonTextReader(sr))
{
    // Advance the reader to start of first array,
    // which should be value of the "Stores" property
    while (reader.TokenType != JsonToken.StartArray)
        reader.Read();

    // Now process each store individually
    while (reader.Read())
    {
        if (reader.TokenType == JsonToken.StartObject)
        {
            dynamic obj = JObject.Load(reader);

            // ...
        }
    }
}

Here is a working fiddle demonstrating the concept.  Note I'm using a hardcoded JSON string and a MemoryStream instead of a FileStream but the result is the same.  I've also made some tweaks to make the department output more readable.


text:
Q: Tiny script logic which connects to database and sends reply to application I am having a painful issue in the following code. My application connects to this script called main.php and sends username and password to it. The script then checks the credentials in the database and replies positively to my application if credentials are correct and negatively if incorrect. To be more specific, it just checks usergroup memberships and sends reply back. Now the issue is that it always sends negative reply. Can you tell me where I am wrong?
    <?php

    function append_file( $filename, $newdata )
    {
            $f = fopen( $filename, "a" );
            fwrite( $f, $newdata );
            fclose( $f );
    }

$userAgent          =   $_SERVER['HTTP_USER_AGENT'];

$m_pUsername            =   $_POST['user'];
$m_pPassword                =   $_POST['pass'];
    $m_pDate                        =   date(DATE_RFC822);
    $m_pIP                          =   $_SERVER[ 'REMOTE_ADDR' ];

    $conf['host']           = 'localhost';
    $conf['user']           = 'XXX';
    $conf['pass']           = 'XXX';
    $conf['database']       = 'XXX';

if( !$m_pUsername || !$m_pPassword )
    die("g_requireUpdate");

    $con = mysql_connect($conf['host'],$conf['user'],$conf['pass']) or die ("cannot connect");
    mysql_select_db($conf['database'])or die("cannot select DB");
$sql = mysql_query("SELECT * FROM `user`");

while($row = mysql_fetch_array($sql))
{

    $salt = $row['salt'];
    $md5_pass = MD5(md5($m_pPassword) . $salt);
    if($m_pUsername == $row['username'] &&  $md5_pass == $row['password'] )
    {

        if( $row['usergroupid'] == '5' || $row['usergroupid'] == '9' || $row['usergroupid'] ==     '7' || $row['usergroupid'] == '6' || $row['usergroupid'] == '71' || $row['usergroupid'] == '72'      )//VIPS + STAFF
{
            print("g_userValid ");

            append_file( "access_log.txt", "($m_pUsername) \t  ($m_pIP) \n");
        }
        if( $row['usergroupid'] == '2')//NON VIP
                    {
            print("g_userNormal ");
            exit;
                    }
        if( $row['usergroupid'] == '8')//BANNED
                    {
            print("g_userBanned ");
            exit;
                    }
    }
}

append_file( "access_log.txt", "($m_pUsername) \t  ($m_pIP) \t \n");
mysql_close();
?>


text:
Q: Rails: Passing a variable from one controller to another for two forms I have two models: one for patient and one for referral request. I've created two forms - one that allows a user to create a new patient and another that allows a user to create a referral request. A patient can have many referral requests, and and a referral request will belong to the user who created it as well as the patient it is created for.
I am having trouble figuring out how to link these forms together in a way that creates the association between the patient and the referral request being created for them by the user. I think I have to put something in the new or create actions of the referral requests controller, but I can't get anything I've tried to work.
Any help appreciated for a rookie!
Patients Controller:
class PatientsController < ApplicationController

def new
    @patient = current_user.patients.build
end

def create
    @patient = current_user.patients.build(patient_params)
    if @patient.save
        flash[:success] = "Patient Created!"
        redirect_to '/referral_requests/new'
    else
        Rails.logger.info(@patient.errors.inspect)
        render 'patients/new'
end
end

private

def patient_params
    params.require(:patient).permit(:age, :user_id, insurance_ids: [], gender_ids: [], concern_ids: [], race_ids: [])

end
end

Referal Requests Controller:
class ReferralRequestsController < ApplicationController
    before_action :logged_in_user, only: [:show, :index, :new, :create, :edit, :update, :destroy]

    def index
        if logged_in?
        @referral_request = current_user.referral_requests.build
        @feed_items = current_user.feed.paginate(page: params[:page])
    else
        @feed_items =[]

    end
end

    def create
        @referral_request = current_user.referral_requests.build(referral_request_params)
        if @referral_request.save
            flash[:success] = "Referral Request Created!"
            render 'referral_requests/index'
         else
    Rails.logger.info(@referral_request.errors.inspect)
      @feed_items = []
      render 'static_pages/home'

    end
  end

    def destroy
    end

    def new
    @referral_request = current_user.referral_requests.build if logged_in?
    end

private

def referral_request_params
    params.require(:referral_request).permit(:content, concern_ids: [],
     insurance_ids: [], race_ids: [], language_ids: [], gender_ids: [])

end
end

A: you need to pass in the patient_id in your redirect in the create action of PatientsController.
redirect_to '/referral_requests/new'
should become
redirect_to new_referral_request_path(patient_id: @patient.id)
then in ReferralRequestsController you can associate the newly built referral_request with the patient
def new
  @patient = Patient.find(params[:patient_id])
  @referral_request = current_user.referral_requests.build(patient: @patient) if logged_in?
end

Then in your referral_requests/new.html.erb form you can add a hidden_field_tag
form_for(@referral_request) do |f|
  f.hidden_field :patient_id
  .....
end

which will then add patient_id to into the form params and pickup the patient_id that got associated in the new action of the controller
You will need to add :patient_id into your referral_request_params method as well


text:
Q: Gantt View JSON data I am trying to reload (via ajax) data into a Gantt chart using php and jquery. I can draw a gantt chart with my data on the initial load without any issues. I have a ajax save call to update chart data in which I would like to redraw the gantt chart after a successful save.
I am able to load part of the data, ie the title data on the left, but not the dates, I believe it is not in the right format? I am using this gantt chart plugin from github: https://github.com/thegrubbsian/jquery.ganttView
Below is a sample of the data they are using? Is this json data?
I am not sure? How do I format my output to mirror and use this data.
var ganttData = [
{
    id: 1, name: "Feature 1", series: [
        { name: "Planned", start: new Date(2010,00,01), end: new Date(2010,00,03) },
        { name: "Actual", start: new Date(2010,00,02), end: new Date(2010,00,05), color: "#f0f0f0" }
    ]
},
{
    id: 2, name: "Feature 2", series: [
        { name: "Planned", start: new Date(2010,00,05), end: new Date(2010,00,20) },
        { name: "Actual", start: new Date(2010,00,06), end: new Date(2010,00,17), color: "#f0f0f0" },
        { name: "Projected", start: new Date(2010,00,06), end: new Date(2010,00,17), color: "#e0e0e0" }
    ]
},

My code looks like this:
[{"id":0,"name":"task number 20","series":[{"name":"Bob","start":"new Date(2012,2,19)","end":"new Date(2012,6,11)"}]},{"id":1,"name":"another new posts","series":[{"name":"Bill","start":"new Date(2012,5,22)","end":"new Date(2012,6,27)"}]},here

A: It's not legal to "call" functions (including constructors) from a json string. JSON isn't anything you can pass to an eval function : http://www.json.org/
You should do the transformation from string to date in your javascript code.
You can send
[{..."start":"Thu Jul 12 2012 16:20:17 GMT+0200 (CEST)"...}]

and in your js code, just after json parsing, iterate over the objects to do
myobj.start = new Date(myobj.start);


text:
Q: JointJs Link hides after Zoom In I am referring to joint/demo/shapes/html.html. I need to scroll the diagram when using zoom in for HtmlElement. To do this I used overflow: auto; in html.js. The Link gets disappeared when it crosses the boundary. Please see the Screen Shot.
To reproduce this issue you can do the following changes.
In https://github.com/clientIO/joint/blob/fe1c39eda24afb2432c4306c1a47c4b79d6039b1/demo/shapes/html.html
at line 19 change 'overflow: hidden;' to 'overflow: auto;'
and In https://github.com/clientIO/joint/blob/fe1c39eda24afb2432c4306c1a47c4b79d6039b1/demo/shapes/src/html.js
at line 134 change y value to 350 'position: { x: 350, y: 350 }'
Could you please let me know how can I fix this?


text:
Q: Automatically insert fold tags around visually selected text in vim I have started to use set foldmethod=marker, because I find it more convenient to use rather than syntax.
But it has the disadvantage of needing to write // {{{ my title and  // }}} around any folding code candidate.
It would be nice if I could select a part of code in visual mode, and call a command ( or some commands) that would insert the two markers before and after the selected code.
Are there any way to do that in vim ?

A: I found it. Visually select the block then input the command :fold
It automatically writes the two tags /*{{{*/ and /*}}}*/.

A: When in visual mode, with the text to be folded highlighted, press zf. This is better than using :fold as you don't have to escape to the command prompt (and use less keystrokes).


text:
Q: How can I see the Tables and Values of my database? I made a new ASP.NET MVC project in Visual Studio.
It created a database with tabels automatically for me.
Now I want to be able to change the database, where can I do this? I've been searching in the Server Explorer but can't seem to find anything.
Let me know if I need to provide some content of certain files for you to be able to answer this question.

A: I'm not sure whether I get your question right, you can change your database connection in your connectionstring. Change your web.config file to the new database.
<connectionStrings>
      <add name="ConnString" connectionString="Data Source=NEWDATABASESE-RVER-IP,PORT; Initial Catalog=DATABASE_NAME; UID=USERNAME; pwd=PASSWORD; Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

More information about connectionstring(s)


text:
Q: A problem in returning a table with Null On it i want my function to return a A table with some values
I must fix something in the update but i don't know what
this is the function FngetTableH BELOW
ALTER FUNCTION [dbo].[FnGetTableH]
 (
  @Date DateTime
  )
  RETURNS  @Listeab_ Table(CLOSING_PRICE money,IdValeur int)
 AS
  BEGIN

    Insert @Listeab_
   (          CLOSING_PRICE ,IdValeur)

     select Distinct 0 , IdValeur
     From Historique

     Update @Listeab_
       Set CLOSING_PRICE = (Select  CLOSING_PRICE
       from Historique H
      inner join (Select MAX(@Date) As DATEDU,IdValeur FROM Historique
  where
     DATE_NEGO<= @Date
       group by IdValeur ) L2
       on
  H.DATE_NEGO=L2.DATEDU
     and
  H.IdValeur=L2.IdValeur
       )
  return
 END

when i Execute this code
declare @Date date = '10/09/2013'

---select*from FnGetTableH(@Date)
select  C.IdClient,H.IdValeur,C.RaisonSocial,SUM( case I.sens
                                                   WHEN 'c' then  + I.Qantite
                                                   WHEN'd' then  - I.Qantite
                                                  END) as 'Solde', H.closing_price
from Imputations I
Inner join FnGetTableH(@Date) H
on H.IdValeur=I.IdValeur
Inner join Clients C
on C.IdClient=I.IdClient
where I.DateImputation=@Date
group by C.IdClient,RaisonSocial,H.closing_price,H.IdValeur
Order by IdClient asc

i get
Msg 512, Niveau 16, État 1, Ligne 4
La sous-requête a retourné plusieurs valeurs. Cela n'est pas autorisé quand la sous-requête suit =, !=, <, <= , >, >= ou quand elle est utilisée en tant qu'expression.
L'instruction a été arrêtée.

A: your query "Select CLOSING_PRICE from Historique H inner..." may be returning more than 1 value.

A: In your innermost query I think MAX(@Date) should be MAX(DATE_NEGO), which might explain why the closing price query is returning multiple results.
There is still the possibility of multiple results, so you might need to account for that You could select max(closing_price) if it doesn't matter which, though I suspect it might, in which case you need to do some ordering to select the correct price to use.
EDIT: Try this:
ALTER FUNCTION [dbo].[FnGetTableH]
(
    @Date DATETIME
)
RETURNS @Listeab_ TABLE
(
    CLOSING_PRICE MONEY,
    IdValeur INT
)
AS
BEGIN
    WITH prices AS
    (
        SELECT IdValeur,
            CLOSING_PRICE,
            ROW_NUMBER() OVER (PARTITION BY IdValuer ORDER BY DATE_NEGO DESC) rn
        FROM Historique
        WHERE DATE_NEGO <= @Date
    )
    INSERT @Listeab_(CLOSING_PRICE, IdValeur)
    SELECT DISTINCT ISNULL(p.CLOSING_PRICE, 0),
        h.IdValeur
    FROM Historique h
    LEFT OUTER JOIN prices p ON h.IdValeur = p.IdValeur
        AND p.rn = 1
        RETURN;
END;

A: Use top to select 1 record. May be it will solve your error.
select Distinct 0 , IdValeur
From Historique
Update @Listeab_
Set CLOSING_PRICE = (Select  Top 1 CLOSING_PRICE
from Historique H
inner join (Select MAX(@Date) As DATEDU,IdValeur FROM Historique
where
DATE_NEGO<= @Date
group by IdValeur ) L2
on
H.DATE_NEGO=L2.DATEDU and H.IdValeur=L2.IdValeur
)


text:
Q: Optional whitespace in regexp I want to create a regexp to specify words between parenthesis. For example, I have a string like this:
"something(a,b)"

and
"something(c, d)"

and I want to extract the letters from between the parentheses.
In the first string I want to get an array ['a','b']. In the second, I want the array ['c','d'].
I have following method:
def suffixes(t)
  (t.scan /\((\w+),(\w+)\)/).flatten
end

but this works only for the first case. In the second variant I have:
def suffixes(t)
  (t.scan /\((\w+),[\s](\w+)\)/).flatten
end

But this works only for the second case. I don't know what regexp will operate in both cases.

A: You can use:
def suffixes(t)
  (t.scan /\((\w+)\s*,\s*(\w+)\)/).flatten
end

\s* will match 0 or more spaces before and after comma.

A: Make the inbetween \s as optional.
def suffixes(t)
  (t.scan /\((\w+),\s?(\w+)\)/).flatten
end

? after the \s would turn the space to optional (0 or 1).

A: I would suggest you to distinguish "scanning" for the text between parentheses and "splitting" the result by comma:
s = "something(c, d)"
s.match( /\((.+)\)/ )[1] # found text between parentheses
 .split(/,/)             # split the result by comma
 .map(&:strip)           # stripped the values

It's more Ruby-like, in my understanding. Hope it helps.
UPD Thanks @theTinMan, there are two possibilities to improve an answer. First of all, s[/\((.+)\)/, 1] looks better ans executes faster than s.match( /\((.+)\)/ )[1]. Secondary, splitting by string is faster than splitting by regexp. The summing up:
s = "something(c, d)"
s[ /\((.+)\)/, 1 ] # found text between parentheses
 .split(',')       # split the result by comma
 .map(&:strip)     # stripped the values

Proof:
require 'benchmark'

n = 1_000_000
s = "something(c, d)"

Benchmark.bm do |x|
  x.report { n.times { s.match( /\((.+)\)/ )[1].split(/,/).map(&:strip) } }
  x.report { n.times { s.match( /\((.+)\)/ )[1].split(',').map(&:strip) } }
  x.report { n.times { s[/\((.+)\)/, 1].split(/,/).map(&:strip) } }
  x.report { n.times { s[/\((.+)\)/, 1].split(',').map(&:strip) } }
end

#       user     system      total        real
#   3.590000   0.000000   3.590000 (  3.598151)
#   3.030000   0.000000   3.030000 (  3.028137)
#   2.940000   0.000000   2.940000 (  2.942490)
#   2.180000   0.000000   2.180000 (  2.182447)

A: \((\w+)|(?!^)\G\s*,\s*(\w+)

Try this.This will work for all arguments.See demo.
https://regex101.com/r/vN3sH3/27


text:
Q: 2D array is printing the wrong way I'm creating a 2D dynamic array to keep track of transactions over several days. I have created the 2D array and added the transactions. The problem is that is not printing the correct transactions. It will print correctly if I have the same amount of noOfdays and transcount. Ex 3 and 2. But it changes values if I have noOfdays 2 and trascount 3.
Example output having noOfdays 2 and trascount 3.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[]) {

int noOfDays, transcount;
printf("Enter no of days:");
scanf("%d", &noOfDays);
printf("Enter total no of transaction:\n ");
scanf("%d", &transcount);
int *p= (int)malloc(noOfDays*transcount * sizeof(int));

int number = 0;
for (int i = 0; i < noOfDays; i++) {
  printf("Enter no of transaction per day:\n", i);
for (int j = 0; j < transcount; j++) {
  scanf("%d", &number);
  p[i*noOfDays + j] = number;
 }

}

printf("%s\n", "#Printing your 2d array:" );
for (int i = 0; i < noOfDays; i++){
 for (int j = 0; j < transcount; j++){
  int number = p[i*noOfDays + j];
  printf("%d\t", number);
}
printf("\n");
}

return 0;
}

A: It's probably your index formula in p[i*noOfDays+j] is not correct.
Change it from p[i*noOfDays+j] to p[i*transcount+j].
The reason is the i is the index of the current transaction group.
The j is the index of specific transaction in a day.


text:
Q: How to remove the last index of a comma from the text file? I am trying to remove the last comma in the text file which i have opened and used.
I am using the (String.LastIndexOf) function to try and make this work.
However it is not working. How can i make the last comma in the text file i open deleted?
Here is what i have tried so far:
DialogResult openFile = openFileDialog1.ShowDialog();
if (openFile == DialogResult.OK)
{
    Functions func = new Functions();
    string file = openFileDialog1.FileName;
    string content = File.ReadAllText(file);
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "Text File|*.txt";
    sfd.FileName = "New Text Doucment";
    sfd.Title = "Save As Text File";
    if (sfd.ShowDialog() == DialogResult.OK)
    {
        string path = sfd.FileName;
        StreamWriter bw = new StreamWriter(File.Create(path));
        bw.WriteLine(content);
        bw.Close();
        File.WriteAllLines(path, File.ReadAllLines(path).Select(x => string.Format("{0},", x)));
        string newContent = File.ReadAllText(path);
        newContent = newContent.Remove(newContent.LastIndexOf(","));
    }
}

However when i check the file to see the last comma removed, it is not working?
Am i doing something wrong or am i missing something?
Help appreciated!
Note: I am taking the original text file, reading its content and adding a comma at the end of each line. I am then writing it in the new text file but i need to get rid of the last comma since it causes issues when it is run in SQL (the file)

A: You don't need to, just change
File.WriteAllLines(path, File.ReadAllLines(path).Select(x => string.Format("{0},", x)));

to
File.WriteAllText(path, string.Join("," + Environment.NewLine, File.ReadAllLines(path)));

and remove the other two lines.
NOTE: The + Environment.NewLine keeps the lines separated when written back to the file, adding it as suggested in comments.

A: Because you don't write the result back out to the file:
File.WriteAllText(path, newContent);

Just reading the text into memory and manipulating it there in your program isn't going to automatically update the file from which it was read.  That would be unexpected behavior, to say the least.

A: You have manipulated your text only in memory and haven't wrote those changes to file.
DialogResult openFile = openFileDialog1.ShowDialog();
        if (openFile == DialogResult.OK)
        {
            Functions func = new Functions();
            string file = openFileDialog1.FileName;
            string content = File.ReadAllText(file);
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Text File|*.txt";
            sfd.FileName = "New Text Doucment";
            sfd.Title = "Save As Text File";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                content= content.Remove(content.LastIndexOf(","));
                string path = sfd.FileName;
                File.WriteAllLines(path, content.Split(','));
            }
        }

And it seems
Functions func = new Functions();

this line of code is unnecessary here.


text:
Q: MVC5 and Swashbuckle with Basic Authorization Header (.NET 4.6.1 Framework) Hello I am using Swashbuckle with MVC5, I am able to generate the Swagger UI but I also need the Basic Authorization Header.
I have tried the following code
public class AddAuthorizationHeaderParameterOperationFilter: IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
        var isAuthorized = filterPipeline
                                         .Select(filterInfo => filterInfo.Instance)
                                         .Any(filter => filter is IAuthorizationFilter);

        var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();

        if (isAuthorized && !allowAnonymous)
        {
            operation.parameters.Add(new Parameter {
                name = "Authorization",
                @in = "header",
                description = "access token",
                required = true,
                type = "string"
            });
        }
    }
}

and added the following in web.config
<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
           <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
        </dependentAssembly>
    </assemblyBinding>
</runtime>

Getting error for Cannot load System.Web.Http 4.0.0

A: I doubt that swagger supports this, I came across this https://github.com/swagger-api/swagger-ui/issues/1566 where basic auth with swagger issue has been reported but didn't get resolved to work.
I recommend testing your code with a Rest-client (Advance Rest client or posteman etc.) tool instead.


text:
Q: Setting dynamic watermark in to the video using ffmpeg Android I am using this command to overlay the image into the video.
ffmpeg",i", inputVideoPath,"-i", imageToOverlay,"
-filter_complex",overlay=10:10","-strict", "-2","-b:a" ,"32k",
"-r","15","-preset", "ultrafast",outputVideoPath

Can we set the dynamic values into the "overlay=x:y" also "imageToOverlay" which is image path?

A: try this command
 //  test with watermark.png 128x128, add it to /sdcard/videokit/
String[] complexCommand = {"ffmpeg","-y" ,"-i", "/sdcard/videokit/in.mp4","-strict","experimental", "-vf", "movie=/sdcard/videokit/watermark.png [watermark]; [in][watermark] overlay=main_w-overlay_w-10:10 [out]","-s", "320x240","-r", "30", "-b", "15496k", "-vcodec", "mpeg4","-ab", "48000", "-ac", "2", "-ar", "22050", "/sdcard/videokit/out.mp4"};

for more information check this link
check this link as well


text:
Q: okhttp3 multipart отправить текстовое поле в кодировке utf-8 отправляю текст с андроида на http сервер таким образом:
MultipartBody.Builder builder=new MultipartBody.Builder()
                                .setType(MultipartBody.FORM);
builder.addFormDataPart("texttosend",readyText);
RequestBody requestBody=builder.build();
CountingRequestBody countingRequestBody=new CountingRequestBody(requestBody,listener);
Request request=new Request.Builder()
    .url("http://"+ip+":"+port)
    .post(countingRequestBody)
    .build();
call = client.newCall(request);
call.enqueue(new okhttp3.Callback() {
    @Override
    public void onFailure(Call call, final IOException e) {
        hnd.post(new Runnable() {
            @Override
            public void run() {
                alert("Ошибка при загрузке: "+e.getLocalizedMessage());
            }
        });
    }
    @Override
    public void onResponse(Call call, okhttp3.Response response) throws IOException {
        hnd.post(new Runnable() {
            @Override
            public void run() {
                //........
            }
        });
    }
});

но русские символы не признает. как установить кодировку urf-8 ?

A: public static final MediaType MEDIA_TYPE_MARKDOWN =
      MediaType.parse("text/x-markdown; charset=utf-8");

Request request = new Request.Builder()
      .url(ANY_URL)
      .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
      .build();


text:
Q: aparece error JSONException No value for Este es mi codigo
               String line;
               while((line = reader.readLine()) != null){
                   result.append(line);
               }
               JSONObject respuestaJSON = new JSONObject(result.toString());
               JSONObject usuario = respuestaJSON.getJSONObject("usuario");
               String resultJSON = respuestaJSON.getString("estado");

               if(resultJSON == "1"){
                   id = id + usuario.getString("id");
                   nombre = nombre + usuario.getString("nombre");
                   ap = ap + usuario.getString("ap");
                   am = am + usuario.getString("am");
                   correo = correo+ usuario.getString("correo");
                   direccion = direccion + usuario.getString("direccion");
                   numero = numero + usuario.getString("numero");
                   dispositivo = dispositivo + usuario.getString("dispositivo");
                   contraseña = contraseña + usuario.getString("contrasena");

                   }

y este es el resultado JSON
{
    "estado": 1
} {
    "usuario": {
        "0": "hola",
        "id": "hola",
        "1": "Hector",
        "nombre": "Hector",
        "2": "asfaf",
        "ap": "asfaf",
        "3": "alala",
        "am": "alala",
        "4": "hola@gmail.com",
        "correo": "hola@gmail.com",
        "5": "23255532",
        "telefono": "23255532",
        "6": "infierno",
        "direccion": "infierno",
        "7": "holamundo",
        "contrasena": "holamundo",
        "8": "1",
        "dispositivo": "1"
    }
}

A: El error

JSONException No value for

es provocado al no poder obtener el valor de un key dentro del .json, seguramente en este el punto:
String resultJSON = respuestaJSON.getString("estado");

El .json que agregas no es válido, me parece que debería ser:
{
    "estado": 1,
    "usuario": {
        "0": "hola",
        "id": "hola",
        "1": "Hector",
        "nombre": "Hector",
        "2": "asfaf",
        "ap": "asfaf",
        "3": "alala",
        "am": "alala",
        "4": "hola@gmail.com",
        "correo": "hola@gmail.com",
        "5": "23255532",
        "telefono": "23255532",
        "6": "infierno",
        "direccion": "infierno",
        "7": "holamundo",
        "contrasena": "holamundo",
        "8": "1",
        "dispositivo": "1"
    }
}

esto para que el código que presentas obtenga los datos correctamente.
               //Convierte respuesta a JSONObject.
               JSONObject respuestaJSON = new JSONObject(result.toString());
               //Obtiene valor JSONObject "usuario".
               JSONObject usuario = respuestaJSON.getJSONObject("usuario");
               //Obtiene valor de key estado en JSONObject.
               String resultJSON = respuestaJSON.getString("estado");

               //if(resultJSON == "1"){ //incorrecta comparación de Strings.
               if(resultJSON.equals("1")){
                   id = id + usuario.getString("id");
                   nombre = nombre + usuario.getString("nombre");
                   ap = ap + usuario.getString("ap");
                   am = am + usuario.getString("am");
                   correo = correo+ usuario.getString("correo");
                   direccion = direccion + usuario.getString("direccion");
                   numero = numero + usuario.getString("numero");
                   dispositivo = dispositivo + usuario.getString("dispositivo");
                   contraseña = contraseña + usuario.getString("contrasena");

                   }


text:
Q: Return code of doing an update query with ADOquery in Delphi to PostgreSQL I'm using  Adoquery with a Postgres database.
When I do an UPDATE or INSERT query the ExecSql nor the OPEN returns the number of affected records as it should , but always -1.
I use the newest version of psqlODBC : 09.01.0200.
Code:
Adoquery1.close;
Adoquery1.SQL.Clear;
query := 'insert into  testtabel (nummer, naam) values (3,''Barnsten'') ';
Adoquery1.SQL.Add(query ) ;
result := Adoquery1.ExecSql;

Result is -1

A: function PerformSQL(const ASQL: string): integer;
begin
  Result := -1;
  if ASQL <> '' then
  begin
    ZQuery1.SQL.Text := ASQL;
    ZQuery1.ExecSQL;
    Result := ZQuery1.RowsAffected;
  end;
end;

 ShowMessage
    (IntToStr(PerformSQL('insert into test(te_id, te_code, te_name, te_type)' +
    ' VALUES(DEFAULT, 15, ''tezty68'', 1), (DEFAULT, 16, ''teztx75'', 1), (DEFAULT, 18, ''teztx89'', 1)')
    ));

Returns me 3.


text:
Q: How to Select Cell Based from Macro This should be simple, not sure why I am having trouble with this.....
In a data input range that a user is entering data there is a "left" and a "right" side of the form. Not all the data in any given row has to be filled in. I want to create a macro (and assign it to a hot key I.E. ctrl-z  ) such that if it is hit it will position the active cell to be in the current row and in column "X". in other words hitting the ctrl-Z will cause the cursor to jump to column "X"

A: In this case column "x" is actually column E:
Sub ToColE()
    Const colE = 5
    Dim offset As Integer
    offset = colE - ActiveCell.Column
    ActiveCell.offset(rowOffset:=0, columnOffset:=offset).Activate
End Sub

A: Either of the following statements should do the trick.  Assign the macro shortcut from the Tools Menu --> Macros.
Public Sub SelectStuff()
    Cells(3, 5).Select
    Rows(17).Select
End Sub

A: Try this
Sub MoveLeftOnForm()
    Dim rn As Integer
    rn = ActiveCell.Row
    Range("B" & rn).Select
End Sub

it assumes B is your leftmost column in the form.

A: This code should do it for you:
Public Sub SetUpKeyboardShortcut()
    Application.OnKey "^z", "SelectColInSelectedRow"
End Sub

Public Sub SelectColInSelectedRow()
    Const ColToSelect = "X"
    Range(ColToSelect & CStr(Selection.Row)).Select
End Sub

Just call SetUpKeyboardShortcut in the Workbook_Open event in the ThisWorkbook module.  I believe the code above needs to be stored in a standard module.
Hope that helps...

A: This will work:
Public Sub go()
Cells(ActiveCell.Row, 5).Activate
End Sub

Just substitute the "5" with whatever column number you wish.  You should be able to assign a ctrl+z hotkey from the options on the macro menu.


text:
Q: Flexbox does not trigger click event You can check the demo at
http://demo.m.moneylife.in/events/advisor2/pricing/
Clicking on next button works fine but when you click on previous edit. It does not work to get the element active
class.
I have just added an alert to check
JQUERY
$(document).ready(function(e) {
    $("button.previous").each(function(e) {
        $(this).click(function(e) {
            alert(90);
        });
    });
    $("button.next").each(function(e) {
        $(this).click(function(e) {
            $(this).parent().next("li").addClass("active");
            $(this).addClass("previous");
            $(this).html('');
            $(this).addClass("collapsed");
            $(this).removeClass("next");
            $(this).parent().addClass("entered");
            $(this).parent().removeClass("active");
            $(this).parent().next("li").addClass("complete");
        });
    });
});

HTML
<!DOCTYPE html>

    <title>Pricing</title>
    <link rel="stylesheet" type="text/css" href="css/pricing.css">

                <input type="button" name="" class="next" value="next" />

                <input type="button" name="" class="next" value="next" />

                <input type="button" name="" class="next" value="next" />

                <input type="button" name="" class="next" value="next" />

                <input type="button" name="" class="next" value="next" />

                <input type="button" name="" class="next" value="next" />

A: You are binding to all buttons with a previous class when you load the document. At that point there are none. Adding the class later will not bind them. You should change your previous binding to a function and call that when your next buttons are clicked.
Untested code:
function doBinding(){
    $('button.previous').each(function(e){
        $(this).click(function(e){
            alert(90);
        });
    });
};
$(document).ready(function(e){
    $('button.next').each(function(e){
        $(this).click(function(e){
        $(this).parent().next('li').addClass('active');
        $(this).addClass('previous');
        $(this).html('')
        $(this).addClass('collapsed')
        $(this).removeClass('next');
        $(this).parent().addClass('entered')
        $(this).parent().removeClass('active');
        $(this).parent().next('li').addClass('complete');
        doBinding();
    });
});


text:
Q: Not able to get location with Service (LocationManager) i am in real trouble here. Trying to get lat and lon with a background service every 3 sec but i am only able to get some data written when i click send lat and lon in extended controls of the emulator , so both phone and emulator are not working. Here is my code below, it would be awesome if someone could help me. Thanks!
Service
public class GPSService extends Service {

    private static final String TAG = "GpsService";
    private LocationListener locationListener;
    private LocationManager locationManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {

        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Intent i = new Intent("location_update");
                i.putExtra("latExtra",location.getLatitude());
                i.putExtra("lonExtra",location.getLongitude());
                sendBroadcast(i);
                Log.i(TAG, "onLocationChanged: extras lat lon"+location.getLatitude()+" "+location.getLongitude());
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {
                Log.i(TAG, "onProviderDisabled: DISABLED");
                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
            }
        };

        locationManager =(LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

        Criteria c = new Criteria();
        String provider =locationManager.getBestProvider(c,true);
        Log.i(TAG, "onCreate: bestProvider "+provider);

        //noinspection MissingPermission
        locationManager.requestLocationUpdates(provider,2000,0,locationListener);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (locationManager != null){
            Log.i(TAG, "onDestroy: Location manager nije null i brisem");
            //noinspection MissingPermission
            locationManager.removeUpdates(locationListener);
        }

    }
}

MainActivity
    private final String TAG = "Main";
    ...
    BroadcastReceiver broadcastReciever;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //setStatusBarTranslucent(false);

        if(!runtimePermisions()){
            startLocationUpdate();}
...

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //stopService();
                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    //REQUEST PERMISSION
                    Log.i(TAG, "onClick: NO PERMISION");
                } else {
                    Log.i(TAG, "onClick: got permision");
                }
...
    }
    public void startLocationUpdate(){
        Intent i = new Intent(this,GPSService.class);
        startService(i);
        Log.i(TAG, "startLocationUpdate: Pokrenuo sam service");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (broadcastReciever == null){
            broadcastReciever = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {

                    lat = (Double) intent.getExtras().get("latExtra");
                    lon = (Double) intent.getExtras().get("lonExtra");

                    Log.i(TAG, "onReceive: lat lon "+lat+" "+lon);
                }
            };
        }
        registerReceiver(broadcastReciever,new IntentFilter("location_update"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (broadcastReciever!=null){
            unregisterReceiver(broadcastReciever);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 100) {
                if (grantResults [0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
                    startLocationUpdate();
                }else{
                    runtimePermisions();}
            }

    }

    private boolean runtimePermisions() {
        if (Build.VERSION.SDK_INT >= 23 &&ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,

            },100);
            return true;
        }
        return false;
    }

MANIFEST
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.digiart.yoweather">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SettingsActivity"
            android:theme="@style/SettingsTheme"></activity>
        <service android:name=".Gps.GPSService"/>
    </application>

</manifest>

Again... Any help would be great! THANKS :D

A: As K. Sopheak said, it can take a while to get the location. From the documentation:

It may take a while to receive the first location update. If an immediate location is required, applications may use the getLastKnownLocation(String) method.

So, you could try getting the last known location using getLastKnownLocation(String) when the service is started and, assuming it exists, broadcast it in the same way you would a location update. Bear in mind, though, that the last known location could be out of date. Depending on what you're using the location for this may or may not be acceptable.
Also, as an aside, a couple of thoughts:

*

*You said 3 seconds, but the code uses 2,000 milliseconds - was that just a typo?

*The frequency of location updates is a minimum time - you are not guaranteed to get updates that often. As per the documentation:

The location update interval can be controlled using the minTime parameter. The elapsed time between location updates will never be less than minTime, although it can be more depending on the Location Provider implementation and the update interval requested by other applications.

*Is there any particular reason you need location updates at such a high frequency? Obtaining a location can be battery intensive, particularly given that you are requesting FINE as well as COARSE location permissions, so requesting it so frequently could place an enormous drain on device battery life. This is particularly so given that the code is running in a service and will therefore continue to run even when the application is in the background or the user is in an activity which does not require location data. Again, from the documentation:

Choosing a sensible value for minTime is important to conserve battery life. Each location update requires power from GPS, WIFI, Cell and other radios. Select a minTime value as high as possible while still providing a reasonable user experience. If your application is not in the foreground and showing location to the user then your application should avoid using an active provider (such as NETWORK_PROVIDER or GPS_PROVIDER), but if you insist then select a minTime of 5 * 60 * 1000 (5 minutes) or greater. If your application is in the foreground and showing location to the user then it is appropriate to select a faster update interval.

*Google recommends using the Google Play services location APIs instead of the Android framework location APIs:

The Google Play services location APIs are preferred over the Android framework location APIs (android.location) as a way of adding location awareness to your app. If you are currently using the Android framework location APIs, you are strongly encouraged to switch to the Google Play services location APIs as soon as possible.


text:
Q: Index versions(historical) data I have a table  storing all the old versions for item in DynamoDB. Is there a way to index the versions data using search engine or other things so that I can do something gracefully for the following scenarios:
Use case 1:
Search for current items that match a specific query with sorting and pagination and get their historical data for a date range (Between January and June, what were the statuses of those items each month?). This would ideally be able to happen in one query.
Use case 2:
Find differences for a field based on the version history.
eg. Find all items whose field changed from 'A' to 'B'
Current state:
Use case 1:
  1.Get all the items matching query first.
  2.For each item ,issue a separate query to get all the versions for that
  item.
  3.Do a lot of in-memory filter operations in back end, and get the data
  within data range.
Use case 2:
   not supported now


text:
Q: TensorFlow Model takes exponential time on large dataSet I am using TensorFlow for Poets to detect features in clothing images. I have trained 4 different models(sleeve, shape, length & hemline). Now i pass image urls to each of the model and store the result. Since i have huge data (100k images), so using spark to broadcast 4 models once  and passing image RDD to detect the features. It's taking exponential time. It starts from 3 secs/images & keep increasing the execution time. When scripts already sensed 10k images, its execution time reaches to 8 secs/ images. I am new to Tensorflow, will be very thankful if get any idea to make the execution time linear.
def getLabelDresses(file_name):
    resultDict = {}
    t = read_tensor_from_image_file(file_name,
                              input_height=input_height,
                              input_width=input_width,
                              input_mean=input_mean,
                              input_std=input_std)
    input_name = "import/" + input_layer
    output_name = "import/" + output_layer

    with tf.Graph().as_default() as g:

        graph_def = tf.GraphDef()

        graph_def.ParseFromString(model_data_hemline.value)

        tf.import_graph_def(graph_def)

        input_operation_hemline = g.get_operation_by_name(input_name);
        output_operation_hemline = g.get_operation_by_name(output_name);

        with tf.Session() as sess:
            results = sess.run(output_operation_hemline.outputs[0],{input_operation_hemline.outputs[0]: t})

        results = np.squeeze(results)

        top_k = results.argsort()[-1:][::-1]
        labels = load_labels(label_file_hemline)
        resultDict['hemline'] = labels[top_k[0]]

    with tf.Graph().as_default() as g:

        graph_def = tf.GraphDef()

        graph_def.ParseFromString(model_data_shape.value)

        tf.import_graph_def(graph_def)

        input_operation_shape = g.get_operation_by_name(input_name);
        output_operation_shape = g.get_operation_by_name(output_name);

        with tf.Session() as sess:
            results = sess.run(output_operation_shape.outputs[0],{input_operation_shape.outputs[0]: t})

        results = np.squeeze(results)

        top_k = results.argsort()[-1:][::-1]
        labels = load_labels(label_file_shape)
        resultDict['shape'] = labels[top_k[0]]

    with tf.Graph().as_default() as g:

        graph_def = tf.GraphDef()

        graph_def.ParseFromString(model_data_length.value)

        tf.import_graph_def(graph_def)

        input_operation_length = g.get_operation_by_name(input_name);
        output_operation_length = g.get_operation_by_name(output_name);

        with tf.Session() as sess:
            results = sess.run(output_operation_length.outputs[0],{input_operation_length.outputs[0]: t})

        results = np.squeeze(results)

        top_k = results.argsort()[-1:][::-1]
        labels = load_labels(label_file_length)
        resultDict['length'] = labels[top_k[0]]

    with tf.Graph().as_default() as g:

        graph_def = tf.GraphDef()

        graph_def.ParseFromString(model_data_sleeve.value)

        tf.import_graph_def(graph_def)

        input_operation_sleeve = g.get_operation_by_name(input_name);
        output_operation_sleeve = g.get_operation_by_name(output_name);

        with tf.Session() as sess:
            results = sess.run(output_operation_sleeve.outputs[0],{input_operation_sleeve.outputs[0]: t})

        results = np.squeeze(results)

        top_k = results.argsort()[-1:][::-1]
        labels = load_labels(label_file_sleeve)
        resultDict['sleeve'] = labels[top_k[0]]

    return resultDict;

model_file_hemline = "/home/ubuntu/amit/feature-sensing/tf_files/attribute/dresses/hemline/retrained_graph_hemline.pb"
label_file_hemline = "/home/ubuntu/amit/feature-sensing/tf_files/attribute/dresses/hemline/retrained_labels_hemline.txt"
model_file_length = "/home/ubuntu/amit/feature-sensing/tf_files/attribute/dresses/length/retrained_graph_length.pb"
label_file_length = "/home/ubuntu/amit/feature-sensing/tf_files/attribute/dresses/length/retrained_labels_length.txt"
model_file_shape = "/home/ubuntu/amit/feature-sensing/tf_files/attribute/dresses/shape/retrained_graph_shape.pb"
label_file_shape = "/home/ubuntu/amit/feature-sensing/tf_files/attribute/dresses/shape/retrained_labels_shape.txt"
model_file_sleeve = "/home/ubuntu/amit/feature-sensing/tf_files/attribute/dresses/sleeve/retrained_graph_sleeve.pb"
label_file_sleeve = "/home/ubuntu/amit/feature-sensing/tf_files/attribute/dresses/sleeve/retrained_labels_sleeve.txt"

with gfile.FastGFile(model_file_hemline, "rb") as f:
    model_data = f.read()
    model_data_hemline = sc.broadcast(model_data)
with gfile.FastGFile(model_file_length, "rb") as f:
    model_data = f.read()
    model_data_length = sc.broadcast(model_data)
with gfile.FastGFile(model_file_shape, "rb") as f:
    model_data = f.read()
    model_data_shape = sc.broadcast(model_data)
with gfile.FastGFile(model_file_sleeve, "rb") as f:
    model_data = f.read()
    model_data_sleeve = sc.broadcast(model_data)

def calculate(row):
    path = "/tmp/"+row.guid
    url = row.modelno
    print(path, url)
    if(url is not None):
        import urllib.request
        urllib.request.urlretrieve(url, path)
        t1=time.time()
        result = getLabelDresses(path)
        print(time.time()-t1)
        print(result)
        return row
    return row

product2.rdd.map(calculate).collect()

A: Every call to getLabelDresses in your code adds operations to the graph.
Split your code into setup (model loading) part, executed once and execution part that is executed for each image. The latter should only contain calls to Session.run.
Another option is to clear graph before processing next image using tf.reset_default_graph. But it is less preferable.


text: Q: How to get number of pages printed when using print document control? Well, as the title says, I want to get the total count of pages printed after the user sends the order. That's because I have a database where I need to store the sale like "A4 COLOR(or black&white)/ 45 pages". I care about the number of pages but I dont know if is possible to get the color mode info too. Thanks for any help


text:
Q: Hacer pivot a una tabla con un cursoren sql server Cordial saludo.
Lo que deseo hacer es un cursor que me permita hacer pivot a una tabla, lo he intentado pero no me funciona.
Esta es la tabla que deseo pivotear:

Este es el código para crear la tabla e insertar los datos:
   CREATE TABLE TABLA_1 (
          TERMINAL VARCHAR(MAX),
          TEXT_NAME VARCHAR(MAX),
          CONTENT VARCHAR(MAX)
   );

INSERT INTO TABLA_1 (TERMINAL,TEXT_NAME,CONTENT) VALUES('34','ID RAN','2');
INSERT INTO TABLA_1 (TERMINAL,TEXT_NAME,CONTENT) VALUES('34','NOMBRE RAN','PORT_L');
INSERT INTO TABLA_1 (TERMINAL,TEXT_NAME,CONTENT) VALUES('34','NOMBRE RAN','LOR_P');
INSERT INTO TABLA_1 (TERMINAL,TEXT_NAME,CONTENT) VALUES('56','ID RAN','5');
INSERT INTO TABLA_1 (TERMINAL,TEXT_NAME,CONTENT) VALUES('56','NOMBRE RAN','PROMPT');
INSERT INTO TABLA_1 (TERMINAL,TEXT_NAME,CONTENT) VALUES('78','ID RAN','5');
INSERT INTO TABLA_1 (TERMINAL,TEXT_NAME,CONTENT) VALUES('78','ID AS','9');
INSERT INTO TABLA_1 (TERMINAL,TEXT_NAME,CONTENT) VALUES('88','POL_L','DEFINIDO');

y este es el resultado que espero:

Cabe aclarar que estos datos son de ejemplo, solo quiero saber si se puede dar vuelta a una tabla con un cursor y si la respuesta es sí, quisiera saber como. Estoy empezando con sql server.
Agradezco la ayuda.

A: Poder, claro que se puede, pero salvo el sentido didáctico del uso de cursores, en TSQL, hacerlo como dices, no lo tiene.
--- Variable de tabla para salida
Declare @Vartablesalida Table
                              (
                              terminal VarChar(Max)
                            , ran1     VarChar(Max)
                            , nombre   VarChar(Max)
                            , ran2     VarChar(Max)
                            , idas     VarChar(Max)
                            , pol      VarChar(Max)
                              );

---------------------------------------------------------------------------
--- Declaración de variables que recogen los valores de la query del cursor
DECLARE @TerminalValue varchar(max);
Declare @TextNameValue varchar(max);
Declare @ContentValue varchar(max);
---------------------------------------------------------------------------

--- Declaración del cursor
DECLARE miCursor CURSOR FOR
SELECT TERMINAL, TEXT_NAME, CONTENT
FROM dbo.TABLA_1;

--- Apertura del cursor
OPEN miCursor
--- Datos a variables.
 FETCH NEXT FROM miCursor INTO @TerminalValue, @TextNameValue,@ContentValue
WHILE @@FETCH_STATUS = 0 --bucle
BEGIN
    -- Trabajamos con las variables los datos a obtener

    Insert into @varTableSalida (TERMINAL, ran1, Nombre, ran2, idas, pol)
    values (
        @TerminalValue, -- 1ª COLUMNA
        case @TextNameValue when 'ID RAN' THEN @ContentValue ELSE '' END, --2ª COLUMNA
        case @TextNameValue when 'NOMBRE RAN' THEN @ContentValue ELSE '' END, --3ª COLUMNA
        '', -- 4ª COLUMNA
        case @TextNameValue when 'ID AS' THEN @ContentValue ELSE '' END, --5ª COLUMNA
        case @TextNameValue when 'POL_L' THEN @ContentValue ELSE '' END --6ª COLUMNA
        );

--- Datos a variables.
 FETCH NEXT FROM miCursor INTO @TerminalValue, @TextNameValue,@ContentValue
END --- fin de bucle

--- cierre de cursor
CLOSE miCursor
--- liberar recursos
Deallocate miCursor

Select t.terminal
     , t.ran1 As [id ran]
     , t.nombre As [nombre ran]
     , t.ran2 As [id ran]
     , t.idas As [id as]
     , t.pol As pol_l
       From @Vartablesalida As t;

Para el ejemplo, primero declaro una variable de tabla que contendrá los datos temporales que se irán insertando en cada vuelta del cursor. Luego las variables que contendrán los datos leídos de la tabla origen, fila por fila. Y posteriormente la declaración del cursor.
Una vez ya está todo preparado, abrimos el cursor e iniciamos el bucle, siempre que la query devuelva alguna fila.
Insertamos en la variable tipo tabla, los datos para presentar la fila. Utilizo una sentencia case para escoger en función de los valores que tenga la variable textNameValue.
Y se va llenando la variable de tabla conforme el cursor va alimentándose de filas
Luego cerramos el cursor y liberamos recursos (muy importante).
Y por último extraemos el resultado.

Cursores TSQL
Nota: Siempre que puedas, evita los cursores

A: Si lo que buscas es que sea dinámico, no necesitas un cursor, si realmente quieres
un "cursor dinámico", solo adapta el código:
DECLARE @columnas AS NVARCHAR(MAX),
        @scritp     AS NVARCHAR(MAX)

select @columnas = STUFF((select distinct ',' + QUOTENAME(TEXT_NAME)
                          from TABLA_1
                          FOR XML PATH(''), TYPE
                          ).value('.', 'NVARCHAR(MAX)') ,1,1,''
                         )
set @scritp = 'select TERMINAL,' + @columnas + ' from
            (  select TERMINAL, CONTENT, TEXT_NAME
                from TABLA_1
            ) data
            pivot
            (
                max(CONTENT)
                for TEXT_NAME in (' + @columnas + ')
            )piv'
execute(@scritp)