text:
Q: SQL to LINQ Converter I have a SQL and having a hard time to convert it to LINQ. Are there any other tools that can convert SQL to LINQ? I heard Linqer and tried it but it doesn't allow you to query on the Junction/Join Table of a Many-to-Many relationship tables. In any case here's the SQL that I need to convert to LINQ or even lambda.
SELECT A.*
FROM
(              SELECT  TOP 10   T2.ID,
                T2.Name,
                SUM(T1.Column1 + T1.Column2 + T1.Column3) AS Total
FROM POS.dbo.Table1 T1
INNER JOIN POS.dbo.Table2 T2 on T2.ID = T1.ID
WHERE T2.ID IN
(
    SELECT ID FROM POS.dbo.Table3 WHERE [Id] = 1
)
AND [Date] BETWEEN '2011-11-09 00:00:00' AND '2011-11-09 23:59:59'
GROUP BY T2.ID, T2.Name
ORDER BY Total DESC
) A
ORDER BY Name ASC

Here is my first attempt:
var query = db.Table1
              .Include(e => e.Table2)
              .Where(x => x.Date >= '2011-11-09 00:00:00'
                       && x.DateCreated <= '2011-11-09 23:59:59')
              .Where(y => y.Table2.Table3.Any(u => u.Id == 1))
              .Take(10);

A: One of the things I like most about Linq is that it will combine queries together, so I break a complicated query into subqueries and let Linq recombine them all.
Using that basis, does something like this work.
DateTime startDate = new DateTime(2011,11,9);
DateTime endDate   = new DateTime(2011,11,9,23,59,59);

var table3Ids = (from r in Pos.dbo.Table3 where id = 1 select r.id) ;

var query1  =
(
    from t1 in Pos.dbo.Table1
    where t1.Table2.Id == 1 && t1.Date >= startDate && t1.Date <= endDate
    where table3Ids.Contains(t1.Table2.Id)
    group t1 by new { t1.Table2.Id , t1.Table2.Name} into results

    select new
    {
        results.Key.Id ,
        results.Key.Name ,
        Total = results.Sum(r=> (r.Column1 + r.Column2 + r.Column3))
    }
);

var query2 = (from r in query1 orderby r.Total descending select r).Take(10);
var query3 = (from r in query2 orderby r.Name select r);

var list = query3.ToList();

A: Here's my shot - it's a bit hard without knowing the actual data structure or the expected results:
var query = db.Table1
    .Join(db.Table2, table1 => table1.Id, table2 => table2.Id, (t1, t2) => new {
        Id = t2.Id,
        Name = t2.Name,
        Total = (t1.Column1 + t1.Column2 + t1.Column3),
        Date = t1.Date //you didn't use a table alias for this field, so I'm not sure which table it comes from
        })
    .Where(x => x.Date >= new DateTime(2011, 11, 9)
                && x.DateCreated <= new DateTime(2011, 11, 9, 23, 59, 59))
    .Join(db.Table3, x => x.Id, table3 => table3.Id, (x, t3) => new {
        Id = x.Id,
        Name = x.Name,
        x.Total
    })
    .Where(x => x.Id == 1)
    .OrderByDescending(x => x.Total)
    .ThenBy(x => x.Name)
    .Take(10)
    .ToList()

Because that might be the craziest Linq statement I've ever written, don't assume it'll work the first time, but it's at least a good starting point.


text:
Q: Creating an array of 10 elements and assigning them by counting randomly Creating an array of 10 elements and assigning them by counting randomly, assigning a new number if the same numbers are repeated
I tried to use the contains method but it didn't appear in the list after the array, I used the exists method but it didn't work either, what kind of way should I follow? thanks
static void Main(string[] args)
{
 Random Rnd = new Random();
 int[] Numbers = new int[10];

 for (int i = 0; i < Numbers.Length; i++)
 {
     int rast = Rnd.Next(10);
     bool b = Array.Exists(Numbers, element => element == rast);
     if (!b)
     {
         i--;
     }
     else { Numbers[i] = rast; }
  }

  foreach (int item in Numbers)
  {
      Console.WriteLine(item);
  }
}

A: It appears that you want the numbers from 0 to 9 in an array in random order. If that is so:
var rng = new Random();
var numbers = Enumerable.Range(0, 10).OrderBy(n => rng.NextDouble()).ToArray();

A: Here's an example. I hope this is the output you want.
public static void Main()
{
     Random Rnd = new Random();
     int[] Numbers = new int[10];

     for (int i = 0; i < Numbers.Length; i++)
     {
         int rast = Rnd.Next(10);

         bool b = Array.Exists(Numbers, element => element == rast);
         if (!b)
         {
             Numbers[i] = rast;
             Console.WriteLine(rast);
         }
         else {
             i--;
         }
      }
}

A: You're close, but there are two issues in your algorithm:

*

*if (!b) should be if (b)

*Rnd.Next(1,10) gets numbers between 1 and 9 so you will never get a 10 and the algorithm will never finish.

After fixing these two your program will work.

Anyway, here's a version that uses .Contains
Random Rnd = new Random();
int[] Numbers = new int[10];

 for (int i = 0; i < Numbers.Length; i++)
 {
     // + 1 because the range of return values includes minValue but not maxValue.
     int r = Rnd.Next(minValue: 1, maxValue: Numbers.Length + 1);
     while(Numbers.Contains(r))
     {
        r = Rnd.Next(minValue: 1, maxValue: Numbers.Length + 1);
     }

     Numbers[i] = r;
  }

Console.WriteLine(string.Join(",", Numbers));

Example output:
9,8,7,1,4,6,3,10,5,2

A: As a result, I have found the solution, thanks to everyone who answered and showed me the way
        int[] Numbers = new int[10];
        int x, y;
        Random ran = new Random();
        for (x = 0; x < 10; x++)
        {
            Numbers[x] = ran.Next(1, 10);
            for (y = x; y >= 0; y--)
            {
                if (x == y)
                {
                    continue;
                }
                if (Numbers[x] == Numbers[y])
                {
                    Numbers[x] = ran.Next(1, 10);
                    y = x;

                }

            }

            Console.WriteLine(Numbers[x]);
        }

A: when i created new project as  Console .net in visual studio 2019 ,

it doesnt bring this libraries automatically ,
Because the following libraries are not attached, the codings I used before did not work, I developed another simple solution, and in this way, I realized that I had a problem due to these libraries not being attached.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

            int[] Numbers= new int[10];

            Random rnd = new Random();

            for (int i = 0; i < Numbers.Length; i++)
            {
                int Num= rnd.Next(10);
                if (Numbers.Contains(Num))
                {
                    i--;
                }
                else
                {
                    Console.WriteLine(Numbers[i] = Num);

                }

            }

redpajama_set_name: RedPajamaStackExchange


text:
Q: WCF-Custom oracleDBBinding: ORA-22062: invalid input string [40,7] at Oracle.DataAccess.Types.OracleDecimal I have a BizTalk 2016 server and in my solution, I'm sending a "40,7" string to insert in a Oracle Database through WCF-Custom oracleDBBinding.
"40,7" is because the Host Instance user has the locale = es-ES.
In the registry is configured at Oracle level, NLS_LANG = AMERICAN_AMERICA.WE8MSWIN1252.
In all BizTalk 2009 servers, with the same configuration works perfect, but in this new BizTalk 2016 server always return the error:
ORA-22062: invalid input string [40,7] at Oracle.DataAccess.Types.OracleDecimal

Any ideas?


text:
Q: Variables not rendering when template is passed from database I have in database template for email with variables ant etc..
When I pass that template in my view from database variable are not rendered and displayed {{ $child_fullname }}, {{ $specialist_fullname }} and etc. instead of given name.
Here is my Mail build function:
public function build()
{
    return $this->subject('Pranešimas apie sėkmingą registraciją')
                ->view('email-template')
                ->with([
                    'body'                => EmailTemplate::find(1)->text,
                    'child_fullname'      => $this->child->name . ' ' . $this->child->surname,
                    'specialist_fullname' => $this->card->specialist->name,
                    'date_time'           => $this->visits->workSchedule->work_date .
                                             ' ' . $this->visits->workSchedule->work_time
                ]);
}

Blade template:
<!doctype html>
<html>
    <head>
        <meta name="viewport" content="width=device-width">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    {!! $body !!}
</html>

Result:

Thanks in advance for help!
P.S Using this to send email.

A: It's not rendering because body is a variable passed to the view.
You should first render the body, then include it into your e-mail.
One solution is to use https://github.com/TerrePorter/StringBladeCompiler it will get you started.
The pseudocode for it is:
public function build()
{
    return $this->subject('Pranešimas apie sėkmingą registraciją')
        ->view('email-template')->with(
            [
                'body'                  => renderFromString(EmailTemplate::find(1)->text,
                [
                    'child_fullname'        => $this->child->name . ' ' . $this->child->surname,
                    'specialist_fullname'   => $this->card->specialist->name,
                    'date_time'             => $this->visits->workSchedule->work_date . ' ' . $this->visits->workSchedule->work_time
            ])
        );
}

A: Try Blade::compileString()
{!! Blade::compileString($body) !!}


text:
Q: how to allow user to add html and javascript in my rails app I want to create a Rails app where users can create their blog in a subdomain like : user1blog.myapp.com, user2blog.myapp.com etc...
I want to allow users to add html and javascript (sometimes they need to add popups to their blog, or tracking code ...)
I see a lot of website which allow users to add scripts and html without any restriction, but How i can do that too without affecting the security of my Rails app ?

A: There are multiple facets to this question:
Dynamic Subdomains:
Other questions address this:
Rails 4 Dynamic Subdomains
Ruby on Rails route for wildcard subdomains to a controller/action
short answer, there are many ways and it depends on your use case.
User submitted html, js
There are many solutions here as well.
I Suggest searching for "CMS" (Content Management System).
There are solutions like refinery, Comfy Mexican Sofa, and others.
Again, it depends significantly on your use case.
Security of my Rails app
If you are allowing user submitted html and js, I would say that you are implicitly compromising the security of your site. Your Rails app itself might be securable, but that's a major thread of conversation about xss, auth[z/n], and other items. Again, highly dependent on your use cases.


text:
Q: Need to reroute url /foo/index to index/foo on Zend Framework I need to reroute a url here. I'm using teh end framework and need to set up some basic static pages here. LIke privacy policy, advertise etc - however the problem is that I need to create a controller for each and every page here. Thats not much of an issue but I was wondering if its possibel for me to set it up so:
mysite.com/privacy/index

would be rerouted to
mysite.com/pages/privacy

Might sound like a non issue but would like to know

A: For every static page, you can add a route for it in your application.ini. For example, for mysite.com/privacy/index you can do:
resources.router.routes.privacy.route = "/privacy/index"
resources.router.routes.privacy.defaults.module = default
resources.router.routes.privacy.defaults.controller = pages
resources.router.routes.privacy.defaults.action = privacy

More about routing in ZF is in the ZF's manual.
Hope this helps

A: From my experience I would STRONGLY discourage creating custom routes if not 100% needed (exception be urls with keywords for products or CMS generated pages). We wanted to our ecommerce solution to have nice urls like /about-us/ instead of /pages/about-us/, but it's PITA to add any more features, as you had to add new route for every such thing. We currently have like 25 custom routes. You can never tell what the hack the url is because standard-url like producer/index is routed from something like producers.
If you still want it, follow Marcin's answer :)


text:
Q: Draining laptop battery power to null using Windows power option My laptop has the same issue as most laptops do have , it does not hold on to its charge for the expected amount of time . Now I have seen blog post that suggest to 'completely' drain battery power out . Now it is one of possible solution for shortened battery power , and many a times I have used my laptop till it hibernated automatically . The situation did not improve and I am not willing to buy a new battery .
Now , my question is , there is an option in Windows power option how much battery power to reserve , usually it is set to 5% after which the laptop is set in to hibernate . Is it a good idea to change that number to as low as 0% to see if the condition improve ?

A: "Completely discharging": It is actually dangerous to charge a li-ion battery once it has been discharged below a certain point (they will overheat rapidly, with resulting possible fire, etc.). So all li-ion packs, and even some individual cells, have a built-in chip called an "electronic fuse". (If you see cells advertised "with chip," this is what they're talking about.) If you somehow manage to discharge the battery below that point, the "fuse" will open and your battery is a paperweight after that! But, not to worry: The "0% charge" on your laptop's charge scale is at least 5 percentage points above this point. The laptop's power controller simply will not let you discharge the battery any farther. You would have to connect a load to the battery directly to do it. So... it is safe to tell Windows to let you go to 0%, in the name of "exercising" the battery.
HOWEVER... I've tried this a couple of times with aging batteries and it's never done a thing for my battery runtime.
It is not clear that deep discharge to near the electronic fuse point (which is to say, the point where the laptop forces shutdown) is damaging to a Li-ion. I've done this to my laptop batteries a few times and have not noticed any issues.
Because of the "electronic fuse", if you store li-ions for a long time, check up on them every two months or so - keep them between 40 and 60% charge. They self-discharge very slowly, but if left for a long time they could self-discharge far enough that the "fuse" will open and you won't be able to charge them again.
Re overcharging: ALL laptops (in fact, all equipment with built-in Li-ion charging circuitry) stop charging when the battery is fully charged and are incapable of "overcharging". The circuitry for this is a single charge controller chip, ridiculously cheap. Manufacturers do not cheap out on this because they do not want their products associated with large numbers of battery fires, which is what would happen.
What does damage laptop batteries if they are left "on charge" too long is heat. This is mostly dependent on the laptop design - if the battery is where it will pick up heat from the hard drive or CPU, its runtime will be degraded sooner than otherwise. So in those systems it IS a good idea to not leave the battery in the laptop once it's charged. The laptops where a part of the battery hangs out beyond the laptop's normal perimeter are actually a good design in this regard!
"Recalibrating": Laptops do not use any sort of "timer" to determine battery remaining charge. (This would be useless as you can easily change your battery drain by a factor of at least 2:1 by varying the screen brightness, by using your hard drive a lot or a little, same for CPU, etc.) They use the battery terminal voltage.
My attitude is that life is too short to treat laptop batteries with kid gloves. I treat mine like I treat the gas tank in my car: I use what I need to use from it, whether that's a little or a lot, and when I can charge it I charge it completely, in case I'll need to use it a lot. I've never had cause to complain about the results.
A lot of the lore about li-ions, in particular the notion that they really don't like deep discharge ("recharge early and often"), seems to come from a web site called "Battery University". It is not a reliable source.

A: First it should be stated that the expected battery life is set rather optimistically with a fresh, new battery.  Every battery starts to degrade immediately and there are several factors which cause it to degrade faster and hold progressively less charge.
Heat will cause the chemistry to break down resulting in less capacity.  You're basically cooking the chemicals in the battery causing them to break down.
Overcharging and overdischarging will both cause breakdown.  If you overcharge, it causes heat and it tries to push the chemical cycle to reverse, but there is a limit.  Keep charging and you won't push the battery to have a higher capacity.  That's why there's a debate whether keeping the battery in while on AC is good or not.  Most laptops will have some circuitry to prevent overcharging, but who's to say that your laptop manufacturer didn't cheap out and not install a really high quality controller?
If you over-discharge, you push the chemical cycle from charged to discharged and it may go to a point where the chemicals can't go back.  Push too far and you may push the chemistry over the edge so doing a 100% discharge is not recommended as a standard practice.
The other issue is simply time - the chemicals degrade as time goes on just like food eventually goes bad.
That said, what are you doing when you do this full charge/discharge until the laptop shuts off?  Basically you are retraining the laptop to recognize how much less capacity the battery has so the meter is more accurate, you aren't really helping the situation - you're hurting the battery.  The laptop starts a timer saying - the battery is full. Then it waits until the battery signals that it is about to quit.  The laptop then calculates a new Full to Empty equation to use from that point onward.
The old NiCad battery packs had a memory problem which the full discharge cycle was supposed to fix.  Remember - you are not using NiCad any longer - you are using Lithium which prefers small, short discharges, and not really deep long ones.  Some lithium packs are limited - they can only take something like a 1000 cycles - then they die.


text:
Q: Hartshorne Corollary 4.7, page 321 I am having trouble understanding two statements from the proof of this Corollary.
First, we take a morphism of degree 2, say $\pi: X \to \mathbb P^1$ where $X$ is an elliptic curve sending our distinguished point to infinity, branched over $0,1,\lambda,\infty$. We consider $\sigma$ in the automorphism group $G$ of $X$, and we find an automorphism $\tau$ of $\mathbb P^1$ fixing infinity such that $\pi \circ \sigma = \tau \circ \pi$, so that $\tau$ permutes the branch points $0, 1, \lambda$.
Hartshorne then claims two things I do not follow:
1.) If $\tau$ is not the identity, $\lambda$, the cross ratio, must be equal to at least one of its other 5 orbit representatives under the action of permutation. Why is this the case?
2.) He then claims that if $\lambda$ equals exactly one other orbit representative, then the size of $G$ is $4$. Why is this true?


text:
Q: $digest already running - AngularJS I want to "refresh" my view after some new data is loaded into my factory, but i cant figure out how to do this correctly.
$http.post(url, postKunde).success(function(data, status) {
                $rootScope.calc = data.calc;
                $rootScope.$apply();
        }).error(function(data, status) {
                console.log(status);
        });

This is the method Im using in my factory. And everytime it triggers i get this error:
Error: $digest already in progress

Can anyone tell me how to do this correctly ? Thanks ...

A: You could write a safe apply that will check if there is a digest:
 $scope.safeApply = function(fn) {
  var phase = this.$root.$$phase;
  if(phase == '$apply' || phase == '$digest') {
    if(fn && (typeof(fn) === 'function')) {
      fn();
    }
  } else {
    this.$apply(fn);
  }
};

Reference for this little gem: https://coderwall.com/p/ngisma


text:
Q: String Char Iterator Just returned to programming in C++.
the errors i get:

request for member begin in sent is of non-class type char[30]
request for member end in sent is of non-class type char[30]

char sent[] = "need to break this shiat down";
    for(vector<string>::iterator it=sent.begin(); it!=sent.end(); ++it){
        if(*it == " ")
            cout << "\n";
        else
            cout << *it << endl;
    }

should i change the char to string or define the vector differently?

A: It has been pointed out in other answers that you are iterating over the wrong type. You should define sent to be of std::string type and use std::string::begin() and std::string::end() to iterate, or, if you have C++11 support, you have some options for easily iterating over a fixed size array. You can iterate using std::begin and std::end`:
char sent[] = "need to break this shiat down";
for(char* it = std::begin(sent); it != std::end(sent); ++it){
    if(*it == ' ')
        std::cout << "\n";
    else
        std::cout << *it << "\n";
}

or you can use a range-based loop:
char sent[] = "need to break this shiat down";
for (const auto& c : sent)
{
  std::cout << c << "\n";
}

A: You can also use streaming to throw out the whitespace and throw in newlines.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main(int argc, char *argv[])
{
    stringstream ss("need to break this shiat down.", ios_base::in);

    string s;
    while (ss >> s)
        cout << s << endl;

    return EXIT_SUCCESS;
}

Result:

need
  to
  break
  this
  shiat
  down.

A: char sent[] is not std::string but string literal - but in this very case you can iterate over it:
int main() {
char sent[] = "need to break this shiat down";
    for(auto it = std::begin(sent); it!=std::end(sent) - 1; ++it){
        if(*it == ' ')
            cout << "\n";
        else
            cout << *it << endl;
    }
}

Note that I changed " " to ' ' - and skipped last null terminating char '\0'...
Live example: http://liveworkspace.org/code/55f826dfcf1903329c0f6f4e40682a12
For C++03 you can use this approach:
int main() {
char sent[] = "need to break this shiat down";
    for(char* it = sent; it!=sent+sizeof(sent) - 1; ++it){
        if(*it == ' ')
            cout << "\n";
        else
            cout << *it << endl;
    }
}

If this is string literal of size not known at that point - use strlen instead of sizeof...

A: Your variable sent is not of type vector<string>, but char[].
Your for loop however, tries to iterate over a vector of strings.
For a plain array, use C iteration:
 int len = strlen(sent);
 for (int i = 0; i < len; i++)

A: Use string instead of char[]
string sent = "need to break this shiat down";
for(string::iterator it=sent.begin(); it!=sent.end(); ++it){
    if(*it == ' ')
        cout << "\n";
    else
        cout << *it << endl;
}

char[] doesnt have begin and end methods..


text:
Q: Prevent my fragment and list from being created every time they are displayed I'm using databinding and fragments with navigation component for the first time in my app. Everything works fine with regard to navigation and loading my list. The problem I have is this:
When I'm in my list and I click on one of the items, I navigate to the item's detail fragment. But when I return to the list (onBack), the fragment and the list are loaded again, they are re-created.
What I want to achieve is that the fragment and therefore the list are not recreated. That they remain in the same state, so that when I return from the detail I can continue to navigate my list from the point where I left off.
My code:
Fragment
 class ListFragment : Fragment() {

    private lateinit var viewDataBinding: FragmentListBinding
    private lateinit var adapter: ListAdapter

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        viewDataBinding = FragmentListBinding.inflate(inflater, container, false).apply {
            viewmodel = ViewModelProviders.of(this@ListFragment).get(ListViewModel::class.java)
            lifecycleOwner = viewLifecycleOwner
        }
        return viewDataBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setupAdapter()
        setupObservers()
    }

    private fun setupObservers() {
        viewDataBinding.viewmodel?.listLive?.observe(viewLifecycleOwner, Observer {
            adapter.updateList(it)
        })

        viewDataBinding.viewmodel?.toastMessage?.observe(viewLifecycleOwner, Observer {
            activity?.longToast(it)
        })
    }

    private fun setupAdapter() {
        val viewModel = viewDataBinding.viewmodel

        if (viewModel != null) {
            adapter = ListAdapter(viewDataBinding.viewmodel!!)
            val layoutManager = LinearLayoutManager(activity)
            list_rv.layoutManager = layoutManager
            list_rv.adapter = adapter
        }
    }

    override fun onResume() {
        super.onResume()
        viewDataBinding.viewmodel?.fetchList()
    }
}

Fragment layout
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>

    <import type="android.view.View" />

    <variable
        name="viewmodel"
        type="app.example.list.ListViewModel" />
</data>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
         android:id="@+id/list_rv"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:visibility="@{safeUnbox(viewmodel.dataLoading) ? View.GONE : View.VISIBLE}" />

</RelativeLayout>

View model
class ListViewModel : BaseViewModel() {
val listLive = MutableLiveData<List<Item>>()

fun fetchList() {
    dataLoading.value = true
    ItemRepository.getInstance().getList() { isSuccess, response ->
        dataLoading.value = false

        if (isSuccess) {
            listLive.value = response?.items
            empty.value = false
        } else {
            empty.value = true
        }
    }
}
}

I'm navigating between the list and the item with navigation
itemView.findNavController().navigate(R.id.action_listFragment_to_detailFragment)

A: You should never be reloading your data in a Lifecycle method such as onResume() - that's why your data goes back to loading every time you go back to the fragment.
Instead, you should call fetchList() just once in your ViewModel's init block - this ensures that it runs only once:
class ListViewModel : BaseViewModel() {
     val listLive = MutableLiveData<List<Item>>()

      init {
          fetchList()
      }

      fun fetchList() {
           dataLoading.value = true
           ItemRepository.getInstance().getList() { isSuccess, response ->
                dataLoading.value = false

                if (isSuccess) {
                     listLive.value = response?.items
                     empty.value = false
                } else {
                     empty.value = true
                }
           }
      }
 }

It isn't clear how your getList() method works. How it is written now is generally correct for a single callback. If your getList() is actually returning a stream of values that continue to deliver callbacks as the underlying data changes, then you must make sure you unregister that callback in onCleared() (the callback when the ViewModel is destroyed).

A: You are getting recycle list recreated every time because of the following code -
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    setupAdapter()     //you are setting adapter every time view is getting created
    setupObservers()
}

As you are using navigation architecture to navigate, every time you navigate to a destination, previous fragment will be stop() and upon back it will be re-created. Because as of now navigation component doesn't have the backstact issue
But the whole point of using the ViewModel is to not save fragment state and let the ViewModel keep the data. You are using the view model but, you must not set the adapter on recycle view each time.
Simply notify the recycle view list when you get the list from view model.


text:
Q: Passport Slack OAuth Scope Throwing Error with Identity I'm trying to request a slack oauth token using the passport-slack module with the following code.
passport.use(new SlackStrategy({
    clientID: xxxxxxx,
    clientSecret: xxxxxxx,
    scope: [
        'chat:write:user',
        'channels:read'
    ],
    callbackURL: xxxxxxx+"/slack/callback"
  }, (accessToken, refreshToken, profile, done) => {
    done(null, profile);
  }
));

router.use(passport.initialize());
router.use(require('body-parser').urlencoded({ extended: true }));

router.get('/authorize', function(req, res, next) {
  passport.authenticate('Slack', function(err, user, info) {
    next();
  })(req, res, next);
});

/* OAuth Callback flow */
router.get('/callback', passport.authorize('Slack', { failureRedirect: '/authorize' }), function(req, res) {

});

However, I am getting the following response "missing_scope","needed":"identity.basic","provided":"identify,channels:read,chat:write:user"}.
But when I add identify.basic as a scope it errors saying I can't request both the identity and other scopes at the same time. Anyone know how to resolve this? I just want to generate an oauth token so my api can post to slack as a user.


text:
Q: CreateDispatch failed when called from dll .vs. exe I have an OCX that has been updated, and a .exe and a .dll that both use it.  My problem is that while the .exe can connect and use the OCX just fine, the .dll is having problems.  Specifically, the CreateDispatch(clsid, &e) call fails with an 80040154 exception (class not registered).  Both the .exe and the .dll are on the same machine, and the connection code is practically identical.  I've looked in the archives for CreateDispatch problems, but none of the answers seem to apply. The only other thing to note is that the .dll is a 32-bit ODBC Driver setup module, called from the ODBC Data Sources (32-bit) utility.
Any ideas?
Thanks in advance.


text:
Q: Is there a "Sleep" command? In a lot of languages, there's a

wait(milliseconds)

or

sleep(milliseconds)

command, that just makes your program not execute any more code until the sleep is up (this doesn't mean it stops the code that's running, it just pauses from running more. Is there a command like this in C#?
Thread.Sleep(time) doesn't work, it pauses all code that is currently executing as well (basically freezes your program)

A: Thread.Sleep(int milliseconds)
is what you're looking for

A: In C#, everything is running on one thread by default. If you want you can create another thread to run a specific piece of code. Then, you can sleep that thread so your app won't freeze.
Check this question out for more information: How do I run a simple bit of code in a new thread?

A: Yeap:
Thread.Sleep(milliseconds)

http://msdn.microsoft.com/es-es/library/system.threading.thread.sleep(v=vs.80).aspx

A: Yeah there is.
Thread.Sleep(milliseconds)

For example, if you use Thread.Sleep(5000) , it will make thread sleep for 5 seconds. Read more @ MSDN

A: Thread.Sleep(milliseconds) should do it for you

A: You'll want to verify the syntax as I'm just wingin' it, but this will go into a non-blocking loop for the designated amount of time...
// Set the wait time
double waitTime = 5.0;

// Get the current time
DateTime start = DateTime.Now;

// Check the wait time
while(DateTime.Now.Subtract(start).TotalSeconds < waitTime)
{
    // Keep the thread from blocking
    Application.DoEvents();
}

That assumes you're using Windows Forms.  If you're using WPF:
//Application.DoEvents();
this.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { }));

Again, you'll want to verify the syntax first...


text:
Q: A problem regarding Linear Transformation It is a given problem of the book LINEAR ALGEBRA by  Hoffman & Kunze (page 96)
Let $V$ be an $n$- dimensional vector space over the field $F$, and let $B=\{\alpha_1,\alpha_2,...,\alpha_n\}$ be an ordered basis for $V$.
(a) $\exists$ a unique linear operator $T$ on $V$ such that $T\alpha_j =\alpha_k,k=j+1,   j=1,...,n-1,  T\alpha_n =0$. What is the matrix $A$ of $T$ in the ordered basis $B$ ?
(b) Prove that $T^n=0$ but $T^m \ne 0,m=n-1$
(c) Let $S$ be any linear operator on $V$ such that $S^n=0$ but $S^m \ne 0 ,m=n-1$  .Prove that  there is an ordered basis $B^*$ for $V$ such that the matrix of $S$ in the ordered basis $B^*$ is the matrix $A$ of part (a).
my try : (a) and (b) is easy to compute. my problem is to prove part (c).
for simplicity I have assumed $n=2$. We know that the matrix with respect to  the standered ordered basis of a given linear map treats as the same linear map.So I name that matrix $B$ and $B= \{\begin {bmatrix}
                                        a&b\\
                                        c&d\\
                                      \end{bmatrix}\}$
Since $S^2=0 , S\ne 0$ the rank of $S$ is one.So I assume $c=\alpha a, d=\alpha b$. Let $X=$[1      0]$\in R^2$ then $B^2X=0$ gives $\alpha= -a/b$.
Thus we get $S(x,y)=xS(1,0)+yS(0,1)=x(a ,\alpha a)+y(b,\alpha b)=(ax+by)(1,-a/b)$. I take $B^*=$$\{\beta_1=(0,1);\beta_2=(b,-a)\}$ then $S\beta_1=\beta_2$ and $S\beta_2=0$. And hence we get the matrix of $S$ with respect to $B^*$ ,which is $\{\begin {bmatrix}
          0&0\\
          1&0\\
          \end{bmatrix}\}=A$.
So we are done, assuming $n=2$ but how to do the general case. It seems to me very difficult in $n$ dimensional case if I generalise my try.Please someone give me a hint to solve part (c).Thanks for reading.

A: Note that $\{0\}\varsubsetneq\ker S\varsubsetneq\ker S^2\varsubsetneq\cdots\varsubsetneq\ker S^{n-1}\varsubsetneq\ker S^n=V$. So, take an element of $\ker S\setminus\{0\}$, then an element of $\ker S^2\setminus\ker S$ and so on.


text:
Q: using HtmlAgilityPack to select innerHtml let say i have follow html document

 hello

 world

  hello world

i want to extract this

 hello

 world

      hello world

what is best way to extract using HtmlAgilityPack with c# or vb.net?
this is my code until done but some struggle .
thanks!
For Each no As HtmlAgilityPack.HtmlNode In docs.DocumentNode.SelectNodes("//div[contains(@class,'wrap_body')]")
    Dim attr As String = no.GetAttributeValue("wrap_body", "")

Next

A: Below is a sample for getting Inner Html
var html =
        @"

 hello

 world

  hello world

        ";

        var htmlDoc = new HtmlDocument();
        htmlDoc.LoadHtml(html);

        var htmlNodes = htmlDoc.DocumentNode.SelectNodes("//body/div");

        foreach (var node in htmlNodes)
        {

            Console.WriteLine(node.InnerHtml);

        }

A: You can use SelectNodes of DocumentNode metod to retrieve specific nodes from html.
class Program
{
    static void Main(string[] args)
    {
        string htmlContent = File.ReadAllText(@"Your path to html file"); ;

        HtmlDocument doc = new HtmlDocument();

        doc.LoadHtml(htmlContent);

        var innerContent = doc.DocumentNode.SelectNodes("/div").FirstOrDefault().InnerHtml;

        Console.WriteLine(innerContent);
    }
}

Output:


text:
Q: How to scan through really huge files on disk? Considering a really huge file(maybe more than 4GB) on disk,I want to scan through this file and calculate the times of a specific binary pattern occurs.
My thought is:

*

*Use memory-mapped file(CreateFileMap
or boost mapped_file) to load the
file to the virtual memory.

*For each 100MB mapped-memory,create one thread to scan and calculate the result.
Is this feasible?Are there any better method to do so?
Update:
Memory-mapped file would be a good choice,for scaning through a 1.6GB file could be handled within 11s.
thanks.

A: Although you can use memory mapping, you don't have to. If you read the file sequentially in small chunks, say 1 MB each, the file will never be present in memory all at once.
If your search code is actually slower than your hard disk, you can still hand chunks off to worker threads if you like.

A: Multithreading is only going to make this go slower unless you want to scan multiple files with each on a different hard drive.  Otherwise you are just going to seek.
I wrote a simple test function using memory mapped files, with a single thread a 1.4 Gb file took about 20 seconds to scan.  With two threads, each taking  half the file (even 1MB chunks to one thread, odd to the other), it took more than 80 seconds.

*

*1 thread:   20015 milliseconds

*2 threads:  83985 milliseconds

That's right, 2 threads was Four times slower than 1 thread!
Here's the code I used, this is the single threaded version, I used a 1 byte scan pattern, so the code to locate matches that straddle map boundaries is untested.
HRESULT ScanForPattern(LPCTSTR pszFilename, LPBYTE pbPattern, UINT cbPattern, LONGLONG * pcFound)
{
   HRESULT hr = S_OK;

   *pcFound = 0;
   if ( ! pbPattern || ! cbPattern)
      return E_INVALIDARG;

   //  Open the file
   //
   HANDLE hf = CreateFile(pszFilename,
                          GENERIC_READ,
                          FILE_SHARE_READ, NULL,
                          OPEN_EXISTING,
                          FILE_FLAG_SEQUENTIAL_SCAN,
                          NULL);

   if (INVALID_HANDLE_VALUE == hf)
      {
      hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
      // catch an open file that exists but is in use
      if (ERROR_SHARING_VIOLATION == GetLastError())
         hr = HRESULT_FROM_WIN32(ERROR_SHARING_VIOLATION);
      return hr;
      }

   // get the file length
   //
   ULARGE_INTEGER  uli;
   uli.LowPart = GetFileSize(hf, &uli.HighPart);
   LONGLONG cbFileSize = uli.QuadPart;
   if (0 == cbFileSize)
      {
      CloseHandle (hf);
      return S_OK;
      }

   const LONGLONG cbStride = 1 * 1024 * 1024; // 1 MB stride.
   LONGLONG cFound  = 0;
   LPBYTE   pbGap = (LPBYTE) malloc(cbPattern * 2);

   //  Create a mapping of the file.
   //
   HANDLE hmap = CreateFileMapping(hf, NULL, PAGE_READONLY, 0, 0, NULL);
   if (NULL != hmap)
      {
      for (LONGLONG ix = 0; ix < cbFileSize; ix += cbStride)
         {
         uli.QuadPart = ix;
         UINT cbMap = (UINT) min(cbFileSize - ix, cbStride);
         LPCBYTE pb = (LPCBYTE) MapViewOfFile(hmap, FILE_MAP_READ, uli.HighPart, uli.LowPart, cbMap);
         if ( ! pb)
            {
            hr = HRESULT_FROM_WIN32(GetLastError());
            break;
            }
         // handle pattern scanning over the gap.
         if (cbPattern > 1 && ix > 0)
            {
            CopyMemory(pbGap + cbPattern - 1, &pb[0], cbPattern - 1);
            for (UINT ii = 1; ii < cbPattern; ++ii)
               {
               if (pb[ii] == pbPattern[0] && 0 == memcmp(&pb[ii], pbPattern, cbPattern))
                  {
                  ++cFound;
                  // advance by cbPattern-1 to avoid detecting overlapping patterns
                  }
               }
            }

         for (UINT ii = 0; ii < cbMap - cbPattern + 1; ++ii)
            {
            if (pb[ii] == pbPattern[0] &&
                ((cbPattern == 1) || 0 == memcmp(&pb[ii], pbPattern, cbPattern)))
               {
               ++cFound;
               // advance by cbPattern-1 to avoid detecting overlapping patterns
               }
            }
         if (cbPattern > 1 && cbMap >= cbPattern)
            {
            // save end of the view in our gap buffer so we can detect map-straddling patterns
            CopyMemory(pbGap, &pb[cbMap - cbPattern + 1], cbPattern - 1);
            }
         UnmapViewOfFile(pb);
         }

      CloseHandle (hmap);
      }
   CloseHandle (hf);

   *pcFound = cFound;
   return hr;
}

A: I would have one thread read the file (possibly as a stream) into an array and have another thread process it. I wouldnt map several at one time because of disk seeks. I would probably have a ManualResetEvent to tell my thread when the next ? bytes are ready to be processed. Assuming your process code is faster then the hdd i would have 2 buffers, one to fill and the other to process and just switch between them each time.

A: Creating 20 threads, each supposing to handle some 100 MB of the file is likely to only worsen performance since The HD will have to read from several unrelated places at the same time.
HD performance is at its peak when it reads sequential data. So assuming your huge file is not fragmented, the best thing to do would probably be to use just one thread and read from start to end in chunks of a few (say 4) MB.
But what do I know. File systems and caches are complex. Do some testing and see what works best.

A: I'd go with only one thread too, not only for HD performance issues, but because you might have trouble managing side effects when splitting your file : what if there's an occurrence of your pattern right where you split your file ?

A: Using a memory mapped file has the additional benefit of avoiding a copy from the filesystem cache memory to the (managed) application memory if you use a read-only view (although you have to use byte* pointers then to access the memory). And instead of creating many threads use one thread to sequentially scan through the file using for example 100MB memory mapped views into the file (don't map the entire file into the process address space at once).

A: I would do it with asynchronous reads into a double buffer. So when one buffer has been read from file, start reading the next buffer while scanning the first buffer. This means you do CPU and IO in parallel. Another advantage is that you will always have data around data boundaries. However I don't know if double buffering is possible with memory mapped files.

A: Tim Bray (and his readers) explored this in depth in his Wide Finder Project and Wide Finder 2. Benchmark results show that multithreaded implementations can outperform a single-threaded solution on a massive Sun multicore server. On usual PC hardware, multithreading won't gain you that much, if at all.


text:
Q: Exim established many connections to strange ips I installed VestaCP and used their mail server for my domain mails. But when I run netstat on my server,it shows some strange connections. There are no problems with my mail server until now, I just worry about these connections.
Does my server meet any security problems?
# netstat -antp

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:25              0.0.0.0:*               LISTEN      5033/exim
tcp        0      0 0.0.0.0:2525            0.0.0.0:*               LISTEN      5033/exim
tcp        0     35 my.server.ip.address:25        87.246.7.228:63258      ESTABLISHED 13152/exim
tcp        0     35 my.server.ip.address:25        212.70.149.88:38064     ESTABLISHED 13518/exim
tcp        0      0 my.server.ip.address:25        212.70.149.88:20194     ESTABLISHED 13519/exim

A: Having connections established to your mail server it's rather normal if it is exposed to the Internet.
That doesn't mean you shouldn't setup fail2ban and verify you aren't running an open relay, but thinking you've been hacked because netstat says you have open connections is pointless. That's just the Internet nowadays...


text:
Q: Can't upgrade Windows Server 2012 Essentials to Windows Server 2012 R2 Essentials So today was RTM of Windows Server 2012 R2 Essentials released.
I immediately tried to do an in-place upgrade of an existing RTM 2012 Essentials to RTM 2012 R2 Essentials, but get:

Windows Server 2012 Essentials cannot be upgraded to Windows Server
  2012 R2 Essentials. You can choose to install a new copy of Windows
  Server 2012 R2 Essentials instead, but this is different from an
  upgrade, and does not keep your files, settings, and programs. You'll
  need to reinstall any programs using the original installation discs
  or files. To save your files before installing Windows, back them up
  to an external location such as a CD, DVD, or external hard drive. To
  install a new copy of Windows Server 2012 R2 Essentials, click the
  Back button in the upper left-hand corner, and select "Custom
  (advanced)".

This seems a bit odd, is this really the case? I can't find anything in the official documentation stating that this upgrade isn't possible.

A: It doesn't appear that an in-place upgrade is available, rather you need to migrate.  Same as in SBS 2011 to 2012 Essentials.
See here: http://social.technet.microsoft.com/Forums/windowsserver/en-US/41695fc1-6e0c-4218-bb7a-0984e54d5ce5/will-i-be-able-to-upgrade-or-migrate-my-current-windows-server-2012-essentials-installation-once-r2

No inplace upgrade.
You will need to migrate from 2012 to 2012 r2 by installing R2 in
  migration mode and copying data/can't copy backups over,
  decommissioning the old box.

and "official" Microsoft Technet article here: Migrate from Previous Versions to Windows Server 2012 R2 Essentials

A: For Windows Server Essentials, upgrade is not supported. Migration would be recommended.
Best Regards,
Eve Wang


text:
Q: Replace Characters for Searching Hope you're having a great Saturday.
I'm creating a project that I need clean URLs for.
Here's what I mean:
People can create a project with a title. The title can contain letters, numbers, dashes (-), commas, colons, semi-colons, and spaces.
So if I create a project like "Foo: Bar", I don't want the URLs to look like localhost:8888/post/foo%3A%20bar, but instead localhost:8888/post/foo-bar.
Here's what I'm asking:
1) Is it possible to remove a string of special characters (defined above) of any length and replace it with a single dash (-)?
2) Is it possible to then have regex or Javascript that replaces the dash with a wildcard so I can search the MongoDB database for that title?
Thanks a million!

A: import re
x="foo:bar"
print re.sub("[^a-zA-Z0-9]+","-",x)

This is in python.There is match in java where the same regex can be used. For b) part be you can again use re.sub to replace "-" to any wildcard of your choice.


text:
Q: Input value is null instead of entered value I would like to use JqueryUI autocomplete but when I try to send a value from search input I have a null instead of entered value. In my blade file I have a form:
<form method="post" action="{{ route('meals.store') }}" class="container-form">
    @csrf
    Nazwa produktu:
    <input name="product-name" type="text" id="product-name" required/>
</form>

In blade I added a script:
$(document).ready(function() {
    $( "#product-name" ).autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "add/search",
                data: {
                    term: request.term
                },
                dataType: "json",
                success: function (data) {
                    var resp = $.map(JSON.parse(data), function (obj) {
                        return {
                            label: obj.name,
                            value: obj.id
                        }
                    });
                    response(resp);
                }
            });
        },
        minLength: 2
    });
});

This script send a term to url 'add/search' and that route is connected with function search:
public function search(Request $request)
    {
        $name = $request->get('product-name');
        Debugbar::info($name);
        $result = DB::table('products')->select(array('id', 'name'))->where('name', 'LIKE', '%' . $name . '%')->limit(25)->get();
        return response()->json($result->toJson());
    }

But I got all results because $name variable is null even when I entered a value.
When I try to use $request->all(); I got an array with key and value "term" => "ban" and I don't know how is that possible when input name is other.

A: This is because you are making a post request and trying to get route parameter.
 change this
$name = $request->get('product-name');

to
$request->'product_name'

or
$request->only('product_name')

and also change product-name to procductName or product_name don't use - use _ or camel case
What you are trying to do is needs to be done like below
http://localhost/meals/store?product-name="abc";

if you do like then your code will work
 $name = $request->get('product-name');
 return $name; // will return abc

Also add validation to your request like below
Controller:
public function search(Request $request)
{
        $this->validate($request, ['product_name' => 'required'])
        $name = $request->get('product-name');
        Debugbar::info($name);
        $result = DB::table('products')->select(array('id', 'name'))->where('name', 'LIKE', '%' . $name . '%')->limit(25)->get();
        return response()->json($result->toJson());
}

Blade file:
<form method="post" action="{{ route('meals.store') }}" class="container-form">
    @csrf
    Nazwa produktu:
    <input name="product-name" type="text" id="product-name" required/>
    @error('email')

               {{ $message }}

    @enderror

</form>

One more thing if you see your jquery script you are passing term as body data having the value of product-name change this:
data: {
         term: request.term
 },

to:
data: {
             product_name: request.term
     },

or alternatively you can change $request->product_name in your controller to $request->term
Hope it helps.
Thanks


text:
Q: Atom for angularJs2 beta + spring boot I work with Atom 1.4.0 with atom-typescript package to write the angularjs2 modules in typescript. At the backend side I have a spring-boot application for the rest api's.
When I change the .ts files atom seems to compile the file and generate the .js. But when I use chrome to see the changes I don't see any change (I switch on Developer console and I saw on the .ts and .js file that the changes were not loaded.
I tryied to restart Atom, the backend server, to clear the cache on chrome, explorer, firefox, to make a build evry time after saving a .ts file but the behaviour don't change. I don't know were I have the mistake.
A colegue has the same setup, same project (I copied from him) same version of atom, but by him the changes are visibible istantiantly.

Any Idea?

tsconfig.json
{
   "compilerOptions": {
   "target": "ES5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
},
"compileOnSave": true,
"exclude": [
    "node_modules"
]
}

package.json
{
 "name": "resend",
 "version": "1.0.0",
  "scripts": {
  "tsc": "tsc",
  "tsc:w": "tsc -w"
  },
  "dependencies": {
   "angular2": "2.0.0-beta.0",
   "systemjs": "0.19.6",
   "es6-promise": "^3.0.2",
   "es6-shim": "^0.33.3",
   "reflect-metadata": "0.1.2",
   "rxjs": "5.0.0-beta.0",
   "zone.js": "0.5.10",
   "bootstrap": "^3.3.6"
   },
   "devDependencies": {
   "concurrently": "^1.0.0",
   "typescript": "^1.7.3"
 }
}

A: So the problem was in the eclipse workspace. The folder were my frontend files are, were not updated, and eclipse blocked the refresh. After I found the solution with manual refresh on the folder (in Eclipse under the Project manager), I found also the solution to tell eclipse to listen to this folder:
Under Windows->Preferences->General->Workspace
I enabled the two flags:

*

*Refresh using native hooks or polling

*Refresh on access


text:
Q: Docker unable to start, new network adapter created on every restart I am using Docker 1.8.2c, VirtualBox 5.0.4 on Windows 8.1.
I have been successfully been using this configuration for a long period, but then I had to install OpenShift to check its feasibility. This never worked out as there were networking issues with new network adapters being created all the time, and not being able to connect to the internet.
I have uninstalled everything, and reinstalled Docker 1.8.2c and somehow the problem is still persistent and Docker will not even start now.
I have looked around and not found a way to investigate or resolve the problem.
Thanks for your advice.
Cheers
Kris

A: Try to do an upgrade like Dan Lowe said and if you have error messages can you post them here ?


text:
Q: Ubuntu 18.04 crashes or takes forever to boot When booting Ubuntu 18.04, it shows this error:
[FAILED] Failed to activate swap /swapfile.
See 'systemct1 status swapfile.swap' for details

and then it takes gets stuck on the Ubuntu loading screen.
The output of running sudo parted -l in the live installer:
Model: ATA ST1000LM035-1RK1 (scsi)
Disk /dev/sda: 1000GB
Sector size (logical/physical): 512B/4096B
Partition Table: msdos
Disk Flags:

Number  Start   End     Size    Type      File system  Flags
 1      1049kB  525MB   524MB   primary   ntfs         boot
 2      525MB   209GB   209GB   primary   ntfs
 3      209GB   210GB   528MB   primary   ntfs         diag
 4      210GB   1000GB  790GB   extended               lba
 5      210GB   968GB   758GB   logical   ntfs
 6      968GB   1000GB  32.2GB  logical   ext4

Warning: Unable to open /dev/sr0 read-write (Read-only file system).
/dev/sr0 has been opened read-only.
Model: PLDS DVD-RW DA8AESH (scsi)
Disk /dev/sr0: 1922MB
Sector size (logical/physical): 2048B/2048B
Partition Table: mac
Disk Flags:

Number  Start   End     Size    File system  Name   Flags
 1      2048B   6143B   4096B                Apple
 2      1880MB  1883MB  2392kB               EFI


text:
Q: Verifying NSEC3 records I'm fiddling with DNSSEC, and I'd like to try to verify NSEC3 records generated by dnssec-signzone from bind9-utils (which I presume are valid). This is my zone file:
$ORIGIN dnssectest.mvolfik.tk.
$TTL 120
@   SOA dnssectestns.mvolfik.tk. email.example.com. 15 259200 3600 300000 3600
    A   192.168.0.101
s3c A   192.168.0.101

$INCLUDE zsk.key
$INCLUDE ksk.key

ZSK and KSK are generated with dnssec-keygen -a ECDSAP256SHA256 dnssectest.mvolfik.tk. (add -f KSK respectively)
I then signed it using the command dnssec-signzone -3 deadbeef -H 5 -o dnssectest.mvolfik.tk -k ksk.key zonefile zsk.key (use NSEC3 with deadbeef hex salt, 5 iterations)
I got the following NSEC3 records in the zonefile.signed: (omitted RRSIG and DNSKEY as irrelevant; A and SOA didn't change)
            0   NSEC3PARAM 1 0 5 DEADBEEF
F66KKS17FM851AVA4EARFHS55I3TOO85.dnssectest.mvolfik.tk. 3600 IN NSEC3 1 0 5 DEADBEEF (
                    D60TA5J5RS4JD5AQK25B1BCUAHGP4DHC
                    A SOA RRSIG DNSKEY NSEC3PARAM )
D60TA5J5RS4JD5AQK25B1BCUAHGP4DHC.dnssectest.mvolfik.tk. 3600 IN NSEC3 1 0 5 DEADBEEF (
                    F66KKS17FM851AVA4EARFHS55I3TOO85
                    A RRSIG )

Now that I know that the only domains in this zone are s3c.dnssectest.mvolfik.tk. and dnssectest.mvolfik.tk., I assume that the following Python script would get me the same hashes as in the signe zone file above: (from pseudocode in RFC 5155)
import hashlib
def ih(salt, x, k):
    if k == 0:
        return hashlib.sha1(x + salt).digest()
    return hashlib.sha1(ih(salt, x, k-1) + salt).digest()

print(ih(bytes.fromhex("deadbeef"), b"s3c.dnssectest.mvolfik.tk.", 5).hex())

print(ih(bytes.fromhex("deadbeef"), b"dnssectest.mvolfik.tk.", 5).hex())

However, I instead got b58374998347ba833ab33f15332829a589a80d82 and 545e01397a776ee73aa0372aea015408cc384574. What am I doing wrong?

A: So I looked into dnspython source code, and found the nsec3_hash function. Turns out that the name must be in wire format (means removing dots and instead prefixing labels a length byte - \x03s3c\x10dnssectest\x07mvolfik\x02tk\x00 etc, null byte at the end). And the result is encoded with base32 (0-9A-V), not hex. Probably easier just to use the dnspython library, but here's the full (a bit naive) code:
import hashlib, base64

b32_trans = str.maketrans(
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", "0123456789ABCDEFGHIJKLMNOPQRSTUV"
)

def ih(salt, x, k):
    if k == 0:
        return hashlib.sha1(x + salt).digest()
    return hashlib.sha1(ih(salt, x, k - 1) + salt).digest()

def nsec3(salt, name, k):
    if not name.endswith("."):
        name += "."
    labels = name.split(".")
    name_wire = b"".join(len(l).to_bytes(1, "big") + l.lower().encode() for l in labels)
    digest = ih(bytes.fromhex(salt), name_wire, k)
    return base64.b32encode(digest).decode().translate(b32_trans)

print(nsec3("deadbeef", "dnssectest.mvolfik.tk.", 5))
print(nsec3("deadbeef", "s3c.dnssectest.mvolfik.tk.", 5))

This gets the correct hashes seen in the NSEC3 records


text:
Q: Convert ascending merge sort to descending (C ) I have a merge sort program that gives output by sorting the array elements in ascending order, but I want it to give output in descending order
void merge(int A[] , int mid, int low, int high){
    int B[high+1];
    int i = low, j = mid+1, k = low;
    while (i <= mid && j <= high)
    {
        if (A[i] < A[j])
        {
            B[k] = A[i];
            k++;
            i++;
        }
        else
        {
            B[k] = A[j];
            k++;
            j++;
        }
    }

    while (i<=mid)
    {
        B[k] = A[i];
        k++;
        i++;
    }
    while (j<=high)
    {
        B[k] = A[j];
        k++;
        j++;
    }

    // finally moving all ele of B to A
    for (int i = low; i <= high; i++)
    {
        A[i] = B[i];
    }
}

void mergesort(int A[], int low, int high){
    int mid;
    if (low<high)
    {
        mid = (low+high)/2 ;
        mergesort(A, low, mid);
        mergesort(A, mid+1, high);
        merge(A, mid, low, high);
    }
}

My approach (didn't work):
Since array B[] is sorted in ascending order (so we copy it to array A[] at the end), So while copying elements of B to A, I tried to copy from last index of B[] to first index of A[] & so on...
int h = high;
    for (int i = low; i <= high; i++)
    {
        A[i] = B[h];
        h--;
    }

But I don't know why it didn't work.

A: If your code is working fine you have only to change the comparision on line #6.
from:
if (A[i] < A[j])

to:
if (A[i] > A[j])


text:
Q: How to display json data with ReactJs as table I would like to display my json data with reactJs in the table, but I can't.
[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
  },

...

]

The source code in full: http://jsonplaceholder.typicode.com/posts

A: are you aiming for a component to display data , you can do something like this

var cols = [
    { key: 'id', label: 'Id' },
    { key: 'userId', label: 'User' },
    { key: 'title', label: 'Title' },
    { key: 'body', label: 'Body' }
];

var data = [
  {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }
];

var Table = React.createClass({

render: function() {
    var headerComponents = this.generateHeaders(),
        rowComponents = this.generateRows();

    return (

 {headerComponents}

 {rowComponents}

    );
},

generateHeaders: function() {
    var cols = this.props.cols;  // [{key, label}]

    // generate our header (th) cell components
    return cols.map(function(colData) {
        return  {colData.label} 	;
    });
},

generateRows: function() {
    var cols = this.props.cols,  // [{key, label}]
        data = this.props.data;

    return data.map(function(item) {
        // handle the column data within each row
        var cells = cols.map(function(colData) {

            // colData.key might be "firstName"
            return  {item[colData.key]} 	;
        });
        return
 {cells}
;
    });
}
});

React.render(
,  document.getElementById('example'));

A: You can use map to iterate over your JSON data

class App extends React.Component {
  constructor(){
    super()
      this.state = {
        data: []
      }

  }
  componentDidMount() {
    $.ajax({
       url: "http://jsonplaceholder.typicode.com/posts",
       type: "GET",
       dataType: 'json',
       ContentType: 'application/json',
       success: function(data) {

         this.setState({data: data});
       }.bind(this),
       error: function(jqXHR) {
         console.log(jqXHR);
       }.bind(this)
    })
  }
  render() {

    return (

{this.state.data.map(function(item, key) {

               return (

                      {item.userId}
                      {item.id}
                      {item.title}
                      {item.body}

                )

             })}

    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'))


text:
Q: angular directive with socket.io updates I would like to ask for your help.
I have:
main.js
angular.module('app',['btford.socket-io'])
    .factory('socket', function (socketFactory) {
        var myIoSocket = io.connect('http://localhost');

        var mySocket = socketFactory({
            ioSocket: myIoSocket
        });

        return mySocket;
    })
    .directive('myDir',function(){

        return {
            restrict: 'E',
            scope:{
                marker:'@'
            },
            template: '

',
            controller:function($scope, socket){

                socket.emit('joinRoom', $scope.marker );

                socket.on('updateEvent',function(data){
                    $scope.ItemList= data;
                });

            }
        };
    })

    .controller('main',function($scope, $http){

        $http.get('localhost/api/getList')
            .success(function(data){
                $scope.markerlist = data;

            });
    });

index.html

                <my-dir marker='{{marker}}'></my-dir>

how the workflow need to work :

*

*open page

*http service get data from server - list of markers
['marker1','marker1','marker1']

*angular use that data to compile directives

*each directive join rooms at socket.io server and listen for
ItemList:

"marker1" join room "marker1"
"marker2" join room "marker2"
...

*when some changes io server send ItemList to rooms

*then io emit data to room "marker1", directive "marker1" receive ItemList only from room "marker1",
then io emit data to room "marker2", directive "marker2" receive ItemList only from room "marker2" and go on

but at step 6:
then io emit data to rooms, directive "marker1","marker2","marker3" receive same ItemList, all together,
and data at ItemList rewrites all the time
any suggestions ? %)
Thanks!

A: solved by
var myIoSocket = io.connect('http://localhost', {'force new connection': true});

docs:
https://github.com/Automattic/socket.io/wiki/configuring-socket.io


text:
Q: jquery Syntax error, unrecognized expression when class name is encrypted and contain special character var className  = "order_enc_YUluWTo6ODA4OTczNjQ3MjAzOTc0OA%3D%3D";
$('input:checkbox.' + className).each(function() {
            (this.checked ? arr.push($(this).val()) : "");
        });

having encrypted class name but when trying to run loop getting error
Uncaught Error: Syntax error, unrecognized expression: input:checkbox.order_enc_YUluWTo6ODA4OTczNjQ3MjAzOTc0OA%3D%3D
tried single double quots but with no success.

A: Try this way
<input type="checkbox" class="order_enc_YUluWTo6ODA4OTczNjQ3MjAzOTc0OA%3D%3D" value="true">

var className  = "order_enc_YUluWTo6ODA4OTczNjQ3MjAzOTc0OA%3D%3D";
$('input:checkbox[class="'+className+'"]').each(function() {
    (this.checked ? arr.push($(this).val()) : "");
});

A:     // Connect in HTML file the src for the CryptoJs Lib
 /* <script type="text/javascript"
 src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js">
 </script> */
 let className  = "order_enc_YUluWTo6ODA4OTczNjQ3MjAzOTc0OA%3D%3D";
 let decrypt = CryptoJS.AES.decrypt(className,'Secure className');
 let decryptToString = decrypt.toString(CryptoJS.enc.Utf8);
 $('input' + decryptToString).each(function() {
        ($(this).checked ? arr.push($(this).val()) : "");
        console.log($(this).val())
    });


text:
Q: hpricot using java? I've just noticed that a lot of hpricot code is written in java...
alt text http://img697.imageshack.us/img697/7447/picture2yw.png
I heard that JRuby performed a lot better than native ruby when processing regular expression. Is maybe the java classes just activated if JRuby or Java is installed and the ruby used if these are not found?
It's something puzzling indeed.
Thanks

A: Ruby gems can be written in pure Ruby, or have native extensions. In that case, they may have a C extension and/or a java extension. When installing on Ruby MRI and Rubinius, the C extension (and only the C extension) will be used. When installing on JRuby, the Java extension (and only that one) will be used.
hpricot has both, to be compatible with all of these major Ruby implementations.


text:
Q: App Inventor's SEND intent not reaching chosen activities i'm using the Activity Starter on App Inventor 2 to send a string to a thermal printer for billing through a third party package. with this code:
Blocks 1

Blocks 2

I've already tried to reach other packages but it seems like my app has restricted privileges and its intents get discarded.... (not sure about this)
I have already tried with other solutions like printershare and cloud printing but none of them works with my actual printer except for this service, which I am unable to call (described at this site) http://qsrtechnologies.com/aboutposdriver.html
is there a way to send a broadcast intent through App Inventor so that a third party app can receive it?
thanks for your help

A: The Extras block of the Activity Starter expects a list of lists, see also this example How to add a contact to the contact list and don't forget to call the ActivityStarter.StartActivity method.
You might want to learn more about lists and lists of lists...

*

*How to work with Lists by Saj

*How to work with Lists and Lists of lists (pdf) by appinventor.org
Also use Do it to debug your blocks, in your case the global variable scontrino, see also tip 4 here  Top 5 Tips: How to learn App Inventor
Edit: After reading the documentation on that link, I would try this

A: I have finally worked it out in a different way... since App Inventor's activity starter seemed a bit limited, i set the app to write to a .txt file and had an external java app to detect when that file was edited to take its content and send it via an intent to the .printservice.
Now it works flawless.


text:
Q: Escaping HTML special character with JSP or JQuery My JSP file contains a table with the following row:

I want it to be empty at first, as above. Later, after the page is loaded and some logic is processed, I want to fill it asynchronously with a content using JQuery .html method:
$("#${doc.id}").html("${doc.description}");

For regular user inputs everything works fine, but error occurs, when a user enters special character: "
How can I prevent application from reading that character as special, and have the application running correctly?
I have tried to use JSP escape functions like this:
$("#${doc.id}").html("${fn:escapeXml(doc.description)}");

And this:
$("#${doc.id}").html("<c:out value="${doc.description}"/>");

And neither first nor second worked. Why?

A: Here is one way  - seeing you already have the data on the page
<c:out value="${doc.description}"/>

where
.hide is {display:none}
and then
$("#${doc.id}").show();


text:
Q: Error in communiction between salt-minion and salt-master I have installed a minion and a master on 2 ec2 instances and started configuring them using the file doc provided in saltstack (below link)
https://docs.saltstack.com/en/latest/ref/configuration/index.html
then i came up with an error like
enter image description here


text:
Q: add multiple csv files to the graph with papaparse So, I've tried parsing my csv file which I've got from an input like this:
  const jsonData = Papa.parse(documentvalue);
  this.data1 = this.prepareData(jsonData.data);

And in my function, i try then to update my graph:
      setTimeout(() => {
        chart.hideLoading();
    self.chartOptions.series = [
      self.chartOptions.series[0],
      {
        data: self.data1
      }
    ];

    self.updateFromInput = true;
  }, 2000);

But my function does not update the graph with the new data, it replaces the data. How can I update the graph instead of the new data replacing it?
I am trying to use addSeries but i am really struggling how to use it:
    self.chartOptions.series = [
    self.chartOptions.series[0],
    {
      data: self.data1
    }
  ];
  self.chart.addSeries({
    data: self.data2
  })
  self.updateFromInput = true;
}, 2000);

What is the correct way to add a series from a new file to the graph instead of replacing it?
here is a snippet explaining my solution: https://codesandbox.io/s/angular-ni0c3
Like I said, i am struggling to code so that when i choose the file, it adds to the graph and not replaces the old one. Does anyone have any ideas or solutions?


text:
Q: I cannot figure out this Access Violation error. Can someone help me out here? I cannot find where this problem is coming from and it is driving me insane! My main and a pastebin link are below. I keep getting this error:
First-chance exception at 0x0FFE108E (msvcr110d.dll) in MasterMindFSM.exe: 0xC0000005: Access violation reading location 0x2CF0D131.
Unhandled exception at 0x0FFE108E (msvcr110d.dll) in MasterMindFSM.exe: 0xC0000005: Access violation reading location 0x2CF0D131.
Here is my main:
#pragma once

#include <iostream>
#include "Answer.hpp"

using namespace Games::MasterMind;

int main() {
   Answer Line;

   std::cout << Line.getAnswer(0) << std::endl;
   std::cout << Line.getAnswer(1) << std::endl;
   std::cout << Line.getAnswer(2) << std::endl;
   std::cout << Line.getAnswer(3) << std::endl;

   system("pause");

   return 0;
}

Here is the header file that accompanies main:
(Sorry, but it lost it's formatting)
Answer.hpp

A: Q: What is "Line"?
Q: Does it's constructor allocate an Answer(0), Answer(1), Answer(2), ...?
Failure to allocate an entity before you use it can easily cause a segmentation violation ;)
======================================
I just looked at your (cleverly hidden ;)) "Answer.hpp".
PROBLEM:
1) "getAnswer()" looks perfectly OK (I thought that's where you were having problems)
2) The actual problem is in "setAnswer()" - you're running off the end of your array!


text:
Q: TASM: Modulo of negative number When I do, for example, -1 % 3, I expect the result to be 2.
When I execute the following TASM instructions I get an unexpected result:
mov ax, -1
xor bh, bh
mov bl,  3
idiv bl ; ah = FF (I expected 02), al = 00

A: This web page states that:

the sign of the remainder is always the same as the sign of the
  dividend.

Wikipedia has some information regarding pitfalls with a signed remainder.
A possible workaround could be to use div instead of idiv, and/or keeping track of signs manually.


text:
Q: How can I use Regex to pull just the CN from a Distinguished Name with PowerShell I have a bunch of strings that are DN's of groups from AD. I need to pull out the Common Name.
An example string is "CN=Group Name I Want,OU=Group Container,DC=corp,DC=test,DC=local"
What I am looking for is some PowerShell Code that will pull "Group Name I Want" out of that string and discard the rest.
I can rip of the CN with this
$s = "CN=Group Name I Want,OU=Group Container,DC=corp,DC=test,DC=local"
$s = $s.Remove(0,3)

But after that, I don't have a good way to rip off everthing starting at ",OU"
I am sure there is some regex that will do this but I need some help figuring it out.

A: An even shorter variation on jon Z's answer:
$s = "CN=Group Name I Want,OU=Group Container,DC=corp,DC=test,DC=local"
$s = $s -replace '^CN=|,.*$'

The ^ and $ are the string beginning and end anchors. The | is an "or".
The matches are the CN= at the beginning of the line or a string that starts with a comma and goes to the end of the line (i.e. everything after the CN). The replace is replacing with nothing, so you're discarding all the matches and leaving just the CN itself.
That obviously does not work if you have a comma in your CN (ugh).
Assuming such a comma is followed by a space, this will work and be fine for the previous examples (\S - non whitespace char):
$s = $s -replace '^CN=|,\S.*$'

I tested to see if jon Z's or this variation was faster to execute. With 1,470,000 DNs, the first took 36.87s to execute and the one here took 34.75. Not really a lot in it.
That was reading the DNs out of a file. Bizarrely, "slurping" the file into an array and executing over that took both regexes a minute longer. The PC was not memory-bound - the file was only 100MB. Can't be bothered getting to the bottom of that one right now!

A: $s = "CN=Group Name I Want,OU=Group Container,DC=corp,DC=test,DC=local"
$s -replace "(CN=)(.*?),.*",'$2'

A: $s = "CN=Group Name I Want,OU=Group Container,DC=corp,DC=test,DC=local"
$s1 = ($s -split ",*..=")[1]
$s1

A: $s = "CN=Hall\, Jeremy,OU=Group Container,DC=corp,DC=test,DC=local"
$s1 = ($s -split ",*..=")[1]
$s1

This works for me - however, I have a \, left in name output.  (I'm pulling the manager property from the get-aduser function and it prints the distinguishedName.  Hall\, Jeremy is one example of what I'm left with.
Anyone want to take a stab?

A: Using the various answers in this thread, I came up with the following:
$s = ($s -split ",*..=")[1]
$s = $s.Remove($s.IndexOf("\"),1)
$s

A: $DN = Get-ADUser Username -Properties * | Select DistinguishedName | ForEach-Object {($_.DistinguishedName) -replace('\\','')}
$OUTemp = $DN -creplace "^[^,]*,",""
$OU = $OUTemp -creplace "^[^,]*,",""
$OU

This worked for me after lots of searching. I am not proud of the redundancy in lines 2 and 3 but I don't know how to make it work on a single line.
The "-replace" at the end of the first line took care of DistinguishedNames that were formatted as CN=LastName\, FirstName when the \ escape character was present. It doesn't negatviely affect at name without out it.
The results of my $OU is OU=ChildOU2,OU=ChildOU1,OU=ParentOU,DC=DOMAIN,DC=local


text:
Q: How do I display CSV data in a html file without hosting on a server I know there are other answers to this problem and I have tried them all. Is it possible to only use html to show csv data. So far the only solutions I can find are not working
My code is:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

 The message you want to send is <big>{{ message }}</big>

You will send the message to these people

    #I want to show the csv file here

    <button> Send message to everyone in the list</button>

A: Your title asks about no server, and the question asks about html only. So, to answer both:

*

*With HTML only you cannot get anything from anywhere. You need to add it manually.

*Without a connection to a server, you would have to update the code manually every time the CSV file changes. If the CSV is hosted somewhere else, you can fetch using JavaScript. If the CSV is yours, you need to host it somewhere i.e. a server, to be able to access it.


text:
Q: Calculated Column for Shift Start in PowerPivot I am importing a report into Power Pivot.  The report has a Production Date (A1) and a Production Time (A2) column.  Shift change over is at 6:00 AM and 6:00 PM.  What formula in a calculated column can I use to get the shift start date?
*Power Pivot will not allow me to change the column to text.

A: =IF(B2<.25, A2-.25, IF(B2>=.75, A2+.75, A2+.25)
How it works
Time, in Excel, is represented as a fraction of a day.  The two columns are A and B are essentially a whole number in column A and a fractional number between 0 and 1 in column B.
It turns out that 6pm is exactly 75% of the way through the day.  Since time is calculated as a fraction of we can add 75% of a day or subtract 25% from the previous day.

If the time is less than 25% of the day or 6am, then the work day starts at 6pm the previous day.  IF(B2<.25, A2-.25)
If the time is greater than 75% of the day or 6pm, then the work day also starts at 6pm of the current day.  If (B2>.75, A2+.75)
If the time does not fall before 6am or after 6pm then the workday starts at 6am.


text:
Q: TypeError: cleanUrl is not a function while creating a React Project Hey everybody I am getting this error after hosting a website on firebase or I am not sure about it.

It's the replace-info.js screenshot.
I am not able to  find the solution on stackoverflow or on other website.

A: This error had appeared on my side after npm update npm@lastest
What I did to fix it:

*

*Go to AppData\Roaming\npm\node_modules\npm\node_modules\npm-registry-fetch\lib\index.js.

*Add module.exports.cleanUrl = require('./clean-url.js') at the end of the file.

P.S. I just copied it from there https://github.com/npm/npm-registry-fetch/blob/main/lib/index.js