text:
Q: PSFTP rename file extension I'm using a PSFTP script to upload files to a remote server for processing and there are specific steps that I need to take with file in order for the file to be processed correctly by their system. Specifically, I have to upload the file with a ".u01" in the extension, then rename it to a ".r01". after it has been uploaded.
Is there a way to replace just the extension of the uploaded file? The rest of the filename can't be modified because the filename is corresponds with the contents of the file.
And no, I can't just upload it with a ".r" extension. Tried that already :P
The script is simple. It uploads all files from the "to_upload" directory into "ul" on the remote server:
 cd ul
 put -r to_upload/


text:
Q: Doesn't compile addthis on iOS I followed the quick guide to install AddThis and I don't know what is wrong, but I can't compile.
I have this errors:
Undefined symbols for architecture armv7:
  "_OBJC_CLASS_$_AddThisSDK", referenced from:
      objc-class-ref in FinishingScene.o
  "_OBJC_CLASS_$_FBSession", referenced from:
      objc-class-ref in AppDelegate.o
ld: symbol(s) not found for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Thanks in advance!

A: I haven't used AddThis, but this smells like the library isn't added in to the project properly.
Click on your target, then Build Phases, then expand Link Binary With Libraries. Make sure all the .a and .framework files you added to the project are listed there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which shebang line should I use? There are scripts in my project that run fine without the first line (like #!/bin/) – without any interpreter path.
So these scripts are running fine, in some cases they fail, but when they run – they execute fine.
I need to modify and put a shell interpreter as the first line.
The problem here is that some scripts fail when I use #!/bin/ksh while others fail when I use #!/bin/bash.
Can anyone tell me when to use which option?
How can I make sure they will work fine, any other way to generalize and make the interpreter common for all the scripts?

A: Each script is written in a certain programming language - bash, ksh, zsh, python, Perl .... You can't for instance write a Python program and hope that Perl can run it. Similarily, a ksh program needs to be executed by ksh, a bash program by bash.
Now, since bash, ksh, zsh and Posix shell do have common subset, it is possible to execute it with any of these command processors. If - and only if! - you are sure that this applies to these scripts, I would propose to use Posix shell, because this is the most restrictive one.
But if people designate a script as bash, or as ksh, or what else, the maintainer of the script might sooner or later use features which are particular to only one of this shell languages. Of course you could require that everyone is programming in, say, ksh, but this is a political question, not technical one.

A: Whether to use bash or ksh is a matter of opinion. However, when the #! is missing, the default shell of /bin/sh is used (or, I thought, is supposed to; bash appears to execute the script with bash.), and how that shell works is defined by the POSIX standard. If you write shell code that conforms to that standard, you can execute it with any POSIX-compatible shell (bash, ksh, dash, etc.) and expect the same results in each case.
If you choose to use features that are specific to a given shell, then you need to ensure that your script is executed with that shell. A script that uses features specific to ksh will not run correctly, e.g., under bash


text:
Q: Crashlytics Flutter iOS: not logging RAM and disk free data There is a default RAM free and Disk free fields in Device data that are automatically populated when a crash occurs.
In Android this works fine, but in iOS it seems to be logging 0 B for those two fields.

Is that a bug, an iOS limitation in Crashlytics or did I forget to set up something?


text:
Q: How to implement auto close SFSafariViewController when process in it is finished? I try to call Webview in my iOS apps, inside the Webview there is form that needs to be submitted. When submission finished in the Webview, i hope sfsafaricontroller is closed automatically and show popup or present something.
To make it happen, is there something that need to be call in the webview ? like deeplink or something else to trigger my mobile apps?
How to do that implementation ?
e.g. : Marketplace apps calls payment webview and when payment is done , autoclose the payment webview and present something else
I've never done it before so i don't have any idea or experience, Thanks for help


text:
Q: How to trigger daily APEX atuomated processes, using Batch or Queueable? I want to create a automated process in APEX that would run daily.  My job look like this:
global without sharing class TriggerBot {

    @InvocableMethod(label='Trigger Bot' description='Trigger Bot')
    global static void TriggerBot(List<TriggerBotParameters> params) {
        System.debug('Trigger Bot Started');
    }
}

I wrote a scheduler to trigger my job, which check the correct day of week in the database entry:
global class BotScheduler implements Schedulable {
    global void execute(SchedulableContext ctx) {
        Date d = System.today();
        Datetime dt = (DateTime)d;
        String dayOfWeek = dt.format('EEEE');

        // Run all bots on the same day of week
        List<Setting__c> configs =
            [SELECT Id FROM Setting__c WHERE Schedule_Day_of_Week__c = :dayOfWeek];

        for(Integer i =0; i<configs.size(); i++){
            Setting__c curSetting = configs[i];
            TriggerBotParameters triggerParam = new TriggerBotParameters();
            triggerParam.ConfigurationId = curSetting.Id;
            // how to trigger the job from here?
        }
    }
}

I am stuck on how to actually trigger the process job from the scheduler?  Should I use a queueable job or use a batch?  And how do I set it up?


text:
Q: Custom Item Template for ComboBox Items I had the following XAML looking just as I want it to look. It's basically a dropdown menu with checkboxes and some text to them.
<ComboBox x:Name="comboBox">
  <ComboBoxItem><CheckBox>WeeHee</CheckBox></ComboBoxItem>
  <ComboBoxItem><CheckBox>BuuHuu</CheckBox></ComboBoxItem>
</ComboBox>

Then I learned that the options are possible to be dynamically adapted so I changed the markup and bound the combobox to an array. That works perfectly well functionality-wise but now I get only the names of the options, while the checkboxes are gone.
<ComboBox x:Name="comboBox"
          ItemsSource="{x:Static local:MainWindow.AllKinds}">
</ComboBox>

So I'm looking for a way to create a custom item for populating the combobox but still so that the data is dynamically bound. I'm assuming WPF/XAML supports such functionality and I'm just too ignorant to know what to google for.
So my request is a rudimentary example or suggestion on what to google for. (Might be something seemingly obvious to everybody but me.)

A: So with most of the controls that offer up things from ItemSource there's a nifty built in feature that allows you to specify how each item should look/behave etc. So you can specify each Item in your ComboBox's by setting your own ItemTemplate.
Since a ComboBox just uses an ItemsControl to list its items, you can utilize this via ComboBox.ItemTemplate to make your items however you like, in this case probably something like (in pseudo).
<ComboBox>
  <ComboBox.ItemTemplate>
    <DataTemplate>
       <CheckBox>
    </DataTemplate>
  </ComboBox.ItemTemplate>
</ComboBox>

Hope this helps, its some pretty handy info to know for when you want to start customizing Item generated lists between wpf, silverlight, wp, win-rt, etc. Cheers!


text:
Q: How to update a row in sql with loop? I'm trying to figure how to call a query once.
I have 6 different variables for images, title and desc.
In this code, I need to know how to loop for id from 0 to 6.
    $date = new DateTime("NOW");

    $image1 = 'SSSS';
    $title1 = 'AAAA';
    $desc1 =  'BBBB';

    $image2 = 'RRRR';
    $title2 = 'GGGG';
    $desc2 =  'VVVV';

    ///  4 vars later....

    $id = 6;

    $get = $this->db->queryRow("UPDATE `featured` SET `image` = '{$image.$id}', `title` = '{$title.$id}', `desc` = '{$desc.$id}', `date` = '{$date->format('Y-m-d H:i:s')}' WHERE id = '{$id}'");
    return(object) $get;

A: I have tried to use a simple $query model and it works fine.
Create a valid Query string to pass to the db
<?php
$query = "UPDATE `featured` SET `image` = '".$image.$id."', `title` = ".$title.$id."', `desc` = '".$desc.$id}."', `date` = '".$date->format('Y-m-d H:i:s')."' WHERE id = '".$id."';"

$result=$mysqli->query($query);
  // Verify results
if(!$result) {
  $ErrMessage  =  "ErrSqlQuery:" . $mysqli->error . "\n";
  $mysqli->close();
  die($ErrMessage);
}

you can check also the result by
echo  $mysqli->affected_rows;
?>

A: $query_build = "";
foreach($arr as $$image){
    $query_build .= "UPDATE `featured` SET `image` = '{$image.$id}', `title` = '{$title.$id}', `desc` = '{$desc.$id}', `date` = '{$date->format('Y-m-d H:i:s')}' WHERE id = '{$id}';";
}
$get = $this->db->queryRow($query_build);

Accumulate all the queries and execute all at once.

A: To build a collection of Querys use the multi_query function.
Loop to build your Query string to pass to the db and concatenated by a semicolon.
<?php
for($i=0;$i <= $maxquerys;$i++){
  $query = "UPDATE `featured` SET `image` = '".$image.$id."', `title` =     ".$title.$id."', `desc` = '".$desc.$id."', `date` = '".$date->format('Y-m-d H:i:s')."' WHERE id = '".$id."';"
}

/* execute multi query */
if ($mysqli->multi_query($query)) {

  while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();

you may check also the result by
echo  $mysqli->affected_rows;
?>


text:
Q: Filter Visual Studio 2008's "Members" drop-down box Myself, along with my coworkers, aren't aware of any way to filter what is show in the "Members" drop-down box in Visual Studio.  This is the drop-down box that lets you jump to different methods and functions depending on where you're at inside your project.
I find it very useful, but it'd be nice to not show a bunch of items I'll never use; such is the case with displaying all of the labels I've created on a Windows form.
Any ideas?

A: If you don't plan to reference a label anywhere in your code, you can change the GenerateMember property to false from the designer.  This will create the label locally within the InitializeComponent method - and will no longer show up in your list.


text:
Q: $(...).tabs is not a function I have this code on two pages on my site, but at one page the function doesn't work. Firebug shows me " $(...).tabs is not a function ". I don't understand why, can anyone tell me what is wrong ?
this is working:
http://www.invat-online.net/variante-rezolvate
this is not working:
http://www.invat-online.net/variante-explicate-limba-romana/varianta-01
Here is the code:

Subiect I

Subiect II

Subiect III

content here

content here

content here

$(document).ready(function() {
   $("#tabss").tabs();
});

A: In my case:
I was using
jquery-ui-1.10.3.minimal.min.js

instead of
jquery-ui-1.10.3.custom.min.js

minimal version does not include ui.tabs.js, hence no ui.tabs function. Hope this helps someone else out there

A: The issue is that the jQuery UI js and css is not loading.
Try changing the path in you

<link href="/stylesheets/smoothness/jquery-ui-1.9.2.custom.min.css" rel="stylesheet" />

A: You have relative paths to javascript files:
javascript/jquery-ui-1.9.2.custom.min.js
change them to absolute paths because you're using mod_rewrite module
/javascript/jquery-ui-1.9.2.custom.min.js
In first link the server is looking to the directory
http://www.invat-online.net/javascript/my_js_file.js (which exists)
but in the second one the path will be
http://www.invat-online.net/variante-explicate-limba-romana/javascript/my_js_file.js which do not exists

A: Your first demo loads:
http://www.invat-online.net/javascript/jquery-ui-1.9.2.custom.min.js

Your second demo attempts to load:
http://www.invat-online.net/variante-explicate-limba-romana/javascript/jquery-ui-1.9.2.custom.min.js

The last one results in a 404. You should correct the path of the later, perhaps instructing it to find jQuery UI in one directory above the current: ../jquery-ui-1.9.2.custom.min.js.

A: Try this:
@section scripts{
$(document).ready(function() {
    $("#tabss").tabs();
});
}

Put @Scripts.Render("~/bundles/jqueryui") in the  of your layout.cshtml

A: The error Uncaught TypeError: $(...).tabs is not a function may also be produced when in a Django project on the Admin area and using django-tabbed-admin under the following setup:

*

*Django = 1.10.5

*django-tabbed-admin=1.0.4

*DEFAULT_JQUERY_UI_JS = 'tabbed_admin/js/jquery-ui-1.11.4.min.js'

The problem is that the code in jquery-ui-1.11.4.min.js for this Django lib is as follows:
    /*! jQuery UI - v1.11.4 - 2015-07-27
    (...)*/
    jQuery = jQuery || django.jQuery.noConflict(false);

and the code on django-tabbed-admin uses it this way (change_form.html):

To sort this out this should be what would be passed in to the IIFE instead of the (django.jQuery) as above:

I've reported this issue in the project and created a PR with a fix for it. Waiting on it to be approved, so in the meantime you can sort it following my simple fix.
I hope this helps someone out there.

A: Check your page you might have loaded multiple versions of jQuery

A: I had the same problem, I realized that I had jquery and bootstrap css imports that enter in conflict each other. Take a look to the ones you have imported and reduce those imports to the minimum to see which is the conflict.
Here there is an example of how to implement it, I took that example and worked, then I adapted to my application:
for jquery 1.9 (click on view source to see the code)
http://jqueryui.com/tabs/
for jquery 1.8 (check the example at the end of the page)
http://api.jqueryui.com/1.8/tabs/
Hope it helps!


text:
Q: Qt nested QsqlQuery not working I have the following problem:
I try to execute two nested queries but after I execute the secon query the results of the first query are deleted or whatever.
Example:
I have two items in the items table and two entries in the lendings table.
The first query holds these 2 items as a result but after the second query based on the first items is executed the sqlQuery.next() method does not deliver the second item anymore.
I hope it is understandable, sorry for that!
This is the method which loads items from the sqlite database:
ItemsList *DatabaseManager::getAllItems() {

this->db.open();

ItemsList* fetchedItems = new ItemsList();
QSqlQuery sqlQuery;

if (sqlQuery.exec("SELECT * FROM items ORDER BY name COLLATE NOCASE")) {
    while (sqlQuery.next()) {
        Item* fetchedItem = new Item();

        fetchedItem->setItemId(sqlQuery.value(0).toInt());
        fetchedItem->setName(sqlQuery.value(1).toString());
        addLendingsToItem(fetchedItem);

        ItemNode* fetchedItemNode = new ItemNode(fetchedItem);
        fetchedItems->add(fetchedItemNode);
    }
} else {
    qDebug() << sqlQuery.lastQuery();
    qDebug() << sqlQuery.lastError().text();
}
if (this->db.isOpen()) {
    this->db.close();
}
return fetchedItems; }

And this is the method which holds the second query:
void DatabaseManager::addLendingsToItem(Item* fetchedItem) {

QSqlQuery sqlQuery;
sqlQuery.prepare("SELECT i.itemId, i.name, l.lent, l.personId FROM items i JOIN lendings l ON i.itemId = l.itemId WHERE i.itemId = :itemId");               sqlQuery.bindValue(":itemId", fetchedItem->getItemId());
sqlQuery.bindValue(":itemId", fetchedItem->getItemId());

if (sqlQuery.exec()) {
    while (sqlQuery.next()) {
        if (sqlQuery.value(2).toInt() == 1) {
            fetchedItem->setPerson(getPerson(sqlQuery.value(3).toInt()));
            fetchedItem->setIsLent(true);
        } else {
            fetchedItem->getLentByList()->add(new PersonNode(getPerson(sqlQuery.value(3).toInt())));
        }
    }
} else {
    qDebug() << sqlQuery.lastQuery();
    qDebug() << sqlQuery.lastError().text();
} }


text:
Q: Writing 1.5 million rows in a file using Python 3+ I am trying to write sql statements into a sql file to create 10,000 tables. Each table containing 5 columns with 1.5 million rows of data in each column.
text_file = open("D:\Output.sql", "a", encoding="utf-8")
count = 0
for i in range(1,10001):
    a=[]
    b=[]
    x='Tab_'+str(i)

    a.append(random.choice(name)+'_'+str(i))
    a.append(random.choice(ssn)+'_'+str(i))
    a.append(random.choice(address)+'_'+str(i))
    a.append(random.choice(dob)+'_'+str(i))
    a.append(random.choice(phone)+'_'+str(i))

    text_file.write('create table Python_test.'+ x + '(' +
                    a[0] + ' VARCHAR(255),' +
                    a[1] +' VARCHAR(255),' +
                    a[2] +' VARCHAR(255),' +
                    a[3] +' VARCHAR(255),' +
                    a[4] +' VARCHAR(255));\n')
    #print('\n')

    for j in range(1,1500001):
        #print(i)
        #print(a)
        text_file.write('insert into '+ x + '('   +
                         a[0]+','+a[1]+','+a[2]+','+a[3]+','+a[4]+
                        ') values (\''+
                        fake.name()+'\',\''+rstr.xeger(random.choice(sList))+'\',\''+
                        fake.address()+'\',\''+rstr.xeger(random.choice(dbList))+'\',\''+
                        rstr.xeger(random.choice(pList))+'\');\n')

    text_file.write('\n')
    count=count+1
    print(count)

text_file.close()

The 2 for loops are taking a lot of time. Is there any way to optimize this code to minimalize the amount of time taken to execute this code?

A: A few pieces of advise, not a complete solution.
Do not concatenate strings. Writing to the file will already concatenate them. Consider:
def write_all(f, *pieces):
  for piece in pieces:
    f.write(piece)

# Now you can:

write_all(
  text_file,
  'create table Python_test.', x, '(',
  a[0], ' VARCHAR(255),',
  # etc ad libitum.
  ');\n'
)

In the meantime you can do away with a[0], etc and name things nicely, and also compute str(i) only once.
Open your output file as binary (so you don't spent any time on the universal newline conversion or encoding checking), and, most importantly, with a large buffer:
with open("file.sql", "wb", 4000000) as text_ file:
  # Do your generation here

Run several processes, for different sub-ranges of i, in parallel, writing to different physical devices. I suppose the code is heavily I/O-bound, and mostly waits for writes to complete. Several parallel processes could generate some more data while the previous portion from  different process is consumed by the filesystem; multiprocessing module should make it simple.
But don't expect a miracle. You are generating 10k files several MBs each, this is many tens of GBs worth of data. It will take some time to just settle on the disk, even the fastest m.2 SSD, especially given the (not very fast) NTFS filesystem.
On a slow disk, it might be useful to pass the output through gzip, as it it is generated, so that fewer bytes hit the disk. It should compress pretty well, given the huge amount of common substrings. Then you could unpack the files on the fly while feeding to the database(s) you are testing (because what else could it be?..).

A: It's usually more efficient to write large files in batches of lines rather than one line at a time. Try building a string of 1000 lines concatenated together (making sure you separate them with \n) and then writing the batch to the file before starting the next one.
You can experiment with different batch sizes to get a suitable balance between speed and memory usage.


text:
Q: Define numeric constant in VS C++ (2013) project Is it possible to add define like this
#define API_VERSION 42

to VC++ project settings?
I tried in Project Settings -> C/C++ -> Preprocessor -> Preprocessor definitions but
API_VERSION 42

doesn't seem to work there, only
API_VERSION

which sets it to 1.

A: To set specific values, use =: API_VERSION=42
You separate additional defines with ;: API_VERSION=42;USE_DEBUG


text:
Q: ExtJS. Can i put new cells or rows into rendered panel, with layout : 'table' For Example:
var tablePanel = new Ext.Panel({
        border: false,
        autoScroll: true,
        layout: 'table',
        layoutConfig: { columns: maxColumns },
        items: items
    });

Can i add rows or cells to that table? And how can i do that? with method .add or? Thanks.

A: I think so.
tablePanel.add(whatever);
tablePanel.add(whatever2);
tablePanel.add(whatever3);
tablePanel.add(whatever4);
...
tablePanel.doLayout();

In the table layout, there are no explicite row objects; just every group of n columns are one row (ignoring rowspan and colspan), n being the value of layoutConfig: { columns: n }


text:
Q: What packages do I need in order to install scikit-learn on Debian I want to install scikit-learn with pip on a Debian Squeeze workstation to which I don't have root access. Apparently, the workstation administrator here is getting tired of my frequent package installation requests every week, so I'd prefer to finish it in one shot. What Debian Squeeze packages exactly do I need in order to install scikit-learn? It appears to me that liblapack-dev and libblas-dev are neccessary. Is there anything else missing?

A: The exact list of dependencies is written in the the documentation.
scikit-learn is available in recent versions of Debian, so if you want to install all the scikit-learn build dependencies at once you can just do:
sudo apt-get build-dep python-sklearn

Also the Neuro Debian APT repository is updated at each scikit-learn release, so that you can get debian packages for the latest versions from there.


text:
Q: Cyrillic symbols in INSERT query $dblocation = "localhost";
$dbname = "xx";
$dbuser = "xx";
$dbpasswd = "xx";
$dbcnx = @mysql_connect($dblocation,$dbuser,$dbpasswd);
mysql_select_db($dbname, $dbcnx);
mysql_query("SET NAMES utf8");
mysql_query("SET COLLATION_CONNECTION=utf8_bin");
$name = mysql_real_escape_string($name);
$about = mysql_real_escape_string($about);
mysql_query("INSERT INTO votes
(name, about, active) VALUES('".$name."', '".$about."', 1 ) ")
or die(mysql_error());

It works perfectly fine when $name and $about is not cyrillic. But when it's cyrillic - script just adds a row with blank name and about fields. What do?
DB is UTF-8, manual adding rows with phpMyAdmin with cyrillic symbols works perfect, PHP-script is UTF-8, everything's UTF-8.

A: You should have:
1.header ("Content-Type: text/html; charset=utf-8"); or <meta http-equiv="content-type" content="text/html; charset=utf-8" />
2.mysql_query("SET NAMES 'utf8'");
3.Set your file's encoding to utf-8 without BOM

A: Specify character set which should be used by the connection with mysql_set_charset(...'). See http://php.net/manual/en/function.mysql-set-charset.php.

A: I've dealt a lot with the cyrillic and it is tricky indeed. So far in my experience I did not use any COLLATION_CONNECTION. All I do is put, as you did, all possible files in utf8. Then the fields in the DB I put in "utf8_unicode_ci" and I only use the SET NAMES params to set the connection encoding. This should be enough. Mind that the Set names might be tricky, as only a single space in extra and it will not work. I use:
define("DBENCODING", "utf8");
mysql_query("SET NAMES '".DBENCODING."'", $this->connection);

I hope I managed to help.


text:
Q: What Database, and In Which Setup Can handle Several Millions Inserts Per Minute? We have come to a point where for few of our customers' systems, at peak times, events are generated at that crazy rate. That is, millions of new events per minute (between 1M and 2M).
The records/docs size are 1.5Kb on average.
Is there a database that can handles such radical writing speed out there (16K - 32K Inserts per second)?
There are several candidates out there, Cassandra, Hive, Hadoop, HBase, Riak and perhaps few others, but I am willing to know from someone's else experience and not just quoting from each db-system's website self testimonials.
If you have handled such load at your work, your advise is highly appreciated.

A: Couchbase can easily handle that write speed. Not sure what budget you have (what size machines you will look at), but getting a trio of m3.2xl's can easily do 80K/s and still have replication for redundancy and failover. Of course, configuring with raid0 multiple ebs volumes and provisioned IOPS will keep things humming.
Of course I would ask more questions about it if we get more specific, like how much of that is working set that needs read access, etc. which can help tune the solution.


text:
Q: Xamarin Android release compile error I've tested every solution proposed for my problem. In particular, my app build correctly in Android debug mode, not in release mode. The error returned is:
/Library/Frameworks/Mono.framework/External/xbuild/Xamarin/Android/Xamarin.Android.Common.targets: Error: Error executing task LinkAssemblies: error XA2006: Reference to metadata item 'System.Void Xamarin.Forms.Binding::.ctor(System.String,Xamarin.Forms.BindingMode,Xamarin.Forms.IValueConverter,System.Object,System.String)' (defined in 'XFormsProvider, Version=0.1.7.26981, Culture=neutral, PublicKeyToken=null') from 'XFormsProvider, Version=0.1.7.26981, Culture=neutral, PublicKeyToken=null' could not be resolved.
My package.config file is:
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Acr.Settings" version="5.1.1" targetFramework="MonoAndroid70" />
  <package id="Acr.Support" version="2.1.0" targetFramework="MonoAndroid70" />
  <package id="Acr.UserDialogs" version="6.3.1" targetFramework="MonoAndroid70" />
  <package id="AndHUD" version="1.2.0" targetFramework="MonoAndroid70" />
  <package id="BCrypt.Net-PCL" version="1.0.1" targetFramework="MonoAndroid70" />
  <package id="ExifLib.PCL" version="1.0.1" targetFramework="MonoAndroid70" />
  <package id="Microsoft.CSharp" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="Newtonsoft.Json" version="9.0.2-beta2" targetFramework="MonoAndroid70" />
  <package id="PCLStorage" version="1.0.2" targetFramework="MonoAndroid70" />
  <package id="RestSharp" version="105.2.3" targetFramework="MonoAndroid70" />
  <package id="Splat" version="1.6.2" targetFramework="MonoAndroid70" />
  <package id="System.Collections" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.ComponentModel.Annotations" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.ComponentModel.TypeConverter" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Dynamic.Runtime" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Globalization" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.IO" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Linq" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Linq.Expressions" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.ObjectModel" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Reflection" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Reflection.Extensions" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Runtime" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Runtime.Extensions" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Runtime.Numerics" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Runtime.Serialization.Primitives" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Text.Encoding" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Text.RegularExpressions" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Threading" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Threading.Tasks" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Xml.ReaderWriter" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="System.Xml.XDocument" version="4.3.0" targetFramework="MonoAndroid70" />
  <package id="Xam.Plugin.Connectivity" version="2.3.0" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Android.Support.Animated.Vector.Drawable" version="23.3.0" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Android.Support.Design" version="23.3.0" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Android.Support.v4" version="23.3.0" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Android.Support.v7.AppCompat" version="23.3.0" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Android.Support.v7.CardView" version="23.3.0" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Android.Support.v7.MediaRouter" version="23.3.0" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Android.Support.v7.RecyclerView" version="23.3.0" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Android.Support.Vector.Drawable" version="23.3.0" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Build.Download" version="0.4.2" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Firebase.Common" version="32.940.0-beta3" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Firebase.Iid" version="32.940.0-beta3" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Firebase.Messaging" version="32.940.0-beta3" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Forms" version="2.3.3.180" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Forms.RangeSlider" version="0.6.14" targetFramework="MonoAndroid70" />
  <package id="Xamarin.Forms.XamlProvider" version="0.1.7" targetFramework="MonoAndroid70" />
  <package id="Xamarin.GooglePlayServices.Base" version="32.940.0-beta3" targetFramework="MonoAndroid70" />
  <package id="Xamarin.GooglePlayServices.Basement" version="32.940.0-beta3" targetFramework="MonoAndroid70" />
  <package id="Xamarin.GooglePlayServices.Tasks" version="32.940.0-beta3" targetFramework="MonoAndroid70" />
  <package id="Xamarin.RangeSlider" version="0.6.14" targetFramework="MonoAndroid70" />
  <package id="ZXing.Net.Mobile" version="2.1.47" targetFramework="MonoAndroid70" />
  <package id="ZXing.Net.Mobile.Forms" version="2.1.47" targetFramework="MonoAndroid70" />
</packages>

My Target SDK version is Android 7 and my minimum sdk version is 19.
Have you any idea/solution?
Thanks.


text:
Q: Valgrind memcheck invalid read of size 1 This example can be compiled and works as expected.
1 #include  <stdlib.h>
2 #include  <stdio.h>
3 #include  <string.h>
4
5 char * getstr() {
6     return strdup("Hello");
7 }
8
9 void *memcpy2(void *dest, const void *src, size_t len)
10 {
11     char * d = dest;
12     const char * s = src;
13
14     for (size_t i = 0; i < len; i++) {
15         d[i] = s[i];
16     }
17     return dest;
18 }
19
20 int main()
21 {
22     char buf[256];
23     char *str = getstr();
24
25     memset(buf, 0, 256);
26     memcpy2(buf, str, 255);
27
28     printf("%s\n", buf);
29
30     free(str);
31     return 0;
32 }

I reimplemented memcpy to have complete control over the test, making it independent from underlaying libc. As you can see, valgrind complains with this warning:
$ valgrind ./a.out
==9479== Memcheck, a memory error detector
==9479== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==9479== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==9479== Command: ./a.out
==9479==
==9479== Invalid read of size 1
==9479==    at 0x4006B6: memcpy2 (k.c:15)
==9479==    by 0x400731: main (k.c:26)
==9479==  Address 0x5203046 is 0 bytes after a block of size 6 alloc'd
==9479==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9479==    by 0x4EC48D9: strdup (strdup.c:42)
==9479==    by 0x400673: getstr (k.c:6)
==9479==    by 0x4006F3: main (k.c:23)
==9479==
Hello
==9479==
==9479== HEAP SUMMARY:
==9479==     in use at exit: 0 bytes in 0 blocks
==9479==   total heap usage: 2 allocs, 2 frees, 1,030 bytes allocated
==9479==
==9479== All heap blocks were freed -- no leaks are possible
==9479==
==9479== For counts of detected and suppressed errors, rerun with: -v

I don't understand why this "invalid read of size 1" message appears. It has not sense for me at all. Can some of you explain what is wrong with this code? Thank you in advance!

A: [...]
for (size_t i = 0; i < len; i++) {
    d[i] = s[i];
}
[...]

Here len is 255, but the string pointed by s is less than 255 length, so you're going out of the array. You could maybe use the '\0' placed by strdup() to avoid this bug.

A: In main the str variable points to a memory area of six bytes length (the string "Hello" is the five characters in the string plus terminator, strdup will allocate strlen("Hello") + 1 bytes). Going out of bounds leads to undefined behavior.
And you are going out of bounds since you want to read 255 bytes from this six-byte area.


text:
Q: Changing value of Block function from observer I have an observer function on the event checkout_cart_add_product_complete that is pulling parameters out of the URL and modifying the cart based on the parameters.  This portion is all working fine.
However, there is a block injected by a 3rd party module that sets a value on radio buttons based on a function that evaluates settings in the Magento backend.  I would like to override the value returned by this function based on the results of my observer.
What would the best way to go about this be?

A: maybe it's not the best way, but in your etc/modules/YOURMODULE.xml, you can add  something like
<?xml version="1.0" ?>
<config>
    <modules>
        <YOUR_MODULE>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <3rdparty_Module/>
            </depends>
        </YOUR_MODULE>
    </modules>
</config>

This will allow your module be loaded after the 3rd party module, so it will override any similar functions.


text:
Q: VSCode / Docker devcontainer.json Issue Within VSCode there is an extention Remote - Containers with option to save the installed extensions to a file name devcontainer.json. This allows VSCode to install the necessary extensions when you are using a container-based environment.
However, this is not working. When I select the following option, no file is created. Or if I create the file it is not updated.

My VSCode setup is:
* Win10
* VSCode 1.44.2
* This is being performed via the WSL2 remote connection.
Many Thanks,

A: Indeed Remote - Containers fails to put extensions' ids into devcontainer.json... unless you create the .devcontainer/devcontainer.json AND unless you put there some content:
{
  "extensions": []
}

should be enough.
Actually, even
{
}

is enough.


text:
Q: PL/SQL : given two numeric ranges, how to detect an inclusion or an intersection? I have two numeric ranges [1, 100] and [50, 200] :
1       100
50      200

*

*This is an intersection

Another case : with the ranges [40, 100] and [10, 200]
40      100
10      200

*

*This is an inclusion

How can I write an SQL query (or a PL:SQL procedure) that detects the inclusion / intersection.
I tried using minus but it doesn't work in all cases.
EDIT 1
The ranges are passed to the procedure as rows in a table.

A: Here's one way:
WITH sd AS (SELECT start_range,
                   end_range,
                   row_number() OVER (ORDER BY start_range, end_range) rn
            FROM   sample_data)
SELECT sd1.*,
       sd2.*,
       CASE WHEN sd1.start_range >= sd2.start_range AND sd1.end_range <= sd2.end_range THEN 'INCLUSION'
            WHEN sd2.start_range >= sd1.start_range AND sd2.end_range <= sd1.end_range THEN 'INCLUSION'
            WHEN sd1.start_range <= sd2.end_range AND sd1.end_range >= sd2.start_range THEN 'INTERSECTION'
            ELSE 'NONE'
       END range_overlap_type
FROM   sd sd1
       INNER JOIN sd sd2 ON sd1.rn = 1 AND sd2.rn = 2;

A: with source1 as
 (select 60 f, 100 s
    from dual
  union
  select 50 f, 200 s from dual),
t as
 (select source1.*, rownum rn from source1)
select case
         /*(1, 100), (50, 90)*/
         when t1.f <= t2.f and t1.s >= t2.s then
          'Inclusion'
         /*(1, 100), (50, 150)*/
         when t1.f <= t2.f and t1.s < t2.s then
          'Intersection'
       end result
  from (select * from t where rn = 1) t1, (select * from t where rn = 2) t2

I have given the possible two cases as comments


text:
Q: Generating combinations of data based on probability of previous data I have a data set(Example) of the following type:
Food Type: Chinese, Indian, Thai, Mexican
Ingredient 1: Salt, Chinese Salt
Ingredient 2: Chilli, Red Chilli, Thai Chilli, Green Chilli
Ingredient 3: Turmeric, Cardamom,
Ingredient 4: Chicken, Beef, Fish, Tofu
I have some combinations of data made by hand and I classified them in different food types based on ingredients and recipes. I need to generate more data based on the most probable combinations. One way I have done it so far is to generate all combinations of all ingredients and then classify them into food types based on previous learning. But this approach will not be practical as the data is large. Each category of ingredient can have more than 30-40 values. Moreover, Ingredients are not just 4, they are much more in real data set.  I am looking for better ways to generate and classify the data than my already proposed approach. I have applied NB classifier to classify the data.  Your help is much appreciated

A: Since I did not get any replies for over 4 four months, I thought of posting my solution which might help someone else.
The technique I used was to get top five most important features from each of the attribute types(food types in my example). Then I made combinations of all those features. For the rest of the features, I chose a value randomly. This generated new data which was manageable in size.
If you need any clarifications, please feel free to ask.


text:
Q: Selecting Array from multidimensional array and save into db table I am trying to list and then insert into a SQL table from this array :
SQL table :
id  time    average_position    search_visibility_index click_potential

data is :
Array
(
    [name] => average_position
    [series] => Array
        (
            [0] => Array
                (
                    [0] => 2020-03-18
                    [1] => 36.27
                )

            [1] => Array
                (
                    [0] => 2020-03-19
                    [1] => 36.23
                )

            [2] => Array
                (
                    [0] => 2020-03-20
                    [1] => 36.18
                )

            [3] => Array
                (
                    [0] => 2020-03-21
                    [1] => 36.07
                )

            [4] => Array
                (
                    [0] => 2020-03-22
                    [1] => 36.53
                )

            [5] => Array
                (
                    [0] => 2020-03-23
                    [1] => 36.65
                )

            [6] => Array
                (
                    [0] => 2020-03-24
                    [1] => 36.21
                )

            [7] => Array
                (
                    [0] => 2020-03-25
                    [1] => 36.08
                )

            [8] => Array
                (
                    [0] => 2020-03-26
                    [1] => 35.87
                )

            [9] => Array
                (
                    [0] => 2020-03-27
                    [1] => 35.53
                )

            [10] => Array
                (
                    [0] => 2020-03-28
                    [1] => 34.6
                )

            [11] => Array
                (
                    [0] => 2020-03-29
                    [1] => 34.19
                )

            [12] => Array
                (
                    [0] => 2020-03-30
                    [1] => 34.11
                )

            [13] => Array
                (
                    [0] => 2020-03-31
                    [1] => 34.08
                )

            [14] => Array
                (
                    [0] => 2020-04-01
                    [1] => 33.09
                )

            [15] => Array
                (
                    [0] => 2020-04-02
                    [1] => 33.03
                )

            [16] => Array
                (
                    [0] => 2020-04-03
                    [1] => 32.96
                )

            [17] => Array
                (
                    [0] => 2020-04-04
                    [1] => 32.64
                )

            [18] => Array
                (
                    [0] => 2020-04-05
                    [1] => 33.08
                )

            [19] => Array
                (
                    [0] => 2020-04-06
                    [1] => 33.03
                )

            [20] => Array
                (
                    [0] => 2020-04-07
                    [1] => 32.83
                )

            [21] => Array
                (
                    [0] => 2020-04-08
                    [1] => 33.02
                )

            [22] => Array
                (
                    [0] => 2020-04-09
                    [1] => 32.75
                )

            [23] => Array
                (
                    [0] => 2020-04-10
                    [1] => 32.27
                )

            [24] => Array
                (
                    [0] => 2020-04-11
                    [1] => 32.18
                )

            [25] => Array
                (
                    [0] => 2020-04-12
                    [1] => 30.64
                )

            [26] => Array
                (
                    [0] => 2020-04-13
                    [1] => 30.6
                )

            [27] => Array
                (
                    [0] => 2020-04-14
                    [1] => 30.56
                )

            [28] => Array
                (
                    [0] => 2020-04-15
                    [1] => 30.53
                )

            [29] => Array
                (
                    [0] => 2020-04-16
                    [1] => 30.1
                )

            [30] => Array
                (
                    [0] => 2020-04-17
                    [1] => 29.86
                )

        )

)
Array
(
    [name] => search_visibility_index
    [series] => Array
        (
            [0] => Array
                (
                    [0] => 2020-03-18
                    [1] => 5.14
                )

            [1] => Array
                (
                    [0] => 2020-03-19
                    [1] => 5.14
                )

            [2] => Array
                (
                    [0] => 2020-03-20
                    [1] => 5.36
                )

            [3] => Array
                (
                    [0] => 2020-03-21
                    [1] => 5.44
                )

            [4] => Array
                (
                    [0] => 2020-03-22
                    [1] => 5.01
                )

            [5] => Array
                (
                    [0] => 2020-03-23
                    [1] => 5
                )

            [6] => Array
                (
                    [0] => 2020-03-24
                    [1] => 5.01
                )

            [7] => Array
                (
                    [0] => 2020-03-25
                    [1] => 5.03
                )

            [8] => Array
                (
                    [0] => 2020-03-26
                    [1] => 4.07
                )

            [9] => Array
                (
                    [0] => 2020-03-27
                    [1] => 5.23
                )

            [10] => Array
                (
                    [0] => 2020-03-28
                    [1] => 4.48
                )

            [11] => Array
                (
                    [0] => 2020-03-29
                    [1] => 4.57
                )

            [12] => Array
                (
                    [0] => 2020-03-30
                    [1] => 5.72
                )

            [13] => Array
                (
                    [0] => 2020-03-31
                    [1] => 5.66
                )

            [14] => Array
                (
                    [0] => 2020-04-01
                    [1] => 5.9
                )

            [15] => Array
                (
                    [0] => 2020-04-02
                    [1] => 5.99
                )

            [16] => Array
                (
                    [0] => 2020-04-03
                    [1] => 6.1
                )

            [17] => Array
                (
                    [0] => 2020-04-04
                    [1] => 6.01
                )

            [18] => Array
                (
                    [0] => 2020-04-05
                    [1] => 6.09
                )

            [19] => Array
                (
                    [0] => 2020-04-06
                    [1] => 5.95
                )

            [20] => Array
                (
                    [0] => 2020-04-07
                    [1] => 5.99
                )

            [21] => Array
                (
                    [0] => 2020-04-08
                    [1] => 6.04
                )

            [22] => Array
                (
                    [0] => 2020-04-09
                    [1] => 5.96
                )

            [23] => Array
                (
                    [0] => 2020-04-10
                    [1] => 6.15
                )

            [24] => Array
                (
                    [0] => 2020-04-11
                    [1] => 5.29
                )

            [25] => Array
                (
                    [0] => 2020-04-12
                    [1] => 5.6
                )

            [26] => Array
                (
                    [0] => 2020-04-13
                    [1] => 6.64
                )

            [27] => Array
                (
                    [0] => 2020-04-14
                    [1] => 6.62
                )

            [28] => Array
                (
                    [0] => 2020-04-15
                    [1] => 6.61
                )

            [29] => Array
                (
                    [0] => 2020-04-16
                    [1] => 6.66
                )

            [30] => Array
                (
                    [0] => 2020-04-17
                    [1] => 5.53
                )

        )

)
Array
(
    [name] => click_potential
    [series] => Array
        (
            [0] => Array
                (
                    [0] => 2020-03-18
                    [1] => 70.73
                )

            [1] => Array
                (
                    [0] => 2020-03-19
                    [1] => 70.74
                )

            [2] => Array
                (
                    [0] => 2020-03-20
                    [1] => 73.77
                )

            [3] => Array
                (
                    [0] => 2020-03-21
                    [1] => 74.89
                )

            [4] => Array
                (
                    [0] => 2020-03-22
                    [1] => 74.35
                )

            [5] => Array
                (
                    [0] => 2020-03-23
                    [1] => 74.19
                )

            [6] => Array
                (
                    [0] => 2020-03-24
                    [1] => 74.34
                )

            [7] => Array
                (
                    [0] => 2020-03-25
                    [1] => 74.71
                )

            [8] => Array
                (
                    [0] => 2020-03-26
                    [1] => 60.46
                )

            [9] => Array
                (
                    [0] => 2020-03-27
                    [1] => 77.58
                )

            [10] => Array
                (
                    [0] => 2020-03-28
                    [1] => 66.51
                )

            [11] => Array
               …

Question is how to save these data with single mysql query as there are multiple arrays. But all of them are based on fixed date time queries.
foreach($contents_series as $avg_array){
DB::table('data_series')->insert(
    ['time' =>$avg_array[0],'average_position' =>$avg_array[0]['url_series'][0]['series'][1]]
);

A: You will need to bring the array to the format in the example. If the dates present and are the same for all arrays, the task is quite trivial - each entry for the date must contain three entries - 'average_position', 'search_visibility_index' and 'click_potential' with corresponding values.
This means that you have to go through each array, take the date from element #0, use it as a key, and add the corresponding array key with its value under element 1.
 <?php

 $yourFirstArray = ['name' => 'average_position', 'series' => [['2020-03-18', 36.27], ['2020-03-19', 36.23]];
 $yourSecondArray = ['name' => 'search_visibility_index', 'series' => [['2020-03-18', 5.14], ['2020-03-19', 5.14]];
 $yourThirdArray = ['name' => 'click_potential', 'series' => [['2020-03-18', 70.73], ['2020-03-19', 70.74]];

 $average_position_series = $yourFirstArray['series'];
 $search_visibility_index_series = $yourSecondArray['series'];
 $click_potential_series = $yourThirdArray['series'];

 $data = [];

 foreach($average_position_series as list($date, $value)) {
     $data[$date]['average_position'] = $value;
 }

 foreach($search_visibility_index_series as list($date, $value)) {
     $data[$date]['search_visibility_index'] = $value;
 }

 foreach($click_potential_series as list($date, $value)) {
     $data[$date]['click_potential'] = $value;
 }

 DB::table('mytable')->insert($data);


text:
Q: How to deserialize gui objects in java I have grid of JPanels that is clickable and can change the color of each panel. I have two buttons store and restore to save and retrieve objects. In the attached screenshot, I have selected first row, second column and store it to a file. I have tried to select the first row, third column and click restore button to restore the previous saved data - which should be the first row, second column only selected. But it is not being restored as it seems.
Below is the code:
private class StoreRestoreButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == buttonStore) {
            if (textFileName.getText().equals("")) {
                labelCurrentStatus.setText("Please input the filename to store");
            } else {
                // Write display list array list to an object output stream.
                  try {
                    FileOutputStream fos = new FileOutputStream(textFileName.getText());
                    ObjectOutputStream oos = new ObjectOutputStream(fos);
                    //displayList is an ArrayList of objects
                    oos.writeObject(displayList);
                    oos.flush();
                    oos.close();
                    fos.close();
                  } catch (IOException ex) {
                     labelCurrentStatus.setText("Error saving file");
                    System.err.println("Error saving file");
                  }
            }

        } else if (e.getSource() == buttonRestore) {
             if (textFileName.getText().equals("")) {
                 labelCurrentStatus.setText("Please input the filename to restore");
             } else {
                 // Read a new display list array list from an object input stream.
                  try {
                    FileInputStream fis = new FileInputStream(textFileName.getText());
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    //displayList is an ArrayList of Room objects
                    displayList = (ArrayList<Room>) ois.readObject();
                    rebuildGridPanel(displayList);
                    ois.close();
                    fis.close();
                    repaint();
                  } catch (IOException ex) {
                    System.err.println("Trouble reading file");
                    labelCurrentStatus.setText("Trouble reading file");
                  } catch (ClassNotFoundException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
             }

        }

    }
}

}


text:
Q: How to create column jsonb on AWS-Redshift I have a table in my demo database.
CREATE TABLE airports_data (
    airport_code character(3) NOT NULL,
    airport_name text NOT NULL,
    city text NOT NULL,
    coordinates super NOT NULL,
    timezone text NOT NULL
);

In the Postgres Database, the data in the coordinate column has POINT as data type, and are like this :

{"x":129.77099609375,"y":62.093299865722656}

When copy the table to csv file, the data are represent like this in the csv file :

"(129.77099609375,62.093299865722656)"

As i defined SUPER as data type for the column coordinate in redshift,how can i copy data type POINT from database postgres to csv file, and load csv file to redshift ?

A: In Amazon Redshift the SUPER data type is used to store semi-structured data.
This is the Amazon Redshift guide for loading and manipulating semi-structured data using the the SUPER data type.
As an example, if you have:
CREATE TABLE "public"."tmp_super2"
  ("id" VARCHAR(255) NULL, "data1" SUPER NULL, "data2" SUPER NULL)
  BACKUP Yes;

With a CSV file named somefile.csv like this:
a|{}|{}
b|{\"a\":\"Hello World\", \"b\":100}|{\"z\":\"Hello Again\"}

Then you can load it with a COPY command like this:
COPY "public"."tmp_super2"
FROM 's3://yourbucket/yourfolder/somefile.csv'
REGION 'us-west-1'
IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftRole'
DELIMITER '|' ESCAPE

The COPY command is picky about double quotes when it is loading SUPER from CSV, hence the use of a pipe field delimiter, and escaping the double quotes.


text:
Q: Should I use time based indexes for non-log data in elasticsearch? For example, if I want to store orders/booking information then I can use order creation date to index data into "order-yyyy" index. But is there any benefits in doing so? For log data using such indexes is a good idea because it is easier to remove old logs. But what about regular and also somewhat time-based data? I want to keep orders data forever.
So far I've come up with this: the only reason to do this is that each year this strategy will allow to automatically scale cluster and prepare it for new data, which will probably improve performance. But intuition suggests that manual fine grained  resharding when it's needed will be much better approach, and I better to stick with "orders-vX" naming schema (in case of mapping changes).

A: rather than think about non-log data, think about it being time based. in that way log data is no different to order data, it's just a timestamp with extra info, and Elasticsearch doesn't really worry about it being either
that aside, yes it's 100% a good idea to approach it in the same manner. I would suggest using ILM to manage your indices.


text:
Q: Is there a way to concatenate the content of the respective cells of two different n * n data-frames within cells in pandas? Is there a way to concatenate the content of the respective cells of two different n * n data-frames within cells in pandas?
For example: Say I have two data-frames df1 and df2.
df1 looks like this:

Index
Score_1
Score_2

Family_1
123
456

Family_2
789
1011

df2 looks like this:

Index
Score_1
Score_2

Family_1
A
B

Family_2
C
D

I want to make a third data-frame that takes each n * n cell from df1 and concatenate it with the content from a respective n * n cell from df2 and make a third data-frame that looks something like this:

Index
Score_1
Score_2

Family_1
A:123
B:456

Family_2
C:789
D:1011

Just to make sure: One table has strings and the other has numbers but I want to do string concatenation so using str() is necessary is fine.
pd.concat() concats whole data-frames like this:

Index
Score_1
Score_2
Score_1
Score_2

Family_1
A
B
123
456

Family_2
C
D
789
1011

I am trying to superimpose the cells instead.
I tried to do it from scratch with zip and intertuples roughly like this:
for i,j in zip(df1.itertuples(),df2.itertuples()):
    n=1
    while n < len(i):
        print(i[n], ":", j[n])
        n = n + 1
    print('\n')

Whose output is along the lines of:

A:123
B:456
C:789
D:1011

Which I think I can reroute to dicts or an intermediate file and reshape from there but that seems a little unwieldy. Is there a more efficient way to do this?

A: You can temporarily set "Index" as index, convert to string, and add:
out = (df2
 .set_index('Index') # skip if already index
 .add(':'+df1.set_index('Index').astype(str))
 .reset_index()      # skip if already index
)

output:
      Index Score_1 Score_2
0  Family_1   A:123   B:456
1  Family_2   C:789  D:1011

If "Index" is already the index:
out = df2.add(':'+df1.astype(str))

output:
         Score_1 Score_2
Index
Family_1   A:123   B:456
Family_2   C:789  D:1011


text:
Q: Returing string from main function in c++ Is there any way to return string from main function in c++? i am mentioning the sample program below
string main(int argv, char* argc[])
{
  .
  .
  return "sucess";
}

A: The standard says:

3.6.1 Main function [basic.start.main]
2/ An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both

*

*a function of () returning int and

*a function of (int, pointer to pointer to char) returning int
as the type of main. [...]

So no, you have to return an int.
From your comments on your post, you seem to want to simply output a string on the standard output, then you can do:
#include <iostream>
int main()
{
    std::cout << "Success" << std::endl;
    // No need for return 0; it is implicit in C++
}

As Kerrek SB said in the comments, the return 0; is implicit in C++ (standard § 3.6.1 /5):

[...] If control reaches the end of main without encountering a return statement, the effect is that of executing
return 0;

A: Nope, It's not standard compliant. You have to return an int in order to show to the caller how the program exited (good, with an error ?).
And why would you return a string ?

A: No you can't, you must always return an int. Thinking more deeply, a string would be difficult for a shell program to deal with: when would the memory be released, what kind of string would be returned &c.)
However you can write to standard output or standard error using std::cout or std::cerr. That's the normal thing to do when you want a console application to output string-like data.
Typically, you then rely on your OS shell to direct the standard output of your program to the input of another one (unix uses the pipe | for that).

A: You probably mean to write to the standard output:
#include <cstdio>

int main()
{
    // ...

    std::puts("success");

}   // no "return", success is implicit in C++

That's one of the standard way for processes to communicate data, and many tools are geared for being used in this way.

A: No, you can't return string from main in c++, cause return value from main function is process return code (0 if success, not 0 if process failed). So OS is waiting proper signal of ending from your app.


text:
Q: Get and show AJAX response while AJAX is working yet I'm using AJAX through the code below:
Javascript :
function CallAJAX() {
    var url = "MyAJAX.ashx";
    xmlRequest.open("POST", url);
    xmlRequest.onreadystatechange = function () { ApplyUpdateCallAJAX() }
    xmlRequest.send(null);
}

function ApplyUpdateCallAJAX() {
    if (xmlRequest.readyState == 4) {
        if (xmlRequest.status == 200) {
            var response = xmlRequest.responseText;
            document.getElementById("resultDIV").innerHTML = response;
        }
    }
}

.ashx file (in asp.net) :
...
...
HttpResponse response = context.Response;
response.ContentType = "text/html";
...

response.Write("Connecting...");
// connecting to database - for example takes 10 seconds !

...
response.Write("Reading...");
// reading data from database - for example takes 5 seconds !

...

This way user will wait 15 seconds for AJAX and then see the result like this:
Connecting...Reading...

Is there anyway to show the two responses independently !?
For example some way that we have the result described below:
User first see the text Connecting... and then after 10 seconds (the time that connecting longs!) the text changes and user see the text Reading... ?


text:
Q: Create a Function which will tell us if an array is sorted or not in C programming New to C programming ^^.
I am working on an assignment, and I have to create a function that verifies if my array is sorted. I have to use a predefined template of code and solve it in a certain way.
Description :
Let's create a function which will tell us if an array is sorted or not. What is sorted? :-)
Write a function that takes an integer array as a parameter (input) and returns a boolean (true/false).
Your function should return true if the integer array is sorted in either ASC(ascending) or DESC(descending) order.
Your function should return false if the integer array is not sorted.
Numbers will be from -2_000_000 to 2_000_000
Array might have duplicate(s).
I have to use this to solve my problem.
#ifndef STRUCT_INTEGER_ARRAY
#define STRUCT_INTEGER_ARRAY
typedef struct s_integer_array
{
    int size;
    int* array;
} integer_array;
#endif

bool my_is_sort(integer_array* param_1)
{

}

The inputs that will be used to verify my code:

Exemple 0:

Input: [1, 1, 2]
Output:
Return Value: true

Exemple 1:
Input: [2, 1, -1]
Output:
Return Value: true

Exemple 2:
Input: [4, 7, 0, 3]
Output:
Return Value: false

Exemple 3:
Input: []
Output:
Return Value: true

Here is my code :
#include <stdbool.h>
#ifndef STRUCT_INTEGER_ARRAY
#define STRUCT_INTEGER_ARRAY
typedef struct s_integer_array
{
    int size;
    int* array;
} integer_array;
#endif

bool my_is_sort(integer_array* a)
{
    if (a->size == 1 || a-> size == 0)
    {
        return true;
    }

    int i;
    for (i=0;i<a->size;i++)
    {   //ascending order
        if (a->array[i] <= a->array[i+1]){
            return true;
        }else if (a->array[i] >= a->array[i+1]){
            return true;
        } else {
        return false;
    }
    }
}

The output I get to verify my code :
The output failure i get
My mistake is in the input -> Input: [4, 7, 0, 3]
My code returns true when it is supposed to return false.
It returns true because of the first two indexes 4 is less then 7 so my code assumes that it is in ascending order, but it's not the case I want my code to keep looping to the next one before it returns a boolean. To check if the number after 7 is greater then 7 or not. but I dont know how to do this in code.
Thank you guys!
I know it might be a dumb question for a lot of you, but please help. I am new to this, and I freaking love programming.

A: This is pretty simple. Check for both ascending/descending sort can be done in a single pass.
We do this by having two flag variables, one for ascending sort [still] being true and one for descending sort [still] being true.
In the loop, if the current elements being compared are not equal, one of the directions must be out-of-sort.
Here is some refactored code. It is annotated:
#include <stdbool.h>

#ifndef STRUCT_INTEGER_ARRAY
#define STRUCT_INTEGER_ARRAY

typedef struct s_integer_array {
    int size;
    int *array;
} integer_array;
#endif

bool
my_is_sort(integer_array *a)
{

    if (a->size <= 1)
        return true;

    int i;

    // true if [still] have ascending sort
    int ascend = 1;

    // true if [still] have descending sort
    int descend = 1;

    // the value of the "previous" array element
    int prev = a->array[0];

    // the value of the "current" array element
    int cur;

    for (i = 1;  i < a->size;  ++i, prev = cur) {
        // early escape -- neither direction is in sort
        if (! (ascend || descend))
            break;

        // get current array value
        cur = a->array[i];

        // compare against previous value
        int dif = cur - prev;

        // elements are the same -- no change in status
        if (dif == 0)
            continue;

        // one of the directions has to be out-of-sort
        if (dif < 0)
            ascend = 0;
        else
            descend = 0;
    }

    return (ascend || descend) ? true : false;
}

UPDATE:
Here is a slightly faster version:
bool
insort_fix1c(integer_array *a)
{
    const int *arr = a->array;
    int size = a->size;

    if (size <= 1)
        return true;

    int i;

    // true if [still] have ascending sort
    int ascend = 1;

    // true if [still] have descending sort
    int descend = 1;

    // the value of the "previous" array element
    int prev = arr[0];

    // the value of the "current" array element
    int cur;

    for (i = 1;  i < size;  ++i, prev = cur) {
        // get current array value
        cur = arr[i];

        // compare against previous value
        int dif = cur - prev;

        // elements are the same -- no change in status
        if (dif == 0)
            continue;

        // one of the directions has to be out-of-sort
        if (dif < 0)
            ascend = 0;
        else
            descend = 0;

        // early escape -- neither direction is in sort
        if ((ascend | descend) == 0)
            break;
    }

    return (ascend | descend) ? true : false;
}

A:
Write a function that takes an integer array as a parameter
(input) and returns a boolean (true/false).

The parameter of this function
bool my_is_sort(integer_array* a)

does not accept an integer array.
In this for loop
int i;
for (i=0;i<a->size;i++)
{   //ascending order
    if (a->array[i] <= a->array[i+1]){
        return true;
    }else if (a->array[i] >= a->array[i+1]){
        return true;
    } else {
    return false;
}

there are checked only the first two elements of an array pointed to by the data member array of an object of the type struct s_integer_array. All other elements are not checked due to return statements within the for loop.
I can suggest the following straightforward function implementation shown in the demonstrative program below.
#include <stdio.h>
#include <stdbool.h>

bool is_sorted( const int a[], size_t n )
{
    bool sorted = true;

    size_t i = 1;

    while ( i < n && a[i-1] == a[i] ) ++i;

    if ( i < n )
    {
        if ( a[i-1] < a[i] )
        {
            while ( ( ++i < n ) && !( a[i] < a[i-1] ) ) { /* empty */ }
            sorted = i == n;
        }
        else
        {
            while ( ( ++i < n ) && !( a[i-1] < a[i] ) ) { /* empty */ }
            sorted = i == n;
        }
    }

    return sorted;
}

int main(void)
{
    int a1[] = { 1, 1, 2 };
    size_t n = sizeof( a1 ) / sizeof( *a1 );

    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ", a1[i] );
    }
    putchar( '\n' );

    printf( "The array is sorted is %s\n", is_sorted( a1, n ) ? "true" : "false" );
    putchar( '\n' );

    int a2[] = { 2, 1, -1 };
    n = sizeof( a2 ) / sizeof( *a2 );

    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ", a2[i] );
    }
    putchar( '\n' );

    printf( "The array is sorted is %s\n", is_sorted( a2, n ) ? "true" : "false" );
    putchar( '\n' );

    int a3[] = { 4, 7, 0, 3 };
    n = sizeof( a3 ) / sizeof( *a3 );

    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ", a3[i] );
    }
    putchar( '\n' );

    printf( "The array is sorted is %s\n", is_sorted( a3, n ) ? "true" : "false" );
    putchar( '\n' );

    return 0;
}

The program output is
1 1 2
The array is sorted is true

2 1 -1
The array is sorted is true

4 7 0 3
The array is sorted is false

A: This is how I would approach something like this. It's a little different and more complex than what you've been asked for, but I'm hoping you can adapt the concept to your code and finish your assignment.
The problem with the code in the question is that it returns after only comparing the first two values in the given array. Instead it needs to compare enough values to decide if the first comparison where the values are not equal is ascending or descending and then continue until a comparison breaks that rule or the end of the array is reached.
For that I've used a flag variable to keep track of previous comparisons. If any comparison is the opposite of previous results the array is unsorted. If the end is reached without finding an opposite the array is sorted.
I used an enum for this, but an int with a value of 0 for undetermined, -1 for descending, and 1 for ascending (or any other 3 values you like) would work fine too.
Hopefully this helps you complete the assignment. Good luck!
#include <stdio.h>

typedef enum
{
    sortUnknown = 0,
    sortAscending,
    sortDescending,
    sortUnsorted
} SortType;

const char *sortNames[] =
{
    "   Unknown",
    " Ascending",
    "Descending",
    "  Unsorted",
};

SortType is_sorted(int* arr, int size)
{
    if (size <= 1)
    {
        return sortUnknown;
    }

    SortType overallSortType = sortUnknown;
    for (int i = 0; i < size - 1; ++i)
    {
        if (arr[i] < arr[i + 1])
        {
            if (overallSortType == sortDescending)
            {
                return sortUnsorted;
            }
            overallSortType = sortAscending;
        }
        else if (arr[i] > arr[i + 1])
        {
            if (overallSortType == sortAscending)
            {
                return sortUnsorted;
            }
            overallSortType = sortDescending;
        }
    }
    return overallSortType;
}

void print(int *arr, int size, SortType st)
{
    printf("%s : ", sortNames[st]);
    for (int i = 0; i < size; ++i)
    {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main()
{
    int arr1[] = { 1, 1, 2 };
    SortType st = is_sorted(arr1, 3);
    print(arr1, 3, st);

    int arr2[] = { 2, 1, -1 };
    st = is_sorted(arr2, 3);
    print(arr2, 3, st);

    int arr3[] = { 4, 7, 0, 3 };
    st = is_sorted(arr3, 4);
    print(arr3, 4, st);

    int arr4[] = { 3 };
    st = is_sorted(arr4, 1);
    print(arr4, 1, st);

    int arr5[] = { 1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 6, 6, 6, 6, 7, 8, 9 };
    st = is_sorted(arr5, 17);
    print(arr5, 17, st);

    return 0;
}

Demo: https://ideone.com/RkfEWI
Output:
 Ascending : 1 1 2
Descending : 2 1 -1
  Unsorted : 4 7 0 3
   Unknown : 3
 Ascending : 1 1 1 1 2 2 2 3 4 5 6 6 6 6 7 8 9

A: This function will check if the array is sorted.
#ifndef STRUCT_INTEGER_ARRAY
#define STRUCT_INTEGER_ARRAY
typedef struct s_integer_array
{
    int size;
    int* array;
} integer_array;
#endif

typedef enum
{
    des,
    notdetermined;
    asc;
}SORT_TYPE;

bool my_is_sort(integer_array* a)
{
    bool result = true;
    SORT_TYPE sort = notdetermined;
    if (a && a -> array && a -> size > 2)
    {
        for(int i = 0; i < a -> size - 1 && result; i++)
        {
            switch(sort)
            {
                case notdetermined:
                    if(a -> array[i] > a -> array[i + 1]) sort = des;
                    else if(a -> array[i] < a -> array[i + 1])) sort = asc;
                    break;
                case asc:
                    if(a -> array[i] > a -> array[i + 1])) result = false;
                    break;
                case des:
                    if(a -> array[i] < a -> array[i + 1])) result = false;
                    break;
            }
        }
    }
    return result;
}

https://godbolt.org/z/xnM7MYz6b


text:
Q: Download files with curl with timestamp or different name? Is there's a command to download files with curl from the same page and rename it with numbers or timestamps instead or rewritten the file with the .php file? I mean the url is downloadfile.php?id=1500 so when I set the option -O I get a file called downloadfile.php and if I download the id=1501 the downloadfile.php is rewritten it is possible to set curl to rename every curl request to number or timestamp like downloadfile00001.php?

A: If you're using flags it sounds like you are working on the commandline. -O uses the same name as the remote file. -o means write to file with whatever name you want. So in your script be it bash or what have you, you would use a variable you increment with the version you want.
example: curl website.com -o websitenamefileiwant.html

A: in bash scripting you'd do this
filenames=( filename1.html filename2.html filename3.html )

    curl -s -o "${filenames[i]}" <url>

or you can do this on the command line
sudo curl http://path-to-url/downloadfile.php?id=1500 -o downloadfile00001.php


text:
Q: Why "d" is undefined in attrTween (d3.js+TypeScript)? I already asked this, but I got advice that I post a new question, since I did not assume that the problem could be related to using TypeScript.
So, I am trying to create an interface on d3. I found the arc animation code (http://bl.ocks.org/mbostock/5100636), and I want to change it a bit (without function arcTween()). Here is part of my code (this code is in a loop function that runs itself):
            var arc3 = d3.arc().innerRadius(77).outerRadius(90).startAngle(0);
            var foregroundArc3 = imgs3
              .append('path')
              .attr('d', arc3)
              .attr('stroke', 'white')
              .attr('fill', 'white')
              .style('fill-opacity', 0.5)
              .attr('transform', 'translate('+(146.5)+','+(150.9)+')')
              .datum({endAngle: 0.0628*90, newAngle: 0.0628*270})
              .transition()
              .duration(1500)
              .attrTween('d',  (d) => {
                return (t) => {
                  const interpolate = d3.interpolate(d.endAngle, d.newAngle);
                    d.endAngle = interpolate(t);
                    return arc3(d);
                  };
          });

But there error: Argument of type '{ endAngle: number; newAng: number; }' is not assignable to parameter of type 'DefaultArcObject'. Property 'innerRadius' is missing in type '{ endAngle: number; newAng: number; }'.
And in browser's console "d" is undefinded. I was given a solution: moving the datum to before the .attr('d', arc3) line. But, if I do this, it doesn't works (the same error occurs), since TypeScript is used.


text:
Q: How to calculate the remaining amount per row? I have a wallet table like this:
// wallet
+----+----------+--------+
| id | user_id  | amount |
+----+----------+--------+
| 1  | 5        | 1000   |
| 2  | 5        | -200   |
| 3  | 5        | -100   |
| 4  | 5        | 500    |
+----+----------+--------+

I want to make a view that calculates the remaining amount per row. Something like this:
+----+----------+--------+------------------+
| id | user_id  | amount | remaining_amount |
+----+----------+--------+------------------+
| 1  | 5        | 1000   | 1000             |
| 2  | 5        | -200   | 800              |
| 3  | 5        | -100   | 700              |
| 4  | 5        | 500    | 1200             |
+----+----------+--------+------------------+

Any idea how can I do that?

A: MySQL 8 has window function for that purpose, like SUM() OVER
for your sample data, this will calculate the running SUM for every user_id
vital for th function to work is the PARTITION BY and the ORDER BY to get the right amount
The PARTITION BY is used to get sums for a user_id, so if you had user 5,6,7,8 it will correctly add (or subtract) the maount theat that user produced.
The ORDER BYis needed to get the right mount at the corect position. Tables are by nature unsortede, so an ORDER BY is needed to give the outout the corect order, if the ids where changed, you would get another mount, as it will be prior added to the running sum
SELECT
`id`, `user_id`, `amount`
, SUM(`amount`) OVER(PARTITION BY `user_id` ORDER BY `id`) run_sum
  FROM wallet

id
user_id
amount
run_sum

1
5
1000
1000

2
5
-200
800

3
5
-100
700

4
5
500
1200

fiddle

A: Do not know if this meets your demands or not
SELECT
  t1.id,t1.user_id,t1.amount,
 (
  SELECT sum(t2.amount) FROM yourtable t2 WHERE t2.id<=t1.id AND t1.user_id=t2.user_id
) as remaning_amount
 FROM  yourtable t1


text:
Q: Get CPU usage in bash, without top or sysstat My test script looks like this:
prev_total_cpu=0
prev_idle_cpu=0

while true
do
 tempenv=$(grep "cpu " /proc/stat)
 #get cpu times
 read cpu user nice system idle <<< "$tempenv"

 #calculate total cpu time
 let total=$[$user + $nice + $system + $idle]

 #calculate delta total and delta idle
 prev_total="prev_total_$cpu"
 prev_idle="prev_idle_$cpu"
 let delta_total=$[$total-${!prev_total}]
 let delta_idle=$[$idle-${!prev_idle}]

 #calculate cpu usage
 printf "$cpu: $[100*($delta_total-$delta_idle)/$delta_total]%% "

 #remember total and idle times
 let prev_total_$cpu="$total"
 let prev_idle_$cpu="$idle"

 echo ""
 sleep 1
done

Now, the same thing with multiple CPU support:
prev_total_cpu=0
prev_idle_cpu=0
prev_total_cpu0=0
prev_idle_cpu0=0
prev_total_cpu1=0
prev_idle_cpu1=0

while true
do
 #loop through cpus
 grep "cpu" /proc/stat | while IFS='\n' read tempenv
 do
  #get cpu times
  read cpu user nice system idle <<< "$tempenv"

  #calculate total cpu time
  let total=$[$user + $nice + $system + $idle]

  #calculate delta total and delta idle
  prev_total="prev_total_$cpu"
  prev_idle="prev_idle_$cpu"
  let delta_total=$[$total-${!prev_total}]
  let delta_idle=$[$idle-${!prev_idle}]

  #calculate cpu usage
  printf "$cpu: $[100*($delta_total-$delta_idle)/$delta_total]%% "

  #remember total and idle times
  let prev_total_$cpu="$total"
  let prev_idle_$cpu="$idle"
 done
 echo ""
 sleep 1
done

Doesn't work - it shows the same numbers over and over again. What am I doing wrong?
Sub-question:
I would like to initialize prev_total_$cpuand prev_idle_$cpu in a loop, but I don't know how to set the condition. I need the opposite of sed -ne 's/^cpu\(.*\) .*/\1/p' /proc/stat so I can loop through its output and do the initialization.

A: When you do
grep "cpu" /proc/stat | while IFS='\n' read tempenv
do
    ...
done

Your while loop runs on a subshell environment.
One solution would be to use process substitution instead:
while IFS='\n' read tempenv
do
    ...
done < <(grep "cpu" /proc/stat)

Another way is to enable lastpipe option if Bash supports it:
shopt -s lastpipe
... loop goes next ...

Adding some suggestions to your code, when doing arithmetic operations in Bash you better use (( )) format e.g.:
(( total = user + nice + system + idle ))

It might also be better to use -n than printf:
echo -n "$cpu: $(( 100 * ($delta_total - $delta_idle) / $delta_total ))%% "

Lastly, I do hope you really mean that you run your script with Bash and not other shells like Ksh. They are very different. Bash is a shell but Shell != Bash.


text:
Q: extract the remaining time period I have two data frames.
df1

             Tstart                Tend       start_temp
2012-12-19 21:12:00 2012-12-20 02:48:00 17.7637930350627
2013-01-31 17:36:00 2013-01-31 22:54:00 18.9618654078963
2013-02-14 09:12:00 2013-02-14 09:48:00 18.2361739981826
2013-02-21 15:36:00 2013-02-21 16:36:00 20.9938186870285
2013-03-21 03:54:00 2013-03-21 05:18:00 16.7130008152092
2013-03-30 23:42:00 2013-03-31 02:30:00 15.3775459369926

df2
           datetime airtemp
2012-12-11 23:00:00   14.40
2012-12-11 23:06:00   14.22
2012-12-11 23:12:00   14.04
2012-12-11 23:18:00   13.86
2012-12-11 23:24:00   13.68
2012-12-11 23:30:00   13.50
......
2015-03-31 23:24:00   15.46
2015-03-31 23:30:00   15.90
2015-03-31 23:36:00   15.82
2015-03-31 23:42:00   15.74

I want to extract the remaining datetime from df2 (df2 is a time series) other than the periods between startT and endT in df1.
Can you please help me to do this?
Many thanks.

A: With base R we can try the following (with the following df1 & df2):
df1 <- read.csv(text='Tstart, Tend, start_temp
2012-12-19 21:12:00, 2012-12-20 02:48:00, 17.7637930350627
2013-01-31 17:36:00, 2013-01-31 22:54:00, 18.9618654078963
2013-02-14 09:12:00, 2013-02-14 09:48:00, 18.2361739981826
2013-02-21 15:36:00, 2013-02-21 16:36:00, 20.9938186870285
2013-03-21 03:54:00, 2013-03-21 05:18:00, 16.7130008152092
2013-03-30 23:42:00, 2013-03-31 02:30:00, 15.3775459369926', header=TRUE)

df2 <- read.csv(text='datetime, airtemp
2012-12-11 23:00:00,   14.40
2012-12-11 23:06:00,   14.22
2012-12-11 23:12:00,   14.04
2012-12-11 23:18:00,   13.86
2012-12-11 23:24:00,   13.68
2012-12-19 23:30:00,   13.50
2013-03-21 04:24:00,   15.46
2013-03-21 23:30:00,   15.90
2015-03-31 23:36:00,   15.82
2015-03-31 23:42:00,   15.74', header=TRUE)

df1$Tstart <- strptime(as.character(df1$Tstart), '%Y-%m-%d %H:%M:%S')
df1$Tend <- strptime(as.character(df1$Tend), '%Y-%m-%d %H:%M:%S')
df2$datetime <- strptime(as.character(df2$datetime), '%Y-%m-%d %H:%M:%S')

indices <- sapply(1:nrow(df2), function(j) all(sapply(1:nrow(df1), function(i) df2[j,]$datetime < df1[i,]$Tstart | df2[j,]$datetime > df1[i,]$Tend)))
df2[indices,]
#              datetime airtemp
#1  2012-12-11 23:00:00   14.40
#2  2012-12-11 23:06:00   14.22
#3  2012-12-11 23:12:00   14.04
#4  2012-12-11 23:18:00   13.86
#5  2012-12-11 23:24:00   13.68
#8  2013-03-21 23:30:00   15.90
#9  2015-03-31 23:36:00   15.82
#10 2015-03-31 23:42:00   15.74


text:
Q: Flyback transformer construction issues Previous thread: Flyback transformer
So, in short, I'm attempting to build a flyback transformer. The schematic I am using is this:

And the flyback core looks like this:

Upon recommendation from the previous thread, I got an actual ferrite core from a TV and wound it myself, 10x 80 turns of 0.125mm copper wire (as in 800), each layer (composed of 80 turns) separated by insulation tape. The primary coil (5 turns) was wound underneath these. All the turns are over the airgap in the flyback core.
The circuit is running to an extent. There's a high pitched squeal when it turns on, and the MOSFET heats up. But no arc. I haven't tried measuring output voltage because I'm worried about frying the multimeter, but it should produce an arc.
I'm really not sure what's going wrong here. I can confirm that the circuit is assembled correctly. The flyback core was damaged when trying to take it out (one of the bars snapped in two), but I glued it back together, having been told that would fix it, and I don't see why that would not be the case.
My power supply is 12V, provided by a 9V and 2x1.5V in series, as required.
I have been told before that the circuit schematic given is not very efficient (as shown by the MOSFET heating up). I'd like to point out that at this stage, getting the circuit to work at all is a greater priority for me than efficiency. I don't want to shell out on new components or build a whole new circuit until I'm sure that that's the issue here.
Overall view of the circuit build:

Okay, got round to testing it.
Anda aka were right about the power supply. When running, the PD across the batteries drops to ~9V. I tested it with 15V - dropped down to 10. At 12V the output current was about 0.2A. Makes sense I guess.
Question is: what could I use to fix this? I'd rather still use batteries due to portability.

A: I did debate about this answer being a comment so don't bust a gut voting down (or up) but I had too much to say to fit a comment.
Can you get 3A from those batteries? For now I'll assume you can...
Assuming that you are producing no-more than 80V on the primary (because the FET will break if you are doing a 100v) and given your turns ratio of 1:160, and given the "imperfect coupling factor" (that I pull out of the experienced side of my brain) I'd say you should produce about 5kV.
The FET is getting warm and this isn't a worry but it does rather hint at your 12V supply rail falling to somewhat less when it is powered on. Maybe you can measure it. My suspicion is that it might be falling to about 6V or 8V and this will not efficiently turn the fet on and this could be causing the FET to warm. If this is true then maybe you might only be producing 1kV.
Of course, there is a strong possibility that you damaged your FET with over voltage the very forst time you used it. I note on your earlier threads/questions you were advised to use a 200V device with lower on-resistance.
I'll also point out that a lot of these circuits are from unprofessional sites that might have (with luck) got something to work and easily misconstrued their own circuit diagram thus misleading everyone who tries to build one. Also notable about the website that contains the circuit is the lack of information about the transformer and how to wind it.
The original design came from: -
http://www.geocities.com/CapeCanaveral/Lab/5322/fbt2.htm
But don't bother trying the link because geocities is no more.
Looking at your pictures and knowing how difficult it is to get a step-up transformer working with ratios over 100 I have to point out that there is no hope for the way you have it connected. 555 needs to drive the transistor which provides voltage to the FET and the FET source, emitter of the transistor and 0V of the 555 have to be "rigidly connected". The currents you might be inducing in 0V connections could easily mean you get less than 200V out of this design.

A: Your MOSFET may heat up because of a slow turn on transition, as it depends completely on the pull up and creates an RC charching circuit with the gate capacitance that are not neglectable for power MOSFETs. Whenever the MOS conducts with a resistance dissipates power. Also, when it's fully on it may have a too high Ron resistance, check it. The old IRF510 is not the best choice I'm thinking... Can you simulate the circuit with LTSpice or any tool? It pays well the time you spend on it, and avoids frustration and empirical searching.
The best driver for a MOSFET would be a push-pull architecture giving/drawing enough instantaneous current to charge/discharge the gate in some ns, any greater than that, especially if switching some amps, sounds to me like needing a fan and a chimney.


text:
Q: Insert Contents of CSV into strings I've been struggling with a small piece of code for a little while now. I have a CSV file with one column that contains a string of numbers. I can import that file without issues and display it.
My goal is to take the numbers in each of the tables and put it into a separate string, run that string through a function and then put the results back into my datagrid in column two. Is there a way that I should be doing this using the code below; the foreach statement is where I believe this should be done.
Edit: I tweaked the code and it now works the way that I want it to but I can't insert my result into any columns except for the first one. Is there a way that I should be targeting the results so they go in the second column?
            using (var fs = File.OpenRead(Dialog.FileName))
            using (var reader = new StreamReader(fs))
            {

                List<string> lista = new List<string>();
                List<string> listb = new List<string>();

                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    var values = line.Split(',');
                    lista.Add(values[0]);
                    dt1.Rows.Add(values[0]);
                }
                foreach (var item in lista)
                {
                    string temp;
                    GetLuhnCheckDigit(item);
                    listb.Add(last.ToString());
                    temp = item + last.ToString();

                    dt1.Rows.Add(temp); //This only adds to the first column
                }
                dataGridView1.DataSource = dt1;

A: Without knowing what GetLuhnCheckDigit method does, it is not possible to determine what values you want the second column to contain. Looking at the posted code, there are many things missing like how many columns the data table has, where is the Dialog variable definition? What is last?
Assuming there are at least two columns in the DataTable dt1, I am not sure why you are adding the items to the first column then loop through a list of those items to set the second column. It appears adding both of the columns at the same time would be easier.
You could do all this while reading the file like below:
try {
  using (var fs = File.OpenRead(Dialog.FileName)) {
    using (var reader = new StreamReader(fs)) {

      List<string> lista = new List<string>();
      List<string> listb = new List<string>();
      string temp;

      while (!reader.EndOfStream) {
        var line = reader.ReadLine();
        var values = line.Split(',');
        lista.Add(values[0]);
        GetLuhnCheckDigit(values[0]); // <-- What is this method doing???
        listb.Add(last.ToString());
        temp = values[0] + last.ToString();
        dt1.Rows.Add(values[0], temp); // <-- this adds both columns
      }
      dataGridView1.DataSource = dt1;
    }
  }
}
catch (Exception e) {
  MessageBox.Show("Error: " + e.Message);
}

Let me know if I am missing something, as I am clueless as to what the GetLuhnCheckDigit method could be doing.


text:
Q: Handle ViewExpiredException in the background and restore form values Is there a database-, primefaces- and "keep-session-alive"-free solution to prevent or to handle a ViewExpiredException silently in the background while restoring the form-inputs?
for example a user with a "stay logged-in cookie" would prefer not to be redirected to some kind of an error- or start-page; he fills out some form values, comes back in an hour and then, when he submits the form, the same view is re-created with its previous inputs and the submit-action of the underlying requestscope-bean is re-executed again.
i already took notice of omnifaces and mojarras
  <o:enableRestorableView />
  <f:view transient="true">

but as we talk about permanent logged-in users, i am not shure, if this would be the right approach.
thanks for pointing into the right direction.

A:
the same view is re-created with its previous inputs and the submit-action of the underlying requestscope-bean is re-executed again

For exactly this requirement, transparently recreating and restoring an expired JSF form tied to a request scoped bean, stateless JSF as in <f:view transient="true"> is the correct solution.
The <o:enableRestorableView> is unnecessary in this specific case. It is only useful for transparently recreating and restoring an expired JSF form tied to a view scoped bean. You only still have to manually populate the view scoped bean properties based on request parameters in its @PostConstruct.
In other words, you don't need to mix those solutions. It does technically not make sense as view scoped beans are useless anyway in stateless JSF, they will behave like request scoped beans.
See also:

*

*What is the usefulness of statelessness in JSF?

*Restoring request parameters in @ViewScoped bean after session expires

*javax.faces.application.ViewExpiredException: View could not be restored


text:
Q: Ansible Looping over dynamic inventory using jinja template Here is my Ansible playbook. It reads /etc/waagent.conf file and checks if variable AutoUpdate.Enabled=y  or not.And it uses Jinja template to generate output.csv file.
ansibleuser@server:~/plays$ cat report_waagent_local.yaml
---
 - name: waagent auto update report
   hosts: localhost
   connection: ssh
   remote_user: ewxxxx
   become: true
   become_user: root
   gather_facts: true

   tasks:
    - name: "Ensure status of AutoUpdate.Enabled in /etc/waagent.conf"
      lineinfile:
         name: /etc/waagent.conf
         line: AutoUpdate.Enabled=y
         state: present
      check_mode: yes #means make no change , just check
      register: conf
      failed_when: (conf is changed) or (conf is failed)
      ignore_errors: yes
      # logic
      # if "conf.changed": false --> that mean AutoUpdate.Enabled=y
      # if "conf.changed": true  --> that means value is not set in file.
    - name: generate report
      template:
        src: report_waagent_local.j2
        dest: ./output.csv

ansibleuser@server:~/plays$

And here is Jinja Template.
ansibleuser@server:~/plays$ cat templates/report_waagent_local.j2
{% if conf.changed == false %}
  {{ ansible_host }} , AutoUpdate.Enabled=y
{% else %}
  {{ ansible_host }} , AutoUpdate.Enabled=n
{% endif %}
ansibleuser@server:~/plays$

It produces output.csv as expected.
127.0.0.1, AutoUpdate.Enabled=y

Now, I need to fetch similar reports for all the servers present in the Azure subscription.
I modified my playbook. Note: I am using dynamic inventory in azure, I have a group named "all_pls" on which I need to run a playbook.
ansibleuser@server:~/plays$ cat report_waagent.yaml
---
- name: "generate waagent report"
  hosts: all
  connection: ssh
  remote_user : ewxxxxx
  become: True
  become_user: root
  gather_facts: True
  tasks:
    - name: "Ensure status of AutoUpdate.Enabled in /etc/waagent.conf"
      lineinfile:
         name: /etc/waagent.conf
         line: AutoUpdate.Enabled=y
         state: present
      check_mode: yes #means make no change , just check
      register: conf
      failed_when: (conf is changed) or (conf is failed)
      ignore_errors: yes
      # if "conf.changed": false --> that mean AutoUpdate.Enabled=y
      # if "conf.changed": true  --> that means the value is not set in the file.
    - name: generate report
      template:
        src: report_waagent_local.j2
        dest: ./output.csv

ansibleuser@server:~/plays$

I am running my playbook and getting no issues.
But I am getting no output in output.csv.
ansible-playbook --limit all_pls report_waagent.yaml

I guess I need to loop over hosts in a group name and also check conf.changed in the Jinja template. Can someone help please?

A: I fixed the issue.
- name: log conf.changed in output.csv using a template
    lineinfile:
      line: "{{ lookup('template', 'report_waagent_local.j2') }}"
      insertafter: EOF
      dest: output.csv
    delegate_to: localhost


text:
Q: How to find the original address of a file from dynamic URL? In some cases, when you want to download a file from a website, you can't see the original address of the file. for example look this URL:

How can I find the direct URL of the file?
Is there any approach or program to find the original(direct) URL?

A: In most of those cases there isn't a "direct URL" of the file. Either the file will be created dynamically or it is located in a directory that isn't accessible via an url. A script (here download.do) reads the file and passes the content through to the requesting browser.


text:
Q: I couldn't get past this error in open cv while using it in spider? error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-h4wtvo23\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

A: please read the error message carefully and thoroughly. it says something is empty() when it shouldn't be ("Assertion failed") and it gives you the source file and line number within OpenCV. you can find that file and look into it.
the assertion is thrown here: https://github.com/opencv/opencv/blob/master/modules/objdetect/src/cascadedetect.cpp#L1689
primary problem:

*

*check if face_cascade.empty() or eye_cascade.empty() after creating the objects in your code. if any of them is empty, it failed to load the xml file. check that the xml files are in an accessible place.

also:

*

*check that video_capture.isOpened() is True, or else you can't read the video

*say rv, frame = video_capture.read()

*check that rv is True, or else break the loop


text:
Q: If I use the word "enumerated", must the list be numeric or can it be bullet points? If I use the word "enumerated" in writing, must the list I am enumerating be numeric or can it be bullet points?

A: Although enumerate has overtones of numeric order because of its etymology, it is not so restricted in its use:

enumerate =
to name things separately, one by one
Cambridge

Similarly, Merriam Webster offers a definition that avoids any numeric content:

enumerate =
to specify one after another : LIST
Merriam Webster

Because bullet points list items separately, the bullets breaking any grammatical link between them, enumerate fits well despite the lack of ordered number to the list.