text:
Q: InvalidPipeArgument: '[object Object],[object Object],[object Object],[object Object],[object Object],[object Object], I am trying to load service data in ngfor through async pipe but i am facing an issue:
this is my component:
    <app-book-list *ngFor="let app of apps | async | serachBox:searchBooksByName | filterSearch:showTechBooks:showMgmBooks:showFictionBooks "
  [bookdetails]="app"></app-book-list>

In this component apps is supposed to come from service.
In My component.ts file:
     public apps= [];
  ngOnInit() {
    this.ServerService.getBookDetails()
      .then((data)=>{
        this.apps = data;
      })
  }

And below is the promise:
getBookDetails(){
let promise = new Promise((resolve,reject)=>{
   return this.http.get('https://lib-http-ng.firebaseio.com/bookdetails.json')
        .toPromise()
        .then((res)=>{
            const data = Object.values(res.json());
            resolve(data[0])
        })

})
return promise;

}
I am getting an error related to async pipe.
1.
  Type '{}' is not assignable to type 'Promise<any>'.

A: this.ServerService.getBookDetails()
  .then((data)=>{
    console.log(data);
    this.apps =  data;
  })

should be
this.apps = this.ServerService.getBookDetails()

or remove | async


text:
Q: How do I summon an enchanted item? I tried this command:
/summon item ~ ~ ~ {Item:{id:iron_pickaxe,Count:1,Enchantments:{id:fortune,lvl:1}}}

But the Iron pickaxe was without enchantment.
I'm on Minecraft java 1.18.1.

A: Try:
/summon item ~ ~ ~ {Item:{id:"minecraft:iron_pickaxe",Count:1b,tag:{Enchantments:[{id:"minecraft:fortune",lvl:1s}]}}}

The changes:
I used MC stacker at https://mcstacker.net/
Mc stacker can help you create commands easily.

I tested this and it works!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any way to provide constructor parameters to generic instances? I can't do this in C#:
    catch (Exception exception)
    {
        var wrappedException = new TException(exception);
    }

Getting error "cannot provide arguments when creating an instance of type parameter 'TException'. Just wanted to check with the community to see if there is any way to do something like this?

A: The easiest (and best) method is to call Activator.CreateInstance yourself. This is what the C# compiler actually does, as the new() constraint just ensures that the specified type has a parameterless constructor; calling new TException() actually uses Activator.CreateInstance to instantiate the type.
Something like this would work:
throw (Exception)Activator.CreateInstance(typeof(TException), exception);

A: I find the easiest way to do this is to have the type in question take a factory lambda in addition to the generic parameter.  This factory lambda is responsible for creating an instance of a generic parameter for certain parameters.  For example
void TheMethod<TException>(Func<Exception,TException> factory) {
  ...
  catch (Exception ex) {
    var wrapped = factory(ex);
    ...
  }
}

Also I wrote a blog article on this problem recently that goes over various ways to solve this problem

*

*http://blogs.msdn.com/b/jaredpar/archive/2010/06/04/using-lambdas-to-create-generic-factories.aspx


text:
Q: RecyclerView's last item is cut off when TextView Error Banner is visible. I'm using Constraint Layout with Barrier I'm not sure how to ask this question. It seems easy to do but I'm not sure why it's not working. Anyways, here goes. I have this Error Banner that should be visible only if the total "Weight" for the Categories is less than or greater than 100. However my issue is that when the error banner is visible, my RecyclerView's last item is cut off, I think by the height of the error banner.
It will only be fixed if I edit it once again and the keyboard is shown, the recyclerview's height is refreshed (probably).
Here's my Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".presentation.screens.gradesetup.gradingcategories.GradingCategoriesFragment">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layoutParent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.appcompat.widget.LinearLayoutCompat
            android:id="@+id/layoutGradeCategoryList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constrainedHeight="true" >

            <TextView
                android:id="@+id/tvInvalidGradeWeightLayout"
                style="@style/Default_Text_Error_Banner"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="@dimen/default_margin_size_16dp"
                android:text="@string/error_invalid_grade_category_weight"
                android:visibility="gone" />

            <!-- Constraint layout_constraintHeight_max dynamically to 24% -->
            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/rvGradingCategories"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </androidx.appcompat.widget.LinearLayoutCompat>

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/tvInfoNoData"
            style="@style/Default_Text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/text_no_data_display"
            android:visibility="visible"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.constraintlayout.widget.Barrier
            android:id="@+id/barrier"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:barrierDirection="bottom"
            app:constraint_referenced_ids="layoutGradeCategoryList" />

        <androidx.appcompat.widget.LinearLayoutCompat
            android:id="@+id/layout_adjust_weight"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/default_margin_size_16dp"
            android:orientation="horizontal"
            app:layout_constraintBottom_toTopOf="@+id/buttonSave"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/barrier"
            app:layout_constraintVertical_bias="0.01">

            <com.google.android.material.switchmaterial.SwitchMaterial
                android:id="@+id/switchViewAdjustWeight"
                style="@style/Default_Text_Bold"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_centerVertical="true"
                android:layout_marginEnd="@dimen/screen_padding_size"
                android:text="@string/text_adjust_weight"
                android:theme="@style/Theme.LMS"
                android:visibility="gone" />

        </androidx.appcompat.widget.LinearLayoutCompat>

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/default_margin_size_30dp"
            android:src="@drawable/ic_plus"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:tint="@color/white" />

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/buttonSave"
            style="@style/Primary_Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/default_margin_size_30dp"
            android:enabled="false"
            android:text="@string/text_save"
            android:visibility="gone"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

As you can see I also have this Constraint Barrier, so whenever the height of the RecyclerView is longer, the SwitchMaterial("switchViewAdjustWeight") is also adjusted. I set the android:layout_constraintHeight_max dynamically based on device height.
// Dynamically set constraintMaxHeight
var constraintMaxHeight = 0
constraintMaxHeight =
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        val windowMetrics = activity!!.windowManager.currentWindowMetrics
        val insets: Insets = windowMetrics.windowInsets
            .getInsetsIgnoringVisibility(WindowInsets.Type.systemBars())
        val height = windowMetrics.bounds.height() - insets.top - insets.bottom
        (height * 0.7).toInt()
    } else {
        val displayMetrics = DisplayMetrics()
        activity!!.windowManager.defaultDisplay.getMetrics(displayMetrics)
        (displayMetrics.heightPixels * 0.7).toInt()
    }

val constraintSet = ConstraintSet()
constraintSet.clone(layoutParent)
constraintSet.constrainMaxHeight(R.id.layoutGradeCategoryList, constraintMaxHeight)
constraintSet.applyTo(layoutParent)

In my code (kotlin): the error banner is toggled to visible if sum != 100
val result = sum == 100
binding.apply {
     buttonSave.isEnabled = result
     tvInvalidGradeWeightLayout.isVisible = !result
}

Target UI:

I also did change LinearLayout to ConstraintLayout However it didn't work, the Banner overlaps with the RecyclerView list :
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layoutParent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/layoutGradeCategoryList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constrainedHeight="true" >

            <TextView
                android:id="@+id/tvInvalidGradeWeightLayout"
                style="@style/Default_Text_Error_Banner"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="@dimen/default_margin_size_16dp"
                android:text="@string/error_invalid_grade_category_weight"
                android:visibility="gone"
                app:layout_constraintTop_toTopOf="parent"/>

            <!-- Constraint layout_constraintHeight_max dynamically to 24% -->
            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/rvGradingCategories"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constrainedHeight="true"
                app:layout_constraintTop_toBottomOf="@+id/tvInvalidGradeWeightLayout" />

        </androidx.constraintlayout.widget.ConstraintLayout>

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/tvInfoNoData"
            style="@style/Default_Text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/text_no_data_display"
            android:visibility="visible"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.constraintlayout.widget.Barrier
            android:id="@+id/barrier"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:barrierDirection="bottom"
            app:constraint_referenced_ids="layoutGradeCategoryList" />

        <androidx.appcompat.widget.LinearLayoutCompat
            android:id="@+id/layout_adjust_weight"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/default_margin_size_16dp"
            android:orientation="horizontal"
            app:layout_constraintBottom_toTopOf="@+id/buttonSave"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/barrier"
            app:layout_constraintVertical_bias="0.01">

            <com.google.android.material.switchmaterial.SwitchMaterial
                android:id="@+id/switchViewAdjustWeight"
                style="@style/Default_Text_Bold"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_centerVertical="true"
                android:layout_marginEnd="@dimen/screen_padding_size"
                android:text="@string/text_adjust_weight"
                android:theme="@style/Theme.LMS"
                android:visibility="gone" />

        </androidx.appcompat.widget.LinearLayoutCompat>

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/default_margin_size_30dp"
            android:src="@drawable/ic_plus"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:tint="@color/white" />

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/buttonSave"
            style="@style/Primary_Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/default_margin_size_30dp"
            android:enabled="false"
            android:text="@string/text_save"
            android:visibility="gone"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

A: This worked for me, I added getViewTreeObserver().addOnGlobalLayoutListener for layoutGradeCategoryList and trigger the request layout there.
layoutGradeCategoryList.getViewTreeObserver().addOnGlobalLayoutListener(OnGlobalLayoutListener {
    layoutGradeCategoryList.requestLayout();
})

This helped me understand more on requestLayout/forceLayout/invalidate view.
https://stackoverflow.com/a/42430695/3777452
Hope this helps someone else.


text:
Q: Javascript -filtering object
I am trying to do something in pure JS.  I have an Object like so
var data = {
    "Something": true,
    "Something else": false,
    "Blah": false,
    "a fish ISA": true
};

What I want to do is filter anything which has true to its own Object.  At the moment I am trying
var thingFunctions = Object.keys(data).filter(function(e) {
    return typeof data[e] == 'function'
});

But I think this is incorrect.  How can I get the data with a value of true to its own Object?
Thanks

A: So firstly you have no functions inside data, so doing a check on functions will return nothing.
var data = {
    "Something": true,
    "Something else": false,
    "Blah": false,
    "a fish ISA": true
};

var thingFunctions = Object.keys( data ).filter(function( e ) {
    return data[ e ] === true;
});

console.log( thingFunctions );

// Will result in [ 'Something', 'a fish ISA' ]

A: You were asking for an object.
I use Array.prototype.forEach() for the iteration over the keys and an empty object for the result filtered, because I can not filter objects:

var data = {
        "Something": true,
        "Something else": false,
        "Blah": false,
        "a fish ISA": true
    },
    filtered = {};

Object.keys(data).forEach(function(e) {
    if (data[e] === true) {                      // explicit testing for boolean and true!
        filtered[e] = data[e];
    }
});

document.write('<pre>' + JSON.stringify(filtered, 0, 4) + '</pre>');

A: As you want to only have all true value we can convert them to true false values by doing the following.
!!({}) // true
!!([]) // true
!!('') // false
!!(true) // true
!!(false) // false
...

With this we can see if any data type is true or false by doing the following.
var thingFunctions = Object.keys(data).filter(function(e) {
    return !!(data[e]);
});

A: To get a new object instead of just an array of the keys that point to a value of true (not truthy such as 1 or "hello"):
var onlyTrues = {};

for (var prop in data) {
  if (data[prop] === true) {
    onlyTrues[prop] = data[prop];
  }
}


text:
Q: Camel Csv read store data to sql I need to read CSV file and than i need to store all data in one table.
public static DataSource setupDataSource(String connectURI) {
    String url = "jdbc:mysql://127.0.0.1:3306/ams";
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUsername("root");
    ds.setPassword("root");
    ds.setUrl(connectURI);
    return ds;
}

public static void main(String[] args) throws Exception {
    String url = "jdbc:mysql://127.0.0.1:3306/ams";
    DataSource dataSource = setupDataSource(url);

    SimpleRegistry reg = new SimpleRegistry();

    reg.put("dataSource", dataSource);

    CamelContext context = new DefaultCamelContext(reg);

    String myString = " <route id=\"UserCSVToMYSQL\"  xmlns=\"http://camel.apache.org/schema/spring\">"
            + "      <from uri=\"file:/home/viral/Projects/camel/cxfJavaTest/src/csvfiles?noop=true\" />"
            + " <log loggingLevel=\"DEBUG\" message=\"${body}\"/>"
            + "      <split  streaming=\"true\">"
            + "              <tokenize token=\"\n\" />"
            + "              <unmarshal>"
            + "                      <csv/>"
            + "             </unmarshal>"
            + "     <transform> "
            + "       <simple>${body[0]}</simple> "
            + "     </transform> "
            + " <log loggingLevel=\"DEBUG\" message=\"${body}\"/>"
            + "               <to uri=\"sql:INSERT INTO user(`external_user_id`,`first_name`,`last_name`,`email`,`active`) VALUES (#,#,#,#,#)?dataSourceRef=dataSource\"/> "
            + "       </split>   " + "               </route> ";

    InputStream is = new ByteArrayInputStream(myString.getBytes());
    RoutesDefinition routes = context.loadRoutesDefinition(is);
    context.addRouteDefinitions(routes.getRoutes());
    context.setTracing(true);

    context.start();

    Thread.sleep(16000);
    System.out.println("Done");
    context.stop();

}

you are able to see the code in which i have used
  + "       <transform> "
        + "       <simple>${body[0]}</simple> "
        + "     </transform> "

After executing this code it will store only 0 index row from csv. I need to store all raws from csv to sql table.
If any one know please provide  me solution for same.

A: You need to add an extra slash to properly escape the new line character in the tokenize part of the code , that is the only issue i see


text:
Q: Nitrous.io desktop fails to sync Nitrous Desktop fails to sync with "Error: connection failed". Even after restart, delete and generate new SSH keys. I moved everything at ~/workspace but it stills says the same. Any ideas?

A: If you are using Windows then you will want to ensure that the nitrous-ssh app is not being blocked by your Windows firewall. You should have been prompted about this when first enabling File Sync, but if you did not check these boxes when first connecting then you will want to locate it within your firewall settings and allow it on all networks.
You may also want to check that the port which Nitrous Desktop uses is not being blocked by your network. The port can be found within the SSH URI field on the boxes page:
https://www.nitrous.io/app#/boxes
The port # is at the end of the SSH URI.


text:
Q: UIScrollView custom paging distance I have a UIImage (Image's width is > 320px) in a UIScrollView (covers full width of screen) and want a paging effect.
All the tutorials/examples I found explain how to do it with multiple UIImages or UIVIews, but I only have 1 UIImage in the UIScrollView. My aim is it to create a 'tape measure' like effect. and the scrollview should 'page' on every marker of the tape?
How can I do the paging on distances less the the width of the UIScrollView?!

A: I can't think of a cleaner solution than doing the math on the fly. If the desired page length is 100px than "slide" the UIImage so that it stays relative to the actual page. So something akin to:
CGFloat pageWidth = 100;
int numPages = ceilf(myImageView.bounds.size.width / pageWidth);
scrollView.contentSize = CGSizeMake(numPages * scrollView.bounds.size.width,
                                  scrollView.bounds.size.height);

Then subclass the scroll view's layoutSubviews method:
- (void)layoutSubviews {
    int numPages = ceilf(myImageView.bounds.size.width / pageWidth);
    CGRect visibleBounds = [self bounds];
    CGFloat start = visibleBounds.origin.x;
    CGFloat offset = start / pageWidth;
    myImageView.frame = CGRectMake(offset, myImageView.frame.origin.y,
                                   myImageView.frame.size.width,
                                   myImageView.frame.size.height);
}

I haven't tested this at all but hopefully it gets you on a working track. What this should be doing is moving the image whenever you scroll so that it looks like each "page" only moves the image 100px.


text:
Q: Using Laplace transforms to solve a convolution of two functions Hi I have this problem where I need to take the convolution of functions and I am not sure if I got the right answer or something close so any advice or help would be very appreciated. So here is the problem.
$$t^{2} * e^{-2t}= L^{-1}(L(t^{2} * e^{-2t}))$$
$$=L^{-1}(L(t^{2}) \cdot L(e^{-2t}))$$
Which is:
$$=L^{-1}((\frac{2}{s^{3}})(\frac{1}{s+2}))$$
$$=L^{-1}(\frac{2}{(s^{3})(s+2)})$$
Then I did partial fractions to solve this:
$$\frac{2}{(s^{3})(s+2)}=\frac{A}{s} + \frac{B}{s^{2}} + \frac{C}{s^{3}} + \frac{D}{s+2}$$
Then I solved for the unknown coefficients and got this:
$$\frac{2}{(s^{3})(s+2)}=\frac{1}{s} - \frac{1}{s+2}$$
Then we take the inverse Laplace transform of this:
$$L^{-1}(\frac{1}{s} - \frac{1}{s+2})= 1- e^{-2t}$$
So my answer would be that $$t^{2} * e^{-2t}= 1- e^{-2t}$$
Now I am not sure if this is the correct answer or the most efficient way of solving a problem like this so any advice/help would be greatly appreciated.
Thanks!

A: Your approach is good. Using Laplace Transforms followed by Partial Fractions is probably the best way to solve this problem. (The next easiest way would be to evaluate $\int_{0}^{t}(t-\tau)^2e^{-2\tau}\,d\tau$).
When doing the partial fractions, you should have gotten:
$\dfrac{2}{s^3(s+2)} = \dfrac{\tfrac{1}{4}}{s} - \dfrac{\tfrac{1}{2}}{s^2} + \dfrac{1}{s^3} - \dfrac{\tfrac{1}{4}}{s+2}$.
Check your work on that step.


text:
Q: How to obtain the line numbers of executable lines from DWScript context map or symbol table I am writing an IDE to use with Delphi DWScript and now have a simple debuggable script. I now want to highlight the executable lines in my source (like the blue dots at the left of the Delphi source). Digging for examples / information I see that there is a program 'SymbolDictionary' where I can call 'FindSymbolUsage( suReference)' - this seems to give me positions of symbols 'being referred to', and I guess I could call this again with 'suImplementation' to get the lines where there is an assignment. This has made me realise though that I could do with understanding what the structure and purpose of the ContextMap and the SymbolDictionary actually are. Does anyone have an example of listing the executable line numbers of the script?
My fledgling code is reproduced below and is awaiting critical analysis :-)
Thanks
  TExecutableLines = class( TObject )
    constructor Create;
    destructor  Destroy; override;
  PRIVATE
    FLines : TBits;
    function GetIsExecutable(ALineNumber: integer): boolean;
    procedure SetIsExecutable(ALineNumber: integer; const Value: boolean);
  PUBLIC
    procedure Clear;

    procedure Evaluate( AProgram : IdwsProgram; const AUnitName : string );

    property  IsExecutable[ALineNumber : integer] : boolean
                read GetIsExecutable
                write SetIsExecutable;
  end;

{ TExecutableLines }

procedure TExecutableLines.Clear;
begin
  FLines.Size := 0;
  FLines.Size := 1024;
end;

constructor TExecutableLines.Create;
begin
  inherited;

  FLines := TBits.Create;
end;

destructor TExecutableLines.Destroy;
begin
  FreeAndnil( FLines );
  inherited;
end;

procedure TExecutableLines.Evaluate(AProgram: IdwsProgram; const AUnitName : string);
var
  I : integer;
  Pos : TSymbolPosition;
begin
  Clear;
  For I := 0 to AProgram.SymbolDictionary.Count-1 do
    begin
    Pos := AProgram.SymbolDictionary.FindSymbolPosList(
      AProgram.SymbolDictionary[I].Symbol ).FindUsage( suReference);
    if Pos <> nil then
      If Pos.ScriptPos.IsMainModule then
        IsExecutable[ Pos.ScriptPos.Line ] := True
       else
         if SameText( Pos.UnitName, AUnitName ) then
            IsExecutable[ Pos.ScriptPos.Line ] := True
    end;

end;

function TExecutableLines.GetIsExecutable(ALineNumber: integer): boolean;
begin
  if ALineNumber = 0 then
    raise Exception.Create('Lines numbers are 1..n' );

  if ALineNumber < FLines.Size then
    Result := FLines[ALineNumber]
   else
     Result := False;
end;

procedure TExecutableLines.SetIsExecutable(ALineNumber: integer;
  const Value: boolean);
begin
  if ALineNumber = 0 then
    raise Exception.Create('Lines numbers are 1..n' );

  if ALineNumber >= FLines.Size then
    FLines.Size := ALineNumber+1;
  FLines[ALineNumber] := Value;
end;

A: The TdwsSymbolDictionary serves a different purpose, mostly knowing where (if) a symbol is declared or used, as well as easing up things like rename refactoring (see http://delphitools.info/2011/02/19/spotlight-on-tsymboldictionary/).
The TdwsSourceContextMap serves to know where in the source code, code "blocks" are (f.i. where a class declaration starts and ends, where function implementation starts and ends, etc.), it's both useful to "jump" to a position in code, or to know where the cursor is in terms of symbols.
What you're after is yet another info, it's what lines correspond to compiled expressions. For that you need to look at what is compiled, TExprBase.SubExpr/SubExprCount are your workhorses, or the utility function that wraps them RecursiveEnumerateSubExprs. With that function you can look at all the expressions in your program, start from TdwsProgram.Expr and TdwsProgram.InitExpr (you can cast the IdwsProgram to a TdwsProgram to get at those properties).
These are where you can have breakpoints.
As an illustration, suppose you have
1.   function Dummy : Integer;
2.   var i : Integer;
3.   begin
4.      while i<10 do begin
5.         Inc(i);
6.         if i>5 then
7.            break;
8.      end;
9.   end;

Then if I'm not mistaken (doing this out of the blue):

*

*The symbol dictionary will list a declaration of "Dummy" at 1, a
usage of "Integer" at 1 & 2, a declaration of "i" at 2, a usage of "i" at
4, 5 & 6.

*The context map will have a block for the function, the main block
and the while loop.

*The lines with compiled expressions will be 2 (.InitExpr) and 4, 5,
6 & 7 (.Expr)


text:
Q: how to scroll a listview in android using appium? I used the following statement to scroll .
  @driver.scroll_to_exact('Text').click

I got the following error
Selenium::WebDriver::Error::WebDriverError:unexpected response, code=404, content-type="text/plain"That URL did not map to a valid JSONWP resource
I tried using the following statement
     b=find_element(:id,'com.dddd.main:id/calenderListView')
     @driver.execute_script 'mobile: scrollTo', :element => b.ref`

I was able to scroll till the end of the list view .But got the following error after scrolling to end of listview
  Failure/Error: @driver.execute_script 'mobile: scrollTo', :element => b.ref
 Selenium::WebDriver::Error::UnknownError:
   Could not scroll element into view: null
 # ./test.rb:68:in `block (2 levels) in <top (required)>'

A: Hope this helps:
STEP:
Given(/^I scroll down/) do
element = find_element :xpath, "//YOUR_ELEMENT_HERE']"
execute_script 'mobile: scrollTo', :element => element.ref
end

FEATURE:
Given I scroll down

You don't have to use xpath to locate element, if you have id or name it would be better choice


text:
Q: Replace existing MVC project with angular 2 app It sounds a bit strange, but I will explain what I want to do.
I currently have an MVC website written in C# that is using Razor Views. In the same project I added an API which I can access like this : www.mysite.com/api/controller/get.
Normal pages can be accessed simply by www.mysite.com/controllername/index.
Now the problem is I recreated the website with angular 2, and now I need to publish the site online, I mean completely replace the mvc project.
My solution 1 is to separate the angular app and the api: So, I publish the angular web site on www.mysite.com and publish the api on api.mysite.com.
Solution 2?: I was wondering if it was possible to simply replace the MVC part of my current project by the angular 2 app? So everything stays on the same domain. (aka same project)
Edit:
If solution 2 is possible: how do you include the angular 2 app inside the project without routes conflicting with the mvc project. In other words, I want to remove the MVC routes.

A: So I ended up going for solution #2.
Turns out to be easier than I thought.
This is what I did:

*

*Create a folder in the project named whatever eg: "app"

*Run ng-build and put the build files inside this folder.

*Create a controller that will act as a wrapper to the application. Mine was AppController

*Add this code inside the controller :
public ActionResult Index()
{
    return new FilePathResult("~/app/index.html", "text/html");
}

*We now need to handle routes. Go in RoutesConfig.cs and make sure you have this in RegisterRoutes
   routes.MapRoute(
      name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "App", action = "Index", id = UrlParameter.Optional }
    );

*Now you need to edit your angular's index.html by changing the "base href" to this : base href="/app/" (This is because the root of the angular project is inside the folder app that you created earlier.)

*Now here is the tricky part, if you run it, it will work, but you will quickly notice that you can't copy and paste your url without having an error. However, we were blessed to have UrlRewrite!
Go to your app folder and create a Web.config if you haven't already.

*Here is what is inside the Web.config file located inside the app folder.
<?xml version="1.0"?>
 <configuration>
  <system.web>
   <compilation debug="true" targetFramework="4.0"/>
  </system.web>

  <system.webServer>
   <rewrite>
   <rules>
    <rule name="Angular Routes" stopProcessing="true">
     <match url=".*" />
      <conditions logicalGrouping="MatchAll">
      <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
      <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
     </conditions>
     <action type="Rewrite" url="/app/" />
     </rule>
   </rules>
  </rewrite>
 </system.webServer>
</configuration>

This will even ignore the pattern site.com/api, so your api calls will still work! Also, the magic here is the line with action type="Rewrite" url="/app/" this will fix the problem of not being able to copy paste your links. Finally, if you have mvc controllers and you try to access them, it will still work.
Voila.

A: Yes, you can replace ASP.NET MVC code with an Angular site that utilizes Web API calls. As you have suspected; the ASP.NET MVC routes will take precedence over any angular ones.
The main thing to do is make sure you have static file serving set up so your web server will send the appropriate javascript and html files to the server. That should at least get your angular app bootstrapping.
The other import thing to do is use the "#" style of routing in angular. MVC doesn't use these routes so they always get passed on to angular. Its possible to configure the router to pass on "normal" routes to angular but this approach tends to be easier.


text:
Q: my mailserver is not responding when I send a ehlo localhost I tried to make a mailserver with this tutorial
I work with Ubuntu Server 16.04
Executing the testing part doesn't provide any respond from my local mailserver (when I send a ehlo localhost message).
What did I do wrong ?


text:
Q: Clip-path in IE11 I'm trying to draw a star using clippath, but the shape appears as a simple square in IE11. Is there any solution to this?
https://jsfiddle.net/sleepydada/mh4bcbcf/
HTML:

<svg id="svg-defs">
  <defs>
    <clipPath id="clip-triangle" clipPathUnits="objectBoundingBox">
      <polygon points=".5 0, .65 .35, .98 .35, .69 .58, .79 .91, .5 .7, .21 .91, .28 .56, .02 .35, .34 .35" />
    </clipPath>
  </defs>
</svg>

CSS:
body {
  background-color: #e0e0e0;
}

#image-wrapper {
  position: relative;
  background: black;
  clip-path: url(#clip-triangle);
  width: 210px;
  height: 210px
}

.background {
  position: absolute;
  top: 5px;
  left: 5px;
  width: 200px;
  height: 200px;
  background: white;
  clip-path: url(#clip-triangle);
}


text:
Q: Is it possible to only target content between ::before and ::after when using CSS? I do not have access to the JavaScript or HTML, only the CSS.
I am trying to change the text that is already there, to something else.

#element::before {
  content: "This is the new text."
}

This is the original text.

Is it possible to target the old text specifically with CSS, to then maybe apply text-indent: -9999px;?

A: It is not possible to specifically target the text node of an element; see Is there a CSS selector for text nodes? for more information.
You could achieve the effect you are after in a variety of ways, although as Paulie_D suggests, whether this is a good idea depends on what you are trying to achieve.

#element {
    visibility: hidden;
}
#element:before {
    content:"My new text using visibilty.";
    visibility: visible;
}
#element2 {
    font-size: 0;
}
#element2:before {
    content:"My new text using font-size.";
    font-size: 16px;
}

This is the original text.

This is the original text.

A: The short answer is: no, you cannot use CSS to target the text within the element independently of the content of the pseudo elements.
However, you can create a work around by pasting the content of the pseudo element over the original
content and thus hide it.
Note: This approach uses absolute positioning so it may created issues if the pseudo-element
content is excessively long.
Better Approach: An alternative approach is to use the visibility property to hide the main content of the
element but make visible the content from the pseudo-elements (credit to Hidden-Hobbes).

#element::before {
  content: "My new text.";
  display: block;
  color: black;
  position: absolute;
  background-color: yellow;
  width: 100%;
}
#element {
  color: red;
  position: relative;
}
#element-alt::before {
  content: "My new alt-text.";
  border: 1px dotted blue;
  visibility: visible;
  display: block;
}
#element-alt {
  border: 1px dotted gray;
  margin-top: 30px;
  visibility: hidden;
}

This is the original text.

This is the original text.


text:
Q: Zuul Gateway No redirecting to client server I have configured a zuul server with a single client application.
But when I hit the URL with Zuul Gateway , it does not redirect to the client service and gives the error
2022-08-21 19:25:39.120+0200 [http-nio-8080-exec-1] DEBUG o.s.w.servlet.DispatcherServlet - GET "/asd", parameters={}
2022-08-21 19:25:39.120+0200 [http-nio-8080-exec-1] DEBUG o.s.w.s.h.SimpleUrlHandlerMapping - Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2022-08-21 19:25:39.121+0200 [http-nio-8080-exec-1] DEBUG o.s.w.s.r.ResourceHttpRequestHandler - Resource not found
2022-08-21 19:25:39.121+0200 [http-nio-8080-exec-1] DEBUG o.s.w.servlet.DispatcherServlet - Completed 404 NOT_FOUND
2022-08-21 19:25:39.122+0200 [http-nio-8080-exec-1] DEBUG o.s.w.servlet.DispatcherServlet - "ERROR" dispatch for GET "/error", parameters={}
2022-08-21 19:25:39.123+0200 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2022-08-21 19:25:39.123+0200 [http-nio-8080-exec-1] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Found key 'spring.template.provider.cache' in PropertySource 'configurationProperties' with value of type String
2022-08-21 19:25:39.127+0200 [http-nio-8080-exec-1] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Found key 'spring.template.provider.cache' in PropertySource 'configurationProperties' with value of type String
2022-08-21 19:25:39.131+0200 [http-nio-8080-exec-1] DEBUG o.s.w.s.v.ContentNegotiatingViewResolver - Selected 'text/html' given [text/html, text/html;q=0.8]
2022-08-21 19:25:39.131+0200 [http-nio-8080-exec-1] DEBUG o.s.w.servlet.DispatcherServlet - Exiting from "ERROR" dispatch, status 404

My Zuul Server config ( application.yml)
server:
  port: 8080

zuul:
  routes:
    client-service:
      path: /asd/**
      #      url: http://localhost:8081/home
      url: http://localhost:8081/login

My Client Service Config :
server:
  port: 8081

spring:
  application:
    name: client-service

Controller in Client Service
@RestController
@RequestMapping("/login")
public class LoginController {

    @GetMapping
    public String findAll() {
        return "simple login get method method";
    }
}

Result when hit the client service endpoint ( client service directly )
Endpoint : http://localhost:8081/login
Result : simple login get method method

Result when hit the endpoint ( via gateway )
Endpoint : http://localhost:8080/asd
Result : Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Aug 21 19:30:45 CEST 2022
There was an unexpected error (type=Not Found, status=404).
No message available

A: I guess you missed enabling the zuul proxy on gateway server
@EnableZuulProxy


text:
Q: Swift: cannot convert value of type 'GameScene' to expected argument type 'UIViewController!' I am trying to load an admob interstitial ad in my app when the users lost but i can't because i am using spritekit (swift), here's my code:
 self.interstitial.presentFromRootViewController(interstitial)

and here's my error:
cannot convert value of type 'GameScene' to expected argument type 'UIViewController!'

Hope one of you has the answer! thx

A: You're trying to present interstitial from itself.
You should present it from a ViewController which is currently visible:
self.interstitial.presentFromRootViewController(self)

(supposed that self is a View Controller).
Update:
If you follow Google tutorial attentively, you will see there exactly what I'm talking about:
func gameOver() {
  if self.interstitial.isReady {
    self.interstitial.presentFromRootViewController(self)
  }
  // Rest of game over logic goes here.
}


text:
Q: Set autofocus => true in custom_fields added on devise I've added 2 new fields on my devise users: :first_name and :last_name
So in the registration page I've added these new fields to be filled by user.

    <%= f.label :first_name %>

    <%= f.text_field :first_name, autofocus => true %>

    <%= f.label :last_name %>

    <%= f.text_field :last_name %>

<%= f.label :email %>

  <%= f.email_field :email %>

<%= f.label :password %>

  <%= f.password_field :password %>

<%= f.label :password_confirmation %>

  <%= f.password_field :password_confirmation %>

Initially the autofocus was set on :email field, but now I changed to :first_name field.
The problem is when I access this page i get this error:
undefined local variable or method `autofocus' for #<#<Class:0x361ef18>:0x449d630>

What forgot I to do in my rails app?

A: You forgot the : before the autofocus symbol, change it to:
<%= f.text_field :first_name, :autofocus => true %>

A: it should be :autofocus and not autofocus
<%= f.text_field :first_name, :autofocus => true %>

The colon : is missing at the start, should be a symbol, else its treated as if local variable/assign.


text:
Q: The geometry behind adjoint of a linear transformation I was going through friedberg section 6.3 where they have introduced the term adjoint of a linear transformation. My basic question is what does it mean to have an adjoint of a linear transformation geometrically (just like we can imagine transformation as an operation on a vector which can rotate the vector or increase or decrease it's length) and why is it important to know?

A: It is helpful to first consider the adjoint of a linear transformation $T: V \to V$ for an arbitrary vector space $V$.  Since we cannot use an inner product, the adjoint $T': V^* \to V^*$ is defined on the dual space instead, and takes a linear functional $f: V \to \mathbb{R}$ to the linear functional $T' f = f \circ T$ (in words, $f$ precomposed by $T$). Linear functionals can be thought of as coordinate functions, for example on $V = \mathbb{R^2}$ we have the functionals $x, y : \mathbb{R}^2 \to \mathbb{R}$ which read off the first and second entries in a vector respectively. I imagine a functional as a series of parallel hyperplanes, the solutions to $f(v) = \ldots -1, 0,1,2,\ldots$. Scaling $f$ to be larger will make the hyperplanes closer together.
We have $x(Tv) = (T'x)(v)$ for all vectors $v\in \mathbb{R}^2$ (by definition of the adjoint). This means that performing the transformation $T$ and then reading the $x$-coordinate is the same as just using the new functional $T'x$, which reads vectors "as if" they had already had $T$ applied to them. If $T$ is a scaling by 2 for instance, we are saying that $x(2v) = (2x)(v)$ - quite unsurprising, but treating $2x$ as a new object in its own right (the $x$ axis with double the number of ticks) can be quite useful, especially for more interesting operators $T$. For example, imagine you have a lot of vectors and you want to measure their $x$-coordinates before and after a rotation by 30°. One way would be to compute $x(v)$ and $x(Tv)$ for every vector, but another would be to compute $z = T'x$ once, and then compute $x(v)$ and $z(v)$ for every vector (much more efficient, requiring only dot products rather than matrix multiplications each time).
Finally, adjoints show up in inner product spaces, because there is a canonical bijection between vectors and linear functionals. To each vector $v$ we get a special linear functional $f_v(u) = (v, u)$, and for any linear transformation $T$ we can take the adjoint of $f_v$ as above, to get $(T' f_v)(u) = f_v(Tu) = (v, Tu)$. Define a bijection $T^*: V\to V$ by the condition that $T'f_v = f_{T^* v}$, then it turns out that $T^*$ is linear, and moreover is the unique linear map such that $(T^* v, u) = (v, Tu)$ for all $u,v \in V$.
The adjoint in inner product spaces holds the same meaning as before: if $(u, -)$ is a "coordinate function", then applying $T$ and measuring to get $(u, Tv)$ is the same as first applying $T^*$ to the coordinate function and then measuring to get $(T^* u, v)$. The significance is that since $T^*$ is now an operator on the original space (rather than the dual space), we can ask lots of interesting questions about how $T$ relates to its adjoint $T^*$.


text:
Q: When deployed on lambda, AWS Textract doesn't return 'LINE' or 'WORD' blocks, only 'PAGE' blocks My function works well when it runs locally and invokes Textract OCR, here is the output:
{'DocumentMetadata': {
'Pages': 1},
'JobStatus': 'SUCCEEDED',
'Blocks': [
{'BlockType': 'PAGE', 'Geometry': {'BoundingBox': {'Width': 1.0, 'Height': 1.0, 'Left': 0.0, 'Top': 0.0}, 'Polygon': [{'X': 1.956095047717099e-06, 'Y': 0.0}, {'X': 1.0, 'Y': 1.9269275526312413e-06}, {'X': 1.0, 'Y': 1.0}, {'X': 0.0, 'Y': 1.0}]}, 'Id': 'e3517e8d-3eb1-4c7a-8ffe-f4f4f40bd923', 'Relationships': [{'Type': 'CHILD', 'Ids': ['3261bf02-d63c-4016-a5b2-a437308de18d']}], 'Page': 1},
{'BlockType': 'LINE', 'Confidence': 99.86868286132812, 'Text': 'John Doe Is', 'Geometry': {'BoundingBox': {'Width': 0.14190037548542023, 'Height': 0.013485041446983814, 'Left': 0.09458228200674057, 'Top': 0.06803429871797562}, 'Polygon': [{'X': 0.0945969745516777, 'Y': 0.06803429871797562}, {'X': 0.2364826500415802, 'Y': 0.06828282028436661}, {'X': 0.2364688366651535, 'Y': 0.08151934295892715}, {'X': 0.09458228200674057, 'Y': 0.08127062022686005}]}, 'Id': '3261bf02-d63c-4016-a5b2-a437308de18d', 'Relationships': [{'Type': 'CHILD', 'Ids': ['d6c105b6-2e5b-425c-bc2d-fda9c4ed1815', '223fbbe4-9a0c-4a26-8947-04bb7e535139', '1bc8b80b-4e35-4815-9843-ac901852e720']}], 'Page': 1},
{'BlockType': 'WORD', 'Confidence': 99.84158325195312, 'Text': 'John', 'TextType': 'PRINTED', 'Geometry': {'BoundingBox': {'Width': 0.05469386279582977, 'Height': 0.013332170434296131, 'Left': 0.09458228200674057, 'Top': 0.06803429871797562}, 'Polygon': [{'X': 0.0945969745516777, 'Y': 0.06803429871797562}, {'X': 0.14927615225315094, 'Y': 0.06813007593154907}, {'X': 0.14926178753376007, 'Y': 0.08136647194623947}, {'X': 0.09458228200674057, 'Y': 0.08127062022686005}]}, 'Id': 'd6c105b6-2e5b-425c-bc2d-fda9c4ed1815', 'Page': 1},
{'BlockType': 'WORD', 'Confidence': 99.9034652709961, 'Text': 'Doe', 'TextType': 'PRINTED', 'Geometry': {'BoundingBox': {'Width': 0.02554963529109955, 'Height': 0.01002489123493433, 'Left': 0.15451456606388092, 'Top': 0.0688563659787178}, 'Polygon': [{'X': 0.15452536940574646, 'Y': 0.0688563659787178}, {'X': 0.18006420135498047, 'Y': 0.06890109926462173}, {'X': 0.18005351722240448, 'Y': 0.07888125628232956}, {'X': 0.15451456606388092, 'Y': 0.07883650064468384}]}, 'Id': '223fbbe4-9a0c-4a26-8947-04bb7e535139', 'Page': 1},
{'BlockType': 'WORD', 'Confidence': 99.86099243164062, 'Text': 'Is', 'TextType': 'PRINTED', 'Geometry': {'BoundingBox': {'Width': 0.05028943344950676, 'Height': 0.010319724678993225, 'Left': 0.1861930638551712, 'Top': 0.06834923475980759}, 'Polygon': [{'X': 0.1862039864063263, 'Y': 0.06834923475980759}, {'X': 0.23648250102996826, 'Y': 0.06843730062246323}, {'X': 0.23647181689739227, 'Y': 0.07866895943880081}, {'X': 0.1861930638551712, 'Y': 0.0785808339715004}]}, 'Id': '1bc8b80b-4e35-4815-9843-ac901852e720', 'Page': 1}],
'DetectDocumentTextModelVersion': '1.0', 'ResponseMetadata': {'RequestId': 'b6179e12-c603-4a2b-8a4f-171e5c722756', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'b6179e12-c603-4a2b-8a4f-171e5c722756', 'content-type': 'application/x-amz-json-1.1', 'content-length': '2571', 'date': 'Tue, 18 Oct 2022 13:34:52 GMT'}, 'RetryAttempts': 0}}

But when I deploy the calling function on lambda, the OCR only returns:
{'DocumentMetadata':
{'Pages': 1},
'JobStatus': 'SUCCEEDED',
'Blocks': [
{'BlockType': 'PAGE', 'Geometry': {'BoundingBox': {'Width': 1.0, 'Height': 1.0, 'Left': 0.0, 'Top': 0.0}, 'Polygon': [{'X': 3.7998024282615006e-08, 'Y': 0.0}, {'X': 1.0, 'Y': 0.000705239363014698}, {'X': 1.0, 'Y': 1.0}, {'X': 0.0, 'Y': 0.9995841383934021}]}, 'Id': '6a2b1917-731e-49ae-8620-2b61c3e75cf8', 'Page': 1}],
'DetectDocumentTextModelVersion': '1.0', 'ResponseMetadata': {'RequestId': 'cbe6c3b8-c60f-4990-b771-0620a2d08bd4', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'cbe6c3b8-c60f-4990-b771-0620a2d08bd4', 'content-type': 'application/x-amz-json-1.1', 'content-length': '388', 'date': 'Tue, 18 Oct 2022 13:09:08 GMT'}, 'RetryAttempts': 0}}

Here is my ocr code:
def InvokeTextDetectJob(s3BucketName, objectName):
    response = None
    client = boto3.client('textract')
    response = client.start_document_text_detection(
        DocumentLocation={
            'S3Object':{
                'Bucket': s3BucketName,
                'Name': objectName}})
    return response['JobId']

def CheckJobComplete(jobId):
    time.sleep(5)
    client = boto3.client('textract')
    response = client.get_document_text_detection(JobId=jobId)
    status = response['JobStatus']
    print('Job status: {}'.format(status))
    while(status == 'IN_PROGRESS'):
        time.sleep(5)
        response = client.get_document_text_detection(JobId=jobId)
        status = response['JobStatus']
        print('Job status: {}'.format(status))
    return status

def JobResults(jobId):
    pages = []
    client = boto3.client('textract')
    response = client.get_document_text_detection(JobId=jobId)
    pages.append(response)
    print('resultset page received: {}'.format(len(pages)))
    nextToken = None
    if 'NextToken' in response:
        nextToken = response['NextToken']
    while(nextToken):
            response = client.get_document_text_detection(JobId=jobId, NextToken=nextToken)
            pages.append(response)
            nextToken = None
            if 'NextToken' in response:
                nextToken = response['NextToken']
    return pages

def OCR_V2(pdf, bucket_name):
    s3 = boto3.resource("s3")
    random_name = get_random_string(10) + ".pdf"
    s3.Bucket(bucket_name).upload_fileobj(pdf, random_name)
    jobId = InvokeTextDetectJob(bucket_name, random_name)
    if(CheckJobComplete(jobId)):
        response = JobResults(jobId)
        final_response = []

        for resultPage in response:
            if 'Blocks' in resultPage.keys():
                for item in resultPage["Blocks"]:
                    if item["BlockType"] == "LINE":
                        final_response.append(item['Text'])
        return ' '.join(final_response)

When fastapi runs locally it works and when the server runs on Lambda, wether I call it from a frontend interface or from the swagger interface, I still only get an incomplete return from the OCR. I've added the full S3 and Textract permissions on the lambda role.


text:
Q: Is it possible to install two MFP servers on one machine? I was wondering if its possible to set up two MFP servers on one machine?
Use one for testing and one for staging(kind of a pre-production).
I found a on IBM docs that they describe how to run multiple servers in MFP studio, but can't seem to find anything multiple MFP servers on WebSphere  Application Server liberty Profile (WAS-LP).
If it is possible, does it require a second installation:
2nd WAS-LP +
2nd MFP +
Create 2nd MFP server +
Install 2nd Appcenter
New config and
A runtime?
with it's own database ? or just tables? with custom names.

Or would it be better to have a single instance of WAS-LP and the Appcenter
and simply create a new config call it dev? and add runtimes.
Many thanks

A: Each Liberty Profile instance, that is each server.xml, is independent, with its own set of working directories. You are (cough) at liberty to run several different servers for different purposes, starting and stopping them independently - this is why the
server start <servername>

takes that servername parameter. You do, of course, need to take care that the servers do not clash, they must be configured to use their own ports, working directories etc.
When deploying MFP/Worklght to a specific server you specify some MFP specific configuration, add WAR files etc. You can reasonably set up completely different MFP servers, perhaps running different versions of your application for different testing phases. In my case I wanted to explore some clustering behaviours and set up two servers as part of of a cluster, not a realistic scenario for production but useful for my testing as I only have one computer. This allowed me to configure a MFP server farm both of whose members happened to be on the same machine. In fact we went further and also ran one MFP server and two analytic server instances all on the same machine.

A: Theoretically, it should be possible to have a single WAS LP installation with 2 server.xml's that you will swap between them. This single application server will have the various .war files and other resources of both MFP servers and its artifacts deployed. To me, this is kinda dirty and not as-easy to manage.
You could also have two separate WAS LP installations, each with its own setup.
For the sake of sanity and clearness, I would opt to having two application server installations. But that's really a personal preference thing.


text:
Q: MVC how to cast long into string in ViewData Dropdownlist ViewData["dropDown_ViewOwnerShare"] = correspondingDropDownValue.Select(j => new SelectListItem { Text = j.ListOfValue, Value = j.ListOfValue, Selected = j.ListOfValue == x.DefaultValue }).ToList();

Base on the above code, the viewdata["dropDown_e"] which is a dropdownlist successfully been generated. And now for each of the element, instead of using j.ListOfValue as Value, I want to use j.UserID as Value. Problem is j.UserID is a long type returned from database and Value is always expecting a string. I've tried j.UserID.ToString() but it has compile error. May I know how should I handle it?

A: What is a type of correspondingDropDownValue? Suppose it's IQueryable<T>, right? At first, you need to get all required fields from the database, then cast result to IEnumerable<T> and only then - create SelectListItems list. Something like this:
    correspondingDropDownValue
    .Select(j => new {Value = j.UserID, Text = j.SomeTextField}) // SELECT UserID, SomeTextField FROM SomeTable
    .AsEnumerable()       // Evaluate the query
    .Select(j => new SelectListItem // Work with in-memory objects using LINQ to Objects instead of LINQ to Entities
    {
        Value = j.Value.ToString(),
        Text = j.Text,
        Selected = j.Value == x.DefaultValue
    })
    .ToList()


text:
Q: Recuperar tiempo de respuesta de una peticion web dentro de un catch Antes de nada, gracias por la ayuda que me podáis prestar.
Vale, primero, disculpad mi pocos conocimientos, estoy aprendiendo, así que perdonad mi ignorancia.
Tengo un método  que llama a un servicio, y se supone que si se recibe alguna respuesta distinta del rango de 200, se va al catch. Pues bien, necesito, dentro de ese catch, recuperar de la cabecera (o de algún sitio) de esa respuesta el tiempo que ha tardado el servicio en responder.
No puedo usar timer ni cosas así (fue lo que primero en lo que pensé).
La cosa es que no se como recuperar de la exepcion este dato.
Muchas gracias!
        {
            try
            {
                // Reading the http response
                using (HttpWebResponse webResponse = httpWebRequest.GetResponse() as HttpWebResponse)
                {

                   /////   Llamada al endpoint

                }
            }
            catch (WebException ex)
            {
                  //// Aquí necesito recuperar el tiempo que ha tardado el servicio en responder (con el error)
            }
            return response;
        } ```

A: Te propongo la siguiente solución
try
{
    var tiempoInicial = Datetime.Now;
    using(....)
    {
        //Tu código
    }
}
catch(....)
{
    var tiempoFinal = DateTime.Now;
    var tiempoTranscurrido = tiempoFinal - tiempoInicial;
}

Bueno aquí lo que se hace es que antes de crear el objeto HttpWebResponse se guarda en una variable la hora de ese momento, te aclaro que este tiempo lo puedes obtener en la parte del código que más te convenga. Posteriormente si se produce la excepción se guarda en otra variable la hora de ese momento, entonces se resta con el tiempoInicial previamente guardado, esta diferencia de tiempos tiene el formato de horas:minutos:segundos:milisegundos, Si quisieras después esta diferencia la podrías mostrar mediante un mensaje o lo que desees, de esta forma vas a saber el tiempo transcurrido con una exactitud increíble

A: Yo voy a responder mi pregunta con otra solución:
var watch = System.Diagnostics.Stopwatch.StartNew();
try
{
    var request = WebRequest.Create("http://www.google.com");
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        using (Stream answer = response.GetResponseStream())
        {
            // do something
            watch.Stop();
            Console.WriteLine($"Success at {watch.ElapsedMilliseconds}");
        }
    }
}
catch (WebException e)
{
    // If we got here, it was a timeout exception.
    watch.Stop();
    Console.WriteLine($"Error occurred at {watch.ElapsedMilliseconds} \n {e}");
}

Creo que el watch es ideal para esto.


text:
Q: Symfony 2.8/3.0 upgrade: how to deal with form types with variable parameters? Let's say I create custom form types as services, as it is described in the Symfony documentation. But I want 2 "gender" custom types, with 2 different input parameters, which I was doing like this in Symfony 2.7:
# app/config/config.yml
parameters:
    genders1:
        m: Male
        f: Female
    genders2: # This makes no sense at all, but it is for the example purpose!
        h: Horse
        t: Turtle

And then, I was declaring 2 services like this:
<!-- src/AppBundle/Resources/config/services.xml -->
<service id="app.form.type.gender1" class="AppBundle\Form\Type\GenderType">
    <argument>%genders1%</argument>
    <tag name="form.type" alias="gender1" />
</service>

<service id="app.form.type.gender2" class="AppBundle\Form\Type\GenderType">
    <argument>%genders2%</argument>
    <tag name="form.type" alias="gender2" />
</service>

As you can see, I was using the same GenderType class for 2 custom form types (with the gender1 and gender2 aliases), which I could use like this:
$builder
    ->add('field1', 'gender1')
    ->add('field2', 'gender2');

This allowed me to add some common logic in only one class (GenderType) with different input parameters (I have many more possibilities than 2 in this example).
But as of Symfony 2.8, adding a field using the service alias is deprecated. The class name has to be passed as the second argument instead, like this:
$builder->add('field1', GenderType::class)

So how can I make the difference between my 2 services (each of them not having the same input parameters)?
Creating Gender1Type and Gender2Type extending an abstract GenderType class would be really painful, as I would have to create a lot of classes with empty content.
Do you have any idea on how to implement my pattern in Symfony 2.8, keeping services with different input parameters, but not creating a lot of classes?

A: Well, after digging this topic a bit more, someone already asked the question directly in the PR concerning this change in Symfony 2.8.
And the answer is that the pattern I was doing is not possible anymore, so I see 2 solutions to my problem:

*

*Create as many classes as I had services for my custom types instead of using all the time the same class, and make these classes extend an abstract one (in my example: create Gender1Type and Gender2Type classes that extend a AbstractGenderType abstract class)

*Keep only one class, but add options to it to pass my specific parameters.


text:
Q: Trouble displaying documents from firestore with a React js frontend Hi I'm relatively new to React js and I'm trying to create a mapping app where users can find a saved farm by searching for it using a search function. So far I can get the results of my queries in firestore ([Database][1]) by console.log and also by displaying this information as a Json object (output of data). I'd really like to just display the locality and the coordinates of the farm but haven't managed to be able to pull just those things out. I have tried data.id and data.locality but it doesn't work. Not sure where I'm going wrong, any help would be much appreciated thanks. Here is my code:
`
import React from 'react'
import { connect } from 'react-redux'
// import ProjectList from './ProjectList'
import { compose } from 'redux'
import { firestoreConnect } from 'react-redux-firebase'
import firebase from '../config/fbConfig'

const searchTerm = 'Methven'
const projRef = firebase.firestore().collection('projects')

let data

export function Trip4 () {
  const [data, setData] = React.useState([])
  const [title, setTitle] = React.useState('')

  React.useEffect(() => {
    projRef
      .where('locality', '==', `${searchTerm}`)
      .get()
      .then((snapshot) => {
        setData(snapshot.docs.map((doc) => ({
          id: doc.id,
          title: doc.data().title,
          content: doc.data().content,
          locality: doc.data().locality,
          ...doc.data()
        })))
        console.log('All data in *projects* collection in useEffect: ', data)
      })
    setTitle(JSON.stringify(data))
  }, [])
  return (

{console.log(`the output of data: ${data}`)}

          {
            JSON.stringify(data)
          }

  )
}

const mapStateToProps = (state) => {
  // console.log(state)
  return {
    projects: state.firestore.ordered.projects,
    auth: state.firebase.auth,
    profile: state.firebase.profile,
  }
}

export default compose(connect(mapStateToProps), firestoreConnect([{ collection: 'projects' }]))(Trip4)

`
EDIT : Based on Magnus' answer I found something which worked, slightly re-tweaked `

{console.log(`the output of data: ${data}`)}

          {data != undefined ? data.map((item) => (
{item.id + ' - ' + item.locality}
)) : null}

`

A: Try something like this:

{console.log(`the output of data: ${data}`)}

   {data != undefined ? data.map(item => {

{item.id + " - " + item.locality}

   }) : null}


text:
Q: CRM 2011 - Audit Settings do not overwrite correctly after deployment We have an existing issue with the Audit Setting on individual entities. When a managed solution is deployed from Dev environment to another, the 'Enable Audit' setting is turned off after the deployment (while the imported CRM soultion has the Enable Audit turned on for the corresponding entity). This only happens for a few entities.
Does anyone have any idea why this might occur ? and is there a way to fix this ? Please assist.
Thanks
Rajesh

A: This is one of the managed solution "gotchas" in crm 2011. Importing a managed solution that contains those entities will effectively turn off Auditing.
For verification, more info take a look here: http://blog.sonomapartners.com/2011/09/some-assembly-required-unmanaged-solution-gotchas.html
Quote: "What we found is that the Enable Auditing in the following areas checkboxes are transferred from one environment to another, without needing to select any of the system settings for export. However, the Start Auditing is not. When documenting the steps to perform a deployment, make sure that manually checking this important box if you are performing auditing on any of your entities is one of those steps."
So you will have to make sure start auditing is enabled on these entities manually. I assume you would be able to automate "start auditing" using a C# Console App as well if automation is an important part of your deployment process.
So, to clarify, when exporting the managed solution, it seems like the following line is transferred:

Here's a work around for this problem that I found here:
Simply open up the managed solution zip and edit the setting for IsAuditEnabled to read 1. After that zip up the solution again and import at will.
A bit of manual work but it should work. Also, make sure going forward you remember to do this. If Auditing is turned off you will lose all Audit Data for the entity...


text:
Q: Google Drive file insertion error quotaExceeded Sometimes when I try to insert a file into a folder, I get this response
{
"code": 403,
"errors": [
{
"domain": "usageLimits",
"message": "The user has exceeded their Drive storage quota",
"reason": "quotaExceeded"
}
],
"message": "The user has exceeded their Drive storage quota"
}

What is "quotaExceeded"? Where can I get a list of all errors and their meanings of Google Drive API?

A: List of errors with advice on how to handle them: https://developers.google.com/drive/handle-errors
If you have exceeded your quota you can request more here: https://docs.google.com/spreadsheet/viewform?formkey=dG0wOFJPeVRxSUxuMHUzdlZpTkU4Z0E6MQ


text:
Q: Jquery-Dynamic Radio Buttons I am trying to create radio buttons in a container. The total number of radio buttosn is supplied from the value selected in Combobox that is in another container, when I am trying to do this, I am getting only 1 radio button displayed even the supplied number is more than 1, also I am getting those appended to the previous selection buttons, instead of that I need to clear the contents when the selection is changed and new number of buttons should only be displayed.
$(document).ready(function(){

$("#choice").change(function(){

    var radio_name=$("#choice option:selected").text();
    var a=$("#choice option:selected").val();
    var element=$('<input type="radio" name='+ radio_name +'/>
');
    for(i=1;i <= a;i++){

       element.prependTo('#reports');
    }
 });

 });
      </script>

    Select Your Choice:  <select id='choice' style="width:100px;">
       <option>Select Your Choice</option>
    <option value="4">Sales</option>
    <option value="2">Income</option>
    <option value="3">Consumer</option>
    <option value="5">Exports</option>
    </select>

A: element's value can't be duplicated in the HTML.
You need to define element inside the loop, or, since I don't see any use of defining the radios into a variable you can simply do:
$("#choice").change(function(){

    $( '#reports' ).empty();

    var radio_name=$("#choice option:selected").text();
    var a=$("#choice option:selected").val();

    for(i=1;i <= a;i++)
        $( '<input type="radio" name='+ radio_name +'/>
' ).prependTo('#reports');

});

empty() is used to clear the container.

A: Try with the following:
$(document).ready(function(){

    $("#choice").change(function(){
        var radio_name=$(this).text();
        var element=$('<input type="radio" name='+ radio_name +'/>
');
        element.appendTo('#reports');
     });

});

*

*Get selected item text

*Create new radio element using selected item text

*Append new element to reports div

Best Regards,

A: I saw a few tweaks, like the name needs a [] to make it part of an array.  And I think them main problem was that the element object being created was being reused when a new object needed to be created every time.
I tested on jsFiddle to make sure jsFiddle
$(document).ready(function(){

    $("#choice").change(function(){

        var radio_name=$("#choice option:selected").text();
        var a=$("#choice option:selected").val();
        for(i=1;i <= a;i++){
           $('<input type="radio" name="'+radio_name+'[]" />
').prependTo('#reports');
        }
     });

 });

A: In your for statement you start with i=1; and you tell the function to run until i <= a.
It doesn't matter what positive integer you set the value of a to be it will always be at least equal to if not more than i. So you're only appending once.


text:
Q: Question on completeness of graphs in Cayley's Formula In my textbook, Cayley's Formula is presented as follows:

There are $n^{n-2}$ distinct labeled trees of order $n$.

However, this statement says nothing about whether or not this formula applies to complete graphs only, which it does. I'm certain that the textbook isn't incorrect, so why is it that the theorem is presented in this way? What am I missing here?

A: The version of the theorem that applies to  complete graphs only is

There are are $n^{n-2}$ spanning trees of the complete graph on $n$ vertices.

Indeed, if you replace the complete graph with any other graph, the number will change.
But the version of the theorem that states

There are $n^{n-2}$ labeled trees on $n$ vertices.

isn't making a claim about spanning trees at all. It is simply counting connected, acyclic graphs on a fixed vertex set of size $n$.
Of course, it's not hard to see that the two statements are equivalent: any spanning tree of $K_n$ has $n$ vertices, and any tree on $n$ vertices is a spanning tree of $K_n$.

A: Yes, this works for counting spanning subtrees of $K_n$.
If you want to count spanning subtrees of any graph $G$ you can use Kirchoffs theorem, Cayleys theorem is a particular case as the laplacian of $K_n$ has spectra $[n-1]^{n-1},[0]^1$


text:
Q: Demonstrative 'that' + indefinite pronoun 'someone' Is it grammatically sound to refer back to the unspecific pronoun 'someone' via the use of 'that' before it? For example:

I heard someone gave it to him as a present. That someone must have been really rich.

Is the above usage correct? Or does grammar necessitate that it be replaced by 'That person' or something else?
Bonus question, is it grammatical to say 'a certain someone' as a way of alluding to a specific yet unknown person?

A: Yes, it's correct.  By its ambiguity, "that someone" imbues the subject with an aura of mystery -- in this case a "mysterious benefactor" --  so be aware of that when you use it.
Bonus answer:  Yes indeed.  Example:

She told us that a certain someone was going to pick her up at seven this evening for a romantic dinner downtown.  Does anyone know who her mysterious new flame could be?

I disagree with user3169's statement that the person, "would probably be known by the speaker, but not known by the audience." It's possible for everyone to be in the dark.


text:
Q: No such file or directory error when using Hadoop fs --copyFromLocal command I have a local VM that has Hortonworks Hadoop and hdfs installed on it. I ssh'ed into the VM from my machine and now I am trying to copy a file from my local filesystem into hdfs through following set of commands:
[root@sandbox ~]# sudo -u hdfs hadoop fs -mkdir /folder1/
[root@sandbox ~]# sudo -u hdfs hadoop fs -copyFromLocal /root/folder1/file1.txt /hdfs_folder1/

When I execute it I get following error as - copyFromLocal:/root/folder1/file1.txt': No such file or directory
I can see that file right in /root/folder1/ directory but with hdfs command its throwing above error. I also tried to cd to /root/folder1/ and then execute the command but same error comes. Why is the file not getting found when it is right there?

A: By running sudo -u hdfs hadoop fs..., it tries to read the file /root/folder1/file.txt as hdfs.
You can do this.

*

*Run chmod 755 -R /root. It will change permissions on directory and file recursively. But it is not recommended to open up permission on root home directory.

*Then you can run the copyFromLocal as sudo -u hdfs to copy file from local file system to hdfs.

Better practice is to create user space for root and copy files directly as root.

*

*sudo -u hdfs hadoop fs -mkdir /user/root

*sudo -u hdfs hadoop fs -chown root:root /user/root

*hadoop fs -copyFromLocal

A: I had the same problem running a Hortonworks 4 node cluster. As mentioned, user "hdfs" doesn't have permission to the root directory. The solution is to copy the information from the root folder to something the "hdfs" user can access. In the standard Hortonworks installation this is /home/hdfs
as root run the following...

mkdir /home/hdfs/folder1
cp /root/folder1/file1.txt /home/hdfs/folder1

now change users to hdfs and run from the hdfs USER's accessible directory

su hdfs
cd /home/hdfs/folder1

now you can access files as the hdfs user

hdfs dfs -put file1.txt /hdfs_folder1


text:
Q: Efficient way to fetch the total number of records in SQL server during Paging When querying a table in sql server, im trying to fetch only the current page of records. However  I need the total number of records that would be returned for the particular query to calculate the number of pages. How to do this efficiently without writing another query to count the records.
 WITH allentities
         AS (SELECT Row_number() OVER (ORDER BY se.entityid ASC) AS
                    rowid
                    ,empid
                    ,lastname
                    ,firstname
                     ,d.depname

             FROM   emp e join dep d on e.depid=d.depid)
    SELECT *
    FROM   allentities
    WHERE  rowid >= @pageid
           AND rowid <= @pageid + 20

A: If you add a second ROW_NUMBER() sorting DESC rather than ASC, you can calculate the total number of records by adding the two rowcounts together and subtracting one. Any row in the rsult set will have the correct total number of rows:
 WITH allentities
         AS (SELECT Row_number() OVER (ORDER BY se.entityid ASC) AS
                    rowid
                    ,empid
                    ,lastname
                    ,firstname
                    ,d.depname
                    ,ROW_NUMBER() OVER (ORDER BY se.entityid DESC) AS rowIdNeg
             FROM   emp e join dep d on e.depid=d.depid)
    SELECT *
            ,rowid + rowIdNeg - 1 as totalRecords
    FROM   allentities
    WHERE  rowid >= @pageid
           AND rowid <= @pageid + 20

A: If your application allows it, you can try to install and use search index to perform such queries. Search indexes have functionality to work with paging.
You can use for example http://lucene.apache.org/solr/. It can be configured to index Sql server db.


text:
Q: Adding Lines and Rectangles to Facet Plots I'm trying to draw a similar graph shown on plotly sample page @ https://plotly.com/python/facet-plots/ , under the 'Adding Lines and Rectangles to Facet Plots' section. The rectangle shade was only drawn on the first col of graphs, but I wish same shades to be seen on rest of graphs. How can it be done?
The code used from the sample is:
import plotly.express as px

df = px.data.stocks(indexed=True)
fig = px.line(df, facet_col="company", facet_col_wrap=2)
fig.add_hline(y=1, line_dash="dot",
              annotation_text="Jan 1, 2018 baseline",
              annotation_position="bottom right")

fig.add_vrect(x0="2018-09-24", x1="2018-12-18", col=1,
              annotation_text="decline", annotation_position="top left",
              fillcolor="green", opacity=0.25, line_width=0)
fig.show()

Though I already provided my finding below and didn't delete my post because wishing to share with other new plotly users with similar confusion, there is still one 'experienced' person from the community vote -1 for this post. However, I will continue to share. :)

A: Realizing the code from the sample specified col=1, which causing the shade only appear on one col of graphs.


text:
Q: How to save a font and its details (colour, size, style) in a SQL database? In my application, the user wants to be able to change the font (font, fontstyle, fontcolor) and it need to be there till changed in the future.
So basically when the font and its details is selected, it needs to be saved into SQL. Is the possible, how do i do this, will it be a VARCHAR?

A: Save the font-family name in varchar or text
Save the font size in int
Make Three Columns with int named Regular, Italic, Underline
Put 1 for yes and 0 for No
Retrieve these values and apply as per format when the app starts up, or whenever u need


text:
Q: Finding the number of edges $k$-connected graph with certain number of vertices I'm trying to figure out giving a $k$-connected graph how to find the number of edges needed for a certain number of vertices. For example, the number of edges in $2$-connected graph giving that it has $8$ vertices. I guess this is relevant to Menger's theorem.

A: You can do this directly if you take a look at a picture. It's easy to see the minimal number of vertices to gain a connected graph is $k-1$ just by chaining them in a straight line. Now each edge you add adds connectivity to both vertices to which it is connected, but it also clearly increases the connectivity to exactly two at a time, so with $8=2\cdot 4$ vertices you need at least $4$ more edges, however, if you look at the vertices in a line labeled $1-8$ from left to right, you can see that since $[i, i+1]$ is an edge for $1\le i\le 7$ then if you also use $[i, i+4]$ for $1\le i\le 4$ this gives each edge connectivity $2$ so we achieve the theoretical minimum of $11=8-1+ \lceil 8/2\rceil$.


text:
Q: Problems starting JMS bridge in Wildfly 10 I'm trying to set up either a JMS or core bridge between two instances of Wildfly 10.
My queue and bridge configuration:
<subsystem xmlns="urn:jboss:domain:messaging-activemq:1.0">
    <server name="default">

        ...

        <jms-queue name="APIResponseSource" entries="queue/APIResponseSource java:/jms/queue/APIResponseSource java:jboss/exported/jms/queues/APIResponseSource" durable="false"/>

        ...

        <bridge name="APIResponseBridge" queue-name="jms.queue.APIResponseSource" forwarding-address="jms.queue.APIResponseTarget" use-duplicate-detection="true" static-connectors="response-bridge-connector"/>

        ...

    </server>
</subsystem>

I used the example in this post:
Wildfly 10 JMS bridge over HTTPS configuration issues

The error I'm getting is this:
2018-09-25 23:44:43,170 WARN  [org.apache.activemq.artemis.core.server] (ServerService Thread Pool -- 65) AMQ222125: No queue found with name jms.queue.APIResponseSource bridge APIResponseBridge will not be deployed.

I've used every combination of queue names I can think of, APIResponseSource, jms.queue.APIResponseSource, jms.queues.APIResponseSource, queue.APIResponseSource, but the end result is the same. I've seen some discussion about setting up a core queue, but there doesn't seem to be anything like that in the documented Wildfly 10 configuration. I've also seen some discussion about a "jms-bridge" element, but I haven't found anything like that in the docs either. I would prefer to use a core bridge for performance reasons.
Any ideas?

A: I believe the issue here is the order in which the resources are deployed.  "Core" resources like core queues, bridges, diverts, etc. are deployed before JMS resources like JMS queues and topics.  Therefore the bridge is deployed before the JMS queue which means the "core" queue which represents the JMS queue doesn't exist yet hence the error.  You should define the "core" queue jms.queue.APIResponseSource which maps to an address of the same name, e.g.:
<queue name="jms.queue.APIResponseSource" address="jms.queue.APIResponseSource"/>

I don't believe this is explicitly documented, but you'll find the queue element in docs/schema/wildfly-messaging-activemq_1_0.xsd.


text:
Q: launchd from terminal to start app I'm trying to use launchd from terminal to start app with command line arguments. I followed along here but can't figure it out: https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man8/launchd.8.html
I'm trying to launch: /Applications/Firefox.app/Contents/MacOS/firefox -profile "blah blah" -no-remote
thanks!

A: You don't need to directly use launchd for that and probably shouldn't.
You can just use:
open -a Firefox --args -profile "blah blah" -no-remote

Or:
open -a /Applications/Firefox.app --args -profile "blah blah" -no-remote

Or:
open -b org.mozilla.firefox --args -profile "blah blah" -no-remote

If Firefox is already running, then the above will just bring it to the front and activate it. In that case, the args are ignored because they are only meaningful when launching the app.
If you want to launch a new process even if the app is already running, pass the -n option to open, before the --args option. Like:
open -a /Applications/Firefox.app -n --args -profile "blah blah" -no-remote


text:
Q: "mprof run ": What does each output column represent? I ran mprof run some-executable and it produced a *.dat file.
What does each column of the *.dat file signify?
vikas@some-host$ cat mprofile_20150224012014.dat
CMDLINE python ../asl
MEM 0.332031 1424769614.8950
MEM 7.593750 1424769614.9954
MEM 8.816406 1424769615.0957
MEM 8.816406 1424769615.1960

What do those 1st/2nd/3rd columns represent?
[EDIT]:
Also I am not able to run mprof run --python.
Here is the error(importerror) I am getting.... looks like it is not able to get the definition of config
(virtualenv)vikas@host:$ ./mprof run --python ../myfile.py
mprof: Sampling memory every 0.1s
running as a Python program...
Traceback (most recent call last):
File "/usr/lib64/python2.6/runpy.py", line 122, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib64/python2.6/runpy.py", line 34, in _run_code
exec code in run_globals
File "/home/vikask/memory_profiler-0.32/memory_profiler.py", line 853, in <module>
execfile(__file__, ns, ns)
File "../myfile.py", line 19, in <module>
from bsite import models, security
File "/home/vikas/bsite/models.py", line 12, in <module>
from bsite import config
ImportError: cannot import name config

A: 1st column: "MEM" is just a label.
2nd column: RSS (resident set size) in megabytes. So your process ended up using 8.8 MB.
3rd column: Unix time stamp:
>>> import time
>>> print(time.ctime(1424769615.1960))
Tue Feb 24 01:20:15 2015

It looks like mprof just logs the process size over time. If you want more specific details about the internals of your program (line-by-line) it looks like you can use mprof run --python file.py to get that information (you also need to decorate your functions with @profile, see the Usage section in the documentation).
Edit: In response to the ImportError & traceback you posted: You are getting that error because you're running the file as "../myfile.py". Since you're outside of the bsite directory it can't find the config.py file.
You need to run the program like this:
 $ cd /home/vikas/bsite/
 $ /home/vikask/memory_profiler-0.32/mprof run --python myfile.py

This way you're in the correct directory for the import to work.
Another way to get it to work is to build your project as a python package. When you do this your files can be properly imported from anywhere. This is a little complicated to get set up, but it's a pretty good idea.
The other more hacky option is to modify PYTHONPATH or sys.path to get the imports to work. For example like this:
$ cd /home/vikask/memory_profiler-0.32/
$ PYTHONPATH=/home/vikas/bsite/ ./mprof run --python ../myfile.py

Finally, it looks like you're running the mprof command directly from the memory_profiler source. You can install the package by doing "python setup.py install" in that directory (or by using pip install memory_profiler). Then you should have the mprof command on your PATH and can run it from any directory.

A: If anyone comes here with a problem that mprof doesnt work on Windows(like me), do the following:
After installation of memory_profiler
1) go to your Python\Scripts folder, change your file mprof type to mprof.py
2) in the same folder as in 1), create new file mprof, add there following text
@echo off

python "%~dpn0.py" %*

3)Save the file and change its type to mprof.bat
Now everything should work.
Good luck!


text:
Q: Image upload validation without using @Assert I'm trying to make image upload compulsory. I've tried it on a Collection Type by @Assert\Valid which was generating an error Image is missing! on the top of the form i.e. error bubbling then I removed error bubbling by setting it false. After removing error bubbling I'm unable to populate image missing error. How can I map the error to its form element i.e. images.
Please help & provide me possible solutions for this problem by using Symfony or jQuery. And also suggest the which one is best & why.
Entity: XYZBundle\Entity\Abc.php
     Class Abc
     {
         .....

         /**
         * @JMS\Groups({"details"})
         * @JMS\Expose
         *
         *@Assert\Valid
         * @var \Doctrine\Common\Collections\Collection
         */
        private $images;

        .....

FormType: XYZBundle\Entity\AbcType.php
     public function buildForm(FormBuilderInterface $builder, array $options)
        {
           .....

            ->add('images', CollectionType::class, array(
                    'entry_type' => MediaType::class,
                    'label' => false,
                    'allow_add' => true,
                    'allow_delete' => true,
                    'by_reference' => false,
                    'prototype' => true,
                    'error_bubbling' => false,

                ))

           .....

A: By adding the following code into AbcController I'm able to show the error now. And I've now removed the @Assert\Valid from the Entity (XYZBundle\Entity\Abc.php).
Controller: AbcController.php
 $images = $form['images']->getData();
            $imageExist=false;
            foreach ($images as $image){
                if(!empty($image->getFilename())){
                    $imageExist=true;
                    break;
                }
            }
            if(!$imageExist){
                $form['images']->addError(new FormError("Please upload at least one image."));
            }

The only thing that is remaining is to map the error just after its form element.


text:
Q: Necessity of an Inductor at CAN Transceiver end
Basically 120 ohm of resistor needs to be connected as terminator resistor at the end of the physical CAN channel.
My question is that here, what is the necessity of an inductor (L310) between CAN transceiver and physical CAN line ?

A:
what is the necessity of an inductor (L310) between CAN transceiver
  and physical CAN line

L310 and the two 220 pF capacitors form a common mode filter so that common mode interference on the line (to the left) is not transferred at the same magnitude to the chip on the right.
If you can provide a data sheet for L310, more information can be provided.


text:
Q: How do I describe the a type in typescript that has dynamic name? I want to describe a type that has the following behavior
export class myData {
    key          : string;
    display_name : string;
}

However I want to have dynamic name for key and display_name with the actual key and display_name that I supplied
eg. the following would be valid myData type
mySample1:myData =
{
    myKey    : 'myKeyValue'
    myName   : 'myNameValue'
}

mySample1:myData =
{
    myKey2    : 'myKeyValue2'
    myName2   : 'myNameValue2'
}

The motivation for this is that I have alot of data from API that returns a list of object with same number of key and with same type of value for each key. But the thing is that each data has different key names.
I want to create a Component in angular2 that only takes a list of object with certain number of keys, and each key's value have to be a certain type.
For example I don't want my Component to take
var test =
{
    myKey2    : 1
    myName2   : 'myNameValue2'
}

or
var test2 =
{
    myKey2    : 'myNameValue1'
    myName2   : 'myNameValue2'
    mySomeOtherKey : 'myNameValue10'
}

Is this possible in typescript? If it is possible, is this a good idea in typescript?

A:
eg. the following would be valid myData type

TypeScript is structural. Since you want both of these to be valid:
mySample1:myData =
{
    myKey    : 'myKeyValue'
    myName   : 'myNameValue'
}

mySample1:myData =
{
    myKey2    : 'myKeyValue2'
    myName2   : 'myNameValue2'
}

You can easily declare myData to be a union of these two types:
type MyData = {
    myKey: string;
    myName: string;
}
    | {
        myKey2: string;
        myName2: string;
    }

let mySample1: MyData =
    {
        myKey: 'myKeyValue',
        myName: 'myNameValue'
    }

mySample1 =
    {
        myKey2: 'myKeyValue2',
        myName2: 'myNameValue2'
    }


text:
Q: Can the datetime module in Python be formatted to output double digit numbers? I am learning about the datetime module in Python and I tried to print the day, month and year.
It works but the date is being printed as a single digit instead of double digits.
Here is my code:
from datetime import datetime
dateNow = datetime.now()
print (dateNow.day)
print (dateNow.month)
print (dateNow.year)

Here is the output:
1
4
2021
>>>

I would like it to be shown as
01
04
2021
Is this possible?

A: Just use strftime:
print(dateNow.strftime('%d %m %Y'))

It gives as expected 01 04 2021


text:
Q: How to authorize requests with x-auth-token in its header using asp.net core api? I generated token included user info and her roles using asp.net core web api and get it at client, then put it in x-auth-token in request header. How cal I authorize user (with her roles) in asp.net api controllers and actions? My setting in startup.cs is like below but I can not catch request in my action!
var securityKey = Environment.GetEnvironmentVariable("SECURITY_KEY");
var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));

services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
      options.TokenValidationParameters = new TokenValidationParameters()
              {
               ValidateIssuer = true,
               ValidateAudience = true,
               ValidateIssuerSigningKey = true,

               ValidIssuer = "shoniz.com",
               ValidAudience = "readers",
               IssuerSigningKey = symmetricSecurityKey
              };
    });

A: The code in your example is an settings of authentication (JWT scheme). First, you have to add middleware, which will authenticate user. This part of code should be present in Startup.cs (Configure() method).
app.UseAuthentication();

Once this middleware is called, all the authentication schemes are taken into account. When the authentication will success, HttpContext.User will be set (including all your issues claims).
The second part is authorization. The simplest way is to use [Authorize] attribute you can use as an annotation along with your action methods and controllers. You can add custom role names or policy restriction.
[Authorize(Roles = "admin")]
public class CmsControllerBase : Controller
{
}


text:
Q: Any way to transfer Store View values to Default Values in Magento? We're a few years and 11,000+ products into our Magento store and we had to shift gears a bit.
Life would be easier if the values (titles, enabled/disabled, descriptions) used in the Store View could overwrite the Default Values without endless hours of copy/pasting.
So, if the Store View Value is different than the Default Value, make that the Default Value. Help appreciated!

A: This can be done directly with SQL, but be sure to set maintenance mode and backup before you start.
SET @default = 0;
SET @store = 1;
-- put the correct store_id here

START TRANSACTION;

INSERT INTO `catalog_product_entity_int` (entity_type_id, attribute_id, store_id, entity_id, value)
SELECT entity_type_id, attribute_id, @default, entity_id, value FROM `catalog_product_entity_int` AS local
WHERE store_id = @store
ON DUPLICATE KEY UPDATE value = local.value;
-- the "ON DUPLICATE..." part works because EAV tables have
-- a unique key for "entity_id, attribute_id, store_id"

DELETE FROM `catalog_product_entity_int`
WHERE store_id = @store;
-- it is safe to delete @store rows because all values
-- have been either copied or updated by now

COMMIT;

Repeat the above for all catalog_product_entity_* tables.  Then rebuild indexes, you can do that while the site is in maintenance mode with SSH...
cd path/to/magento/shell/
php indexer.php --reindex catalog_product_attribute

A: I wrote a PHP script that goes through the storeview values, copies them to default scope if they are different and then deletes the local value.
You can see the GIST here: https://gist.github.com/janzikmund/a92e0a219af5e362fa1293b52b6b831e .
It is commented to give you the idea. At the bottom the UPDATE and TRUNCATE lines are commented out, so you should be able to first run it without any data modification and then when you are sure uncomment these lines and transform the data.
Of course don't forget to do a backup first!


text: Q: Is it possible to use the onEdit trigger in google spreadsheets for google slides? I'm trying to make something where when a slide is edited after it is "saved" in a slides api, whoever edits it becomes commenter. If you can't use onEdit trigger in slides, are there any alternatives?


text:
Q: Laravel routes going to wrong route I do not understand the following problem.
Here are me routes:
Route::get('events', array('as' => 'events' ,'uses' => 'EventController@index'));
Route::get('event/{id}', array('as' => 'event' ,'uses' => 'EventController@view'));
Route::get('event/new_event', array('as'=> 'new_event', 'uses' => 'EventController@newEvent'));
Route::post('event/create', array('uses' => 'EventController@create'));
Route::get('event/{id}/edit', array('as' => 'edit_event', 'uses' => 'EventController@edit'));
Route::post('event/update', array('uses' => 'EventController@update'));
Route::delete('event/delete', array('uses' => 'EventController@destroy'));

I can not create a new event, because when I click on the 'New Event' button, it uses EventController@view instead of EventController@newEvent.
Here is the EventController:
<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use App\EventModel;

class EventController extends Controller
{
    public function index()
    {
        $events = EventModel::all();
        return \View::make('event/index')->with('events', $events);
    }

    public function view($id)
    {
        return \View::make('event/view')
        ->with('event', EventModel::find($id));

    }

    public function newEvent()
    {
        dd("dd");
      return \View::make('event/create');
    }

    public function create()
    {
        $validator = EventModel::validate(Input::all());

        if($validator->fails())
        {
            $messages = $validator->messages();

            return redirect()->action('EventController@newEvent')
            ->withErrors($validator)
            ->withinput();
        }
        else
        {
            EventModel::create(array(
                'title'=>Input::get('title'),
                'start'=>Input::get('start'),
                'end'=>Input::get('end'),
                'userID'=>\Auth::user()->id,
            ));

            //Session::flash('message', 'New event has been created!');
            flash()->overlay('New event has been created!', 'Success');

            return redirect()->back();
        }
    }

    public function edit($id)
    {
        return \View::make('event/edit')
        ->with('event', EventModel::find($id));
    }

    public function update()
    {
        $event = EventModel::find(Input::get('event_id'));

        $validator = EventModel::validate(Input::all());

        if($validator->fails())
        {
            $messages = $validator->messages();

            return redirect()->back()
            ->withErrors($validator)
            ->withinput();
        }
        else
        {
            $event->title = Input::get('title');
            $event->start = Input::get('start');
            $event->end = Input::get('end');
            $event->save();

            //Session::flash('message', 'Successfully updated!');
            flash()->overlay('Event has been sucessfully updated!', 'Success');

            return redirect()->back();
        }
    }

    public function destroy()
    {
        $id = Input::get('event_id');
        dd("$id");
    }
}

Why does this problem occur?

A: You have to sort your routes because laravel checks the order of the routes.
Try:
Route::get('events', array('as' => 'events' ,'uses' => 'EventController@index'));
Route::get('event/new_event', array('as'=> 'new_event', 'uses' => 'EventController@newEvent'));
Route::post('event/create', array('uses' => 'EventController@create'));
Route::post('event/update', array('uses' => 'EventController@update'));
Route::delete('event/delete', array('uses' => 'EventController@destroy'));
Route::get('event/{id}', array('as' => 'event' ,'uses' => 'EventController@view'));
Route::get('event/{id}/edit', array('as' => 'edit_event', 'uses' => 'EventController@edit'));

A: Laravel route checks in the order they were defined.
event/new_event and event/{id} both have same route structure and so it is going to view action.
Change the order -
Route::get('event/new_event', array('as'=> 'new_event', 'uses' => 'EventController@newEvent'));
Route::get('event/{id}', array('as' => 'event' ,'uses' => 'EventController@view'));


text:
Q: fabricJS stringifying an object changes its semantics When adding a filter to my objects in the canvas, I create a filter which I add into index no. 6 in the object's filter attribute.
When getting objects from my canvas using the let obj = canvas.getObjects() method and accessing the filter attribute I get a value of this type: [empty × 6, klass]. Expanding the array in dev tools gives me:
6: klass {matrix: Array(20), type: 'ColorMatrix'}
length: 7

However, the very moment I run JSON.stringify either like this JSON.stringify(obj)) or like this I get returned:
"filters":[{"type":"ColorMatrix","matrix":[0.41176,0.41176,0.41176,0,0,0.70915,0.70915,0.70915,0,0,0.28431,0.28431,0.28431,0,0,0,0,0,0,0]}]}

Which is semantically identical, other than the fact that the filter has been moved to index no. 0.
This is causing some problems for me, so I am wondering why this is happening and what the best practice is if I would like to maintain perfectly semantic and identical JSON representation of the object?