Wikipedia opensearch API returns similar entries - search

I am using the Wikipedia opensearch API to retrieve some basic info from Wikipedia entries.
My code is as follows:
$persona = $_GET["persona"];
$pattern = '/\s+/';
$replacement = '_';
$url = preg_replace($pattern, $replacement, $persona);
$search = "https://it.wikipedia.org/w/api.php?action=opensearch&search=".$url;
$response = json_decode(file_get_contents($search));
$t = $response[1];
$s = $response[2];
$u = $response[3];
Now, the problem is that it outputs info about similar entries. For example, if $url is "giuseppe_ferrandi", it returns info about "giuseppe_ferrandino". I assume "giuseppe_ferrandi" does not exist in Wikipedia, but I would prefer it to return nothing.

Related

Get all parent hierarchy from a work Item via API Azure Boards

I need to get all the parent hierarchy from a work item.
The parent of the parent of the parent.. find all the parent links.
There is a way to do it via API?
Thanks :)
Yes, you can.
But you must use code to handle this situation. The below is a Python demo.
from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
#get all the work items linked to a work item
def get_work_items_parents(Organization_Name, personal_access_token, wi_id):
#get a connection to Azure DevOps
organization_url = 'https://dev.azure.com/'+Organization_Name
credentials = BasicAuthentication('', personal_access_token)
connection = Connection(base_url=organization_url, creds=credentials)
work_item_tracking_client = connection.clients.get_work_item_tracking_client()
work_item = work_item_tracking_client.get_work_item(wi_id, expand="relations")
#get the work item links
for item in work_item.relations:
#get parent and child work items
if item.attributes['name'] == 'Parent':
#get the work item id
work_item_id = item.url.split('/')[-1]
#get the work item
linked_work_item = work_item_tracking_client.get_work_item(work_item_id)
#add the work item to the list
work_items_parents.append(linked_work_item)
#get the parents of the parent
get_work_items_parents(Organization_Name, personal_access_token, work_item_id)
return work_items_parents
personal_access_token = 'xxx'
Organization_Name = 'xxx'
workitem_id = 120
#create a list
work_items_parents = []
items = get_work_items_parents(Organization_Name, personal_access_token, workitem_id)
for item in items:
print(item.fields['System.Title'])
I can successfully get all parents of workitem id '120':
The above is the API of Python SDK Demo, if you want to use REST API, I can also give you an idea.
Just call this REST API:
https://dev.azure.com/<Organization Name>/<Project Name>/_apis/wit/workitems/<Workitem ID>?api-version=6.0&$expand=relations
You can call it again after getting the current parent:
Official document of the REST API:
Work Items - Get Work Item
Try the following PowerShell script: (In this sample, the work item 2434is the last parent work item - top1 parent, 2435 is top2 parent ...)
Param(
[string]$orgurl = "https://dev.azure.com/{org}",
[string]$project = "Artifacts",
[string]$workitemid = "2527", #The specific child work item ID
[string]$user = "",
[string]$token = "PAT"
)
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
#Get all parent hierarchy from a specific work Item
cls
$parenturl = "$orgurl/$project/_apis/wit/workItems/$($workitemid)?"+"$"+"expand=relations&api-version=6.0"
$parentwi = #()
Do {
$wiresults = Invoke-RestMethod -Uri $parenturl -Method Get -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$wirelations = $wiresults.relations | where{$_.rel -eq 'System.LinkTypes.Hierarchy-Reverse'}
$parentwi += $wiresults.id
$wiurl = $wirelations.url
#Print the parent work item link
Write-Host $wiurl
$parenturl = "$wiurl"+"?"+"$"+"expand=relations&api-version=6.0"
}
While($wiurl)
#Print the work items hierarchy Child -> Parent
Write-Host "########################################"
Write-Host "Work Items Hierarchy : Child -> Parent"
Write-Host "########################################"
$parentwi

Turn a formatted PowerShell hash table/array definition into a single line (and vice versa) via hot key in Visual Studio Code

In Visual Studio Code I am trying to work out a way to convert a piece of PowerShell (which defines a collection of hash tables and arrays) into a single line of code, and also a way to perform the same operation but the other way (i.e. take a single line and make it more readable). I need to do this because the YAML variable I am defining needs to be done on a single line (the PowerShell gets passed to another PowerShell script via this variable).
So, for example, I need to be able to turn:
#{
TestData = #{
Connections = #(
#{
ResourceGroup = 'd3zuks-bussvc-342-brimig-rgrp01';
SourceVmName = 'D3ZUKS342APP01';
Targets = #(
#{
DestinationVmName = 'D3ZUKS342SQL01';
DestinationVmResourceGroup = 'd3zuks-bussvc-342-brimig-rgrp01';
DestinationPort = 1433;
Status = 'Reachable'
}
)
}
)
};
IPFlows = #(
#{
ResourceGroup = 'd3zuks-bussvc-342-brimig-rgrp01';
TargetVmName = 'D3ZUKS342SQL01';
InboundFlows = #(
#{
Description = 'Application Server D3ZUKS342APP01';
Protocol = 'TCP';
LocalPorts = 1433;
RemoteIpAddress = '10.124.36.132';
RemotePort = 0;
}
);
OutboundFlows = #()
}
)
}
into:
#{TestData = #{Connections = #(#{ResourceGroup = 'd3zuks-bussvc-342-brimig-rgrp01';SourceVmName= 'D3ZUKS342APP01';Targets = #(#{DestinationVmName= 'D3ZUKS342SQL01';DestinationVmResourceGroup = 'd3zuks-bussvc-342-brimig-rgrp01';DestinationPort= 1433;Status = 'Reachable' })});IPFlows = #(#{ResourceGroup = 'd3zuks-bussvc-342-brimig-rgrp01';TargetVmName= 'D3ZUKS342SQL01';InboundFlows= #(#{Description = 'Application Server D3ZUKS342APP01';Protocol= 'TCP';LocalPorts= 1433;RemoteIpAddress = '10.124.36.132';RemotePort= 0;});OutboundFlows = #()})}}
And more importantly, do the same in reverse (i.e. take the single line and make it readable/editable). Ideally I'd love to be able to do both by mapping a hotkey to both operations.
The multi line > single line seems easier - a regex replace of \s+( ) with nothing, followed by a replace of carriage returns with nothing, but how can I map that to a hotkey?
The single line > multi line seems much harder :( I have searched for an extension that might help, but to no avail. Does anyone have any suggestions, either native Visual Studio Code functionality or an extension that I could use?
Although I do not understand why you need this either, specific to the request for a oneliner: you might use this ConvertTo-Expression cmdlet to rebuild your expression from an object using several expansion levels:
$Object = #{
TestData = #{ ...
# Oneliner
$Object | ConvertTo-Expression -Expand 0
#{IPFlows = ,#{ResourceGroup = 'd3zuks-bussvc-342-brimig-rgrp01'; TargetVmName = 'D3ZUKS342SQL01'; InboundFlows = ,#{Description = 'Application Server D3ZUKS342APP01'; RemoteIpAddress = '10.124.36.132'; RemotePort = 0; Protocol = 'TCP'; LocalPorts = 1433}; OutboundFlows = #()}; TestData = #{Connections = ,#{ResourceGroup = 'd3zuks-bussvc-342-brimig-rgrp01'; SourceVmName = 'D3ZUKS342APP01'; Targets = ,#{DestinationVmName = 'D3ZUKS342SQL01'; DestinationPort = 1433; DestinationVmResourceGroup = 'd3zuks-bussvc-342-brimig-rgrp01'; Status = 'Reachable'}}}}
# Compressed
$Object | ConvertTo-Expression -Expand -1
#{IPFlows=,#{ResourceGroup='d3zuks-bussvc-342-brimig-rgrp01';TargetVmName='D3ZUKS342SQL01';InboundFlows=,#{Description='Application Server D3ZUKS342APP01';RemoteIpAddress='10.124.36.132';RemotePort=0;Protocol='TCP';LocalPorts=1433};OutboundFlows=#()};TestData=#{Connections=,#{ResourceGroup='d3zuks-bussvc-342-brimig-rgrp01';SourceVmName='D3ZUKS342APP01';Targets=,#{DestinationVmName='D3ZUKS342SQL01';DestinationPort=1433;DestinationVmResourceGroup='d3zuks-bussvc-342-brimig-rgrp01';Status='Reachable'}}}}
# Expanded (to any level)
$Object | ConvertTo-Expression # -Expand to any level
#{
IPFlows = ,#{
ResourceGroup = 'd3zuks-bussvc-342-brimig-rgrp01'
TargetVmName = 'D3ZUKS342SQL01'
InboundFlows = ,#{
Description = 'Application Server D3ZUKS342APP01'
RemoteIpAddress = '10.124.36.132'
RemotePort = 0
Protocol = 'TCP'
LocalPorts = 1433
}
OutboundFlows = #()
}
TestData = #{Connections = ,#{
ResourceGroup = 'd3zuks-bussvc-342-brimig-rgrp01'
SourceVmName = 'D3ZUKS342APP01'
Targets = ,#{
DestinationVmName = 'D3ZUKS342SQL01'
DestinationPort = 1433
DestinationVmResourceGroup = 'd3zuks-bussvc-342-brimig-rgrp01'
Status = 'Reachable'
}
}}
}

Str::limit laravel

I have a file name examples:
4030-2210201884140.jpg
527884197_w640_h640_1ff2cccdbed562cef696d0c7adf41292.jpg
need to do to so was:
4030-22...1884140.jpg
5278841...df41292.jpg
Been looking for a solution but could not find it.
I have visited the post
Cutting down a length of a PHP string and inserting an ellipses
But sometimes it may not fit for you try below function
I have converted your requirement to a function with default arguments:
function getFirstLast($string='527884197_w640_h640_1ff2cccdbed562cef696d0c7adf41292.jpg',$orgOnF=7,$orgOnB=-11,$maskedString='.',$maskRepeat=3)
{
if (strlen($string) <= 21)
{
return $string;
}
$firstPartString = mb_substr($string, 0 ,$orgOnF);
$secondPartString = mb_substr($string,$orgOnB);
$maskedString = str_repeat($maskedString, $maskRepeat);
$finalResult = $firstPartString.$maskedString.$secondPartString;
return $finalResult;
}
echo getFirstLast();

Perl: String to anonymous array?

SOLVED ALREADY --> See edit 7
At this moment I'm fairly new on Perl, and trying to modify part of an existing page (in Wonderdesk).
The way the page works, is that it gets the information from the GET url and parses it to an SQL query.
Since this is part of a much larger system, I'm not able to modify the coding around it, and have to solve it in this script.
A working test I performed:
$input->{help_id} = ['33450','31976'];
When running this, the query that is being build returns something as
select * from table where help_id in(33450,31976)
The part of my code that does not work as expected:
my $callIDs = '33450,31450';
my #callIDs = split(/,/,$callIDs);
my $callIDsearch = \#callIDs;
$input->{help_id} = $callIDsearch;
When running this, the query that is being build returns something as
select * from table where help_id = '33450,31976'
I've tried to debug it, and used Data::Dumper to get the result of $callIDsearch, which appears as [33450, 31450] in my browser.
Can someone give me a hint on how to transform from '123,456' into ['123', '456']?
With kind regards,
Marcel
--===--
Edit:
As requested, minimal code piece that works:
$input->{help_id} = ['123','456']
Code that does not work:
$str = '123,456';
#ids = split(/,/,$str);
$input->{help_id} = \#ids;
--===--
Edit 2:
Source of the question:
The following part of the code is responsible for getting the correct information from the database:
my $input = $IN->get_hash;
my $db = $DB->table('help_desk');
foreach (keys %$input){
if (/^corr/ and !/-opt$/ and $input->{$_} or $input->{keyword}){
$db = $DB->table('help_desk','correspondence');
$input->{rs} = 'DISTINCT help_id,help_name,help_email,help_datetime,help_subject,help_website,help_category,
help_priority,help_status,help_emergency_flag,help_cus_id_fk,help_tech,help_attach';
$input->{left_join} = 1;
last;
}
}
# Do the search
my $sth = $db->query_sth($input);
my $hits = $db->hits;
Now instead of being able to provide a single parameter help_id, I want to be able to provide multiple parameters.
--===--
Edit 3:
query_sth is either of the following two, have not been able to find it out yet:
$COMPILE{query} = __LINE__ . <<'END_OF_SUB';
sub query {
# -----------------------------------------------------------
# $obj->query($HASH or $CGI);
# ----------------------------
# Performs a query based on the options in the hash.
# $HASH can be a hash ref, hash or CGI object.
#
# Returns the result of a query as fetchall_arrayref.
#
my $self = shift;
my $sth = $self->_query(#_) or return;
return $sth->fetchall_arrayref;
}
END_OF_SUB
$COMPILE{query_sth} = __LINE__ . <<'END_OF_SUB';
sub query_sth {
# -----------------------------------------------------------
# $obj->query_sth($HASH or $CGI);
# --------------------------------
# Same as query but returns the sth object.
#
shift->_query(#_)
}
END_OF_SUB
Or
$COMPILE{query} = __LINE__ . <<'END_OF_SUB';
sub query {
# -------------------------------------------------------------------
# Just performs the query and returns a fetchall.
#
return shift->_query(#_)->fetchall_arrayref;
}
END_OF_SUB
$COMPILE{query_sth} = __LINE__ . <<'END_OF_SUB';
sub query_sth {
# -------------------------------------------------------------------
# Just performs the query and returns an active sth.
#
return shift->_query(#_);
}
END_OF_SUB
--===--
Edit 4: _query
$COMPILE{_query} = __LINE__ . <<'END_OF_SUB';
sub _query {
# -------------------------------------------------------------------
# Parses the input, and runs a select based on input.
#
my $self = shift;
my $opts = $self->common_param(#_) or return $self->fatal(BADARGS => 'Usage: $obj->insert(HASH or HASH_REF or CGI) only.');
$self->name or return $self->fatal('NOTABLE');
# Clear errors.
$self->{_error} = [];
# Strip out values that are empty or blank (as query is generally derived from
# cgi input).
my %input = map { $_ => $opts->{$_} } grep { defined $opts->{$_} and $opts->{$_} !~ /^\s*$/ } keys %$opts;
$opts = \%input;
# If build_query_cond returns a GT::SQL::Search object, then we are done.
my $cond = $self->build_query_cond($opts, $self->{schema}->{cols});
if ( ( ref $cond ) =~ /(?:DBI::st|::STH)$/i ) {
return $cond;
}
# If we have a callback, then we get all the results as a hash, send them
# to the callback, and then do the regular query on the remaining set.
if (defined $opts->{callback} and (ref $opts->{callback} eq 'CODE')) {
my $pk = $self->{schema}->{pk}->[0];
my $sth = $self->select($pk, $cond) or return;
my %res = map { $_ => 1 } $sth->fetchall_list;
my $new_results = $opts->{callback}->($self, \%res);
$cond = GT::SQL::Condition->new($pk, 'IN', [keys %$new_results]);
}
# Set the limit clause, defaults to 25, set to -1 for none.
my $in = $self->_get_search_opts($opts);
my $offset = ($in->{nh} - 1) * $in->{mh};
$self->select_options("ORDER BY $in->{sb} $in->{so}") if ($in->{sb});
$self->select_options("LIMIT $in->{mh} OFFSET $offset") unless $in->{mh} == -1;
# Now do the select.
my #sel = ();
if ($cond) { push #sel, $cond }
if ($opts->{rs} and $cond) { push #sel, $opts->{rs} }
my $sth = $self->select(#sel) or return;
return $sth;
}
END_OF_SUB
--===--
Edit 5: I've uploaded the SQL module that is used:
https://www.dropbox.com/s/yz0bq8ch8kdgyl6/SQL.zip
--===--
Edit 6:
On request, the dumps (trimmed to only include the sections for help_id):
The result of the modification in Base.pm for the non-working code:
$VAR1 = [
33450,
31450
];
The result of the modification in Condition.pm for the non-working code:
$VAR1 = [
"help_id",
"IN",
[
33450,
31450
]
];
$VAR1 = [
"cus_username",
"=",
"Someone"
];
$VAR1 = [
"help_id",
"=",
"33450,31450"
];
The result for the modification in Base.pm for the working code:
$VAR1 = [
33450,
31976
];
The result for the modification in Condition.pm for the working code:
$VAR1 = [
"help_id",
"IN",
[
33450,
31976
]
];
It looks as if the value gets changed afterwards somehow :S
All I changed for the working/non-working code was to replace:
$input->{help_id} = ['33450','31976'];
With:
$input->{help_id} = [ split(/,/,'33450,31450') ];
--===--
Edit 7:
After reading all the tips, I decided to start over and found that by writing some logs to files, I could break down into the issue with more details.
I'm still not sure why, but it now works, using the same methods as before. I think it's a typo/glitch/bug in my code somewhere..
Sorry to have bothered you all, but I still recommend the points to go to amon due to his tips providing the breakthrough.
I don't have an answer, but I have found a few critical points where we need to know what is going on.
In build_query_cond (Base.pm line 528), an array argument will be transformed into an key in (...) relation:
if (ref($opts->{$field}) eq 'ARRAY' ) {
my $add = [];
for ( #{$opts->{$field}} ) {
next if !defined( $_ ) or !length( $_ ) or !/\S/;
push #$add, $_;
}
if ( #$add ) {
push #ins, [$field, 'IN', $add];
}
}
Interesting bit in sql (Condition.pm line 181). Even if there is an arrayref, an IN test will be simplified to an = test if it contains only a single element.
if (uc $op eq 'IN' || $op eq '=' and ref $val eq 'ARRAY') {
if (#$val > 1) {
$op = 'IN';
$val = '('
. join(',' => map !length || /\D/ ? quote($_) : $_, #$val)
. ')';
}
elsif (#$val == 0) {
($col, $op, $val) = (qw(1 = 0));
}
else {
$op = '=';
$val = quote($val->[0]);
}
push #output, "$col $op $val";
}
Before these two conditions, it would be interesting to insert the following code:
Carp::cluck(Data::Dumper::Dump(...));
where ... is $opts->{$field} in the first snippet or $cond in the second snippet. The resulting stack trace would allow us to find all subroutines which could have modified the value. For this to work, the following code has to be placed in your main script before starting the query:
use Carp ();
use Data::Dumper;
$Data::Dumper::Useqq = 1; # escape special characters
Once the code has been modified like this, run both the working and not-working code, and print out the resulting query with
print Dumper($result);
So for each of your code snippets, we should get two stack traces and one resulting SQL query.
A shot in the dark... there's a temporary array #callIDs created by this code:
my #callIDs = split(/,/,$callIDs);
my $callIDsearch = \#callIDs;
$input->{help_id} = $callIDsearch;
If some other part of your code modifies #callIDs, even after it's been assigned to $input->{help_id}, that could cause problems. Of course the fact that it's a lexical (my) variable means that any such changes to #callIDs are probably "nearby".
You could eliminate the named temporary array by doing the split like this:
$input->{help_id} = [ split(/,/,$callIDs) ];
I'm not sure I understand exactly why this is happening. It seems that your query builder needs an arrayref of strings. You can use map to do that
my $callIDs = '33450,31450';
my #callIDs = map {$_*1} split(/,/,$callIDs);
$input->{help_id} = \#callIDs;
This code should work
my $callIDs = '33450,31450';
$input->{help_id} = [split ",", $callIDs];
If your code somehow detect your data is number you can use
my $callIDs = '33450,31450';
$input->{help_id} = [map 0+$_, split ',', $callIDs];
If it somehow become number and you need string instead which should not in this case but advice for future work:
my $callIDs = '33450,31450';
$input->{help_id} = [map ''.$_, split ',', $callIDs];

Powershell Script loop output to txt file

I am using a Powershell script to write to a text file. A client showed me this Powershell script to use to replace a excel macro I used to use...
$computers= gc "C:\Users\Powershell\DeviceList.txt"
foreach ($computername in $computers)
{
write-output "<$computername>
active = yes
group =
interval = 5min
name = $computername
host = $computername
community =
version = 1
timeout = 0
retries = default
port = 161
qos_source = 1
</$computername>" | Out-File -filepath "C:\Users\Powershell\Cisco_Mon.txt" -append
}
It works great but now I wanted to build on it to add additional variables. In a perfect world I would like it to read from an excel spreadsheed grabbing each rowof data and each column being defined as a variable. For now using another text file is fine as well. Here is what I started with (it doesnt work) but you can see where I am going with it...
$computers= gc "C:\Users\Powershell\devicelist.txt"
$groups= gc "C:\Users\Powershell\grouplist.txt"
foreach ($computername in $computers) + ($groupname in $groups)
{
write-output "<$computername>
active = yes
group = $groupname
interval = 5min
name = $computername
host = $computername
community =
version = 1
timeout = 0
retries = default
port = 161
qos_source = 1
</$computername>" | Out-File -filepath "C:\Users\Powershell\Cisco_Mon.txt" -append
}
Of course it is not working. Essentially I would LOVE it if I could define each of the above options into a variable from an excel spreadsheet, such as $community, $interval, $active, etc.
Any help with this would be very much appreaciated. If someone could show me how to use an excel spreadsheet, have each column defined as a variable, and write the above text with the variables, that would be GREAT!!!.
Thanks,
smt1228#gmail.com
An Example of this would be the following...
Excel Data: (Colums seperated with "|"
IP | String | Group
10.1.2.3 | Public | Payless
Desired Output:
<10.1.2.3>
active = yes
group = Payless
interval = 5min
name = 10.1.2.3
host = 10.1.2.3
community =
version = 1
timeout = 0
retries = default
port = 161
qos_source = 1
</10.1.2.3>
Addition:
Pulling data from CSV for IP, String, Group where data is as follows in CSV...
10.1.2.3,public,group1
10.2.2.3,default,group2
10.3.2.3,public,group3
10.4.2.3,default,group4
to be writting into a .txt file as
IP = 10.1.2.3.
String = public
Group = Group1
and look for each line in the CSV
Ok, new answer now. The easiest way would be to save your Excel document as CSV so that it looks like this (i.e. very similar to how you presented your data above):
IP,String,Group
10.1.2.3,Public,Payless
You can still open that in Excel, too (and you avoid having to use the Office interop to try parsing out the values).
PowerShell can parse CSV just fine: with Import-Csv:
Import-Csv grouplist.csv | ForEach-Object {
"<{0}>
active = yes
group = {1}
interval = 5min
name = 10.1.2.3
host = 10.1.2.3
community =
version = 1
timeout = 0
retries = default
port = 161
qos_source = 1
</{0}>" -f $_.IP, $_.Group
}
I'm using a format string here where {0}, etc. are placeholders. -f then is the format operator which takes a format string on the left and arguments for the placeholders on the right. You can also see that you can access the individual columns by their name, thanks to Import-Csv.

Resources