text:
Q: Download Document in the right format without MIME I have got this WebService that allows uploading/downloading any docs (mostly .docx, .doc, .pdf) and all it returns is byte[] when querying for downloading.
I have written this code
 string ContractGUID = dtContract.Rows[0]["ContractGUID"].ToString();

 //Get Bytes from WebService
 byte[] fileData = BLL.Contract.GetDocument(new Guid(ContractGUID));
 Response.Clear();
 Response.BinaryWrite(fileData);
 Response.AddHeader("Content-Disposition", "Attachment");
 Response.Flush();

The other methods that the WebService exposed are GetDocumentName and GetDocumentLen
Is it possible to determine the Mime-Type or force the browser to download it in the right format? Currently it is downloading as .htm in Chrome and when open, I see funny characters. Any better advice?
Thanks.

A: I think, the browser does it through filename.
e.g.:
response.Clear();
response.AddHeader("Content-Disposition", "attachment; filename=" + dbFile.filename.Replace(" ", "_"));
response.AddHeader("Content-Length", dbFile.data.Length.ToString());
response.ContentType = "application/octet-stream";
response.OutputStream.Write(dbFile.data, 0, dbFile.data.Length);
response.End();

dbFile.filename is a string
dbFile.data is a byte[]

A: No, it's not possible to force the browser to download in the right format without you telling it via the Content-Type header.
Response.ContentType = "application/pdf"; //or whatever appropriate

If the web service exposes a GetDocumentName() method you can probably infer the appropriate format by looking at the name, assuming the name has a file extension. This, obviously, is not bullet proof since you can change the extension of a file to anything you want.
Another alternative would be to try and guess the file format by peeking at the first bytes. For example, if the first 4 bytes of the file are 25 50 44 46 then it's very likely that this is a PDF file. On this website, they have a pretty extensive list.
Here's the list of possible content-type headers.


text:
Q: Laravel Nova show computed field in BelongsToMany sub table Using Laravel Nova, I want to show a computed field in a BelongsToMany subview. In the intermediate model I have setup a virtual attribute field which computes a value using connected tables. However this field is not getting shown probably because Nova checks the withPivot fields (to which it cannot be added as it's not a real field). Is there an alternative method to get this to work?
The database model behind this is:
[GameVariation] has BelongsToMany using [GameVariationMatch] with [GameMatch]

[GameMatch] HasOne [Match]

In the GameVariation resource I've setup a BelongsToMany field which should display the computed field:
BelongsToMany::make( 'Game Matches', 'game_matches', GameMatch::class )
    ->fields( function () {
        return [
            Text::make( 'Match Data' )->displayUsing(function() {
                return $this->match_data;
            })
        ];
    } ),

In the GameVariation model the tables are connected with BelongsToMany:
final public function game_matches(): BelongsToMany {
    return $this->belongsToMany(
        GameMatch::class
    )
    ->using( GameVariationMatch::class );
}

In the pivot tabel model GameVariationMatch the computed field is setup like this:
final public function getMatchDataAttribute(): string {
    return $this
        ->game_match
        ->match
        ->match_data;
}

A: As it turns out, on the GameVariation resource the index view of the BelongsToMany to GameMatch is served from the GameMatch resource. When only setting up ->fields() on the GameVariation BelongsToMany field, it won't show up. The recommended way is to set up ->fields() using a field class like this:
<?php

namespace App\Nova\Fields;

use App\Models\GameVariationMatch;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\Text;

class GameVariationMatchFields {

    /**
     * Get the pivot fields for the relationship.
     *
     * @param Request $request
     *
     * @return array
     */
    final public function __invoke( Request $request ): array {
        return [
            Text::make( 'Match Data', function ( GameVariationMatch $GameVariationMatch ) {
                return $GameVariationMatch->match_data;
            } ),
        ];
    }
}

In the above, the computed Text field receives the intermediate pivot model and can therefore access all computed attributes.
The field class is used in the GameVariation resource as:
BelongsToMany::make( 'Game Matches', 'game_matches', GameMatch::class )
    ->fields( new RoundMatchVariationFields ),

And in the GameMatch resource as:
BelongsToMany::make( 'Game Variations', 'game_variations', GameVariation::class )
    ->fields( new GameVariationMatchFields ),

As described in official Nova docs on pivot fields https://nova.laravel.com/docs/2.0/resources/relationships.html#belongstomany

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript regex- phone number i'm trying to find an expression that matches a phone number in the format of  (0[2,3,6,7,8,or 9]) XXXXXXXX where X is a digit, the space must be matched and so must the parentheses
My current expression is:
/\b\(0[236789]\)\s(\d){8}\b/g

but it's not picking up any test numbers such as
(02) 12345678

I know regex phone number questions get spammed on SO. I have been reading through all the ones I can find which is how I've made it to this point but I can't for the life of me figure this out.

A: Just remove the \b on either end, and it should work
/\(0[236789]\)\s(\d){8}/g

This will match multiple phone numbers, not sure if that is what you want. If you want to make sure the entire string from start to finish is the full phone number, you can do this
/^\(0[236789]\)\s(\d){8}$/

This will match (02) 12345678, and won't work if there are any characters around the string.

A: Well, this is the best I can come up with.
/^[+]?(1\-|1\s|1|\d{3}\-|\d{3}\s|\d{2}\-|\d{2}\s|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})
(\-|\s)?(\d{4})$/g

This should support all combinations like

*

*(541) 754-3010

*+1-541-754-3010

*1-541-754-3010

*001-541-754-3010

*191 541 754 3010

*+91 541 754 3010

and so on.


text:
Q: Disable false warning "possible missing interpolator" I have some nested case classes, and for a specific serialization mechanism I need to provide a productPrefix that contains $ characters. Like so
object Foo {
  case class Bar() {
    override def productPrefix = "Foo$Bar"
  }
}

Now I get a compiler warning from this:

Warning:(53, 42) possible missing interpolator: detected interpolated identifier `$Bar`
    override def productPrefix: String = "Foo$Bar"

Is there a way to disable the warning, if possible only for this instance? Scala version is 2.11.8.

Edit: I just thought I was clever: "Foo\u0024Bar". But the compiler even warns about this. Another solution is classOf[Bar].getName, given the constraint that there are no further outer objects.

A: The warning is induced by -Xlint. The specific linter about the supposedly missing interpolator can be disabled by giving the scalac command line option as
-Xlint:_,-missing-interpolator

The underscore (_) is for "everything" and the -missing-interpolator is for "except the missing interpolator warning".

A: -Xlint warns if it sees a var in scope:
$ scala -Xlint
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101).
Type in expressions for evaluation. Or try :help.

scala> { val x = "hi" ; s"$x" }
res0: String = hi

scala> { val x = "hi" ; "$x" }
<console>:12: warning: possible missing interpolator: detected interpolated identifier `$x`
       { val x = "hi" ; "$x" }
                        ^
res1: String = $x

scala> { val y = "hi" ; "$x" }  // no warning if x is not a symbol
res2: String = $x

scala> object Foo { case class Bar() { override def productPrefix = "Foo$Bar" } }
<console>:11: warning: possible missing interpolator: detected interpolated identifier `$Bar`
       object Foo { case class Bar() { override def productPrefix = "Foo$Bar" } }
                                                                    ^
defined object Foo

Usually, use double dollar for literal dollar when interpolating. (Edit: to be clear, $$ is like \$.)
scala> object Foo { case class Bar() { override def productPrefix = s"Foo$$Bar" } }
defined object Foo

scala> Foo.Bar().productPrefix
res8: String = Foo$Bar

Use f-interpolator to get a constant string.
scala> def productPrefix = f"Foo$$Bar"
productPrefix: String

scala> :javap -pv -
[snip]
  public java.lang.String productPrefix();
    descriptor: ()Ljava/lang/String;
    flags: ACC_PUBLIC
    Code:
      stack=1, locals=1, args_size=1
         0: ldc           #16                 // String Foo$Bar
         2: areturn

You can also put your funky constants in a quarantined scope:
scala> :pa -raw
// Entering paste mode (ctrl-D to finish)

package k {
trait K { final val p = "Foo$Bar" }
}
package q {
  case class Bar() { override def productPrefix = (null: k.K).p }
}

// Exiting paste mode, now interpreting.

scala> q.Bar().productPrefix
res1: String = Foo$Bar

The constant is inlined. The trick of the null reference avoids any allocations, including any singleton object.

A: If there's a way to compose the string from its parts you could do something like this.
override def productPrefix = "Foo$" + "Bar"

You could also quiet the "missing interpolator" warning by actually invoking the interpolator, but escaping the $.
override def productPrefix = f"Foo$$Bar"

A: The warning only happens when there is an identifier with that name in  the lexical scope.
In case the linter complains about it when the identifier is a val/var, you could just rename the val/var

A: You can put the @nowarn annotation on the definition:
@nowarn("msg=possible missing interpolator")
override def productPrefix = "Foo$Bar"

The "missing interpolator" warning is useful in general, so I would not disable it.


text:
Q: Recyclerview is so slow with a lot of item I have made this code that could retrieve from realm 50k items and show it in recyclerview:
public class ListAirportFragment
        extends Fragment {
    Realm realm;
    List<AirportR> airports = new ArrayList<>();
    RealmResults<AirportR> airps;
    RecyclerView recyclerView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_list_airport, container, false);

        RealmConfiguration defaultConfig = new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build();
        realm = Realm.getInstance(defaultConfig);

        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
        SearchView searchView = (SearchView) rootView.findViewById(R.id.searchview);

        final RealmResults<AirportR> airps = realm.where(AirportR.class).findAll();

        airports = realm.copyFromRealm(airps, 0);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        final AirportAdapter adapter = new AirportAdapter(airports, getActivity());
        recyclerView.setAdapter(adapter);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                adapter.getFilter().filter(newText);
                return true;
            }
        });

        return rootView;
    }

    private class AirportAdapter
            extends RecyclerView.Adapter<RecyclerView.ViewHolder>
            implements Filterable {
        private List<AirportR> originalAirports;
        private List<AirportR> listAirports;
        private Context context;
        private AirportFilter filter;
        private boolean isLoading;
        private int visibleThreshold = 5;
        private int lastVisibleItem, totalItemCount;
        private OnLoadMoreListener mOnLoadMoreListener;

        public AirportAdapter(List<AirportR> airports, Context context) {
            this.originalAirports = airports;
            this.listAirports = airports;
            this.context = context;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.airport_show, parent, false);
            AirportClass holder = new AirportClass(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            AirportR airportR = listAirports.get(position);

            AirportClass mHolder = (AirportClass) holder;

            mHolder.country.setText(airportR.getIsoCountry());
            mHolder.name.setText(airportR.getName());
        }

        @Override
        public int getItemCount() {
            return listAirports.size();
        }

        @Override
        public Filter getFilter() {
            if(filter == null) {
                filter = new AirportFilter(this, originalAirports);
            }
            return filter;
        }

        private class AirportFilter
                extends Filter {
            private final AirportAdapter adapter;

            private final List<AirportR> originalList;

            private final List<AirportR> filteredList;

            private AirportFilter(AirportAdapter adapter, List<AirportR> originalList) {
                super();
                this.adapter = adapter;
                this.originalList = new LinkedList<>(originalList);
                this.filteredList = new ArrayList<>();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                filteredList.clear();
                final FilterResults results = new FilterResults();

                if(constraint.length() == 0) {
                    filteredList.addAll(originalList);
                } else {
                    final String filterPattern = constraint.toString().toLowerCase().trim();

                    for(final AirportR airportR : originalList) {
                        if(airportR.getName().contains(filterPattern)) {
                            filteredList.add(airportR);
                        }
                    }
                }
                results.values = filteredList;
                results.count = filteredList.size();
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                adapter.listAirports.clear();
                adapter.listAirports.addAll((ArrayList<AirportR>) results.values);
                adapter.notifyDataSetChanged();
            }
        }

        private class AirportClass
                extends RecyclerView.ViewHolder {
            TextView name, country;
            ImageView image;

            public AirportClass(View itemView) {
                super(itemView);
                name = (TextView) itemView.findViewById(R.id.name);
                country = (TextView) itemView.findViewById(R.id.country);
                image = (ImageView) itemView.findViewById(R.id.imageView);
            }
        }
    }
}

but I have two problems:

*

*the charging of the 50k items is so slow (30 seconds after I go to the fragment with a button) and so I don't know how to make it fast: it's possible to charge only 50 airports for time for example? It's possible it with realm?

*the filter is not working correctly, for example if I search Lowell and I digit lo it does not show Lowell, why this bug?

Thank you for answer

A:
I have made this code that could retrieve from realm 50k items and show it in recyclerview:
final RealmResults<AirportR> airps = realm.where(AirportR.class).findAll();
     airrports = realm.copyFromRealm(airps, 0);

That's because you're copying 50000 objects from your zero-copy database on your UI thread.
Solutions:
1.) don't copy the elements out from the zero-copy database
2.) copy out 50000 elements into memory on a background thread and have fun with the memory usage

Honestly, it's quite obvious that #2 isn't a real solution, so instead, you should follow the practices of how to use Realm's lazy query evaluation feature and managed objects, rather than trying to hack it by calling realm.copyFromRealm()
So this is solution #1 :
public class ListAirportFragment
        extends Fragment {
    Realm realm;
    RealmResults<AirportR> airps;
    RecyclerView recyclerView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_list_airport, container, false);

        RealmConfiguration defaultConfig = new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build();
        realm = Realm.getInstance(defaultConfig);

        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
        SearchView searchView = (SearchView) rootView.findViewById(R.id.searchview);

        airps = realm.where(AirportR.class).findAll();

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        final AirportAdapter adapter = new AirportAdapter(realm, airps, getActivity());
        recyclerView.setAdapter(adapter);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                adapter.getFilter().filter(newText);
                return true;
            }
        });

        return rootView;
    }

    private class AirportAdapter
            extends RecyclerView.Adapter<RecyclerView.ViewHolder>
            implements Filterable {
        private RealmResults<AirPort> listAirports;
        private Context context;
        private Realm realm;

        private final RealmChangeListener realmChangeListener = new RealmChangeListener() {
            @Override
            public void onChange(Object element) {
                notifyDataSetChanged();
            }
        };

        public AirportAdapter(Realm realm, RealmResults<AirportR> airports, Context context) {
            this.realm = realm;
            this.listAirports = airports;
            this.listAirports.addChangeListener(realmChangeListener);
            this.context = context;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.airport_show, parent, false);
            AirportClass holder = new AirportClass(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            AirportR airportR = listAirports.get(position);

            AirportClass mHolder = (AirportClass) holder;

            mHolder.country.setText(airportR.getIsoCountry());
            mHolder.name.setText(airportR.getName());
        }

        @Override
        public int getItemCount() {
            if(listAirports == null || !listAirports.isValid()) {
                return 0;
            }
            return listAirports.size();
        }

        @Override
        public Filter getFilter() {
            if(filter == null) {
                filter = new AirportFilter(this);
            }
            return filter;
        }

        private class AirportFilter
                extends Filter {
            private final AirportAdapter adapter;

            private AirportFilter(AirportAdapter adapter) {
                super();
                this.adapter = adapter;
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                final FilterResults results = new FilterResults();
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if(adapter.listAirports != null && adapter.listAirports.isValid()) {
                    adapter.listAirports.removeChangeListener(adapter.realmChangeListener);
                }
                if(constraint.length() == 0) {
                    adapter.listAirports = adapter.realm.where(AirportR.class).findAll();
                } else {
                    final String filterPattern = constraint.toString().toLowerCase().trim();
                    adapter.listAirports = adapter.realm.where(AirportR.class)
                                                .contains("fieldToQueryBy", filterPattern, Case.INSENSIIVE) // TODO: change field
                                                .findAll();
                }
                adapter.listAirports.addChangeListener(adapter.realmChangeListener);
                adapter.notifyDataSetChanged();
            }
        }

        private class AirportClass
                extends RecyclerView.ViewHolder {
            TextView name, country;
            ImageView image;

            public AirportClass(View itemView) {
                super(itemView);
                name = (TextView) itemView.findViewById(R.id.name);
                country = (TextView) itemView.findViewById(R.id.country);
                image = (ImageView) itemView.findViewById(R.id.imageView);
            }
        }
    }
}

This solution didn't use RealmRecyclerViewAdapter and managed adding/removing change listener manually, but you can also use RealmRecyclerViewAdapter for a better looking solution.

A: With this many items in a list do you really think anybody is actually going to scroll through it? I mean, are you sure a list of items is necessary here or would just a search bar be more efficient?
If you want to keep your set up though I would suggest 3 improvements:

*

*Don't load all available data at once. Add for example 50 objects to the adapter and then when you pass scroll position 30 or so on your RecyclerView add the next 50 results to your adapter. Something along the lines of the code snippet I posted below. (To listen to the scroll position look at this question: How to implement endless list with RecyclerView?) EpicPandaForce's answer addresses this problem better

*Don't let your searchbar filter the populated adapter. Use the fact that RealmResults are auto-updating views on the database so you can actually execute a new transaction on it to filter the data using realm without re-fetching the data. (See Realm docs and api reference)

*Do all loading and searching on a separate thread so to not block the main thread with it. You could for example use rx Observables.

This should fix your performance problems and you don't have to implement the search yourself, but can instead rely on Realms optimized performance.
Code snippet for 1.: Only left for the record. EpicPandaForce's answer addresses this in a better way
private void addToAdapter() {
        final int maxElements = 50;
        final int startPosition = adapter.getItemCount();
        int endPosition = startPosition + maxElements();
        if (endPosition > realmResults.size()) {
            endPosition = realmResults.size() - 1;
        }

        // there might be better ways to do it. Pretty new to Realm
        for (int i = startPosition; i < endPosition; i++) {
            /* for this your adapter has to hold a List as a field
               and expose a public add method that appends to it*/
            adapter.add(realmResults.get(i));
        }

        adapter.notifyItemRangeInserted(startPosition, endPosition);
    }

A: You should return results from another thread. If you have 50k.. is to much for main thread to process. You should use a lazy loading for 50 elements. And filter search is case sensitive. Make both lowercase.


text:
Q: Variable heights and overflow in flexbox children I'm stuck in this scenario:
I'm trying to design this structure:

I have a wrap with 100% width and variable height.
This wrap is a flexbox with these settings:
.wrap {
    width:100%;
    display:flex;
    flex-direction:row;
    justify-content:space-between;
    align-items:stretch;
    background:black;
}

Inside this wrap I have two boxes (left and right). Like this:
.left {
    width:250px;
    display:flex;
    flex-direction:column;
    justify-content:space-between;
    background:yellow;
}

.right {
    width:calc(100% - 260px);
    display:flex;
    background: blue;
}

.right img {max-width:100%;}

Inside the .left box I have two other boxes with variable heights.
Like this:
.left-one {
    width:100%;
    height:100%;
    background:green;
    margin-bottom:10px;
    overflow:auto;
}

.left-two {
    width:100%;
    background:red;
}

 .left-two img {max-width:100%;}

Everything seems to work.. But...
Inside the .right div I'll have a random image that will make the .wrap height grows. Ok.
And inside the .left-two I'll have another image with unknown dimensions that will make it grow!
This is working. OK.
The problem is:
The .left-one div will have dynamic content with unknown height too (text). And I'm trying .left-one div fill all the avaiable space (discounting .left-two height after recieve image) and overflow the surplus text.
And this is not working!
Here is a fiddle without the text inside left-one div:
https://jsfiddle.net/bson25c1/7/
And here is a fiddle with the text that should be hidden by scrollbar:
https://jsfiddle.net/bson25c1/9/

A: This is the problem:
.left-one {
    width: 100%;
    height: 100%;      <-- height 100% of what?
    background: green;
    margin-bottom: 10px;
    overflow: auto;
}

Since you haven't defined a height on the parent, the percentage height on the child falls back to auto (content-based), per the spec.
Here are complete explanations:

*

*Why is percentage height not working on my div?

*Chrome / Safari not filling 100% height of flex parent
Once you fix that percentage height issue, the vertical scroll bar works fine.
Instead of height: 100%, try flex: 1 0 1px (short for flex-grow, flex-shrink, flex-basis).
The flex-basis: 1px is used to trigger the scrollbar, which requires some form of fixed length.

In order for overflow to have an effect, the block-level container must have either a set height (height or max-height) or white-space set to nowrap.
https://developer.mozilla.org/en-US/docs/Web/CSS/overflow

Then flex-grow: 1 consumes all free space that may be available.
revised fiddle demo

.wrap {
  display: flex;
  justify-content: space-between;
  background: black;
  height: 100vh;
}

.left {
  flex: 0 0 250px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background: yellow;
}

.right {
  flex: 1;
  display: flex;
  background: blue;
}

.left-one {
  flex: 1 0 1px; /* NEW */
  margin-bottom: 10px;
  overflow: auto;
  background: lightgreen;
}

.left-two {
  background: red;
}

.left-two img,
.right img {
  max-width: 100%;
}

body { margin: 0; }

      HELLO
 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO

 HELLO


text:
Q: How to save selected columns in memory? There is a Columns component that allows to choose which column to display in the table and which not.
<mat-form-field>
  <mat-label>Columns</mat-label>
  <mat-select [(ngModel)]="activeCols" multiple>
    <mat-option *ngFor="let c of allCols" [value]="c">{{ c }}</mat-option>
  </mat-select>
</mat-form-field>

How to prevent the previously selected columns for a table from being reset when refreshing the page?
Project on stackblitz

A: I suggest using the Local Storage, this way you'll be able to retain the data after refresh

The read-only localStorage property allows you to access a Storage
  object for the Document's origin; the stored data is saved across
  browser sessions. localStorage is similar to sessionStorage, except
  that while data stored in localStorage has no expiration time, data
  stored in sessionStorage gets cleared when the page session ends —
  that is, when the page is closed.
It should be noted that data stored in either localStorage or
  sessionStorage is specific to the protocol of the page.
The keys and the values are always strings (note that, as with
  objects, integer keys will be automatically converted to strings).

Here is an example for how to save data to Local Storage:
localStorage.setItem("myActiveColumns", activeCols);

A: You can use localStorage to save your data. Here is a stackblitz.
More info is here  Docs


text:
Q: Entity Framework Code First Centralized database deployment I originally posted this on stack overflow but was told that here is a better place to ask this kinda stuff. I couldn't find any other similar answered question but if there is one please give me a link.
I am developing a software which uses a database that is hosted on a main server(MSSQL). Multiple clients can be connected to the same server at any given time. I am using Entity Framework with the Code-First approach.
My concern is how the database is going to be deployed and later updated. Since we are talking about a centralized database, automatic database migration being performed by any of the clients is out of the question in my opinion. I have been thinking of using a separate server configuration app that is going to connect to the server(database) and perform database creation(first time only) and migration when needed.
Also the reason why I think automatic database migration cannot work in my case is because whenever a client is run, it will check if it there is a migration available for the database and if there is, it is going to apply it. That, though, might result in problems for other clients which haven't been updated yet. That is why I think there should be a configuration app that updates the database independently of any of the clients.
Do you think this is a good way to solve the problem or is there a better one?

A: Hey I know it has been a while since I posted this, but I noticed there are people still interested in the answer so I thought I should update with what I chose to go with.
I decided to use a self-hosted WCF service that clients connect to and get their data from. The service is responsible for database creation and migration and also notifies clients if they need to update in order to be able to connect.
I think this is the best solution for my case.


text:
Q: Email newsletter first empty table cell height issue in Outlook 2013 The first empty table cell in my newsletter is displayed much bigger in Outlook 2013. This is what I have:

This works fine on every email client I have tested on but in Outlook 2013, the height seems double the assigned height. I also put the following code in the header but it does not seem to have any effect:

I have similar empty cells further down the newsletter but they are all working fine. Just this first one is having an issue.

A: Outlook 2013 tends to render images/spacers at double their height if they are below 19px. Adding a style to the  and styling the font-size and line-height to 1px should fix this.


text:
Q: Accessing variables in view - Django template I am totally new to python and django. I want to know how to access the dictionary variables in template. I tried few ways but nothing worked out. if i print the variable in the template i receive from my view function this is what i get
{'BSE:INFY': {'instrument_token': 128053508, 'last_price': 1150.3},
'NSE:INFY': {'instrument_token': 408065, 'last_price': 1150}}

I want to loop through the ltp and print something like this
BSE:INFY - 1150.3
NSE:INFY - 1150

EDIT
For ex : in my template
{{ ltp }}

gives the output
{'BSE:INFY': {'instrument_token': 128053508, 'last_price': 1150.3},
'NSE:INFY': {'instrument_token': 408065, 'last_price': 1150}}

now how do i loop through them and print something like above mentioned ?

A: You can use a for loop in the django template.
EX:
{% for key, value in ltp.items %}
    {{ key }} - {{ value.last_price }}
{% endfor %}

A: You can access any dictionary item into your django template as {{dict.key}}.
Suppose you have following dictionary in your views:
 dict = {'first_name':'first','last_name':'last'}

You need to send your dictionary item as follows:
 return render(request, self.template_name, {'data': dict})

To access your dictionary data in template, you can use
    {{ data.first_name }}

To iterate over dictionary, you can do following
{% for key, item in ltp.items %}
    {{ key }} : {{item.instrument_token}}, {{ item.last_price }}
{% endfor %}


text:
Q: A 3D scene within a 3D scene Consider a camera (on a plane) viewing a 3D model of terrain. Imagine now that it takes a photograph of what it sees. I would like to view the terrain from a different camera (even move that camera around) and I would like to see the picture taken by the plane projected on the terrain.
My current approach has been as follows:

*

*Create a 3D scene representing the plane view.

*Create a 3D scene representing the observer view.

*Inside the latter scene there is a model of the terrain upon which I project the whole 3D scene from the plane.

It doesn't work as expected - I won't go into the details quite yet, but can anyone say whether they think this would be the right approach?
Maybe one scene is sufficient with some matrix magic?

A: I think the general way of doing something like this rendering the plane view to a texture, then overlaying that texture on the terrain in the observer view.
Unless of course that's what you're already doing.


text:
Q: TypeScript data object class with Object.assign() properties from constructor argument Here's a class that is constructed to augment a data object with methods.
export default class ViewModel<T> {
  constructor(props: T) {
    Object.assign(this, props);
  }

  foo() {
    console.log('This class and children have methods as well as data');
  }
}

Is it possible to have TypeScript understand that all the props of T exist on the instances of ViewModel<T>?
type User = { id: number; name: string };

const m = new ViewModel<User>({ id: 1, name: 'Alice' });

m.foo(); // fine

console.log(m.id); // Property 'id' does not exist

(Playground)
If not, is there a better way to wrap a plain JS object with methods that access its data properties? I'm not attached to this abstract class and would be fine with UserViewModel in the above case, but the codebase already has many different T types and I'd prefer to re-use them if possible. (E.g. make UserViewModel reference User instead of duplicating much of that type's definition.)
I know I can also export an interface along with the class, like in Extending `this` in Typescript class by Object.assign , but I'd also like the methods in the class to know what values are available on this.

A: TypeScript really doesn't like to let you use class if the type you are extending or implementing doesn't have statically-known members.  A generic type like T doesn't work:
class Foo<T> implements T {} // error!
// A class can only implement an object type or intersection of
// object types with statically known members.

Typescript can represent such class constructors in the type system:
type BarConstructor = new <T>(props: T) => T & { foo(): void }; // okay

and if you had an object of that type you could use it the way you want to use ViewModel:
function makeABarAndDoThings(Bar: BarConstructor) {
  const bar = new Bar({ a: 1, b: "2", c: true });
  bar.foo(); // okay
  bar.a; // okay
  bar.b; // okay
  bar.c; // okay
}

but you can't use class to build a constructor that the compiler understands to be of that sort of generic type.

Note that when you write class Foo {}, you are introducing both a named type called Foo, corresponding to an instance of the class, and a named value called Foo, the constructor of the class.
Since we can't use your ViewModel class implementation directly, we will rename it out of the way, and then use type assertions and type aliases to create a type and a value named ViewModel which does behave as you desire.
Here's the renamed class:
class _ViewModel<T> {
  constructor(props: T) {
    Object.assign(this, props);
  }
  foo() {
    console.log("This class and children have methods as well as data");
  }
}

And here are the new type-and-value combo:
type ViewModel<T> = _ViewModel<T> & T;
const ViewModel = _ViewModel as new <T>(props: T) => ViewModel<T>;

The type ViewModel<T> is defined as the intersection of your _ViewModel<T> with T itself.  And the new ViewModel value is the same as _ViewModel at runtime, but at compile time we've asserted that it is a generic constructor which takes a parameter of type T and produces a ViewModel<T>.

Let's see how it works:
type User = { id: number; name: string };

const m = new ViewModel<User>({ id: 1, name: "Alice" });

m.foo(); // fine
console.log(m.id); // also fine

Looks good to me now.  Hope that helps; good luck!
Link to code


text:
Q: android - apply button default style to linear layout I want to have a button with multiple TextViews - so I figured I should have a linearlayout and put Textviews inside.
I want the linearlayout to look exactly like the button, and I can't achieve that.
Here is how the button "Add Ride" looks like (not the blue title, the grey button):

and the button code is like this, without any style:
 <Button
     android:id="@+id/btnAddRide"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:layout_marginTop="10dip"
     android:text="Add Ride" />

How do I make the linearlayout look like this??
thanks!

A: I think what you should add to you linear layout is:
android:theme="@style/Widget.AppCompat.Button"

A: This is probably the default look of the button. So, if you want your linearlayout too have a look like this then I guess, you will have to take the color of button and have that as background of linearlayout something like
<LinearLayout
    android:id="@+id/lin_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/<btn_bg_color>"
    android:orientation="vertical"
/>


text:
Q: Instantiate error related to path.combine

Here is the codes:
 private void CreatePlayer()
    {
        Debug.Log("Creating Player");
        PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "PhotonPlayer"),
            Vector3.zero, Quaternion.identity);
    }

And There is the error:PhotonNetwork.Instantiate() can only instantiate objects with a PhotonView component. This prefab does not have one: PhotonPrefabs\PhotonPlayer
So my question is :How to solve the error ? I am confused since I thought I have instantiated it but it seemed not to work .As there is no ways to create a game object (not prefab) like capsule within the folder inside the project window. Did I make a path correctly for path.combine ?
Thank you for your patience and hope there's someone who can help me.Your help is greatly appreciated !  If there is any misunderstanding , it is welcomed to tell me and I give more detail of it .Thanks
edit: the first pic show no error and function properly .The second one(mine) can't function .

A: The prefab needs a Photon View component.
The prefab in the first pic looks like it has a child capsule. Right click on your prefab and create a 3D capsule object.


text:
Q: How to remove spaces in filenames on s3 bucket programmatically using boto with python? so I have 1000s of files on my s3 bucket. But, the names of the files contain spaces. I want to replace the space with '_' programmatically using boto python. How do I achieve this?
Thanks.
Snapshot of filenames:

A: It is not possible to rename objects in Amazon S3.
Instead, you would need to call CopyObject() to copy the object, and then DeleteObject() to delete the original object.
Alternatively, here's a cheating method that I use:

*

*I create an Excel spreadsheet with the name of the files

*Then, in Column B, I create a formula to convert the spaces into underlines, so it contains the desired name

*In Column C, I write a command that renames the object, like this:

="aws s3 mv 's3://bucketname/"&A1&"' s3://bucketname/"&B1

*

*Test the command by pasting it into a terminal window

*If it works, use Copy Down to create the formula for all of the files

*Copy that column, paste it into a .sh file, then run the file (preferably on an Amazon EC2 instance to reduce network latency)

The AWS CLI aws s3 mv command will call CopyObject() and DeleteObject().


text:
Q: replace strings with lines from another text file by matching patterns I have a file with a correspondence key -> value:
sort keyFile.txt | head
ENSMUSG00000000001  ENSMUSG00000000001_Gnai3
ENSMUSG00000000003  ENSMUSG00000000003_Pbsn
ENSMUSG00000000003  ENSMUSG00000000003_Pbsn
ENSMUSG00000000028  ENSMUSG00000000028_Cdc45
ENSMUSG00000000028  ENSMUSG00000000028_Cdc45
ENSMUSG00000000028  ENSMUSG00000000028_Cdc45
ENSMUSG00000000031  ENSMUSG00000000031_H19
ENSMUSG00000000031  ENSMUSG00000000031_H19
ENSMUSG00000000031  ENSMUSG00000000031_H19
ENSMUSG00000000031  ENSMUSG00000000031_H19

And I would like to replace every correspondence of "key" with the "value" in the temp.txt:
head temp.txt
ENSMUSG00000000001:001  515
ENSMUSG00000000001:002  108
ENSMUSG00000000001:003  64
ENSMUSG00000000001:004  45
ENSMUSG00000000001:005  58
ENSMUSG00000000001:006  63
ENSMUSG00000000001:007  46
ENSMUSG00000000001:008  11
ENSMUSG00000000001:009  13
ENSMUSG00000000003:001  0

The result should be:
out.txt
ENSMUSG00000000001_Gnai3:001    515
ENSMUSG00000000001_Gnai3:002    108
ENSMUSG00000000001_Gnai3:003    64
ENSMUSG00000000001_Gnai3:004    45
ENSMUSG00000000001_Gnai3:005    58
ENSMUSG00000000001_Gnai3:006    63
ENSMUSG00000000001_Gnai3:007    46
ENSMUSG00000000001_Gnai3:008    11
ENSMUSG00000000001_Gnai3:009    13
ENSMUSG00000000001_Gnai3:001    0

I have tried a few variations following this AWK example but as you can see the result is not what I expected:
awk 'NR==FNR{a[$1]=$1;next}{$1=a[$1];}1' keyFile.txt temp.txt | head
 515
 108
 64
 45
 58
 63
 46
 11
 13
 0

My guess is that column 1 of temp does not match 'exactly' column 1 of keyValues. Could someone please help me with this?
R/python/sed solutions are also welcome.

A: Use awk command like this:
awk 'NR==FNR {a[$1]=$2;next} {
   split($1, b, ":");
   if (b[1] in a)
       print a[b[1]] ":" b[2], $2;
   else
       print $0;
 }' keyFile.txt temp.txt

A: Another awk option
awk -F: 'NR == FNR{split($0, a, " "); x[a[1]]=a[2]; next}{print x[$1]":"$2}' keyFile.txt temp.txt

A: Code for GNU sed:

$sed -nr '$!N;/^(.*)\n\1$/!bk;D;:k;s#\S+\s+(\w+)_(\w+)#/^\1/s/(\\w+)(:\\w+)\\s+(\\w+)/\\1_\2\\2 \\3/p#;P;s/^(.*)\n//' keyfile.txt|sed -nrf - temp.txt
ENSMUSG00000000001_Gnai3:001 515
ENSMUSG00000000001_Gnai3:002 108
ENSMUSG00000000001_Gnai3:003 64
ENSMUSG00000000001_Gnai3:004 45
ENSMUSG00000000001_Gnai3:005 58
ENSMUSG00000000001_Gnai3:006 63
ENSMUSG00000000001_Gnai3:007 46
ENSMUSG00000000001_Gnai3:008 11
ENSMUSG00000000001_Gnai3:009 13
ENSMUSG00000000003_Pbsn:001 0

A: Another awk version:
awk 'NR==FNR{a[$1]=$2;next}
{sub(/[^:]+/,a[substr($1,1,index($1,":")-1)])}1' keyFile.txt temp.txt


text:
Q: .htaccess Url Rewrite stop my search function i have set in .htaccess Url Rewrite
all working just my search function stop how to make working search function
my search URL is this
http://domain.com/index.php?a=search&q=word

but after submit search box url this and not work
http://www.domain.com/?a=search&q=word

how can i make search box work ?
my htaccess file
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.domain.com
RewriteRule (.*) http://domain.com/$1 [R=301,L]
RewriteCond %{request_filename} -f
RewriteRule ^(.*) $1 [L]
RewriteRule ^([^/]*)$ /index.php?a=$1 [L]
RewriteRule ^([^/]*)/([^/]*)$ /index.php?a=$1&q=$2&page=$3 [L]
RewriteRule ^([^/]*)/([^/]*)/([^/]*)$ /index.php?a=$1&q=$2&page=$3 [L]

my search form
<form class="form-wrapper cf">
<form accept-charset="UTF-8" action="http://www.domain.com/index.php" method="get">
<input name="a" type="hidden" value="search" />
        <input type="text" id="search" name="q" placeholder="Search here..." required>
        <button type="submit">Search</button>
</form>

THanks

A: i got solutions by change
<form class="form-wrapper cf">
<form accept-charset="UTF-8" action="/index.php" method="get">
<input name="a" type="hidden" value="search" />
        <input type="text" id="search" name="q" placeholder="Search here..." required>
        <button type="submit">Search</button>
</form>

Change TO

<form accept-charset="UTF-8" action="/index.php" method="get">
<input name="a" type="hidden" value="search"/>

<input id="search" name="q" type="text"/>
<button type="submit">Search</button>
</form>


text:
Q: How do I change struct variables in a C function? Basically, what I am trying to do is change struct variables inside a function. Here's the code:
int weapon_equip(struct player inventory, int in) {
    int x = in - 1, y;
    int previous_wep[4];

    //Stores the values of the previous equipped weapon.
    for(y = 0; y < 4; y++)
        previous_wep[y] = inventory.weapons[0][y];

    /* Since the equipped weapon has a first value of 0,
    I check if the player hasn't chosen a non-existant
    item, or that he tries to equip the weapon again.*/
    if(inventory.weapons[x][TYPE] != NULL && x > 0) {
        inventory.weapons[0][TYPE] = inventory.weapons[x][TYPE];
        inventory.weapons[0][MATERIAL] = inventory.weapons[x][MATERIAL];
        inventory.weapons[0][ITEM] = inventory.weapons[x][ITEM];
        inventory.weapons[0][VALUE] = inventory.weapons[x][VALUE];

        inventory.weapons[x][TYPE] = previous_wep[TYPE];
        inventory.weapons[x][MATERIAL] = previous_wep[MATERIAL];
        inventory.weapons[x][ITEM] = previous_wep[ITEM];
        inventory.weapons[x][VALUE] = previous_wep[VALUE];
    }
}

Basically, what the function does is, it changes the first value of the selected weapon array into 0, making it equipped to the player. It swaps the places of the equipped weapon, with the selected weapon to equip.
But the thing is - I have to change a lot of variables in the function, and all of them belong in a struct. I know how to change normal integers in a function(with pointers), but I have no idea how to do it with structure variables.

A: When you pass a struct to a function, all its values are copied (on the stack) as arguments to the function. Changes made to the struct are only visible inside the function. To change the struct outside of the function, use a pointer:
int weapon_equip(struct player *inventory, int in)

and then
inventory->weapons[0][TYPE] = inventory->weapons[x][TYPE];

which is a prettier version of
(*inventory).weapons[0][TYPE] = (*inventory).weapons[x][TYPE];

A: To access the members of a structure using a pointer to that structure, you must use the → operator as follows −
structPointer->variable=5

Example
struct name{
int a;
int b;
};

struct name *c;
c->a=5;

or with
(*c).a=5;


text:
Q: What is @!72,27;BDH and @!0,27;BDH? There are other posts here asking about a mysterious program called @!0,27;BDH.
This program (is it a program?) appeared out of nowhere for me after I upgraded from 20.10 to 21.04 last Friday.
I noticed it first when attempting to share my screen on a Zoom meeting with my friends. Upon sharing a screen on Zoom, you may choose to share your entire desktop screen or a specific application. This @!0,27;BDH program appeared as one of the options for screen sharing. I could also see it if I press Ctrl+Alt+Tab.
I saw the other posts about @!0,27;BDH and none of them presented any solutions or answers. And this program didn't affect me in the exact same way as it did other people. It appears that it gets people stuck in Activities Overview Mode like this. It happened to me a few times but not too often and it has never been like this.
I decided to reinstall Ubuntu 21.04 from scratch today, erasing the disk and all. I had, of course, backup all my files. Upon finishing the installation I noticed that it now appears as @!72,27;BDH and not @!0,27;BDH.
I never noticed it before when I was using 20.10. I'm starting to feel really worried about this. Does anyone have any idea what it is and how to get rid of it?
Here it is as an option for screen sharing on Zoom.
EDIT: showing ls -al ~/.local/share/gnome-shell/extensions and ls -al /usr/share/gnome-shell/extensions as requested:
    jorgepotyguara@jorgepotyguara-Inspiron-3268:~$ ls -al ~/.local/share/gnome-shell/extensions
    ls: cannot access '/home/jorgepotyguara/.local/share/gnome-shell/extensions': No such file or directory

    jorgepotyguara@jorgepotyguara-Inspiron-3268:~$ ls -al /usr/share/gnome-shell/extensions
    total 20
    drwxr-xr-x 5 root root 4096 abr 20 07:44 .
    drwxr-xr-x 7 root root 4096 abr 20 07:49 ..
    drwxr-xr-x 2 root root 4096 jun 10 20:06 ding@rastersoft.com
    drwxr-xr-x 3 root root 4096 abr 20 07:44 ubuntu-appindicators@ubuntu.com
    drwxr-xr-x 3 root root 4096 abr 20 07:44 ubuntu-dock@ubuntu.com

A: Go to https://extensions.gnome.org/local/, or use the Extensions or Tweaks app...
Disable Desktop Icons NG (ding) and restart gnome-shell (if on X11), or log out/in (if in Wayland). Remove/uninstall ding.
Reinstall the original Desktop Icons gnome-shell extension...
sudo apt update
sudo apt install gnome-shell-extension-desktop-icons
Restart gnome-shell (if on X11), or log out/in (if on Wayland).
Report this issue at https://gitlab.com/rastersoft/desktop-icons-ng/-/issues


text:
Q: jQuery Traversing Dynamically generated DOM (next(), prev()) I have an HTML table and jQuery handlers to move rows up and down, using .next() and .prev(), but I also want to add new rows and after adding new row and trying to move old rows up or down they move more positions than expected. Here is an example on jsfiddle http://jsfiddle.net/3CQYN/
$(function() {

    initControls();

    $('.new').click(function() {

        $('
TEST	Up Down
').appendTo($('table tbody'));

        initControls();

    });

});

function initControls()
{
    $('.down').click(function() {
        var parentRow = $(this).closest('tr');

        parentRow.insertAfter(parentRow.next());
});

$('.up').click(function() {
        var parentRow = $(this).closest('tr');

        parentRow.insertBefore(parentRow.prev());
    });
}

Try to move rows up and down, then add few new rows and move the OLD rows up and down again and you'll see the problem.

A: Every time you add a new row, you rebind the handlers, ending up with multiple handlers bound to individual up and down links. Instead, use event delegation (only executed once, on DOM ready):
$(document).on('click', '.down', function() {
    // ...
});

$(document).on('click', '.up', function() {
    // ...
});

http://jsfiddle.net/Gt4Zq/
Note that if you can find a container to bind to that is closer to the elements than document, that would be preferable.


text:
Q: "Error in strsplit(version_with_dots, "\\.")[[1]] : subscript out of bounds" for updater function I am using package installr version 0.17.0 to update R and related packages. However, I get the following error message when I typed updater():
Error in strsplit(version_with_dots, "\\.")[[1]] :
  subscript out of bounds

How can I deal with this situation?

A: The current version of R is "3.2.4 Revised". installr appears to be having trouble with the " Revised" part of the name. The bug has been fixed in the latest version of the package.


text:
Q: DokuWiki - Code Example Breaking When I put example code in the  tags it does not show as code but appears as normal text.
Can anyone shed some light on what is happening and how it can be corrected.
Screen Grab of code:

Output of what I get:


text:
Q: mxGraph - How to automatically resize mxCell to content width if it exceeds the default size How can I create an mxCell, setting the minimum width of its mxGeometry, but that would resize to the width of the html element of its value field if it is higner than the default width?
For now I have this code
var style = 'rounded=0;whiteSpace=wrap;html=1;autosize=1;resizable=0;';
var cell = new mxCell(value, new mxGeometry(0, 0, width, height), style);

But when I create this mxCell, it is always of size "width" and "height", even when the html element it contains (an h3 title) exceeds the mxRectangle. How can I fix this?
Edit : Thanks, it worked using graph.updateCellSize(). As I wanted to change the size only if it had to be higher than default, I wrote this code
this.graph.updateCellSize(cell, true);
var geom = cell.getGeometry();
geom.width = geom.width > width ? geom.width : width;

It changes the value twice, which is inefficient. I found another way using getPreferredSizeForCell
var preferred = this.graph.getPreferredSizeForCell(cell);
var current = cell.getGeometry();
current.width = preferred.width > width ? preferred.width : width;
current.height = preferred.height > height ? preferred.height : height;

A: Try graph.updateCellSize(cell, true);


text:
Q: Access row relatively with position number in Power Query I've this source of data https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo
I want to select "Time Series (1min)" and then first record from it - because the time changes and then "1. open".
I tried to use this query
= Json.Document(Web.Contents("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo"), 1250)
= Source[#"Time Series (1min)"]{0}[#"1. open"]

But I get:
Expression.Error: We cannot convert a value of type Record to type List.
Details:
    Value=Record
    Type=Type

This didn;t helped me http://excel-inside.pro/blog/2015/11/05/absolute-and-relative-references-in-power-query/ I think the problem might lay that I'm getting null when referencing first row.

A: Try:
let
Source = Json.Document(Web.Contents("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo"), 1250),
#"Time Series (1min)" = Source[#"Time Series (1min)"],
#"Converted to Table" = Record.ToTable(#"Time Series (1min)"),
Value = #"Converted to Table"{0}[Value]
in
Value


text:
Q: Gradle - How can I execute bat file in new cmd window? An part of build.gradle:
task runCraftBukkit(type:Exec) {
    println "Starting CraftBukkit server..."
    commandLine = ['cmd', '/C', 'start', 'D:/Projects/WorkSpaces/WorldCleaner/devserver/start.bat'] // cmd /C start D:/Projects/WorkSpaces/WorldCleaner/devserver/start.bat
    workingDir = file('./devserver/')
}
jar.doLast {
    runCraftBukkit.execute()
}

Output:
15:13:54: Executing external task 'jar'...
Starting CraftBukkit server...
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:jar UP-TO-DATE

BUILD SUCCESSFUL
...

But the command prompt window and does not appear.
Question:
What I do wrong?

A: Working solution:
task runCraftBukkit(type:Exec) {
    doFirst {
        println "Starting CraftBukkit server..."
        workingDir = file('./devserver/')
        commandLine = ['cmd', '/C', 'start', 'start.bat']
        // cmd /C start D:/Projects/WorkSpaces/WorldCleaner/devserver/start.bat
    }
}
jar.finalizedBy runCraftBukkit

I spent a lot of time looking for errors. And the problem was not one :)
The main problem was that the task is not executed. Decision proved method .finalizedBy
And now:
...
:jar UP-TO-DATE
:runCraftBukkit
Starting CraftBukkit server...
...

That is exactly what i want to see :]


text:
Q: How to install node.js v16 on VPS cPanel WHM when ea-nodejs10 installs v10.24.1? I want to yum install xrpl to sign transactions via the xrpl.js library on a cPanel WHM VPS and have made it through How to install a Node.js Application enough that all four ea-*** RPMs, including ea-nodejs10 v10.24.1, have been installed. However, xrpl.js recommends node.js v14 while also supporting v12 & v16.
Further, package-lock.json must be installed prior to xrpl.js - yet even though WHM Edit Package shows package-lock.json added:

yum install package-lock.json throws "No package package-lock.json available." Although repeating yum install ea-nodejs10 returns "Package already installed."
So I would appreciate advice on how to install node.js v14 and package-lock.json on this system thanks.

A: I am now able to sign, send, and validate XRP Ledger transactions with python - hence my iOS-XRPL UI javascript brew will delegate its signing-validating to python functions.
Edit:
MobileApp-XRP Ledger blockchain Linux dedicated server xrpl-py library installation
MobileApp business XRPL transactions on MoblieAppDomainName.com browser requires a Dedicated Server, instead of a VPS, to install the required xrpl-py python library. Several guides continue to evolve for the several systems.
Present solution starts with Bluehost Linux DS Python Installation latest version 3.9.2 guide.
However the make install command attempts - and fails - to break the existing python 2.7 installation integral to the cPanel framework and needs to be replaced by make altinstall as described by Grepitout: How to Install Python 3 in cPanel Server.
Except that didn't quite work either -> What eventually worked on author's Mac OS-Linux system was Computing for Geeks: Install Python 3.9 on CentOS 8 / CentOS 7 guide:
$ ssh username@serveripaddress
sudo yum -y update
sudo yum groupinstall "Development Tools" -y
sudo yum install openssl-devel libffi-devel bzip2-devel -y
$ gcc --version
sudo yum install wget -y
wget https://www.python.org/ftp/python/3.9.7/Python-3.9.7.tgz
tar xvf Python-3.9.7.tgz
cd Python-3.9*/
./configure --enable-optimizations
sudo make altinstall
$ python3.9 --version
Python 3.9.7


text:
Q: ProfileBase Create method return returning null I am using the aspnet_Profile table , it runs locally but when I push it to dev environment and run it there ProfileBase.Create(user.Username) returns a null value.
var user = Membership.GetUser(Username);

is not null and returns a user ,so I'm not sure why a null value is being return for ProfileBase.Create.
Any ideas?

var user = Membership.GetUser(Username);
var ext_user= ProfileBase.Create(user.UserName) as UserProfile;
ext_user.Name = Name;
ext_user.Save();

public class UserProfile : ProfileBase
    {
        public static UserProfile GetUserProfile(string UserName)
        {
            return Create(UserName) as UserProfile;
        }

        public string NameExtended
        {
            get { return base["NameExtended"] as string; }
            set { base["NameExtended"] = value; }
        }

    }

A: Fabii is correct with the marked answer, but I didn't initially understand what the answer was until resolving this issue myself.  For the record, you need to do something similar in your config file in which your inherits statement points to your class that is inheriting from ProfileBase:
<profile defaultProvider="DefaultProfileProvider" inherits="YourNamespace.YourClass">

A: Resolved ,silly mistake on my part. The inherit attribute was not set in my environment .config file.


text:
Q: Refreshing tokens Blazor server side openId connect I'm having struggling to get the authentication in a Blazor server side app to work as expected.
I have been following this documentation, and added registered the scoped service: ASP.NET Core Blazor Server additional security scenarios
From _Host.cshtml  I am fetching the tokens from HttpContext:
 var tokens = new InitialApplicationState
            {
                AccessToken = await HttpContext.GetTokenAsync("access_token"),
                RefreshToken = await HttpContext.GetTokenAsync("refresh_token"),
                IdToken = await HttpContext.GetTokenAsync("id_token"),
                ExpiresAtUtc = expiryTime.UtcDateTime,
            };

They are then passed to  App.razor.
 protected override Task OnInitializedAsync()
    {
        var shouldSetInitialValues = TokenProvider.AccessToken is null || TokenProvider.RefreshToken is null;
        if (shouldSetInitialValues)
        {
            TokenProvider.AccessToken = InitialState!.AccessToken;
            TokenProvider.RefreshToken = InitialState.RefreshToken;
            TokenProvider.IdToken = InitialState.IdToken;
            TokenProvider.ExpiresAtUtc = InitialState.ExpiresAtUtc;
        }

        return base.OnInitializedAsync();
    }

The problem I am having, is that sometimes the AccessToken in the HttpContext has expired. When this happens, I simply want to refresh the token. I have code in place that makes sure that the token is valid when an AccessToken is present.
But every time a new request is sent, or when navigating to a different page, the TokenProvider is cleared, so shouldSetInitialValuesis always set to true.
Then a expired AccessToken is always passed into the TokenProvider.
How do I update the AccessToken once expired?

A: I solved this by updating the tokens stored in the HttpContext instead.
First I was trying to do this with a newly created razor page, but ran into some issues with redirecting the user afterwards.
Eventually I placed the logic for updating the tokens directly in the _Host.cshtml.
EDIT:
Inside of _Host.cshtml I check if the token has expired:
@{
    Layout = "_Layout";

    var tokenExpiry = await HttpContext.GetTokenAsync("expires_at");
    DateTimeOffset.TryParse(tokenExpiry, out var expiresAt);
    var accessToken = await HttpContext.GetTokenAsync("access_token");

    var tokenShouldBeRefreshed = accessToken != null && expiresAt < DateTime.UtcNow.AddMinutes(20);
    if (tokenShouldBeRefreshed)
    {
        await RefreshAccessTokenAsync();
    }

    accessToken = await HttpContext.GetTokenAsync("access_token");

    var refreshToken = await HttpContext.GetTokenAsync("refresh_token");
}

<component type="typeof(App)" param-InitialAccessToken="accessToken" param-InitialRefreshToken="refreshToken" render-mode="Server" />

The method RefreshAccessTokenAsync() looks something like this:
 async Task RefreshAccessTokenAsync()
    {
        var auth = await HttpContext.AuthenticateAsync();

        if (!auth.Succeeded)
        {
            await HttpContext.SignOutAsync();
            return;
        }

        var injectedIOptionsHere= injectedIOptionsHere.Value;
        var refreshToken = await HttpContext.GetTokenAsync("refresh_token");

        if (refreshToken == null)
        {
            await HttpContext.SignOutAsync();
            return;
        }

        var httpClient = HttpClientFactory.CreateClient();
        var refreshTokenUrl = $"{injectedIOptionsHere.Authority}/common/oauth/tokens?";

        var postData = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("grant_type", "refresh_token"),
                new KeyValuePair<string, string>("client_id", injectedIOptionsHere.ClientId!),
                new KeyValuePair<string, string>("client_secret", injectedIOptionsHere.ClientSecret!),
                new KeyValuePair<string, string>("refresh_token", refreshToken!),
                new KeyValuePair<string, string>("redirect_url", injectedIOptionsHere.RedirectUrl!),
            };

        var content = new FormUrlEncodedContent(postData);
        HttpResponseMessage? responseMessage = await httpClient.PostAsync(refreshTokenUrl, content);
        responseMessage.EnsureSuccessStatusCode();
        var responseJson = await responseMessage.Content.ReadAsStringAsync();
        var responseJObject = JObject.Parse(responseJson);
        var newAccessToken = responseJObject.GetStringValue("access_token");
        var expiresInSeconds = responseJObject.GetIntValue("expires_in");
        var newExpiryTime = DateTime.UtcNow.AddSeconds(expiresInSeconds).ToString(CultureInfo.InvariantCulture);

        var expiresAtTokenUpdated = auth.Properties!.UpdateTokenValue("expires_at", newExpiryTime);
        var accessTokenUpdated = auth.Properties!.UpdateTokenValue("access_token", newAccessToken);

        var tokensUpdatedCorrectly = expiresAtTokenUpdated && accessTokenUpdated;

        if (tokensUpdatedCorrectly)
        {
            await HttpContext.SignInAsync(auth.Principal, auth.Properties);
        }
    }

Hope this helps!


text:
Q: error "permission denied" in VPS servers I am noob and I have two VPS servers. In the first server, I have user "bob". And I copied-pasted folder (home/bob) this user in the same folder in second VPS server. And when I tried to change a file in this folder (in the second server) a console speaks "permission denied ". What is the problem?

A: Copying files tends to copy permissions, which includes the UID. You will need to reset the UID:
sudo chown -R youruser:youruser /path/to/folder

So, if you want to make /home/bob owned by bob on your second VPS, run:
sudo chown -R bob:bob /home/bob

I would recommend you read these two excellent pages from the Arch Wiki:

*

*Users and Groups

*File Permissions and Attributes


text:
Q: Why Hazelcast CacheLoader class needs to be visible by all clients? Currently I'm discovering the Hazelcast technology. I'm trying to implement it in a system combined with multiple clients apps and one central server.
The server is the only provider of data from an external source. The data is cached by the Hazelcast ICache and loaded at request of Hazelcast client by a class implementing the CacheLoaded interface.
The CacheLoader implementor has to be in clients classpathes (I get ClassNotFoundException if I remove it) and this is the thing I don't understand... If a Hazelcast client is connected to the server, the CacheLoader is invoked on the server side. Moreover I don't know the implementation would look like if it's dependant on i.e. server database.
Thanks for any help!


text:
Q: Alternative to using triggers to automatically send email for each calendar event created I am trying to automate certain parts of my workflow for scheduling clients with Google Calendar. I've successfully managed to capture new/edited/deleted events in Google Apps Script using a trigger which detects changes and Calendar.event.list to sync those changes with a spreadsheet.
I create a new row, or edit an existing one, in my spreadsheet of all the clients. What I desire to do is three days before the appointment with the client, automatically generate a custom email with all of their details, to send them as a reminder regarding the appointment.
My plan was every time a new row was created in the Spreadsheet (when a new Calendar event was created), was to make a new email trigger. That trigger would execute code to create an email, with all of the clients info.
function createEmailTrigger(event) {
  var today = new Date();
  today.setHours(0,0,0,0);  // Don't care about time

  // Create Email Trigger three days before
  const sendDaysBefore = 3;
  var daysBefore = new Date(event.start);
  daysBefore.setDate(daysBefore.getDate() - sendDaysBefore);

  var trigger = ScriptApp.newTrigger('sendEmail')
    .timeBased()
    .at(daysBefore)
    .create();

  associateEventWithTrigger(trigger.getUniqueId(), event);

  return trigger.getUniqueId();
}

associateEventWithTrigger connects the trigger id with the Calendar event. sendEmail would then create a new email with all of the client's info, which came from the Calendar event. When the trigger is executed, it deletes the trigger since it won't be used again.
All of this was working fine, as I was testing one Calendar event at a time. However, once I decided to sync all of this year's Calendar events, the script very quickly threw this error:
Exception: This script has too many triggers. Triggers must be deleted from the script before more can be added.

Apparently you can only have 20 triggers per user/script. This is very inconvenient, as I was expecting to create hundreds of triggers.
Therefore, I need to rethink how to go about doing this. Any suggestions? I appreciate it.

A: Proposed workaround
This script is designed to be run on a time-driven trigger that runs daily.
function sendReminderEmails() {
  let file = SpreadsheetApp.getActive();
  let sheet = file.getSheetByName("Sheet1");
  let range = sheet.getDataRange();
  let values = range.getValues();

  // removing headers
  values.shift()

  values.forEach(row => {
    let name = row[0]
    let email = row[1]
    let date = row[2]

    // Date object representing time now
    let now = new Date();

    // helper variables
    let second = 1000;
    let minute = second * 60;
    let hour = minute * 60;
    let day = hour * 24;

    // gets time to appointment in milliseconds
    let timeToApp = date.getTime() - now.getTime()

    if (timeToApp > 2 * day && timeToApp < 3 * day) {
      MailApp.sendEmail(
        email,
        "Remember Your Appointment",
        "Hello " + name + ",\nYou have an appointment coming up soon."
      )
    }
  })
}

This is based on a sample spreadsheet like this:

So you would need to adapt it to your particular format.
Script walkthrough

*

*It is based on the date object.

*If your dates are stored as formatted dates in your spreadsheet, when you getValues, Apps Script will automatically pass them as Date object. Alternatively you can cast them as Date objects in Apps Script if needed.

*The script starts off by getting all the values in the target sheet.

*It initialized a new Date object that represents the time now.

*It then goes through each row of the target sheet and gets a value for how long until the appointment.

*If the value is between 2 days and 3 days, then an email is sent.

A: I Think you could make an script to search events every day , events that are 3 days ahead , select then and send email. So it will be just one script that will be triggeres every day, using the date trigger mode.


text:
Q: How to Fake Host and Multithread Download of One File? I would like to download the 227 GB data file here but it takes me about 20-24 hours now. Torrent protocol would be awesome for the task and/or parallel process in the download but the host is limiting the number of connection to one (1).
Proposals

*

*Can you fake host and multithread the task with wget here? ... I think not easily ...
Pseudocode where I think disabling directories and disabling host directories make sense; putting robots off; taking only the .bin file; saying my browser is mozilla; downloading to the directory /tmp/; the number of thread 150
wget -n 150 -nd -nH -e robots=off -A".bin" -U mozilla \
    -P /tmp/ http://horatio.cs.nyu.edu/mit/tiny/data/tiny_images.bin

*exclude proxilla since not in apt-get
Characteristics

*

*Host limits the number of connections to one (1).

*I set 150 number of connections in the axel because my max download speed is 30 MB so should get 15 MB/s (=0.1 MB/s * 150) download speed but now estimated time is 21 h at the start.

*VPN attempt: Just if the host starts to blacklist the user.

Exclude axel from the task
Axel fails even with 1-16 connections where wanting also the progress bar (-a)
# http://www.cyberciti.biz/tips/download-accelerator-for-linux-command-line-tools.html
axel -a -n 1 -s 16 http://horatio.cs.nyu.edu/mit/tiny/data/tiny_images.bin
Initializing download: http://horatio.cs.nyu.edu/mit/tiny/data/tiny_images.bin
File size: 243615796224 bytes
Opening output file tiny_images.bin
Error opening local file

Exclude aria2c from the task

*

*Host causes failure even with 2-16 number of connections; -c allows continuation of download if it gets interrupted, -x 10 and -s 10 allow up to 10 connections per server
# http://askubuntu.com/a/507890/25388
aria2c -c -x10 -s10 http://horatio.cs.nyu.edu/mit/tiny/data/tiny_images.bin

08/17 21:27:25 [ERROR] CUID#6 - Download aborted. URI=http://horatio.cs.nyu.edu/mit/tiny/data/tiny_images.bin
Exception: [AbstractCommand.cc:398] errorCode=16 URI=http://horatio.cs.nyu.edu/mit/tiny/data/tiny_images.bin
  -> [RequestGroup.cc:714] errorCode=16 Download aborted.
  -> [AbstractDiskWriter.cc:222] errNum=13 errorCode=16 Failed to open the file /media/masi/SamiSwapVirtual/tiny_images.bin, cause: Permission denied

08/17 21:27:25 [NOTICE] Download GID#1e5701ee3b4d44f4 not complete: /media/masi/SamiSwapVirtual/tiny_images.bin

Download Results:
gid   |stat|avg speed  |path/URI
    ======+====+===========+=======================================================
1e5701|ERR |       0B/s|/media/masi/SamiSwapVirtual/tiny_images.bin

Status Legend:
(ERR):error occurred.

aria2 will resume download if the transfer is restarted.
If there are any errors, then see the log file. See '-l' option in help/man page for details.

Ubuntu: 16.04 64 bit
LTE router: TP-link MR220 with the latest firmware
LTE connection: 30/20 MB for Download/Upload
Download HDD: 2 TB ext4 Transcend

A: Unfortunately, what you are asking is pretty much impossible. You can't force a server to allow multiple connections.
If they limit the number of connections based on IP then you would need to send a different IP for each connection. At that point, you would need a program that can merge multiple parts of the same file from different computers with parts created on-the-fly. This should be technically possible but certainly not practical because you'd have to find such a program and, to my knowledge, such a program does not exist.

There are only 2 choices I can think:

*

*Download with the rate allowed.

*Transload the file from that server to another server and then download from that server.

*

*this is the fastest option but utilizes an existing server in a datacenter preferably.

*this is not a practical option for most people.

With that said, I tested the download myself and it provides the absolute maximum speed that my internet plan can handle with only one connection.
I have a 60 Mbit connection so I can download files at between 5.5MBps - 7.5MBps (megabytes per second). This download from NYU offered 7.2MBps which is totally reasonable and more than my average top speed of 6.5MBps. This means that downloading at my speed would take about 10 hours.
I suspect that you have a 30Mbit connection resulting in twice as much time so it is my estimation that the bottleneck is on your end, not NYU.


text:
Q: RxSwift - Receive the same event at two ViewControllers at the same time Hi i'm just getting started with RxSwift and decided to make simple Currency Exchange application. My app has two view's (allCurrenciesList and userFavouritesView). Basically all logic works, but only if i run networking func every single time one of view didAppear/didLoad. My point is two fetch it only once, and received many times, when necessary.  Application fetch dictionary of currencies and in ViewModel pass it to BehaviorSubject, and when view being load/appear it just subscribe it, and use it in UITableView. Thanks
class ListViewModel {

    let service: CurrencyService!
    var curriencies = BehaviorRelay<[Currency]>(value: [])
    var currienciesObservable: Observable<[Currency]> {
        return curriencies.asObservable().share()
    }
    let disposeBag = DisposeBag()

    init(service: CurrencyService) {
        self.service = service
    }

    func fetchAllCurrencies() {

            self.service.fetchAllSymbols { result in
                switch result{
                case .success(let currencies):
                    self.dictionaryIntoArray(currencies: currencies["symbols"] as! [String : Any])
                case .failure:
                    print("error")

                }
            }
    }

    private func dictionaryIntoArray(currencies: [String: Any]) {
        var currencyArray = [Currency]()
        for (symbol, name) in currencies {
            currencyArray.append(Currency(symbol: symbol, fullName: name as! String))
        }
        let sortedArray = currencyArray.sorted { $0.fullName < $1.fullName }
        self.curriencies.accept(sortedArray)
    }

allCurrenciesList
override func viewDidLoad() {
        super.viewDidLoad()
        setupView()
        configureTableViewDataSource()
        tableView.delegate = self
        fetchData()
    }

    private func fetchData() {
        viewModel.fetchAllCurrencies() // this func is necceserry everysingle time
        viewModel.currienciesObservable.subscribe(onNext: { curriencies in
            self.applySnapshot(curriencies: curriencies)
        }).disposed(by: disposeBag)
    }

userFavouritesView
 override func viewDidLoad() {
        super.viewDidLoad()

        viewModel.fetchAllCurrencies() // this func is necceserry everysingle time
        viewModel.currienciesObservable.subscribe(onNext: { allCurencies in
            let selectedItems = UserDefaults.standard.array(forKey: "SelectedCells") as? [Int] ?? [Int]()
            var currenciesArray: [Currency] = []
            selectedItems.forEach { int in
                self.pickerValues.append(allCurencies[int])
                currenciesArray.append(allCurencies[int])
            }
            self.applySnapshot(curriencies: currenciesArray)
        }).disposed(by: disposeBag)

    }

A: The key here is to not use a Subject. They aren't recommended for regular use. Just define the currienciesObservable directly.
Something like this:
class ListViewModel {
    let currienciesObservable: Observable<[Currency]>

    init(service: CurrencyService) {
        self.currienciesObservable = service.rx_fetchAllSymbols()
            .map { currencies in
                currencies["symbols"]?.map { Currency(symbol: $0.key, fullName: $0.value as! String) }
                    .sorted(by: { $0.fullName < $1.fullName }) ?? []
            }
    }
}

extension CurrencyService {
    func rx_fetchAllSymbols() -> Observable<[String: [String: Any]]> {
        Observable.create { observer in
            self.fetchAllSymbols { result in
                switch result {
                case let .success(currencies):
                    observer.onNext(currencies)
                    observer.onCompleted()
                case let .failure(error):
                    observer.onError(error)
                }
            }
            return Disposables.create()
        }
    }
}

With the above, every time you subscribe to the currenciesObservable the fetch will be called.

A: As I understand, it's because your fetchAllSymbols function was not stored in the DisposeBag.
func fetchAllCurrencies() {
    self.service.fetchAllSymbols { result in
         switch result{
            case .success(let currencies):
                self.dictionaryIntoArray(currencies: currencies["symbols"] as! [String : Any])
            case .failure:
                print("error")

         }
    }.dispose(by: disposeBag)
}


text:
Q: How to generate a multi-columns table with the checkbox form insert in the first column? This is my forms.py file:
from django import forms

class MusicCheckboxForm(forms.Form):
    songs = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple())

I want use the forms.py file to produce the multi-columns table with the checkbox insert to the first column, But I don't want hard code <input type="checkbox" ...> to the template.
And I want the multi-columns look like this:
All song artist album genre date
[]  aaa  Smith  fdaf  rock 2001
[]  bbb  Davis  fdsaf blue 2002
[]  ccc  Doe    dfaj  sjaf 2000

The snippet of my template looks like this:

    music list

    All
    song
    artist
    album
    genre
    date

  {% for info in all_info %}

    {% if info|hasattr:"title" %}
      {{ info.title }}
    {% else %}

    {% endif %}

    {% if info|hasattr:"artist" %}
      {{ info.artist }}
    {% else %}

    {% endif %}

    {% if info|hasattr:"album" %}
      {{ info.album }}
    {% else %}

    {% endif %}

    {% if info|hasattr:"genre" %}
      {{ info.genre }}
    {% else %}

    {% endif %}

    {% if info|hasattr:"date" %}
      {{ info.date }}
    {% else %}

    {% endif %}

  {% endfor %}

A: django-tables2 simplifies transforming data into HTML tables. It does for HTML tables what django.forms does for HTML forms..
See this : http://django-tables2.readthedocs.org/en/latest/index.html


text:
Q: What is the advantage of using useDebounce insted of using just debounce function I have noticed people using this kind of useDebounced hook:
import { useState, useEffect } from 'react';

export default function useDebounce(value: any, delay: number) {

    const [debouncedValue, setDebouncedValue] = useState(value);

    useEffect(
        () => {
            const handler = setTimeout(() => {
                setDebouncedValue(value);
            }, delay);

            return () => {
                clearTimeout(handler);
            };
        }
    );

    return debouncedValue;
}

*Taken from https://dev.to/gabe_ragland/debouncing-with-react-hooks-jci
What is the advantage of using the hook, and not just simple javascript debounce, like in lodash library??


text:
Q: Is there anyway to safely clean up local Firebase project folder? I'm new to Firebase. Recently, in order to fix certain errors, I tried many different ways until I feel that my local project folder is pretty much messed up, which could cause more other hidden problems. For example, I keep running npm init on many different folders, sometimes manually edited the package.json file, run npm install firebase@5.9.4 --save on several different folders and so on.
So I wonder, is there a way (or tool) that we can scan through our project folder and safely clean it up, e.g. remove redundant/unused dependencies, e.g. node_modules, add required dependencies, fix declarations/referencing errors, and so on without removing user-created assets like .js, .css, images etc.? I want to do that is because I believe this could potentially reduce many hidden problems and help to narrow down my troubleshooting tasks...
Alternatively, can I do the following:

*

*Backup all my JS files.

*Empty my Firebase's functions folder.

*run firebase init again.

*Restore my JS files.

*Deploy and troubleshoot my Firebase functions again? Or any steps missing?

Sorry for a silly question. Any advice would be much appreciated, thank you!

A: If you think there is a problem with the contents of your node_modules folder:

*

*Remove all node_modules folders completely.  They don't contain any special information.  It is just copies of modules downloaded from the internet.

*Rebuild it completely with npm install from the correct location (your functions folder), which uses your package.json to determine what it should contain.


text:
Q: get rows where queryColumns > tableColumns as well as queryColumns = tableColumns SORRY I COULDN'T THINK OF BETTER TITLE
usually we have a table and we have a query  and we want rows which in them
query = table but what if also want the rows if query > table
so here is an example ,  lets say we have a website which connects people who wants some services to companies , we have 4 services a,b,c,d,
so a user would select his desired services an we store them in database
wanted :
+-----------+----------+---------+------+--------
| user_id   | a        | b       | c    | d     |
+-----------+----------+---------+------+--------
|  23       | 1        |   0     | 1    | 0     |
+-----------+----------+---------+---------------

for example this guy wants a,c

now a company would come to our website and says we offer a,c
so i query
 $query = "select user_id from wanted where a=1 && c =1 ";

i get user 21 and i would connect them to each other .
but what if the company offers services a,b,c
 $query = "select user_id from wanted where a=1 && b =1 && c=1 ";

it wouldn't return user 21 , but it should .... they are not perfect match but service required by user  21 is covered by this company
i know i should to the process other way around and first store companies and let the users search for them and i wouldn't have this problem , but this how this website works
so what are my options ? anything can be done ?
pleas note that i can't use OR ||  cuz the company should cover all the needs of customer
so if i have a user x which  wants a,b,c and company with a,b,d
the query
select * from wanted where a = 1 || b = 1 || d = 1

would return user x and thats wrong cuz the company doesn't cover desired service c

A: I would use OR to get all users which are at least in one service:
$query = "select user_id from wanted where a = 1 OR b = 1 OR c = 1 ";

A: Almost seems like too simple of a fix, but how about OR instead of AND?
$query = "select user_id from wanted where a=1 or b =1 or c=1 ";

A: In your senario you could use or rather than and so
where a=1 || b =1 || c=1 ";

which would return any customer who wants product a, b or c bit not necessarily all of them.
Personally I would change the structure of the database so I had a products table and a customers tables then a 1 to many join between the two tables. That would allow you to query like:
where product.product_id IN (1,2,3);


text:
Q: Mail spelling checker will not stop This is driving me crazy.
I have gone into Preferences and set spellchecking -> NEVER
But it will not stop!
:
  :

This gets my goat. I rarely if ever make spelling errors, and it is constantly getting in my way.
Is there some way to get rid of it once and for all?
EDIT: I use Mavericks' native speech recognition; maybe there're some conflict?

A: They blue lines are alternate speech recognition hints. Spelling is in red, not dark blue.
I don't know of a way to disable the blue lines directly other than enunciating in a way that the engine has less uncertainty about what you are dictating.


text:
Q: How to pass arrays from C++ to assembler dll? I would like to pass 4 arrays from c++, 2 arrays are 2D and 2 arrays are normal. I have this code in c++:
typedef int(*DLLFunc)(double**, double*, double**, double*, int);

//main and some other code
hDll = LoadLibrary("FibAsmLib");

    if (hDll != NULL){

        myAsmProc = (DLLFunc)GetProcAddress(hDll, "MyProc");

        if (myAsmProc != NULL){
            result = myAsmProc(arrayA, arrayB, arrayAlfa, arrayBeta, rowA);
        }
        cout << "Result from library: " << result;
    }

and this in assembler:
.486
.model flat, stdcall
.data
.code

PUBLIC MyProc
MyProc proc w: DWORD, x:DWORD, y:DWORD, z:DWORD, e:DWORD
mov eax, 5
ret
MyProc endp
end

When i run program I have strange error:
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call.  This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.

Do you have any suggestions?

A: You told your assembler that the exported procedure adheres to the stdcall calling convention, but the C program thinks it's cdecl (if you don't specify a particular calling convention VC++ assumes cdecl). Fix either side and the problem should go away.


text:
Q: How to update document in Mongodb with condition There is a log collection in my mongodb which has an unique index named log_id. I want to achieve this goal:
Whenever I update the documents, if document with the same log_id already exists, then {$inc: {count: 1}}. If not, then insert the new document with {count: 1}. Can I do this in a single command?

A: you can this in a single query with {upsert : true} option.
and $inc syntax is { $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } } so you should use {$inc: {count: 1}} instead of {count: {$inc: 1}}
try it:
db.log.update(
      {"log_id": compareLogId},
      {$inc: {count: 1}},
      {upsert:true}
)


text:
Q: integrate new Vue js 3 app to spring boot/thymeleaf application I already have an application built with spring boot/thymeleaf as a template engine and everything is working fine, now I need to add new section to the application I need to build it with Vue js 3, I would like to make it inside my development environment and also to be able to deploy it with my main app into tomcat server and of course load it from inside my original app.
So for now In "src" I created new vue app using vue-cli I only changed the port to 8888:

I can explore it at localhost:8888 and it is working, this is main.js:
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

and of course the default app.vue:
<template>

  <HelloWorld msg="Welcome to Your Vue.js App"/>
</template>

Also I created thymeleaf file vueapp.html and a controller to route me to it:
<!DOCTYPE html>

    @GetMapping("/vue")
    public String vueApp(ModelMap model, HttpSession session) {

        return "user/vueapp";
    }

The thymeleaf already Loaded, the build.js also loaded but Vue app content is not loaded the page still empty and the div with id="app" also empty

Can any one help me with the best practice to integrate the vue app with thymeleaf
Note: I will need vue-router later, I followed this , Thank you.

A: If using vue.js is simple, I recommend doing the following:

*

*Remove Vue from your project.

*Add the follow dependencies:

*

*org.webjars.npm » vue » 3.x.x

*org.webjars » webjars-locator

*Configure the location about your resources adding this in .properties file:

*

*spring.thymeleaf.prefix=file:src/main/resources/templates/

*spring.web.resources.static-locations=file:src/main/resources/static/

*Now you should re-locate your main.js into static location, for example: src/main/resources/static/js/main.js and remember called to Vue.createApp

*Now you should re-locate your vueapp.html into templates location, for example: src/main/resources/templates/vueapp.html
For more specific detail please visit this github project: thymeleaf-vue3-webflux
Now if you have a big app I recommend kill the monolithic, you should create front and back separate.


text:
Q: Excel VBA - Dynamically supply ranges to Union method User has defined named ranges to print in Excel.
I am reading these ranges into a VBA array. Is there a way to supply the range names to the Union method to set non-contiguous print ranges.
For example, something like:
ActiveSheet.PageSetup.PrintArea = Union(Range(array(1)), Range(array(2))).Address
The number of ranges held in the array can vary.  I've experimented with looping through the array and building a string variable, but no success.
Any help would be appreciated.

A: You'll have to substitute the actual range names or objects in the statement, but here is how to use the Union function to set a PrintArea:
Sub foo()
    Dim setup As PageSetup
    Set setup = ActiveSheet.PageSetup

    setup.PrintArea = Union(Range("MyRange1"), Range("MyRange2")).Address
End Sub

What I'm actually looking for is a method to construct the Union statement using range names that are held in an array

OK, then use the above method and a custom function to construct the Union in a loop:
Sub foo()
    Dim setup As PageSetup
    Dim RangeArray(1) As Range

    Set setup = ActiveSheet.PageSetup
    Set RangeArray(0) = Range("MyRange1")
    Set RangeArray(1) = Range("MyRange2")

    setup.PrintArea = GetUnion(RangeArray)
End Sub
Function GetUnion(arr As Variant) As String
    Dim itm As Variant
    Dim ret As Range
    For Each itm In arr
        If Not ret Is Nothing Then
            Set ret = Union(ret, itm)
        Else
            Set ret = itm
        End If
    Next
    If Not ret Is Nothing Then
        GetUnion = ret.Address
    Else
        GetUnion = ""  'May cause an error...
    End If
End Function


text:
Q: why i can't run app-engine-patch on my gae this is app-engine-patch http://code.google.com/p/app-engine-patch/
i download it  ,and unzip , but can't running on my google-app-engine launcher
why ?
updated
but the patch has app.yaml, and i can't find aep-sample
updated2
when i python manage.py runserver
so  can app-engine-patch running on gae launcher ?

A: App Engine Patch isn't an App Engine app, it's a library to use with your app.  If it doesn't have an app.yaml file, it won't be able to be run.
It looks like there's an aep-sample app included in the .zip file, try running that.
(response to edit)
The app.yaml file you found references aep-sample as the app's name, but the app listed in the launcher says "patch", so something's wrong there.
Have you read the Getting Started page on the project's site?  Reading the documentation is generally a helpful first step.


text:
Q: Creating Side by Side Barcharts in ggplot I am trying to create a side by side bar chart from this subset of a data frame
ExitVelocityAverage

 Name          CombinedAvgEV PlayerAvgEV
  <chr>                 <dbl>       <dbl>
1 Adam Harrison          85.9        80.8

Ultimately I would have one barchart that has Adam's Average (PlayerAvgEV) and another barchart that shows the total average of the data frame (CombinedAvgEV). Ideally these barcharts would be side by side and this would show that Adam is below the average.
This is where I am at but it isn't working
ggplot(ExitVelocityAverage, aes(x=Name))
  geom_bar(aes(x = Name,y=PlayerAvgEV), col = "red", fill = "red", stat="identity") +
  geom_bar(aes(x = Name,y=CombinedAvgEV), col = "blue", fill = "blue", stat="identity")

Any help would be greatly appreciated.


text:
Q: Remove image cache from SDWebImage I am not able to remove image cache which are cached by SDWebImage.
I am using "UIImageView+UIActivityIndicatorForSDWebImage.h"
I am caching image with this code.
[cell.imageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"image_icon.png"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

Now sometime i want to remove cache of image because sometime same url will give me another image by server.
I am removing image cache using this code.
[[SDImageCache sharedImageCache] removeImageForKey:[self.imgArray objectAtIndex:indexForDelete] fromDisk:YES];

But is give's me error like:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryM UTF8String]:
  unrecognized selector sent to instance 0x7fcb01f9bf70'

How to remove cache ??

A: in swift
SDImageCache.shared.removeImage(forKey: _imageURL?.description, withCompletion: nil)

A: The method  - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk in the SDWebImage takes NSString as an argument.
In your above code it looks like [self.imgArray objectAtIndex:indexForDelete] gives you an an NSDictionary object and hence the crash.
So you would need something like this;
NSDictionary *imageDictionary = [self.imgArray objectAtIndex:indexForDelete];
NSString *cacheKeyToDelete = [imageDictionary objectForKey:@"YourKeyForImageCacheKey"];

[[SDImageCache sharedImageCache] removeImageForKey:cacheKeyToDelete fromDisk:YES];

A: Try this, updating single image url with SDWebImageRefreshCached options.
Objective-C:
[self.imageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"???"] options:SDWebImageRefreshCached];

Swift: u can translate it by method name


text:
Q: Free algebra generated by one element, but has two unary operations My question is - how can I describe a free Algebra, say $\mathcal F_{\mathcal K}(1)$, where $\mathcal K$ is a class of all algebras that have two unary operations - they are arbitrary and not specifically defined.
The notation $\mathcal F_{\mathcal K}(1)$ is meant to describe that this algebra is generated by one element and belongs to the class $\mathcal K$. My textbook says that a free monoid generated by two elements can be used to obtain an algebra such as $\mathcal F_{\mathcal K}(1)$ - unfortunately that was only a remark, with no further explanation.
I would appreciate any kind of an example for a free algebra that fulfills these properties.


text:
Q: SSRS2008: Show Row Count of SubReport in Main Report Using SSRS 2008
Have Main Report with text and 3 hidden subreports embedded in the main report.  There are three SubReports (Current, Expired and Missing) which provide detail information for the report (Parameter) you select in the main report. These work properly.
What I want to do is add a table to the Main report that displays a row count of the products displayed in the subreport.
For Instance:
Current
Product#1 Location CountofCurrent#1
Product#2 Location CountofCurrent#2
Expired
Product#1 Location CountofExpired#1
Product#2 Location CountofExpired#2
etc
I have been trying:
[Reports]![YourReportName]![YourSubReportName]!CountRows([TheValueFromTheSubReportYouWantToReference])

in different variations without success.
How do you reach from the main report and count the rows in the subreport?
Thanks in advance.