text:
Q: Active Record Relation Alias i'm trying to set an alias to a relation by using the "with" method of ActiveRecord.
The problem is that i can only set the alias for the last element :
$ar->with(array('rel1.rel2' => array('alias' => 'rel2Alias'));

I have to retrieve the "rel1" and "rel2" for two columns of the AC class so i must set a different alias for the "rel1" relation but i don't know how to do.
Any suggestions ?

A: if found the solution by reading closely the documentation :
$ar->with(array('rel1' => array('alias' => 'rel1Alias', 'with' => array('rel2' => array('alias' => 'rel2alias'))));


text:
Q: jQuery dataTable - how to search column with exact match for multiple options I have a column with levels such as "A, A+, A, B+, B...".  I have check boxes for filters that let you choose multiple boxes and it filters results.  the filter is working with multiple but I can't seem to get the EXACT match to work.  I have it creating a regex that spits out something like "C-|C|C+".
If you click "C" box it shows results with "C", "C+", and "C-".  I need to grab just "C".  What am I doing wrong?
$('.dataTable').DataTable({
      "order": [[ 0, 'asc' ]],
       bFilter:true,
       "search": {
            "regex": true
       }
});

$("input[name='tourneyLevel']").on("change", function(e) {
      var levelSelected = [];
      $("input[name='tourneyLevel']:checked").each(function(index, city) {
          levelSelected.push([$(this).val()]);
      });

      var regex = levelSelected.join("|");
      console.log(regex);

      $('.dataTable').DataTable().column(4).search(regex, true, false).draw();
});

A: If you need to filter your data based on exact match against exact (multiple) criteria, you're going to need those criteria somewhere in your view to use them. Which means, you need separate checkboxes for 'C', 'C+' and 'C-', so that when you check it, you can refer to this element value (val()).
Your example, employing external search $.fn.DataTable.ext.search may thus look like:

//define data source
var srcData = [
  {subject: 'math', student: 'Peter Jackson', score: 'C+'},
  {subject: 'math', student: 'Steven Spielberg', score: 'A'},
  {subject: 'math', student: 'Jeffrey Abrams', score: 'A+'},
  {subject: 'math', student: 'George Lucas', score: 'A-'},
  {subject: 'math', student: 'Martin Scorsese', score: 'A'},
];
//define data table
var dataTable = $('#mytable').DataTable({
  sDom: 't',
  data: srcData,
  columns: [
    {title: 'subject', data: 'subject'},
    {title: 'student', data: 'student'},
    {title: 'score', data: 'score'}
  ]
});
//create dynamically score checkboxes
var scores = dataTable.column(2).data().unique().sort().toArray();
var checkboxes = scores.reduce((elements, item) => elements+=`<input type="checkbox" class="score" value="${item}">${item}</input>`,'');
$('body').append(checkboxes);
//employ external search
var scroresChecked = [];
$.fn.DataTable.ext.search.push((settings, row) => scoresChecked.indexOf(row[2]) > -1 || scoresChecked.length == 0);
//listenr for checkboxes change, grab checked, redraw table
$('.score').on('change', function(){
  scoresChecked = [...$('.score:checked')].map(checkbox => $(checkbox).val());
  dataTable.draw();
});
<!doctype html>

  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">

Though, this example is viable, whenever you need to filter across multiple column with bigger number of options, it may go clunky, and you may want to consider another user interface approach (like dropdowns or input fields). So, following DataTable plug-in may become of use.
Sot, that same example may look nice and neat:

//define data source
var srcData = [
  {subject: 'math', student: 'Peter Jackson', score: 'C+'},
  {subject: 'math', student: 'Steven Spielberg', score: 'A'},
  {subject: 'math', student: 'Jeffrey Abrams', score: 'A+'},
  {subject: 'math', student: 'George Lucas', score: 'A-'},
  {subject: 'math', student: 'Martin Scorsese', score: 'A'},
];
//define data table
var dataTable = $('#mytable').DataTable({
  sDom: 'tF',
  data: srcData,
  columns: [
    {title: 'subject', data: 'subject'},
    {title: 'student', data: 'student'},
    {title: 'score', data: 'score'}
  ]
});
<!doctype html>

  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.mfilter.tk/css/mfilter.min.css">

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find out who is starting a service? In one of our servers, SQL Server service though set to manual and its dependant services are stopped, still it starts automatically if we stop the SQL Server service.
Is there a utility or way to find out who or which service is starting SQL Server Service?

A: Look in the System event log for Event ID 7035 from source Service Control Manager. This should tell you when the service was started and by whom.


text:
Q: A specific MP4 file is not playable with avfoundation in iOS I have an mp4 video file that I want to play it in iOS using avfoundation. Unfortunately, the file is not being played and unable to save into the default gallery(photos) even it has h264 video codec and aac audio codec. And it is only playable when I reencode it using ffmpeg. I want to know why the file only becomes playable after reencoding the video?
Not Playable(originalFile.mp4) vs Playable File(outputFile.mp4) Information Comparison

File is playable with avfoundation when these commands are being applied:

*

*ffmpeg -y -hide_banner -i originalFile.mp4 -f mp4 -vcodec h264 -vf scale=out_color_matrix=bt709 -color_primaries bt709 -color_trc bt709 -colorspace bt709 -b:v 5703k -acodec aac -b:a 249k outputFile.mp4

*ffmpeg -y -hide_banner -i originalFile.mp4 -f mp4 -vcodec h264 -acodec aac outputFile.mp4
File is not playable with avfoundation when this command is being applied:

*

*ffmpeg -y -hide_banner -i originalFile.mp4 -f mp4 -vcodec copy -acodec aac outputFile.mp4
originalFile.mp4 file link: https://drive.google.com/file/d/1-yZFL0EsLztMIfwU79Al6dv8gdwJyGAD/view?usp=sharing
ffprobe streams of both files are here
https://www.diffchecker.com/VgZL66QB

A: I tried to dive into that, and I am blocked at this call stack:
#0  0x00007fff24e0d82e in PullParamSetSPS ()
#1  0x00007fff24e0f357 in FigH264Bridge_GetSPSIsInterlaced ()
#2  0x00007fff27fdc473 in mv_CheckIfVideoPresentable ()
...

These functions are from CoreMedia framework.
I guess there is something with SPS in this video (https://www.quora.com/What-are-SPS-and-PPS-in-video-codecs).
The framework calls mv_CheckIfVideoPresentable to check if the video is "valid".
This function copies a piece of data from a video and this pieces are:
outputFile.mp4

6764001F ACD940C0 126C0440 00000040 00000C83 C60C6580

originalFile.mp4

6764001F AC1B2940 C024D80B 50501064 00000004 000000CB
898000B3 620001E8 48FC638C 4C00059B 10000F42 47E31C28

Then PullParamSetSPS uses this data to calculate something, and FigH264Bridge_GetSPSIsInterlaced returns 1 or 0 depending on that data.
So you need to figure out what SPS is, what these pieces of data are. And you could set breakpoints to these functions to see what is going on there.
I used this code to trigger the breakpoints:
let good = AVURLAsset(url: Bundle.main.url(forResource: "outputFile", withExtension: "mp4")!)
print(good.isPlayable)

let bad = AVURLAsset(url: Bundle.main.url(forResource: "originalFile", withExtension: "mp4")!)
print(bad.isPlayable)

I hope this helps


text:
Q: How to customize message with multiple params in knockout validation? My code is as follows:
ko.validation.rules.between = {
    validator: function(value, params) {
        var min = params[0];
        var max = params[1];
        value = parseInt(value, 10);
        if (!isNaN(value)) {
            return value >= min && value <= max;
        }
        return false;
    },
    message: 'Value must be between {0} and {1}'
};
ko.validation.registerExtenders()
// Use the rule
viewModel.someValue.extend({between: [10, 100]});

But when not valid, the error message will be:

Value must be between 10, 100 and {1}


text:
Q: Java Generics with inheritance and covariance I'm having a bit of a hard time to understand how to correctly use covariance and wildcards when using generics in Java.
I'm trying to avoid having to use casting.
Here's my situation :
class Element {}

class ChildElement extends Element {}

interface A<T> {
    T doSomething(T foo);
}

interface B extends A<Element> {}

interface C extends B {}

class D implements B {

    @Override
    public Element doSomething(Element foo) {}
}

class E extends D implements C {
    @Override
    public Element doSomething(Element foo) {}
}

This situation works, but I would like to be able to do this instead for class E :
class E extends D implements C {

    @Override
    public ChildElement doSomething(ChildEment foo) {}
}

From what I've seen, what I want to do is covariance, but I can't do it in the current sitution as I need to use wildcards. But I've read that you can't do covariance with generics and wildcards.
Is there any solution to this problem ? I'd like to keep the strong dependencies between each classes.
Thanks for your help !

A: You have to make B generic, but you can put a bound on the generic parameter such that it's at least an Element:
interface B<T extends Element> extends A<T> {}

interface C<T extends Element> extends B<T> {}

Then about the closest you can get is:
 class D<T extends Element> implements B<T> {
    @Override
    public T doSomething(T foo) { return null;}
}

class E extends D<ChildElement> implements C<ChildElement> {
    @Override
    public ChildElement doSomething(ChildElement foo) { return null;}
}

which compiles.

A:
But I've read that you can't do covariance with generics and
  wildcards.

This statement is not about covariant return type, but it means that you can't do this:
List<Number> l1 = new ArrayList<>();
List<Integer> l2 = new ArrayList<>();
l1 = l2; //illegal

But T it's also any subclass of T. So thing like this:
interface Interface<T> {
    T method();
}

class SomeClass implements Interface<Number>{
    @Override
    public Float method() {
        return 1F;
    }
}

works fine. But method's signature of subclass(implementation) and superclass(interface) must matches. So in your example
class E extends D implements C {

    @Override
    public ChildElement doSomething(ChildEment foo) {}
}

it's illegal.

A: The interface you've described can't be covariant. What would you want/expect to happen with this code?
class OtherElement extends Element{}
Element oe = new OtherElement();
E e = new E();
B b = e;
b.doSomething(oe);

This compiles correctly, as it must - but if E#doSomething expected a ChildElement we would have a failure here.


text:
Q: CASE expression ent returning ELSE value for every account even when condition is True The below query returns two rows for every account with both the 'Active' and 'Inactive' labels even when the CASE expression logic is True.
ex.
If an account has 'revenue' greater than 0 and the fiscal_qtr = '2022-Q1' instead of returning just 'Active' it also returns a row with the value 'Inactive'.

SELECT
geo,
account,
subsegment,
forecast_group,
CASE
WHEN revenue > 0 and fiscal_qtr = '2022-Q1' then 'Active'
ELSE 'Inactive'
END AS "Active Acct"
FROM rev_planning.ace_global
WHERE
(fiscal_year_num between 2018 and 2021 or fiscal_qtr = '2022-Q1')
and revenue > 0
GROUP BY geo, account, subsegment, forecast_group

I have tried putting the case expression in parenthesis but it still returns two rows for all of the accounts that should just be returning 'Active'
(WHEN revenue > 0 and fiscal_qtr = '2022-Q1' then 'Active' ELSE 'Inactive'END) AS "Active Acct"

Current Output

geo
account
subsegment
forecast group
acitveacct

APAC
brothers neilsen
australia
dbiq
Active

APAC
brothers neilsen
australia
dbiq
Inactive

Expected Output (because brothers neilsen should be "Active" based on the case expression

geo
account
subsegment
forecast group
acitveacct

APAC
brothers neilsen
australia
dbiq
Active

A:
I have tried putting the case expression in parenthesis but it still
returns two rows for all of the accounts that should just be returning
'Active'

That's what should happen if the SELECT returns rows for multiple years and quarters. Due to the CASE the current year and quarter (2022-Q1) would be considered 'Active' and prior years would be 'Inactive'.
It sounds like you only want to return the most recent year. Try using ROW_NUMBER() to sort and rank the fiscal quarters for each account. Then use where RowNum = 1 to grab the most recent one. The query below partitions results by geo, account, subsegment, but you can adjust it as needed:
WITH cte AS (
   SELECT *
          , ROW_NUMBER() OVER(
             PARTITION BY geo, account, subsegment
             ORDER BY fiscal_year_num DESC, fiscal_qtr DESC
          ) AS RowNum
   FROM   ace_global
   WHERE  revenue > 0
   OR   ( fiscal_year_num BETWEEN 2018 AND 2021
           OR fiscal_qtr = '2022-Q1'
        )
)
SELECT geo
      , account
      , subsegment
      , forecast_group
      , CASE WHEN fiscal_qtr = '2022-Q1' THEN 'Active' ELSE 'Inactive' END AS "Active Acct"
FROM   cte
WHERE  RowNum = 1

Sample Data

geo | account     | subsegment | forecast_group | revenue | fiscal_year_num | fiscal_qtr
:-- | :---------- | :--------- | :------------- | ------: | --------------: | :---------
ABC | abc company | australia  | dbiq           |   50000 |            2018 | 2018-Q1
ABC | abc company | australia  | dbiq           | 1000000 |            2022 | 2022-Q1
EFG | efg company | australia  | dbiq           |   75000 |            2020 | 2020-Q2
HIJ | hij company | australia  | dbiq           |  787000 |            2021 | 2021-Q3
HIJ | hij company | australia  | dbiq           | 2000000 |            2022 | 2022-Q1

Results:

geo | account     | subsegment | forecast_group | Active Acct
:-- | :---------- | :--------- | :------------- | :----------
ABC | abc company | australia  | dbiq           | Active
EFG | efg company | australia  | dbiq           | Inactive
HIJ | hij company | australia  | dbiq           | Active

db<>fiddle here


text:
Q: Recover Deleted MySQL Row? I've deleted some rows by mistake. I have MYD, FRM and MYI files. When I check MYD file I can see deleted records. I got copies of that 3 files right after deleted.
How do I recover deleted rows in MYD file?

A: restore from backups, and in the worst case seek professional help. also take a look here.
do not make any modifications to the disk where data is stored. if you want to play around it - image it first.


text:
Q: Debian installation - how to correctly partition the disk? My system:

*

*most recent Debian 11 image

*vServer running at my hosting provider

*virtualized via Xen

*normal HDD, no SSD; no lvm or raid used

Somehow I managed to install Debian 11 with misaligned partitions.  (this question is a follow-up of this one)
fdisk says:
Device     Boot      Start        End    Sectors  Size Id Type
/dev/xvda1               2 2095151103 2095149056  999G 83 Linux
/dev/xvda2      2095153150 2097149951    1996802  975M  5 Extended
/dev/xvda5      2095153152 2097149951    1996800  975M 82 Linux swap

The weird thing: I recently installed another Debian on a vServer having the same setup in almost the same way, and on that machine all is ok (first sector starts at 2048)
What I did:

*

*expert installation

*on the machine where all is ok: chose 'guided, use whole disk'; I did not enter the menu for manual or guided partitioning

*on the faulty machine: I thought about manual partitioning, entered the menu, but then aborted without writing anything to disk and let the debian installer make partitioning

Result is different as you can see in above output
(my biggest problem right now is that grub has not enough space to be installed)
How is this possible???
When I manually partition the disk when installing debian, how can I be sure that partitions are aligned??
Any thoughts what could have gone wrong here?
Update:
reinstalled the vServer, manually partitioned the whole disk; then, even before finishing installation checked with fdisk in another terminal window: everything ok this time, first partition start at sector 2048
Question stays: how can it be possible that the debian installer screws up the partitioning sometimes?


text:
Q: Bash, no-arguments warning, and case decisions I am learning bash.
I would like to do a simple script that, when not arguments given, shows some message. And when I give numers as argument,s depending on the value, it does one thing or another.
I would also like to know suggestions for the best online manuals for beginners in bash
Thanks

A: If only interested in bailing if a particular argument is missing, Parameter Substitution is great:
#!/bin/bash
# usage-message.sh

: ${1?"Usage: $0 ARGUMENT"}
#  Script exits here if command-line parameter absent,
#+ with following error message.
#    usage-message.sh: 1: Usage: usage-message.sh ARGUMENT

A: if [[ $# -eq 0 ]] ; then
    echo 'some message'
    exit 0
fi

case "$1" in
    1) echo 'you gave 1' ;;
    *) echo 'you gave something else' ;;
esac

The Advanced Bash-Scripting Guide is pretty good. In spite of its name, it does treat the basics.

A: Example
 if [ -z "$*" ]; then echo "No args"; fi

Result
No args

Details
-z is the unary operator for length of string is zero.
$* is all arguments.
The quotes are for safety and encapsulating multiple arguments if present.
Use man bash and search (/ key) for "unary" for more operators like this.

A: Old but I have reason to rework the answer now thanks to some previous confusion:
if [[ $1 == "" ]] #Where "$1" is the positional argument you want to validate

 then
 echo "something"
 exit 0

fi

This will echo "Something" if there is no positional argument $1. It does not validate that $1 contains specific information however.

A: If there is not only 1 argument, then print usage and exit
if [[ $# != 1 ]] ; then
  echo 'USAGE: bin/siege COOKIE'
  exit 0
fi


text:
Q: CGBitmapContextCreate issue while trying to resize images I'm running into an issue when I try to create a CGContextRef while attempting to resize some images:
There are the errors
Sun May 16 20:07:18 new-host.home app [7406] <Error>: Unable to create bitmap delegate device
Sun May 16 20:07:18 new-host.home app [7406] <Error>: createBitmapContext: failed to create delegate.

My code looks like this
     - (UIImage*) resizeImage:(UIImage*)originalImage withSize:(CGSize)newSize {
 CGSize originalSize = originalImage.size;
 CGFloat originalAspectRatio = originalSize.width / originalSize.height;

 CGImageRef cgImage = nil;
 int bitmapWidth = newSize.width;
 int bitmapHeight = newSize.height;
 CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
 CGContextRef context = CGBitmapContextCreate(nil, bitmapWidth, bitmapHeight, 8, bitmapWidth * 4, colorspace, kCGImageAlphaPremultipliedLast);

 if (context != nil) {
  // Flip the coordinate system
  //CGContextScaleCTM(context, 1.0, -1.0);
  //CGContextTranslateCTM(context, 0.0, -bitmapHeight);

  // Black background
  CGRect rect = CGRectMake(0, 0, bitmapWidth, bitmapHeight);
  CGContextSetRGBFillColor (context, 0, 0, 0, 1);
  CGContextFillRect (context, rect);

  // Resize box to maintain aspect ratio
  if (originalAspectRatio < 1.0) {
   rect.origin.y += (rect.size.height - rect.size.width / originalAspectRatio) * 0.5;
   rect.size.height = rect.size.width / originalAspectRatio;
  } else {
   rect.origin.x += (rect.size.width - rect.size.height * originalAspectRatio) * 0.5;
   rect.size.width = rect.size.height * originalAspectRatio;
  }

  CGContextSetInterpolationQuality(context, kCGInterpolationHigh);

  // Draw image
  CGContextDrawImage (context, rect, [originalImage CGImage]);

  // Get image
  cgImage = CGBitmapContextCreateImage (context);

  // Release context
  CGContextRelease(context);
 }
 CGColorSpaceRelease(colorspace);

 UIImage *result = [UIImage imageWithCGImage:cgImage];
 CGImageRelease (cgImage);
 return result;
}

A: You cannot pass nil as the first argument of CGBitmapContextCreate.  Allocate some space for the pixels.  Think of the poor pixels.

A: So it appears I was using images that were TOO big. Essentially I was trying to scale by a magnitude of 10x which appears to be too much. Anyways, that's that.


text:
Q: Replace left side text with regex in notepad++ I want to replace statements like these:
identity_LineItemId TEXT(300),
identity_TimeInterval TEXT(300),
bill_InvoiceId TEXT(300),

With these in a large file:
identity_LineItemId=NULLIF(LinkedAccountId, ''),
identity_TimeInterval=NULLIF(LinkedAccountId, ''),
bill_InvoiceId=NULLIF(LinkedAccountId, ''),
bill_BillingEntity=NULLIF(LinkedAccountId, ''),

I tried:

search: .* TEXT(300)
replace with: \1=NULLIF(\1, ''),

But that didn't work.
How can I use a regex replace in notepad++ to replace TEXT(300) with table_name=NULLIF(table_name, ''),  ?

A: You have to capture the first group:
(.*)\sTEXT\(300\)
and replace with whatever you want using \1 to use the first captured group again (everything up to the space)
\1=NULLIF\(LinkedAccountId, ''\)


text:
Q: delete sms programatically is NOT working on android 5.1 and above I have tried

getContentResolver().delete(Uri.parse("content://sms/inbox/" + id), null, null);

even

getContentResolver().delete(Uri.parse("content://sms"),"_id=?",new String[]{id});

with this permission in manifest
<uses-permission android:name="android.permission.WRITE_SMS"/>

but it returns 0 each time with no exception thrown. I need help!

A: From Android 4.4 onward Only one app can delete , upgrade , block or do anything .so in order to work you have to set your app as default messaging app .
For more information refer here Official android page on policy change
hope it helps ...


text:
Q: Chrome web developer tools focus console input with keyboard shortcut I can open developer tools console using Ctrl+Shift+J in chrome developer tools. But how can I focus on the input to start typing using the keyboard?
Since the cursor isn't at the input box most times. I am currently having to click at the console input box to start typing.

A: After opening the devtools console, try hitting Tab, it will put the focus on the console input.


text:
Q: How to call SparkMLLib algorithms using R or SparkR? I am trying use to SparkR and R as front end to develop machine learning models.
I want to make use Spark's MLLib which works on distributed data frames. Is there anyway to call spark MLLib algorithm from R?

A: Unfortunately no.  We will have to wait  Apache Spark 1.5 for sparkR-mllib bindings.


text:
Q: How to remove the space on top of Tabs.TabPane of Ant Design? There is always a space on top of each TabPane, can anybody help to let me know I can remove it?
Thanks.

A: You should rewrite ant element's style. If there is some margin you should find class of this element, try to change it in inspector.
Then if everythink look good, you should rewrite it like .ant-class-name{ margin: 0 //or other }


text:
Q: Purpose & Meaning of 'replicateable' field I'm looking at the getUpdated() and getDeleted() calls in the SOAP and REST APIs, and I see that they are only supported by SObjects that are flagged as 'replicateable'. I haven't found any docs though about what this field really means. Is this flag just the Salesforce way of saying "These are the SObjects that you need for Data Replication, and you shouldn't need those that don't have this flag"? Or is this their way of saying "We haven't yet implemented the code to make these other SObjects support these calls"? In other words, do the SObjects with the replicateable flag represent the complete set of SObjects needed to do a reasonable job of data replication, or has Salesforce simply not implemented support for getUpdated() and getDeleted() on other essential SObjects?
Secondary question: When it comes to custom objects, how is this flag handled? Is it set to true by default, based off of a SystemModstamp field?

A: I agree that the documentation is a bit vague on what actually makes an sObject replicateable.

Certain objects cannot be replicated via the API. To replicate an object via the getUpdated() call, its object must be configured as replicateable (replicateable is true). To determine whether a given object can be replicated, your client application can invoke the describeSObjects() call on the object and inspect its replicateable property.

There isn't any guidance on how  the replicateable property can be configured.

For empirical evidence, I iterated over all the DescribeSObjectResult's returned via the API and captured the name of anything where replicateable was false:
The resulting non-replicateable list was:
AcceptedEventRelation
AccountPartner
AccountShare
ActionLinkGroupTemplate
ActionLinkTemplate
ActivityHistory
AggregateResult
ApexLog
ApexTestQueueItem
ApexTestResult
AppMenuItem
AssignmentRule
AsyncApexJob
AttachedContentDocument
AuraDefinition
AuraDefinitionBundle
AuthConfig
AuthConfigProviders
AuthProvider
AuthSession
CampaignShare
CaseShare
CaseStatus
ChatterActivity
ClientBrowser
CollaborationGroup
CollaborationGroupMember
CollaborationGroupMemberRequest
CollaborationInvitation
CombinedAttachment
Community
ConnectedApplication
ContactShare
ContentDocument
ContentDocumentLink
ContentFolderLink
ContentFolderMember
ContentVersion
ContentWorkspace
ContentWorkspaceDoc
ContractStatus
CorsWhitelistEntry
CronJobDetail
CronTrigger
CustomObjectUserLicenseMetrics
CustomPermission
CustomPermissionDependency
Dashboard
DashboardComponent
DataType
DeclinedEventRelation
DocumentAttachmentMap
Domain
DomainSite
DuplicateRule
EmailDomainKey
EmailStatus
EntityDefinition
EntityParticle
EventLogFile
ExternalDataSource
ExternalDataUserAuth
FeedComment
FeedLike
FeedPollChoice
FeedPollVote
FeedTrackedChange
FieldDefinition
FieldPermissions
ForecastShare
GrantedByLicense
KnowledgeableUser
LeadShare
LeadStatus
ListView
ListViewChart
ListViewChartInstance
LoginGeo
LoginHistory
LoginIp
LookedUpFromActivity
MacroShare
MatchingRule
MatchingRuleItem
MobileDeviceRegistrar
Name
NamedCredential
NoteAndAttachment
OauthToken
ObjectPermissions
OpenActivity
OpportunityPartner
OpportunityShare
OpportunityStage
OwnedContentDocument
PackageLicense
PartnerRole
PermissionSet
PermissionSetAssignment
PermissionSetLicense
PermissionSetLicenseAssign
PlatformAction
ProcessDefinition
ProcessInstance
ProcessInstanceHistory
ProcessInstanceStep
ProcessInstanceWorkitem
ProcessNode
Publisher
PushTopic
RecentlyViewed
RelationshipDomain
RelationshipInfo
Report
SamlSsoConfig
SecureAgent
SecureAgentPlugin
SecureAgentPluginProperty
ServiceFieldDataType
SetupEntityAccess
Site
SolutionStatus
StreamingChannelShare
TaskPriority
TaskStatus
TenantUsageEntitlement
ThirdPartyAccountLink
Topic
TopicAssignment
UndecidedEventRelation
UserEntityAccess
UserLicense
UserListView
UserListViewCriterion
UserLogin
UserPackageLicense
UserPreference
UserProvisioningConfig
UserProvisioningRequestShare
UserRecordAccess
UserShare

Points of interest:

*

*None of my numerous custom objects appeared (no __c suffix). I assume this means replication is available for all custom objects. However, this is a based on a sample size of 1, so your results may vary.

*Many of these represent views and sharing access over other data. This is system level data. Things like CronTrigger and ApexLog. It wouldn't really make sense to provide this data for replication.

*The Content* (e.g. ContentVersion) records appear and might be something you want to replicate. Content has always been a bit off the standard sObject implementation and more a law unto itself. The probably also explains why it isn't supported.

*I did have some external custom objects with the __x suffix appear as non-replicateable (I excluded them from the list above). That makes sense as the data isn't actual in Salesforce.

Interesting response from @superfell in SOAP API - getUpdated()/retrieve() vs query()/queryMore(): (my emphasis)

Specifically for the getUpdated() case, you are correct that you can do a query/queryMore alternative by building the correct where clause. However the where clause differs by object type. You should use the SystemModstamp field where available, if it doesn't have that, then use LastModifiedDate and if it doesn't have that, use CreatedDate. This is basically what getUpdated() is doing under the covers.

So replicatable is relying on those three fields to provided the getUpdated() functionality.
The same answer also has:

But, it worth understanding that there is no SOQL equivalent for getDeleted(), many types of rows can be hard deleted and so a queryAll with isDeleted=true will not spot these deletes, but getDeleted() will (which keeps a separate delete log).

It is unclear what drives that separate delete log, but it is probably tied into the replicateable flag.


text:
Q: Django 4 Отправка email на адрес юзера посредством SMTP изучаю Django 4, допиливаю свой первый проект, осталось разобраться с отправкой email-сообщений с активацией аккаунта на адреса пользователей через SMTP.
Когда я использую localhost и порт 25(отправка письма вникуда) -- в принципе все работает как надо, когда я пытаюсь подключиться к smtp.yandex.ru -- ничего не происходит, ни отправки сообщения, ни каких-то ошибок, вероятно я где-то ошибся в настройках.
Немножко кода:
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST = 'smtp.yandex.ru'
EMAIL_PORT = 465
EMAIL_HOST_USER = "MAIL@yandex.ru"
EMAIL_HOST_PASSWORD = "PASSWORD"
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True
SERVER_EMAIL = EMAIL_HOST_USER
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

views.py
class RegisterUserView(CreateView):
    """Контроллер, использующий форму для регистрации"""
    model = SimpleUser
    template_name = 'main/register_user.html'
    form_class = RegisterUserForm
    success_url = reverse_lazy('main:register_done')

forms.py
class RegisterUserForm(forms.ModelForm):
    """Форма для регистрации нового юзера"""

    email = forms.EmailField(required=True, label='Адрес электронной почты')
    password1 = forms.CharField(label='Пароль',
                                widget=forms.PasswordInput,
                                help_text=password_validation.password_validators_help_text_html())
    password2 = forms.CharField(label='Пароль(повторно)',
                                widget=forms.PasswordInput,
                                help_text='Введите пароль еще раз')

    def clean_password1(self):
        password1 = self.cleaned_data['password1']
        if password1:
            password_validation.validate_password(password1)
        return password1

    def clean(self):
        super().clean()
        password1 = self.cleaned_data['password1']
        password2 = self.cleaned_data['password2']
        if password1 and password2 and password1 != password2:
            errors = {'password2': ValidationError('Введенные пароли не совпадают',
                                                   code='password_mismatch')}
            raise ValidationError(errors)

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        user.is_active = False
        user.is_activated = False
        if commit:
            user.save()
        user_registered.send(RegisterUserForm, instance=user)
        return user

    class Meta:
        model = SimpleUser
        fields = {'username', 'email', 'password1', 'password2',
                  'first_name', 'last_name'}

Сама функция отправки письма с активацией реализована отдельно:
utilities.py
signer = Signer()

def send_activation_notification(user):
    """Функция отправляет подтверждение регистрации на емейл юзера"""

    if ALLOWED_HOSTS:
        host = 'http://' + ALLOWED_HOSTS[0]
    else:
        host = 'http://localhost:8000'
    context = {'user': user,
               'host': host,
               'sign': signer.sign(user.username)}
    subject = render_to_string('email/activation_letter_subject.txt', context)
    body_text = render_to_string('email/activation_letter_body.txt', context)
    user.email_user(subject, body_text)

apps.py
user_registered = Signal()

def user_registered_dispatcher(sender, **kwargs):
    send_activation_notification(kwargs['instance'])

user_registered.connect(user_registered_dispatcher)

Буду благодарен за любую помощь, спасибо :)

A: В общем, разбиравшись в этом вопросе двое суток, очень многое узнал об устройстве SMTP серверов.
Первое, что необходимо сделать - УБЕДИТЬСЯ в том, что в вашем почтовом аккаунте разрешена отправка писем через smtp сервера(как это сделать вам подскажет гугл)
Второе - не включайте в терминале отладочный smtp сервер django
Третье - правильно выберите EMAIL_PORT
ну и код settings.py прилагаю
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = "acc@gmail.com"
EMAIL_HOST_PASSWORD = "pass"
EMAIL_USE_TLS = True
SERVER_EMAIL = EMAIL_HOST_USER
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER


text:
Q: FCM Node.js server issue android For sending FCM upstream messages through my app I followed this tutorial Sending Notifications with Firebase
My working code is below:
var firebase = require('firebase-admin');
var request = require('request');
const functions = require('firebase-functions');
firebase.initializeApp(functions.config().firebase);

var API_KEY = "my api key"; // Your Firebase Cloud Messaging Server API key

// Fetch the service account key JSON file contents
//var serviceAccount = require("serviceAccountKey.json");

// Initialize the app with a service account, granting admin privileges
//firebase.initializeApp({
//  credential: firebase.credential.cert(serviceAccount),
//  databaseURL: "https://-----.firebaseio.com"
//});

exports.listenForNotificationRequests = functions.database.ref('/notificationRequests')
    .onWrite(event => {
       const request = event.data.val();
              sendNotificationToUser(
                    request.username,
                    request.message,
                    function() {
                      console.error("success");
                    }
                  );
    });

function sendNotificationToUser(username, message, onSuccess) {
  request({
    url: 'https://fcm.googleapis.com/fcm/send',
    method: 'POST',
    headers: {
      'Content-Type' :' application/json',
      'Authorization': 'key='+API_KEY
    },
    body: JSON.stringify({
       notification: {
       title: message, //title of notification
       body: message
        },
      to : usertoken //a static registered user token
    })
  }, function(error, response, body) {
    if (error) { console.error(error); }
    else if (response.statusCode >= 400) {
      console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
    }
    else {
      onSuccess();
    }
  });
}

On running this code I am receiving RemoteMessage in my MyFirebaseMessagingService 's onMessageReceived , but this message return null notification or data. So notification does not appear in app. Can any body here help me what I am doing wrong?
admin.messaging() worked!!

A: This is running code in my module
var request = require('request');
var sendMsgToGroup = function(deviceId, message) {
    request({
        url: 'https://fcm.googleapis.com/fcm/send',
        method: 'POST',
        headers: {
            'Content-Type': ' application/json',
            'Authorization': 'key=<YOUR API KEY>'
        },
        body: JSON.stringify({
            notification: {
                title: message,
                body: 'Testing Notificaiton'
            },
            "to": deviceId
        })
    }, function(error, response, body) {
        if (error)
            console.log(error);
        else if (response.statusCode >= 400)
            console.log("HTTP Error" + response.statusCode + "-" +
                        response.statusCode + "\n" + body);
        else
            console.log(body);
        });
    };

module.exports.sendMessageToGroup = sendMsgToGroup;

You can call this function like
 var FCM = require('./FCM/fcm_config.js');
 FCM.sendMessageToGroup("<Device Token Number>", 'testing');

Reference Link


text:
Q: Split Character String Using Only Last Delimiter in r I have a character variable that I would like to split into 2 variables based on a "-" delimiter, however, I would only like to split based on the last delimiter as there might be multiple "-" in the string.  Example:
Input          Output1  Output2
foo - bar      foo      bar
hey-now-man    hey-now  man
say-now-girl   say-now  girl
fine-now       fine     now

I've tried using strsplit to no avail.

A: You can also use a negative lookahead:
df <- tibble(input = c("foo - bar", "hey-now-man", "say-now-girl", "fine-now"))

df %>%
    separate(input, into = c("output1", "output2"), sep = "\\-(?!.*-)", remove = FALSE)

Refs:
[1] https://frightanic.com/software-development/regex-match-last-occurrence/
[2] https://www.regular-expressions.info/lookaround.html

A: You can try using gregexpr :
a=c("foo - bar","hey-now-man","say-now-girl","fine-now")
lastdelim = tail(gregexpr("-",a)[[1]],n=1)
output1 = sapply(a,function(x) {substr(x,1,lastdelim-1)})
output2 = sapply(a,function(x) {substr(x,lastdelim+1,nchar(x))})

A: Using unglue you would do :
# install.packages("unglue")
library(unglue)
df <- data.frame(input = c("foo - bar","hey-now-man","say-now-girl","fine-now"))
unglue_unnest(df, input, "{output1}{=\\s*-\\s*}{output2=[^-]+}", remove = FALSE)
#>          input output1 output2
#> 1    foo - bar     foo     bar
#> 2  hey-now-man hey-now     man
#> 3 say-now-girl say-now    girl
#> 4     fine-now    fine     now

Created on 2019-11-06 by the reprex package (v0.3.0)

A: A solution based on stringi  and data.table: reverse the string and split it into fixed items and then reverse back:
library(stringi)
x <- c('foo - bar', 'hey-now-man', 'say-now-girl', 'fine-now')

lapply(stri_split_regex(stri_reverse(x), pattern = '[-\\s]+', n = 2), stri_reverse)

If we want to make a data.frame with this:
y <- lapply(stri_split_regex(stri_reverse(x), pattern = '[-\\s]+', n = 2), stri_reverse)

y <- setNames(data.table::transpose(y)[2:1], c('output1', 'output2'))

df <- as.data.frame(c(list(input = x), y))

# > df
# input output1 output2
# 1    foo - bar     foo     bar
# 2  hey-now-man hey-now     man
# 3 say-now-girl say-now    girl
# 4     fine-now    fine     now

A: Came across this really awesome package strex
library(strex)

input <- c('foo - bar', 'hey-now-man', 'say-now-girl', 'fine-now')

output1 <- str_after_last(input, "-")
# [1] " bar" "man"  "girl" "now"
output2 <- str_before_last(input, "-")
# [1] "foo "    "hey-now" "say-now" "fine"

Note that there is a whitespace after "foo" and before "bar" because there is whitespace in the original string.
You can use str_trim or str_squish from the stringr package to remove the whitespace if that is needed. link


text:
Q: Why does my application freeze when I copy a large file? I have an MFC application. It is basically just copying files from one drive to another. When I'm copying large files (more than 1 Gb) and I click on my window, my application freezes, but the copying proceeds in the background. Someone told me that I have to use a worker thread. I used it, but it still freezes. When I'm copying small files then it is OK. I can't figure out what could be the problem. Please someone help!
Here's my code:
void CGetFileListDlg::OnBnClickedButtonGetFileList()
{
 //here i'm doing file list comparing
 AfxBeginThread( CopyThread, &Tstruct ); //here i call my thread and give a struct to it as a paramter, which contains, which file i have to copy
}

UINT CopyThread( LPVOID pParam )
{
UINT uiMaxPass = 3;
UINT uiPAssCount = 0;
int i = 0;

threadstruct *Test = (threadstruct*)(pParam);
CGetFileListDlg* ptr = (CGetFileListDlg*)Test->ez ;

struct address
{
    char *from;
    char *to;
    int current;
};

struct address Address;

for ( i = 0; i < Test->diff; i++ )
    {

    TCHAR currentfile[512], file[MAX_PATH +32], successf[10], unsuccessf[10], buf[20], remainingf[20], oprog[10];
    char tmp[1024], tmp2[1024],dest[1024];
    int j,k,l;
    char ch;

    memset( tmp, 0, sizeof( tmp ) );
    memset( dest, 0, sizeof( dest ) );
    memset( tmp2, 0, sizeof( tmp2 ) );
    memset( buf, 0, sizeof( buf ) );
    memset( currentfile, 0, sizeof( currentfile ) );
    memset( file, 0, sizeof( file ) );
    memset( successf, 0, sizeof( successf ) );
    memset( unsuccessf, 0, sizeof( unsuccessf ) );
    memset( remainingf, 0, sizeof( remainingf ) );
    memset( oprog, 0, sizeof( oprog ) );
    ch = NULL;
    strcat( dest, SecondaryHDD );

    l = 1;
    for ( k = strlen( SecondaryHDD ); k < strlen( Test->difference[i].filename ); k++ )
    {
        dest[k] = Test->difference[i].filename[ l + strlen( SecondaryHDD ) - 1 ];
        l++;
    }
    dest[k]='\0';

    for ( j = strlen( Test->difference[i].filename); ch != '\\'; j-- )
    {
        ch = Test->difference[i].filename[j];
    }

    l = 0;
    for ( k = 3; k < j + 1; k++ )
    {
        tmp2[l] = Test->difference[i].filename[k];
        l++;
    }
    tmp2[l]='\0';
    strcpy( tmp, SecondaryHDD );
    strcat( tmp, tmp2);

    SHCreateDirectoryExA( NULL, tmp, NULL );

    memset( file, 0, sizeof( file ) );

    memset( tmp, 0, sizeof( tmp ) );
    strcpy(tmp, Test->difference[i].filename );

    MultiByteToWideChar(  CP_ACP, NULL, tmp, -1, file, strlen( Test->difference[i].filename ) );
    wsprintf( currentfile, _T("%s"), file );
    ptr->m_edCurrentCopy.SetWindowText( currentfile );

    Address.from = strdup(tmp);
    Address.to = strdup(dest);
    Address.current = i;

    PostMessage( (HWND)Test->hWnd , WMU_PROGRESS, (WPARAM)&Address, (LPARAM)&dest ); //calling OnProgressMsg function, which does the copy
    Sleep(100);
}

PostMessage( (HWND)Test->hWnd, WMU_COPYDONE, uiPAssCount, 0 );

return 0;
}

LRESULT CGetFileListDlg::OnProgressMsg( WPARAM wParam, LPARAM lParam )
{
    TCHAR currentfile[512], file[MAX_PATH +32], successf[10], unsuccessf[10], buf[20], remainingf[20], oprog[10];
char tmp[1024], tmp2[1024],dest[1024];
int j,k,l;
char ch;
struct address
{
    char *from;
    char *to;
    int current;
};

address *Address = (address*)wParam;

//char *to = (char*)lParam;
//char *from = (char*)wParam;

int ret = 0;
ret = CopyFileA( Address->from, Address->to, false );
//ret = CopyFileExA( Address->from, Address->to, &MyCopyProgressRoutine, this, FALSE,FALSE);

if ( ret == 0 ) //failed
{
    wsprintf( buf, _T("Failed ( %d )"), GetLastError() );
    m_difference.SetItemText(Address->current, 2, buf);
    unsuccess++;
    wsprintf( unsuccessf, _T("%d"), unsuccess, GetLastError() );
    m_unsuccess.SetWindowText( unsuccessf );
}
else
{
    m_difference.SetItemText(Address->current, 2, L"OK!");
    success++;
    wsprintf( successf, _T("%d"), success );
    m_success.SetWindowText( successf );
}

wsprintf( remainingf, _T("%d"), ( diff - ( success + unsuccess ) ) );
m_remaining.SetWindowText( remainingf );

wsprintf( oprog, _T("%d %%"), ( (success + unsuccess ) *100 )/diff );
m_overallprog.SetWindowText( oprog );

UpdateData(FALSE);

return 0;
}

A: PostMessage( (HWND)Test->hWnd , WMU_PROGRESS, (WPARAM)&Address, (LPARAM)&dest );
//calling OnProgressMsg function, which does the copy

So you spawn a new thread, that ... posts messages to the main thread and gets the main thread to do all the copying?
That's not how you use worker threads. Your worker thread should be the one doing the copying, and all that OnProgressMsg should do is update the UI.

A: I think what was meant by use a WorkerThread is that the WorkerThread must be doing the copying. To talk in terms of Win32API at least, all Windows, in fact anything with a hWnd handle in Windows, has a message loop. When this message loop stops responding within a sufficient timeframe, Windows Explorer thinks your application is "not responding" because in essence it isn't - it isn't processing messages.
What you need to do is invoke the subthread which does the copying, then notify the "parent" thread when done so that the dialog can be closed; or notify the parent dialog of progress so that the parent dialog can update a progress bar, or something like that.


text:
Q: HP ILO utility for Ubuntu - hponcfg fails due to missing hp-ilo package I'm working with an Ubuntu-based system running on an HP ProLiant DL360p Gen8 server. I prefer to install HP's management agents when I can for full hardware monitoring/configuration capabilities.
Per HP's documentation, I added the download tree for the Ubuntu Management Component Pack to: /etc/apt/sources.list
Following an apt-get update, I was able to run:
apt-get install cpqacuxe hp-ams hp-health hp-snmp-agents hpacucli hponcfg

So I run the hponcfg -w ilo.xml to retrieve ILO settings, with result:
root@zetavault1:~# hponcfg
HP Lights-Out Online Configuration utility
Version 4.2.0 Date 6/10/2013 (c) Hewlett-Packard Company, 2013
ERROR:  Could not find the Management Processor Device Node.
        Please check if the iLO driver module is installed and running properly.
        ACTION REQUIRED: Install/Re-install hp Lights-Out driver package('hp-ilo' RPM) for iLO.

The takeaway is that the ILO device isn't initialized or available to the OS due to the missing hp-ilo package. My system's info is:
# uname -a && cat /etc/issue
Linux zetavault1 3.10.28-42-zetavault #1 SMP Mon Jan 27 09:33:22 GMT 2014 x86_64 x86_64 x86_64 GNU/Linux
Ubuntu 12.04.4 LTS \n \l

*

*Are there any workarounds for this?

*For people who run Ubuntu on HP gear, are there other things I should be watching out for?

*Does HP not fully support Ubuntu as an OS target?

A: The hp-ilo package doesn't need to exist anymore on modern Linux systems, since the driver is now part of the mainline kernel (since 2.6.33 or thereabouts).
It should not be necessary to do anything with a standard kernel on any mainstream Linux distribution, since they all build the hpilo module and make it available by default.
However, you seem to have a nonstandard kernel from a third party. In this case, you may have to manually load the module:
modprobe hpilo

Or, you may find that the people who built the kernel (Zetavault?) did not actually build in this module. In this case you need to take up the issue with them.

A: If someone still arrives to this question, ipmitool works fine on HP servers as well.
After installing the tool, get the list of users:
$ ipmitool user list 1
ID  Name       Callin  Link  Auth   IPMI Msg  Channel Priv     Limit
1               true   false        false             NO ACCESS
2   root        true   true         true              ADMINISTRATOR
etc...

Change root password (ID = 2 in this case):
$  ipmitool user set password 2

It will be prompted to enter a new password.


text:
Q: How to update a property in a .properties file without removing the comments(in Java) I am trying to update a property in a properties file. Its working fine but the comments which I have given in the properties file gets deleted. Comments section is very important for that properties file since many users will use that properties file and make changes to it. Below is the code I am using to store/update the property.
prop.setProperty("someproperty", "sometext");
prop.store(new FileOutputStream("Test.properties"), null);

Thank you.

A: You can't without writing entirely custom code for both load and store. Otherwise you will lose not only the comments but the ordering.


text:
Q: Copy and paste in Excel using Python I try to copy and paste from file to another in Excel with  this code:
from win32com import client

xlapp = client.Dispatch("excel.application")
work = xlapp.Workbooks
copysheet = work.Open("D:/mm/trn files/Field Inspection Test Notification for
ERC Review (CI).xlsx" )
cs = copysheet.Worksheets(1)
cs.Visible = 1
cs.Range("B2:G66").Copy()
pastesheet = work.Open("D:/mm/trn files/Field Inspection Test Notification
for ERC Review (ss).xlsx")
pastesheet.Paste(cs.Range("B2:G66"))

But it gives me this error:
raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
AttributeError: '<win32com.gen_py.Microsoft Excel 15.0 Object Library._Workbook instance at 0x47919440>' object has no attribute 'Paste'

And I don't know what's the problem. Do you have any idea?

A: The pastesheet is a Workbook object, which does not have a Paste method. You might do something similar to what you did with the copysheet object.
i.e.
ps = pastesheet.Worksheets(1)
ps.Paste(cs.Range("B2:G66"))


text:
Q: When to use Foo.Process(Bar) over Bar.Process() in OOP? I don't know what these techniques are called, please help me rephrase the question if necessary.
I always face this dilemma when creating classes. Is there a rule in OOP or in some programming principles that encourages either Foo.Process(Bar) or Bar.Process()?
Foo.Process(Bar) and Bar.Process() does the same thing to Bar, the only difference is where the method is declared. The first  is property of Foo while the latter is property of Bar.

A: That's a simple example.
Car c = new Car();
c.start(); //start the car

PetrolStationMan p = new PetrolStationMan();
p.reFill(c); //refill fuel tank

I hope you understand better that way.
Both are valid like @deceze said, it's just a logical question

A: In OOP, state (data) and behaviour (functions/methods) are combined together, into objects.
Some methods tell you about the state of an object (getter methods). As those methods are tightly coupled with the object, they are declared as part of the class of the object. In the common case that the state is stored in otherwise inaccessible (private) fields, there is no other option.
Some methods alter the state of an object. If they are tightly coupled with the object, or they alter private fields, they must be declared as part of the class (as mutator methods) just like a getter.
A third, and significant case, is when you have polymorphism. That is, when the class of an object has more than one concrete types that have different behaviour. In that case which behaviour depends on the type (class) and thus must be declared as part of the class.
The remaining style, Foo.Process(Bar), is suitable for cases where the operation is not tightly coupled with the object itself and for which there is no polymorphism.
 public abstract class Person
 {
    private String name;

    // This getter method access the private name field
    // so it must be declared as part of the class
    public final String getName() {
       return name;
    }

    // This mutator method access the private name field
    // so it must be declared as part of the class
    public final void setName(String name) {
       this.name = name;
    }

    // This method is polymorphic; Minion.getBoss() and Boss.getBoss()
    // have different behaviour and so must be declared as part of the class.
    public abstract Boss getBoss();

 }

 public class Minion extends Person
 {
    private Boss boss;

    public Boss getBoss()
    {
       return boss;
    }
 }

 public class Boss extends Person
 {
    public Boss getBoss()
    {
       // *I* am the boss, nobody is *my* boss.
       return null;
    }
 }


text:
Q: 20.04 : "open with other application" menu not working properly on the Desktop I recently installed 20.04 and for some kinds of files, whether text or binary ones, I'm unable to choose an application  to open them like I used to in 18.04.
For example, when I right-click a .c (C source code) file and select 'open with other application', it immediately opens it with gedit, even though I have other programs able to open these, like Geany.
For other kind of files, like object code/ binary files, the menu does show up but it says there are "No Apps Available" for it, whereas I have several programs able to read them, like GHex. Even worse, double clicking on these files has no effect. In 18.04 it would at least try to open them with gedit.
The .desktop files in /usr/share/applications have the correct Exec=command %F, so I have no idea why it doesn't list them.
What's even stranger is that for some filetypes like images, the menu works fine and even has the View all applications button, which is the behavior I wish to  have for ALL files, regardless of their extensions and MIME type.
Is there a way to force Gnome to list all possibilities when I click on "open with other applications" ?
Thanks for your tips !
Edit : I've narrowed down the bug behavior : it only happens on the Desktop. When opening files through Nautilus, the correct behavior happens.
In case my description is not clear, here are images showing the desired and problematic behaviors of the "Open With other application" menu :

A: Ubuntu 20.04 uses a Gnome Shell extension to handle files on the desktop, whereas previously, these files were handled by the file explorer, nautilus. This extension is limited and has several limitations, including lacking the ability to assign applications to a file type. So, until that extension is further developed, you have to use the file manager.

A: I suggest installing the package 'filemanager-actions' that provide an extension to the nautilus allowing user-defined actions. The command is
sudo apt install filemanager-actions


text:
Q: For-each loop is iterating backwards Given the code
String[] p = { "A", "B", "C", "D" };
String b = "";

for ( String q : p )
   b = q + b;

System.out.println( b );

I thought the output would be "ABCD" but it is "DCBA"
Why??

A: Your loop prepends each element to b.
That is:

*

*prepend "A" -> "A"

*prepend "B" -> "BA"

*prepend "C" -> "CBA"

*prepend "D" -> "DCBA"

If you want to get "ABCD", change the logic to append:
for ( String q : p ) {
   // b = q + b;  // prepend
   // b = b + q;  // append
   b += q;        // append, using the shorter `+=` notation
}

A: Because in
b = q + b;

*

*q represents current element loop is getting from your array

*b is result of previous concatenations

which means you are adding new part in front of old result.

A: The expression
q + b;

means new element + old string.
For each iteration through the 4 element array, the values are
b = "A" + "" - resulting in "A"
b = "B" + "A" - resulting in "BA"
b = "C" + "BA" - resulting in "CBA"
b = "D" + "CBA" - resulting in "DCBA"

Change the assignment to
    b = b + q;
or
    b += q;


text:
Q: What is purpose of items in function parentheses? function handleButtonClick(e) {
var textInput = document.getElementById("songTextInput");
var songName = textInput.value;
//alert("Adding " + songName);

if (songName == "") {
    alert("Please enter a song");
}
else {
    //alert("Adding " + songName);
    var li = document.createElement("li");
    li.innerHTML = songName;
    var ul = document.getElementById("playlist");
    ul.appendChild(li);

    // for Ready Bake
    save(songName);
}
}

At this code why we put an "e" into function that stays in first line. As far as i can see, we didn't used it except there?

A: You don't use it now but :

*

*this parameter, an event, is received even if you don't declare it, if you provide it as callback to an event binding utility (for example myElement.onclick=handleButtonClick;)

*it's possible that your event handler will have to use the event in the future, it's cleaner to declare it now

You don't have to declare it, but it's a good practice.

A: From the name of the function, I'm assuming this is a click handler attached to a button on your page. Normally, when an event is triggered, the browser passes an Event object as an argument to the event handler. In your code, the e argument would contain this Event object. In your event handler you are not using the passed in Event object and hence this can be removed.
However, at times you may want to use the passed in event object. For example: you may want a certain action to be performed when the button is clicked and a different action to be performed when the button is clicked with the Ctrl key held down. In this case, you would use the ctrlKey property of the passed in Event object to determine which action to perform.


text:
Q: Использование return без возвращаемого значения Есть код:
private void showResult() {
        if (mt == null) return;
        int result = -1;
        try {
            Log.d(LOG_TAG, "Try to get result");
            result = mt.get();
            Log.d(LOG_TAG, "get returns " + result);
            Toast.makeText(this, "get returns " + result, Toast.LENGTH_LONG).show();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

Почему return прописывается без возвращаемого значения и что при этом происходит?

A: В данном случае, ключевое слово return использовано для того, чтобы прервать дальнейшее выполнение метода и вернуть управление обратно вызывающему методу.

A: Поскольку у Вас функция showResult объявлена как void? то есть не возращяет значения.

Оператор return используется для выполнения явного возврата из метода.
То есть он снова передает управление объекту, который вызвал данный
метод. ... Оператор return предписывает интерпретатору Java остановить
выполнение текущего метода. Если метод возвращает значение, оператор
return сопровождается некоторым выражением.

в Вашем случае просто выполнения явного возврата из метода.

A: private void showResult() {
        if (mt == null) return; //Если mt == null функция здесь завершается
        int result = -1;
        try {
            Log.d(LOG_TAG, "Try to get result");
            result = mt.get();
            Log.d(LOG_TAG, "get returns " + result);
            Toast.makeText(this, "get returns " + result, Toast.LENGTH_LONG).show();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

Почему return прописывается без возвращаемого значения

Так как у вас  функция типа void, функция ничего не должен возвращать.


text:
Q: Pyspark Generate rows depending on column value Below is the data input,
|       start       |   format_date     |    diff|
+-------------------+-------------------+--------+
|2019-11-15 20:30:00|2019-11-15 18:30:00|     4  |

Expected output:
start                     format_date                      Diff                    seq
2019-11-15 20:30:00     2019-11-15 18:30:00                  4                       1
2019-11-15 20:30:00     2019-11-15 18:30:00                  4                       2
2019-11-15 20:30:00     2019-11-15 18:30:00                  4                       3
2019-11-15 20:30:00     2019-11-15 18:30:00                  4                       4

how do i generate rows depending up on the value (diff) of a column?

A: Spark 2.4 or greater solution
from pyspark.sql import functions as F

from pyspark.sql.types import *

df= spark.createDataFrame([["2019-11-15 20:30:00","2019-11-15 18:30:00" ,4]], ["start", "format_date", "diff"])

df.select("*", F.explode(F.sequence(F.lit(1), F.col("diff"))).alias("seq")).show

+-------------------+-------------------+----+---+
|              start|        format_date|diff|seq|
+-------------------+-------------------+----+---+
|2019-11-15 20:30:00|2019-11-15 18:30:00|   4|  1|
|2019-11-15 20:30:00|2019-11-15 18:30:00|   4|  2|
|2019-11-15 20:30:00|2019-11-15 18:30:00|   4|  3|
|2019-11-15 20:30:00|2019-11-15 18:30:00|   4|  4|

A: Spark < 2.4
You can use explode function
import pyspark.sql.functions as F
import pyspark.sql.types as Types

def rangeArr(diff):
  return range(1,diff+1)
rangeUdf = F.udf(rangeArr, Types.ArrayType(Types.IntegerType()))

df = df.withColumn('seqArr', rangeUdf('diff'))

df = df.withColumn('seq', F.explode('seqArr'))


text:
Q: C# Convert string to int (with rounding) What's the easiest way to get a string with the value of "76.10" into an int rounded to 76?
I've tried a few different ways using Convert.ToInt32 and Decimal but I can't seem to get it right?
Edit: Here's the code Jon helped me with:
            decimal t = Math.Round(decimal.Parse(info.HDDStatus));
            int v = (int)t;

A: The simplest way would be to use Decimal.Parse to parse it, and then Math.Round (or potentially Math.Floor depending on how you want numbers like "76.7" to be handled) to round it. Then convert to an integer just by casting.
I would suggest using decimal rather than double as you're inherently talking about a decimal number (as that's how it's represented in text).
The exact method of parsing will depend on culture - would you expect text of "76,10" to appear in a European context, or will it always use "." as the decimal point, for example?

A: *

*Convert it to double first and use Math.Floor()

*Extract the substring (76) first .

string s = "76.7";
int n = int.Parse(s.Substring(0, s.IndexOf('.')));


text:
Q: Finding cube roots of a unity - proper explanation is needed SQUARE ROOT
Let's say that I have:
\begin{align*}
x^2 &= 9
\end{align*}
And I $\sqrt{\phantom{x}}$ an entire equation to get:
\begin{align*}
x_{1,2} &= \sqrt{9}\\
x_{1} &= +3\\
x_{2} &= -3
\end{align*}
Experience and "fundamental theorem of algebra" thought me that:

There are always two square roots ($x_1$, $x_2$)!

Experience thought me that:

Product of mixed roots doesn't return back the original:
\begin{align*}
x_1 \cdot x_2 &= -3 \cdot 3 = -9\\
x_2 \cdot x_1 &= 3 \cdot (-3) = -9
\end{align*}

Experience also thought me that:

Only if roots are multiplied by itself they return back the result:
\begin{align*}
x_1 \cdot x_1 &= 3 \cdot 3 = 9\\
x_2 \cdot x_2 &= (-3) \cdot (-3) = 9
\end{align*}

CUBE ROOT
Then there comes this:
\begin{align*}
x^3 &= 1\\
\end{align*}
If I $\sqrt{\phantom{x}}$ an entire equation I get:
\begin{align*}
x_{1,2,3} &= \sqrt[3]{1}\\
x_1 &= 1\\
x_2 &= \text{???}\\
x_3 &= \text{???}
\end{align*}
Here I have no experience whatsoever but "fundamental theorem of algebra" says that:

There are always three cube roots ($x_1$, $x_2$, $x_3$)!

Now pay attention! Like for square root it should be true that:

If roots $x_1$, $x_2$, $x_3$ are multiplied by itself they return $1$. Their mixed products will probably return something else.
\begin{align*}
x_1 \cdot x_1 \cdot x_1 = 1\\
x_2 \cdot x_2 \cdot x_2 = 1\\
x_3 \cdot x_3 \cdot x_3 = 1
\end{align*}

So at this point everybody's already rushing to their paper and drawing this complex plane:

And in complex plane:

If we multiply complex numbers, length of their position vectors multiply and their angles sum up.

So everybody will now draw $x_1$ on the $\mathbb{R}$ axis and tell me that this is the first root. I agree with that. Then they say:

Length of a position vector of other two roots ($x_2$, $x_2$) must be $1$ as well.

And I agree with that. But what they say now, I can't agree with no matter how I look at it. They say:

Because according to "fundamental theorem of algebra" there are three cube roots, and we will multiply them in order to get to $1$, angle between them must be $120^\circ$. We now start at $1$ and if we do a full circle we end at $1$ again. Woila! Problem solved...

I can't agree with this explanation as is because this only holds for $x_1$. If I take $x_1$ and make a full circle I end up getting $1$. But with $x_2$ and $x_3$ my starting point is not $1$. Starting points are actually:
\begin{align*}
\text{starting point for $x_2$:} \hspace{5mm} -\frac{1}{2} - \frac{\sqrt{3}}{2}i \\
\text{starting point for $x_3$:} \hspace{5mm} -\frac{1}{2} + \frac{\sqrt{3}}{2}i
\end{align*}
And in case of $x_2$ and $x_3$ when we do a full circle we don't end up getting $1$, but we geometricaly looking end at positions:
\begin{align*}
-1/2 - \sqrt{3}/2 i \\
-1/2 + \sqrt{3}/2 i
\end{align*}
If the starting positions are as I state they are, angle that we need in order to get to the $1$ should be $\pm240/3 = \pm80^\circ$.
But then why does this explanation that they use, work? At the end of the day e.g. $x_2$ solves the problem:
\begin{align*}
\left(x_2\right)^3 &= 1\\
\left( -\frac{1}{2} + \frac{\sqrt{3}}{2} i \right)^3 &= 1\\
\left( -\frac{1}{2} + \frac{\sqrt{3}}{2} i \right) \left( -\frac{1}{2} + \frac{\sqrt{3}}{2} i \right) \left( -\frac{1}{2} + \frac{\sqrt{3}}{2} i \right)&= 1\\
\left(\frac{1}{4} - \frac{\sqrt{3}}{4}i - \frac{\sqrt{3}}{4}i + \frac{3}{4}i^2\right) \left( -\frac{1}{2} + \frac{\sqrt{3}}{2} i \right) &= 1\\
\left(\frac{1}{4} - \frac{2\sqrt{3}}{4}i - \frac{3}{4}\right) \left( -\frac{1}{2} + \frac{\sqrt{3}}{2} i \right) &= 1\\
\left(-\frac{1}{2} - \frac{\sqrt{3}}{2}i\right) \left( -\frac{1}{2} + \frac{\sqrt{3}}{2} i \right) &= 1\\
\frac{1}{4} - \frac{\sqrt{3}}{4} i + \frac{\sqrt{3}}{4} i - \frac{3}{4} i^2 &= 1\\
\frac{1}{4} + \frac{3}{4} &= 1
\end{align*}
I am sure there is something wrong with the explanation everybody are using but it is correct to assume roots are $120^\circ$ appart...

Probably the point here is  not about making a full circle at all! Like most of the people say. It must be about adding conjugate pairs so that artifficialy we create enough roots to satisfy fundamental theorem of algebra! Thats all! So odd number root $3$ was historicaly first one that forced us to get out of the horizontal axis in complex plane and invent complex roots...

Can anyone present a proper explanation of why we choose $120^\circ$ for cube roots?

A: There is really no "first" root, "second" root, etc.
In the case of $x^2=1$, there are two roots, $-1$ and $1$. It is your choice to give these two roots whatever names you like.
In the case of $x^3=1$, there are three distinct roots. Again, it does not matter which one you call $x_1$.
In general, (complex) solutions to the equation $x^n=1$ together with complex multiplication form a group: https://en.wikipedia.org/wiki/Root_of_unity
This group tells you what happens when you multiply two solutions to the equations $x^n=1$.

I don't know where the "everybody explanation" is from; I would not do that anyway.
One way to find the three roots for $x^3=1$ is quite straightforward. Write $x=re^{i\theta}$ where $r\ge 0$ and $\theta\in[0,2\pi)$. Then
$$
(re^{i\theta})^3=1
$$
Taking the absolute value on both sides you get $r=1$. On the other hand,
$$
e^{i(3\theta)}=1
$$
which implies that $3\theta=2k\pi$ where $k$ is some integer. Now write
$$
\theta=\frac{2k\pi}{3},\quad k\in\mathbb{Z}
$$
and pick the ones that are in $[0,2\pi)$. By periodicity, this is not a unique way to represent the roots. You could, for example, restrict $\theta$ to $[-\pi,\pi)$ at the beginning of the calculation.


text:
Q: Minimum changes required to make the array in increasing or decreasing order I have an array where I want to find out the minimum number of values I need to make to change the array to be in increasing or decreasing order.
For example:
a = [1,2,5,6,5,7]

In above array, a[4]=5 which is less than a[3]=6. So I can add 1 to 5 to make it 6 so array becomes a=[1,2,5,6,6,7]. It is ok if I have same values consecutively.

I have written below program but I am not sure if this works fine for all cases.
public int process(List<Integer> list) {

    int up = 0;
    int down = 0;
    for (int i = 0; i < list.size() - 1; i++) {
        int left = list.get(i);
        int right = list.get(i + 1);
        if (left > right) {
            up += left - right;
        } else {
            down += right - left;
        }
    }
    if(up < down) {
       return up;
    } else {
       return down;
    }
}

This is my interview question, and I was told that the program fails for some scenarios which I am not able to find out.

A: So I think this is asking about your sorts, and how many iterations it would take for that sort to accomplish the goal of sorting your numbers, whether it is ascending or descending order. Were you allowed to use common sorts? If so, I would either make Selection sort or a Merge Sort program. I actually did that on a personal project and also had it count iterations to compare the speeds of different sorts. Merge Sort took me a while to reproduce, but Selection Sort is quite simple to do.
Each of these sorts have best and worst case scenarios.
EDIT
I also found this:
Minimum no of changes required to make array strictly increasing


text:
Q: Why my simple Toast doesn't want to appear and the app crashes? I everyone, I am trying to make such a dumb thing: center the text inside a Toast which is created inside an onclick event listener.
I have created a TextView inside the layout I use and when I try to call the event that should the display the toast the app crashes with this exception:
03-19 23:20:40.258: E/AndroidRuntime(3364): java.lang.IllegalArgumentException: View not
attached to window manager

This is my code:
toastTextView = (TextView) findViewById(R.id.toastView);
Toast toast = Toast.makeText(MyActivity.this, "Very very very long long text that should be displayed in the middle of this toast",
                           Toast.LENGTH_SHORT);
                toast.setView(toastTextView);
                toast.show();

The xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical" android:layout_width="fill_parent"
          android:layout_height="fill_parent">

<LinearLayout android:id="@+id/chart" android:orientation="horizontal"
              android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1"/>

<TextView
    android:id="@+id/toastView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<LinearLayout android:orientation="horizontal"
              android:layout_width="fill_parent" android:layout_height="wrap_content">

</LinearLayout>

Where's the problem with this simple code?
Thanks for the attention!
EDIT: this is the layout of the custom_toast.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >

</LinearLayout>

A: You are using a view that is already attached to another view hierarchy. You have to inflate your custom toast view separately like this:
custom_toast.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/black"
                android:padding="5dp">

        <TextView
                android:id="@+id/tvToast"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"/>

</RelativeLayout>

And that's how you use it:
LayoutInflater inflater = LayoutInflater.from(context);
View customToastView = inflater.inflate(R.layout.custom_toast, null);

TextView tvToast = (TextView) customToastView.findViewById(R.id.tvToast);
tvToast.setText("This is a custom toast with centered text");

Toast toast = new Toast(context);
toast.setView(customToastView);
toast.setDuration(Toast.LENGTH_SHORT);
toast.show();

A: Try using a SpannableString to format your Toast, you can get a lot of mileage out of that without worrying about custom views.
String fancyText = "MyFancy long text";
SpannableStringBuilder span = new SpannableStringBuilder(fancyText);
span.setSpan(new AlignmentSpan(Layout.Alignment.ALIGN_CENTER), 0, fancyText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Toast.makeText(MyActivity.this, span, Toast.LENGTH_SHORT).show();

A: My guess is that you have to set the toast_layout.xml as the view of your toast, not only the single textView out of it.
Try to add an id to your outermost linear layout, ...
toast_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/toast_layout_root"
      android:orientation="vertical" android:layout_width="fill_parent"
      android:layout_height="fill_parent">

      <LinearLayout .../>
      <TextView .../>
</LinearLayout>

... inflate it with the layout inflater and set this as your toast view.
java.file
View toastRootView = getLayoutInflater().inflate(R.layout.toast_layout,
                           (ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = findViewById(R.id.toastView);
text.setText("Very [...] long text [...]");

Toast toast = new Toast(MyActivity.this)
.setView(toastRootView)
.setDuration(Toast.LENGTH_SHORT)
.show();

So "toast_layout" is the name of the xml file containing the layout and toast_layout_root is the id of the root element in this file (the outermost linear layout).
Hope this helps,
Kai
Follow up link:
http://meddington.hubpages.com/hub/How-To-Toast-In-Android


text:
Q: Downloading a CSV that requires authentication from an email link I'm a very junior developer, tasked with automating the creation, download and transformation of a query from Stripe Sigma.
I've been able to get the bulk of my job done: I have daily scheduled queries that generate a report for the prior 24 hours, which is linked to a dummy account purely for those reports, and I've got the Transformation and reports done on the back half of this problem.
The roadblock I've run into though is getting this code to pull the csv that manually clicking the link generates.
import re
from imbox import Imbox # pip install imbox
import traceback
import requests
from bs4 import BeautifulSoup
mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=None, starttls=False)

messages = mail.messages(unread=True)
message_list = []
for (uid, message) in messages:
    body = str(message.body.get('html'))
    message_list.append(body)

mail.logout()

def get_download_link(message):
    print(message[0])
    soup = BeautifulSoup(message, 'html.parser')

    urls = []
    for link in soup.find_all('a'):
        print(link.get('href'))
        urls.append(link.get('href'))
    return urls[1]
    # return urls

dl_urls = []
for m in message_list:
     dl_urls.append(get_download_link(m))

for url in dl_urls:
print(url)
try:
s = requests.Session()
s.auth = (username, password)
response = s.get(url, allow_redirects=True, auth= (username, password))
# print(response.headers)
if (response.status_code == requests.codes.ok):
print('response headers', response.headers['content-type'])
response = requests.get(url, allow_redirects=True, auth= HTTPDigestAuth(username, password))
# print(response.text)
print(response.content)
# open(filename, 'wb').write(response.content)
else:
print("invalid status code",response.status_code)
except:
print('problem with url', url)
I'm working on this in jupyter notebooks, I've tried to just include relevant code detailing how I got into the email, how I extracted URLS from said email, and which one upon being clicked would download the csv.
All the way til the last step, I've had remarkably good luck, but now, the URL that I manually click downloads the csv as expected, however that same URL is being treated as the HTML for a stripe page by python/requests.
I've tried poking around in the headers, the one header that was suggested on another post ('Content-Disposition') wasn't present, and the printing the headers that are present takes up a good 20-25 lines.
Any suggestions on either headers that could contain the csv, or other approaches I would take would be appreciated.
I've included a (intentionally broken) URL to show the rough format of what is working for manual download, not working when kept in python entirely.
https://59.email.stripe.com/CL0/https:%2F%2Fdashboard.stripe.com%2Fscheduled_query_runs%xxxxxxxxxxxxxxxx%2Fdownload/1/xxxxxxxxxxxx-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx-000000/xxxxxxxxx-xxxxx_xxxxxxxxxxxxxxxx=233

A: If you're using scheduled queries, you can receive notification about completion/availability as webhooks and then access the files programmatically using the url included in the event payload. You can also list/retrieve scheduled queries via the API and check their status before accessing the data at the file link.
There should be no need to parse these links out of an email.

A: You can also set up a Stripe webhook for the Stripe Sigma query run, pointing that webhook notification to a Zap webhook trigger. Then:

*

*Catch the hook in Zapier

*Filter by the Sigma query name

*Use another Zapier webhook custom request to authenticate and grab the data object file URL

*Use the utilities formatter by Zapier to transform the results into a CSV
file


text:
Q: Grouping subquery and use concat_ws() to separate and combine result set I have written query by combining two tables and result looks like below mentioned
Result Set

recipient_email
recipient_name
accrual_deadline
CCA

siva@gmail.com
siva
jun 24
reddy@gmail.com

siva@gmail.com
siva
jun 24
sa@gmail.com

mohan@gmail.com
mohan
jun 24
ma@gmail.com

mohan@gmail.com
mohan
jun 24
run@gmail.com

Query:
 SELECT te.email AS recipient_email
    ,te.employee_name AS recipient_name
    ,(
        SELECT CONVERT(VARCHAR, DATEADD(d, - 3, MAX(TRANSACTION_DATE)), 107)
        FROM [POT].[vw_Calendar]
        WHERE CURRENT_FISCAL_YEAR_FLAG = 'Y'
            AND CURRENT_FISCAL_QUARTER_FLAG = 'Y'
        ) AS accrual_deadline
    ,'GR' AS emp_type
    ,te1.email AS CostCenterAnalyst FROM [POT].[vw_POT_Open_PO] op
    LEFT JOIN POT.vw_Employee te ON te.Employee_Number = op.Goods_Recipient_Emp_ID
    AND te.flag_Status = 'A'
    JOIN POT.vw_Employee te1 ON te1.Employee_Number = op.pocostcenteranlystid
    LEFT JOIN [POT].[tbl_POT_Open_PO_Accrual_Reminder_History] opair ON DATEPART(month, GETDATE()) + DATEPART(year, GETDATE()) = DATEPART(month, [Mail_Sent_On]) + DATEPART(year, [Mail_Sent_On])
    AND [Recipient_Email] = te.email
    AND opair.Flag_Active = 1
    AND [Reminder_Type] = 'Accrual_Input'
    WHERE te.email IS NOT NULL
    AND opair.Recipient_Email IS NULL
    AND te.Email IN (
        'siva@amat.com'
        ,'mohan@amat.com'
        )  GROUP BY te.email
    ,te.employee_name
    ,te1.email

I have to group the recipient_email and result should display like below

recipient_email
recipient_name
accrual_deadline
CCA

siva@gmail.com
siva
jun 24
reddy@gmail.com; sa@gmail.com

mohan@gmail.com
mohan
jun 24
ma@gmail.com; run@gmail.com


text:
Q: Two questions about copy_pte_range() in kernel I've been trying to understand how fork() works and finally arrived at copy_pte_range(). Most of the functions are understandable but few are quite questionable.
Kernel: 4.14.84
static int copy_pte_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
           pmd_t *dst_pmd, pmd_t *src_pmd, struct vm_area_struct *vma,
           unsigned long addr, unsigned long end)
{
    pte_t *orig_src_pte, *orig_dst_pte;
    pte_t *src_pte, *dst_pte;
    spinlock_t *src_ptl, *dst_ptl;
    int progress = 0;
    int rss[NR_MM_COUNTERS];
    swp_entry_t entry = (swp_entry_t){0};

again:
    init_rss_vec(rss);

    dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
    if (!dst_pte)
        return -ENOMEM;
    src_pte = pte_offset_map(src_pmd, addr);
    src_ptl = pte_lockptr(src_mm, src_pmd);
    spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
    orig_src_pte = src_pte;
    orig_dst_pte = dst_pte;
    arch_enter_lazy_mmu_mode();

    do {
        /*
         * We are holding two locks at this point - either of them
         * could generate latencies in another task on another CPU.
         */
        if (progress >= 32) {
            progress = 0;
            if (need_resched() ||
                spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
                break;
        }
        if (pte_none(*src_pte)) {
            progress++;
            continue;
        }
        entry.val = copy_one_pte(dst_mm, src_mm, dst_pte, src_pte,
                            vma, addr, rss);
        if (entry.val)
            break;
        progress += 8;
    } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);

    arch_leave_lazy_mmu_mode();
    spin_unlock(src_ptl);
    pte_unmap(orig_src_pte);
    add_mm_rss_vec(dst_mm, rss);
    pte_unmap_unlock(orig_dst_pte, dst_ptl);
    cond_resched();

    if (entry.val) {
        if (add_swap_count_continuation(entry, GFP_KERNEL) < 0)
            return -ENOMEM;
        progress = 0;
    }
    if (addr != end)
        goto again;
    return 0;
}

Questions
1. In the do {} while(), what is the purpose of progress variable?
2. After do {} while(), there is pte_unmap(orig_src_pte); Why is it needed? This is the process of fork(). Based on my knowledge, the parent pte(orig_src_pte) should still be mapped because the process is based on Copy-on-Write so I guess it doesn't have to be unmapped.

A: *

*The progress variable measures the cost of the operations performed under locks, and avoids holding those locks for too long. At most every 32 calls to pte_none, or 4 calls to copy_one_pte (which is expensive), or a combination thereof, the function checks whether a reschedule is needed, or if the locks are requested elsewhere; if so, it releases the locks and allows a reschedule. The function continues where it left off, thanks to the jump to again.

*The unmap call doesn't unmap the original PTE in the source process, it undoes the effects of the src_pte = pte_offset_map(src_pmd, addr); line at the start of the function.


text: Q: How to get Coinbase option market data via API or Websocket? I was trying to get Coinbase option market data via any API or Websocket but I could not find anything matching my requirement in their API docs.I even looked their advanced trading doc.Can someone suggest me any API or Websocket that could help me?


text:
Q: jQuery drag&drop timeline tolerance I'm building a small but simple timeline scheduler, where external events (divs) could be dragged in. In the timeline one day exists out of 8 hours.
When draggin i have the option snap set to the snap element (.drop tr) and the snapMode to inner. In the over method from droppable when the dragged element is over the drop element the bg color is being changed.
But i've some problems

*

*When i drag the element down over the droppable (over) the event bg is changed, but when drag the element up the out method is still being called, how is this possible?

*When dragging the event horizontal i want a interval from 15 minutes. So i was thinking width cell (20px) = 1 hour / 4 = 5px (15 min). I have tried this with draggable grid but its not working correctly.

For code i've added a jsfiddle, dont look at the style its a concept :).
Jquery part
$(function()
{
    $('.evt').draggable({
        revert  : 'invalid',
        grid    : [20 / 4, 40],
        snap    : '.drop tr',
        snapMode: "inner"
    });

    $('.day tr').droppable({
        accept   : '.evt',
        tolerance: "fit",
        over     : function(event, ui)
        {
            $(ui.draggable).css('background', 'lightgreen');
            console.log('over');
        },
        out      : function(event, ui)
        {
            $(ui.draggable).css('background', 'red');
            console.log('out');
        }
    });
});

https://jsfiddle.net/dvr4zysc/
I hope someone could help me


text:
Q: Ubuntu 12.04 not recognizing my 4 tb hdd I am using a SSD as the main hard drive and want to use my 4tb hdd as a storage drive. However, I can't find it in Ubuntu. I checked the bios, and it is known.
edit
Disk /dev/sda: 240.1 GB, 240057409536 bytes
255 heads, 63 sectors/track, 29185 cylinders, total 468862128 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00048cf8

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048   435378175   217688064   83  Linux
/dev/sda2       435380222   468860927    16740353    5  Extended
/dev/sda5       435380224   468860927    16740352   82  Linux swap / Solaris

Disk /dev/sdb: 4000.8 GB, 4000787030016 bytes
255 heads, 63 sectors/track, 486401 cylinders, total 7814037168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x00000000

Disk /dev/sdb doesn't contain a valid partition table

Disk /dev/sdc: 8019 MB, 8019509248 bytes
20 heads, 16 sectors/track, 48947 cylinders, total 15663104 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xc3072e18

   Device Boot      Start         End      Blocks   Id  System
/dev/sdc1   *          80    15663103     7831512    c  W95 FAT32 (LBA)

Disk /dev/mapper/cryptswap1: 17.1 GB, 17142120448 bytes
255 heads, 63 sectors/track, 2084 cylinders, total 33480704 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xf3c5ebb4

Disk /dev/mapper/cryptswap1 doesn't contain a valid partition table


text:
Q: How to deal with shared models in micro service architectures My goal is to create an architecture in which services should be able to deploy independent of each other and are completely autonomous, but what do you do when you have 2 services that reads from DB the same object type?
In my case I have a socket server (micro service 1) and a http server (micro service 2). Using the http server my users creates an asset called: A, this asset gets stored on a DB and a mongoID is returned. Then, using another protocol and the ID, there are calls to the socket server that needs to check that validity of that ID, thus, needs to read from DB. This two services will have to share the model of A in order to map it to an object, but this means the 2 services will have to share code, and that's not ok.
Do I need another service? or should I make only service1 able to read from DB and then make the second one talks to service 1?

A: Two microservices should not share same data model. You can create a service which is solely responsible for managing data persistence, and can use it in other services.

A:
... there are calls to the socket server that needs to check that validity of that ID, thus, needs to read from DB. This two services will have to share the model of A in order to map it to an object, ...

Well - no, they do not need to share code! The only thing they actually need, is a common understanding of the schema of the DB (I assume you're using MongoDB). Whether that understanding is coming from shared class definitions in shared libraries or from duplicated class definitions in separate libraries does not really matter. Many developers will now start screaming at me for violating the DRY (Don't repeat yourself) principle, but with microservices many things are different to what we're used to!
In her answer, Priti Singh states that:

Two microservices should not share same data model

which in correct in a microservice context and considered good practice! Let me show you why:
In the microservice pattern, services should be independant of other sevices and have well-defined interfaces. Having two different services reading the same DB makes that DB another "service" (I KNOW, weird, right?!?). By definition this database now needs a well-defined interface - which is kind of difficult in a schemaless DB ;-) Another reason not to make a DB act like a service is, that changes in one service will always have some influence on the other service accessing the data. This means, changing the "schema" on one service might force you to change another service as well, just to keep your system running! That's a headache when you consider a full-blown microservice system with >100 services.
That is why your second idea:

... or should I make only service1 able to read from DB and then make the second one talks to service 1?

is much better. Keep your database hidden behind a service with a well-defined interface that can be versioned. Like this you can refactor inside service 1 as your heart desires without necessarily influencing other services. Once you need to make a breaking change on your interface - give it a new version and start migrating other services to use the new interface.
The underlying controversy in your question is the one of Coupling vs. Duplication. Sharing an interface definition and database is coupling (the wakes-you-up-at-night-after-a-small-change kind of coupling) but duplicating the database schema to both services is duplication. I believe that coupling will kill you long before duplication does, but taking your second approach, having the http-service access the socks-service which then accesses the database should remove duplication as well as reduce coupling!
Let me know if this was helpfull!

A: Microservices help solve the issue of coupling, to achieve that you need to keep your services/components autonomous, which means they can't share anything, not code assemblies or any resources, especially not the database.
If you need a read only copy of the data you can use patterns like publish subscribe to save a local copy of some information your component needs (subscribe to an event like NewUserCreatedEvent: new user was created and his id is this guid for example), there should be only one owner of the user data in the system and the owner is the only one who can modify the state of the data he owns, the rest of the components in the system can keep a local copy of reference data for read only purposes.

this asset gets stored on a DB and a mongoID is returned. Then, using
  another protocol and the ID, there are calls to the socket server that
  needs to check that validity of that ID, thus, needs to read from DB

In your scenario the client that creates the user should provide the id (a guid), the component that owns the user (therefore it's the one that creates it) will publish an event the other component (service) subscribes to and stores the data it needs in it's own database.
Does that make sense?


text:
Q: SPARQL: enumerate result list For simplicity I use wikidata as example: I have a query:
SELECT  ?item ?itemLabel ?mastoadress
WHERE
{
  ?item wdt:P4033 ?mastoadress.
  ?item wdt:P106 wd:Q1930187. # occupation journalist
  ?item wdt:P27 wd:Q183. # country of citizenship germany
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
ORDER BY ?itemLabel

How can I achieve the result list to include a column where each entry gets its own unique integer index.


text:
Q: Look for algorithm/research area that determines facts that would make a Prolog query true given a Prolog program I'm looking for research, algorithms or even terminology for this area of research that take a Prolog program and a query I want to be true and attempt to find the facts that would need to be asserted to make it true.  For example:
% Program
hasProperty(Object, Property) :-
   property(Object, hasProperty, Property).

property(apple, hasProperty, red).
property(car, hasProperty, drivable).

% Magic function that determines what Facts would make
% query 'hasProperty(lemon, sour)' true
% in the program above
?- whatFacts(hasProperty(lemon, sour), Facts).
Facts = [property(lemon, sour)]

I'm sure research has been done on this, and certainly it seems unsolvable in the general case, but I'm curious what has been done but am having trouble finding the right terminology to find the work.
Would love any pointers to actual algorithms or names for the area or problem I'm describing.

A: This is called "abduction".
For the view from philosophical logic, Stanford Encyclopedia of Philosophy offers this entry: Abduction.
For the view from logic programming, Wikipedia offers this entry: Abductive Logic Programming.
A paper that uses Prolog and CHR (Constraint Handling Rules) for Abductive reasoning:
Henning Christiansen: Abductive reasoning in Prolog and CHR (PDF): A short introduction for the KIIS course, Autumn 2005.
Christiansen refers to the book
Abduction and Induction: Essays on their Relation and Integration, edited by Peter A. Flach and Antonis Hadjiantonis (Kluwer Academic Publishers, April 2000), Amazon Link, first chapter at researchgate
and provides this introductory explainer:

Deduction, reasoning within the knowledge we have already, i.e.,from those
facts we know and those rules and regularities of the world that we are
familiar with. E.g., reasoning from causes to effects: If you make a fire
here, you will burn down the house.

In Prolog, the language is structured so as to most naturally find the premise "make a fire here" if your goal happens to be "burn the house down".

Induction, finding general rules from the regularities that we have
experienced in the facts that we know; these rules can be used later for
prediction: Every time I made a fire in my living room, the house burnt
down ... Aha, the next time I make a fire in my living room, the house
will burn down too.

Abduction, reasoning from observed results to the basic facts from which
they follow, quite often it means from an observed effect to produce a
qualified guess for a possible cause: The house burnt down, perhaps my cousin
has made a fire in the living room again.

"Abductive Logic Programming" (ALP) is (used to be?) an active area of research.
Here is a Sprinker Link with search result.
ALP is a common problem in commonsense reasoning and planning. Examples that come to mind:

*

*The CIFF Proof Procedure for
Abductive Logic Programming with Constraints: Theory, Implementation and
Experiments

*Robert Kowalski, Fariba Sadri et al. have worked on "LPS" (Logic Production
System), which uses ALP (but not by name?) in the
context of the event calculus
to decide what actions to take to make facts about the world true (wishing
for more details here, I do hope they are editing a book on this).

*Contrariwise, Raymond Reiter does not use Prolog but
Answer Set Programming
(which may be more adapted to ALP than the SLDNF approach of Prolog) for
(among others) abductive reasoning in the
Situation Calculus.
More on this in the book Knowledge in Action (MIT Press, July 2001).

A: As said in the comments this is called abductive reasoning, a good guide is in simply logical: https://too.simply-logical.space/src/text/3_part_iii/8.0.html


text:
Q: How to list only printers in JavaFX Print Dialog? Is it possible to list only printers in the JavaFX Print Dialog ?
example for use of Print Dialog :
...
final PrinterJob printerJob = PrinterJob.createPrinterJob();
ret = printJob.showPrintDialog(owner);
...

Thank you in advance
Fabrice


text:
Q: How to make div expand only from bottom down I have a div in a modal below. The problem I'm having is when I click on Add Row, this creates another div with a row and expands both top and bottom. The div then goes off the screen after a couple of rows added. Please see screenshots.
Note: the query-row element is an angular directive, so that's why you don't see the template for that (which includes the actual fields and add row button). But that's irrelevant in this case.
HTML

CLOSE

                            <query-row rows="rows" remove-row="removeRow(row)" add-row="addRow()"></query-row>

                            <button ng-click="submit()" class="btn btn-primary">Submit</button>
                            <button ng-click="cancel()" class="btn btn-info">Cancel</button>

CSS
.ng-modal {
    position: fixed;
    z-index: 9999;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
.ng-modal-overlay {
    position: absolute;
    z-index: 9999;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #282828;
    opacity: 0.9;
}
.ng-modal-dialog {
    z-index: 10000;
    position: absolute;
    top: 164px;
    left: 53%;
    width: 800px;
    transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    padding: 10px;
    background-color:#FFF;

}
.ng-modal-dialog-content {
    overflow: hidden;
    height: 100%;
}

.ng-modal-dialog-input {
    margin: 0px;
    padding: 5px;
    font-size: 36px;
    width: 100%;
    border: none;
    background-color: #fff;
    outline: 0;
    color: #000;
    font-weight:700;

}

.ng-modal-close {
    position: absolute;
    top: 15px;
    right: 28px;

}
.ng-modal-close-x {
    font-family: Arial, sans-serif;
    display: inline-block;
    cursor: pointer;
    float: right;
    font-size: 18px;
    color: #fff;
}
.ng-modal-title {
    font-weight: bold;
    font-size: 200%;
    display: block;
    margin-bottom: 10px;
    padding-bottom: 7px;
    border-bottom: solid 1px #999;
}

Plunker Example: http://plnkr.co/edit/RFNsrC
First screenshot is just with one row.
Screenshot 1
The second screenshot is 3 rows added, and you can see how the modal goes off the screen on the top. I want it to remain fixed on top and grow only towards to the bottom Screenshot 2

A: Here is a codepen, The problem is where you are trying create the new row, it's above not below, try putting in a table. http://codepen.io/calendee/pen/buCHf
  Add Row {{counter}}

  Some Header

      {{rowContent}}

And to set the css of the .ng-modal-dialog as follows:
height:900px;
overflow-x: auto;

Let me know if that works :)


text:
Q: Tools for Apache Cordova project build crashes in Visual Studio 2017 I have a copy of Visual Studio 2017 Professional and I downloaded the Tools for Apache Cordova. I created a new blank project, downloaded the JDK/JRE and the Android SDK tools and emulator.
Every time I hit the 'Build' or 'Deploy' button, the build appears to complete, then Visual Studio stalls - and remains this way until the process is terminated via task explorer. There are no other error messages or apparent build failures.
Any ideas why this would happen? I'm totally lost here.


text:
Q: jquery mobile 1.4.2 input type time 24 h mode Is there a way of changing the mode of a input type time in jquery mobile?
I use Jquery mobile 1.4.2
Here is the code:
<label for="time">Time:</label>
<input type="time" data-theme="a" data-clear-btn="true" name="time" id="time" value="">

But as default the input field is in am/pm mode so the behavior in a mobile device it is also in am/pm mode. In Germany we use 24h mode so I want to change the mode if possible. How can I change the mode?
I found the input type="time" here:
http://demos.jquerymobile.com/1.4.2/textinput/

A: Check this fiddle.It shows 24 hour date format.By default there is no date and time in jquery mobile. So you need to add external plugins.
FIDDLE OUTPUT
Your HTML input is like
 <input name="mytime" id="mytime" type="time" data-role="datebox" data-options='{"mode": "timebox", "useNewStyle":true,"overrideTimeFormat": 24}'/>

download the date picker here.
Datepicker download link
Note: If you want to show the time in 24 hr format in input field you need to customize the JQM datepicker plugin. Like in JQM-datebox-core.js you need to set the timeFormat : 24,.
EDIT: In JQM 1.4.2 the document Document link says they are using third party plugin. They referred two plugins one is JQUERY UI and another one is arschmitz JQUERY MOBILE DATEPICKER . In the above example i use that is jquery mobile datepicker same as like second plugin.