text:
Q: Jquery .ajax not posting data correctly in asp.net mvc site -- formcollection empty I'm using jquery to submit my form (with id "#myForm" here) as follows:
$(document).ready(function() {
        $("#my_form").submit(function(event) {
            $.ajax(
          {
              type: "POST",
              url: $("#my_form").attr("action"),
              contentType: "application/json; charset=utf-8",
              data: ("#my_form").serialize(),
              success: function(result) {
                  alert('hi');
              },
              error: function(req, status, error) {
                  alert("Sorry! We could not process the form at this time.");
              }
          }
         );
         event.preventDefault();
        });//end submit for my_form
    });//end document ready

If I view the data being posted, I see the following
POST /PageContents/Edit HTTP/1.1
x-requested-with: XMLHttpRequest
Accept-Language: en-us
Referer: [EDITED OUT BY ME]
Accept: /
Content-Type: application/json; charset=utf-8
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR   2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR   3.5.30729)
Host: www.somesite.com:3852
Content-Length: 142
Connection: Keep-Alive
Pragma: no-cache
id=1&small_title=Welcome+to!!!&big_title=Chicago!!!&body=here+is+some+stuff+for+the+body.!!!&subheading=The+place+for+pizza!!
But this does not get mapped to the correct action because the Request.Forms collection is empty.
If I submit this form without javascript and just use normal HTML, the data posted looks like this:
POST /PageContents/Edit HTTP/1.1
Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, /
Referer: [EDITED OUT BY ME]
Accept-Language: en-us
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: www.somesite.com:3852
Content-Length: 164
Connection: Keep-Alive
Pragma: no-cache
small_title=Welcome+to%21%21%21&big_title=Chicago%21%21%21&subheading=The+place+for+pizza%21%21&body=here+is+some+stuff+for+the+body.%21%21%21&id=1
You can see, the data being posted properly, so my routing all works and the correct action is called.
All of the fields in my form do indeed have a name attribute.
Thanks, and apologies for the lengthy post.

A: I think the problem is the contentType you are passing.  You have:
contentType: "application/json; charset=utf-8",

but the data you are passing is not json.  Your best bet is to remove that line.


text:
Q: Windows cannot resolve a CNAME records in bind In linux I use bind - version: 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6_4.5 -
configured in such a way that  2 host names share the same IP address.
The 2 host names are server2 and server3 and they must share the same IP 192.168.1.62 , for this purpose I used a CNAME record as shown below :
$TTL 86400
@       IN      SOA     server1.eda. admi.server1.eda. (
                    2 ; serial
                    28800 ; refresh
                    7200 ; retry
                    604800 ; expire
                    86400 ; ttl
                    )

@                NS      server1.
                 NS      8.8.8.8.

server1                 A       192.168.1.60
server3                 A       192.168.1.62
server2                 CNAME   server3

The domain is eda
What happens is that on Windows the ping to server1 and server3 without the domain works, while the ping to server2 works only with the domain, that is with ping server2.eda as shown below :

The only way to make ping server2 works is to append eda suffix on on the DNS tab in 'Advanced TCP/IP Settings' window.

Below I have reported the image of nslookup

How can i make Windows resolve hostname server2 without adding the .eda suffix? Which it already does with server1 and server3

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to integrate Kotlin Multiplatform Mobile with Amazon amplify services? I am raising this to just get inputs from community if there is any lib which I can use for integrating Amazon's amplify services in KMM? Also I have searched but there is no specific SDK or lib for KMM as of now.
So any input would be helpful on this.

A: The Amplify team is currently investing in Flutter as a multi-platform offering. Support for Flutter had been one of our top feature requests. Amplify Flutter became generally available as of February 15th, 2021. Amplify Flutter currently supports iOS & Android. Customers have additionally expressed interest for Flutter on the Web and on the Desktop.
We don't currently have any plans to support Kotlin Multiplatform (or Multiplatform Mobile.) That said, we are an open source project, and love to see community contributions. You could build something on your own.
To do so, I'd start by defining a Kotlin-language API surface for the library. You can probably use the Kotlin-language facade for the Android library as a starting point. From there, you can add platform bindings to Amplify Android, iOS, and JavaScript.
As a final note: the Amplify products are intended as a front-end framework. Therefore, it's unlikely that we we'll ever prioritize a full multi-platform build. But if we see enough customer demand, we could potentially add more explicit support for Multiplatform Mobile.
Source: I am an engineer on the Amplify team.


text:
Q: Tensor product of free modules over free algebra Suppose $M$ and $N$ are modules over a (commutative, unital) ring $S$. Let $R$ be a subring of $S$ such that $S,M$ and $N$ are all free, finitely generated modules over $R$.
Question: Under what conditions is $M\otimes_S N$ projective over $R$?
Of course, the tensor product over $R$, namely $M\otimes_R N$, is free over $R$ and $M \otimes_S N$ is the quotient of this by the $R$-submodule generated by $(sa)\otimes b-a\otimes (sb)$ where $a,b,s$ run over $R$-bases.
Note, that $S$ is only supposed to be module-free over $R$ not a free algebra over $R$!


text:
Q: why is method of moments estimates asymptotically normal I have noticed that a lot of statistics textbooks contain lengthy discussions and detailed proofs on showing that MLE estimates are asymptotically normal (under regularity conditions).
On the other hand they seem to deal with Method of Moments estimates much more casually by usually just stating it as a an obvious fact that MoM estimates are asymptotically normal.
How can I actually prove this? Is it just a simple consequence of the Delta method? Are there any resources that present the proof?


text:
Q: How to view question edit history when my question is migrated to another Stack Exchange site? How view the question edit history when my question is migrated to another Stack Exchange site?
For example, this question: Make Startpage search results page bold or highlight keywords used

A: Just click on the superuser.com link underneath the question:

It will take you to this page with the original question's revision history:


text:
Q: ViewPager only load the fragments once time I have an android DrawerLayout and it has 2 items, one of them is a fragment with a PagerTabStrip and it load their fragments but when I change the item of the DrawerLayout and I come back to the PagerTabStrip it loads the tabs, but doesn't their fragments.
This is my PagerTabStrip class
public class maintabs extends Fragment {

    FragmentPagerAdapter adapterViewPager;
    PagerTabStrip pagerTabStrip;
    View rootView;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.tabs_main, container, false);
        ViewPager vpPager = (ViewPager) rootView.findViewById(R.id.vpPager);
        pagerTabStrip = (PagerTabStrip) rootView.findViewById(R.id.pager_header);
        pagerTabStrip.setDrawFullUnderline(true);
        adapterViewPager = new SampleFragmentPagerAdapter(getFragmentManager());

        vpPager.setAdapter(adapterViewPager);
        return  rootView;
    }

}

A: I've found a solution.
Just use a FragmentStatePagerAdapter instead FragmentPagerAdapter


text:
Q: teradata case when issue I have the following queries which are supposed to give the same result, but drastically different
1.
         select count(*)
         from qigq_sess_parse_2
         where str_vendor = 'natural search' and str_category is null and destntn_url = 'http://XXXX.com';

*     create table qigq_test1 as
     (
       select case
            when (str_vendor = 'natural search' and str_category is null and destntn_url = 'http://XXXX.com' ) then 1
            else 0
        end as m
        from qigq_sess_parse_2
      ) with data;

     select count(*)  from qigq_test1 where m = 1;

the first block gives a total number of count 132868, while the second one only gives 1.
What are the subtle parts in the query that causes this difference?
Thanks

A: When you create a table in Teradata, you can specify it to be SET or MULTISET.  If you don't specify, it defaults to SET.  A set table cannot contain duplicates.  So at most, your new table will contain two rows, a 0 and a 1, since that's all that can come from your case statement.
EDIT:
After a bit more digging, the defaults aren't quite that simple.  But in any case, I suspect that if you add the MULTISET option to your create statement, you'll see the behavior your expect.

A: My guess would be that your Create Table statement is only pulling in one row of data that fits the parameters for the following Count statement. Try this instead:
CREATE TABLE qigq_test1 (m integer);
INSERT INTO qigq_test1
SELECT
    CASE
        WHEN (str_vendor = 'natural search' and str_category IS NULL AND destntn_url = 'http://XXXX.com' ) THEN 1
        ELSE 0
    END AS m
FROM qigq_sess_parse_2;
SELECT COUNT(*) FROM qigq_test1 WHERE m = 1;

This should pull ALL ROWS of data from qigq_sess_parse_2 into qigq_test1 as either a 0 or 1.


text:
Q: AnimationDrawable not change frames I'm puzzled with the problem "AnimationDrawable not change frames" for some time.I'm confirmed I've added all the frames I need into the AnimationDrawable object,and I've called start(),and the result I called isRunning() is true,but the AnimationDrawable can't change the frame.
I called the start() in MainActivity's handler,not in onCreate() or onResume(),although the the called of start() is in the onResume() state.
Thanks for your thinkings.
----^_^ banlalaotou.
Added code which has the problem.
public class MainActivity extends Activity{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ma = new Ma(this);
        ablt = ma.ablt;
        setContentView(ablt);

        mt = new MinorThread(this);
        new Thread(mt).start();

        while(true){
            if(mt.mHandler==null) continue;
            else{
                Message msg = new Message();
                mt.mHandler.sendMessage(msg);
                break;
            }
        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            ma.control();
            Message msg1 = new Message();
            mt.mHandler.sendMessage(msg1);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode,KeyEvent event){
        switch(keyCode){
        case KeyEvent.KEYCODE_BACK:
            System.exit(0);
        }
        return true;
    }

    private MinorThread mt = null;
    private ImageView v1 = null;
    private Ma ma = null;
    private int x = 0;
    private int y = 0;
    private int width = 0;
    private int height = 0;
    private AbsoluteLayout ablt = null;
}

    class MinorThread implements Runnable{

   @Override
    public void run() {

       Looper.prepare();
       mHandler = new Handler(){
           @Override
           public void handleMessage(Message msg){
               Message msg2 = new Message();
               mainActivity.handler.sendMessage(msg2);
               try {
                   Thread.sleep(3000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
       };
       Looper.loop();
   }

   public MinorThread(MainActivity mainAcitivy){
       this.mainActivity = mainAcitivy;
   }

   private MainActivity mainActivity = null;
   public Handler mHandler = null;
}

    class Ma{

public Ma(MainActivity context){

        ablt = new AbsoluteLayout(context);
        TestView v = new TestView(context);
        AbsoluteLayout.LayoutParams lp = new LayoutParams(480,320,0,0);
        ablt.addView(v, lp);
        Drawable d = null;

        ad = new AnimationDrawable();
        d = context.getResources().getDrawable(R.drawable.f1);
        ad.addFrame(d, 100); d = context.getResources().getDrawable(R.drawable.f2);
        ad.addFrame(d, 100); d = context.getResources().getDrawable(R.drawable.f3);
        ad.addFrame(d, 100); d = context.getResources().getDrawable(R.drawable.f4);
        ad.addFrame(d, 100); d = context.getResources().getDrawable(R.drawable.f5);
        ad.addFrame(d, 100);

        v1 = new ImageView(context);
        v1.setImageDrawable(ad);

        String tag = "test";
        v1.setTag(tag);

        ablt.addView(v1, new LayoutParams(100, 40, 20, 20));
    }

    public void control(){

        v1 = (ImageView) ablt.findViewWithTag("test");
        if(x<480&&y<320){
            x+=10;
            y+=5;
            v1.layout(x, y, x+100, y+40);
            AnimationDrawable ad = (AnimationDrawable)v1.getDrawable();
            ad.start();
        }
    }

    public AbsoluteLayout ablt = null;
    private AnimationDrawable ad = null;
    private ImageView v1 = null;
    private int x = 0;
    private int y = 0;
    private int width = 0;
    private int height = 0;
}

    class TestView extends View{

    public TestView(Context context) {
        super(context);
    }

    @Override
    public void onDraw(Canvas canvas){
        paint.setColor(Color.WHITE);
        canvas.drawRect(0,0,480,320, paint);
    }

    private Paint paint = new Paint();
}

I'sorry for not uploaded the frames,because my reputation is less than 10.
If you execute the code,you need to find some pictures to let the animation run.
thanks.
=============================
Now,I know how to let the result show,but I can't know the resaon.
The solution of the problem is that add a ImageView object into the layout object before show the all ImageView,and, "add a ImageView..." and "show the all ImageView" can't been processed in an function.The right method is like that "if(..){add a ImageView}else{show the all ImageView}".
Although,this method can resolve the problem I'd puzzeled,but why Android can't show the all ImageView's animations at first time?

A: Try to use start() in onWindowFocusChange(boolean focus) when focus is true.


text:
Q: System.Action<> defined multiple times when using Mono I've been working on a winforms C# project in Visual Studio 2010 and have just started compiling it with Mono 2.10.8. Importing the project into Monodevelop 3.0.3.5 works great, and it compiles and runs without any trouble at all as long as the .NET runtime is used.
However, when I try to compile it with the Mono runtime, everything compiles except (two) references to System.Action and System.Func - I get error CS0433 that it is defined multiple times. I have references to System.dll, System.Drawing.dll, and System.Windows.Forms.dll which I'm using from the version 4.0 of the Mono libraries. I gather I'm getting a conflict between declarations in System.core - and somewhere else. Has anybody else had this problem? My entire project compiles and runs apart from perfectly apart from this!
SOLVED
It seems I was doing something rather dumb (though I'm going to blame the Monodevelop UI!) and that was causing the conflict. The projects were still set up to target the .NET framework 4 client profile. I didn't realise you could change them, as there no option to do so on the options for the solution, but there is on each individual project. I spent ages rooting through the included libraries and figured there was a conflict between v4.0 mscorlib.dll and v2.0 System.core.dll. When I replaced the v2.0 mscorelib.dll with the v4 it compiled fine.
I then discovered that simply changing the targetting to Mono / .NET 4 solves the problem. Oh well...

A: First be sure that you have cleared out the bin /obj folder.
What do you use to compile mono (xbuild, monodevelop or a makefile?)?
Which compiler do you use dmcs?
These references (Func<> and Action<>) are a part of mscorlib. Mscorlib is added during link time.
Are you on an independant environment (vurtual machine) or mono and .NET are on the same PC?


text:
Q: re-bind href tag on click I am new to Ember and I work on big legacy project. The issue is that URI fooUri in the following template is bound only once and fooUri stays the same:

Controller code:
App.barController = Ember.ObjectController.extend({
    . . .
    fooUri: function() {
        var fooOptions = $.extend({}, this.model.foo.options);
        . . .
        var querystring = encodeURIComponent($.param(fooOptions));
        var uri = '#' + router.generate( ..., querystring, ...);
        return uri;
    }.property('fooMeasureId'),
    . . .
})

E.g. I need uri will be recalculated each time I click on link because this.model.foo.options is changed.
Thank you

A: If this.model.foo is an ember object it is observable. So you would add it as a dependency to your .property() call:
}.property('fooMeasureId', 'model.foo.options')

But then make sure to modify it with the Ember .set() and not with a simple assignment (=).
If it isn't an Ember.Object you have to manually call notifyPropertyChange on your fooUri computed property.


text:
Q: Runtime exec() doesn't run commands when filename has spaces I am new to Java and trying to convert one of my project from C to Java in order to combine it with another Java program. I'm having difficulty to get correct result when I use Runtime.exec(). I have the following program segment and Java ignores to process the given command.
command1 = "mv output/tsk/dir1/metabolic\\ waste.txt output/converted/file16.txt";
r2 = Runtime.getRuntime();
p2 = r2.exec(command1);
p2.waitFor();

The problem here is the filename "metabolic waste.txt". The same command work when there is no space. I know I have to use escape char for space and I do it. I'm working on Ubuntu btw.
I also tried using
String[] command1 = new String[] {"mv output/tsk/dir1/metabolic\ waste.txt", "output/converted/file16.txt";
but it didn't work.
p.s. the given code is just an example. I don't only use linux mv command. I also run some of the command line tools such as pdf2txt. I still have the same problem of running commands if there is any space in the filename.
SOLVED: I've solved my problem. It's ridiculous that I had to remove escape character and use string array. So, NO ESCAPE CHARACTER for space. The following code just worked for this example and for more general.
source_filepath = "output/tsk/dir1/metabolic waste.txt";
dest_filepath = "output/converted/file16.txt";
String[] str2= {"mv", source_filepath, dest_filepath};
r2 = Runtime.getRuntime().exec(str2);
p2.waitFor();

A: You can enclose the filename in double quotes as follows :
  String srcFile = "output/tsk/dir1/metabolic\\ waste.txt"
  command1 = "mv " + srcFile +" output/converted/file16.txt";

A: You have to escape the escape, or enclose the path in quotes:
String[] command1 = new String[] {"mv output/tsk/dir1/metabolic\\ waste.txt", "output/converted/file16.txt"};
String[] command1 = new String[] {"mv \"output/tsk/dir1/metabolic waste.txt\"", "output/converted/file16.txt"};

You have to use \\ because java also uses \ as an escape character, so "\\" really just contains one \


text:
Q: Getting error in VsCode C# (Omnisharp) when select the second project I use the vscode 1.48.0, c# extension 1.23.0. I use workspace and have more than one project inside workspace. The problem is when i select second project omnisharp give an error " Error: command 'o.fixAll.solution' already exists". I have to restart the vscode. But still get so many warning from omnisharp until i remove all project from workspace and put just one project in workspace.
So, if i have to use c# extension, i always remove all project from workspace and put only one that i want to work. It is so tiring. Projects are webapp. Does anybody has this problem?

A: The appears to be an open issue for this with the Omnisharp project


text:
Q: Zoho subscription validate webhook signature NodeJS I'm trying to secure my Zoho webhook implementation. I followed this doc: https://www.zoho.com/subscriptions/kb/webhooks/securing-webhooks.html
I don't find it super clear on what to do, but I'm pretty sure that in the end I still did everything what they said.
I DONT have any query parameters.
The format is just a default JSON payload NO X-WWW-FORM-URLENCODED.
I tried with following code, but I don't get the correct hash. It's also unclear if I should sort the default payload or not. According to this answer, it's only necessary for form-url-encoded and query parameters, but for plain JSON payload is no processing required. Either way I tried both ways with following implementation as a result:
function computeZohoSignature(query, payload) {
    return crypto
         .createHmac('sha256', process.env.ZOHO_WEBHOOK_SECRET)
         .update(JSON.stringify(payload), 'utf8')
         .digest('hex');
}

function validSignature(signatureHash, computedHash) {
  return signatureHash.length === computedHash.length
     && crypto.timingSafeEqual(Buffer.from(signatureHash), Buffer.from(computedHash));
}

I also tried wrapping the payload with following function:
function sortObjectByKeys(object) {
  if (!isObject(object)) return object;

  const sortedObj = {};
  Object
    .keys(object)
    .sort()
    .forEach((k) => {
      sortedObj[k] = sortObjectByKeys(object[k]);
    });

  return sortedObj;
}

The sorting works correct, and I even tried with just sorting the "root-keys". Doesn't matter what I try, the hash is never the same. And YES I'm 100% certain the secret is correct, I triple checked that.
Does anyone see what's wrong here or has a working NodeJS implementation of doing this?
Thanks in advance!

A: A typical Express setup uses the following configuration for parsing :
app.use(bodyParser.json());

This parser will add the parsed (object) content of a request's body to the body property of the first req parameter of your route handler (req, res) => { ... }.
The hash of your webhook, however, is calculated based on the raw (string) payload. While you could use JSON.stringify to convert your parsed body back to a string, this may result in inconsistencies with the original raw payload.
For example, if your currency is Euro, Zoho will pass the encoded "\u20a" as the value for currency_symbol. However, if you use JSON.stringify to convert your parsed body back to a string, you'll find that it produces the unencoded "€" instead. And because this results in both strings not being identical, they will not produce the same hash.
Without direct access to the raw body, it is very difficult to detect precisely what's the difference between the original raw body & the result of your JSON.stringify and thus how the latter should be transformed for it to be in the same format as the original raw body. The simplest way to overcome this, is to use the verify method of your parser, to add the raw body to eg. the rawBody property of the first req parameter of your route handler, as described in this article :
app.use(bodyParser.json({
  verify: (req, res, buf) => {
    req.rawBody = buf
  }
}))

If you assign the value of req.rawBody to payload, the hash produced by your computeZohoSignature method should now correspond with the signature passed by Zoho!


text:
Q: Привязка блока к верху страницы Здравствуйте

Есть 2 блока, расположены вертикально.
По-умолчанию расположены один за другим. Типа:

  Блок 1
  Блок 2

Как сделать чтобы при сколлинге страницы вниз(когда 1-й блок уже скрыт), 2-й блок(нижний) привязывался к верху страницы.
Спасибо.
A: На чистом css это сделать не получится. Это можно реализовать с помощью jQuery Waypoints.
A: Можно и без jQuery. Но совсем без JS не получится.

window.onscroll = function() {
  var scrolled = window.pageYOffset || document.documentElement.scrollTop;
  document.getElementById('B').style.position = scrolled > 150 ? 'fixed' : 'inherit';
}
* {
  margin: 0;
  padding: 0;
}
.A {
  width: 100%;
  height: 150px;
  background: #EEE;
}

.B {
  top: 0;
  left: 0;
  width: 100%;
  height: 50px;
  background: #66A;
}

Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.

Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.

Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.

Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.

Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.

Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.

Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.

Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.Make ten changes at the same time, not one change ten times. Multiple selections allow you to interactively change many lines at once, rename variables with ease, and manipulate files faster than ever.


text:
Q: Conditions on Hypothesis testing I am taking an introductory level statistics course, and I really need help with this problem:
The null hypothesis on true/false test is that the student is guessing, and the proportion of right answers is 0.50. A student taking a five question true/false quiz gets 4 right out of 5. She says that she knows the material, because the one tailed p value from the one proportion z test is 0.090 and she is using the significance level of 0.10. What is wrong with her approach?
a)Sample is not random and independent
b)sample size is not large enough
c)the population is not large enough
d)there is nothing wrong with her approach, the necessary conditions are satisfied.
I am leaning towards c; I believe that A is not the correct answer because we're assuming here that the sample is random and independent. I believe that C is not the correct answer because the population of true/ false test is most likely 10 times greater than her sample size....
If anyone could help me on this problem, I would greatly appreciate it. Thanks!

A: You are right. Both A and C are not correct answers, and B is. The sample size here is $n=5$ observations, whereas z-test calculates p-value using Central Limit Theorem (CLT) which states that the distribution of a mean in a large sample is approximately Normal. The number $5$ is not large. To see how the exact $p$-value differs from $0.090$ let's calculate it.
For five observations, if we have $4$ successes, the exact $p$-value is a probability to have at least $4$ right answers to $5$ questions when the null-hypothesis is true (correct answer with probability $0.5$). Using Binomial formula, we get:
$$
\mathbb P(\text{$4$ or $5$ correct answers}) = \binom54 (0.5)^4 (0.5)+ (0.5)^5 = \frac{6}{32}=0,1875.
$$
This is very far from the result obtained by CLT.


text:
Q: Global sections of canonical sheaf and genus Let $k$ be algebraically closed and C a curve. Then $g(C) = h^0(C, \omega_C)$. I want to show that if all the degree $0$ line bundles are trivial, then $g = 0$. I can sort of see that if I think of $C$ as a compact complex surface, then being able to shrink down every degree $1$ loop on the surface to a point implies that the surface has no holes. But I am unsure how to obtain a proper geometric argument. Thanks.

A: Let $C$ be a complete smooth curve $C$ of genus $g$ over an algebraically closed field.
An explicit  approach
Fix a point $p_0\in C$.   Then, if $g\gt 0$, the line bundles $\mathcal O(1.p-1.p_0) \: (p\in C)$ associated to the divisors of degree zero $1.p-1.p_0\in \operatorname {Div}_0(C)$ are pairwise non isomorphic.
A conceptual approach
The curve  $C$ has a Jacobian, which is an abelian variety of dimension $g$ and whose closed points parametrize the isomorphism classes of line bundles of degree zero on $C$ .
So indeed it is only for $g=0$ that all line bundles on $C$ are trivial.


text:
Q: Clean composer output from non readable characters in Jenkins' console output page I have a Jenkins job to tweak, but no administration right on Jenkins itself.
I'd like to clean composer output from non readable characters, e.g:
the command is composer update --no-progress --ansi which outputs

in Jenkins'console.
I didn't exactly get the the reason why Jenkins cannot output some characters correctly.
As per https://medium.com/pacroy/how-to-fix-jenkins-console-log-encoding-issue-on-windows-a1f4b26e0db4, I perhaps could have tried to specify -Dfile.encoding=UTF8 for java, but as I said I don't have rights for Jenkins administration.
How could I get rid of these 'squares' characters ?

A: By pasting output lines into Notepad++, i noticed that these characters were backspaces. Hereafter how I've managed to embellish the output for Jenkins console :
# run the command, redirect the output into composer.out file
bin/composer.sh update --no-progress --ansi >composer.out 2>&1

# getting rid of backspaces
composer_out=$(cat composer.out | tr -d '\b')
# adding line feeds instead of numerous spaces
composer_out=$(echo "$composer_out" | sed -r 's/\)\s*(\w+)/\)\n\1/g')

echo "$composer_out"


text:
Q: No module named '_overlapped' Working on a masters project and a fellow course mate has developed a web application using Django on a windows computer and has sent the file to us. I am trying to run the server on my MacBook terminal but when I run it, get the error "ModuleNotFoundError: No module named '_overlapped'. I have installed trollius as recommended in a previous post but hasn't worked for me. any help?

A: I got this error when I wanted NULL as default for my Model's field, so Visual Studio Code added automatically on the first line from asyncio.windows_events import NULL, I saw that the traceback were pointing

File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/windows_events.py", line 3, in <module>
import _overlapped

So I just deleted from asyncio.windows_events import NULL, then the error was gone.


text:
Q: Bootstrap 3 Datetimepicker minDate is not working as spected Hello i'm new with this library and i wanted to set the minimum date = today, but when i select any date after today and try to select again today, it doesn't work, i'll show my small code and hope you to help me, thanks.

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


text:
Q: Return line conditonally on next line I am trying to return a list of  IP Addresses for computers that have a windows OS (for my security course). The output is in this format
Nmap scan report for 192.168.xx.xxx
Host is up (0.066s latency).
PORT    STATE SERVICE
139/tcp open  netbios-ssn
445/tcp open  microsoft-ds
MAC Address:

Host script results:
| smb-os-discovery:
|   OS: Windows Server (R) 2008 Standard 6001 Service Pack 1 (Windows Server (R) 2008 Standard 6.0)
|   OS CPE: cpe:/o:microsoft:windows_server_2008::sp1
|   Computer name:
|   NetBIOS computer name:
|   Workgroup: WORKGROUP
|_  System time: 2015-12-22T17:01:33-08:00

I was able to get the values into a better format using grep "for\|Windows"
Nmap scan report for 192.168.xx.xx1
|   OS: Windows XP (Windows 2000 LAN Manager)
Nmap scan report for 192.168.xx.xx5
|   OS: Windows 2000 (Windows 2000 LAN Manager)
Nmap scan report for 192.168.xx.xx8
Nmap scan report for 192.168.xx.x15

I am now trying to get the value (grep) of the previous line, if the next line contains a "|" character, but I have no idea how. I have tried using tr "|" "\b" but that did not work
Input (stored in a text file)
Line 1
|   Line2
Line 3
|   Line 4
Line 5
|   Line 6
Line 7
Line 8
Line 9
|   Line 10
Line 11

Desired Output
Line 1
Line 3
Line 5
Line 9

A: You could do without grep e.g with sed you could save the line with the IP to hold buffer and copy it over the pattern space only when OS is Windows (deleting all other lines):
... | sed '/^Nmap scan report for/h;/^|[[:blank:]]*OS: Windows/!d;g'

or, in a similar manner, with awk, this time printing only the IP instead of the whole line:
... | awk '/^Nmap scan report for/{t=$5};/^\|[[:blank:]]*OS: Windows/{print t}'

A: sed -e'$!N;/\n|/P;D' \
<<""
Line 1
|   Line2
Line 3
|   Line 4
Line 5
|   Line 6
Line 7
Line 8
Line 9
|   Line 10
Line 11

Line 1
Line 3
Line 5
Line 9

If it gets deeper...
sed -e'/^ *|/!{$!N;/\n|/P;}' -eD \
<<""
Line 1
|   Line2
|   Line 3
|___|   Line 4
    |   Line 5
    |___Line 6
Line 7
Line 8
Line 9
|   Line 10
Line 11

Line 1
Line 9

You can drop grep w/ ...
sed -ne'/^Nmap.* /!{/^|.*: Win.*(W/!d;}' \
    -e's///;/)/H;x;s/\n/: (W/p' \
<<""
Nmap scan report for 192.168.xx.xxx
Host is ...
bla... and more ...
and bla and so on...
#
Host script results:
| smb-os-discovery:
|   OS: not windows Server (R) ... !(Windows Server (R) 2008 Standard 6.0)
|   OS CPE: cpe:/o:microsoft:windows_server_2008::sp1
|   Comp ... some words ...
|   Net... more words ...
|   Work... words again ...
|_  Sys...
#
Nmap scan report for 192.168.xx.xxx
Host is ...
MAC Address:
#
Host script results:
| smb-os-discovery:
|   OS: Windows Server (R) 2008 Standard 6001 Service Pack 1 (Windows Server (R) 2008 Standard 6.0)
|_  System time: 2015-12-22T17:01:33-08:00

192.168.xx.xxx: (Windows Server (R) 2008 Standard 6.0)


text:
Q: Decomposing the Schrödinger Equation I heard that the Schrödinger Equation is (naturally) to two coupled first-order real differential equations, where one is a continuity equation for the probability amplitude and the other is somehow the evolution of the phase. What is this decoupling and how does one do it?

A: If I remember correctly this trick boils down to writing the wavefunction $\psi(x)$ as an amplitude times a phase factor $\psi(x) = \sqrt{\rho} e^{i \varphi(x)}$, and working on the new (real) variables $\rho(x)$ and $\overrightarrow{v} = \frac{\hbar}{m} \overrightarrow{\nabla} \varphi(x)$.
This is especially useful when working with an interacting Bose-Einstein condensate, which can be described by the Gross-Pitaevskii equation (GPE) at $T = 0$. This is the same as Schrödinger equation, but with an extra non-linear term $\propto |\psi|^2 \psi$. In both cases (regular Schrödinger equation or GPE), the continuity equation for the probability density can be written as:
$$\partial_t |\psi|^2 + \mathrm{div}(\overrightarrow{j}) = 0,$$
with $\overrightarrow{j} = \frac{\hbar}{2im} \left(\psi^* \overrightarrow{\nabla} \psi - \psi \overrightarrow{\nabla} \psi^*\right) = \rho \overrightarrow{v}$.
So the continuity equation writes:
$$\partial_t \rho + \mathrm{div}(\rho \overrightarrow{v}) = 0,$$
which is the same continuity equation as in fluid dynamics.
In the case of GPE, the analogy with fluid dynamics actually goes further than that, and you can find an equation on $\rho$ and $\overrightarrow{v}$ very similar to the equation of a perfectly inviscid fluid (also known as Euler equation). I won't do the calculation myself here but you can check for "Hydrodynamics of the Gross Pitaevskii equation" online.
From this tutorial:
$$m \partial_t \overrightarrow{v} + \overrightarrow{\nabla}\left( \frac{1}{2}m v^2 + U - \frac{\hbar^2}{2m} \frac{\Delta \sqrt{\rho}}{\sqrt{\rho}} \right) = 0$$
The last term (which is not present in the usual Euler equation) is often reffered to as "quantum pressure term". It can be dropped if the condensate is strongly interacting (Thomas-Fermi approximation).
Edit : since you were talking about the Schrödinger equation rather than the GPE, it might be interesting to look at the notion of Quantum Potential, which seems to be the equivalent of the hydrodynamic treatment of GPE for the regular Schrödinger equation, as pointed out in a comment by Cosmas Zachos. I am not familiar with this version of the Schrödinger equation so I don't think I would be able to say a lot about it.


text:
Q: Python3 xlutils.copy I use xlutils.copy() to copy an excel file I opened using xlrd.
Then I proces the excel file, get the relevant data and add comments using xlwr.write() for the lines I used in the copied excel file.
Last step is to save the copied excel file using xlwr.save().
So far, so good. The essentiel part of the code looks like this.
import xlwt
import xlrd
from xlutils.copy import copy

    rb = xlrd.open_workbook(file)
    # print (rb)
    wb = copy(rb)
    # print (wb)
    sheet = rb.sheet_by_name(MNS Brandmelders')
    wsheet = wb.get_sheet(0)

    os.remove(file)
    os.chdir(path_opslag)
    # wb.save(file)
    os.chdir(path)
    continue

In the example above the wb.save command has been disabled.
I wrote the script on my laptop running Windows7 and Python3.5.1.
If however I copy the file to the production environment it reports an error on the last save command. Production also on Windows 7 with python 3.5.1.
AttributeError: 'dict_items' object has no attribute 'sort'


text:
Q: Is there a way to force an email received by a blackberry to open directly in a certain URL? Let me explain:
There are some apps (like the Facebook app) that send emails to the BB device, but when I open the said email, it opens directly in my facebook app. How is that possible? Is there an API or something I need to know about to be able to program that on my own app?
On another topic, could I do the same thing, but simply force the email to open a certain url in the BB browser?
Hope I explained myself.
Cheers!

A: Short answer, yes.
Take a look at the Message List Demo Sample application and the net.rim.blackberry.api.messagelist.* apis. That will handle the "injecting my own stuff into the message list" component of what Facebook does.
Secondly as for "grabbing incoming emails and doing things with them" you need to use FolderListener from net.rim.blackberry.api.mail.* APIs


text:
Q: Add Table Row Data within the Material-UI Accordion I have to create a table populated with two accordions with mock data and one accordion with the data from the database using reactjs in Material-UI. I have created an accordion having the table data. I want only the Table data in the accordion not the heading. I am having trouble getting the Table data in the accordion section.
<Paper className={classes.root}>
      <Table className={classes.table}>
        <TableHead>
          <TableRow>
             <TableCell>Dessert (100g serving)</TableCell>
            <TableCell align="right">Calories</TableCell>
            <TableCell align="right">Fat (g)</TableCell>
            <TableCell align="right">Carbs (g)</TableCell>
            <TableCell align="right">Protein (g)</TableCell>
          </TableRow>
         </TableHead>
         <Accordion>
      <AccordionSummary
        expandIcon={<ExpandMoreIcon />}
        aria-controls="panel1a-content"
        id="panel1a-header"
      >
        <Typography className={classes.heading}>OutStanding</Typography>
      </AccordionSummary>
      <AccordionDetails>
         <TableBody>
        {rows.map(row => (
            <ExpandingRow row={row} />
          ))}
          </TableBody>
         </AccordionDetails>
    </Accordion>
    </Table>
    </Paper>

The Screen looks like this
current screen
How do I achieve it?
Any assistance would be greatly appreciated, thanks!

A: You will need to include table inside accordionDetails, and map rows.
Somewhat similar I have just created to show, Please check :
https://codesandbox.io/s/mui-table-accordion-inside-qc7sq


text:
Q: Fatal errors in live servers I'm writing some client/server software and I'm facing the following design issue. Normally, I use a VERIFY macro very liberally - if something is wrong in an user's machine, I want the software to fail and log the error so it can be fixed. I was never a fan of ignoring any kind of errors.
However, I'm now writing a server. If the server dies, many clients go down, so the server should die as little as possible. Therefore, I don't know how to treat some conditions that I'd treat as fatal exceptions otherwise.
For example, I get a network packet from an user who isn't logged in. Even though it shouldn't happen, I have enough experience to know "impossible" errors do happen from time to time. So I'm pretty sure if I do a fatal error on these cases, the server WILL crash eventually. On the other hand, I could log and ignore the error and continue, but I'm afraid some bugs may go undetected this way.
What would you do in a situation like this one?

A: If you can recover from the error, than obviously it wasn't fatal. I can't see the benefit of failing if you can log the error and continue execution - the most important thing is that you've captured the error on log. If you can recover and continue to operate as normal, than that is the best course.
You should implement in addition a notification system (server monitoring) that depending on the error level would notify you in varying degrees of urgency so you'd pick up as soon as possible on something time critical. There are generic system like that for servers, such as Nagios and Munin. You should have look at what they do and see if you can take something from them and implement / integrate it into your system.
Regardless, you should try to make sure client instances are as sandboxed as possible. A client thread going down shouldn't take down the entire server - ever (at least in theory).


text:
Q: How do I get a moving average? I want to get a 5 day moving average from an array of numbers like so.

Array of numbers: 11,12,13,14,15,16,17
First day of 5-day moving average: (11 + 12 + 13 + 14 + 15) / 5 = 13
Second day of  5-day moving average: (12 + 13 + 14 + 15 + 16) / 5 = 14
Third day of 5-day moving average: (13 + 14 + 15 + 16 + 17) / 5 = 15

int[] arry = {11,12,13,14,15,16,17};
int sum = 0;

for(int j = 0; j < 5; j++) {
    sum += arry[j];
    System.out.println(sum);
}

System.out.println();
int average = sum / 5;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);

Am able to get the first average but am lost on how to implement a loop to get the next set of averages?

A: Please see the following tested code (method from @ajb is more elegant, but I use the idea from @zapl for simplicity):
public static void main(String[] args) {
    int[] arry = { 11, 12, 13, 14, 15, 16, 17 };
    int size = 5;

    for (int i = 0; i + size <= arry.length ; i++)

        int sum = 0;
        for (int j = i; j < i + size; j++) {
            sum += arry[j];
            System.out.println(sum);
        }

        System.out.println();
        int average = sum / 5;
        System.out.println("Sum: " + sum);
        System.out.println("Average: " + average);
    }
}

A: public class MovingAvarage {
public static void main(String[] args) {
    double[] array = {1.2, 3.4, 4.5, 4.5, 4.5};

    double St = 0D;
    for(int i=0; i<array.length; i++) {
        St = movingAvarage(St, array[i]);
    }
    System.out.println(St);

}

private static double movingAvarage(double St, double Yt) {
    double alpha = 0.01, oneMinusAlpha = 0.99;
    if(St <= 0D) {
        St = Yt;
    } else {
        St = alpha*Yt + oneMinusAlpha*St;
    }
    return St;
}

}


text:
Q: SQL Server 2012: Procedure is taking very long time to execute when I call a function within it with parameters but it doesn't if a pass raw values I am asking wondering if any of you can help me with ideas. You see, I am tuning a store procedure, call it proc1, and it calls internally a table function. The procedure have a table input parameter (idk why, but it was build like that) and then it executes the table function:
Call to the procedure as it is being done by front end:
declare @p3 dbo.tblType

insert into @p3
values( 11 , 1 , 2 , 5 , 0 , 0 , 0 , 0 , 0 , 'true', 'test')

exec sp_executesql N'proc1 @tblSearch',N'@tblSearch [dbo].[tblType] READONLY',@tblSearch=@p3

Call to the table function within the procedure.
INSERT INTO #TempTable
    SELECT *
    FROM Func1(@Param1, @Param2,@Param3)

The spooky thing is this, I tuned up the table function to reduce the timing to execute, however, the procedure it is taking about the same. Then I try to figured out the problem and simplify the problem. Finally I put the raw execution of the table function with values.. and it works. So if the procedure got this, it executes in 1 second, but if I change it with variables, it takes ages (8 minutes). And I review and verify several times that the values that I am binding are the same that those I am putting raw.
lightspeed execution:
SELECT *
FROM [dbo].[Func1] (11,1,2,5,0,0,0,0,0,0)
ORDER BY 1

Snail slow execution:
SELECT *
FROM [dbo].[Func1] (@IDa, @IDb, @OtherActionId, @Idc, @IDd, @IDe, @IDf, @IDg, @IDh, @IDi)
ORDER BY 1

This issue is driving me crazy, it is nuts. How come the very same call have such different timings?? just in one I put the values and I swear that I verify the input parameters, I put the below statement just before the execution so I know them:
SELECT @IDa '@IDa',@IDb '@IDb',@OtherActionId '@OtherActionId',@Idc '@Idc',@IDd '@IDd',@IDe '@IDe',@IDf '@IDf',@IDg '@IDg',@IDh '@IDh',@IDi '@IDi'

Any idea? Perhaps related to sp_executesql? Has anyone had similar issues?
Thanks in advance and kind regards!


text:
Q: BTRFS inside a KVM-VM on a qcow2 formatted image I have a Ubuntu 14.04 application appliance that makes heavy use of BTRFS snapshots. The application is meant to be hypervisor agnostic and the snapshots need to be stored with the virtual machine image in case we need to troubleshoot an issue. Using the hypervisors built in snapshotting methods instead of BTRFS snapshotting would be more work than it's worth since it would require API access to the hypervisor from the VM which we don't want for security reasons. I can also remotely access the BTRFS snapshot filesystem subvolumes directly from the appliances command line via ssh without having to power down the machine or access a hypervisor API.
In the past I've only had to deal with deploying this application to vmware based hypervisors. I always used thin provisioning on my vmware disks and never noticed any performance issues. I use thin provisioning because I do a large amount of testing on this appliance and I tend to deploy many appliances at a time to run different tests in parallel.
I'm very careful about not over committing the storage by using scripts that ensure the disk growth doesn't run out of control. The I/O dip that happens when the thin provisioned disk needs to grow isn't all that noticeable either.
Now I need to support KVM and would very much like to keep Thin/sparse provisioning my disks, however I've read a few things that state mixing a CoW filesystem with another CoW filesystem is a bad idea due to over-redundant writes and disk fragmentation among other things. The common example given was running a VM with a qcow2 formatted disk stored on a BTRFS formatted volume. My situation would be the opposite. I want to have a BTRFS formatted filesystem in a VM running from a qcow2 image. I haven't found much on the particulars of the performance impact of BTRFS snapshots on top of a qcow2 image.
Question: Are there any other sparse file formats that grow with the disk size that KVM likes to use?
I've explored with using sparse raw files, but I can't seem to get them to stay sparse through a cp, download untar/gunzip, ect. It seems that if you want to use a sparse raw file, you can't move it around at all which would make distribution a pain in the ass.

A: The thing is, KVM doesn't support disk images at all. Unlike vmware which is an all-in-one type of solution, KVM only provides the virtualization capabilities, upon which a virtulization solution can be built.

...It consists of a loadable kernel module, kvm.ko, that provides the
  core virtualization infrastructure and a processor specific module,
  kvm-intel.ko or kvm-amd.ko. - http://www.linux-kvm.org/page/Main%5FPage

Typically, a KVM-based solution involves the combination of:

*

*KVM - for access to the CPU's virtualization capabilities

*QEMU - which provides the emulation bits, such as BIOS/UEFI

*additional libraries and tools - such as libvirt and Virtual Machine Manager
QEMU
QEMU supports two native disk formats (there are other formats as well, like VDI):
Raw

Raw disk image format (default). This format has the advantage of
  being simple and easily exportable to all other emulators. If your
  file system supports holes (for example in ext2 or ext3 on Linux or
  NTFS on Windows), then only the written sectors will reserve space. - man qemu-img

Qcow/2

QEMU image format, the most versatile format. Use it to have
  smaller images (useful if your filesystem does not supports holes,
  for example on Windows), optional AES encryption, zlib based
  compression and support of multiple VM snapshots. - man qemu-img

libvirt
libvirt provides a number of ways to store disk images:

*

*Directory backend

*Local filesystem backend

*Network filesystem backend

*Logical backend - LVM but without thin-provisioning :(

*Disk backend

*iSCSI backend

*SCSI backend

*Multipath backend

*RBD (RADOS Block Device) backend

*Sheepdog backend

*Gluster backend

*ZFS backend

*Virtuozzo storage backend

Take a look at those and see which, if any, meet your requirements. See https://libvirt.org/storage.html, and better yet https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Virtualization_Administration_Guide/chap-Virtualization_Administration_Guide-Storage_Pools-Storage_Pools.html

A: My personal experience is that you can work with raw files on a sparse-capable host filesystem.
I have raw files on an ext4 host file-system. With the vm shut down I can use "zerofree" on the raw files (mounted as loop device) and using cp --sparse=always oldfile newfile I get reduced file sizes.
I dont know if the files keep sparse during use as I only use this method to "archieve" images of test systems.
BTW, btrfs with heavy snapshotting seems to be a bad idea:
https://btrfs.wiki.kernel.org/index.php/Gotchas#Having_many_subvolumes_can_be_very_slow


text:
Q: PHP: Which ZipArchive::EM_ constant to use when encoding ZIP Archive with custom password I have a question about encoding zip files with password, which is available from PHP v 7.2
When I am encoding ZIP with method
ZipArchive::setEncryptionName
There are argument method which can be:

*

*ZipArchive::EM_AES_128

*ZipArchive::EM_AES_192

*ZipArchive::EM_AES_256

Can somebody tell me / explain which to use and why?
I am now using ZipArchive::EM_AES_256 because I am expecting that it is the most secure but my colleague is telling me that he cannot open it (his zip software is not even asking for password).
So is there one which will be working in all the cases? We have software which is used by a lot of people in my country and a lot of old people might get these ZIP files and it is required that they could be opened and that every zip file has a password.
Please consider that they might even use Windows XP etc.

A: As per your comment, Windows cannot decrypt AES-encrypted archives natively, not even in recent versions such as Windows 10 (see why).
PHP v8.0 adds "traditional pkware encryption" that will allow Windows users to work with files without 3rd party apps (7-Zip, etc).
For PHP v7.x, one needs to either rely on shell commands or use a library that supports ZipCrypto encryption algorithm (sometimes called "pkware" - as per the company that created the zip format). Several out of the most popular zip libraries on packagist use ext-zip, so they won't offer PKWARE encryption on PHP 7.x. However nelexa/zip doesn't and it supports pkware encryption.


text:
Q: jQTouch browser back button not working to separate index page Our jQTouch mobile site has a News & Events sections. Because of technical limitations with PHP, these sections had to live in a separate directory and jQTouch index pages (this can't be changed).
When I go from the main jQTouch index page to News or Events the browser back button doesn't work in iOS, Android, Safari and Firefox (oddly, Chrome works fine).
Do you know how to get the browser back button to work on the News and Events index pages?
Here is the main jQTouch index page of our mobile site:
http://bit.ly/ePbqHl

A: These are all shot-in-the-dark options, but it sounds like it might be similar to an older issue like this one (which is from about a year ago). Are you using an older version of jQT?
A few possible things to try:
1) Grab the latest version of jQT. This might introduce additional issues, but maybe worth swapping out the .js file to see if it resolves your problem.
2) Based on an even older post, your issue sounds like it might be related to the dumbLoopStart function. Maybe try altering/disabling this to see if it helps.
3) It's definitely more quiet on the jQT Google Group as opposed to here, but you may want to post your issue there to see if others have experienced the same behavior.


text:
Q: How can a variable be a type of a class? I am currently learning about how delegates work, however I cannot understand why a variable is initialized as a type of the class, and not instantiated. How can a variable be a type of a class and why is that necessary when you could just instantiate the class?
var person: person!

A:
How can a variable be a type of a class and why is that necessary when you could just instantiate the class?

You obviously can just create an instance of the class:
var person = Person(...)   // Note, class names generally begin with uppercase letter

But consider the following:
var person: Person!

This means that person is now an Optional, one that can refer to a Person instance. And the ! indicates that this optional will be implicitly unwrapped when you reference it in your code.
So the question is why would you use the latter (the implicitly unwrapped reference which is not yet set) rather than the former (just instantiating the Person immediately). The answer is that you generally do this when the person variable simply cannot be set initially, but will be set later.
A common example would be a "details" view controller which will show us details about a Person object selected from a prior view controller. If this details view controller is instantiated from, say, a storyboard scene, clearly the person variable isn't set yet, so it has to be an optional. But the presenting view controller (or the coordinator or whatever) will set the person reference after the scene's view controller is first instantiated, but before the view controller appears on the screen. E.g., we might set the destination's person inside the presenting view controller's prepare(for:sender:) method.
So, in this case, we would declare person to be an Optional (so the view controller can be instantiated, even though the person hasn't been set yet), but declare it to be an implicitly unwrapped one (Person!) because we know the presenter will make sure to set person before the details view controller appears on screen.

A: The statement referenced is a variable declaration without an initializer expression. The normal format is:
var variable name: type = expression

The colon followed by type is a type annotation, while the expression that follows the equal sign is the actual initialization expression.
var person: Person!

So here we are declaring a variable named person, annotated with a type of Person, and the exclamation point marks it as an implicitly unwrapped optional.
There are probably several reasons why a variable (whether class or struct or some other type) might be declared without also being initialized:
An example is when working with IBOutlet variables that are declared inside a view controller class.  These variables are usually declared as implicitly unwrapped optionals.  When the view controller object is first created, these variables are not yet initialized.  However, they are always set by the time viewDidLoad is invoked.
Another reason might be that it just wouldn't make sense in terms of the application logic to instantiate the variable immediately.  Lazy initialization is a special case of this where the variable in question is automatically initialized at the first point  it is needed.


text:
Q: Can I use a RN2483 to make a LoraWAN gateway? I have a Microchip RN2483 LoRaWAN module and I would like to use it for making a LoraWAN Gateway. Is it possible? If it is, how can I do it? Or if it is not, why?

A: It is not possible to create a "full" LoRaWAN gateway using the RN2483 because RN2483 can only listen on one channel. A full gateway needs to listen on multiple channels because LoRaWAN devices randomly select which channel to send on.
However, it is possible to create a single channel gateway. Such gateway would not be LoRaWAN-compatible, but can still solve some use cases. More information: https://www.thethingsnetwork.org/forum/t/single-channel-gateway-with-rn2483/1848


text:
Q: NPIV support on RHEL Hypervisor (KVM) We are planning to setup RHEL KVM hypervisor on a Physical machine and then create multiple Linux VMs on that hypervisor.
In order to directly map/present Storage LUNs to these VMs, we are planning to use NPIV technology of KVM.
I want to clarify few things:

*

*Is KVM NPIV technology same as NPIV technology of Windows 2012 Server Hypervisor where once NPIV environment is set correctly, Storage LUNs can be directly mapped to VM using virtual WWN?

*What are the supported guest VM OS type which are supported for NPIV like RHEL, SUSE etc.

*Any particular Network switch types which supports KVM NPIV technology.

It will be great if somebody knows the answer of these questions and share them.
Thanks,
Nitin

A: 1)  NPIV is an ANSI Standard, so yes it is the same idea as 2012 Hyper-V Uses.
2)  I'm looking for this info as well, will update if I get it.  http://www.linuxtopia.org/online_books/rhel6/rhel_6_virtualization/rhel_6_virtualization_chap-Para-virtualized_Windows_Drivers_Guide-N_Port_ID_Virtualization_NPIV.html seems to indicate it's agnostic to the guest operating system, but I have a couple contacts I'm asking for details from.
3)  Brocade and Cisco FC switches both support.


text:
Q: How to handle null objects for entities in php I have an Entity class that maps records from MySQL database. For example, a class User that inherits an Entity class would map table user.
class User extends Entity
{
    function init(){ $this->_table = 'user';}
}

When I map an object with id 30 i use
$user = new User(30);

What is the best way to handle when object id 30 is not available (let's say it is deleted).

*

*Throw an exception, "This object is not available"

*Return a null object.

A solution or a set of solutions with pros/cons would be appreciated.

A: I like to use exceptions in cases like this because the exception can contain the various reasons the object is unavailable.  A null object you'll have no idea.

A: Throwing exceptions means that an exceptional situation occurred in your application. In my opinion an object with a specific ID not existing is not an exceptional situation. I would go with returning a null object.
And the mechanism for throwing/catching exceptions comes with a performance penalty.

A: Throw an exception. This way you can catch it wherever you're trying to construct the User object, and decide what to do there.

A: Personally I prefer to return an object with an error code property.

A: Its hard to say without knowing the design of your program, such as where these "ID's" are coming from, how they are generated, etc.
The pros/cons here are based on the design of your program and your needs for the given situation. Once you assess those, you can determine what is best for you.


text:
Q: Can you convert an .accdr file to .accdb? I don't have access the original executable files but only the runtime versions of the Access files. I need to change a key core function of a database and I cannot access the core functionality. Do I need the original files or can I work with what I have?

A: The .accdr file extension does not tell you whether the database is actually ACCDB or ACCDE format.  If it's ACCDE, source code was removed and you can not use it for further development.
Find out which you have:

*

*Make of copy of the .accdr and rename that copy with an .accdb file extension.

*Open the .accdb in Access.

*Attempt to open any module and view its source code.

If step #3 is successful, your database is an ACCDB and you can make design changes to it.
If step #3 fails, the database is probably an ACCDE.  You will need to find the original ACCDB to use for your design changes.


text:
Q: There is a compilation error in my PL/SQL code I have a compilation error in my PL/SQL code, The audit_client table will be updated if any update or delete occurs on client_master
create or replace trigger t1
after update or delete on client_master
for each row

DECLARE
v1 varchar2(10);
v2 varchar2(80);
v3 number(11);
oper varchar2(15);
BEGIN
v1:= :old.CLIENT_NO
v2:= :old.NAME
v3:= :old.BALANCE
if updating then
    oper:='update'
    insert into audit_client values(v1,v2,v3,oper,v4,v5);
    end if;
if deleting then
    oper:='delete'
    insert into audit_client values(v1,v2,v3,oper,v4,v5);
end if;
end;
/

A: Why would you declare those v variables at all? Somewhat simplified:
create or replace trigger t1
  after update or delete on client_master
  for each row
declare
  l_oper varchar2(15);
begin
  if updating then
     l_oper := 'update';
  elsif deleting then
     l_oper := 'delete';
  end if;

  insert into audit_client
    (client_no, name, balance, oper, col4, col5)
  values
    (:old.client_no, :old.name, :old.balance, l_oper, null, null);
end;
/

Instead of v4 and v5 I inserted NULL as you never said what should be put in there.
Also, as a good practice, you should always specify column list you're working with. That's why I made up those column names as I don't know their real names, but you do and you should use them.


text:
Q: Angular Adal how to retrieve the username or email I have written an angular js app that I am using angular-adal.js to authenticate against Azure AD. I have configured all routes to requireADLogin and also added
extraQueryParameter: 'nux=1,scope=openid'

in the init method.
My question is where can I pull the logged in username or email etc from to store against the records they are creating after they've logged in. Because I am not manually authenticating in code I don't have a token object or anything to play with. Any pointers would be appreciated as although I've searched all the exmaples seem to be when you are making the calls yourself rather than letting UI Router do the authentication.
I'm sure this must be a common thing to do though!!
Thanks in advance!

A: After we sign-in the Angular application using ADAl library, it provides userInfo object which we can get the information about the user. And we can get the userName from this object directly.
Here is the code and figure for your reference:
$scope.printUserName = function () {
                    console.log(adalAuthenticationService.userInfo.userName);
                };

The Microsoft also provide a code sample for the Angular application, you can refer it from here.


text:
Q: Expected value : Reciprocal Sum Positive iid Random Variables Let $\{X_i\}_{i=1}^{n}$ be iid positive valued random variables. Show that $\mathbb{E}[\frac{\sum_{i=1}^{m}X_i}{\sum_{i=1}^{n}X_i}]=\frac{m}{n}$ for $1\leq m\leq n$.
I know $\mathbb{E}[\frac{\sum_{i=1}^{m}X_i}{\sum_{i=1}^{n}X_i}]=m \mathbb{E}[\frac{X_i}{\sum_{i=1}^{n}X_i}]$.

A: If you can prove that $\mathbb{E}[\frac{\sum_{i=1}^{m}X_i}{\sum_{i=1}^{n}X_i}]=m \mathbb{E}[\frac{X_i}{\sum_{i=1}^{n}X_i}]$, then simply find $$1=\mathbb{E}[\frac{\sum_{i=1}^{n}X_i}{\sum_{i=1}^{n}X_i}]=n \mathbb{E}[\frac{X_i}{\sum_{i=1}^{n}X_i}]$$ and conclude.


text:
Q: Minimum distance between Hamiltonian cycles in cubic Hamiltonian graph It is $NP$-hard to find constant factor approximation of longest cycle in cubic Hamiltonian graphs. Therefore, finding a Hamiltonian cycle in a cubic Hamiltonian graph is NP-hard.
By Smith's theorem, cubic Hamiltonian graph contains at least two Hamiltonian cycles. Therefore, finding a Hamiltonian cycle in a cubic Hamiltonian graph is NP-hard. Given cubic graph on $N$ nodes:

What is the best lower bound on the minimum Hamming distance between two Hamiltonian cycles (each Hamiltonian cycle contains $N$ nodes) in cubic Hamiltonian graph?

Here Hamming distance between two Hamiltonian cycles is the is $N-$ the number of shared edges. $N$ is the number of nodes in the graph. The upper bound is $N/2$.
EDIT: I conjecture that it is at least $\Omega(\log N)$ and I even conjecture a tighter lower bound of $\Omega( \epsilon N)$ for some constant $\epsilon \gt 0$.

A: Let me maybe just formulate the comment as an answer.
It is easy to see that the lower bound can't be 1. Assume that $H_1$ contains the edge $e$, and $H_2$ does not contain $e$. If the edge $e$ is not contained in a triangle, then it has 4 adjacent edges. Then $H_2$ has to contain all 4 of these edges, while $H_1$ can only contain 2 of them, so the hamming distance is at least 2. If the edge $e$ is contained in a triangle, then $H_1$ and $H_2$ can share at most one edge of the triangle and at most one of the incoming edges of the triangle, or no edge of the triangle and two of the incoming edges. In either case the hamming distance is at least 2.
In case of the $K_4$ the minimum Hamming distance is 2. To construct a cubic graph in which the minimum hamming distance is 2, just take any hamiltonian cubic graph. Remove an edge that is contained in a hamiltonian cycle. Take a $K_4$ and remove an edge. Connect the vertices of degree two in both graphs to get a new cubic graph. The new graph is hamiltonian and contains two hamiltonian cycles that only differ in the edges in the $K_4$, so the hamming distance is 2.
Of course the graphs above have girth 3, so it  might be possible to give a better lower bound as a function of the girth of the graph.
Edit: Maybe this illustration will make things more clear. Take any hamiltonian cubic graph and take an edge that is contained in a hamiltonian cycle (shown in red at the top). Insert a $K_4$ minus an edge into that edge. The new graph has two hamiltonian cycles (shown in red at the bottom left and right) which have hamming distance 2. You can do this for any cubic graph which has a hamiltonian cycle so you can get any number of vertices and still have minimum hamming distance 2.

Edit 2: Since both $K_4$ and $K_{3,3}$ contain hamiltonian cycles with hamming distance 2, and the construction above adds 4 vertices, we have that for all $n\geq4$, there exists a cubic hamiltonian graph $G$ on $n$ vertices such that $G$ contains at least two hamiltonian cycles at hamming distance 2.


text:
Q: Generic parameter 'Self' could not be inferred (swift 4) I want to make a substring extension for string , I tried below 2 ways but unsuccessful:
extension String
{
    func substringToFirstChar(of char: Character) -> String
    {
        let pos = self.range(of: String(char))
        let subString = self[..<pos?.lowerBound]
        return String(subString)
    }
}

or
extension String
{
    func substringToFirstChar(of char: Character) -> String
    {
        let pos = self.index(of: char)
        let subString = self[..<pos]
        return String(subString)
    }
}

xcode prompt error:  Generic parameter 'Self' could not be inferred  at the "let subString = self[.." line.

How to do that ?

A: range(of / index(of returns an optional. You have to unwrap the optional in the range expression
extension String
{
    func substringToFirstChar(of char: Character) -> String?
    {
        guard let pos = self.range(of: String(char))?.lowerBound else { return nil }
        // or  guard let pos = self.index(of: char) else { return nil }
        let subString = self[..<pos]
        return String(subString)
    }
}

alternatively – to avoid the optional – return the unchanged string if there is no match
extension String
{
    func substringToFirstChar(of char: Character) -> String
    {
        guard let pos = self.range(of: String(char))?.lowerBound else { return self }
        // or  guard let pos = self.index(of: char) else { return self }
        let subString = self[..<pos]
        return String(subString)
    }
}


text:
Q: jQuery mobile $.mobile.changePage not working properly on iPhone in PhoneGap I was having an annoying problem that had me stumped for about two days.
I developed a PhoneGap application using jQuery mobile for the framework.  I initially developed it on Android and all worked fine.
Now, it's supposed to be cross-platform but when I brought it over to iPhone, it wouldn't get past the splash screen.  I followed a few red herrings but eventually managed to zone in on the problem in JavaScript.
It was a call to $.mobile.changePage early on in the program execution that was causing the problem.  Appears to be some kind of race condition because when I commented out the offending line of code, it got past the splash screen and then if I ran the statement remotely from the Safari development console, it worked okay.  To add to my frustration, it even worked okay in the Safari browser on the iPad but just not within the PhoneGap app which was even more strange.
I followed some advice to use setTimeout as a workaround which I got from a jQuery mobile github issue page here:
https://github.com/jquery/jquery-mobile/issues/3190
This made it work (thankfully!!).  However, am I doing something wrong?  I feel there should be a better solution than merely adding a delay to the program execution.
Here is the code:
$(document).on('pageinit', '#home', onHomePageInit);

function onHomePageInit() {
    $("#home").on("pageshow", checkTokenAndSync());
}

function checkTokenAndSync() {
    // check for stored values
    var storedId = window.localStorage.getItem('id');
    var tokenValue = window.localStorage.getItem('token');

    if(storedId == null || tokenValue == null) {
        // no token value found, direct user to login screen to obtain one

        // This doesn't work.  Need to use setTimeout as below
        // $.mobile.changePage("#loginDialog");

        window.setTimeout(changeToLoginDialog, 1000);
    }
}

function changeToLoginDialog() {
    $.mobile.changePage("#loginDialog");
}

I'm going to add a comment to that github issue page.

A: Add these two lines on your config.xml
<preference name="scheme" value="app" />
<preference name="hostname" value="localhost" />

A: In case anyone is looking for a quick-fix workaround to this problem.  Try using window.setTimeout to add a delay to the program execution.  See question above for code.


text:
Q: why does rolling without slipping imply no work done by the frictional force? Suppose we have a cylinder (mass $m$, radius $R$, and moment of inertia $I$) that rolls without slipping straight down an inclined plane which is at an angle $\alpha$ from the horizontal. The quickest way to solve for the motion is to use conservation of energy, assuming that there is no work down by the frictional force.
My question is: why does rolling without slipping imply no work done by the frictional force? One explanation you will sometimes read is that this is because the point of contact of the cylinder is instantaneously at rest relative to the ramp surface, so when we compute the work via $W = F\ dx$ we have $dx = 0$ and hence $dW = 0$.
However, consider a related problem. Suppose the cylinder is held fixed in place (say by a rod drilled down its middle) but is free to rotate around its center. Now suppose we take the ramp up against the cylinder and move the ramp so as to get the cylinder spinning. In this case the frictional force obviously did work on the cylinder, yet once again the contact point of the cylinder is at rest relative to the ramp. Question: what is the difference between the two cases?

A: Friction without slipping can do work. Consider two blocks stacked on top of one another. If you push the bottom one, it will do work on the top one, and the two blocks will move together. The key here is that both blocks are moving, as in your second example.
Note that "work done" is a quantity that depends on the reference frame your are working in. Your argument says that there is no work done on the cylinder in the reference frame where $dx=0$. That is only the same as the lab frame if the ramp is not moving.
In your first example, the ramp isn't moving, and so the friction of an object rolling on it without slipping does no work.


text:
Q: Fabric js - On mouse over - event target is wrong I have created some rectangles and added custom data to it.
On mouse over, i am retreiving the object on which mouse is hover and getting the custom data and shoiwng it on tooltop.
However, the event.target object is wroing.
Its not getting correct the object (object on which mouse is hovering)
See the pic below for illustrationenter image description here
station_.platforms.forEach(function (platform_) {
  journey_attrs.top = top;
  var platform = new fabric.Rect(journey_attrs);

  if(subway.subwayConfig.isEndStation(station_.key)) platform.set({opacity: 0});

  top = top + 15;

  platform.set('subwayConfig', { type: 'platform',
    stationKey: station_.key,
    journeyKey:  platform_.journeyKey });

  subway.canvas.add(platform);
  platform_.fabricObject = platform;
})

{"fill":"black","width":60,"left":1448,"height":8,"stroke":"RGB(112,210,250)","strokeWidth":3,"top":364}


text:
Q: Sharing Team Members Login Accounts This question is probably quite subjective, but it's one that I'd like to know what others are doing.
In most organizations there comes a time when a team member is out of the office on vacation, sick, holiday, whatever. In some cases, their coworkers may need to access files stored on their machine (or in their My Documents which may/may not be on the network) or in their email.
How does your organization handle these cases? Do you:

*

*Allow departments to share login
information with each other. This
would allow team members to access
what they need when they need it.

*Create a common email address or
distribution group for critical
email and enforce that users use the
out of office assistant and direct
customers to that address. All
critical files would then be stored
in network shares or a ticket would
need to be placed with IT.

*Something else

Thanks in advance!

A: At work, all code is stored on the development server. Every member of the dev team has sudo access to become root and access each others files.  Theres also a work-wide shared document directory that we all have access to. Nothing of any importance should be stored on local machines.
Relying on a mechanism like sudo leaves a really nice audit trail. You never want to directly password share, because in addition to a huge privacy violation you also have the situation arise where you can not be sure who was actually logged in as the user at the time of any incident in the future.

A: The way we handle it (and I think it is the most secure) is that a Security Exception is filed and an administrator for whichever system the information is on retrieves the required information.

A: For the case you mentioned, the department manager would have to file a request to gain access.  Depending on the situation, we may access the data for them, grant the manager access, or give another user access to the data.
Never do we have a policy where sharing usernames and passwords is acceptable.

A: You should think about setting up procedures for accessing files on your staff's personal folders (either shared or local) in situations of urgency.   Every data on work property belongs to your work, but there needs to be a process of WHO has rights to see these data in situations that call for access when the person is not available.

A: Normally, things should be organized such that information required by the team is accessible to them.
That means putting information about bugs into a bug tracker, putting customer communication into a trouble ticket system or similar, putting documentation into a shared folder, intranet wiki or similar etc.
If that is done, there should be no need to access someone else's files. There may be a need in special cases, but at least in my (small) company it's never happened to me.


text:
Q: How can I  troubleshoot this "object reference not set to an instance of an object, use new" error I am using threads to read from a file and process content. I have the following code:
Dim line As String = Nothing
Dim result As String = Nothing
Dim solved As Boolean
While strReader.EndOfStream <> True
    SyncLock strReader
        line = strReader.ReadLine()
        result = "ERROR"
    End SyncLock
    solved = False
    While solved = False
        result = Process(line)
        If Not result.Contains("ERROR") Then
            solved = True
        End If
    End While
    //some code
End While

and it gives me that error at line: If Not result.Contains("ERROR") Then
with labels works fine but I read that they are bad for coding.
How can I get rid of this error? What am I doing wrong?
Thanks!

A: The error pretty much says it all
Process(line)

Is returning a null value. Fix Process() to return a non-null value.
Alternately you could do this
If not result is nothing then
  solved = not result.Contains("ERROR")
End if


text:
Q: Probability of a random triangle containing the center of a polygon Consider a regular polygon of $2n+1$ sides. Let three random vertices be chosen at random to get a triangle. The probability that the chosen triangle contains the center of the polygon is 5/14.
What is n?
I'm confused as to how to proceed on the cases that we will get. They do not form any definite pattern.

A: The probability seems to work out for a regular $9$-gon (so $n=4$).
Consider a circle with $9$ equally spaced points marked.  Let's label the points $0, 1, 2, \dots, 8$ going clockwise around the circle.  These points form our regular $9$-gon.  When we choose $3$ of these vertices and form a triangle, the triangle contains the center if and only if the triangle is acute. This in turn occurs if and only if as you go from one chosen vertex to the next you never skip more than $3$ vertices.
By symmetry, we can freely choose vertex $0$.  And then we choose two other vertices $a$ and $b$ with $a<b$.  We need the spacing between these consecutive vertices to be at most $4$.  This means that $a$ must be $1$, $2$, $3$, $4$.
For $a=1$ we must have $b=5$ to contain the center.
For $a=2$ we must have $b=5$ or $6$ to contain the center.
For $a=3$ we must have $b=5$ or $6$ or $7$.
For $a=4$ we must have $b=5$ or $6$ or $7$ or $8$.
This gives us a total of $10$ good triangles out of ${8\choose 2}=28$ triangles that use vertex $0$.
So the probability of containing the center is $\frac{10}{28}=\frac{5}{14}$.


text:
Q: TypeScript: keyof unexpected behavior class Target {
  prop1 = "321";
}

const target = new Target()

class Target2 {
  prop2 = "123";
}

const target2 = new Target2()

type TValue<V extends object> = {
  target: V;
  key: keyof V;
}

class Case<V extends TValue<any>[]> {
  constructor(private values: V) {}
}

const someCase = new Case([
  {
    target: target,
    key: "123"
  },
  {
    target: target2,
    key: "prop2"
  }
])

The target type is successfully inferred, but the keyof is not working as expected. What am I doing wrong?
I also created a playground.

A: My previous answer  is similar to your use case, but it differs a bit because I have used a function and you are dealing with class.

type Entity<Obj, Key> = {
  target: Obj,
  key: Key
}

type IsValid<T extends Entity<any, any>[]> =
  /**
   * Infer each element of the array
   */
  T[number] extends infer Elem
  /**
   * Check if every element of the array extends Entity
   */
  ? Elem extends Entity<any, any>
  /**
   * Check if keyof Elem['object'] extends `key` property
   * 1) if [key] property is one of object properties - return true
   * 2) if at least one element does not meet your requirements return false | true,
   * because some element are ok
   */
  ? keyof Elem['target'] extends Elem['key']
  ? true
  : false
  : false
  : false;

// credits goes to https://stackoverflow.com/a/50375286
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
  k: infer I
) => void
  ? I
  : never;

// credits https://stackoverflow.com/users/125734/titian-cernicova-dragomir
type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;

type Validator<T extends boolean> =
  /**
   * If IsValid returns false | true (boolean) it means Error
   * otherwise - ok
   */
  IsUnion<T> extends true ?
  ['Dear developer, please do smth right']
  /**
   * I'm using empty array here, because
   * (...flag:[])=>any evaluates to function without arguments
   */
  : []

class Case<
  Value extends { [prop: string]: any },
  Key extends keyof Value,
  Data extends Entity<Value, Key>[],
  > {
  constructor(private values: [...Data], ...flag: [...Validator<IsValid<[...Data]>>]) { }
}

class Target {
  prop1 = "321";
}

const target = new Target()

class Target2 {
  prop2 = "123";
}

const target2 = new Target2()

const result = new Case([{
  target: target, key: 'prop1'
},
{
  target: target2, key: 'prop2'
}]) // ok

const result_ = new Case([{
  target: target, key: 'prop1'
},
{
  target: target2, key: 'prop1' // wrong
}]) // error

You can replace ['Dear developer, please do smth right'] with [never]
Here you can find more information about infering function arguments


text:
Q: How can I test that a value is "greater than or equal to" in Jasmine? I want to confirm that a value is a decimal (or 0), so the number should be greater than or equal to zero and less than 1.
describe('percent',function(){

  it('should be a decimal', function() {

    var percent = insights.percent;
    expect(percent).toBeGreaterThan(0);
    expect(percent).toBeLessThan(1);

  });

});

How do I mimic " >= 0 "?

A: You just need to run the comparison operation first, and then check if it's truthy.
describe('percent',function(){
  it('should be a decimal',function(){

    var percent = insights.percent;

    expect(percent >= 0).toBeTruthy();
    expect(percent).toBeLessThan(1);

  });
});

A: I'm late to this but posting it just in case some one still visits this question looking for answers, I'm using Jasmine version 3.0 and as mentioned by @Patrizio Rullo you can use toBeGreaterThanOrEqual/toBeLessThanOrEqual.
It was added in version 2.5 as per release notes - https://github.com/jasmine/jasmine/blob/master/release_notes/2.5.0.md
For e.g.
expect(percent).toBeGreaterThanOrEqual(1,"This is optional expect failure message");

or
expect(percent).toBeGreaterThanOrEqual(1);

A: Somewhat strangley this isn't basic functionality
You can add a custom matcher like this:
JasmineExtensions.js
yourGlobal.addExtraMatchers = function () {
    var addMatcher = function (name, func) {
        func.name = name;
        jasmine.matchers[name] = func;
    };

    addMatcher("toBeGreaterThanOrEqualTo", function () {
                   return {
                       compare: function (actual, expected) {
                           return {
                               pass: actual >= expected
                           };
                       }
                   };
               }
    );
};

In effect you're defining a constructor for your matcher - it's a function that returns a matcher object.
Include that before you 'boot'.  The basic matchers are loaded at boot time.
Your html file should look like this:
<!-- jasmine test framework-->
<script type="text/javascript" src="lib/jasmine-2.0.0/jasmine.js"></script>
<script type="text/javascript" src="lib/jasmine-2.0.0/jasmine-html.js"></script>

<!-- custom matchers -->
<script type="text/javascript" src="Tests/JasmineExtensions.js"></script>
<!-- initialisation-->
<script type="text/javascript" src="lib/jasmine-2.0.0/boot.js"></script>

Then in your boot.js add the call to add the matchers after jasmine has been defined but before jasmine.getEnv().  Get env is actually a (slightly misleadingly named) setup call.
The matchers get setup in the call to setupCoreMatchers in the Env constructor.
/**
 * ## Require & Instantiate
 *
 * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference.
 */
window.jasmine = jasmineRequire.core(jasmineRequire);
yourGlobal.addExtraMatchers();

/**
 * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference.
 */
jasmineRequire.html(jasmine);

/**
 * Create the Jasmine environment. This is used to run all specs in a project.
 */
var env = jasmine.getEnv();

They show another way of adding custom matchers in the sample tests, however the way it works is to recreate the matcher(s) before every single test using a beforeEach.  That seems pretty horrible so I thought I'd go with this approach instead.

A: I have run into the same issue today, and as it turns out, it is not that difficult to add a custom matcher for it. The main advantage of a custom matcher is that it can return meaningful messages when a test fails.
So here is the code for two matchers, .toBeAtLeast() and .toBeAtMost(), in case it helps someone.
beforeEach( function () {

  // When beforeEach is called outside of a `describe` scope, the matchers are
  // available globally. See http://stackoverflow.com/a/11942151/508355

  jasmine.addMatchers( {

    toBeAtLeast: function () {
      return {
        compare: function ( actual, expected ) {
          var result = {};
          result.pass = actual >= expected;
          if ( result.pass ) {
            result.message = "Expected " + actual + " to be less than " + expected;
          } else {
            result.message = "Expected " + actual + " to be at least " + expected;
          }
          return result;
        }
      };
    },

    toBeAtMost: function () {
      return {
        compare: function ( actual, expected ) {
          var result = {};
          result.pass = actual <= expected;
          if ( result.pass ) {
            result.message = "Expected " + actual + " to be greater than " + expected;
          } else {
            result.message = "Expected " + actual + " to be at most " + expected;
          }
          return result;
        }
      };
    }

  } );

} );

A: It was just merged in the Jasmine GitHub master branch my patch to add the matchers you need:
Add toBeGreatThanOrEqual and toBeLessThanOrEqual matchers
But I have no idea in which release it will be. In the while, you can try to use the code of my commit in your local Jasmine copy.

A: Using This Updated Formula:
toBeGreaterThanOrEqual
toBeLessThanOrEqual
Should Work!

A: The current version of Jasmine supports toBeGreaterThan and toBeLessThan.
expect(myVariable).toBeGreaterThan(0);

A: I figured I should update this since the API has changed in newer versions of Jasmine.  The Jasmine API now has built in functions for:

*

*toBeGreaterThanOrEqual

*toBeLessThanOrEqual

You should use these functions in preference to the advice below.
Click here for more information on the Jasmine matchers API

I know that this is an old and solved question, but I noticed that a fairly neat solution was missed.  Since greater than or equal to is the inverse of the less than function, Try:
expect(percent).not.toBeLessThan(0);

In this approach, the value of percent can be returned by an async function and processed as a part of the control flow.

A: I recommend use this Jasmine pluging:
https://github.com/JamieMason/Jasmine-Matchers

A: You can use the function least to check if a value is greater than or equal to some other value.
An alias of least is gte (great than or equal to). Vice versa, you can use lte (less than or equal to) to check the opposite.
So, to answer the question, you can do:
expect(percent).to.be.gte(0)


text:
Q: spring cloud and spring boot compatibility issue in pom.xml I'm getting this error when I'm trying to run my application

java.lang.NoSuchMethodError:
  org.springframework.boot.builder.SpringApplicationBuilder.([Ljava/lang/Object;)V

Please find below pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>test</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.5.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        <version>1.4.2.RELEASE</version>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

I hope this issue was related to spring cloud and spring boot version compatibility issue. Can someone please help me to resolve it?

A: Where possible, just use the latest versions to fix version issues.
Changing 1.4.2.RELEASE to 2.0.1.RELEASE works.
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    <version>2.0.1.RELEASE</version>
</dependency>

Ideally you should remove the version completely, let Spring Boot take care of it.

A: I tend to use dependency versions provided by Spring Cloud project in my dependencyManagement section: http://projects.spring.io/spring-cloud/
This way I don't have to manually put dependency versions and avoid problems like you just presented. Selecting dependency versions manually quickly becomes a huge pain and this approach uses versions that are tested by the community.
In case of Spring Cloud, Finchley release train works with Spring Boot 2.
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.0.1.RELEASE</version>
</parent>
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>Finchley.SR1</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
<dependencies>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  </dependency>
</dependencies>


text:
Q: Dynamic colours in chartJS based on entries in the array I have an issue trying to color my bar chart dynamically based on a JSON response.
I know this has been asked a number of times before but none of the answers I've found or tried to work thorugh have got me any closer to a solution.
I've created a quick JSfiddle to show the issue.
I have a number of other charts which are all generated from different JSON strings so have cut this down a lot to try and isolate the issue.  I don't have the same problem with the other charts as the number of entries in the Label array in consistent with the number of colours.  The offending piece of code is this;
DT_Labels.forEach(function(DT_LABELS, x) {
data.datasets.push({
    label: DT_LABELS,
    backgroundColor: backgroundColor[x],
    data: JSON.parse(DT_Values[x]).map(Number)
            });
            });

DT_Labels only contains a single entry as the chart is a summarised list - In theory, this would work if I counted the number of DT_Values but if I do that, I can't get the correct data in the chart.
Any ideas how I can reformat this to generate the colours counter based on the number of Values instead of Labels?

A: Change:
backgroundColor: backgroundColor[x],

to:
backgroundColor: backgroundColor,

Result:

Why does this work?
The backgroundColor property can be specified in a number of ways. Typically it's set to a string, e.g. #abcdef but it can also be set to an array. In this case Chart.js itself will pick the colour from the array based on the index of the data point it is drawing.


text:
Q: How can I moved a .js file in my react-native project to a different directory I am trying to rearrange my files and folders in an inherited project but to project fails to build when I move any of the files to another location.
The error I get is:
error: bundling failed: Error: ENOENT: no such file or directory, scandir '/Users/serdar/Work/tone-and-sculpt-front-end/screens/images'
    at Object.readdirSync (fs.js:887:3)
    at Object.getDirFiles (/Users/serdar/Work/tone-and-sculpt-front-end/node_modules/metro/src/node-haste/DependencyGraph.js:103:34)
    at Map._factory (/Users/serdar/Work/tone-and-sculpt-front-end/node_modules/metro/src/node-haste/AssetResolutionCache.js:41:36)
    at Map.get (/Users/serdar/Work/tone-and-sculpt-front-end/node_modules/metro/src/node-haste/lib/MapWithDefaults.js:23:24)
    at AssetResolutionCache.resolve (/Users/serdar/Work/tone-and-sculpt-front-end/node_modules/metro/src/node-haste/AssetResolutionCache.js:91:43)
    at resolveAsset (/Users/serdar/Work/tone-and-sculpt-front-end/node_modules/metro/src/node-haste/DependencyGraph.js:229:36)
    at resolveAssetFiles (/Users/serdar/Work/tone-and-sculpt-front-end/node_modules/metro-resolver/src/resolve.js:463:22)
    at resolveFile (/Users/serdar/Work/tone-and-sculpt-front-end/node_modules/metro-resolver/src/resolve.js:349:20)
    at resolveFileOrDir (/Users/serdar/Work/tone-and-sculpt-front-end/node_modules/metro-resolver/src/resolve.js:262:22)
    at resolveModulePath (/Users/serdar/Work/tone-and-sculpt-front-end/node_modules/metro-resolver/src/resolve.js:184:18)

I have checked the file paths being referenced in other files and cant find a problem.
Also the file in the error message doesn't actually exist '/screens/images/' so don't know where that came from/
Any troubleshooting steps you can think of?
I have restarted VS code, the metro bundler, reset cache etc etc.