Bash query sqlite - bash

sorry for the noob question. I'm trying to write a simple bash script, based on newsbeuter. Basically I'm trying to get the first 5 articles I haven't read yet, once I got them, I send them to my phone with pushover and I need so set them as read on newsbeuter.
#!/bin/bash --
urls=$( sqlite3 /home/pi/.newsbeuter/cache.db <<END
select url from rss_item where unread = 1 limit 5;
END
)
This is the first query. I send the message variable through the pushover api.
Now I need to get how to update the table and set the articles as read.
Any ideas? (I'm totally new to bash syntax).
I tried both to recreate a query like
UPDATE rss_item set unread = 0 where url = '$url'
I looped it but it didn't work, then I tried to make
`UPDATE rss_item set unread = 0 where url in ($urls)`
but I keep getting errors I can't even understand! I really need a syntax lecture!

Try this:
#!/bin/bash --
urls="$(
sqlite3 /home/pi/.newsbeuter/cache.db \
'select url from rss_item where unread = 1 limit 5' \
)"
for url in $urls; do
sqlite3 /home/pi/.newsbeuter/cache.db \
"UPDATE rss_item set unread = 0 where url = '$url'"
done

Related

Check if a file exists faster than OPEN DATASET

I'm searching for a way to check if a file exists before using the OPEN DATASET command to open it. The OPEN DATASET command takes up to 30 seconds to trigger an exception, which is too slow for my liking.
This is the code:
TRY.
OPEN DATASET lv_file FOR OUTPUT IN TEXT MODE
ENCODING DEFAULT
WITH SMART LINEFEED.
CONCATENATE ` ` lv_resultdata INTO lv_resultdata.
TRANSFER lv_resultdata TO lv_file.
CLOSE DATASET lv_file.
CATCH cx_sy_file_access_error.
MESSAGE 'Placeholder-message. File cannot be reached'.
EXIT.
ENDTRY.
Try this:
DATA: filepath TYPE epsf-epsdirnam VALUE '/tmp'.
CALL FUNCTION 'EPS_GET_DIRECTORY_LISTING'
EXPORTING
dir_name = filepath
file_mask = 'somefile.txt'
EXCEPTIONS
invalid_eps_subdir = 1
sapgparam_failed = 2
build_directory_failed = 3
no_authorization = 4
read_directory_failed = 5
too_many_read_errors = 6
empty_directory_list = 7
OTHERS = 8.
CHECK sy-subrc = 0.
" writing dataset
It can also be used for remote servers.

Passing xml vallues from windows events as a variables

I appreciate any advice from Powershell wizards out there.
I am trying to setup an email alert that will be triggered on event but having problems passing values as a variable so I can use it later in the body and subject of an email.
I have a few lines of script that pulls an event and stores it as XML but have no luck converting the value to variable to call it later.
$event = wevtutil qe 'Microsoft-Windows-Base-Filtering-Engine-Connections/Operational' /rd:true /c:1 /q:"*[System[(EventID=2000)]]" /f:renderedxml
$xmlresults = [xml]$event
$eventDate = $xmlresults.event.system.timecreated.systemtime
$eventTime = get-date $eventDate -Format ('dd-MM-yyyy hh:mm:ss')
Now when calling $xmlresults.event.eventdata.data I can see all values in a table:
PS C:\Windows\system32> $xmlresults.Event.EventData.Data
Name #text
---- -----
ConnectionId 1324000000003942
MachineAuthenticationMethod 2
RemoteMachineAccount DOMAIN\COMPUTERNAME$
UserAuthenticationMethod 2
RemoteUserAcount DOMAIN\USERNAME$
RemoteIPAddress XXXX:XXXXX:XXXX:XXXX:XXXXX:XXX:XXXX
LocalIPAddress XXXXX:XXXX:XXXX:XXXX::1
TechnologyProviderKey {XXXXXX-XXXX-XXXXX-XXXX-XXXXXXXXXX}
IPsecTrafficMode 1
DHGroup 0
StartTime 2021-05-17T13:52:38.103Z
How do I store the values of RemoteMachineAccount and RemoteUserAccount as a variable so I can call upon it later in the script when composing email alert and log input by simply using something along the lines of $computer and $user?
Any help greatly appreciated.
If you just need a few specifically named properties, you can use the .Where({}) method to filter the nodes returned by the XML provider and grab the text from that specific property:
$RemoteMachineAccount = $xmlresults.Event.EventData.Data.Where({$_.Name -eq 'RemoteMachineAccount'}).InnerText
$RemoteUserAccount = $xmlresults.Event.EventData.Data.Where({$_.Name -eq 'RemoteUserAccount'}).InnerText
If you need to discover/use them dynamically, another option is to convert the node list into a hashtable:
$eventData = #{}
$xmlresults.Event.EventData.Data.ForEach({ $eventData[$_.Name] = $_.InnerText })
At which point you can dereference the individual property values by name:
$eventData["RemoteUserAccount"]

Magento stock update with csv

I am using the following script
http://www.sonassi.com/knowledge-base/magento-kb/mass-update-stock-levels-in-magento-fast/
It works beautifully with the test CSV file.
My POS creates a CSV file but it puts a different heading so the script does not work. I want to automate the process. Is there any way to change the names of headers automatically?
The script requires the headers to be
“sku”,”qty”
my CSV is
“ITEM”,”STOCK”
Is there any way for these two different names to be linked within the script so that my script sees ITEM as sku and STOCK as qty?
You should create a php script with an input of the yourfilename.csv, which is the unformatted file.
$file = file_get_contents('yourfilename.csv');
$file = str_replace('ITEM', 'sku', $file);
$file = str_replace('STOCK', 'qty', $file);
file_put_contents('yourfilename.csv', $file);
The below links are for your reference.
find and replace values in a flat-file using PHP
http://forums.phpfreaks.com/index.php?topic=327900.0
Hope it helps.
Cheers
PHP isn't usually the best way to go for file manipulation granting the fact you have SSH access.
You could also run the following commands (if you have perl installed, which is default in most setups...):
perl -pi -e 's/ITEM/sku/g' /path/to/your/csvfile.csv
perl -pi -e 's/STOCK/qty/g' /path/to/your/csvfile.csv
If you want qty update using raw sql way then you can create a function like below:
function _updateStocks($data){
    $connection     = _getConnection('core_write');
    $sku            = $data[0];
    $newQty         = $data[1];
    $productId      = _getIdFromSku($sku);
    $attributeId    = _getAttributeId();
 
    $sql            = "UPDATE " . _getTableName('cataloginventory_stock_item') . " csi,
                       " . _getTableName('cataloginventory_stock_status') . " css
                       SET
                       csi.qty = ?,
                       csi.is_in_stock = ?,
                       css.qty = ?,
                       css.stock_status = ?
                       WHERE
                       csi.product_id = ?
                       AND csi.product_id = css.product_id";
    $isInStock      = $newQty > 0 ? 1 : 0;
    $stockStatus    = $newQty > 0 ? 1 : 0;
    $connection->query($sql, array($newQty, $isInStock, $newQty, $stockStatus, $productId));
}
And call the above function by passing csv row data as arguments. This is just a hint.
In order to get full working code with details you can refer to the following blog article:
Updating product qty in Magento in an easier & faster way
Hope this helps!

Password Changer using VAccess

Hey I am working on a password changer. User logs in ( successfully), loads a global var with user initials, then launch a password expired form. I try and use those initials on the password expired form to retrieve user info from DB.
vaUserLog.FieldValue("USERINIT") = UserInitials
vaUserLog.GetEqual
vaStat = vaUserLog.Status
vaStat keeps giving me an error of 4. I am using pervasive v9. Connection with VA looks like:
With vaUserLog
.RefreshLocations = True
.DdfPath = DataPath
.TableName = "USERLOG"
.Location = "USERLOG.MKD"
.Open
If .Status <> 0 Then
ErrMsg = "Error Opening File " + .TableName + " - Status " + str$(.Status) + vbCrLf + "Contact IT Department"
End If
End With
In DB table, USERINIT is Char, 3. UserInitials is a String.
Probably missing something small but can't think right now. Any help is appreciate. Lemme know if you require more info.
Cheers
Status 4 means that the record could not be found. In your case, it could be the case of the value being searched is wrong, there's a different padding (spaces versus binary zero), or that the UserInitials value just isn't in the data file.
You can use MKDE Tracing to see what's actually being passed to the PSQL engine. Once you've done that, make sure the value you're using works through the Function Executor where you can open the file and perform a GetEqual.
Here are my suggestions:
- Make sure you're pointing to the right data files.
- Make sure you're passing the right value into the GetEqual (by setting the FieldValue).

Creating a new rrd database based on an existing one

I have some old rrdtool databases, for which the exact creation recipe has long been since lost. I need to create a new database with the same characteristics as the current ones. I've dumped a couple of old databases and pored over the contents but I'm not sure how to interpret the metadata. I think it appears in the following stanzas
<cf> AVERAGE </cf>
<pdp_per_row> 360 </pdp_per_row> <!-- 1800 seconds -->
<xff> 5.0000000000e-01 </xff>
There are four such stanzas, which correspond to the way I recall the round-robin cascading was set up. Has anyone already done this, or can give me pointers as to how to clone a new empty rrd database from an existing one? Or show me where I missed this in the documentation.
I use the command rrdcreate. It can create a new rrd based in an existing one. The -t parameter indicate a existing rrd as template.
rrdcreate new.rrd -t existing.rrd
rrdtools' rrdinfo is your friend!
It will tell you how the rrd file's data source(s) and archive(s) were created. Example
$ rrdtool info random.rrd
filename = "random.rrd"
rrd_version = "0001"
step = 300
last_update = 955892996
ds[a].type = "GAUGE"
ds[a].minimal_heartbeat = 600
ds[a].min = NaN
ds[a].max = NaN
ds[a].last_ds = "UNKN"
ds[a].value = 2.1824421548e+04
ds[a].unknown_sec = 0
ds[b].type = "GAUGE"
ds[b].minimal_heartbeat = 600
ds[b].min = NaN
ds[b].max = NaN
ds[b].last_ds = "UNKN"
ds[b].value = 3.9620838224e+03
ds[b].unknown_sec = 0
rra[0].cf = "AVERAGE"
rra[0].pdp_per_row = 1
rra[0].cdp_prep[0].value = nan
rra[0].cdp_prep[0].unknown_datapoints = 0
rra[0].cdp_prep[1].value = nan
rra[0].cdp_prep[1].unknown_datapoints = 0
You can try use the clone script described here. It's very basic but it works for simple rrd files. I used it to figure out a schema that was generated by munin. I needed to insert old data into munin so I reverse engineered the schema, set the --start to a date prior to the start of my old data and re-imported data into the rrd.
$ python rrdinfo-parser.py -f test.rrd
rrdtool create test.rrd --start 920804400 --step 300 \
DS:speed:COUNTER:600:U:U \
RRA:AVERAGE:0.5:1:24 \
RRA:AVERAGE:0.5:6:10 \

Resources