text:
Q: c# template method pattern design question I'm currently in a situation where I have multiple derived class types(just one is shown in the example below) that need to apply some logic before and/or after calling a method implemented in a common base class. I have two scenarios below and was wondering what would be a downside and upside for each approach in this use case scenario? The client code will be calling the relevant classes as defined in the main stub. The template method design pattern that is presumably being followed correctly in scenario b seems to be more popular based on research, but from first glance the code for approach a looks to be more minimal.
Thank you.
Scenario A:
using System.IO;
using System;

interface IContract
{
  void Foo();
};

abstract class Base : IContract
{
    protected void FooImpl()
    {
        Console.WriteLine("base work");
    }
    public abstract void Foo();
};

class Derived : Base
{
    public override void Foo()
    {
        Console.WriteLine("pre work derived");
        FooImpl();
        Console.WriteLine("post work derived");
    }
}

class Program
{
    static void Main()
    {
        IContract contract = new Derived();
        contract.Foo();
    }
}

Scenario B:
using System.IO;
using System;

interface IContract
{
  void Foo();
};

abstract class Base : IContract
{
    protected abstract void PreFooHook();
    protected abstract void PostFooHook();

    public void Foo()
    {
        PreFooHook();
        Console.WriteLine("base work");
        PostFooHook();
    }
};

class Derived : Base
{
    protected override void PreFooHook()
    {
        Console.WriteLine("pre work derived");
    }

    protected override void PostFooHook()
    {
        Console.WriteLine("post work derived");
    }
}

class Program
{
    static void Main()
    {
        IContract contract = new Derived();
        contract.Foo();
    }
}

Desired Output:
pre work derived
base work
post work derived

A: In your first scenario, you're not enforcing any sort of behavior on the derived classes. You're counting on them calling FooImpl properly, between the hooks, but if they don't, your whole process can be broken by a misbehaving child class. And consider it from the child class developer, who may be in a different team or even a different company if the base class is part of a public framework: you want to implement a base class, but how do you know what to do? When to call FooImpl, if at all? Read the docs? Flaky, risky.
Scenario B is, IMO, cleaner, safer and easier. Child classes need to explicitly implement the hooks, which will always be called before and after FooImpl. And if you need a completely different FooImpl? Simply implement a completely different IContract.

A:
... in scenario b seems to be more popular ... approach a looks to be more minimal

Neither popularity nor the size of the code is an indicator of its quality. Neither it indicates what approach better suites your particular needs.
In the type A having FooImpl and for the first time using it only in Derived makes no sense. You cannot inforce classes derived directly from Base to use it. Better would be to merge Base and Derived into a single class.
I suppose that you reproduced the cases that you observed not quite correctly. In both cases A and B the template implementation of method Foo should be final. Means, Derived.Foo in the case A and Base.Foo in the case B should both be final. Thus these classes would enforce particular pattern for all their subclasses.
If you declare them as final, you will see that there is not much difference between A and B: The core implementation will be in the Foo, and subclasses will be allowed to modify only some part of it. Both A and B will be then just a specific cases of more generic case:
public abstract class Base : IContract
{
    protected abstract void Hook1();
    protected abstract void Hook2();
    protected abstract void Hook3();

    public final void Foo()
    {
        ... some logic ...
        Hook1();
        ... some logic ...
        Hook2();
        ... some logic ...
        Hook3();
        ... some logic ...
        ...
    }
};

An example of such class can be sending an email. The base class can provide the core logic and subclasses could provide a hook method to determine the sender, another hoos to determine the list of receivers, a hook that provide sbject, a hook that provides message body.
But having too many hook methods makes code harder to understand and to maintain. It may be easier to provide the whole own implementation of method Foo instead of trying to understand the meaning of each hook method. That's why in reality I mainly see really only two types similar to A and B. In case subclasses need to provide the core logic, but some pre- and post-operations need to be enforced, type A is used. In case the core logic is implemented in the base class, but subclasses are allowed to participate on pre- and post-operations, type B is used.


text:
Q: Read after specific text and stop reading when it reaches a empty line and then write it to output file Currently I only can read and write everything from my input file to the output file. But I only want to read the line after book1|book2|book3 and stop reading when it reaches a empty line, after that write to the output file based on what it reads. I have found this code nStr(strLine, sStringToFind), but I don't know if it will work properly here, or how to use it.
My input file

My current output based on my codes

This is the output I want to achieve

 Set objWorkbook = objFSO2.OpenTextFile(inputFilePath)

              Dim strLine
              Dim intLineCounter

              intLineCounter = 0

              Do Until objWorkbook.AtEndOfStream

              strLine = objWorkbook.ReadLine

              objFile.WriteLine(strLine)

              intLineCounter = intLineCounter + 1
              Loop

A: Copy part of input file to output file - top level structure:

*

*Preparations

*Read/Write Loop

*CleanUp

Preparations: open files and setup state variable to indicate writing

*

*Set tsIn = oFS.OpenTextFile(...)

*Set tsOut = oFS.CreateTextFile(...)

*bWrite = False

CleanUp: close the files

*

*tsOut.Close

*tsIn.Close

Read/Write Loop
Do Until tsIn.AtEndOfStream
   sLine = tsIn.ReadLine()
   ... Kernel ...
Loop

Interesting events

*

*sLine = "book1|book2|book3" ==> write from next line on

*sLine = "" after event 1 ==> done

Kernel:
If sLine = "book1|book2|book3" Then
   bWrite = True
Else
   If bWrite Then
      If sLine = "" Then
         Exit Do
      Else
         tsOut.WriteLine sLine
      End If
   End If
End If

Update wrt @Hackoo's answer:
A decent implementation of the above plan:
Option Explicit

Dim oFS    : Set oFS   = CreateObject("Scripting.FileSystemObject")
Dim tsIn   : Set tsIn  = oFS.OpenTextFile("..\data\25301708.txt")
Dim tsOut  : Set tsOut = oFS.CreateTextFile("..\data\25301708-out.txt")
Dim bWrite : bWrite    = False
Dim sLine

Do Until tsIn.AtEndOfStream
   sLine = tsIn.ReadLine()
   If sLine = "book1|book2|book3" Then
      bWrite = True
   Else
      If bWrite Then
         If sLine = "" Then
            Exit Do
         Else
            tsOut.WriteLine sLine
         End If
      End If
   End If
Loop

tsOut.Close
tsIn.Close

A: Try out this code :
Option Explicit
Dim Titre,Data,s,LogFile,ws,fso,Result,Lines,Line
Set fso = CreateObject("Scripting.FileSystemObject")
Set ws = CreateObject("Wscript.Shell")
LogFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "txt"
if fso.FileExists(LogFile) Then
    fso.DeleteFile LogFile
end If
Data = ReadFileText("file.txt")
Result = Between_Ands(Data,"book1|book2|book3","fax1|fax2|fax3")
Lines = Split(Result,vbCrLf)
For Each Line In Lines
    If Len(Line) > 0 Then
        WriteLog Line,LogFile
    end if
Next
ws.Run LogFile,1,False
'**********************************************************************************************
Function Between_Ands(ByVal Full_String, ByVal First_Delimiter, ByVal Second_Delimiter)
    Dim Pos,Pos2
    Pos = InStr(Full_String, First_Delimiter)
    Pos2 = InStr(Full_String, Second_Delimiter)
    If Pos = 0 Or Pos2 = 0 Then
        Between_Ands = "Missing Delimiter"
        Exit Function
    End If
    Between_Ands = Mid(Full_String, Pos + Len(First_Delimiter), Pos2 - (Pos + Len(First_Delimiter)))
End Function
'***********************************************************************************************
Function ReadFileText(sFile)
    Dim objFSO,oTS,sText
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    If Not objFSO.FileExists(sFile) Then
        MsgBox "CRITICAL ERROR " & VbCrLF & "The File "& DblQuote(sFile) & " dosen't exists !",VbCritical,"CRITICAL ERROR"
        Wscript.Quit
    Else
        Set oTS = objFSO.OpenTextFile(sFile)
        sText = oTS.ReadAll
        oTS.close
        set oTS = nothing
        Set objFSO = nothing
        ReadFileText = sText
    End if
End Function
'***********************************************************************************************
Sub WriteLog(strText,LogFile)
    Dim fs,ts
    Const ForAppending = 8
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set ts = fs.OpenTextFile(LogFile,ForAppending,True)
    ts.WriteLine strText
    ts.Close
End Sub
'************************************************************************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************

With the solution proposed by Ekkehard.Horner
You have to do like this :
Option Explicit
Dim Titre,Data,s,LogFile,ws,fso,Result,Lines,Line,bWrite
Set fso = CreateObject("Scripting.FileSystemObject")
Set ws = CreateObject("Wscript.Shell")
bWrite = False
LogFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "txt"
if fso.FileExists(LogFile) Then
    fso.DeleteFile LogFile
end If
Data = ReadFileText("file.txt")
Lines = Split(Data,vbCrLf)
For Each Line In Lines
    If Line = "book1|book2|book3" Then
        bWrite = True
    Else
        If bWrite Then
            If Line = "" Then
                Exit For
            Else
                WriteLog Line,LogFile
            End If
        End if
    End if
Next
ws.Run LogFile,1,False
'***********************************************************************************************
    Function ReadFileText(sFile)
        Dim objFSO,oTS,sText
        Set objFSO = CreateObject("Scripting.FileSystemObject")
        If Not objFSO.FileExists(sFile) Then
            MsgBox "CRITICAL ERROR " & VbCrLF & "The File "& DblQuote(sFile) & " dosen't exists !",VbCritical,"CRITICAL ERROR"
            Wscript.Quit
        Else
            Set oTS = objFSO.OpenTextFile(sFile)
            sText = oTS.ReadAll
            oTS.close
            set oTS = nothing
            Set objFSO = nothing
            ReadFileText = sText
        End if
    End Function
'***********************************************************************************************
    Sub WriteLog(strText,LogFile)
        Dim fs,ts
        Const ForAppending = 8
        Set fs = CreateObject("Scripting.FileSystemObject")
        Set ts = fs.OpenTextFile(LogFile,ForAppending,True)
        ts.WriteLine strText
        ts.Close
    End Sub
'************************************************************************************************
    Function DblQuote(Str)
        DblQuote = Chr(34) & Str & Chr(34)
    End Function
'**********************************************************************************************

A: I found myself needing a similar script tonight. Instr acts like boolean when just searching for a string, even though it technically gives you the position of the match (in the other string you're searching). I find it a little more flexible too (than doing a straight comparison with equals). Else If consolidates the main logic:
Const ForReading = 1, ForWriting = 2, ForAppending = 8

strInFile = "inFile.txt" 'Put a full path if you want
strOutFile = "outFile.txt"

Set objFS = CreateObject("Scripting.FileSystemObject")
Set objInFile = objFS.OpenTextFile(strInFile, ForReading)
Set objOutFile = objFS.OpenTextFile(strOutFile, ForWriting, True)
writeNow = false

Do Until objInFile.AtEndOfStream
   sReadLine = objInFile.ReadLine()

    If instr(sReadLine, "book1|book2|book3") Then
        writeNow = true                'We exit the if statement here ready to write on the next loop
    ElseIf (writeNow AND Trim(sReadLine) = "") Then
        Exit Do                        'We exit the loop, finished writing
    ElseIf writeNow Then
        objOutFile.WriteLine sReadLine 'Otherwise, we write
    End If
Loop

objOutFile.Close
objInFile.Close

Long live VBScript!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding row inside a row in repeat.? I am adding a row inside a row..Here is the scenario. On Click of add button i am adding a row.i know how to do that..I am able to do that.Now i want to add more rows inside that row using some different button i.e i have adding a row by clicking on main add row button.now i also have a different section inside that row where i can further add rows.
<apex:repeat value="{!wrapperList}" var="wra">
 <apex:pageBlock title="Consolidated Feed">
    <apex:pageBlockSection >

                <apex:inputField value="{!wra.conFeed.CPF_Quantity__c}"/>

   </apex:pageBlockSection>
  </apex:pageBlock>

     <apex:pageBlock title="test">

      <apex:commandButton action="{!addRowHex}" value="Add new section inside" reRender="hexSec" />
     <apex:pageBlockSection >

               <apex:repeat value="{!wra.excEnti}" var="wrEx">
                 <apex:inputField value="{!wrEx.Name}"/>
                 <apex:inputField value="{!wrEx.Hex_Code__c}"/>
              </apex:repeat>
     </apex:pageBlockSection>
     </apex:pageBlock>
</apex:repeat>

wrapper class
public object1 conFeed{get;set;}
 public List<object2> excEnti{get;set;}
  public Integer counterWrap{get;set;}

 public wrapperClass(object1 conFeed,List<object2> excEnti)
 {
     this.conFeed=conFeed;
     this.excEnti=excEnti;
 }
 }

public void addRow(){

       wrapperClass actWrap = new wrapperClass(new object1(),new List<object2>());
        counter++;
        actWrap.counterWrap = counter;
        wrapperList.add(actWrap);

 }

 **public void addRowHex()
 {

 **//I dont know what to write here.//Please help.How to add a row inside of the first row added**

 }**

A: The below example should get you started on what you want to achieve. You can try it out separately as it uses the standard Account and Contact objects.
Page:
<apex:page controller="NestedTableLogicClass">
<apex:form >
<apex:commandButton value="Add Outer" action="{!addOuter}" rerender="panel"/>

<apex:outputPanel id="panel">

     <apex:repeat value="{!myWrapperObject}" var="key">

        <apex:inputField value="{!myWrapperObject[key].objectVar.Name}" />
        <apex:commandButton value="Add Inner Row" action="{!addInnerRow}" rerender="panel">
            <apex:param value="{!key}" name="row" assignTo="{!row}"/>
            </apex:commandButton>

              <apex:repeat value="{!myWrapperObject[key].innerList}" var="innerListVar">

                  <apex:inputField value="{!innerListVar.lastName}" />

              </apex:repeat>

     </apex:repeat>

</apex:outputPanel>
</apex:form>
</apex:page>

Controller:
public class NestedTableLogicClass{

  public Map<Integer,WrapperClass> myWrapperObject{get; set;}
  public Integer counter {get; set;}

  public Integer row {get; set;}

  public class WrapperClass{

    public List<Contact> innerList {get; set;}
    public Account objectVar{get; set;}

    public WrapperClass(){
      this.innerList = new List<Contact>();
      this.objectVar = new Account();
    }
  }

  public NestedTableLogicClass(){
    counter = 0;
    myWrapperObject = new Map<Integer,WrapperClass>();

    /* Adding one outer row on page load*/
    addOuter();

  }

  public void addOuter(){
    counter++;
    myWrapperObject.put(counter,new WrapperClass());

    /* Add one inner row everytime an outer row is created */
    row = counter;
    addInnerRow();
  }

  public void addInnerRow(){
    myWrapperObject.get(row).innerList.add(new Contact());

  }
}


text:
Q: Cannot see finished job in Spark web UI I am using ./bin/spark-submit to run my Spark job. It runs fine but opening Spark web UI, I cannot see job in completed list.
./bin/spark-submit --name "myapp" --master local --conf "spark.master=spark://fahad:7077" --class com.apptest.App ~/app-0.0.1-SNAPSHOT.jar

Note: Spark version 2.0.1, 1 worker running, master UI at localhost:8080 both worker and master ran from ./sbin/start-*.sh scripts.

A: There are two different UI's, the regular Spark UI, and the Spark History Server.
The one that shows jobs after they complete is the history server.
http://spark.apache.org/docs/latest/monitoring.html
They explain in the docs that you need to start it by running:
./sbin/start-history-server.sh

This creates a web interface at http://server-url:18080 by default,
  listing incomplete and completed applications and attempts.
When using the file-system provider class (see spark.history.provider
  below), the base logging directory must be supplied in the
  spark.history.fs.logDirectory configuration option, and should contain
  sub-directories that each represents an application's event logs.
The spark jobs themselves must be configured to log events, and to log
  them to the same shared, writeable directory. For example, if the
  server was configured with a log directory of
  hdfs://namenode/shared/spark-logs, then the client-side options would
  be:
spark.eventLog.enabled true spark.eventLog.dir
  hdfs://namenode/shared/spark-logs


text:
Q: Retrieve Alerts using the legacy REST API Using the legacy REST API I was able to retrieve alerts following the documentation using Postman. (https://automation.deepsecurity.trendmicro.com/legacy-rest/20_0/index.html?env=onprem#list_alert_types)
But since 1 week I can't retrieve those informations anymore by using the same parameters used before.
Here is what I do :

*

*Authenticating using valid user (https://SERVER_IP:PORT/rest/authentication/login)

*Trying to retrieve alerts using the sID given after authenticating (https://SERVER_IP:PORT/rest/alerts)
I don't understand why I can't retrieve those informations anymore since before I was able to do it.
Here is the configuration and the version
Any idea on what I'm missing ?


text:
Q: Flex 4 - What makes a GC root? What are the rules for something to be a GC root in Flash?
I'm using the Flash Builder 4 profiler, and I'm finding odd things are labeled as GC roots in the object reference details (e.g., an Image control that is no longer in the display list, nor static).

A: This discussion might be helpful.
http://tech.groups.yahoo.com/group/flexcoders/message/144288
Apparently there is some depth from the root at which the profiler just stops displaying the rest of the chain and labels the object as a GC root even though there is more chain above it.


text:
Q: How to pack a C# 9 source generator and upload it to the Nuget? I made a C# 9 source code generator, you can find it here
When I use the whole project inside another solution and reference it as a project it works but when I upload it with current configs into the Nuget (here) it does not work.
How to config a C# 9 source generator correctly to work as a Nuget package? What is wrong with my project?
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <Version>0.0.2</Version>
    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
    <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
    <PackageLicenseExpression>MIT</PackageLicenseExpression>
    <PackageTags>dotnet</PackageTags>
    <PublishRepositoryUrl>true</PublishRepositoryUrl>
    <GenerateRepositoryUrlAttribute>true</GenerateRepositoryUrlAttribute>
    <PackBuildOutput>true</PackBuildOutput>
    <PackageId>MockableStaticGenerator</PackageId>
    <PackOnBuild>true</PackOnBuild>
    <PackFolder>analyzers\cs</PackFolder>
    <DebugType>embedded</DebugType>
    <DebugSymbols>true</DebugSymbols>
  </PropertyGroup>
  <PropertyGroup>
    <RestoreAdditionalProjectSources>https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5/nuget/v3/index.json ;$(RestoreAdditionalProjectSources)</RestoreAdditionalProjectSources>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.8.0" PrivateAssets="all" />
    <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>
</Project>

A: Yair's answer covers this well. I wanted to add a debugging tip that is hopefully helpful.
If you're using an SDK-style project to specify your package, then after packing it you can find the generated .nuspec file in the obj folder. Reviewing the contents of that file can be very helpful when understanding what the consumer of your package will actually have available to them.

A: If you unzip the nuget package, you'll see that the package is stored in the lib directory. It has to be stored in the analyzers directory.
One way to do that is to add the following to your csproj:
<ItemGroup>
  <None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
</ItemGroup>

If you're multitargeting it should be:
<ItemGroup>
  <None Include="$(OutputPath)\netstandard2.0\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
</ItemGroup>

This will include your project as both a library and an analyzer.
To use it just as an analyzer, add the following:
<PropertyGroup>
  <IncludeBuildOutput>false</IncludeBuildOutput>
</PropertyGroup>


text:
Q: Concatenate two list of different type I have two Lists List<int> and List<SharedCroList>.
 public class SharedCroList
    {
        public int CRO1Id { get; set; }
        public int CRO2Id { get; set; }
    }

  List<int> _cro1ReceiptEmpId = _receiptList
                                .Where(r => r.StudentRegistration.StudentWalkInn.CROCount == 1)
                                .Select(r => r.StudentRegistration.StudentWalkInn.Employee1.Id)
                                 .ToList();

//if walkinn is shared one
List<SharedCroList> _cro2ReceiptEmpId = _receiptList
                                       .Where(r =>  r.StudentRegistration.StudentWalkInn.CROCount == 2)
                                       .Select(r => new SharedCroList
                                           {
                                               CRO1Id=r.StudentRegistration.StudentWalkInn.Employee1.Id,
                                               CRO2Id=r.StudentRegistration.StudentWalkInn.Employee2.Id
                                           })
                                           .ToList();

My aim is to concatenate these two lists into one.How can I do that?
I have tried the concatenate method but its not working??

A: you cannot concat 2 list with 2 different type.
so you'd better to convert your first list (_cro1ReceiptEmpId) to second one , and use AddRange() to concat.
for example :
List <SharedCroList> temp = _cro1ReceiptEmpId.Select(x => new SharedCroList { CRO1Id = x, CRO2Id = 0 }).ToList();

List<SharedCroList> ConcatinatedList = _cro1ReceiptEmpId.AddRange(_cro2ReceiptEmpId);

Edit :
if you want your output become List so you need to convert your second list to 2 separate List<int> :
List<int> listOfCRO1Id = _cro2ReceiptEmpId.Select(x=>x.CRO1Id).ToList();
List<int> listOfCRO2Id = _cro2ReceiptEmpId.Select(x=>x.CRO2Id).ToList();

List<int> FinalList = listOfCRO1Id.Concat(listOfCRO2Id).Concat(_cro1ReceiptEmpId).ToList();


text:
Q: Trying to learn recursive functions, but can't wrap my head round it I'm trying to learn how to use recursive functions, but am not understanding what is happening at all.
function power(base, exponent) {
    return base * power(base, exponent - 1);
};

alert(power(4,4));

I'm getting:

RangeError: Maximum call stack size exceeded.

From the example that I'm going off of, it has:
function power(base, exponent) {
  if (exponent == 0)
    return 1;
  else
    return base * power(base, exponent - 1);
}

alert(power(4,4));

Could someone explain to me why the if statement is needed? I suspect that I'm missing something.

A: A recursive function calls itself. That's the definition of it.
This brings a problem: it will indefinitely call itself. So it will go forever which is why you're getting stack overflows.
Instead, you should stop at a certain point. This is where the if clause comes in. When exponent == 0, you don't call the function, but stop the process.
So when executing power(3, 3) it will go like:
   power(3, 3) is equal to:

   3 * power(3, 2)
or 3 * 3 * power(3, 1)
or 3 * 3 * 3 * power(3, 0)
or 3 * 3 * 3 * 1            // no additional calls anymore; can be calculated now

Seen from a little different angle:

*

*power(4, 4) is defined as  4 * power(4, 3) by the function.

*power(4, 3) is defined as  4 * power(4, 2) by the function.

*power(4, 2) is defined as  4 * power(4, 1) by the function.

*power(4, 1) is defined as  4 * power(4, 0) by the function.

*power(4, 0) is defined as  1 by the function.

If you substitute everything into each previous one, you'll obtain:
                         power(4, 4)
equals               4 * power(4, 3)
equals           4 * 4 * power(4, 2)
equals       4 * 4 * 4 * power(4, 1)
equals   4 * 4 * 4 * 4 * power(4, 0)
equals   4 * 4 * 4 * 4 *      1
equals   256

A: You need a base case in recursion so that it stops calling itself. In this case, the power function is called forever (well, until the javascript interpreter gives up) as the exponent goes to negative infinity.

A: A recursive function calls itself. So you need some mechanism to tell it to stop or you will be in an infinite loop. In your case you always return and provide no means for exiting the loop. Hence the RangeError.

A: Notice that the function is calling itself. In your first example, the function calls itself, and then the newly called function calls itself and so on. Internally, your computer is storing these function calls in a memory structure called a stack. When there is no more memory for storing function calls, you have exceeded the call stack size.
In the second example, you have a way of escaping this vicious circle. The base case lets the function return, and so you "pop" the method calls off the stack.
Note that in your second example, you can start with alert(power(4, -1)) and you will again experience the same problem, because now your function will subtract one from -1, giving you -2, and so on. You could fortify the code by using
if (exponent <= 0 )

... instead.

A: You have to give it some corner conditions because otherwise it will keep calling itself over and over. Because stack size is limited, it will reach end of stack memory, and then an error will be thrown.

A: Recursion is actually calling function within its own function body again & again until you get your desired result.
public int FactorialOfNumber(int k) {

    if (k==1)
        return 1;
    else
        return k * FactorialOfNumber(k-1);  //Function called within Function.
}

What happens that Recursion uses stack to operate?
Suppose if k=1, returns 1.
If k=4, control goes to else, returns (4*FactorialOfNumber(3)). since you doesn't know , FactorialOfNumber(3). it stores at top of stack.
now, k=3, control goes to else, it returns (3*FactorialOfNumber(2)). nw this goes to top of stack.
now k=2, returns (2*FactorialOfNumber(1)), top of stack.
Finally it calls i.e pops from stack, finally (4*FactorialOfNumber(3)) is called.
If a recursive method never reaches a base case, The stack will never stop growing. The computer, however, limits the stack to a particular height, so that no program eats up too much memory. If a program's stack exceeds this size, the computer initiates an exception, which typically would crash the program. The exception is labeled a StackOverflowError.

A: The if creates a check to stop the recursion when the exponent reaches zero. Without it, it will continue with negative values and never stops.


text:
Q: Ubuntu 13.04 - When maximized, Window title blocks the maximize, minimize, and close buttons You can access the menu bar when you bring your cursor up to the top (as in the first image), but when I move it over to the X button to close the program or the maximize or minimize buttons, the title blocks it (in the second image). Is there any way to stop this from happening?

A: This shouldn't happen. It looks like a bug, the buttons stay visible when I'm hovering them. Do they re-appear if you hover out of the title bar and come back over the buttons?
Maybe you should open a bug for Unity on Launchpad.
Edit: Another possibility is that the window is not really maximised, and your title bar goes in fact behind the Unity panel, but it doesn't seem to be the fact here (you have the "un-maximize" icon, not the "maximize" one).


text:
Q: Python struct.pack() not working in script I have some problems here when I try to use struct.pack from a script. Everything is fine in the interpreter:
>>> import struct
>>> k=2
>>> struct.pack(">b", k)
'\x02'

Now when I do the same from a script I have problems:
k=2
p =  struct.pack(">b", k)
print "p is %s"%(p,)
return p

Result:
p is

what am I doing wrong? I really don't understand this and would be glad if somebody could help me. Thanks

A: Everything is fine. The character is unprintable.
print "p is %r" % (p,)

A: In the interpreter it is displaying the repr of that char and it is interpreting it when you do a print. So you can just do repr(p) in your script if you want to have same result as the interpreter.

A: You are actually printing character '\x02' which is not visible. Try printing it's representation instead.
print "p is %r"%(p,)


text:
Q: synapse spark notebook strange errors reading from ADLS Gen 2 and writing to another ADLS Gen 2 both using private endpoints and TokenLibrary The premise is simple two ADLS Gen 2 accounts. Accessing both as abfss://

*

*Source account with directory format yyyy/mm/dd records stored as jsonl format.

*I need to read this account recursively starting at any directory.

*Transform the data.

*Write the data to the target account in parquet with format Year=yyyy/Month=mm/Day=dd.

*The source account is an ADLS Gen 2 account with private endpoints that is not a part of Synapse Analytics.

*The target account is the default ADLS Gen 2 for Azure Synapse Analytics.

*Using Spark notebook within Synapse Analytics with managed virtual network.

*Source storage account has private endpoints.

*Code written in pyspark.

*Using linked services for both ADLS Gen 2 accounts setup with private endpoints.

from pyspark.sql.functions import col, substring

spark.conf.set("spark.storage.synapse.linkedServiceName", psourceLinkedServiceName)
spark.conf.set("fs.azure.account.auth.type", "SAS")
spark.conf.set("fs.azure.sas.token.provider.type", "com.microsoft.azure.synapse.tokenlibrary.LinkedServiceBasedSASProvider")

#read the data into a data frame
df = spark.read.option("recursiveFileLookup","true").schema(inputSchema).json(sourceFile)

#perform the transformations to flatten this structure
#create the partition columns for delta lake

dfDelta = df.withColumn('ProductSold_OrganizationId',col('ProductSold.OrganizationId'))\
.withColumn('ProductSold_ProductCategory',col('ProductSold.ProductCategory'))\
.withColumn('ProductSold_ProductId',col('ProductSold.ProductId'))\
.withColumn('ProductSold_ProductLocale',col('ProductSold.ProductLocale'))\
.withColumn('ProductSold_ProductName',col('ProductSold.ProductName'))\
.withColumn('ProductSold_ProductType',col('ProductSold.ProductType'))\
.withColumn('Year',substring(col('CreateDate'),1,4))\
.withColumn('Month',substring(col('CreateDate'),6,2))\
.withColumn('Day',substring(col('CreateDate'),9,2))\
.drop('ProductSold')

#dfDelta.show()

spark.conf.set("spark.storage.synapse.linkedServiceName", psinkLinkedServiceName)
spark.conf.set("fs.azure.account.auth.type", "SAS")
spark.conf.set("fs.azure.sas.token.provider.type", "com.microsoft.azure.synapse.tokenlibrary.LinkedServiceBasedSASProvider")

dfDelta.write.partitionBy("Year","Month","Day").mode('append').format("parquet").save(targetFile) ;

when trying to access a single file you get the error message
Caused by: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 4 times, most recent failure: Lost task 0.3 in stage 0.0 (TID 3) (vm-19231616 executor 2): java.nio.file.AccessDeniedException: Operation failed: "Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.", 403, HEAD,

The error indicates that it cannot authenticate to the source file.  However
Here is where it gets strange.
I uncomment the line
#dfDelta.show()

And it works.
However, if you put the comment back and run it again it continues to work.  The only way to  see the failure again is to totally stop the spark session and then restart it.
Ok more strangeness
change the sourcefile path so that its something like 2022/06 which should read multiple files and regardless of if the dfDelta.show() statement is uncommented you get the same error.
The only method I have found to get this to work is to process one file at a time within the spark notebook.  option("recursiveFileLookup","true") only works when there is one file that is processed.
Finally what have I tried.
I have tried creating another spark session.
Spark session 1 reads the data and puts into a view.
Spark session 2 reads the data in the view and and attempts to write it.
The configuration for spark session two uses the token library for the sink file.
Results in the same error message.
My best guess - this has something to do with the spark cores processing multiple files and when I change the config they get confused as to how to read from the source file.
I had this working perfectly before I changed the Synapse Analytics account to use a managed virtual network. But in that case I accessed the source storage account using a managed identity linked service and had not issues writing to the default Synapse Analytics ADLS Gen 2 account.
Also tried option("forwardSparkAzureStorageCredentials", "true") on both the read and write dataframes
Any suggestions on how to get this to work with multiple files would be appreciated.


text:
Q: Complex Django model query I have the following model:
class Vote(models.Model):
    voter = models.ForeignKey(User)
    target = model.ForeignKey(User)
    timestamp = models.DateTimeField()
    game = models.ForeignKey(Game)
    step = model.IntegerField()
    type = models.ForeignKey(VoteType)

I need to select the most voted target and in case of ties select the target who got the earliest vote. Is it possible using Django ORM?
UPDATE: Actually I have also three more field inside Vote: game, turn and type (I added them to the code above), I need to select the winner according to the previous constraint given a particular game, turn and type (i.e. something like .filter(game=1, step=2, type=3))

A: You can use annotation to select the vote count and the earliest vote time for each user, and then order by the annotated fields and select the first:
from django.db.models import Count, Min

winner = User.objects.annotate(vote_count=Count('vote_set'))\
    .annotate(first_vote_time=Min('vote_set__timestamp'))\
    .order_by('-vote_count', 'first_vote_time')[0]

UPDATE:
You can apply the following filter to count only the votes for a specific game:
.filter(vote_set__game=game, vote_set__step=step, vote_set__type=type)

The double underscore allows you to filter on attributes of related objects.
Be sure to apply the filter before the annotations, so that only the correct votes will be counted, and be sure that all filter conditions for the votes are within the same filter call. Why you have to do the latter is explained here.


text:
Q: JavaFX: what is the proper way to inject a service in a controller of a simple desktop application? I'm writing a simple desktop JavaFX application, which has a service to retrieve Person objects:
import model.entities.Person;

public class PersonService {

    public List<Person> findAll() {
        (...)
    }
}

Then I'm writing a JavaFX controller which depends on PersonService, and I'd like to implement a simple dependency injection mechanism to make things decoupled:
import model.services.PersonService;

public class PersonDetailsController {

    private PersonService personService;

    public PersonDetailsController(PersonService personService) {
        this.personService = personService;
    }

    (...)

However, as the JavaFX application doesn't need me to explicitly instantiate the controllers, I don't know how I could provide a PersonService instance to my PersonDetailsController. So what is the proper way to inject a service instance to my desktop JavaFX application?


text:
Q: how to grep .txt .tar.gz .py file once i can use
ls|grep \.py$

to list all ends with .py file,but it's seems hard for me to grep all .py & .txt & .tar.gz file once
any one could give me a hand

A: ls | grep -E '\.(py|txt|tar\.gz)$'

A: No need external commands. Use the shell(bash/ksh)
shopt -s nullglob
for file in *.{txt,tar,gz,py}
do
  echo "$file"
done


text:
Q: Copy data from DynamoDB into Redshift across two different AWS accounts? For reasons beyond my control, I have the following:

*

*A table CustomerPhoneNumber in DynamoDB under one AWS account.

*A Redshift cluster under a different AWS account (same geographic region; EU)

Is there any way to run the COPY command to move data from Dynamo into Redshift across accounts?
Typically if they were under the same account, it would be done via IAM role pretty easily:
copy public.my_table (col1, col2, col3) from 'dynamodb://CustomerPhoneNumber' iam_role 'arn:aws:iam::XXXXXXXXXXX:role/RandomRoleName' readratio 40;

But obviously this doesn't work in my case.
Any ideas?

A: Answer above by John is not applicable any more; This is how you can do it-

*

*AWS account with required resource like dynamodb in this case(trustING account) need to have account requiring access(trusTED AWS account)... as trusted in their Dynamo db read only role: arn:aws:iam:::role/

*Create a policy which does sts:AssumeRole (above trustING account's role arn as the resource),

*attach that policy to redshift-access-role(which has all privileges required to run the copy command).

*Run the command as:
iam_role 'arn:aws:iam::<trusTEDawsAccountId>:role/redshift_access_role,arn:aws:iam::<trusTINGawsAccountId>:role/<dynamodbreadrole>'
readratio 50

Details in:
https://docs.aws.amazon.com/redshift/latest/mgmt/authorizing-redshift-service.html

A: You can use CREDENTIALS and specify the access key and secret key for the other account. Add the following to your COPY statement:
credentials 'aws_access_key_id=AKIAXXXXX;aws_secret_access_key=yyyyyy'

You cannot use cross account roles with Redshift. To quote Amazon documentation:

An IAM role can be associated with an Amazon Redshift cluster only if
  both the IAM role and the cluster are owned by the same AWS account.

Authorizing COPY and UNLOAD Operations Using IAM Roles

A: apparently stackoverflow need formatting, the code is:
copy redshift_tbl from 'dynamodb://dynamotbl'
iam_role 'arn:aws:iam::<TRUSTEDacAWSid>:role/redshift_access_role,arn:aws:iam::<trusTINGacAWSid>:role/<dynamodb-role-in-trustingac>'
readratio 50

*Note: no space between commas in roles


text:
Q: Assigning strings to a struct member (pointer) in C I need to be able to fill out my my_s1 structure with data. I am passing it to a get_data() function that should do all the dirty work. The problem I have is the b member of my structure which is a pointer. I have no idea how to properly assign value pointed by (char *) buff to b without segmentation faults or valgrind errors.
For example:

*

*Why does initial p1->b="abc"; works fine, but if i try to strcpy() or assign through "=" operator an array to p1->b i get errors?

*Does s1 my_s1 allocate memory for b or should I somehow malloc() p1->b myself? But then again i need to free() it and assign a NULL pointer before returning from the function, which defeats the purpose (of having the function assigning data to structure), right?

*With current code listed below I have "proper execution result" but I also get the following valgrind output errors (from what I understand, please correct me if I'm wrong, it seems as if printf() accesses not properly allocated memory - so it works in this case but it's rubbish) :
valgrind:
==1067== Memcheck, a memory error detector
==1067== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==1067== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==1067== Command: ./if
==1067== Parent PID: 1059
==1067==
==1067== Invalid read of size 1
==1067==    at 0x4E7ADF9: vfprintf (in /usr/lib64/libc-2.17.so)
==1067==    by 0x4E83E38: printf (in /usr/lib64/libc-2.17.so)
==1067==    by 0x4005EF: main (iface.c:10)
==1067==  Address 0x51f3040 is 0 bytes inside a block of size 5 free'd
==1067==    at 0x4C294C4: free (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-
linux.so)
==1067==    by 0x40064D: get_data (ifacelib.c:17)
==1067==    by 0x4005D3: main (iface.c:8)
==1067==
==1067== Invalid read of size 1
==1067==    at 0x4EA9459: _IO_file_xsputn@@GLIBC_2.2.5 (in /usr/lib64/libc-2.17.
so)
==1067==    by 0x4E7ADB1: vfprintf (in /usr/lib64/libc-2.17.so)
==1067==    by 0x4E83E38: printf (in /usr/lib64/libc-2.17.so)
==1067==    by 0x4005EF: main (iface.c:10)
==1067==  Address 0x51f3043 is 3 bytes inside a block of size 5 free'd
==1067==    at 0x4C294C4: free (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-
linux.so)
==1067==    by 0x40064D: get_data (ifacelib.c:17)
==1067==    by 0x4005D3: main (iface.c:8)
==1067==
==1067== Invalid read of size 1
==1067==    at 0x4EA946C: _IO_file_xsputn@@GLIBC_2.2.5 (in /usr/lib64/libc-2.17.
so)
==1067==    by 0x4E7ADB1: vfprintf (in /usr/lib64/libc-2.17.so)
==1067==    by 0x4E83E38: printf (in /usr/lib64/libc-2.17.so)
==1067==    by 0x4005EF: main (iface.c:10)
==1067==  Address 0x51f3042 is 2 bytes inside a block of size 5 free'd
==1067==    at 0x4C294C4: free (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-
linux.so)
==1067==    by 0x40064D: get_data (ifacelib.c:17)
==1067==    by 0x4005D3: main (iface.c:8)
==1067==
==1067== Invalid read of size 4
==1067==    at 0x4EBBDDE: __GI_mempcpy (in /usr/lib64/libc-2.17.so)
==1067==    by 0x4EA939C: _IO_file_xsputn@@GLIBC_2.2.5 (in /usr/lib64/libc-2.17.
so)
==1067==    by 0x4E7ADB1: vfprintf (in /usr/lib64/libc-2.17.so)
==1067==    by 0x4E83E38: printf (in /usr/lib64/libc-2.17.so)
==1067==    by 0x4005EF: main (iface.c:10)
==1067==  Address 0x51f3040 is 0 bytes inside a block of size 5 free'd
==1067==    at 0x4C294C4: free (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-
linux.so)
==1067==    by 0x40064D: get_data (ifacelib.c:17)
==1067==    by 0x4005D3: main (iface.c:8)
==1067==
==1067==
==1067== HEAP SUMMARY:
==1067==     in use at exit: 0 bytes in 0 blocks
==1067==   total heap usage: 1 allocs, 1 frees, 5 bytes allocated
==1067==
==1067== All heap blocks were freed -- no leaks are possible
==1067==
==1067== For counts of detected and suppressed errors, rerun with: -v
==1067== ERROR SUMMARY: 10 errors from 4 contexts (suppressed: 2 from 2)

Code in 3 files.
ifacelib.h:
#ifndef IFACELIB_H
#define IFACELIB_H

typedef struct
{
    int a;
    char * b;
} s1;

int get_data(s1 *);

#endif

ifacelib.c:
#include "ifacelib.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int get_data(s1 *p1)
{
    char *buff;
    p1->a=1;
    p1->b="abc";

    buff = (char *) malloc(strlen("test")*sizeof(char)+1);
    strcpy(buff, "test");

    p1->b = buff;

    free(buff);
    buff = NULL;

    return 0;
}

iface.c:
#include "ifacelib.h"
#include <stdio.h>

int main()
{
    s1 my_s1;

    if ((get_data(&my_s1))==0)
    {
        printf("a= %d\tb= %s\n", my_s1.a, my_s1.b);
    }

    return 0;
}

Any help or just pointing in a right direction would be appreciated.
From best practices point of view, when working with structures should I be writing a function that fills out data in structure (works on a passed structure) and returns int to control successes/fails or should I be writing a function that returns a modified structure instead ?
This is my first post here, so please bear with me, my formatting mistakes, walls of text and my ignorance.
Thanks in advance,
Tom

A: You are doing wrong, and just lucky to get correct result, in fact you are accessing memory that just being freed.
It's right that you have to malloc for the char* in struct(by the way, you can use strdup), but you need another destructor to free the struct when their job are done.
In your case, you need a function like free_s1 after the printf, rather than free in constructor function(get_data).

A: This works in C, not so good in C++:
If you are going to malloc(), it may be better to malloc both your structure and the data area in one blow. Rather than having a pointer arrange a minimal data area at the end of the struct. When allocating the struct add additional bytes to allow for the data. You are then good to go. One free will release both struct and data.
Reworking fragments of your code to show the key idea I get the following. I leave compiling, debugging, even syntax checking, for the student.
typedef struct
{
    int a;
    char * b;
    char   data[1];    // data goes here.
                       // structure MUST be malloced at run time WITH
                       //  extra storage for data.
} s1;

    s1   *p1;
    data = "test";
    data_len = strlen(data);       // additional bytes of storage
    p1 = malloc( data_len + sizeof( *p1 ) );  // allocate structure + data
    strcpy(s1->data, data );        // copy data to buffer

    ...
    free(p1);        // free storage


text:
Q: Is there a more efficient way to build a sorted hash from a collection of Ruby objects? I'm building a sorted hash for use in a grouped select in a rails app. I am not using ActiveRecord. Is there a more efficient or cleaner way than this?
def for_select
  select_list = {}
  Department.all.each do |dept|
    select_list[dept.top_level_department_cn] ||= []
    select_list[dept.top_level_department_cn] << [dept.cn, dept.sorid]
  end
  select_list.each_value { |select_options| select_options.sort_by!(&:first) }
             .sort
             .to_h
end

A: def for_select
  Department.all
  .sort
  .group_by(&:top_level_department_cn)
  .each_value{|v| v.map!{|dept| [dept.cn, dept.sorid]}.sort_by!(&:first)}
end

A: Another solution:
def for_select
  # @see: https://stackoverflow.com/questions/2698460#answer-28916684
  select_list = Hash.new { |h, k| h[k] = [] }

  Department.all
    .map { |d| [d.top_level_department_cn, [d.cn, d.sorid]] }
    .sort
    .each { |top_level_cn, data| select_list[top_level_cn] << data }

  select_list
end


text:
Q: Mega Menu in shiny R Problems with mega menu shiny R.
I'm trying to make a navbar with a mega menu, however when running the app it doesn't seem to work in shiny, however, putting the homologous code in html does work.
The image shown below is how the menu should look, the image is what the html code returns.
I also attach the code in HTML.
I don't know what I could be doing wrong, I would appreciate any guidance.

The code I have is below:
library(shiny)

ui <- fluidPage(

  tags$head(

    tags$link(
      rel="stylesheet",
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
    ),

    tags$style(

      '
* {
  box-sizing: border-box;
}

body {
  margin: 0;
}

.navbar {
  overflow: hidden;
  font-family: Arial, Helvetica, sans-serif;
}

.navbar a {
  float: left;
  font-size: 16px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.dropdown {
  float: right;
  overflow: hidden;
}

.dropdown .dropbtn {
  font-size: 16px;
  border: none;
  outline: none;
  color: #13347b;
  padding: 24px 16px;
  background-color: inherit;
  font: inherit;
  margin: 0;
}

.subtitle {
  color: white
}

.navbar a:hover, .dropdown:hover .dropbtn {
  background-color: #13347b;
  color: white;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  width: 100%;
  left: 0;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content .header {
  background: #13347b;
  padding: 16px;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}

/* Create three equal columns that floats next to each other */
.column {
  float: left;
  width: 33.33%;
  padding: 10px;
  background-color: #13347b;
  height: 250px;
}

.column a {
  float: none;
  color: black;
  padding: 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.column a:hover {
  background-color: #ddd;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

/* Responsive layout - makes the three columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) {
  .column {
    width: 100%;
    height: auto;
  }
}
'

    ),

  ),# FIN DEL HEAD ----

  # INCIO DEL BODY
  tags$body(
    tags$div(
      class = "navbar",
      tags$img(
        src = "https://assets.turbologo.com/blog/en/2020/07/19084433/what-size-should-logo-be.png",
        width = 250)
      ,
    tags$div(
      class = "dropdown",
      tags$button(
        class="dropbtn",
        "Dropdown 1",
        tags$i(class = "fa fa-caret-down")
        ),
      tags$div(
        class="dropdown-content",
        tags$div(class="header",tags$h2("Mega Menu")),
        tags$div(class = "row",
                 tags$div(class="column",
                          tags$h3(class = "subtitle","Categoria 1"),
                          tags$a(href="#","Link1")),
                 tags$div(class="column",
                          tags$h3(class = "subtitle","Categoria 2"),
                          tags$a(href="#","Link2")),
                 tags$div(class="column",
                          tags$h3(class = "subtitle","Categoria 3"),
                          tags$a(href="#","Link3"))
                 )
      )
    )
    )

  )

)

server <- function(input, output) {

}

# Run the application
shinyApp(ui = ui, server = server)

shinyApp(ui, server)

HTML:
<!DOCTYPE html>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <button class="dropbtn"> Dropdown 1

    </button>

Category 1

          Link 1
          Link 2
          Link 3

Category 2

          Link 1
          Link 2
          Link 3

Category 3

          Link 1
          Link 2
          Link 3

A: shiny uses Bootstrap under the hood. Apparently, this creates a conflict with the expected behavior of your app. You can remove this Bootstrap dependency by placing this in fluidPage:
shiny::suppressDependencies("bootstrap")

However, note that this will remove Bootstrap styling for all elements that are not in your custom CSS.


text:
Q: How to add post reference field to a plugin? I am trying to add a field to a custom post type through a plugin I am creating.
One of the fields I need is a post reference / link to field. Any ideas on how to do this?
In the WYSIWYG when you are adding a link, there is an area that lists existing posts ... I am looking to add this functionality to a custom field / meta box.
Any help is greatly appreciated.

A: You can create something similar to WYSIWYG link dialog by generating traditional HTML SELECT with OPTIONs as post items, and then make it more interactive (searchable,...) with Chosen jQuery library. It's not as precise solution as that in editor, but it can be enough for you.


text:
Q: Book a room in Lotus Notes via C# I'm trying to book a room in Lotus Notes via C# from code below.
The code I have so far:
//First, create a new Lotus Notes Session Object
Domino.NotesSession LNSession = new Domino.NotesSession();
//Next add a Database and a Document Object (not new)
Domino.NotesDatabase LNDatabase;
Domino.NotesDocument LNDocument;

//Initialize your Session with your Password
LNSession.Initialize("qwerty");
//Connect to your Notes Server and the path of your
//.nsf File (in my case its in a subfolder 'mail').
LNDatabase = LNSession.GetDatabase("Clone/testdomain", "mail\\asystem.nsf", false);
//Create an in memory document in the server database
LNDocument = LNDatabase.CreateDocument();
//-------Assign Field Values-------
//Define Start&End Date+Time of your appointment
//Year, Month, Day, Hour, Minute and Second
System.DateTime StartDate = new DateTime(2012, 12, 03, 17, 15, 0);
System.DateTime EndDate = new DateTime(2012, 12, 03, 17, 30, 0);
//This Defines that it is an Calendar Entry
LNDocument.ReplaceItemValue("Form", "Appointment");
LNDocument.ReplaceItemValue("Location", "Home");
LNDocument.ReplaceItemValue("Room", "Testroom/TestSite");
LNDocument.ReplaceItemValue("AppointmentType", "3");
//Type of the appointment, means:
//0 = Date, Appointment
//1 = Anniversary
//2 = All Day Event (Do Not Set Time Here!)
//3 = Meeting
//4 = Reminder
//5 = Date (Special, experimental!)
// Title of your entry
LNDocument.ReplaceItemValue("Subject", "hello Sir");
// Set Confidential Level (Public=1 or Private=0)
LNDocument.ReplaceItemValue("$PublicAccess", "1");
//Add Start&End Time of your event
LNDocument.ReplaceItemValue("CALENDARDATETIME", StartDate);
LNDocument.ReplaceItemValue("StartDateTime", StartDate);
LNDocument.ReplaceItemValue("EndDateTime", EndDate);
LNDocument.ReplaceItemValue("StartDate", StartDate);
LNDocument.ReplaceItemValue("MeetingType", "1");
//Infos in The Body
LNDocument.ReplaceItemValue("Body", "Body Text Body Text ...");
//Add an alarm to your appointment
LNDocument.ReplaceItemValue("$Alarm", 1);
LNDocument.ReplaceItemValue("$AlarmDescription", "hello world (alarm)");
LNDocument.ReplaceItemValue("$AlarmMemoOptions", "");
//-5 = Time (in minutes) before alarm goes on
LNDocument.ReplaceItemValue("$AlarmOffset", -5);
LNDocument.ReplaceItemValue("$AlarmSound", "tada");
LNDocument.ReplaceItemValue("$AlarmUnit", "M");
//This saves your Document in the Notes Calendar
LNDocument.ComputeWithForm(true, false);
LNDocument.Save(true, false, false);

It creates the meeting correctly in the client but on the resource database it will not save the time and date to the specified room. I have looked everywhere for code examples to this kind of problem but I found nothing.

A: From the scratch i guess, you should use a NotesDateTime object instead of System.DateTime.
Something like this...
Domino.NotesDateTime datetime = LNSession.CreateDateTime("3.12.2012 17:15");
LNDocument.ReplaceItemValue("CALENDARDATETIME", datetime.LSLocalTime); //maybe GetLSLocalTime...

Hope it will help, JiKra


text:
Q: Maven Unable to Find Dependencies For Stash Plugin I'm trying to make a Stash (Bitbucket Server) hook following this tutorial.
I installed the Atlassian SDK and ran both atlas-create-stash-plugin and atlas-create-stash-plugin-module.
However, Maven is unable to find any dependencies, despite them being in my local repository. I mean, look at this screenshot:

As you can see, the dependencies have successfully been installed to my local Maven repo, but IntelliJ (and Maven when I try to compile the plugin) are unable to locate the dependencies. Why?

A: It can be cache issue. So please try to do following in Intellij Idea:
File -> Invalidate Caches / Restart.

Also, you can try to reimport your project:

A: Try point to the repository and maven of Atlassian SDK installation:


text:
Q: what is the page table size for a 32-bit process? If the page size for a process is 4096 bytes what should be its page table size that it keeps for mapping virtual addresses to physical storage?

A: A 32 bits process can allocate up to 4G bytes = 1M pages @ 4K. So, a process may need up to one million entries in the page table(s). The page table architecture varies quite a bit between processors, so it's hard to give a more precise answer to such a generic question.


text:
Q: Upload file by HTTP POST I want to upload a file (an image specifically) to a REST Server using HTTP POST. I have already imported/add to build path httpmime-4.3.1.jar and apache-mime4j-0.6.jar. And I am getting the follow errors below in the Stack Trace.
Is this valid? post.setHeader("enctype", "multipart/form-data");
HTTP POST Code
public void multiPartPost() throws ClientProtocolException, IOException {
    File image = new File(EXTERNALSTORAGE + "/Pictures/sample.jpg");
    FileBody fileBody = new FileBody(image);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    post.setHeader("enctype", "multipart/form-data");

    MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
    multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    multipartEntity.addPart("sampleImage", fileBody);
    post.setEntity(multipartEntity.build());

    HttpResponse response = client.execute(post);
    String responseBody = EntityUtils.toString(response.getEntity());
    Log.v("multiPartPost HTTP Response", responseBody);
}

Stack Trace
01-05 17:41:25.470: W/dalvikvm(6564): VFY: unable to resolve static field 1755 (DEFAULT_BINARY) in Lorg/apache/http/entity/ContentType;
01-05 17:41:25.470: D/dalvikvm(6564): VFY: replacing opcode 0x62 at 0x0000
01-05 17:41:25.470: I/dalvikvm(6564): Could not find method org.apache.http.entity.ContentType.create, referenced from method org.apache.http.entity.mime.content.FileBody.<init>
01-05 17:41:25.470: W/dalvikvm(6564): VFY: unable to resolve static method 6613: Lorg/apache/http/entity/ContentType;.create (Ljava/lang/String;)Lorg/apache/http/entity/ContentType;
01-05 17:41:25.470: D/dalvikvm(6564): VFY: replacing opcode 0x71 at 0x0000
01-05 17:41:25.470: I/dalvikvm(6564): Could not find method org.apache.http.entity.ContentType.create, referenced from method org.apache.http.entity.mime.content.FileBody.<init>
01-05 17:41:25.470: W/dalvikvm(6564): VFY: unable to resolve static method 6614: Lorg/apache/http/entity/ContentType;.create (Ljava/lang/String;Ljava/lang/String;)Lorg/apache/http/entity/ContentType;
01-05 17:41:25.470: D/dalvikvm(6564): VFY: replacing opcode 0x71 at 0x0000
01-05 17:41:25.470: W/dalvikvm(6564): VFY: unable to find class referenced in signature (Lorg/apache/http/entity/ContentType;)
01-05 17:41:25.470: W/dalvikvm(6564): VFY: unable to find class referenced in signature (Lorg/apache/http/entity/ContentType;)
01-05 17:41:25.478: W/dalvikvm(6564): VFY: unable to find class referenced in signature (Lorg/apache/http/entity/ContentType;)
01-05 17:41:25.478: W/dalvikvm(6564): VFY: unable to find class referenced in signature (Lorg/apache/http/entity/ContentType;)
01-05 17:41:25.478: I/dalvikvm(6564): Could not find method org.apache.http.util.Args.notNull, referenced from method org.apache.http.entity.mime.content.FileBody.<init>
01-05 17:41:25.478: W/dalvikvm(6564): VFY: unable to resolve static method 6808: Lorg/apache/http/util/Args;.notNull (Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;
01-05 17:41:25.478: D/dalvikvm(6564): VFY: replacing opcode 0x71 at 0x0005
01-05 17:41:25.478: I/dalvikvm(6564): Could not find method org.apache.http.util.Args.notNull, referenced from method org.apache.http.entity.mime.content.FileBody.writeTo
01-05 17:41:25.478: W/dalvikvm(6564): VFY: unable to resolve static method 6808: Lorg/apache/http/util/Args;.notNull (Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;
01-05 17:41:25.478: D/dalvikvm(6564): VFY: replacing opcode 0x71 at 0x0002
01-05 17:41:25.478: I/dalvikvm(6564): Could not find method org.apache.http.entity.ContentType.parse, referenced from method org.apache.http.entity.mime.content.AbstractContentBody.<init>
01-05 17:41:25.478: W/dalvikvm(6564): VFY: unable to resolve static method 6618: Lorg/apache/http/entity/ContentType;.parse (Ljava/lang/String;)Lorg/apache/http/entity/ContentType;
01-05 17:41:25.486: D/dalvikvm(6564): VFY: replacing opcode 0x71 at 0x0000
01-05 17:41:25.486: W/dalvikvm(6564): VFY: unable to find class referenced in signature (Lorg/apache/http/entity/ContentType;)
01-05 17:41:25.486: I/dalvikvm(6564): Could not find method org.apache.http.util.Args.notNull, referenced from method org.apache.http.entity.mime.content.AbstractContentBody.<init>
01-05 17:41:25.486: W/dalvikvm(6564): VFY: unable to resolve static method 6808: Lorg/apache/http/util/Args;.notNull (Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;
01-05 17:41:25.486: D/dalvikvm(6564): VFY: replacing opcode 0x71 at 0x0005
01-05 17:41:25.486: I/dalvikvm(6564): Could not find method org.apache.http.entity.ContentType.getCharset, referenced from method org.apache.http.entity.mime.content.AbstractContentBody.getCharset
01-05 17:41:25.486: W/dalvikvm(6564): VFY: unable to resolve virtual method 6616: Lorg/apache/http/entity/ContentType;.getCharset ()Ljava/nio/charset/Charset;
01-05 17:41:25.486: D/dalvikvm(6564): VFY: replacing opcode 0x6e at 0x0002
01-05 17:41:25.486: W/dalvikvm(6564): VFY: unable to find class referenced in signature (Lorg/apache/http/entity/ContentType;)
01-05 17:41:25.486: I/dalvikvm(6564): Could not find method org.apache.http.entity.ContentType.getMimeType, referenced from method org.apache.http.entity.mime.content.AbstractContentBody.getMediaType
01-05 17:41:25.486: W/dalvikvm(6564): VFY: unable to resolve virtual method 6617: Lorg/apache/http/entity/ContentType;.getMimeType ()Ljava/lang/String;
01-05 17:41:25.486: D/dalvikvm(6564): VFY: replacing opcode 0x6e at 0x0002
01-05 17:41:25.493: I/dalvikvm(6564): Could not find method org.apache.http.entity.ContentType.getMimeType, referenced from method org.apache.http.entity.mime.content.AbstractContentBody.getMimeType
01-05 17:41:25.493: W/dalvikvm(6564): VFY: unable to resolve virtual method 6617: Lorg/apache/http/entity/ContentType;.getMimeType ()Ljava/lang/String;
01-05 17:41:25.493: D/dalvikvm(6564): VFY: replacing opcode 0x6e at 0x0002
01-05 17:41:25.493: I/dalvikvm(6564): Could not find method org.apache.http.entity.ContentType.getMimeType, referenced from method org.apache.http.entity.mime.content.AbstractContentBody.getSubType
01-05 17:41:25.493: W/dalvikvm(6564): VFY: unable to resolve virtual method 6617: Lorg/apache/http/entity/ContentType;.getMimeType ()Ljava/lang/String;
01-05 17:41:25.493: D/dalvikvm(6564): VFY: replacing opcode 0x6e at 0x0002
01-05 17:41:25.493: W/dalvikvm(6564): threadid=11: thread exiting with uncaught exception (group=0x40dc51f8)
01-05 17:41:25.501: E/AndroidRuntime(6564): FATAL EXCEPTION: AsyncTask #1
01-05 17:41:25.501: E/AndroidRuntime(6564): java.lang.RuntimeException: An error occured while executing doInBackground()
01-05 17:41:25.501: E/AndroidRuntime(6564):     at android.os.AsyncTask$3.done(AsyncTask.java:287)
01-05 17:41:25.501: E/AndroidRuntime(6564):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-05 17:41:25.501: E/AndroidRuntime(6564):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-05 17:41:25.501: E/AndroidRuntime(6564):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-05 17:41:25.501: E/AndroidRuntime(6564):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-05 17:41:25.501: E/AndroidRuntime(6564):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:217)
01-05 17:41:25.501: E/AndroidRuntime(6564):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-05 17:41:25.501: E/AndroidRuntime(6564):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-05 17:41:25.501: E/AndroidRuntime(6564):     at java.lang.Thread.run(Thread.java:856)
01-05 17:41:25.501: E/AndroidRuntime(6564): Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType
01-05 17:41:25.501: E/AndroidRuntime(6564):     at org.apache.http.entity.mime.content.FileBody.<init>(FileBody.java:89)
01-05 17:41:25.501: E/AndroidRuntime(6564):     at com.medusa.checkit.HTTPPostRequest.multiPartPost(HTTPPostRequest.java:79)
01-05 17:41:25.501: E/AndroidRuntime(6564):     at com.medusa.checkit.MenuActivity$BackgroundTask.doInBackground(MenuActivity.java:79)
01-05 17:41:25.501: E/AndroidRuntime(6564):     at com.medusa.checkit.MenuActivity$BackgroundTask.doInBackground(MenuActivity.java:1)
01-05 17:41:25.501: E/AndroidRuntime(6564):     at android.os.AsyncTask$2.call(AsyncTask.java:273)
01-05 17:41:25.501: E/AndroidRuntime(6564):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-05 17:41:25.501: E/AndroidRuntime(6564):     ... 5 more

A: You seem to be missing a dependency.
I have httpclient-4.2.5, httpcleint-cache-4.2.5, httpcore-4.2.4 and httpmime-4.2.5 with commons-lang3-3.1 and commons-logging-1.1.2 jars in my class path.
I also use entity.addPart(formFieldName, new FileBody(file, "image/jpeg")); instead of using the header property.
Take a look at Internet media type for more details


text:
Q: Normal Matrix with Real Eigenvalues is Hermitian Let $A$ be a normal matrix. Then I want to show that, if $A$ has real eigenvalues, $A$ is Hermitian. (Notation: * denotes the complex conjugate, T denotes the transpose, and $\dagger$ denotes the conjugate transpose.)
Suppose that $A$ has only real eigenvalues and let $\lambda,v$ be a nonzero eigenvalue-eigenvector pair of $A$. Then we have
$\lambda(v,v)=(v,\lambda v)=(v,Av)=(A^\dagger v,v)$.
$\lambda(v,v)=\lambda^*(v,v)=(\lambda v,v)=(Av,v)$.
Thus, $(Av,v)=(A^\dagger v,v)$ and hence $\sum_i (Av)_i^*v_i=\sum_i (A^\dagger v)_i^* v_i$.
Write this as a matrix product: $(A^*v^*)^Tv=(A^{\dagger*}v^*)^Tv\implies (A^*v^*)^Tv-(A^{\dagger*}v^*)^Tv=0\implies ((A^*v^*)^T-(A^{\dagger*}v^*)^T)v=0$.
Since $v$ is nonzero, we have $(A^*v^*)^T-(A^{\dagger*}v^*)^T=0\implies A^*v^*-A^{\dagger*}v^*=0\implies (A^*-A^{\dagger*})v^*=0$
Since $v$ was nonzero, we have $v^*$ is also nonzero, so $(A^*-A^{\dagger*})=0\implies A^*=A^{\dagger*}$. Thus, we have $A=A^\dagger$ so $A$ is hermitian.
I've seen (here, for example) a much simpler proof. However, I can't find where I use that $A$ is normal, but I know that normality is required. Could anyone could point out where I made this assumption or where I've made a mistake?

A: You use the "fact" that if $(Bx,y)=0$ and $y\neq 0$, then $Bx =0$. You wrote it as
$$((A - A^\dagger) \nu, \nu ) = 0 \implies (A- A^\dagger) \nu = 0$$


text:
Q: Shell + tar.gz problem with shell with archive files with --exclude= Thank for you help
While I want to archive all files in home without directory "pictures_old"
I tried find solution, but no results.
Can you help me?
 for dir in `ls`; do tar -cvzf ${dir}.tar.gz --exclude="/home/pictures_old/" ${dir}; done

That script archive all files in home with "pictures_old"
I woud like to exclude pictures_old

A: Solution: for dir in ls --hide='pictures_old' ; do tar -cvzf ${dir}.tar.gz ${dir}; done


text: Q: Handbrake start button greyed out I'm running Handbrake rev 5474 (x86_64) under Kubuntu 14.04.  The Start button is greyed out. As far as I know, I have the latest version.  There are a number of reports of this problem from 2010, but the solutions proposed there are all version-related. How can I get the transcription started?


text:
Q: Error en webservices java Tengo un webservice en Java que recibe un Json y lo tiene que insertar en una tabla. El problema es que me esta arrojando un error que no he podido solventar.
En primera instancia pensé que era el valor "contenido" del Json porque lo tenia que guardar en una columna tipo blob pero intente guardar ese valor en una columna varchar(1000) y me sigue dando el mismo error.
Ya no se que mas intentar, este fragmento de código lo he utilizado en otros proyectos con Json y nunca me había fallado.
El JSON
{
"status": "ok",
"message": "datos obtenidos correctamente",
"data": {
    "nroFolio": "123456789",
    "idEspecieValorada": "123456789",
    "contenido": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<datosImpresionTOList>\n    <datosImpresionTO>\n        <basedest>LOS ANGELES</basedest>\n        <bd>LSQ</bd>\n        <c01></c01>\n        <c02></c02>\n        <c03></c03>\n        <c04></c04>\n        <c128_cb28l>5330066881571030013301083025</c128_cb28l>\n        <c39_os>6688157103</c39_os>\n        <cbl28>5330066881571030013301083025</cbl28>\n        <cde>8302</cde>\n        <comuna>ANTUCO</comuna>\n        <contacto_dest>CRISTIAN ROMERO</contacto_dest>\n        <cta_cte>96801150-11-8</cta_cte>\n        <detcod01></detcod01>\n        <detcod02></detcod02>\n        <detcod03></detcod03>\n        <detcod04></detcod04>\n        <detcod05></detcod05>\n        <detdd01></detdd01>\n        <detdd02></detdd02>\n        <detdd03></detdd03>\n        <detdd04></detdd04>\n        <detdd05></detdd05>\n        <detdd06></detdd06>\n        <detdd07></detdd07>\n        <detdd08></detdd08>\n        <dims>25,7 x 25,7 x 25,7 CM</dims>\n        <dir_dest1>CAUPOLICAN 123</di...",
    "idGuias": "GUIA",
    "nombreArchivo": "template_guia_landscape.jasper",
    "rutaArchivo": "/home/l101/Proyectos java/asdasd asdasd/asd/asd/asd/sad/asd/",
    "tipo": "LASER"
}}

El JAVA
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public jsonResultResponse postEtiqueta(List<ResponseBxe> data) throws ParseException, SQLException {

    Conexion con = new Conexion("DESA");
    Connection miCon = con.GetConnection();

    jsonResultResponse result = new jsonResultResponse();
    try {

        for (int i = 0; i < data.size(); i++) {
            ResponseBxe response = new ResponseBxe();

            response.setNroFolio(data.get(i).getNroFolio());
            response.setIdEspecieValorada(data.get(i).getIdEspecieValorada());
            response.setContenido(data.get(i).getContenido());
            response.setIdGuias(data.get(i).getIdGuias());
            response.setNombreArchivo(data.get(i).getNombreArchivo());
            response.setRutaArchivo(data.get(i).getRutaArchivo());
            response.setTipo(data.get(i).getTipo());

            String query = "INSERT INTO NOMBRETABLA (N_FOLIO, ID_ESPECIE_VAL, CONTENIDO, ID_GUIA, NOM_ARCHIVO, RUTA_ARCHIVO, TIPO) "
                    + "VALUES('" + response.getNroFolio() + "' ,'" + response.getIdEspecieValorada() + "','" + response.getContenido() + "','" + response.getIdGuias() + "','" + response.getNombreArchivo() + "','" + response.getRutaArchivo() + "','" + response.getTipo() + "')";
            prep = miCon.prepareStatement(query);
            prep.executeQuery();
            prep.close();
        }

        result.setCode(200);
        result.setStatus("OK");
        result.setMessage("Datos insertados correctamente!");

    } catch (SQLException ex) {
        result.setCode(401);
        result.setStatus("Error");
        result.setMessage(ex.getMessage());
    } catch (Exception ex) {
        result.setCode(300);
        result.setStatus("Error");
        result.setMessage(ex.getMessage());
    } finally {
        if (prep != null) {
            try {
                prep.close();
            } catch (SQLException ex) {
                result.setCode(400);
                result.setStatus("Error");
                result.setMessage(ex.getMessage());
            }
        }
    }

    return result;
}

El ERROR

    <title>Payara Server 5.181 #badassfish - Error report</title>

HTTP Status 500 - Internal Server Error

type Exception report

messageInternal Server Error

descriptionThe server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: javax.ws.rs.ProcessingException: Error deserializing object from entity stream.

root cause

javax.ws.rs.ProcessingException: Error deserializing object from entity stream.

root cause

javax.json.bind.JsonbException: Can't infer a type for unmarshalling into: java.util.List

note The full stack traces of the exception and its root causes are available in the Payara Server
            5.181 #badassfish logs.

Payara Server 5.181 #badassfish


text:
Q: Example of Matrix in Reduced Row Echelon Form I'm struggling with this question and can't seem to come up with an example:
Give an example of a linear system (augmented matrix form) that has:

*

*reduced row echelon form

*consistent

*3 equations

*1 pivot variable

*1 free variable

The constraints that I'm struggling with is: If the system has 3 equations, that means the matrix must have at least 3 non-zero rows. And given everything else, how can I have only 1 pivot?

A: Hint: It's gotta have only three columns, one for each of the variables (1 pivot, 1 free) and one column for the constants in the equations.


text:
Q: Fixing Box2D Drawings I am trying to draw a rectangle which would have an edge next to each of its sides (it should represent a building with a fence) for one building it goes quite well, but when I am trying to add a new building it messes itself up completely.
I have this code to create buildings:
class Building():
    def __init__(self, Box_2_World,shape, position, sensor= None):
        self.Box_2_World = Box_2_World
        self.shape = shape
        self.position = position

        if sensor == None:
            sensor = False

        self.sensor = sensor
        self.footprint = self.Box_2_World.CreateStaticBody(position = position,
                                                           angle = 0.0,
                                                           fixtures = b2FixtureDef(
                                                               shape = b2PolygonShape(box=(self.shape)),
                                                               density = 1000,
                                                               friction = 1000))

        self.Lower_Fence = self.Box_2_World.CreateStaticBody(position=(self.footprint.position[0],self.footprint.position[1] -1.75*self.shape[1]))
        self.Lower_Fence.CreateEdgeChain([(self.Lower_Fence.position[0]-4.25*self.shape[0],self.Lower_Fence.position[1]),
                            (self.Lower_Fence.position[0]-2.25*self.shape[0],self.Lower_Fence.position[1]),
                        ])

        self.Right_Fence = self.Box_2_World.CreateStaticBody(position=(self.footprint.position[0]-1*self.shape[0],self.footprint.position[1]))
        self.Right_Fence.CreateEdgeChain([(self.Right_Fence.position[0],self.Right_Fence.position[1] - 1.25*self.shape[1]),
                            (self.Right_Fence.position[0],self.Right_Fence.position[1]-3.25*self.shape[1]),
                        ])

        self.Upper_Fence = self.Box_2_World.CreateStaticBody(position=(self.footprint.position[0],self.footprint.position[1] -0.45* self.shape[1]))
        self.Upper_Fence.CreateEdgeChain([(self.Upper_Fence.position[0] - 4.25* self.shape[0],self.Upper_Fence.position[1]),
                            (self.Upper_Fence.position[0]- 3.25* self.shape[0]+ self.shape[0],self.Upper_Fence.position[1]),
                        ])

        self.Left_Fence = self.Box_2_World.CreateStaticBody(position=(self.footprint.position[0]-2.25*self.shape[0],self.footprint.position[1]))
        self.Left_Fence.CreateEdgeChain([(self.Left_Fence.position[0],self.Left_Fence.position[1] - 1.25*self.shape[1]),
                            (self.Left_Fence.position[0],self.Left_Fence.position[1]-3*self.shape[1]),
                        ])

Skyscrapers = []
Rectangles = [(pos_X-5, pos_Y-5),(pos_X+15, pos_Y -5),(pos_X - 5,pos_Y + 15),(pos_X+15, pos_Y + 15)]

for i in range(4):
    Skyscrapers.append(Building(Box_2_World,shape = (5,5), position =  Rectangles[i]))

and these functions to draw it using PyGame:
SCREEN_OFFSETX, SCREEN_OFFSETY = SCREEN_WIDTH/16, SCREEN_HEIGHT

def fix_vertices(vertices):
    return [(int(SCREEN_OFFSETX + v[0]), int(SCREEN_OFFSETY - v[1])) for v in vertices]
def _draw_polygon(polygon, screen, body, fixture):
    transform = body.transform
    vertices = fix_vertices([transform * v * PPM for v in polygon.vertices])
    pygame.draw.polygon(
        screen, [c / 2.0 for c in colors[body.type]], vertices, 0)
    pygame.draw.polygon(screen, colors[body.type], vertices, 1)
polygonShape.draw = _draw_polygon

def _draw_edge(edge, screen, body, fixture):
    vertices = fix_vertices(
        [body.transform * edge.vertex1 * PPM, body.transform * edge.vertex2 * PPM])
    pygame.draw.line(screen, colors[body.type], vertices[0], vertices[1])
edgeShape.draw = _draw_edge

And the output is this: Blue rectangles represent buildings, blue lines are fences, first building fits quite nice, but the others are for some reason out of desired positions
Also, if you find out a way how to create the fences using for loop, it would be great (that's the reason why I put for-loop tag into this question)
Any help appreciated

A: The coordinates which are passed to CreateEdgeChain have to be relative to the body.
The position of the body is set when the object is constructed e.g:
self.Lower_Fence = self.Box_2_World.CreateStaticBody(
    position=(self.footprint.position[0], self.footprint.position[1] -1.75*self.shape[1]))

And the edges have to be relative to this position rather than an absolute position.e.g:
self.Lower_Fence.CreateEdgeChain([(-4.25*self.shape[0], 0), (-2.25*self.shape[0], 0)])

To create the fences in a for-loop, you've to define a list of the edges. With the list of the edges you can create a list of fences:
fence_edges = [
    [(-4.25, -1.75), (-2.25, -1.75)],
    [(-1.00, -1.25), (-1.00, -3.25)],
    [(-4.25, -0.45), (-2.25, -0.45)],
    [(-2.25, -1.25), (-2.25, -3.25)]
]

self.Fences = []
for edge in fence_edges:
    p1, p2 = edge
    fence = self.Box_2_World.CreateStaticBody(position=self.footprint.position[:])
    fence.CreateEdgeChain(
        [(p1[0] * self.shape[0], p1[1] * self.shape[1]),
         (p2[0] * self.shape[0], p2[1] * self.shape[1])])
    self.Fences.append(fence)

self.Lower_Fence, self.Right_Fence, self.Upper_Fence, self.Left_Fence = self.Fences


text:
Q: Eliminate duplicates in Array (Eliminate duplicates) Write a method that returns a new array by eliminating the
duplicate values in the array using the following method header:
public static int[] eliminateDuplicates(int[] list)

Write a test program that reads in 10 integers, invokes the method, and displays the distinct numbers separated by exactly one space. Here is a sample run of the
program:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The distinct numbers are: 1 2 3 6 4 5
package bucky;

import java.util.Scanner;

public class Arrays {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        System.out.print("Enter ten numbers: ");

        int[] list = new int[10];

        for (int i = 0; i < list.length; i++) {
            list[i] = in.nextInt();
        }
        eliminateDuplicates(list);

        System.out.print("The distinct numbers are: ");
        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i]);
        }
    }

    public static int[] eliminateDuplicates(int[] list) {

        int count = 0;
        int j = 0;
        int[] nArray = new int[list.length];
        while (j < list.length) {
            for (int i = 1; i < list.length; i++) {
                int low = list[j];
                if (list[i] == low) {
                    count++;
                } else {
                    nArray[i] = low;
                }
            }
            j++;
        }
        return nArray;
    }
}

A: Array can be simply converted to a HashSet which eliminates duplicate automatically.
Set list2 = Arrays.stream(list).boxed().collect(Collectors.toSet());
System.out.print("The distinct numbers are: " + list2);


text:
Q: How to determine what type is returned by concatwith angular store Hi have 2 observables ,

*

*this.resolveActifsFromStore() // return Observable

*this.store.select(fromActifSelector.DoSelector.selectAllActifs) // return Observable<IActifModel[]>

I need to execute by order, so I use the concatWith like this
actifs$!: Observable<IActifModel[]>;

ngOnInit(){
    this.resolveActifsFromStore()
    .pipe(
        concatWith(this.store.select(fromActifSelector.DoSelector.selectAllActifs)),
    )
    .subscribe((val)=>{
              //error first return is boolean , the second is  IActifModel[]
              //HERE IS I DON´T KNOW HOW TO DO
              if(val) {
                        actifs$ = of(val);
                      }
}

The problem is the val will have the return boolean, and also IActifModel[].
How can I identify the type of each return, because I want to do this, if the first observables is true then I want to assign the value of the second observable to actifs$

A: You can use Array.isArray. It inferes the type correctly and knows within the if block, that the type of val is an array.(https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
.subscribe((val: boolean | IActifModel[])=>{
    if(Array.isArray(val)) {
      // code for IActifModel[]
    } else {
      // code for boolean
    }

A: You could use concatMap to wait for the first observable to complete and then proceed to the second one:
this.resolveActifsFromStore().pipe(
  withLatestFrom(this.store.select(fromActifSelector.DoSelector.selectAllActifs),
  concatMap(([myBoolean, myIActifModel]: [boolean, IActifModel[]]) => {
    //....
    return of({
       theBoolean: myBoolean,
       theOtherOne: myIActifModel
    });
  })
).subscribe(console.log);

Or based on your post, you could also use forkJoin and see when the value is true do some logic with it...
const total$ = forkJoin({
  theBoolean: this.resolveActifsFromStore(),
  theOtherOne: this.store.select(fromActifSelector.DoSelector.selectAllActifs)
});

total$.subscribe(({theBoolean, theOtherOne}) => {
   if (theBoolean) {
     //... do some logic
   }
});


text:
Q: httpwebrequet for https fails with "The system cannot find the file specified exception" I am creating an "httpWebRequest"with following code
System.Net.WebRequest.DefaultWebProxy = null;
HttpWebRequest request =  (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
ServicePointManager.ServerCertificateValidationCallback += CustomServiceCertificateValidation;
X509Certificate2 clientCertificate = new X509Certificate2("Client.cer");
request.ClientCertificates.Add(clientCertificate);

CustomServiceCertificateValidation function
private static bool CustomServiceCertificateValidation(
                object sender, X509Certificate cert, X509Chain chain,
                SslPolicyErrors error)
{
     return true;
}

when I call
WebResponse response = request.GetResponse();

I get "The system cannot find the file specified exception".
Following trace I got it
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.X509Certificates.X509Utils._QueryCertFileType(String fileName)
   at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags)
   at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName)
   at Transport.SendOut.CustomServiceCertificateValidation(Object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
   at System.Net.Security.RemoteCertificateValidationCallback.Invoke(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
   at System.Net.ServerCertValidationCallback.Callback(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Net.ServerCertValidationCallback.Invoke(Object request, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
   at System.Net.Security.SecureChannel.VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertValidationCallback)
   at System.Net.Security.SslState.CompleteHandshake()
   at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
   at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.ConnectStream.WriteHeaders(Boolean async)

using Command
"openssl s_client -connect 127.0.0.1:portno"
able to connect and return the server certificate.
In browser, I am able to access the same URL.
Please some one help me on this.
Thanks.

A: It looks to me like it can't find the file "client.cer". Make sure that the file is in the application's current working directory. Add this code above what you've posted:
if (!System.IO.File.Exists("client.cer"))
{
    throw new FileNotFoundException();
}

You either need to put the file in the application's working directory, or supply a path so that the system can find it.
You should put a try ... catch around your call to request.GetResponse() and examine the exception. I assume you're getting FileNotFoundException. According to the documentation, the FileName property will tell you which file it was trying to read. So:
try
{
    WebResponse response = request.GetResponse();
}
catch (FileNotFoundException fex)
{
    Console.WriteLine("Unable to find file " + fex.FileName);
}
catch (Exception ex)
{
    Console.WriteLine("Some other exception.");
}

In the debugger, put breakpoints inside both of the catch clauses and examine the exception. That should tell you what file it's trying to find.


text:
Q: PayPal Rest API - End Point Used In my Dev environment, I can correctly use the Rest API to the sandbox site:
    $sdkConfig = array(
         "mode" => 'sandbox'
    );

    $cred = new OAuthTokenCredential(
        $SANDBOX_clientId,
        $SANDBOX_clientSecret
    );

    $access_token = $cred->getAccessToken($sdkConfig);

When using the same code with Live Keys and a verified Live account:
    $sdkConfig = array(
         "mode" => 'live'
    );

    $cred = new OAuthTokenCredential(
        $LIVE_clientId,
        $LIVE_clientSecret
    );

    $access_token = $cred->getAccessToken($sdkConfig);

I get this error:
Http response code 401 when accessing https://api.sandbox.paypal.com/v1/oauth2/token
How does the PayPal REST API know which endpoint to access?
I am not specifying the endpoint in the sandbox or live calls and am not using a bootstrap or ini file. The account is verified and approved.

A: The best way I would recommend is to create an ApiContext object similar to shown at https://gist.github.com/jaypatel512/a2b037ab5ddc51fa7280
<?php

// 1. Autoload the SDK Package. This will include all the files and classes to your autoloader
require __DIR__  . '/PayPal-PHP-SDK/autoload.php';

// 2. Provide your Secret Key. Replace the given one with your app clientId, and Secret
// https://developer.paypal.com/webapps/developer/applications/myapps
$apiContext = new \PayPal\Rest\ApiContext(
    new \PayPal\Auth\OAuthTokenCredential(
        'AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS',     // ClientID
        'EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL'      // ClientSecret
    )
);

// Step 2.1 : Between Step 2 and Step 3
$apiContext->setConfig(
  array(
    'mode' => 'live',
    'log.LogEnabled' => true,
    'log.FileName' => 'PayPal.log',
    'log.LogLevel' => 'FINE'
  )
);

// 3. Lets try to save a credit card to Vault using Vault API mentioned here
// https://developer.paypal.com/webapps/developer/docs/api/#store-a-credit-card
$creditCard = new \PayPal\Api\CreditCard();
$creditCard->setType("visa")
    ->setNumber("4417119669820331")
    ->setExpireMonth("11")
    ->setExpireYear("2019")
    ->setCvv2("012")
    ->setFirstName("Joe")
    ->setLastName("Shopper");

// 4. Make a Create Call and Print the Card
try {
    $creditCard->create($apiContext);
    echo $creditCard;
}
catch (\PayPal\Exception\PayPalConnectionException $ex) {
    echo $ex;
}


text:
Q: How do I make my row names appear on my x axis? And the numbers on from my variables appear as the y axis? I created a dataframe with countries as row names and percentages as obs. from the variables, but when making a histogram it seems that the percentages from the variables are occupying the x axis and the country names aren't even there. How do I make it so that the countrie's names are on the x axis and the variables on the y?
Country <- c('Albania','Armenia','Austria','Belarus','Belgium','Bosnia and Herzegovina','Bulgaria','Croatia','Cyprus','Czechia','Denmark','Estonia','Finland','France','Georgia','Germany','Greece','Hungary','Iceland','Ireland','Italy','Latvia','Lithuania','Luxembourg','Malta','Moldova','Montenegro','Netherlands','Norway','Poland','Portugal','Romania','Russia','Serbia','Slovakia','Slovenia','Spain','Sweden','Switzerland','Turkey','Ukraine','United Kingdom')
Anxiety.Disorders <- c(3.38,2.73,5.22,3.03,4.92,3.70,3.84,3.74,5.61,3.59,5.18,3.01,3.59,6.37,2.46,6.37,5.58,3.69,5.15,5.66,5.57,3.04,3.06,5.19,5.14,2.77,3.55,6.43,7.33,3.68,5.52,3.41,3.02,3.60,3.61,3.60,5.14,5.16,5.28,3.85,3.09,4.43)
Depressive.Disorders <- c(2.42,3.16,3.66,4.84,4.35,2.88,3.30,3.60,3.88,3.25,3.62,4.78,5.08,4.55,2.98,4.42,4.56,3.53,3.55,4.37,3.94,4.44,5.20,3.95,3.69,3.77,2.96,4.34,3.95,2.72,5.27,2.88,4.36,3.15,2.87,3.58,3.91,4.84,4.17,3.76,5.02,4.35)
Bipolar.Disorder <- c(0.72,0.77,0.95,0.73,0.91,0.79,0.67,0.77,1.04,0.75,0.99,0.71,0.99,0.93,0.67,0.79,0.93,0.74,0.97,0.80,0.95,0.71,0.73,0.95,0.97,0.67,0.74,0.94,0.85,0.76,0.97,0.78,0.70,0.74,0.76,0.75,0.97,1.04,0.98,0.85,0.73,1.05)
G08 <- data.frame(Country, Anxiety.Disorders, Depressive.Disorders, Bipolar.Disorder)
row.names(G08) <- G08$Country
G08[1] <- NULL

hist(G08$Anxiety.Disorders)

A: I use the melt() call to create one observation per row. Then, I use ggplot to produce the bar plot.
library(ggplot2)
library(reshape2)

Country <- c('Albania','Armenia','Austria','Belarus','Belgium','Bosnia-Herzegovina','Bulgaria','Croatia','Cyprus','Czechia','Denmark','Estonia','Finland','France','Georgia','Germany','Greece','Hungary','Iceland','Ireland','Italy','Latvia','Lithuania','Luxembourg','Malta','Moldova','Montenegro','Netherlands','Norway','Poland','Portugal','Romania','Russia','Serbia','Slovakia','Slovenia','Spain','Sweden','Switzerland','Turkey','Ukraine','United Kingdom')

Anxiety.Disorders <- c(3.38,2.73,5.22,3.03,4.92,3.70,3.84,3.74,5.61,3.59,5.18,3.01,3.59,6.37,2.46,6.37,5.58,3.69,5.15,5.66,5.57,3.04,3.06,5.19,5.14,2.77,3.55,6.43,7.33,3.68,5.52,3.41,3.02,3.60,3.61,3.60,5.14,5.16,5.28,3.85,3.09,4.43)

Depressive.Disorders <- c(2.42,3.16,3.66,4.84,4.35,2.88,3.30,3.60,3.88,3.25,3.62,4.78,5.08,4.55,2.98,4.42,4.56,3.53,3.55,4.37,3.94,4.44,5.20,3.95,3.69,3.77,2.96,4.34,3.95,2.72,5.27,2.88,4.36,3.15,2.87,3.58,3.91,4.84,4.17,3.76,5.02,4.35)

Bipolar.Disorder <- c(0.72,0.77,0.95,0.73,0.91,0.79,0.67,0.77,1.04,0.75,0.99,0.71,0.99,0.93,0.67,0.79,0.93,0.74,0.97,0.80,0.95,0.71,0.73,0.95,0.97,0.67,0.74,0.94,0.85,0.76,0.97,0.78,0.70,0.74,0.76,0.75,0.97,1.04,0.98,0.85,0.73,1.05)

G08 <- data.frame(Country, Anxiety.Disorders, Depressive.Disorders, Bipolar.Disorder)

G08melt <- melt(G08, "Country")

G08.bar <- ggplot(G08melt, aes(x = Country, y=value)) +
  geom_bar(aes(fill=variable),stat="identity", position ="dodge") +
  theme_bw()+
  theme(axis.text.x = element_text(angle=-40, hjust=.1))

G08.bar

A: Looking at your question, I think you tried to do a grouped column diagram instead of a histogram. You can do the plot directly using the barplot function from the graphics package. But before that, you need to convert your dataframe into a matrix. I removed the first column from G08.
mat<-G08[,-1]

Now just simply use the barplot function on the transpose of the matrix mat and use the names parameter of barplot to write the names of the Countries on the x-axis:
barplot(t(mat),beside=T,col=c('red','blue','gold'),border=NA,names=G08$Country,cex.names=0.45,las=2)
par(new=T)
legend('topright',c("Anxiety","Depressive","Bipolar"),fill=c("red","blue","gold"),cex=0.5,title='Disorder types')

Suggestion:
For a little bit of more 'fresh air' in the graph, you can just set beside=F in barplot and get a stacked column diagram:


text:
Q: How do I disable message sending using the return key on Ipad or Iphone? While using a bluetooth keyboard Using a Bluetooth keypad with my Ipad how do I compose a message with new paragraphs?    Pressing Énter/return' sends the message immediately and message is most often incomplete. I also experience this with Facebook when posting messages!?

A: By experience, latest macOS (11.1) and iPadOS (14.4) versions let you get a new line by pressing the Shift ⇧ + Enter ⏎
In older versions of iPadOS it would be pressing Option ⌥ + Enter ⏎ (same as for macOS)