text:
Q: DialogFragment not appearing For some reason, a DialogFragment that I've just created won't appear whenever I try to launch it from a click event. Why does the dialog not have a view, when my view has been clearly set builder.setView(rootView)?
Fragment does not have a view
click event to launch DialogFragment
    holder.myButton.setOnClickListener {
        val dialog = MyDialog()
        val manager = (holder.itemView.context as FragmentActivity).supportFragmentManager
        dialog.show(manager, "example")
    }

DialogFragment
class MyDialog : DialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        LayoutInflater.from(requireContext())

        val builder = AlertDialog.Builder(activity)
        val rootView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_sample, null, false)

        lateinit var tabLayout: TabLayout
        lateinit var viewPager: ViewPager

        builder.setIconAttribute(R.attr.myImg)
        builder.setTitle("My Program")
        builder.setView(rootView)
        builder.setMessage("My Message")
        builder.setPositiveButton(getString(R.string.ok)) { dialog, _ -> dialog.dismiss() }

        tabLayout = rootView.findViewById(R.id.tabLayout)
        viewPager = rootView.findViewById(R.id.masterViewPager)

        val adapter = CustomAdapter(childFragmentManager)
        adapter.addFragment("Boy", CustomFragment.createInstance("John"))
        adapter.addFragment("Girl", CustomFragment.createInstance("Stacy"))
        adapter.addFragment("Robot", CustomFragment.createInstance("Aeon"))
        viewPager.adapter = adapter
        tabLayout.setupWithViewPager(viewPager)

       // return builder.create()
        return builder.show()
    }
}

dialog_sample.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/masterViewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

CustomFragment class
class CustomFragment : androidx.fragment.app.Fragment() {
    private var mText = ""

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val v = inflater.inflate(R.layout.fragment_sample, container, false)
        (v.findViewById(R.id.textView_sample) as TextView).text = mText
        return v
    }

    companion object {
        fun createInstance(txt: String): CustomFragment {
            val fragment = CustomFragment()
            fragment.mText = txt
            return fragment
        }
    }
}

Logcat
    java.lang.IllegalStateException: Fragment does not have a view
        at androidx.fragment.app.Fragment$3.onFindViewById(Fragment.java:2396)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:869)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1229)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1295)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:686)
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2057)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1847)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1802)
        at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManagerImpl.java:1679)
        at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:536)
        at androidx.fragment.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:148)
        at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1244)
        at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
        at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
        at com.android.internal.widget.AlertDialogLayout.onMeasure(AlertDialogLayout.java:71)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at com.android.internal.policy.DecorView.onMeasure(DecorView.java:716)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2718)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1545)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1855)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1460)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
        at android.view.Choreographer.doCallbacks(Choreographer.java:761)
        at android.view.Choreographer.doFrame(Choreographer.java:696)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I/Process: Sending signal. PID: 4867 SIG: 9
Application terminated.

adapter class
class MyRVAdapter(private val itemsList: ArrayList<Item>) : RecyclerView.Adapter<MyRVAdapter.ViewHolder>() {
    override fun getItemCount(): Int {
        return itemsList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        // Button click listener
        holder.myButton.setOnClickListener {
            val dialog = CustomFragment()
            val manager = (holder.itemView.context as FragmentActivity).supportFragmentManager
            dialog.show(manager, dialog.tag)
        }
     }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.my_cv, parent, false)
        return ViewHolder(v)
    }

    class ViewHolder (itemView : View):RecyclerView.ViewHolder(itemView) {
        val mCV = itemView.findViewById<CardView>(R.id.cv_main)!!

        val myButton = itemView.findViewById<Button>(R.id.btn_main)!!
    }

    class MyViewPagerAdapter(manager: androidx.fragment.app.FragmentManager) : androidx.fragment.app.FragmentPagerAdapter(manager){
        private val fragmentList : MutableList<androidx.fragment.app.Fragment> = java.util.ArrayList()
        private val titleList : MutableList<String> = java.util.ArrayList()

        override fun getItem(position: Int): androidx.fragment.app.Fragment {
            return fragmentList[position]
        }

        override fun getCount(): Int {
            return fragmentList.size
        }

        fun addFragment(fragment: androidx.fragment.app.Fragment, title: String){
            fragmentList.add(fragment)
            titleList.add(title)
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return titleList[position]
        }
    }
}

A: If you override onCreateDialog with AlertDialog instead of overriding onCreateView, you shall bump into IllegalStateException.
please checkout the link to solve


text:
Q: error while calling a soap webservice in eclipse java.io.IOException: Server returned HTTP response code: 500 for URL: https://***/fiwebservice/services/FIUsbWebService
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1459)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
    at com.abcde.testClient.TestClientTry.main(TestClientTry.java:109)

I have replaced the url as *** for security purpose, as it is confidential..
Why is there an error when I call a soap webservice in eclipse?
Please help me regarding this.

A: It seems that there is an error in com.abcde.testClient.TestClientTry. Could you provide the logs and the the source of the File?

A: HTTP status code 500 usually means that the web server code crashes.
If HttpURLConnection#getResponseCode() and error and HttpURLConnectionof#getErrorStream() instead of (to the status code to determine in advance), it is necessary to read. It can in other words, information about the problem.
Host if blocked you, you have got the code 4NN State, as the more 401 and 403rd

A: Http 500 can mean many things. In Spring security I think that can mean that you didnt have the appropriate authentication to reach the resource. Without knowing much about your server side its hard to say what the problem is or how to solve it.
What kind of technology did you have at the server?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why we can assert, in general, that physical processes have the behaviour of low-pass filter? Consequently, why is it not allowed to produce physically some controllers for processes that are described by a transfer function that is an improper function?
A simple example is the driven harmonic oscillator. So the equation in this case is $mx'' +Ax'+k=f(t)$, where $x$ is the variable that stands for the position of the mass, $m$ is the mass, $A$ is a certain constant for the friction and $f$ is a force that pull the mass.
Omitting some passages we get a transfer function (in the frequency domain) that is:
$$W(s)=\frac {1/m}{s^2+2\alpha s+w_0^2}$$
where $\alpha = \frac Am$    and   $w_0 = \sqrt\frac km$.
So the harmonic function is:
$$W(jw) = \frac {1/m}{(w_0^2-w^2)+2\alpha jw}$$
Now the module of the function is $M=\frac {1/m}{\sqrt{(w_0^2-w^2)^2+4\alpha^2 w^2}}$ and $\lim_{x\to+\infty} M = 0$. So the process has a visible response just in "low" values of the frequency of the force ($w$). The professor added that in some controlling problems of some process we could obtain a transfer function of the controller that is an improper transfer function, and that a controller of this type is impossible to produce physically. I'd like just some kind of intuitive explaination for this.

A: Exponential fall-off in frequency domain is equivalent to smoothness in time domain. Since physical processes usually happen smoothly, they act as a low-pass filter.

A: Physical systems are either proper or strict proper. This means, they either show low-pass properties or a 'constant' one (imagine the two end-points of a bar that can move in one direction and can't rotate: every movement, you apply to one end, will immediately be applied at the other end).
If a system's transfer function was improper, your system can have non-continuous behavior even if your input is conintuous.
For example, if $x$ is your variable denoting some coordinate, it could change value instantaneously even if the input is continuous. This is a property physical system usually don't have. Also this behavior would require an infinite amount of energy.
From a control theory point of view, an improper system has a differentiator. So if your input is not smooth, your system has to have some points, at which it changes state in zero time.


text:
Q: how to clone div bassed select option i have select option with count of numbers so i need now when user choose any number clone div tag personal information by this number ex: - select 8 clone 8 time ..
i try do that by use( for loop )but i have problem when run i see clone over this number ex:- choose 8 clone 16 time
this is html code and my try js code

$('#c3').change(function() {
  $('.cloneHere').empty();

  var count = $('#c3').val();
  for (i = 1; count > i; i++) {
    var clone = $('.rowClone').clone();

    $('.cloneHere').append(clone);

  }
});

  count of person
  <select class='form-control select2' name="" id="c3">
    <option value="" selected disabled hidden>Choose here</option>
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
     <option value="7">7</option>
  </select>

Information of Person

Person 1

            <input type="text" class="form-control">

            <input type="text" class="form-control">

            <input type="tel" class="form-control">

            <input type="text" class="form-control">

A: The problem you are facing comes from this line: var clone = $('.rowClone').clone();
the first clone is fine because only 1 .rowClone exist, next time multiple .rowClone exist and it appends all of those.
You have 2 solutions, either use var clone = $('.rowClone:first').clone(); or move var clone = $('.rowClone').clone(); before your for loop
Demo of the problem, run it and look at the console

$('#c3').change(function() {
  $('.cloneHere').empty();

  var count = $('#c3').val();
  for (i = 1; count > i; i++) {
    console.log("Number of .rowClone that exist = " + $('.rowClone').length)
    var clone = $('.rowClone').clone();
    $('.cloneHere').append(clone);
  }
});

  count of person
  <select class='form-control select2' name="" id="c3">
    <option value="" selected disabled hidden>Choose here</option>
    <option value="8">8</option>

  </select>

Information of Person

Person 1

            <input type="text" class="form-control">

            <input type="text" class="form-control">

            <input type="tel" class="form-control">

            <input type="text" class="form-control">


text:
Q: I have accidentally removed FCM registration tokens from my server I have accidentally removed FCM (Firebase Cloud Messaging) registration tokens from my server, is there any way that I can get all the tokens (like via Firebase console) ?
I don't have a backup, unfortunately.
Thank you for your time.


text:
Q: How can I fix my out of index errors after I've capped the max index at the length of the list? I'm working with two lists and trying to do so linearly. I have to look at each list element. To go through the first list, I've used a for loop. Then I nested a second loop--tried both for and while--to iterate through my second list. I'm trying to sort the lists into a bigger sorted list as I iterate over each list element. I used a counter to index the second list. When going through the second list, I keep getting an 'out of index' error, despite trying to limit the highest index value to the length of the second list.
TLDR--Why do I keep getting an out of index error when I specified the highest index it should look to as the length of the list?
Working through google excercises with lists, code below:
# E. Given two lists sorted in increasing order, create and return a merged
# list of all the elements in sorted order. You may modify the passed in lists.
# Ideally, the solution should work in "linear" time, making a single
# pass of both lists.
def linear_merge(list1, list2):
    x = []
    j = 0
    for item1 in list1:
        print("1\t", str(item1))
        while item1 >= list2[j] and j < len(list2):
            x.append(list2[j])
            j += 1
        x.append(item1)

I've been getting the following error:
in linear_merge
    while item1 >= list2[j] and j < len(list2):

IndexError: list index out of range

Here's the problem attempted with for loops:
def linear_merge(list1, list2):
    x = []
    j = 0
    for item1 in list1:
        print("1\t", str(item1))
        for item2 in list2[j:]:
            print("2\t", str(item2))
            if item1 >= item2:
                x.append(item2)
                if j <= len(list2):
                    j += 1
            else:
                x.append(item1)
    return x

What error am I making with the indices? Is there something I'm missing here?

A: Swap the order of the two tests:
while j < len(list2) and item1 >= list2[j]:

This way, if j is out of range, the second test won't be evaluated.

A: You should change places of 2 tests in this condition:
while item1 >= list2[j] and j < len(list2):

to:
while j < len(list2) and item1 >= list2[j]:


text:
Q: Is it possible to trade Pokemon from the 1st generation games to the most recent ones? I know that you can trade Pokemon between games of the same generation (Gold/Silver, Ruby/Sapphire) and even trade between 1st gen and 2nd gen. However, I haven't been able to find a way to trade Pokemon so that I can play with my 1st generation Pokemon in HeartGold, for instance. If it is possible, how many steps would it take and what equipment would I need?

A: You cannot trade from the 1st Generation or 2nd Generation into the 3rd Generation and onwards.

A: As of 2016, it is possible to trade from the Virtual Console editions of Pokémon Red, Blue, Green and Yellow to the new Pokémon Sun/Moon (Gen 7) via Pokémon Bank.
Unfortunately while Gen 6 (X/Y/OR/AS) is compatible with Pokémon Bank, it is not possible to receive Gen 1 Pokémon in those games.

However, if we're talking about the original Gameboy cartridges, it can't be done. The limits on trading are as follows:
Generation 1 (Red/Blue/Green/Yellow)
↑↓ Both directions
Generation 2 (Gold/Silver/Crystal)
X Trade impossible
Generation 3 (Ruby/Sapphire/Emerald/FireRed/LeafGreen)
↓ One-way only, allows held items
Generation 4 (Diamond/Pearl/Platinum/HeartGold/SoulSilver)
↓ One-way only, no items
Generation 5 (Black/White/Black 2/White 2)
↓ One-way only, no items
Generation 6 (X/Y/Omega Ruby/Alpha Sapphire)
↓? (Unreleased, backwards trading yet to be confirmed, Pokémon Bank currently forbids items)
Generation 7 (Sun/Moon)
There are three main reasons you can't trade between Gen I/II and Gen III:

*

*The Pokémon data format changed significantly in Gen III, so the two were incompatible.

*The GBA link cable uses a different voltage to the Gameboy link cable. Even though a GBA can play old Gameboy games, it uses different circuitry than when playing GBA games, so the games' link cable functionalities are  fundamentally incompatible.

*Even if these weren't an issue, Nintendo never released a product that allowed trade from one to the next.

A: While it may not be possible to transfer from Gens I and II to III, seeing as Gen III has FireRed and LeafGreen, it would be advisable to just play through that and trade upwards (to gens IV and V) from there..

A: Yes, you can trade from Generation 1 and 2 cartridges (not just Virtual Console) to more recent generations
However, it is not something that is officially supported by Nintendo.
The website Atop the Fourth Wall posted a how-to video showing that it was absolutely possible to go from Generation 1 and 2 cartridge all the way to Generation 6, the latest as of the video's creation. Since it ends with the Pokémon Bank, you can presumably go to any generation after that.

A tutorial on trading up Pokémon off of Generation 1 and 2 cartridges and into the modern generations! Yes, it IS possible.

It does involve using hardware to extract your save file from the cartridge and manipulating it using a save game editor. Still, the end result is having your original team from a Generation 1 or 2 cartridge transferrable all the way to the Pokébank.

A: This is technically possible now that the Gen 1 Vurtual Console games support migration to Sun and Moon.
It's not easy and is only doable with pricey hardware.
The steps are as follows:

*

*Dump your save game from your original Pokemon Red, Blue or Yellow cartridge to your PC using either a Retron 5, Retro Freak, or some other Game Boy cartridge reader. You can build one with an Arduino if you're good at soldering and don't mind destroying a Game Boy for the cartridge slot. Depending on the hardware you choose this step will be expensive or time consuming.

*Hack your 3DS so that it can run homebrew. I won't go into the steps for this because it's against Nintendo's terms of service but on the latest firmware it requires you to buy a game that has an exploitable defect. This will cost you due to the popularity and rarity of those games.

*Purchase and download the Virtual Console version of the same Pokemon game that you copied the save from and start a new game.

*Use homebrew software such as SaveDataFiler to replace the Virtual Console game's save file with the one you dumped earlier from your original cartridge.

*You now have a working copy of your original game's save file on your 3DS. Use Pokemon Bank to migrate your original team to Pokemon Sun and Moon.

A: *

*Generation 1 (Red/Blue/Green/Yellow)
↑↓ Both directions

*Generation 2 (Gold/Silver/Crystal)
X Trade impossible

*Generation 3 (Ruby/Sapphire/Emerald/FireRed/LeafGreen)
↓ One-way only

*Generation 4 (Diamond/Pearl/Platinum/HeartGold/SoulSilver)
↓ One-way only, no items

*Generation 5 (Black (2)/White (2))
X Trade impossible*

*Generation 6 (XY/ORAS)

*It is not possible to trade pokémon from Generation 5 to Generation 6. As explained on the official website:

There are a number of differences between the functions and specifications of the Nintendo 3DS family of systems compared to other systems in the Nintendo DS family (DSi XL/DSi/DS Lite/DS), meaning that it is unfortunately not possible to communicate directly between software made for the two different systems (models).

However, a paid service called Pokémon Bank has been created to fulfil this gap. The service costs $4.99 (yearly subscription) and it allows users to upload their pokémon  to the cloud. The "uploading" service can be used on both 5th and 6th generations, while the "downloading" service can only be used on Pokémon X and Y. Using this service allows de facto the users to trade pokémon from generation 3 up to 6.


text:
Q: Using fixures in Unit testing with Nodejs and MongoDB I'm working on a Nodejs, MongoDB project, and I want to write unit tests for it using Jest, Let's assume that there are two schemas in my project: User, Book. What I need is a structure, or a way or a tool to solve these issues:

*

*be able to load a bunch of data before each test, and clear it afterward (I want a fix and clear database state for each test)

*

*it is better if the data is loaded from a JSON file.

*I need to be able to specify the data I want to load for each test. for example, I only need fixtures related to User schema when I want to write unit tests for User API, so I don't want to load fixtures related to Book schema.

*it would be a bonus point, but not necessary if the database used is the in-memory database instead of the real MongoDB database. (I want the tests to be fast)
so far I only have found some libraries that solve the first one, but not the second one.


text:
Q: TypeError when creating a new MatTable with Angular Material 2 I'm creating a table using mat-table (from MatTableModule) but I'm getting the following error:
ERROR TypeError: Cannot read property 'addClass' of undefined
  at MatHeaderCell.CdkHeaderCell (table.es5.js:275)
  at new MatHeaderCell (table.es5.js:132)
  at createClass (core.js:12166)
  at createDirectiveInstance (core.js:12011)
  at createViewNodes (core.js:13449)
  at createEmbeddedView (core.js:13327)
  at callWithDebugContext (core.js:14740)
  at Object.debugCreateEmbeddedView [as createEmbeddedView] (core.js:14070)
  at TemplateRef_.createEmbeddedView (core.js:11414)
  at ViewContainerRef_.createEmbeddedView (core.js:11130)

The error in the console appears related to the first occurrence of <mat-header-cell *matHeaderCellDef> ID </mat-header-cell> tag.

I can't understand what is not working since the same code worked like a charm until yesterday evening.
The table in the component.html file
<mat-table #table [dataSource]="dataSource" style="text-align:center">
    <!-- Id Column -->
    <ng-container matColumnDef="id">
        <mat-header-cell *matHeaderCellDef> ID </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.id}} </mat-cell>
    </ng-container>
    <!-- Creation date Column -->
    <ng-container matColumnDef="created">
        <mat-header-cell *matHeaderCellDef> Created </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.created}} </mat-cell>
    </ng-container>
    <!-- Device ID Column -->
    <ng-container matColumnDef="deviceId">
        <mat-header-cell *matHeaderCellDef> Device ID </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.deviceId}} </mat-cell>
    </ng-container>
    <!-- Failures Column -->
    <ng-container matColumnDef="failures">
        <mat-header-cell *matHeaderCellDef> No. Failures </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.failures}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>

In my component TypeScript file I defined data as:
export class MyComponent implements OnInit {
  displayedColumns = ['id', 'created', 'deviceId', 'failures'];
  dataSource:MatTableDataSource<Element>;

  constructor() { }

  ngOnInit() {
    this.dataSource = new MatTableDataSource<Element>(ELEMENTS);
  }
}

export interface Element {
  id: string;
  created: string;
  deviceId: string;
  failures: number;
}
const ELEMENTS: Element[] = [
  {id: 'Hydrogen', created: "123", deviceId: "ABC123", failures: 0},
  {id: 'Helium', created: "123", deviceId: "123ABC", failures: 3},
  {id: 'Lithium', created: "123", deviceId: "ABCEF5", failures: 0},
  {id: 'Beryllium', created: "123", deviceId: "ABC123", failures: 2},
  {id: 'Boron', created: "123", deviceId: "67ABC3", failures: 0},
];

So, apparently, data in TS and table cells in HTML are matched, what is causing this error to show up?

Update
Used library versions from package.json:

*

*@angular/cdk: ^5.0.0-rc.1;

*@angular/material: ^5.0.0-rc.2;

A: In your package.json can you check the version of Angular material you have.
What ever version you have, make sure your @angular/cdk is the same version.
That is likely you problem. I believe the problem is you may have higher version of angular material probably "@angular/material": "5.0.0-rc.3" and in that version the renderer parameter passed to CdkHeaderCell is not being passed any longer and for that reason you have to update     "@angular/cdk": "5.0.0-rc.3" as well


text:
Q: Issues decompressing (FlateDecode) audio data in XFDF from Adobe Acrobat I'm trying to decompress AIFF audio data from an XFDF sound annotation, and play the audio in the browser. Any time I export a sound annotation from Adobe Acrobat and decompress the audio data it results in seemingly garbage data.
The code below works for compressed audio starting with 789C header, but a few compressed streams start with 4889 or 78DA and fail to play in the browser. After numerous tests with Acrobat, exported sound annotations in XFDF start with 4889.

// Two audio examples, one working and one failing.
// Can't paste it all due to char limit.
const compressedHexString_working = `789C3C9C059C13D7FBF5473293F55DBCB8BBBBBB53DC8ABB142FEE5AB4 ...`;
const compressedHexString_failing = `48892C97077C8FE716C7CFF9532EB7418D5E24768492DABB0862146DAF ...`;

// Convert hex string into ArrayBuffer.
const compressedByteArray = new Uint8Array(
  compressedHexString_working
    .match(/[a-fA-F0-9]{2}/g)
    .map((str: string) => parseInt(str, 16))
);

const { default: zlib } = await import('pako');
const audioData = await zlib.inflate(compressedByteArray);

// Parse header bytes to determine audio file.
const fileHeader = new TextDecoder().decode(audioData).substring(0, 4);
console.log('Sound File Header:', fileHeader);

The console.log usually prints ID3, RIFF, or FORM when decompression is successful. But when decompressing the failing example, the result is a garbage value: �D�C.
Am I doing the decompression incorrectly? Or am I missing a step?


text:
Q: R function for returning multiplication result of a function appreciate your guidance as im new to R programme. basically i've created a function to check whether the value is even or odd.
i wish to create a new result column whereby 'even' results in the original value * 2, and 'odd' results in the original value - 5.
not sure where i've gone wrong with the second part of the code but i am trying to figure out where can i include my 'check' column in the second function to specify it should be checked for even or odd.
i only learnt about ifelse(check(df$check) but it doesnt seem to work in my instance.
much appreciated!
## print 'odd' or 'even' results in df

check = function(df,col){
  df['check'] =
     ifelse(df[,col] %% 2 ==0, 'even', 'odd')
     return(df)
}

# multiplication and subtraction for odd_even results
checkresult = function(df,col){
  df['res'] =
    ifelse(check(df) == 'even', df[,col] * 2, df[,col]-5)
  return(df)
}

checkresult(df)

A: The simplest way to do it is by not implementing a new function, just use ifelse() as it was intended:
set.seed(100)
df <- data.frame(x = sample(1:15, size = 100, replace = T))
df$res <- ifelse(df$x %% 2 == 0, df$x * 2, df$x  - 5)
df |> head()
#>    x res
#> 1 10  20
#> 2  7   2
#> 3  6  12
#> 4  3  -2
#> 5  9   4
#> 6 10  20

If you need to implement a function that returns a dataframe:
set.seed(100)
df <- data.frame(x = sample(1:15, size = 100, replace = T))

my_func <- function(dframe, column){
  vec <- dframe[,column]
  dframe$res <- ifelse(vec %% 2 == 0, vec * 2, vec - 5)
  return(dframe)
}

my_func(df, "x") |> head()
#>    x res
#> 1 10  20
#> 2  7   2
#> 3  6  12
#> 4  3  -2
#> 5  9   4
#> 6 10  20

Edit 1
If you want the parity of the number, one extra line is required:
set.seed(100)
df <- data.frame(x = sample(1:15, size = 100, replace = T))

my_func <- function(dframe, column){
  vec <- dframe[,column]
  dframe$parity <- ifelse(vec %% 2 == 0, "EVEN", "ODD")
  dframe$res <- ifelse(vec %% 2 == 0, vec * 2, vec - 5)
  return(dframe)
}

my_func(df, "x") |> head()
#>    x parity res
#> 1 10   EVEN  20
#> 2  7    ODD   2
#> 3  6   EVEN  12
#> 4  3    ODD  -2
#> 5  9    ODD   4
#> 6 10   EVEN  20


text:
Q: Beauty of Spectral Graph Theory
*

*Why would one choose to study spectral graph theory?

*Where can the spectrum of complete graphs, for example, be applied in real- life example or of any graph in general?

*A brief historical background of spectral graph theory

*What is beautiful about this result?

I'm interested in all these questions to find the purpose of spectral graph theory

A: I'm an undergraduate student doing academic research in spectral graph theory.
I ended up doing spectral graph theory because I didn't have any particular interest when I approached my current mentor about working under him. His area of research is focused on graph theory and combinatorics, and he introduced me to some of his work. When I finished, he presented me some open questions related to his latest publication and I decided to work in spectral graph theory.
I'll give a few applications of spectral graph theory that have come up in my research. First, the spectral partitioning algorithm and algebraic connectivity. If $G$ is a connected graph, the second smallest eigenvalue of the laplacian matrix, called the Fiedler eigenvalue or algebraic connectivity, is related to the connectivity of the graph. The positive and negative entries of the eigenvector corresponding to this eigenvalue create an almost equitable partition on the vertex set of the graph.
There is also the spectral positioning algorithm. If $x_1, x_2, x_3$ are the eigenvectors corresponding to the three smallest nonzero eigenvalues of the graph laplacian, the $(x, y, z)$ coordinate of the $i$-th vertex of $G$ is given by the $i$-th entries of $x_1, x_2$, and $x_3$, respectively. I created a graph plotting library that used spectral positioning to do most of the heavy lifting, so it does come in useful.
More relevant to my research, the minors of the laplacian matrix count the number of unique spanning trees and spanning forests of a graph. I study the resistance distance, which is a graph distance metric characterized as
$$\begin{equation*}
    r_G(i, j) = \frac{\mathcal F_G(i, j)}{T(G)},
\end{equation*}$$
where $\mathcal F_G(i, j)$ is the number of spanning forests separating $i, j \in V(G)$ and $T(G)$ is the number of spanning trees in $G$.
My current work is focused on Kemeny's constant, an invariant of Markov chains. The Kemeny's constant of a simple connected graph $G$ is given by the weighted sum
$$\begin{equation*}
    \mathcal K(G) = \sum_{i, j \in G} \frac{d_i d_j r_G(i, j)}{4m},
\end{equation*}$$
where $m$ is the number of edges in the graph and $d_i$ is the degree of the $i$-th vertex. This constant is another way to describe graph connectivity, characterized by the expected number of transitions to reach any vertex in the graph, independent of the starting point. A large Kemeny's constant corresponds to a poorly connected graph, and a small Kemeny's constant to a well-connected one.
A real-life application of Kemeny's constant is Braess' paradox in traffic planning; Braess was able to show that there exist graphs such that adding edges between certain vertices would result in an increase of Kemeny's constant. Counterintuitively, graphs with more edges may be poorly connected compared to less dense graphs. Braess used this result to improve traffic networks and building plans for hospitals.
I know very little of the history of spectral graph theory, but the pioneers in my area of research include John Kemeny, J. Snell, and Ravindra Bapat. More recently, Jane Breen, Lorenzo Ciardo, and Steve Kirkland have authored and co-authored many interesting results that I frequently refer to.
To me, spectral graph theory is a beautiful discipline because of the structure and order of graphs. The way that graph spectra capture so many of the interesting properties and invariants of graphs is an intriguing connection. Most results require extensive eigenvalue computations or formula manipulation, which makes discovering a new connection very rewarding.


text:
Q: How do i fix createCipheriv throwing "Exception has occurred: RangeError: Invalid Key Length" I've been working on a nodeJS bot for a couple of days now. I'm working on making it more secure by encrypting the discord token when not in use. so I found a way to encrypt it using createCipher(), however as you all know, NodeJS has decided to deprecate it for security reasons. I don't want to create vulnerability when trying to minimize them. so i tried using createCipheriv(), however, when I did it threw me the following error:
Exception has occurred: RangeError: Invalid key length
  at Cipheriv.createCipherBase (node:internal/crypto/cipher:116:19)
    at Cipheriv.createCipherWithIV (node:internal/crypto/cipher:135:3)
    at new Cipheriv (node:internal/crypto/cipher:243:3)
    at Object.createCipheriv (node:crypto:138:10)
    at encrypt (/home/herbgamerwow/VScode Projects/CCB/index.js:77:25)
    at Object.<anonymous> (/home/herbgamerwow/VScode Projects/CCB/index.js:84:14)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)

what do I do?
here's the function that I used to encrypt:
const algorithm = 'aes-256-ctr';

const IV_LENGTH = 11;

async function encrypt(text) {

    let iv = crypto.randomBytes(IV_LENGTH);
    let cipher = crypto.createCipheriv(algorithm, Buffer.from(encryptionkey, 'hex'), iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return iv.toString('hex') + ':' + encrypted.toString('hex');

}

thank you in advanced


text:
Q: highcharts click on data point throwing error I am working with highcharts at the moment, and I wanting to trigger a function when a user clicks on a data point.
My highcarts config looks like this,
this.chartOptions = {
            chart : {
                //height: (5 * self.categories.length) + 100,
                width : self.$('.graph-holder').width()
            },
            title: {
                useHTML: true,
                text: 'Number of projects [' + title.totalNumber + ']' +
                      'Value of projects [' + title.totalVal + '(' + self.model.get('currency') + ')]'
            },
            legend : {
                enabled : false
            },
            xAxis: {
                categories: yAxisLabels
            },
            tooltip: {
                enabled : false,
                crosshairs: {
                    color: '#636363',
                    dashStyle: 'solid',
                    width: '1px'
                }
            },
            plotOptions: {
                series: {
                    cursor: 'pointer',
                    point: {
                        events: {
                            click: function (event) {
                                console.log(this);
                                self.showClientProjects(this.category, this.series.options.status, this.clientX, this.plotY);
                            }
                        }
                    }
                }
            },
            series: data
        };

        this.chart = $('.graph-holder').highcharts(this.chartOptions);

Whenever I click on data point it get the following error,

Uncaught TypeError: Cannot read property 'call' of null

What could be causing this? My graph is a line graph that can output multiple series. Sorry I cannot get this on jsfiddle at the moment. So I found a fiddle example of what I want to happen,
http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/series-events-click/
If I put this example into my code, I still get the error,

Uncaught TypeError: Cannot read property 'call' of null

which is this line in particular in the hightcharts source,
if (fn.call(el, eventArguments) === false) {
    eventArguments.preventDefault();
}

Only differences are that I am running jquery 2 and the graph is in a bootstrap tab.


text:
Q: Show difference between multiple values from one measurements in InfluxDB within one Grafana panel I am currently trying to display difference of results from 2 sensors in a Grafana panel.
In my InfluxDB database I have a measurement that holds values of both sensors:
> SELECT * FROM "Vergleich" WHERE time>now()-2m
name: Vergleich
time                rh_dht22 rh_tfa temp_dht22 temp_tfa           tp_dht22 tp_tfa
----                -------- ------ ---------- --------           -------- ------
1611407400000000000          45                21.883333333333333          9.40611175608533
1611407433000000000 47              21.3                          9.5
1611407460000000000          45                21.833333333333332          9.360802312324173
1611407493000000000 47              21.2                          9.4

For both sensors (DHT22 and some TFA device) I have stored 3 values each. They are not provided with identical timestamp but that should not be a problem.
I want to calculate the difference to see how well the various sensors provide similar data.
I am able to get some useful data out of influx:
> SELECT mean("temp_dht22") - mean("temp_tfa") AS "d_temp_dht22" FROM "Vergleich" WHERE time>now()-5m GROUP BY time(60s) fill(null)
name: Vergleich
time                d_temp_dht22
----                ------------
1611407220000000000
1611407280000000000 -0.6000000000000014
1611407340000000000 -0.6000000000000014
1611407400000000000 -0.5833333333333321
1611407460000000000 -0.6333333333333329
1611407520000000000

Unfortunately I am not able to add this to my Grafana panel.
If I add a query and enter this code
SELECT mean("temp_dht22") - mean("temp_tfa") AS "d_temp_dht22" FROM "Vergleich" WHERE $timeFilter GROUP BY time($__interval) fill(null)

it is automatically changed to
SELECT "temp_dht22" -, "temp_tfa" AS "d_temp_dht22" FROM "Vergleich" WHERE $timeFilter GROUP BY time($__interval) fill(null)

and the graph only shows "No data".
My Grafana version is "v7.3.7 (1e261642f4)" and I run it on a Raspberry 3B+ with RaspiOS Buster (Image from 2020-12-02).
Any hints how to insert the query into the fields of my panel is welcome.


text:
Q: JSON is returning a list type object when it has 1 position as object and not as a list I have a list of objects instantiated in a return class in a service's response. But when this list has 1 position, it is returning as an object and not as a list. can anybody help me?

@XmlRootElement(name = "exame")
public class ExameVO implements Serializable {

    private static final long serialVersionUID = -5840337332057658386L;

    private long id;

    @NotNull
    private String cpf;

    @NotNull
    private String dataNascimento;

    @NotNull
    private int tipoExame;

    @NotNull
    private String excluido;

    private List<ExameArquivoVO> resultadoExameArquivos;

    private String observacao;

    private String dataInclusao;

    public ExameVO() {
        super();
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public String getDataNascimento() {
        return dataNascimento;
    }

    public void setDataNascimento(String dataNascimento) {
        this.dataNascimento = dataNascimento;
    }

    public int getTipoExame() {
        return tipoExame;
    }

    public void setTipoExame(int tipoExame) {
        this.tipoExame = tipoExame;
    }

    public String getObservacao() {
        return observacao;
    }

    public void setObservacao(String observacao) {
        this.observacao = observacao;
    }

    public String getExcluido() {
        return excluido;
    }

    public void setExcluido(String excluido) {
        this.excluido = excluido;
    }

    public List<ExameArquivoVO> getResultadoExameArquivos() {
        return resultadoExameArquivos;
    }

    public void setResultadoExameArquivos(List<ExameArquivoVO> resultadoExameArquivos) {
        this.resultadoExameArquivos = resultadoExameArquivos;
    }

    public String getDataInclusao() {
        return dataInclusao;
    }

    public void setDataInclusao(String dataInclusao) {
        this.dataInclusao = dataInclusao;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }

    @Override
    public String toString() {
        return "ResultadoExameVO [id=" + id + ", cpf=" + cpf + ", dataNascimento=" + dataNascimento + ", tipoExame="
                + tipoExame + ", observacao=" + observacao + ", excluido=" + excluido + ", dataInclusao=" + dataInclusao
                + ", resultadoExameArquivos=" + resultadoExameArquivos + "]";
    }

}

@Override
    public List<ExameVO> listarExames(String cpf, String dtNascimento, Long tipoExame) throws WebServiceException {
        List<ExameVO> examesVO = new ArrayList<ExameVO>();

        try {
            examesVO = exameDAO.listarExames(cpf, dtNascimento, tipoExame);

            if(!examesVO.isEmpty()) {
                for(ExameVO exameVO : examesVO) {
                    exameVO.setResultadoExameArquivos(new ArrayList<ExameArquivoVO>());
                    exameVO.getResultadoExameArquivos().addAll(exameDAO.listarExameArquivos(exameVO.getId()));
                }
            }

            return examesVO;
        } catch (Exception e) {
            throw new WebServiceException(e);
        }
    }

Response to postman: Notice that there is 1 object that has 2 objects inside the file list and another object that has 1 and it returns as an object and not as a list with 1 object.


text:
Q: Passing 2 parameters in ajax url in Laravel route I need help, my ajax request doesn't work if i use 2 parameters in url
--- AJAX---
url: "/post/"+post_id+"/"+vote,
--- ROUTE ---
Route::get('/post/{id}/{up_or_down_vote}

but if i only use 1 parameter
--- AJAX---
url: "/post/"+post_id
--- ROUTE ---
Route::get('/post/{id}

it works perfectly fine.
There isn't error in the first one but i think it does not reach to the controller because the output in response is undefined.
this is my view
this is my ajax request
when i clicked the vote i alerted it to check if the url is correct and it is
this is the response, the json should be here
This is the controller

A: First off, avoid images that show only code in your question. It's much better if you type it out here. Now this is how you can solve your issue.
In your route, give it a name, so you can access it via the route() method as such:
Route::get('/post/{id}/{up_or_down_vote}', [YOUR CONTROLLER HERE::class, 'vote'])->name('post.updown');
Replace YOUR CONTROLLER HERE with your controller(because I don't know the name of your controller as you did not mention it above).
Now in your ajax code just before the $.ajax(, add a url variable as such:
let url = {{ route('post.updown', ['id' => ':post_id', 'up_or_down_vote' => ':vote']) }};
url = url.replace(':post_id', post_id);
url = url.replace(':vote', vote);

Now that you have a variable containing the url, just pass it to your ajax request as such:
url : url,
And this should work!


text:
Q: Python and SWIG - Multiple modules in a single .pyd (.so) I am writing a C++ extension for Python using SWIG. From what I understand of Python and SWIG, each module must have its own .pyd file. For example, if I have a module named 'mymodule', there should be a corresponding '_mymodule.pyd' file.
In my particular case, I would like to have only one 'pyd' file and multiples modules linking to it.
mypackage/
mypackage/__init__.py
mypackage/module1.py
mypackage/module2.py

I don't want to have to maintain multiples .pyd, so I can put my interface (.i) files all under the same project in VS2010.
Edit: So far, the only way I have been able to make it work is by duplicating my 'pyd' file into two new files: _module1.pyd and _module2.pyd. But I don't like this solution, because I need to duplicate the 'pyd' file of 30 Mo unnecessarily. I would prefer the modules to link to one '_package.pyd' file.
What is the best way of doing that?

A: Finally, the easiest way and "correct" way of doing that is by creating multiple projects calling only some exposed parts of the big monolithic project. The smaller projects will be parsed by SWIG to create the Python modules. Works like a charm.

A: I just have the same problem my solution use python ctypes module
spclient_python.pyd is a pydll with two init functions the official one initspclient_python as the dll name and another module called example with initexample function. Every module in python has a corresponding initXXXXXXX function in the dll.
import ctypes
testlib = ctypes.PyDLL("spclient_python.pyd") #this will call initspclient_python
testlib.initexample() # here I am manually calling initexample function inside spclient_python.pyd
import sys
print (sys.modules.keys()) # this will display all the modules imported...spclient_python and example will show
import spclient_python # this is for me to use the module in the code below
import example
test1=spclient_python.test1()
test2=example.test2()


text:
Q: How do I have contiguous memory behave polymorphically in a manner that is safe? I have a large group of thousands of objects that I iterate through, in order, tens of thousands to hundreds of thousands (and in some cases, millions) of times. I would like to store these objects contiguously to reduce my number of cache misses. I would also like to get polymorphic behavior out of them. My idea was to allocate a big chunk of memory, construct them in place, and store a pointer to each object in a vector. Some example code looks like this:
#include <iostream>
#include <vector>
#include <cstdlib>

using namespace std;

class Base
{
public:
  virtual ~Base() {}
  Base(int x) : x_(x) {}
  Base& operator=(const Base& b) { x_ = b.x(); return *this; }
  inline int x() const { return x_; }
  virtual void foo() const { cout << "Base::foo() = " << x() << "\n"; }
private:
  int x_;
};

class Derived : public Base
{
public:
  ~Derived() {}
  Derived(int x, int y) : Base(x), y_(y) {}
  Derived& operator=(const Derived& d) { Base::operator=(d); y_ = d.y();
                                         return *this; }
  inline int y() const { return y_; }
  void foo() const { cout << "Derived::foo() = " << x() << ", " << y() <<
                     "\n"; }
private:
  int y_;
};

constexpr size_t max_class_hierarchy_size()
{
  return (sizeof(Base) > sizeof(Derived)) ? sizeof(Base) :
          sizeof(Derived);
}

enum class DynamicType : unsigned { BASE, DERIVED };

int main()
{
  const static unsigned int n = 5;
  const int xs[] = {1, 3, 2, -4, 5};
  const int ys[] = {-4, 7, 12, 15, 3};
  const DynamicType tps[] = {DynamicType::BASE, DynamicType::DERIVED,
                             DynamicType::DERIVED, DynamicType::DERIVED,
                             DynamicType::BASE};

  cout << "sizeof(Base) = " << sizeof(Base) << "\n";
  cout << "sizeof(Derived) = " << sizeof(Derived) << "\n";
  cout << "max size() = " << max_class_hierarchy_size() << "\n";

  void* main_mem_pool = malloc(n * max_class_hierarchy_size());

  Base* mem_pool = static_cast<Base*>(main_mem_pool);
  vector<Base*> bs(n);

  for (unsigned i = 0; i < n; ++i)
  {
    bs[i] = mem_pool;
    switch(tps[i])
    {
      case DynamicType::BASE:
      {
        Base* new_loc_base = static_cast<Base*>(mem_pool);
        new (new_loc_base) Base(xs[i]);
        new_loc_base++;
        mem_pool = static_cast<Base*>(new_loc_base);
        break;
      }
      case DynamicType::DERIVED:
      {
        Derived* new_loc_derived = static_cast<Derived*>(mem_pool);
        new (new_loc_derived) Derived(xs[i], ys[i]);
        new_loc_derived++;
        mem_pool = static_cast<Base*>(new_loc_derived);
        break;
      }
      default:
        cerr << "Type: " << static_cast<unsigned>(tps[i])
             << " not defined. Exitting...\n";
        exit(1);
    }
  }

  for (const auto& b : bs) b->foo();

  for (int i = n-1; i >= 0; --i) bs[i]->~Base();
  free(main_mem_pool);

  return 0;
}

I apologize for a lengthy example, but this gives me the behavior I expect. The only issue is that valgrind tells me that I have a memory leak. Valgrinds output says that I have 3 allocations and only 2 deallocations. I don't see it though.
Why is this a memory leak? Is there a better way to solve this problem? Is there an easier way to allocate/deallocate than malloc/free/manually calling destructors?

A: Running this with valgrind --leak-check=yes --leak-check=full options, as the original diagnostic from valgrind advised you to do, will show you that the extra allocation comes from some startup code in the C++ standard library, and has nothing to do with your code.
It is quite common for runtime libraries to allocate some static storage at initialization, that they don't bother to release at termination. The original output that you got from valgrind was probably this:
==8498== LEAK SUMMARY:
==8498==    definitely lost: 0 bytes in 0 blocks
==8498==    indirectly lost: 0 bytes in 0 blocks
==8498==      possibly lost: 0 bytes in 0 blocks
==8498==    still reachable: 72,704 bytes in 1 blocks
==8498==         suppressed: 0 bytes in 0 blocks

Unless something shows up in the first two categories, it's usually not a true memory leak. Most distributions configure valgrind with a suppression file that ignores warnings about known memory chunks that standard system libraries grab at initialization, and don't bother to clean up at exit. Gnome libraries are the worst offenders, and the C++ standard library is usually pretty clean, but I guess that current versions of libstdc++ leave something behind, and the various distro valgrind installs haven't been updated to account for that.


text:
Q: Hi, how would I go about animating this jquery slider to a specific value on page load? I have this basic jquery slider in a form and I'd like to have it animate to a specific value on page load but can't seem to make it happen:
[my codepen][1]
 [1]: http://codepen.io/lami0007/pen/MyEoed

A: If that specific value is always going to be the same, just set it in your jquery.
On the 4th line of your JS file, there is a value called "value". Changing that number will cause it to load in as that value.
If the value will change depending on the situation, you should make an OnLoad event that sets that value.


text:
Q: Wanted but not invoked, Kotlin, RxJava, MVP, Mockito I am trying to write a simple test for my MainPresenter(SchedulerProvider) class. It should check if the showEventFragment(String) and showPromptFragment(String) shows up after successful API response.
I create MainPresenter instance in MainActivity like this:
private val presenter: MainContract.Presenter = MainPresenter(AppSchedulerProvider())

Presenter class:
class MainPresenter(private val scheduler: SchedulerProvider) : MainContract.Presenter{

    private val subscriptions = CompositeDisposable()
    private val api: RxApiServiceInterface = RxApiServiceInterface.create()
    private lateinit var view: MainContract.View

    override fun subscribe() {

    }

    override fun unsubscribe() {
        subscriptions.clear()
    }

    override fun loadProfileData() {
        view.showLoadingView()
        val subscribe = api.getProfileDataRequest()
            .subscribeOn(scheduler.io())
            .observeOn(scheduler.ui())
            .subscribe({profileList : List<Profile> ->
                view.showEventFragment(profileList[0].profile_id)
                view.showPromptFragment(profileList[0].profile_id)
            },{ error ->
                view.showErrorMessage(error.message.toString())
                view.showRetryView()
            })

        subscriptions.add(subscribe)
    }

    override fun attach(view: MainContract.View) {
        this.view = view
    }

}

Test class:
class MainPresenterTest {

    @Mock
    private lateinit var view: MainContract.View

    private var api: RxApiServiceInterface = RxApiServiceInterface.create()
    private lateinit var mainPresenter: MainPresenter
    private lateinit var testScheduler: TestScheduler
    private lateinit var testSchedulerProvider: TestSchedulerProvider

    @Before
    fun setup() {
        MockitoAnnotations.initMocks(this)

        testScheduler = TestScheduler()
        testSchedulerProvider = TestSchedulerProvider(testScheduler)

        mainPresenter = MainPresenter(testSchedulerProvider)
        mainPresenter.attach(view)
    }

    @Test
    fun getProfileSuccess() {

        val address = Address("SillyStreet", "4", "80333", "NY")
        val contact = Contact("i.am@dummy.com", "000 000 000 00")
        val mockedProfile = Profile(
            "freemium_profile",
            "Dum",
            "my",
            "male",
            "Sil ly",
            true,
            "First Class",
            "1989-01-01",
            address,
            contact,
            listOf("freemium", "signup_complete")
        )

        doReturn(Single.just(listOf(mockedProfile)))
            .`when`(api)
            .getProfileDataRequest()

        mainPresenter.loadProfileData()

        testSchedulerProvider.testScheduler.triggerActions()

        verify(view).showLoadingView()
        verify(view).showEventFragment(mockedProfile.profile_id)
        verify(view).showPromptFragment(mockedProfile.profile_id)
    }

}

RxApiServiceInterface interface:
interface RxApiServiceInterface {

    @GET("user/customer/profiles")
    fun getProfileDataRequest() : Single<List<Profile>>

    companion object {
        private val restClient by lazy {
            RestClient.createRetrofit(API_URL)
        }

        fun create(): RxApiServiceInterface = restClient.create(RxApiServiceInterface::class.java)
    }
}

TestSchedulerProvider class:
class TestSchedulerProvider constructor(val testScheduler: TestScheduler) : SchedulerProvider {
    override fun ui(): Scheduler = testScheduler
    override fun computation(): Scheduler = testScheduler
    override fun io(): Scheduler = testScheduler
}

I am using these test libs:
testImplementation 'org.mockito:mockito-core:2.22.0'
testImplementation 'org.mockito:mockito-inline:2.22.0'
testImplementation 'org.jetbrains.kotlin:kotlin-test-junit:1.2.71'
androidTestImplementation 'org.mockito:mockito-android:2.7.22'

What the hell am I doing wrong, that I still get the "Wanted but not invoked error"?
The logs also says:
However, there was exactly 1 interaction with this mock:
view.showLoadingView();

but I am not suprised about that as this method is outside API query.


text:
Q: What's the largest REG_SZ value that Regedit can edit? I came across a large string value (REG_SZ) in the Registry and I want to copy it. As I double clicked the value, the textbox was empty.
What is the largest REG_SZ value that Regedit can edit in its textbox?

A: The largest string that can be displayed in the Regedit's textbox has a length of 43679. beginning with a length of 43680, the textbox will appear to be empty. (Windows 10 21H1, if that matters).
And I say "appear", because the value is actually still there. You can press Ctrl+A and Ctrl+C in order to copy it into the clipboard. And you can also copy a text into the clipboard and paste it back to Regedit and accept it.

A: I am sure Ctrl + A & Ctrl + V will not always work, since it does not work on this two keys:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsSelfHost\OneSettings\TargetingAttributes
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsSelfHost\OneSettings\TargetingAttributesVerified

Both values are multi-line very long texts (>60000 each), just like this small  reduced sample pattern:
{
  "Version": ...
  "SchemaVersion": ...
  ...
}

But i can confirm that Ctrl + A & Ctrl + C works, it copy the very long multi-line value perfectly.
But any attempt to put a new multi-line value (for a simple edit of a small part) does not work, no matter how long or short it is, it will only take/accept (write) the first line of the text.
So using REGEDIT to edit such kind of values looks like it is not an option.
Also tried:

*

*If i export the branch to a (.reg) file, edit the text inside the (.reg) file and try to re-import (double clicking) and refresh (with F5 key), such values are not updated.

*If i export the branch to a (.reg) file, delete the key, try to re-import (double clicking) and refresh (with F5 key), such keys are not imported (but the message says all keys were imported).

*I also had tested with a short multi-line value, same results, no way to paste it, only accepted first line, also ignored if inside a (.reg) file, etc.

The key type is somehow weird, it is REG_SZ, not REG_MULTI_SZ.
That is getting me really madness, how is it possible to put/edit such values when they are multi-line in a REG_SZ type key is something i do not know.
Thanks anyway, at least i can read/copy them.


text:
Q: NSView Drag and Drop Data to Controller I'm building an application where I have a subclass of NSView that I want to be a drag and drop area. I then want to pass the data from that operation to the view controller to process the information and do other tasks. I've found that I can't implement the drag and drop methods from the controller; I've had to do it from the view. This means that I have to find a good way to pass the information from the view back to the controller.
My first thought was to try to create delegate functions for the view and then try to implement drag and drop from the controller. This still seems like the best way, but I can't seem to make it work or find a tutorial where someone else did this.  Since I am trying to pass data back, I don't think that notifications will work.
I haven't included any code because I am still at a conceptual stage for how to do this. I have been successful getting the information from the drag and drop information in the view -- the issue is where to go from there.  If I just wanted to display information about the drag and drop in the view, or to perform another action with the view, then I should be set.  My issue exists since I want to further process that information.
So, my question is, what is the best way to pass the data I get from the drag and drop even back to the controller. Should I continue trying to delegate the drag and drop methods so I can get the data directly in the controller?  If so, does anyone have an example of where this has been done?  I know this is a novice question, but any help would be greatly appreciated!

A: Answering my own question again...but this was novice.
I made my controller header a delegate of the NSCollectionView since that was the view type I am using.
@interface MainViewController : NSViewController <NSCollectionViewDelegate>

In my controller awake from NIB, I set the view delegate to my controller...
- (void) awakeFromNib{
    [collectionView setDelegate: self];
}

And then implemented the drag and drop functions in the controller which allows me to accept the data and then make changes to both the view and the business logic as needed.


text:
Q: IsIn for python dataframe 3 of the columns of my dataframe involve medical specialties, I am trying to do a isin on if column1 is in column2, its true... if column2 isin column 3 its true. so the expression would be true. I am also factoring out for nulls, and if everything matches. Swapping the Or between the first line to and & either gives alot of false positives, or seems like it doesnt do anything. The 2nd and 4th line should also be correct.
Dataframe https://i.stack.imgur.com/IqqaZ.png how it looks after doing the formatting.
dfMaster = pd.dataframe({'Specialty_M' : ['Telemetry', 'M/S; Clinic; ER', 'Healthcare', 'M/S; Telemetry', 'ICU', 'Clinic', 'ICU'], 'Specialty_AM': ['ICU', 'ER', 'HLTH', 'M/S', 'ICU', 'PEDS', 'ICU'], 'Specialty_BE' : ['ICU', 'ER', '','M/S', 'ICU', '', 'ICU']})
dfMaster['SPECIALTY Okay?'] = np.NaN

comparisonSpecialty999 = np.where(
    (dfMaster['Specialty_BE'].isin(dfMaster['Specialty_AM']) & dfMaster['Specialty_AM'].isin(dfMaster['Specialty_M'])) |
    ((dfMaster['Specialty_M'].str.upper() == dfMaster['Specialty_BE'].str.upper()) &
    (dfMaster['Specialty_M'].str.upper() == dfMaster['Specialty_AM'].str.upper())) |
    (
            (dfMaster['Specialty_M'] != dfMaster['Specialty_M']) &
            (dfMaster['Specialty_AM'] != dfMaster['Specialty_AM']) &
            (dfMaster['Specialty_BE'] != dfMaster['Specialty_BE']))
    | ~Exists, 'Correct', 'Fix')

dfMaster['SPECIALTY Okay?'] = comparisonSpecialty999

A: Try with apply and in:
dfMaster['SPECIALTY Okay?'] = (np.where(dfMaster.apply(lambda x: (x["Specialty_BE"] in x["Specialty_AM"]) and
                                                       (x["Specialty_AM"] in x["Specialty_M"]),
                                                       axis=1),
                                        "Correct",
                                        "Fix")
                               )

>>> dfMaster
       Specialty_M Specialty_AM Specialty_BE SPECIALTY Okay?
0        Telemetry          ICU          ICU             Fix
1  M/S; Clinic; ER           ER           ER         Correct
2       Healthcare         HLTH                          Fix
3   M/S; Telemetry          M/S          M/S         Correct
4              ICU          ICU          ICU         Correct
5           Clinic         PEDS                          Fix
6              ICU          ICU          ICU         Correct


text:
Q: Ion-segment value checks all Whenever I'm trying to put the value of ion-segment, all of them go on. See my image below for reference.

HTML
 <!-- Segment -->
            <ion-segment
              scrollable
              *ngIf="rating.Type === 'radio'"
              class="segment"
              value=" rating.Checked "
            >
              <ion-segment-button
                (click)="scoreButton(score, rating)"
                *ngFor="let score of rating.Scores"
                value="score.Score_id"
              >
                <!-- {{ score.Descriptions[0].Description }} -->
                {{ score.Score_id }}
              </ion-segment-button>
            </ion-segment>

scoreButton()
  scoreButton(score: any, rating: any) {
// To make sure only 1 score.Selected can be true.
    rating.Scores.map((ratingScore) => {
      if (score.Score_id == ratingScore.Score_id) {
        score.Selected = true;
      } else {
        ratingScore.Selected = false;
      }
    });
    rating.Checked = score.Score_id;
    console.log(score.Descriptions[0].Description, rating);
  }

Image of a rating so you can see the data behind it:

As you can see, I use the rating.Checked value to set the value of ion-segment

A: value of ion-segment and ion-segment-button had to be between parenthesis. So value="score.Score_id" had to be value="{{score.Score_id}}".


text:
Q: How to compare a word is it found in table rows? I have this PostgreSQL table for storing words:
CREATE TABLE IF NOT EXISTS words
(
    id bigint NOT NULL DEFAULT nextval('processed_words_id_seq'::regclass),
    keyword character varying(300) COLLATE pg_catalog."default",
);

insert into words (keyword)
VALUES ('while swam is interesting');

CREATE TABLE IF NOT EXISTS trademarks
(
   id bigint NOT NULL DEFAULT nextval('trademarks_id_seq'::regclass),
   trademark character varying(300) COLLATE pg_catalog."default",
);

Into table trademarks I will have thousands of registered trademarks names.
I want to compare words stored into words table keyword, do they match not only for a words but also for word which is in a group of words. For example:
I have a keyword while swam is interesting stored into words.keyword. I also have a trademark swam located in trademarks.trademark I have a word match, so I want to detect this using SQL.
I tried this:
select
    w.id, w.keyword, t.trademark
from
    words w
inner join
    trademarks t
on
  t.trademark ilike  '%'||w.keyword||'%'
where
   w.keyword = 'all';

But I get this result:

As you can see, the result is wrong. I need to match complete words, not parts of the words. How I can fix this?

A: Split the words field on space to create an array, then use any twice: once for the where (ie "any words list containing 'all') and once for the match (ie any trademark that appears in a words list that also contains 'all'):
select
    w.id,
    w.keyword,
    t.trademark
from words w
join trademarks t on t.trademark =
  any(string_to_array(w.keyword, ' '))
where 'all' = any(string_to_array(w.keyword, ' '))

This matches the whole word, so no need to worry about word boundaries etc.

You can tidy this up and improve performance with a CTE that unnests the words:
with w as (
    select
        id,
        keyword,
        unnest(string_to_array(keyword, ' ')) as term
    from words
    where 'all' = any(string_to_array(keyword, ' '))
)
select
    w.id,
    w.keyword,
    t.trademark
from w
join trademarks t on t.trademark = w.term

Add indexes to make this fly:
create index words_keywords_index on words using gin (keyword);
create index trademarks_trademark_index on trademarks(trademarks);

gin indexes index nested values.

A: One option is to use regular expression as richyen mentions.
If you need to use sql what you have got is correct, except you need to look for a pattern that uses the conditions '%SPACE'||w.keyword||'SPACE%'
select w.id, w.keyword, t.trademark
  from words w
  join trademarks t
    on w.keyword like '% '||t.trademark||' %'
 where t.trademark = 'all'
union all /*condition when there are only single words without a space*/
select w.id, w.keyword, t.trademark
  from words w
  join trademarks t
    on w.keyword =t.trademark
 where t.trademark = 'all';

https://dbfiddle.uk/k5bYAPUh

A: You can split the keyword into a array then later compare if the trademark is inside of the splited array.
select
    w.id, w.keyword, t.trademark
from
    words w
inner join
    trademarks t
on
  t.trademark = ANY( string_to_array(REPLACE(w.keyword , ' ' , '~^~' ),'~^~' , '') )
where
   w.keyword = 'all';

trademark and keywords overlaps each other example:
SELECT
ARRAY['swam'] && string_to_array(REPLACE('while swam is interesting',' ','~^~'), '~^~' ,'');

keywords is inside of trademark example
SELECT
ARRAY['swam'] @> string_to_array(REPLACE('while swam is interesting',' ','~^~'), '~^~' ,'');


text:
Q: Drupal 8 preprocess page I'm new in Drupal 8 & I have an issue.
I need to display a CCK field (custom field) in my theme page page-front.html.twig.
As I understand it's impossible to display node variables in a non-node page, so I start to do a preprocess hook.
My preprocess looks like this:
mythemename.theme
<?php

function THEME_NAME_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    $node = $vars['node'];
    if ($node->isset('field_numero_cin') {
      $field_cin = $node->get('field_numero_cin');
      $vars['field_cin'] = $field_image->value();
    }
  }
}

Unfortunately, when I'm debugging (kint) my variable in page-front.html.twig is NULL.

A: Humm...

*

*Are you entering the preprocess ? ( add a debug message before your
first "if")

*You're trying to access $field_image's value with ->value(). Try
with ->getValue() or ->value

*Stupid question but maybe worth-it : Have you tried clearing the cache ? It's needed after added a preprocess function.

A: Your second if statement is is missing a close bracket, are you getting an error?if ($node->isset('field_numero_cin')) {
      $field_cin = $node->get('field_numero_cin');
      $vars['field_cin'] = $field_image->value();
    }


text:
Q: How to avoid new line when reading from MS Access file? I am trying to read data from MS Access 2007 file and everything seems fine. The problem is that I am storing some values as null and when I am trying to read only few values, the null values create new line in my output.
How can I avoid this, or what other approach should I use while reading from MS Access file?
This is what I am using:
        while (readPersonalData.Read())
        {
            // Count all entries read from the reader.
            countEntries++;

            txtDisplay.Text += "Entry ID: " + readPersonalData.GetValue(0) + Environment.NewLine;
            if (readPersonalData.GetValue(1) != null)
                txtDisplay.Text += "Type: " + readPersonalData.GetValue(1) + Environment.NewLine;
            if (readPersonalData.GetValue(2) != null)
                txtDisplay.Text += "URL: " + readPersonalData.GetValue(2) + Environment.NewLine;
            if (readPersonalData.GetValue(3) != null)
                txtDisplay.Text += "Software Name: " + readPersonalData.GetValue(3) + Environment.NewLine;
            if (readPersonalData.GetValue(4) != null)
                txtDisplay.Text += "Serial Code: " + readPersonalData.GetValue(4) + Environment.NewLine;
            if (readPersonalData.GetValue(5) != null)
                txtDisplay.Text += "User Name: " + readPersonalData.GetValue(5) + Environment.NewLine;
            if (readPersonalData.GetValue(6) != null)
                txtDisplay.Text += "Password: " + readPersonalData.GetValue(6) + Environment.NewLine;
        }

A: You should check for null, so change the line:
readPersonalData.GetValue(0) + Environment.NewLine;

Into:
if(!readPersonalData.IsDBNull(0))
{
  ...readPersonalData.GetValue(0) + Environment.NewLine;
}

In this way you append text only when value in 0 is not null...


text:
Q: How to prove ~~P from P in the Hilbert Axiomatic System? Can someone provide me with hints for, or a rough sketch of, a proof of ~~P from P in the Hilbert system? I had very little trouble proving the reverse, that P is provable from ~~P, but seem to be totally stuck on this guy. My axioms are the following:
φ->(ψ->φ) (1)
[φ->(ψ->χ)]->[(φ->ψ)->(φ->χ)] (2)
(~ψ->~φ)->[(~ψ->φ)->ψ] (3)
and my one rule of inference is modus ponens.
I am also allowed to work with tools like ex falso quodlibet, transitivity, weakening the consequent, etc.
Any help would be greatly appreciated; thank you!

A: You say you can derive $P$ from $\neg \neg P$. Using the Deduction theorem, you can therefore prove $\neg \neg P \rightarrow P$. And that means that we can use $\neg \neg \varphi \rightarrow \varphi$ as a Lemma.
Now, let's show that $\neg \psi \rightarrow \neg \varphi, \varphi \vdash \psi$:

*

*$\neg \psi \rightarrow \neg \varphi$ Premise

*$\varphi$ Premise

*$\varphi \rightarrow (\neg \psi \rightarrow \varphi)$ Axiom 1

*$\neg \psi \rightarrow \varphi$ MP 2,3

*$(\neg \psi \rightarrow \neg \varphi) \rightarrow ((\neg \psi \rightarrow \varphi) \rightarrow \psi$ Axiom 3

*$(\neg \psi \rightarrow \varphi) \rightarrow \psi$ MP 1,5

*$\psi$ MP 4,6

Using the Deduction Theorem, that means we can also prove $(\neg \psi \rightarrow \neg \phi) \rightarrow (\varphi \rightarrow \psi)$ (this statement is usually used as the third axiom in the Hilbert System ... so let's call it Axiom 3')
OK, so then:

*

*$P$ Premise

*$\neg \neg \neg P \rightarrow \neg P$ Lemma

*$(\neg \neg \neg P \rightarrow \neg P) \rightarrow (P \rightarrow \neg \neg P)$ Axiom 3'

*$P \rightarrow \neg \neg P$  MP 2,3

*$\neg \neg P$ MP 1,4

A: Here's a computer generated rough sketch of a detachment based proof.  I used the theorem prover, Prover9, which is freely available online courtesy of Argonne National Laboratory near Chicago.  You'll need to find the substitution instances of axioms and theorems in order to fill in the details.  I used '~' instead of $\lnot$ as a symbol.  I didn't use any strategy whatsoever.  I merely embedded the axioms into the first-order context appropriate for the theorem-prover and used "-P(x-> y) | -P(x) | P(y)." since under hyperressolution (the hyper referenced in the proof) it behaves like condensed detachment does in propositional calculus:
% -------- Comments from original proof --------
% Proof 1 at 0.03 (+0.00) seconds.
% Length of proof is 17.
% Level of proof is 7.
% Maximum clause weight is 20.
% Given clauses 48.

1 P(~(~(x)) -> x) # label(non_clause) # label(goal).  [goal].
2 -P(x-> y) | -P(x) | P(y).  [assumption].
3 P(x -> (y -> x)).  [assumption].
4 P((x -> (y -> z)) -> ((x -> y) -> (x -> z))). [assumption].
5 P((~(x) -> ~(y)) -> ((~(x) -> y) -> x)). [assumption].
6 -P(~(~(c1)) -> c1).  [deny(1)].
7 P(x -> (y -> (z ->> y))).  [hyper(2,a,3,a,b,3,a)].
8 P(((x -> (y -> z)) -> (x -> y)) ->((x -> (y -> z)) -> (x -> z))).  [hyper(2,a,4,a,b,4,a)].
10 P((x -> y)-> (x -> x)).  [hyper(2,a,4,a,b,3,a)].
11 P(((~(x) -> ~(y)) -> (~(x) -> y)) -> ((~(x) -> ~(y)) -> x)).  [hyper(2,a,4,a,b,5,a)].
17 P(x -> x).  [hyper(2,a,10,a,b,7,a)].
20 P(x -> (y -> y)). [hyper(2,a,3,a,b,17,a)].
27 P((x -> ((y -> x) -> z)) -> (x -> z)). [hyper(2,a,8,a,b,7,a)].
71 P((~(x) -> ~(~(x))) -> x). [hyper(2,a,11,a,b,20,a)].
77 P(x -> ((~(y) -> ~(~(y))) -> y)). [hyper(2,a,3,a,b,71,a)].
255 P(~(~(x)) -> x). [hyper(2,a,27,a,b,77,a)].
256 $F.  [resolve(255,a,6,a)].

============================== end of proof ==========================


text:
Q: SharePoint Client Object Model not returning hidden folders in document library I am using the SharePoint Client Object Model to get information from a SharePoint 2010 document library to be able to delete old htm-files located there. The problem is that these htm-files have hidden "_files"-folders associated to them. I am not able to find these folders using the SharePoint Client Object Model, they just don't show up. I can see them in Windows Explorer using WebDav, but not in SharePoint. They don't get deleted if I just delete the .htm-file.
 using (ClientContext context = new ClientContext(webUrl))
        {
            Web web = context.Web;
            context.Credentials = System.Net.CredentialCache.DefaultCredentials;
            context.Load(web);
            context.ExecuteQuery();
            Folder fldr = web.GetFolderByServerRelativeUrl(serverRelativeFolderUrl);
            context.Load(fldr);
            context.Load(fldr.Folders);
            context.ExecuteQuery();
            foreach (Microsoft.SharePoint.Client.Folder folder in fldr.Folders)
            { // no hidden folders found here, only usual folders
                Console.WriteLine(folder.Name);
            }
        }

A: According to http://blogs.msdn.com/b/findnavish/archive/2011/11/16/some-specific-folder-or-files-not-getting-created-in-sharepoint-thickets.aspx and
http://social.technet.microsoft.com/Forums/windows/en-US/d6c187ab-3d70-4357-878f-018b9731c161/sharepoint-folder-with-an-underscore-contained-within
you shouldn't be able to upload the folders without getting renamed to *_files_. Are the folders there without the trailing underscore?
If yes, and you somehow really created thickets you won't see them - they won't reveal as they are beliefed as "internal" and never be listed in the OM.
You can still delete them though:
SPFolder folder = web.GetFolder("Documents/google_files")
//while folder.Exist is false the folder could still exist but be hidden
folder.Delete()

This won't throw an exception if the folder is not found and delete if it exists.
Edit, after finding out that you are searching for a method to do this automatically
You could create an EventReceiver that handles the situation of a file getting deleted and delete the ticket folder to the .htm file accordingly. In the example on http://msdn.microsoft.com/en-us/library/ms453149.aspx they are canceling the ItemDeleting event, you just have to catch the event occuring in the libraries you want (The event will fire on all items in a web) and delete the thicket.
Just a hint when doing so, Sharepoint Manager (http://spm.codeplex.com) is a great tool that helps you stumbling through the objects on your SharePoint. It has done a great job for me when i was deploying features and custom Receivers into SharePoint.


text:
Q: Equivalence relation for $X \sim Y \iff X \cap T = Y \cap T$ For the question

Let $T$ be a fixed subset of a nonempty set $S$. Define the relation $\sim$ on power set of S by $$X \sim Y \iff X \cap T = Y \cap T$$
  Show that $\sim$ is an equivalent relation. In particular let $S = \{1,2,3,4,5\} \text{ and } T = \{1,3\}$
Is $\{1,2,4\} \sim \{1,4,5\}$ and equivalent relationship. What about $\{1,2,4\} \sim \{1,3,4\}$?

The book just gives the answer as true for the first and false for the second. I want to know why my answers are wrong because I get true for both and how to get the right answer.
$\{1, 2, 4\} \sim \{1,4,5\}$ is an equivalence relation because:

*

*Reflexive: $X \cap T = X \cap T$ is true

*Symmetric: $X \cap T = Y \cap T \implies Y \cap T = X \cap T$ is true

*Transitive: $\{1, 2, 4\} \cap \{1,3\} = \{1,4,5\} \cap \{1,3\} \land \{1,4,5\} \cap \{1,3\} = Z \cap \{1,3\} \implies \{1,2,4\} = Z$ is true

$\{1, 2, 4\} \sim \{1,3,4\}$ is an equivalence relation because:

*

*Reflexive is true (see above)

*Symmetric: $\{1, 2, 4\} \cap \{1,3\} = \{1,3,4\}\cap\{1,3\}$ is false since $\{1\} \neq \{1,3\}$ since the premise is false, the implication is true

*Transitive: $\{1, 2, 4\} \cap \{1,3\} = \{1,3,4\} \cap \{1,3\} $ is false since $\{1\} \neq \{1,3\}$. Since the premise is false, the implication is true

A: Honestly, I've been as confused as you are right now when I first saw this stuff. So let's go over it step by step.
First, we need to show the relation $\sim$ satisfies the demands of an equivalence relation. Your reflexivity and symmetricity checks are correct. For transitivity you have, for some reason, replaced $X,Y,T$ with some fixed subsets. To fix this, assume $X\cap T = Y\cap T$ and $Y\cap T = Z\cap T$. Is is then true that $X\cap T = Z\cap T$?
Once we've established that $\sim$ is an equivalence relation, we fix sets $S,T$ and we are asked whether
$$\{1,2,4\} \sim \{1,4,5\}\quad\mbox{or}\quad \{1,2,4\}\sim \{1,3,4\}. $$
To check this, we simply check the condition we defined the relation $\sim$ with. Do the following hold?
$$\{1,2,4\}\cap \{1,3\} \overset{?}= \{1,4,5\}\cap \{1,3\} \quad (\text{yes}) \\
\{1,2,4\}\cap \{1,3\} \overset{?}= \{1,3,4\}\cap \{1,3\}\quad (\text{no})$$
Can you pick it up from here?

A: You're mixing up two different things:

*

*Whether the relation $\sim$ is an equivalence relation or not.

*Whether two particular elements are related by $\sim$ or not.
It does not make sense to ask whether "$\{1,2,4\}\sim\{1,4,5\}$" is an equivalence relation or not, becasue "$\{1,2,4\}\sim\{1,4,5\}$" is not a relation. It is just a claim -- and this happens to be true because the $\sim$ relation you have defined does indeed say that the element $\{1,2,4\}$ is related to the element $\{1,4,5\}$. But it makes no sense to ask, for example, whether the fact that $\{1,2,4\}\sim\{1,4,5\}$ "is reflexive" or not.
I think you're being confused by the fact that $\{1,2,4\}$ and $\{1,2,5\}$ are sets of numbers. However, as far as the relation $\sim$ is concerned those sets are elements, and its properties as a relation do not depend on the incidental fact that the elements it speaks about happen to be sets.

For the exercise I would strongly suggest doing the second part first, to get a feeling for what $\sim$ does in two particular cases.
Then consider whether the entire $\sim$ is an equivalence relation or not.

A: No $\{1,2,4\} \not\sim \{1,4,5\}$  since $\{1,2,4 \} \cap \{1,3 \} = \{1 \} \neq \{1,3\} = \{1,3,4 \} \cap \{1,3 \}.$

A: Something got garbled in your statement of the question. You write "Is $\{1,2,4\} \sim \{1,4,5\}$ an equivalent relationship." First off, what does "equivalent relationship" mean? Your work makes it seem like you think it means "equivalence relation," but that doesn't make sense, because $\{1,2,4\} \sim \{1,4,5\}$ is a single true-or-false statement. Asking if a single true-or-false statement is an equivalence relation is like asking whether the number $5$ is a triangle. It's not even the right kind of thing. I think the question is whether $\{1,2,4\} \sim \{1,4,5\}$ and $\{1,2,4\} \sim \{1,3,4\}$ are true or false. Your attempt doesn't work, because the properties of relexivity, symmetry, and transitivity make no sense to ask about for a single statement like $\{1,2,4\} \sim \{1,4,5\}$.


text:
Q: ASP.NET MVC 3 HiddenFor Javascript I have two hidden input fields in my form:
<input type="hidden" name="lat" id="lat" value=""/>
<input type="hidden" name="long" id="long" value="" />

I am assigning their value by doing the following:
document.getElementById('lat').value = lat;
document.getElementById('long').value = lng;

Can someone please tell me how I can remove the hidden <input> fields and replace them with a @Html.HiddenFor<> and make my Javascript update the HiddenFor? I want to do this because it will obviously automatically bind the data.
My HiddenFor currently looks something like this:
@Html.HiddenFor(m => Model.Listing.Location.Latitude);
@Html.HiddenFor(m => Model.Listing.Location.Longitude);

I change the Javascript to do this:
document.getElementById('Listing.Location.Latitude').value = lat;
document.getElementById('Listing.Location.Longitude').value = lng;

I get the following error in the Console:
Uncaught TypeError: Cannot set property 'value' of null

Can anyone see where I am going horribly wrong?

A: Try this.
@Html.HiddenFor(m => m.Listing.Location.Latitude, new {id = "theIdyouWant"})

So you can get the element using Javascript:
document.getElementById("theIdyouWant")

A: Your problem is that id will be another. Listing.Location.Latitude is name attribute.
For example:
@Html.TextBoxFor(x => x.General.Site_Name)

generated as:
<input id="General_Site_Name" type="text" name="General.Site_Name" />

A: The Ids of these fields will have underscores not dots, their names will have the dots.  Try this:
document.getElementById('Listing_Location_Latitude').value = lat;


text:
Q: Count Value with smaller than and Endswith condition Problem:
Find unitcode that endswith '1001' in the .txt file and count this unit if anyone getting marks below 50. If yes, count. If no, give a value of 0
My code:
skipped_header = True
counters_unit_code = {}
with open("inp.txt") as csv_file:
  for line in csv_file:
    if skipped_header:
      skipped_header = False
      continue
    record = line.rstrip().split(':')
    unit_code = record[2].endswith('1001')
    min_mark = int(record[4])
    if unit_code not in counters_unit_code:
      counters_unit_code[unit_code]=0
    if min_mark < 50:
      counters_unit_code[unit_code] += 1

for unit_code in counters_unit_code:
  print(str(unit_code),counters_unit_code[unit_code])

My output:
False 1
True 3

Expected output:
engl1001 3
math1001 0

txt file (inp.txt):
Name:unikey:unitcode:year:mark
Joe Smith:jsmi3031:chem1101:2016:40
Oleg Catem:ocat3031:chem1101:2016:79
Joe Smith:jsmi3031:engl1001:2015:0
Joe Smith:jsmi3031:engl1001:2016:45
Tim Gold:tgol2145:engl1001:2016:46
Paula Dong:pdon1234:engl1001:2016:91
Joe Smith:jsmi3031:engl1001:2017:54
Oleg Catem:ocat3031:engl1001:2017:87
Oleg Catem:ocat3031:math1001:2016:95
Joe Smith:jsmi3031:math1001:2016:59
Paula Dong:pdon1234:math1001:2016:99

A: unit_code = record[2].endswith('1001')
This line gives you True or False and not substring.
for substring use
if record[2].endswith('1001'):
   unit_code = record[2][:-4]

A: The problem is the line
unit_code = record[2].endswith('1001')

The .endswith() function returns a boolean value, which is why your output contains "True" and "False" instead of the unit codes.  I think you meant to extract the unit code, and test whether it ends with '1001'.  Something more like this:
skipped_header = True
counters_unit_code = {}
with open("inp.txt") as csv_file:
  for line in csv_file:
    if skipped_header:
      skipped_header = False
      continue
    record = line.rstrip().split(':')
    unit_code = record[2]
      if unit_code.endswith('1001'):
        min_mark = int(record[4])
        if unit_code not in counters_unit_code:
          counters_unit_code[unit_code] = 0
        if min_mark < 50:
          counters_unit_code[unit_code] += 1

for unit_code in counters_unit_code:
  print(str(unit_code), counters_unit_code[unit_code])

A: skipped_header = True
counters_unit_code = {}
with open("inp.txt") as csv_file:
  for line in csv_file:
    if skipped_header:
      skipped_header = False
      continue
    record = line.rstrip().split(':')
    unit_code = record[2]
    min_mark = int(record[4])
    if unicode.endswith('1001'):
      if unit_code not in counters_unit_code:
        counters_unit_code[unit_code]=0
      if min_mark < 50:
        counters_unit_code[unit_code] += 1

for unit_code in counters_unit_code:
  print(str(unit_code),counters_unit_code[unit_code])

A: I think you meant your expected value for eng1001 is 3 right?
The problem was your line
unit_code = record[2].endswith('1001')

endswith returns a boolean-value
This should do, what you are trying to achieve:
skipped_header = True
counters_unit_code = {}
unit_code = 0
with open("inp.txt") as csv_file:
    for line in csv_file:
        if skipped_header:
            skipped_header = False
            continue
        record = line.rstrip().split(':')
        if record[2].endswith('1001'):
            unit_code = record[2]
        min_mark = int(record[4])
        if unit_code not in counters_unit_code:
            counters_unit_code[unit_code] = 0
        if min_mark < 50:
            counters_unit_code[unit_code] += 1

for unit_code in counters_unit_code:
    print(str(unit_code), counters_unit_code[unit_code])

A: I would use re instead of basing it on :s
import re

pattern = r"(\w{4}1001):\d{4}:(\d+)"

with open("inp.txt") as csv_file:
    values = csv_file.read()
    subjects = {}
    for match in re.finditer(pattern, values):
        subject, score = match.groups()
        scores = subjects.setdefault(subject, [])
        if int(score) < 50:
            scores.append(score)

    for subject, scores in subjects.items():
        print("{}: {}".format(subject, len(scores)))

# Output
engl1001: 3
math1001: 0


text:
Q: RangeError: Maximum call stack size exceeded at Array.map () when trying to deploy to heroku I am trying to deploy an mern stack app to heroku when I got this error in heroku cli.
RangeError: /tmp/build_c861a30c/frontend/node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js: Maximum call stack size exceeded
           at Array.map (<anonymous>)
           at Array.map (<anonymous>)
           at Array.map (<anonymous>)

-----> Build failed

The app itself works fine on localhost so I don't really understand where this error is coming from. The app code is located here: https://github.com/gbopola/mern-learn-tut-2022

A: Tried to run in my computer and it is giving me the following error:
Failed to compile.
RangeError: /home/hafizur/projects/stackoverflow/mern-learn-tut-2022/frontend/node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js: Maximum call stack size exceeded
    at Array.map (<anonymous>)
    at Array.map (<anonymous>)
    at Array.map (<anonymous>)
asset static/js/bundle.js 3.45 MiB [emitted] (name: main) 1 related asset
asset index.html 1.68 KiB [emitted]
asset asset-manifest.json 190 bytes [emitted]
runtime modules 28.1 KiB 13 modules
modules by path ./node_modules/ 3.03 MiB 177 modules
modules by path ./src/ 62.7 KiB
  modules by path ./src/features/ 10.7 KiB 4 modules
  modules by path ./src/components/*.jsx 11.7 KiB 4 modules
  modules by path ./src/*.js 11.4 KiB
    ./src/index.js 2.1 KiB [built] [code generated]
    + 2 modules
  modules by path ./src/pages/*.jsx 16.7 KiB
    ./src/pages/Dashboard.jsx 4.04 KiB [built] [code generated]
    + 2 modules
  modules by path ./src/*.css 11 KiB
    ./src/index.css 2.72 KiB [built] [code generated]
    ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!./src/index.css 8.29 KiB [built] [code generated]
  ./src/app/store.js 1.26 KiB [built] [code generated]

WARNING in src/components/Header.jsx
  Line 1:9:  'FaSignInAlt' is defined but never used  no-unused-vars

src/pages/Login.jsx
  Line 6:9:  'FaUser' is defined but never used  no-unused-vars

ERROR in ./node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
RangeError: /home/hafizur/projects/stackoverflow/mern-learn-tut-2022/frontend/node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js: Maximum call stack size exceeded
    at Object.decode (/home/hafizur/projects/stackoverflow/mern-learn-tut-2022/frontend/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js:36:20)
    at new TraceMap (/home/hafizur/projects/stackoverflow/mern-learn-tut-2022/frontend/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js:187:48)
    at /home/hafizur/projects/stackoverflow/mern-learn-tut-2022/frontend/node_modules/@ampproject/remapping/dist/remapping.umd.js:230:26
    at Array.map (<anonymous>)
    at build (/home/hafizur/projects/stackoverflow/mern-learn-tut-2022/frontend/node_modules/@ampproject/remapping/dist/remapping.umd.js:206:42)
    at /home/hafizur/projects/stackoverflow/mern-learn-tut-2022/frontend/node_modules/@ampproject/remapping/dist/remapping.umd.js:230:20
    at Array.map (<anonymous>)
    at build (/home/hafizur/projects/stackoverflow/mern-learn-tut-2022/frontend/node_modules/@ampproject/remapping/dist/remapping.umd.js:206:42)
    at /home/hafizur/projects/stackoverflow/mern-learn-tut-2022/frontend/node_modules/@ampproject/remapping/dist/remapping.umd.js:230:20
    at Array.map (<anonymous>)
 @ ./src/app/store.js 3:0-50 6:21-35
 @ ./src/index.js 8:0-36 14:11-16

webpack 5.69.0 compiled with 1 error and 1 warning in 30571 ms

from what u are saying, it runs perfectly fine on ur local computer, this probably means u are using an older version of npm and/or nodejs with older packages and stuff, and the Heroku is probably trying to build with the latest packages, u might just want to update ur npm & nodejs and reinstall the node modules, this will probably cause u to be able to recreate this error in ur local machine and therefore it would be easier to debug,
note: I'm not sure about any of these


text:
Q: The right way to create Eclipse product could someone from Eclipse guru explain in plain English what I do wrong? :) Suppose I have a multimodal maven project and each module is an eclipse plugin. Additionally, I have a module that creates an Eclipse feature(s) from these plugins.
I want to create an Eclipse product from all my features and run it as CLI application which is run by ant.
So, I create another module that contains a product file for my application.
I decided that my product will be feature-oriented, thus I add the  section in my product file and insert all my features there.
After that on "Configuration" tab I press "Add recommended" and Eclipse adds the next plugins
 <plugin id="org.apache.felix.scr" autoStart="true" startLevel="2" />
 <plugin id="org.eclipse.core.runtime" autoStart="true" startLevel="0" />
 <plugin id="org.eclipse.equinox.common" autoStart="true" startLevel="2" />
 <plugin id="org.eclipse.equinox.event" autoStart="true" startLevel="2" />
 <plugin id="org.eclipse.equinox.simpleconfigurator" autoStart="true" startLevel="1" />

in the configuration section of the product file.
I compile the whole of my maven project and receive an executable file that I can run in the terminal.
But unfortunately, when I start this file by command
ant -propertyfile ant.cfg -f config/compile.xml
I receive
BUILD FAILED
..... : exec returned: 139

When I start my executable file I receive "Segmentation fault"
So my question is: which plugins should I add to the configuration section of the product file?
P.S. There is a more detailed description in my another post
P.P.S There was a lot of additional plugins in the product file when this product was running by Java 8 on Eclipse Kepler, should I add all of them?

A: The root problem was not in the list of the features and plugins, but in
<programArgsLin>-os ${target.os} -ws ${target.ws} -arch ${target.arch} -consoleLog
After removing -os ${target.os} -ws ${target.ws} -arch ${target.arch} the application is starting without "Segmentation fault".
And about the list of the features and plugins - I've found the "an algorithm" :)

*

*Open product file and on the "Contents" tab add all your features you need

*Go to "Configuration" tab and press "Add Recomended", eclipse will add

<configurations>
      <plugin id="org.apache.felix.scr" autoStart="true" startLevel="2" />
      <plugin id="org.eclipse.core.runtime" autoStart="true" startLevel="0" />
      <plugin id="org.eclipse.equinox.common" autoStart="true" startLevel="2" />
      <plugin id="org.eclipse.equinox.event" autoStart="true" startLevel="2" />
      <plugin id="org.eclipse.equinox.simpleconfigurator" autoStart="true" startLevel="1" />
   </configurations>

to the product file
3. On this step application still cannot be compiled, because org.apache.felix.scr cannot be found. I've used approach from this post to find in which feature org.apache.felix.scr is belonged - it's org.eclipse.e4.rcp

*So, I've returned to "Contents" tab and added org.eclipse.e4.rcp as a feature

*After that I've pressed "Add required" and eclipse added additional features. Thus full product configuration file looks like

...
<launcherArgs>
      <programArgs>-consoleLog
      </programArgs>
      <vmArgs>-Xshare:auto -Declipse.ignoreApp=true -Dosgi.noShutdown=true -Dlogback.configurationFile=log.xml
      </vmArgs>
      <vmArgsLin>
         <argsX86_64>-Xmx2048m -Xms512m -XX:+UseParallelGC</argsX86_64>
      </vmArgsLin>
      <vmArgsMac>-XstartOnFirstThread -Dorg.eclipse.swt.internal.carbon.smallFonts
      </vmArgsMac>
      <vmArgsWin>-Xmx768m -Xms256m
      </vmArgsWin>
   </launcherArgs>
...
<features>
     ... list of my features ...
      <feature id="org.eclipse.e4.rcp" installMode="root"/>
      <feature id="org.eclipse.emf.ecore" installMode="root"/>
      <feature id="org.eclipse.emf.common" installMode="root"/>
   </features>

   <configurations>
      <plugin id="org.apache.felix.scr" autoStart="true" startLevel="2" />
      <plugin id="org.eclipse.core.runtime" autoStart="true" startLevel="0" />
      <plugin id="org.eclipse.equinox.common" autoStart="true" startLevel="2" />
      <plugin id="org.eclipse.equinox.event" autoStart="true" startLevel="2" />
      <plugin id="org.eclipse.equinox.simpleconfigurator" autoStart="true" startLevel="1" />
   </configurations>
...