text:
Q: How to select rows based on how many consecutive times a number is present in a column? I have a file that looks like this:
chr1    3000823 3000829 1
chr1    3001003 3001009 1
chr1    3001014 3001020 1
chr1    3001273 3001279 2
chr1    3001625 3001631 3
chr1    3003222 3003228 4
chr1    3003335 3003341 4
chr1    3003375 3003381 4
chr1    3003578 3003584 4
chr1    3003636 3003642 4
chr1    3003717 3003723 4
chr1    3003881 3003887 4
chr1    3003894 3003900 4
chr1    3004526 3004532 5
chr1    3005994 3006000 6
chr1    3006183 3006189 6
chr1    3006412 3006418 7
chr1    3006778 3006784 8
chr1    3006877 3006883 8
chr1    3007166 3007172 9
chr1    3007426 3007432 10
chr1    3007528 3007534 10
chr1    3007576 3007582 10

And I would like to take only the rows that contain a specific number of times any number in the 4th column.
Lets say I would like to take rows that have 3 times the same number in the 4th column so the output would be:
chr1    3000823 3000829 1
chr1    3001003 3001009 1
chr1    3001014 3001020 1
chr1    3007426 3007432 10
chr1    3007528 3007534 10
chr1    3007576 3007582 10

..this is because these rows have the number 1 and 10 that is present 3 times in the 4th column
Any idea would be very appreciated.
Thanks!

A: A solution with awk:
awk 'FNR==NR{c[$4]++;next;} c[$4]==3' file.dat file.dat

Output:
chr1    3000823 3000829 1
chr1    3001003 3001009 1
chr1    3001014 3001020 1
chr1    3007426 3007432 10
chr1    3007528 3007534 10
chr1    3007576 3007582 10

Explanation:

*

*FNR==NR: This test is true when the number of records is equal to the number of records in the file. This is only true for the first file, for the second file NR will be equal to the number of lines of file1 + FNR.

*c[$4]++: Increment an array element index by $4. I use this as a counter.

*next: Skip to the next record without doing anything else.

*c[$4]==3: This only happens on records of the second file. If this test succed the line will be printed, since print is the default action in awk.

This code has the disadvantage to read the file twice, but in my opinion it's a clean and easy to understand way to do this job.

A: {
  i = int(count[$4])
  arr[$4,i] = $0
  count[$4]++
}

END {
  for (i in count) {
    if (count[i]== n) {
      for (j=0; j<n; j++) {
        printf("%s\n", arr[i,j])
      }
    }
  }
}

sample run --

awk -v n=3 -f 1.awk 1.dat
chr1 3007426 3007432 10
chr1 3007528 3007534 10
chr1 3007576 3007582 10
chr1 3000823 3000829 1
chr1 3001003 3001009 1
chr1 3001014 3001020 1

awk -v n=8 -f 1.awk 1.dat
chr1 3003222 3003228 4
chr1 3003335 3003341 4
chr1 3003375 3003381 4
chr1 3003578 3003584 4
chr1 3003636 3003642 4
chr1 3003717 3003723 4
chr1 3003881 3003887 4


text:
Q: Login in Oracle DB Do I have to surround the user id or the password with special chars or does it work like this**:**
con.ConnectionString = "User Id=uid;Password=pSw;Data Source=(DESCRIPTION=(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1234)))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = db)))";
In case of which special character I have to use the escape sequence?

A: It has to be like this:
con.ConnectionString = "USER ID=uid;PASSWORD=pSw;Data Source=(DESCRIPTION=(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1234)))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = db)))";

redpajama_set_name: RedPajamaStackExchange


text:
Q: paypal Adaptive Payment from my custom webservice for an mobile application Can i perform adaptive payment without going to the paypal site.I also can not use the implicit payment as i have to make a paypal chained payment from server site(i.e. webservice) for an ios application.

A: You can setup Adaptive Payments with an iframe or pop-up as oppose to the full redirect if you want.  They call it "Embedded Payments" and you can get more details about it here:  https://developer.paypal.com/webapps/developer/docs/classic/adaptive-payments/integration-guide/APIntro/

A: I've found that some mobile devices block the popup with the Lightbox embedded flow.  I now use the mini browser experience for mobile web.
More information regarding the mini browser experience (expType=mini) can be found here:
Adaptive Payments without modal box or popups?


text:
Q: static Finder from parent class I'm annoyed of adding static Finders to all my Model classes.
Why isn't it possible to do this:
@MappedSuperclass
public class MyModel<T> extends Model {

    public static Finder<Integer,T> FIND = new Finder<Integer, T>(Integer.class,T.class);

}

@SuppressWarnings("serial")
@Entity
public class ValidationScript extends MyModel<ValidationScript> {

    @Id
    public Integer id;

    @Column(length = 5000)
    public String scriptCode;

}

A: I spent some time to search a solution because I have the same problem but this is not a problem related to Play/Ebean.
Unfortunately you can not do this in Java. By design, a static field is shared by all suclasses (the same object!). And of course you cannot have an object with multiple types!
The generics are used at compile time to check the correctness of the methods invocation:
http://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html
The solution you proposed with the use of generics cannot work because the static field/method cannot access the type (all instance may have a different type).
In your case the field FIND is shared for all the subclasses of MyModel.

I tried to convert you field in a static method finder() and to create a "finder pool" with a static hashmap class/finder but you must anyway provide the class like this  MyModel.finder(ValidationScript.class) because the invoker is always the superclass.
Too much verbose...

A: The template is quite easy. Use this template instead manual adding @Id field and Finder
@javax.persistence.Id
public $ID$ id;

public static Finder<$ID$, $CL$> find
        = new Finder<$ID$, $CL$>($ID$.class, $CL$.class);

After paste it in template's editor click Edit variables and set expression for CL to className()
take a look at the screenshots


text:
Q: Create dynamic playlist in ffmpeg I want to stream videos countinuously so I create this playlist (test.txt)
file 'test1.mp4'
file 'test2.mp4'
file 'test3.mp4'
and I use this command in ffmpeg to run playlist
ffmpeg -re -f concat -i test.txt -b:v 2.5M -c:v libx264 -acodec aac -f mpegts udp://127.0.0.1:1234?pkt_size=188&buffer_size=3M

But is there a way to add files to run after this playlist without interrupt streaming or Make the process moves to another playlist When the first one ends
I am looking for any way to stream other movies after playlist finish during the process running (without interrupt streaming)
please help me


text:
Q: как сохранять правильно в БД если один тот самый клиент будет клиентом у разных сотрудников а также с разных компаний? на сайте может быть много компаний
У компаний может быть много сотрудников
У сотрудников может быть много клиентов
так вот если сделать что клиент добавленный сотрудником сохранится в БД
если этот же клиент придет до второго сотрудника через время то сохранить его нужно повторно тоесть в БД будет 2 строчки того самого клиента имя и телефон а если будет много компаний и этот клиент к примеру будет у 100 компаниях тоесть 100 строк того самого телефона и имени это нормально?
Или если сделать что клиент добавляется один раз в БД
а уже при добавлении из какой либо компании каким то сотрудником  этого же клиента то просто он привязывается к этому клиенту также

A: Введите дополнительную таблицу для связи клиент-компания. Если клиент новый, то добавляются две записи: в таблицу клиентов и в таблицу связи клиент-компания. Если такой клиент уже есть, то добавляется только запись в таблицу связи.
Компаниям не нужно сообщать о чужих записях в таблице связи.
Но если в таблице связи уже есть запись, что данный клиент уже связан с данной компанией, нужно выводить сообщение, что такой клиент уже есть.


text:
Q: How to Move all files within a single directory to multiple directories? I have a directory that contains files I need from a calculation (6.00-film2) and I have 10 other directories, each with 10 sub-directories that I would like these files copied into. Is there an easier way of doing this rather than doing
cp -r 6.00-film2/ 5.5-film/5.5-1

100 times.
The directory 5.5-film contains 5.5-1, 5.5-2, 5.5-3, 5.5-4, 5.5-5, ..., 5.5-10. I need the files from 6.00-film2 to be copied into each of the 10 directories above, how would I go about doing that?

A: cp can copy from multiple sources, but can't copy to multiple destinations. See man cp for more info.
The only bash command that I know which can copy/save to multiple destinations is tee.
You can use it as follows:
tee ~/folder1/test.txt ~/folder2/test.txt < ~/test.txt

Note that tee also writes the input to the standard output (stdout). So if you don't want this, you can prevent it by redirecting standard output to /dev/null as follow:
tee ~/folder1/test.txt ~/folder2/test.txt < ~/test.txt >/dev/null


text:
Q: Generically Binding Values with ngModel I am just learning Angular 2 and one issue I've been unable to tackle is creating forms with ngModel without statically specifying the name of the attribute I am binding to.
I am unsure of the mechanisms for overcoming this problem (though I am sure it's common enough) or how it's referred to within the community.
My template does display the keys and values but it doesn't reflect the updates on save. It seems like referring to the attribute in a dynamic way causes the binding to be lost. (Is it evaluating the bound attribute before piping the data?)
Here is where I am stuck:
Template:

    {{ prop.key }}

    // Problem here:
    // if I have [(ngModel)]="prop.key", it only displays the keys
    // if I sub in a static attribute e.g. [(ngModel)]="account.accountName" it works
    <input name="{{prop.key}}"  [(ngModel)]="prop.value" />

Pipe:
@Pipe({
    name: 'keyValues'
})
@Injectable()
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    }
    return keys;
  }
}

Component:
  ... boiler plate ...

  save(): void {
    this.accountsService.update(this.account)
      .then(() => this.goBack());
  }

  ...

A: Answer is to use Angular's Dynamic Forms
You can also leverage certain libraries like PrimeFaces' PrimeNG's editable datatable, which I highly recommend!


text:
Q: Command-line / Virtual terminal issue I've recently got into Ubuntu, still learning using the terminal. I decided to try initiating the command-line on boot by editing boot commands to quiet splash text or quiet splash nomodeset only to find that neither works. I've tried starting the virtual terminal with CTRL + ALT + F(1-6) - again, with no success. Using the text line, I get a blank black screen on boot. Using the nomodeset line, I get a somewhat random color on my screen. CTRL + ALT + F(1-6) goes into a blank black screen as well, similar to the text boot. I've tried suggested fixes , however, with no success. Any help would be appreciated.
Regards

A: by pressing shift on starting, boot and from grub menu select recover mode and drop to root shell prompt.
open /etc/default/grub as and add text to the
nano /etc/default/grub

And in the file, change this line:
GRUB_CMDLINE_LINUX_DEFAULT="text"
Then update your Grub
update-grub

and
reboot

Your system will then boot to text mode.
If you once want to use GUI you can easly make light works
sudo service lightdm start

hope this will work for you
http://www.iasptk.com/ubuntu/20348-ubuntu-login-to-text-mode-without-removing-gui


text:
Q: firebase AnimatedList dbRef error undefined name
dbRef error please help me whats problem is this
query dbRf undefined name why?

A: listItem is a method inside your class, therefore when you declare a variable inside that method then that variable which is in this case dbRef is only accessible from that method.
If you want to access dbRef in multiple methods, then you need to add it as an instance variable to the class.
You can read this documentation to understand more:
https://dart.dev/guides/language/language-tour


text:
Q: node js mongoose express-fileupload replacing error I'm creating an upload for a project. So i created two routes for my upload. 1st is when the user registration part will upload an image the 2nd one is if a driver adding a vehicle he can add a image of the vehicle.
The problem is when i run a function for the 1st time it works as i expected. but if i run the other router after running any of those function. the file replace as the last uploaded file name. so please help me to fix it
here is the user registration upload function
if(req.files.file.name.split('.').pop() == 'jpg' ||
    req.files.file.name.split('.').pop() == 'jpeg' ||
    req.files.file.name.split('.').pop() == 'png') {
    Uploads
    .findOne({}, {}, { sort: { 'created_at' : -1 }},
    function(err, last){
        if(err) throw err;
        if(!last) {
            Uploads
            .create({
                filename: fileName + '.' + extension,
                path: licenseImg
            },
            function(err, license){
                if(err) throw err;
                Driver
                .create({
                    driver_id: user._id,
                    driving_license_copy: license._id
                },
                function(){
                    req.files.file.mv(licenseImg + req.files.file.name, function(err){
                        if(err) return res.status(500).send(err);
                        fs.rename(licenseImg + req.files.file.name, licenseImg + fileName + '.' + req.files.file.name.split('.').pop(), function(err){
                            if(err) throw err;
                            config.sendWithHash(
                                user.email,
                                'Verify Your account',
                                'Please click the link down below to verofy your account \n http://localhost:1200/user/verify/email/',
                                user.NIC + user.phone + user.email
                            );
                            res.send({
                                message: 'New user created, Please verify your email first',
                            });
                        })
                    })
                });
            });
        }
        else {
            var filename = last.filename;
            var renamedName = filename.split('_')[0] + "_" + parseInt(parseInt(filename.split('.')[0].substr(filename.split('.')[0].lastIndexOf('_')+1))+1);
            console.log(filename);
            console.log(renamedName);
            Uploads
            .create({
                filename: renamedName + '.' + extension,
                path: licenseImg
            },
            function(err, license){
                if(err) throw err;
                Driver
                .create({
                    driver_id: user._id,
                    driving_license_copy: license._id
                },
                function(){
                    req.files.file.mv(licenseImg + req.files.file.name, function(err){
                        if(err) return res.status(500).send(err);
                        fs.rename(licenseImg + req.files.file.name, licenseImg + renamedName + '.' + req.files.file.name.split('.').pop(), function(err){
                            if(err) throw err;
                            config.sendWithHash(
                                user.email,
                                'Verify Your account',
                                'Please click the link down below to verofy your account \n http://localhost:1200/user/verify/email/',
                                user.NIC + user.phone + user.email
                            );
                            res.send({
                                message: 'New user created, Please verify your email first',
                            });
                        })
                    })
                });
            });
        }
    });
}
else {
    res.send('Cannot upload that type of files');
}

this is the other upload function executes where the driver adding a vehicle
Uploads
.findOne()
.sort({ 'created_at' : -1})
.exec(function(err, last){
    if(err) throw err;
    var filename = last.filename;
    var filePath = './public/uploads/vehicles/';
    var extension = last.filename.split('.').pop();
    var renamedName = filename.split('_')[0] + "_" + parseInt(parseInt(filename.split('.')[0].substr(filename.split('.')[0].lastIndexOf('_')+1))+1);
    console.log(last);
    console.log(filename);
    console.log(renamedName);
    Uploads
    .create({
        filename: renamedName + '.' + extension,
        path: filePath
    },
    function(err, vehicleImg){
        if(err) throw err;
        Vehicle
        .create({
            driver_id: req.decoded._doc._id,
            make: req.body.make,
            model: req.body.model,
            year: req.body.year,
            registration_no: req.body.reg_no,
            vehicle_img: vehicleImg._id
        },
        function(){
            req.files.file.mv(filePath + req.files.file.name, function(err){
                if(err) return res.status(500).send(err);
                fs.rename(filePath + req.files.file.name, filePath + vehicleImg.filename, function(err){
                    if(err) throw err;
                        res.send({
                            message: 'Vehicle added',
                        });
                    });
                });
            });
        });
    });

So here is all of the code that error coming from. if anybody knows why is that, please let me know how to fix it
thank you


text:
Q: How to update Xcode to 11.0, currently I am using macOS High Sierra (version 10.13.6), I can't update my macOS How to install Xcode 11, In macOS High Sierra (version 10.13.6)
Hello I am a student, Eagerly learning ios Development, I bought the second hand mac from amazon, its pitts old, currently I am using macOS High Sierra (version 10.13.6), and Xcode Version 10.1. I can't able to upgrade to Xcode 11 due to old laptop. Due to this i can't learn swift 5, and I can't purchase new laptop
I tried couple of solutions from google answers but nothing worked for me,
error: SWIFT_VERSION '5.0' is unsupported, supported versions are: 3.0, 4.0, 4.2.

A: Before updating the xcode first you need to update the mac os by below steps & then update the Xcode it will work just fine

*

*Download the latest version of the Catalina patch here. Open the Catalina Patcher app.

*Click Continue.

*Choose Download a Copy.

*The download (of Catalina) will start - since it's almost 8GB it is likely to take a while.

*Plug in a flash drive.

*Choose 'Create a bootable installer' from the options.

*Plug the bootable installer into the Mac you wish to update.

*Restart the Mac while holding the Option/Alt key. This will cause the Mac open in Startup Manager.

*Choose the bootable installer drive and Enter.

*Now your Mac should open in Recovery.

*Choose Reinstall macOS and wait for the new version of macOS to install.

*After the installation has completed, you should restart the Mac in Recovery mode again, choosing the drive that contains the bootable installer.

*Now choose macOS Post Install and the required patches will be installed on your Mac so that Catalina can work.

*When the patches have been applied to choose Force Cache Rebuild.

*Restart.

I also suggest you go through this video.


text:
Q: What is a minimal set of unicode characters for reasonable Japanese support? I have a mobile application that needs to be ported for a Japanese audience. Part of the application is a custom font file that needs to be extended from only containing latin-1 characters to also containing Japanese characters. I realise that this will make it rather large, but that is not todays problem.
Note that I have no control over the text to be displayed by this application, so it needs to be able to support enough to be able to display user-generated content.
Here is what I believe to be a maximal set of unicode ranges that would cover anything required of it.
 Compatability                         U+3300  -  U+33FF
 Compatability forms                   U+FE30  -  U+FE4F
 Compatability ideographs              U+F900  -  U+FAFF
 Compatability ideographs supplement  U+2F800  - U+2FA1F
 Radicals supplement                   U+2E80  -  U+2EFF
 Strokes                               U+31C0  -  U+31EF
 Symbols and punctuation               U+3000  -  U+303F
 Unified Ideographs                    U+4E00  -  U+9FBB
 Unified Ideographs ext. A             U+3400  -  U+4DB5
 Unified Ideographs ext. B            U+20000  - U+2A6D6
 Enclosed letters and months           U+3200  -  U+32FF
 Hiragana                              U+3040  -  U+309F
 Kanbun                                U+3190  -  U+319F
 Katakana                              U+30A0  -  U+30FF
 Katakana phonetic                     U+31F0  -  U+31FF

What I need to know is:

*

*Is anything missing from this list?

*Is anything obviously not required?

*Is anything arguably non-essential, and why could it be argued as such?

A: Summary of Essential Characters

Enclosed Alphanumerics                U+2460  -  U+2473
            "                         U+2474  -  U+24E9*
            "                         U+24EA  -  U+24FF
Miscellaneous Symbols                 U+2600  -  U+2607
            "                         U+2618  -  U+2618
            "                         U+260E  -  U+260F
            "                         U+2614  -  U+2615
            "                         U+263D  -  U+2653
            "                         U+2660  -  U+266F
Symbols and punctuation               U+3000  -  U+303F
Hiragana                              U+3040  -  U+309F
Katakana                              U+30A0  -  U+30FF
Katakana phonetic                     U+31F0  -  U+31FF
Enclosed letters and months           U+321F  -  U+325F*
            "                         U+3280  -  U+32FF*
Unified Ideographs ext. A             U+3400  -  U+4DB5
Unified Ideographs                    U+4E00  -  U+9FBB
Compatability ideographs              U+F900  -  U+FAFF
Compatability forms                   U+FE30  -  U+FE4F
Full-Width Roman                      U+FF00  -  U+FF5E
Half-Width Katakana                   U+FF61  -  U+FF9F
Full- and Half-Width Symbols          U+FFE0  -  U+FFEE
Unified Ideographs ext. B            U+20000  - U+2A6D6
Compatability ideographs supplement  U+2F800  - U+2FA1F

* = Lower priority

Full Explanation
Don't forget the full-width Roman, which are used often for the Roman alphabet in Japanese (FF00-FF5E) and half-width Katakana pages (FF61-FF9F). You will probably also need the full- and half-width symbols (FFE0-FFEE).
An argument can be made that the Kanbun annotation page (3190-319F) will generally not be used. Kanbun is and old style of Japanese which uses all Chinese characters (no Hiragana or Katakana) with a different set of grammar rules, generally taught at school. These annotation marks will not be used unless someone is trying to explain how to read/understand one of these passages, which is probably unlikely. It could be included for completeness, but probably is not a high priority.
CJK Compatability (3300-33FF) is generally used by newspapers in print media, but will almost certainly not be used by the average public (I have yet to see one on a website). In either event, they have equivalent long forms (e.g. ㌘ can be written as グラム instead), so this is also in the non-essential category.
CJK Radicals Supplement (2E80-2EFF) is also non-essential, but could be used. They are not complete characters, but the "radical" (base part) of characters. They could be used to explain the derivation of a character, but unlikely to be used in normal application of the language.
CJK Strokes (31C0-31E3) is the same as the CJK Radicals Supplement, and probably has an even less likelyhood of being used in everyday application.
The first part of Enclosed CKJ Letters and Months (3200-321E) are unnecessary. They are Korean symbols. Same with (3260-327F). The rest of the page has a low usage rate, but I would include it for completeness because someone will probably try to use one occasionally. But you can consider them lower priority.
The rest you have called out in your original list are essential.
Also missing from the list is Enclosed Alphanumerics (2460-24FF). The circled numbers (2460-2473 and 24EA-24FF) are used relatively frequently. The circled alphabet, parenthesized numbers, and numbers period (2474-24E9) could be omitted as non-essential, however.
Also, you would do well to include Miscellaneous Symbols (2600-263C), although some are used more often than others. Absolutely essential ones include some of the weather symbols (2600-2607), shamrock (2618), the telephones (260E-260F), umbrella and hot drink (2614-2615), Astrological and Zodiac symbols (263D-2653), and playing cards, hot springs, and musical symbols (2660-266F).

A: Technically speaking, you should include:
1. Arabic numerals (0,1..9)
2. English Punctuation (!"#$%'...)
3. Roman letters (A..Z, a..z) (Half-Width, and Full-Width)
1-3 basically means ASCII support.

*

*Hiragana

*Katakana

*Japanese Punctuation

*Joyo Kanji (This is the list of about 2000 Kanji approved by the Japanese government for use in newspapers, etc.)

*Name Kanji (Another list compiled by the Japanese government for proper names).

All together, that will give you 2600 kanji or something like that, and you will be able to represent most normal stuff you could find on the web.  There are some minor exceptions where characters are common but not in Joyo (f.e. 沢).
The problem is that Unicode isn't exactly organized around the Joyo kanji list, so you would have to pick and choose within the ranges.  It's probably just easier to include every kanji that exists in Japanese, even if it isn't frequently used or part of Joyo.


text:
Q: Bootstrap non collapsable navbar with dropdowns I am trying to create navbar which is not responsive and have some dropdowns
I am able to make it non responsive via below css.But if i click the drop downs in navbar in mobile it messes up.Here is the bootply http://www.bootply.com/k9wnO3WaO4 , Try the mobile view and click todo to recreate this problem.

sample dropdown

Todo 0

4:00 AMFavourites Snippet

4:30 AMEmail marketing

5:00 AMSubscriber focused email
                            design

View All

A: There is one media query responsible for the behavior that I think you don't like.
It is in css the following media query:
@media (max-width: 767px) {
    .navbar-nav .open .dropdown-menu {
         background-color: transparent;
         border: 0 none;
         box-shadow: none;
         float: none;
         margin-top: 0;
         position: static;
         width: auto;
    }
...
}

Just override the style like in the following css:
.navbar-nav .open .dropdown-menu {
    background-color: #fff;
    border: 1px solid rgba(0, 0, 0, 0.15);
    border-radius: 4px;
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.176);
}

You can find your updated Bootply here.
In the demo below I had to add !important to the background color. Not sure why because at Bootply that isn't required.

.navbar-collapse.collapse {
display: block!important;
}

.navbar-nav>li, .navbar-nav {
float: left !important;
}

.navbar-nav.navbar-right:last-child {
margin-right: -15px !important;
}

.navbar-right {
float: right!important;
}

.navbar-nav .open .dropdown-menu {
 background-color: #fff !important;
    border: 1px solid rgba(0, 0, 0, 0.15);
    border-radius: 4px;
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.176);
    position: static;
}

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>

 0

Chat

Todo 0

4:00 AMFavourites Snippet

4:30 AMEmail marketing

5:00 AMSubscriber focused email
                            design

View All

Profile

Settings

Logout


text:
Q: html 5 input for Amount money I am trying to create an input box in HTML 5 that meets the below set of parameters:

*

*It should contain only numbers

*Should contain minimum of 3 numbers

*Should not contain any characters or special characters

*Should not begin with 0

Below is the code:
<input type="number" name="txtAmount" pattern="^[0-9]{3,}" title="Amount must contain a minimum for 3 numbers. It cannot contain Characters or Special Characters" class="form-control" placeholder="Enter Amount" required/>

Please advice, Thanks in advance.
Rajiv

A: <input  pattern="[^0][0-9]{3,}"   required title="Amount must contain a minimum for 3 numbers. It cannot contain Characters or Special Characters">


text:
Q: Crawling over a website directories using BeautifulSoup? This is my code:
https://pastebin.com/R11qiTF4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as req
from urllib.parse import urljoin
import re

urls = ["https://www.helios-gesundheit.de"]
domain_list = ["https://www.helios-gesundheit.de/kliniken/schwerin/"]
prohibited = ["info", "news"]
text_keywords = ["Helios", "Helios"]
url_list = []

desired = "https://www.helios-gesundheit.de/kliniken/schwerin/unser-angebot/unsere-fachbereiche-klinikum/allgemein-und-viszeralchirurgie/team-allgemein-und-viszeralchirurgie/"

for x in range(len(domain_list)):
    url_list.append(urls[x]+domain_list[x].replace(urls[x], ""))

print(url_list)

def prohibitedChecker(prohibited_list, string):
    for x in prohibited_list:
        if x in string:
            return True
        else:
            return False
        break

def parseHTML(url):
    requestHTML = req(url)
    htmlPage = requestHTML.read()
    requestHTML.close()
    parsedHTML = soup(htmlPage, "html.parser")
    return parsedHTML

searched_word = "Helios"

for url in url_list:
    parsedHTML = parseHTML(url)
    href_crawler = parsedHTML.find_all("a", href=True)
    for href in href_crawler:
        crawled_url = urljoin(url,href.get("href"))
        print(crawled_url)
        if "www" not in crawled_url:
            continue
        parsedHTML = parseHTML(crawled_url)
        results = parsedHTML.body.find_all(string=re.compile('.*{0}.*'.format(searched_word)), recursive=True)
        for single_result in results:
            keyword_text_check = prohibitedChecker(text_keywords, single_result.string)
            if keyword_text_check != True:
                continue
            print(single_result.string)

I'm trying to print the contents of ''desired'' variable. The problem is the following, my code doesn't even get to request the URL of ''desired'' because its not in the website scope. ''desired'' href link is inside another href link that's inside the page I'm currently scraping. I thought I'd fix this by adding another for loop inside line 39 for loop, that requests every href found in my first, but this is too messy and not efficient
Is there way to get a list of every directory of a website url?


text:
Q: Showing that $F_1(x)=\sum^{\infty}_{n=-\infty} f(x+n)$ is continuous for $f$ a Schwartz function on the real line
Given a Schwartz function $f\in S(\mathbb{R})$ on the real line, we can construct a new function on the circle by the recipe
$$F_1 (x)=\sum ^{\infty}_{n=-\infty} f(x+n)$$
Since $f$ is rapidly decreasing, the series converges absolutely and uniformly on every compact subset of $\mathbb{R}$, so $F_1$ is continuous.

Could someone please explain what theorem are we using here? How do we rigorously show that $F_1$ is absolutely and uniformly convergent? (I think intuitively it is very true, especially given that $F_1$ is periodic, but I have trouble proving it)

A: There exists $C \in (0,\infty)$ such that $|x^{2}f(x)| \leq C$. For $0\leq x\leq T$ this gives $|f(x+n) | \leq \frac  C {(x+n)^{2}} \leq \frac C {n^{2}}$. Apply M-test to see that the series converges uniformly on $[0,T]$ for any $T>0$. I will leave $x<0$ to you.


text:
Q: Github Action: How to pull LFS files in submodule My project contains a submodule that holds LFS files:
mainproject/
   submodule/
     path/to/lfs/file

QUESTION: How do I ensure the LFS files in the submodule are pulled?  (Currently they aren't)
In my main.yml file, I do the following:
jobs:
    steps:
...
    - uses: actions/checkout@v2
      with:
        lfs: true
        token: ${{ secrets.ACCESS_TOKEN }}
        submodules: recursive
        fetch-depth: 0

This used to work, but I started getting errors a few weeks ago that I root-caused to the LFS files not being pulled.

A: This is really weird and appears to be undocumented.
I did a little bit of fishing inside my self-hosted runner, and it turns out there's a _work/ inside the github-runner directory where the runner clones repos.  This folder gets mapped to /_work/ when running inside a Docker container.
Somewhere along the way, the repos must have broken and git lfs pull stopped updating the latest files.
The solution was to log into the runner and wipe out the repos from under _work/.


text:
Q: Non-subdifferentiable convex function on a normed space Is there any convex function $f$ on a normed space $X$ such that $\partial f(x)=\emptyset$ at every $x\in X$?

A: From Rockafellar's Convex Optimization book, Theorem 23.3:

Let $f$ be a convex function, and let $x$ be a point where $f$ is finite.  If $f$ is subdifferentiable at $x$, then it is proper.  If $f$ is not subdifferentiable at $x$, there must be some infinite two-sided directional derivative at $x$, i.e. there must exist some $y$ such that $f'(x;y) = -f'(x,-y) = -\infty$.

Additionally, Rockafellar Theorem 23.4 says that if $f$ is a proper convex function, then if $x \in \text{ri} (\text{dom} f)$ then $\partial f(x)$ is non-empty.
Or in other words, if you have a proper convex function with a non-empty relative interior, then there is at least one point where it is subdifferentiable.
To construct an example of a convex function that is never subdifferentiable, we can build a function that has no relative interior and whose directional derivative in its domain is always infinite in at least one direction.
I believe this is one such example:
$$
f(x) = \begin{cases}
   -\infty & \text{if } ||x||<1, \\
   0 & \text{if } ||x|| =1, \\
   +\infty & \text{if } ||x||>1
  \end{cases}
$$

A: A convex function must be subdifferentiable on the relative interior of its domain (where it is finite). So the only points where one can have an issue is the boundary of its domain.
The function constructed by Kevin Holt is one where all of the domain is boundary--hence Theorem 23.4 in Rockafellar's Convex Analysis cannot be used.
As another illustration of how things can go badly at boundary points, consider the function $$g(x) = \left\{ \begin{array}{cc} 1-\sqrt{x} & x \geq 0 \\ \infty & \text{otherwise} \end{array} \right.$$
which is convex and defined at $0$, but not subdifferentiable there. A linear equation tangent to $g$ at $0$ must have infinite slope.


text:
Q: Quickly digitising several polygons based on classified raster output using ArcGIS Spatial Analyst I have a raster DTM of a river which I would like to split into 90 sections, each measuring 125m. I have used Euclidean Distance to outline each section by reclassifying the symbology to change colour at each appropriate interval. I would now like to extract each coloured section from the Euclidean Distance symbology to create individual rasters.
Is there a quick way to do this without having to manually cut around each section?
Here is what I am looking at

A: You can use the Extract by Attributes tool in the Spatial Analyst toolbox to create a new raster from a range of data.  You will need to sort out ModelBuilder iterators, or loop the Extract by Attributes tool with Python to get each of your classifications into different files.


text:
Q: Why don't first_name and last_name appear when you print_r the WP_User object? Here's some simple code,
$user = get_userdata(5);
print_r($user);
echo $user->first_name;

And the result,
WP_User Object
(
[data] => stdClass Object
    (
        [ID] => 9
        [user_login] => adam@corolla.com
        [user_pass] => $P$Bck6WbL2RpNuUt4VjZGIp525jccfkE/
        [user_nicename] => adamcorolla-com
        [user_email] => adam@corolla.com
        [user_url] =>
        [user_registered] => 2016-04-14 20:35:51
        [user_activation_key] =>
        [user_status] => 0
        [display_name] => addycorolla
    )

[ID] => 9
[caps] => Array
    (
        [subscriber] => 1
    )

[cap_key] => fccv_capabilities
[roles] => Array
    (
        [0] => subscriber
    )

[allcaps] => Array
    (
        [read] => 1
        [level_0] => 1
        [subscriber] => 1
    )

[filter] =>
)

Adam

Why does echo $user->first_name work when the property isn't listed in the print_r?

A: first_name and last_name are not the part of _users table it is user metadata. Therefore, user object does not have it. So when you access the property first_name user object has a PHP magic method __get()
/**
 * Magic method for accessing custom fields
 *
 * @since 3.3.0
 * @param string $key
 * @return mixed
 */
public function __get( $key ) {
    if ( 'id' == $key ) {
        _deprecated_argument( 'WP_User->id', '2.1', __( 'Use WP_User->ID instead.' ) );
        return $this->ID;
    }

    if ( isset( $this->data->$key ) ) {
        $value = $this->data->$key;
    } else {
        if ( isset( self::$back_compat_keys[ $key ] ) )
            $key = self::$back_compat_keys[ $key ];
        $value = get_user_meta( $this->ID, $key, true );
    }

    if ( $this->filter ) {
        $value = sanitize_user_field( $key, $value, $this->ID, $this->filter );
    }

    return $value;
}

Which query the metadata and return the value from _usermeta table.


text:
Q: How to toggle case of Entire string in sql I want to toggle case of entire string.
I am able to do for characters, not for string.
DECLARE @Char AS VARCHAR(1)
SET @Char='a'
IF ASCII(@Char)>=97 AND ASCII(@Char) <=122
PRINT UPPER(@Char)
IF ASCII(@Char)>=65 AND ASCII(@Char) <=90
PRINT LOWER(@Char)

How, I can change case for entire string?
For Ex. "AbCdE", I want to change it to "aBcDe".

A: You can do it by creating functions:
First make function for one character:
CREATE FUNCTION ToggleChar
(
@Char VARCHAR(1)
)
RETURNS VARCHAR(1)
AS
BEGIN
RETURN CHAR(ASCII(UPPER(@Char))+ASCII(LOWER(@Char))-ASCII(@Char))
END

Then, create function for string:
CREATE FUNCTION ToggleCase
(
@Str VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @ResultStr VARCHAR(MAX)
SET @ResultStr=''
WHILE ( @Str<>'')
BEGIN
SET @ResultStr=@ResultStr + [dbo].[ToggleChar](@Str)
SET @Str= SUBSTRING(@Str,2,LEN(@Str))
END
RETURN @ResultStr
END

Now, use this function to toggle string.
SELECT dbo.ToggleCase('AbCdE') AS ToggleString

A: Try this:
DECLARE @Name VARCHAR(10) = 'SaMplE'
DECLARE @Count INT = 1
WHILE @Count <= LEN(@Name)
BEGIN
    SET @Name = STUFF(@Name, @Count, 1,
                CASE
                    WHEN ASCII(SUBSTRING(@Name,@Count,1)) BETWEEN 97 AND 122 THEN
                        UPPER(SUBSTRING(@Name,@Count,1))
                    WHEN ASCII(SUBSTRING(@Name,@Count,1)) BETWEEN 65 AND 90 THEN
                        LOWER(SUBSTRING(@Name,@Count,1))
                END)
    SET @Count = @Count + 1
END

SELECT @Name


text:
Q: How can I prevent Facebook Connect isUserConnected function from running twice in jQuery? I've got a bit of a problem with a Facebook integration.
When my users click a link, a function checks if a user is logged into Facebook. If they are not logged in, I set a piece of data, and then run the Facebook login stuff. When Facebook returns that they login, I go check the piece of data that was stored and run the original function they selected.
The problem:
The Facebook function runs twice. There are some comments on their message boards about this issue, but it seems this has been an issue since the beginning of connect, and it isn't being addressed.
So, I don't want to wait for Facebook. Is there any way for me to prevent the function from calling my function more than once?
Can I set something that says 'run once'? The problem being that once it runs once, if the user clicks again, I will need to run it again, so I can't completely disable the function (even if that were possible).

A: This is pretty hack-ish, but it should get around the issue of Facebook calling your function twice.  Since there's no code, I'm going to make some up for the purpose of my solution.  Also, I'm assuming that the facebook login code has a callback (how else would it be calling your function twice?).
// This function is what is called when the link is clicked
// funToRun - the function that should be run after login is confirmed.
// params - parameters to pass to fToRun, as an array
clickWrapper = function(funToRun, params)
{
    // Keeps track of the state of the click
    var doFunction = true;

    var callback = function()
    {
        if (doFunction)
        {
            funToRun.apply(this, params);
            doFunction = false;
        }
    }

    // The facebook
    facebookLogin(callback);
}

In this solution, you're wrapping the function that you want run in a callback that will only run once, since doFunction will prevent future callbacks from doing anything.  However, it will run at least once every time the user clicks, since doFunction is managed locally (and thus is true once for each click).


text:
Q: Is socket's "leave" automatically converted to "left" for the receiver? In my code, I use WebRTC, AngularJS and rtpConnection.
One declare is:
https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js

In my code, I react to the following event:
socket.on("left", somevar)

However, I don't see where this is emitted, I searched just anywhere in my code.
But I just don't find any .emit("left" or ".emit('left' in my code.
The only code that is SOMEWHAT related is
 socket.emit('leave', somevar);

But I just don't understand it: "leave" is not "left".
The only possible explanation would be that "leave" is internally converted to "left" for the receiver.
Is that actutally the case?
If not, where else could I find this emitting code?

A: No, socket doesn't do this automatically.
It's stated in the code somewhere by you.


text:
Q: Combine document ready and self-invoking function I am doing this, often. The reason for the self-invoking function is that I am often in WordPress, where it's in noconflict mode .
jQuery(document).ready(function(){
(function ($) {
        //do things
})(jQuery);
});

Am I doing it right? Is there a shortcut, to do both things at once?
I just found
jQuery(function( $ ) {
  // Your code using failsafe $ alias here...
});

Does this do the same thing?

A: Your options for operating in no-conflict mode are as follows (as per the jQuery documentation)
jQuery( document ).ready(function( $ ) {
  // Code that uses jQuery's $ can follow here.
});

OR
(function( $ ) {
  $(function() {
    // More code using $ as alias to jQuery
  });
})(jQuery);


text:
Q: WrapGrid in ListView (without xaml) with C# Somebody know how to translate the following xaml code to C#?
<ListView>
     <ListView.ItemsPanel>
          <ItemsPanelTemplate>
                <WrapGrid Orientation="Horizontal" />
          </ItemsPanelTemplate>
     </ListView.ItemsPanel>
</ListView>

A: I'm not sure why you want to create this in code, it would probably be better to just put the ItemPanelTemplate in a resource in your page or in App.xaml.
Otherwise here how to create it by code:
ItemsPanelTemplate template=new ItemsPanelTemplate();
var str = "<ItemsPanelTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">"
     +"<WrapGrid Orientation=\"Horizontal\" />"
     +"</ItemsPanelTemplate>";
ItemsPanelTemplate panelTemplate = (ItemsPanelTemplate)Windows.UI.Xaml.Markup.XamlReader.Load(str);

ListView listView=new ListView();
listView.ItemsPanel = panelTemplate ;

A: From this link what I conclude is that ItemsPanelTemplate belongs to mainly XAML because you can not alter them from simple run time APIs. So you need to stick to either XAML declaration or you can use XamlReader to load the XAML.
using Windows.UI.Xaml.Markup;

private ListView GetListView()
{

    const string xaml = @"<ListView xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">
                             <ListView.ItemsPanel>
                                  <ItemsPanelTemplate>
                                        <WrapGrid Orientation=""Horizontal"" />
                                  </ItemsPanelTemplate>
                             </ListView.ItemsPanel>
                        </ListView>";
    var lv = (ListView)XamlReader.Load(xaml);
    return lv;
}


text:
Q: Flutter: How to make a button invisible but active so that you can only see Text?             Padding(
              padding: const EdgeInsets.symmetric(horizontal: 92),
              child: RaisedButton(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20)),
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => SecondPage()),
                    );
                  },
                child: Center(
                    child: Text(
                      "Forgot Password?",
                      style: TextStyle(color: Color.fromRGBO(196, 135,
                          198, 1)),
                    )),
              ),
            ),

How would you go about making a button that is invisible so that the user would only see the text? Let's say, they forgot their account and press on the text which would refer them to a new page.

A: The FlatButton may be what you're looking for. It is a regular button but only shows its child.

A: Use flat button instead of Raisedbutton try below example
              FlatButton(
                        child: Text(
                          "Forgot Password?",
                          style: your text style;
                        ),
                        onPressed: () {},
                      ),

A: You can use Inkwell widget to implement onTap event on Text or any widget.
InkWell(
  onTap: () {},
  child: Text(
    "Forgot Password?",
    style: const TextStyle(
      color: Color.fromRGBO(196, 135, 198, 1),
    ),
  ),
)

A: Yes FlatButton without any background color. The default is transparent. Just a child: Text()
FlatButton

A: Since Flutter v1.26.0-18.0-pre FlatButton is deprecated.
Use TextButton instead.
TextButton(
    onPressed: () {},
    child: Text('Button Text')
)


text:
Q: Jquery file upload ... freezes more than 100MB # blueimp jquery file upload i wanted to upload bigger files using jquery file upload from blueimp.
it is fine for smaller files but for big files >100mb it doesnt seem to be doing anything.  The progress bar doesnt move it just freezes.
i have done all the suggestions with regards to max file size and max post size in the php.ini
also set the maxfilesize in the script
$('#fileupload').fileupload({
    url: url,
    dataType: 'json',
    formData: [{ name: 'custom_dir', value: 'mydir' }],
    autoUpload: true,
    acceptFileTypes: /(\.|\/)(mp4|wmv|mov|Mp4|Wmv|Mov|MP4|WMV|MOV)$/i,
    maxFileSize: 419430400, // 400 MB

doesnt work.   does anybody have any suggestions ?

A: oh problem solved
put in the maxchunksize param   maxChunkSize: 1048576,
    url: url,
    dataType: 'json',
    formData: [{ name: 'custom_dir', value: '$f{sessionid}' }],
    autoUpload: true,
    acceptFileTypes: /(\\.|\\/)(mp4|wmv|mov|Mp4|Wmv|Mov|MP4|WMV|MOV)\$/i,
    maxFileSize: 419430400, // 400 MB
    maxNumberOfFiles: 1,
    maxChunkSize: 1048576,


text:
Q: A Database Error Occurred Unable to connect to your database server using the provided settings.

Filename:
  C:\wamp\www\bdwey-flowrank-f557ab5e422d\system\database\DB_driver.php
Line Number: 124

where the problem, please help?
DB setting is correct
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = 'sqlpass';
$db['default']['database'] = 'myDBName';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;`

and when remove password from
$db['default']['password'] = '';
generate this error

A Database Error Occurred
Error Number: 1017
Can't find file: '.\flowrank\use@0009rs.frm' (errno: 22)

SELECT items.image, CONCAT(users.fname,' ',users.lname) AS full_user_name, competition.competition_id,competition.title,competition.votes FROM items AS items LEFT JOIN competitions AS competition ON competition.competition_id = items.competition_id LEFT JOIN users AS users ON competition.user_id = users.user_id GROUP BY items.competition_id ORDER BY items.votes ASC LIMIT 5

Filename:
  C:\wamp\www\bdwey-flowrank-f557ab5e422d\system\database\DB_driver.php
Line Number: 330

Where the problem?

A: Looks like the problem is not a code problem but your MySQL server.
Try repairing your mysql tables. Have a read here: http://dev.mysql.com/doc/refman/5.0/en/rebuilding-tables.html


text:
Q: Jmeter Regular expression extractor and parsing into request In Jmeter, I can able to extract the value using regular expression extractor, but while parsing the value I need some changes in the value as below.
Example,
Suppose If I extract this value in regular expression extractor (single Value in multiple lines),
PHNhbW+xwO
U0FNTDoyL
cmFjbGUu+
Here
I Need to replace + by %2B, need to add %OD%OA at the end of each line and multiple lines to a single line as below.
PHNhbW%2BxwO%OD%OAU0FNTDoyL%OD%OAcmFjbGUu%2B%OD%OA
I need to parse this as a single parameter value.

A: I think you can use __javaScript() function which allows calling arbitrary JavaScript code and inside JMeter __javaScript() funciton you can call EcmaScript EncodeURIComponent() function
It will automatically convert all newline characters \r\n to %OD%OA and + to %2B and in fact any character except alphanumeric and these ones:
_ . ! ~ * ' ( )

Demo:

See Using JMeter Functions guide for comprehensive information on how to deal with the functions in JMeter


text:
Q: How to response to client or browser when post file size excess the limit in nodejs and express I'm getting the "POST" value from browser to nodejs and express.
I post the file to nodejs.
Below is the code.
var express = require('express')
  , routes = require('./routes')
  , http = require('http');

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  //app.use(express.bodyParser());
  app.use(express.bodyParser({
      uploadDir: __dirname + '/upload',
      keepExtensions: true,
      limit: '50mb'
    }));
  app.use(express.limit('35mb'));
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.post('/', function(request, response){

    console.log(request.body.upfile);
    console.log(request.files);
    var ret = {a:'a',b:'b'};
    response.writeHead(200, { 'Content-Type': 'application/json'});
    response.write(JSON.stringify(ret));
    response.end();

});

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

It can receive the post file.
But I have set the file size limit to 50mb.
 When I'm post the file size larger than 50mb.
The browser will continue to upload the file until finish.
What I need is when size larger than 50mb. It response 413(request entity too large, that is what express error print out) http code to browser that stop it uploading.
I've investigate the express source code.
It use connect that locate in
node_modules/express/node_modules/connect/lib/middleware/limit.js of line 45.
That it log the 413 and the call stack to stdio.
I think I can do the trick here to response to browser with 413 http code.
But when I test it. The browser print reset.
Below is the modify code.
module.exports = function limit(bytes){
  if ('string' == typeof bytes) bytes = utils.parseBytes(bytes);
  if ('number' != typeof bytes) throw new Error('limit() bytes required');
  return function limit(req, res, next){
    var received = 0
      , len = req.headers['content-length']
        ? parseInt(req.headers['content-length'], 10)
        : null;

    // self-awareness
    if (req._limit) return next();
    req._limit = true;

    // limit by content-length
    if (len && len > bytes) {
      var ret = {a:'bbbbb',b:'b'};
      res.writeHead(413);
      res.write(JSON.stringify(ret));
      res.end();

      return next(utils.error(413));
    }

    // limit
    req.on('data', function(chunk){
      received += chunk.length;
      if (received > bytes) req.destroy();
    });

    next();
  };
};

A: What happens here is that the first "if":
// limit by content-length
if (len && len > bytes) {
  var ret = {a:'bbbbb',b:'b'};
  res.writeHead(413);
  res.write(JSON.stringify(ret));
  res.end();

  return next(utils.error(413));
}

is executed only if the browser sent the 'content-length' header, which is not always the case. Most of the time it will fallback to counting the bytes on-the-fly here:
// limit
req.on('data', function(chunk){
  received += chunk.length;
  if (received > bytes) req.destroy();
});

But as you can see, when it goes past the allowed limit it simply destroys the request, which results in a reset message from the browser. You could change it to be like this:
// limit
req.on('data', function(chunk){
  received += chunk.length;
  if (received > bytes) {
    var ret = {a:'bbbbb',b:'b'};
    res.writeHead(413);
    res.write(JSON.stringify(ret));
    res.end();
  }
});

It seems to work, but I'm not sure if this is the right way to do it.


text:
Q: jQuery : Append child + sortable I need to sort some li's but I don't know how to add a children to an empty li. At this moment I can add li's to another li only if is not empty.
EG.

Item

Item

Item

Item

Item

Item

So I can add li_1 into li_2 but I can't add li_6 into li_5 because li_5 is empty.
My work can be found here.

A: A simple solution is to add empty ul with an padding / margin than you can drop the items into this empty sublist.
http://jsfiddle.net/k83QH/2/

A: One way to get around this would be to add an empty ul, in jQuery, to any list items that could potential have children dragged into them. That way you'll get the drop container for all of your li's

A: You will have to check whether there is any ul child element for that li, if not, then add a ul element, and then add your child li elements in it.


text:
Q: How to set DHCP interface as default gateway in Debian 9 Debian 9 running on virtualbox. I have 2 adaptors, one NAT and the other Host Only. Here's my /etc/network/interfaces file:
allow-hotplug enp0s3
auto enp0s3
iface enp0s3 inet dhcp

allow-hotplug enp0s8
auto enp0s8
iface enp0s8 inet static
    address 192.168.56.3
    netmask 255.255.255.0
    gateway 192.168.56.1

When I boot I get the 2nd interface as the default gateway, but I need the first.
Running this command manually solves it:
ip route change default via 10.0.2.3

Assuming(?) that because this IP is DHCP generated (by virtualbox) how can I set this as the default route on boot?
In case it's helpful, here's the output of ip route show (after that command)
default via 10.0.2.3 dev enp0s3
10.0.2.0/24 dev enp0s3 proto kernel scope link src 10.0.2.15
169.254.0.0/16 dev enp0s8 scope link metric 1000
192.168.56.0/24 dev enp0s8 proto kernel scope link src 192.168.56.3

And here's the output of ip addr show:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:b8:c5:ff brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global enp0s3
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:feb8:c5ff/64 scope link
       valid_lft forever preferred_lft forever
3: enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:c8:d2:fb brd ff:ff:ff:ff:ff:ff
    inet 192.168.56.3/24 brd 192.168.56.255 scope global enp0s8
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fec8:d2fb/64 scope link
       valid_lft forever preferred_lft forever

A: Remove the allow-hotplug lines (you've got auto instead) and the gateway line (which sets the default gateway manually).


text:
Q: Angular 2 rc3 - unresolved dependencies Im using packages.json from official Angular2 site, the quick start. Yesterday it was working fine, today npm cant resolve dependecies. I get error:
npm ERR! peerinvalid The package @angular/core@2.0.0-rc.3 does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer @angular/common@2.0.0-rc.3 wants @angular/core@2.0.0-rc.3
npm ERR! peerinvalid Peer @angular/compiler@2.0.0-rc.3 wants @angular/core@2.0.0-rc.3
npm ERR! peerinvalid Peer @angular/forms@0.1.1 wants @angular/core@2.0.0-rc.3
npm ERR! peerinvalid Peer @angular/http@2.0.0-rc.3 wants @angular/core@2.0.0-rc.3
npm ERR! peerinvalid Peer @angular/platform-browser@2.0.0-rc.3 wants @angular/core@2.0.0-rc.3
npm ERR! peerinvalid Peer @angular/platform-browser-dynamic@2.0.0-rc.3 wants @angular/core@2.0.0-rc.3
npm ERR! peerinvalid Peer @angular/router@3.0.0-alpha.7 wants @angular/core@^2.0.0-rc.2
npm ERR! peerinvalid Peer @angular/router-deprecated@2.0.0-rc.2 wants @angular/core@^2.0.0-rc
npm ERR! peerinvalid Peer @angular/upgrade@2.0.0-rc.3 wants @angular/core@2.0.0-rc.3
npm ERR! peerinvalid Peer angular2-in-memory-web-api@0.0.12 wants @angular/core@2.0.0-rc.2

My npm-debug: http://q.i-systems.pl/file/3dd29e55.zip

A: This happens when you update some packages and leave some hanging, that's what angular just did in RC.3.

So instead of fixing who needs what,

*

*I deleted node_modules

*copied package.json from QuickStart, added my extras

*ran npm install
npm is happy again.

A: Upgrade npm worked for me:
npm install npm -g

Then delete node_modules and
npm install

A: This happens because of mismatch of package version required.Inside quickstart folder there is file called package.json. This package.json looks like this
 {
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation,supplemented with testing support",
  "scripts": {
  "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
  "docker-build": "docker build -t ng2-quickstart .",
  "docker": "npm run docker-build && docker run -it --rm -p 3000:3000 -p 3001:3001 ng2-quickstart",
  "pree2e": "npm run webdriver:update",
  "e2e": "tsc && concurrently \"http-server\" \"protractor    protractor.config.js\"",
  "lint": "tslint ./app/**/*.ts -t verbose",
  "lite": "lite-server",
  "postinstall": "typings install",
  "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
  "tsc": "tsc",
  "tsc:w": "tsc -w",
  "typings": "typings",
  "webdriver:update": "webdriver-manager update"
},
 "keywords": [],
 "author": "",
 "license": "ISC",
  "dependencies": {
      "@angular/common":  "2.0.0-rc.2",
"@angular/compiler":  "2.0.0-rc.2",
"@angular/core":  "2.0.0-rc.2",
"@angular/forms": "0.1.0",
"@angular/http":  "2.0.0-rc.2",
"@angular/platform-browser":  "2.0.0-rc.2",
"@angular/platform-browser-dynamic":  "2.0.0-rc.2",
"@angular/router":  "3.0.0-alpha.7",
"@angular/router-deprecated":  "2.0.0-rc.2",
"@angular/upgrade":  "2.0.0-rc.2",

"systemjs": "0.19.27",
"core-js": "^2.4.0",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"zone.js": "^0.6.12",

"angular2-in-memory-web-api": "0.0.12",
"bootstrap": "^3.3.6"
},
"devDependencies": {
"concurrently": "^2.0.0",
"lite-server": "^2.2.0",
"typescript": "^1.8.10",
"typings": "^1.0.4",

"canonical-path": "0.0.2",
"http-server": "^0.9.0",
"tslint": "^3.7.4",
"lodash": "^4.11.1",
"jasmine-core": "~2.4.1",
"karma": "^0.13.22",
"karma-chrome-launcher": "^0.2.3",
"karma-cli": "^0.1.2",
"karma-htmlfile-reporter": "^0.2.2",
"karma-jasmine": "^0.3.8",
"protractor": "^3.3.0",
"rimraf": "^2.5.2"
},
"repository": {}
}

Now if look inside dependency section we see something like this
  dependencies": {
      "@angular/common":  "2.0.0-rc.2",
"@angular/compiler":  "2.0.0-rc.2",
"@angular/core":  "2.0.0-rc.2",
"@angular/forms": "0.1.0",
"@angular/http":  "2.0.0-rc.2",
"@angular/platform-browser":  "2.0.0-rc.2",
"@angular/platform-browser-dynamic":  "2.0.0-rc.2",
"@angular/router":  "3.0.0-alpha.7",
"@angular/router-deprecated":  "2.0.0-rc.2",
"@angular/upgrade":  "2.0.0-rc.2",
}

This is where we are specifying which packages we need along with its version. If want to use higher version of packages , use ^ in version number.Following will set dependency to rc.2 or higher
dependencies": {
"@angular/common":  "^2.0.0-rc.2",
"@angular/compiler": "^2.0.0-rc.2",
"@angular/core":  "^2.0.0-rc.2",
"@angular/forms": "^0.1.0",
"@angular/http":  "^2.0.0-rc.2",
"@angular/platform-browser":  "^2.0.0-rc.2",
"@angular/platform-browser-dynamic":  "^2.0.0-rc.2",
"@angular/router":  "^3.0.0-alpha.7",
"@angular/router-deprecated":  "^2.0.0-rc.2",
"@angular/upgrade":  "^2.0.0-rc.2"
}

Now go to shell and run command
 npm cache clean -f
 npm update -g

This will update your packages to higher version if available.


text:
Q: html not working for firefox but works for chrome I have a template :

Some long message

I get justify text in chrome but not in firefox. What might be the solution?

A: Font tag is deprecated in HTML5 but also is always better to separate structure (HTML) and presentation (CSS).
Use a
 tag (paragraph) for adding long text.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

Also the CSS property to justify text is text-align:justify;
div{
    width:500px;
}

p{
    font-size:14px;
    text-align:justify;
}

If you really have to use inline styles, you can:

DEMO http://jsfiddle.net/a_incarnati/undmcszz/5/

A: The html font tag is deprecated. From w3schools website:

Definition and Usage
  The  tag is not supported in HTML5. Use CSS instead.
  The  tag specifies the font face, font size, and color of text.

Source: http://www.w3schools.com/tags/tag_font.asp
Use a supported HTML structure and style it with CSS:

YOUR TEXT


text:
Q: Error using model.fit on MNIST deep neural network training TensorFlow 2.0 I am trying to train a Deep Neural Network using MNIST dataset, here is some of the code of my jupyter notebook:
The first block works fine:
# Select the hyperparameter batch size
BATCH_SIZE = 100
# Batch the train, validatiion and test data
train_data = train_data.batch(BATCH_SIZE)
validation_data = validation_data.batch(num_validation_samples)
test_data = test_data.batch(num_test_samples)
# Transform the validation data into tuples for the inputs and targets
validation_inputs, validation_targets = next(iter(validation_data))
# Defining model hyperparameters
input_size = 784
output_size = 10
hidden_layer_size = 50
# Defining the model
model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28, 1)),
    tf.keras.layers.Dense(hidden_layer_size, activation='relu'),
    tf.keras.layers.Dense(hidden_layer_size, activation='relu'),
    tf.keras.layers.Dense(output_size, activation='softmax')
])
# Select the optimizer algorithm and the loss function
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

This last block is where I get the error
# Defining hyperparameter number of epochs
NUM_EPOCHS = 5
# Training the model
model.fit(train_data, epochs=NUM_EPOCHS, validation_data=(validation_inputs, validation_targets), verbose=2)

Epoch 1/5
---------------------------------------------------------------------------
DataLossError                             Traceback (most recent call last)
 in
      2 NUM_EPOCHS = 5
      3 # Training the model
----> 4 model.fit(train_data, epochs=NUM_EPOCHS, validation_data=(validation_inputs, validation_targets), validation_steps=1, verbose=2)

~\Anaconda3\envs\PY3-TF2.0\lib\site-packages\tensorflow\python\keras\engine\training.py in _method_wrapper(self, *args, **kwargs)
     64   def _method_wrapper(self, *args, **kwargs):
     65     if not self._in_multi_worker_mode():  # pylint: disable=protected-access
---> 66       return method(self, *args, **kwargs)
     67
     68     # Running inside `run_distribute_coordinator` already.

~\Anaconda3\envs\PY3-TF2.0\lib\site-packages\tensorflow\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
    846                 batch_size=batch_size):
    847               callbacks.on_train_batch_begin(step)
--> 848               tmp_logs = train_function(iterator)
    849               # Catch OutOfRangeError for Datasets of unknown size.
    850               # This blocks until the batch has finished executing.

~\Anaconda3\envs\PY3-TF2.0\lib\site-packages\tensorflow\python\eager\def_function.py in __call__(self, *args, **kwds)
    578         xla_context.Exit()
    579     else:
--> 580       result = self._call(*args, **kwds)
    581
    582     if tracing_count == self._get_tracing_count():

~\Anaconda3\envs\PY3-TF2.0\lib\site-packages\tensorflow\python\eager\def_function.py in _call(self, *args, **kwds)
    609       # In this case we have created variables on the first call, so we run the
    610       # defunned version which is guaranteed to never create variables.
--> 611       return self._stateless_fn(*args, **kwds)  # pylint: disable=not-callable
    612     elif self._stateful_fn is not None:
    613       # Release the lock early so that multiple threads can perform the call

~\Anaconda3\envs\PY3-TF2.0\lib\site-packages\tensorflow\python\eager\function.py in __call__(self, *args, **kwargs)
   2418     with self._lock:
   2419       graph_function, args, kwargs = self._maybe_define_function(args, kwargs)
-> 2420     return graph_function._filtered_call(args, kwargs)  # pylint: disable=protected-access
   2421
   2422   @property

~\Anaconda3\envs\PY3-TF2.0\lib\site-packages\tensorflow\python\eager\function.py in _filtered_call(self, args, kwargs)
   1663          if isinstance(t, (ops.Tensor,
   1664                            resource_variable_ops.BaseResourceVariable))),
-> 1665         self.captured_inputs)
   1666
   1667   def _call_flat(self, args, captured_inputs, cancellation_manager=None):

~\Anaconda3\envs\PY3-TF2.0\lib\site-packages\tensorflow\python\eager\function.py in _call_flat(self, args, captured_inputs, cancellation_manager)
   1744       # No tape is watching; skip to running the function.
   1745       return self._build_call_outputs(self._inference_function.call(
-> 1746           ctx, args, cancellation_manager=cancellation_manager))
   1747     forward_backward = self._select_forward_and_backward_functions(
   1748         args,

~\Anaconda3\envs\PY3-TF2.0\lib\site-packages\tensorflow\python\eager\function.py in call(self, ctx, args, cancellation_manager)
    596               inputs=args,
    597               attrs=attrs,
--> 598               ctx=ctx)
    599         else:
    600           outputs = execute.execute_with_cancellation(

~\Anaconda3\envs\PY3-TF2.0\lib\site-packages\tensorflow\python\eager\execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     58     ctx.ensure_initialized()
     59     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 60                                         inputs, attrs, num_outputs)
     61   except core._NotOkStatusException as e:
     62     if name is not None:

DataLossError:  truncated record at 15713022
     [[node IteratorGetNext (defined at :4) ]] [Op:__inference_train_function_957]

Function call stack:
train_function

I have no idea where exactly is the error. I have already tried changing some of the arguments of the model.fit method, like aggregating validation_steps argument, but it didn't work. Thanks in advance for your help

A: I managed to solve the issue by changing the version of the tensoflow-datasets module, I was using version 3 and by going back to version 2.1 the script worked.


text:
Q: Is there a term to describe a word or idiom that translates literally as one thing, but is actually a specific word? Is there a term to describe a word or idiom that translates literally as one thing, but is actually a specific word in the translated language?
My best example would be 'pomme de terre' from French translating literally as 'ground apple', but would be translated to 'potato'.
Another might be 'pied-à-terre' meaning 'foot on the ground', but meaning something more like 'city house'.


text:
Q: Xcode Objective-C equivalent of visual studio's [DebuggerHidden] attribute In visual studio, when programming with C# (or other .NET languages), one can apply an attribute to a method which causes the debugger to ignore it. [DebuggerHidden] or [DebuggerStepThrough] both allow this in C#.
Is there an equivalent when working with Objective-C code using Xcode 5?

Example to illustrate the behaviour
void Main() {
    Print("GetNumber returns: ", GetNumber());
}

[DebuggerHidden]
int GetNumber() {
    return 42;
}

void Print(string s, int n) {
    Console.WriteLine(s + n.ToString());
}

Without the [DebuggerHidden] attribute, when stepping through the code using "Step Into...", control flow goes like this:

*

*Main

*GetNumber

*Print

With the attribute, the debugger skips GetNumber, and goes straight from Main to Print.
This is very useful for ignoring trivial method calls such as property getters, etc.
I have some various such trivial methods that I'd like to make the debugger skip past in Xcode if possible.


text:
Q: Receive Quiz JSON string from server and display on screen i've received Quiz JSON string from server this string contain 10 Question, i received and stored response in ArrayList.  now i want that one Question (and its 4 options)should display on screen then there is next button when i press then next question should be display on screen similarly until control reached all 10 question. my problem is that i cannot do functionality of on press next button show the second one(next) Question. please any one help me i am beginner in android thanks.
Here Is JSON String.
   {
  "status": 200,
  "status_message": "Success",
  "response":
   [
    {
      "quizNumber" :  "1",
        "image" : "",
        "question" : "Which car manufacturer was the first to win 100 F1 races?",
        "option1" : "Ferrari",
        "option2" : "Nissan",
        "option3" : "Ford",
        "option4" : "",
        "answer" : "Ferrari."
    },
    {
      "quizNumber" :  "2",
        "image" : "",
        "question" : "In the professional era which woman has won the most titles at Wimbledon [singles, doubles and mixed] ?",
        "option1" : "Venus",
        "option2" : "Hingis",
        "option3" : "Martina Navratilova",
        "option4" : "Waynetta",
        "answer" : "Martina Navratilova"
    },
    {
      "quizNumber" :  "3",
        "image" : "",
        "question" : "How many times have Liverpool been relegated from the top flight of English football?",
        "option1" : "Four",
        "option2" : "Three",
        "option3" : "Two",
        "option4" : "Five",
        "answer" : "Three"
    }]}

And Here Is my MainActivity.java class.
     package com.example.quistest;

  //import goes here

   public class MainActivity extends Activity {

    String serviceUrl;
    ImageView next;
    TextView question,quizno;
    CheckBox ans_1,ans_2,ans_3,ans_4;
    ArrayList<Quiz_List>data;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    data=new ArrayList<Quiz_List>();

    next=(ImageView) findViewById(R.id.imageView_nextID);
    quizno=(TextView) findViewById(R.id.question_noID);
    question=(TextView) findViewById(R.id.txt_questionID);

    ans_1=(CheckBox) findViewById(R.id.chk_ans1ID);
    ans_2=(CheckBox) findViewById(R.id.chk_ans2ID);
    ans_3=(CheckBox) findViewById(R.id.chk_ans3ID);
    ans_4=(CheckBox) findViewById(R.id.chk_ans4ID);

    next.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "Next...", Toast.LENGTH_SHORT).show();
        }
    });

    if (isNetworkAvailable()) {
        execute();

}

   else {
    // Error message here if network is unavailable.
    Toast.makeText(this, "Network is unavailable!",   Toast.LENGTH_LONG).show();
}

}

private boolean isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();

    boolean isAvailable = false;
    if (networkInfo != null && networkInfo.isConnected()) {
        isAvailable = true;
    }
    return isAvailable;
}

private void execute() {

    serviceUrl ="http://mobile.betfan.com/api/?action=quiz&key=MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP&sporttype=all";

    class LoginAsync extends AsyncTask<String, Void, String>{

        private Dialog loadingDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadingDialog = ProgressDialog.show(MainActivity.this, "Please  while wait", "Loading...");
        }

        @Override
        protected String doInBackground(String... params) {

            JSONObject jsonObject = new JSONObject();

            String dataString = jsonObject.toString();

            InputStream is = null;
            List<NameValuePair> nameValuePairs = new
          ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("data", dataString));

            String result = null;

            try{

                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpRequest = new HttpGet();

                URI apiurl = new URI(serviceUrl);

                httpRequest.setURI(apiurl);

                HttpResponse response = httpClient.execute(httpRequest);

                HttpEntity entity = response.getEntity();

                is = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return result;
        }

        protected void onPostExecute(String result){
            String s = result.trim();

            loadingDialog.dismiss();

                JSONObject respObject;
                try {
                    respObject = new JSONObject(s);
                    String active = respObject.getString("status_message");

                    if(active.equalsIgnoreCase("success")){
                         JSONArray array = respObject.getJSONArray("response");
                            for (int i =0; i<array.length();i++){

                         JSONObject jsonObject = array.getJSONObject(i);
                         String quizNumber= jsonObject.getString("quizNumber");
                         String question= jsonObject.getString("question");
                         String option1 = jsonObject.getString("option1");
                         String option2 = jsonObject.getString("option2");
                         String option3 = jsonObject.getString("option3");
                         String option4 = jsonObject.getString("option4");

                         data.add(new Quiz_List(quizNumber,question,option1,option2,option3,option4));

                         quizno.setText("Question numer:"+quizNumber);
                        MainActivity.this.question.setText(question);
                        ans_1.setText(option1);
                        ans_2.setText(option2);
                        ans_3.setText(option3);
                        ans_4.setText(option4);

                        }

                    }else {
                        Toast.makeText(MainActivity.this, "Quiz received Fail", Toast.LENGTH_LONG).show();

                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

        }

    }

    LoginAsync la = new LoginAsync();
    la.execute();

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
  }
 }

And Here is my AarrayList Quiz_List.java class.
     package com.example.quistest;

   public class Quiz_List {
   private String quiz_no;
   private String question;
   private String answer_1;
   private String answer_2;
   private String answer_3;
   private String answer_4;

  public String getQuiz_no() {
    return quiz_no;
}
public void setQuiz_no(String quiz_no) {
    this.quiz_no = quiz_no;
}

public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnswer_1() {
return answer_1;
}
public void setAnswer_1(String answer_1) {
this.answer_1 = answer_1;
}
public String getAnswer_2() {
return answer_2;
}
public void setAnswer_2(String answer_2) {
this.answer_2 = answer_2;
}
public String getAnswer_3() {
return answer_3;
}
public void setAnswer_3(String answer_3) {
this.answer_3 = answer_3;
}
public String getAnswer_4() {
return answer_4;
}
public void setAnswer_4(String answer_4) {
this.answer_4 = answer_4;
}
public Quiz_List(String quiz_no, String question, String answer_1,
    String answer_2, String answer_3, String answer_4) {
super();
this.quiz_no = quiz_no;
this.question = question;
this.answer_1 = answer_1;
this.answer_2 = answer_2;
this.answer_3 = answer_3;
this.answer_4 = answer_4;
 }

}

Please anyone help  i want when i want press next then it should display second one question(its 4 options) should display on screen.
And In current situation it displays last question(its 4 options) only.

A: I write an example as per your requriment
1-we have a json array
  {
  "status": 200,
  "status_message": "Success",
  "response":
   [
    {
      "quizNumber" :  "1",
        "image" : "",
        "question" : "Which car manufacturer was the first to win 100 F1 races?",
        "option1" : "Ferrari",
        "option2" : "Nissan",
        "option3" : "Ford",
        "option4" : "",
        "answer" : "Ferrari."
    },
    {
      "quizNumber" :  "2",
        "image" : "",
        "question" : "In the professional era which woman has won the most titles at Wimbledon [singles, doubles and mixed] ?",
        "option1" : "Venus",
        "option2" : "Hingis",
        "option3" : "Martina Navratilova",
        "option4" : "Waynetta",
        "answer" : "Martina Navratilova"
    },
    {
      "quizNumber" :  "3",
        "image" : "",
        "question" : "How many times have Liverpool been relegated from the top flight of English football?",
        "option1" : "Four",
        "option2" : "Three",
        "option3" : "Two",
        "option4" : "Five",
        "answer" : "Three"
    }]}

2-Make a pojo class
class Mypojo {
  String op1,op2,op3,op4,ans;
  Mypojo(String s1,String s2,String s3,String s4,String ss){
        op1 = s1;
       .......
     ans = ss;

}
 //add getter / setter method here
}

3- Now in activity take an array list
  int i = 0;
 ArrayList<Mypojo> mypojo = new AarrayList();

where you parse json
make pojo class object like
Mypojo pojo = new Mypojo(parameters) and pass all parameters
then mypojo.add(pojo);
In this way all json data will be added in pojo type array list.

4-Now in Next button code will be
int arraysize = mypojo.size();

if(i<arraysize){

  i++;
 get all values from pojo arraylist by using i as a index position like
 String op1 = mypojo.get(i).getOp1();
and change your UI.
}

This is for example if you will do all steps correctly your problem will be solved.

A: Initially set in MainActivity
int count=0;

Add 1 to count and send count to MainActivity.class when next button is clicked.
Intent i=new Intent(MainActivity.this,MainActivity.class);
i.putStringExtra("count",count);
startActivity(i);

and according to received count in post Execute
 JSONObject jsonObject = array.getJSONObject(count);
                         String quizNumber= jsonObject.getString("quizNumber");
                         String question= jsonObject.getString("question");
                         String option1 = jsonObject.getString("option1");
                         String option2 = jsonObject.getString("option2");
                         String option3 = jsonObject.getString("option3");
                         String option4 = jsonObject.getString("option4");

Every time next button is clicked count is increased by one
Paste the below in MainActivity
 package com.example.quistest;

  //import goes here

   public class MainActivity extends Activity {

    String serviceUrl;
    ImageView next;
    TextView question,quizno;
    CheckBox ans_1,ans_2,ans_3,ans_4;
    ArrayList<Quiz_List>data;

    String count=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    data=new ArrayList<Quiz_List>();

    next=(ImageView) findViewById(R.id.imageView_nextID);
    quizno=(TextView) findViewById(R.id.question_noID);
    question=(TextView) findViewById(R.id.txt_questionID);

    ans_1=(CheckBox) findViewById(R.id.chk_ans1ID);
    ans_2=(CheckBox) findViewById(R.id.chk_ans2ID);
    ans_3=(CheckBox) findViewById(R.id.chk_ans3ID);
    ans_4=(CheckBox) findViewById(R.id.chk_ans4ID);

    Intent i=getIntent();

    count=i.getStringExtra("count");

    next.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            int new_count=Integer.parseInt(count)+1;

            Intent intent=new Intent(MainActivity.this, MainActivity.class);

            intent.putExtra("count",String.valueOf(new_count));

            Toast.makeText(getApplicationContext(), "Next...", Toast.LENGTH_SHORT).show();
        }
    });

    if (isNetworkAvailable()) {
        execute();

}

   else {
    // Error message here if network is unavailable.
    Toast.makeText(this, "Network is unavailable!",   Toast.LENGTH_LONG).show();
}

}

private boolean isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();

    boolean isAvailable = false;
    if (networkInfo != null && networkInfo.isConnected()) {
        isAvailable = true;
    }
    return isAvailable;
}

private void execute() {

    serviceUrl ="http://mobile.betfan.com/api/?action=quiz&key=MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP&sporttype=all";

    class LoginAsync extends AsyncTask<String, Void, String>{

        private Dialog loadingDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadingDialog = ProgressDialog.show(MainActivity.this, "Please  while wait", "Loading...");
        }

        @Override
        protected String doInBackground(String... params) {

            JSONObject jsonObject = new JSONObject();

            String dataString = jsonObject.toString();

            InputStream is = null;
            List<NameValuePair> nameValuePairs = new
          ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("data", dataString));

            String result = null;

            try{

                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpRequest = new HttpGet();

                URI apiurl = new URI(serviceUrl);

                httpRequest.setURI(apiurl);

                HttpResponse response = httpClient.execute(httpRequest);

                HttpEntity entity = response.getEntity();

                is = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return result;
        }

        protected void onPostExecute(String result){
            String s = result.trim();

            loadingDialog.dismiss();

                JSONObject respObject;
                try {
                    respObject = new JSONObject(s);
                    String active = respObject.getString("status_message");

                    if(active.equalsIgnoreCase("success")){
                         JSONArray array = respObject.getJSONArray("response");

                         JSONObject jsonObject = array.getJSONObject(Integer.parseInt(count));
                         String quizNumber= jsonObject.getString("quizNumber");
                         String question= jsonObject.getString("question");
                         String option1 = jsonObject.getString("option1");
                         String option2 = jsonObject.getString("option2");
                         String option3 = jsonObject.getString("option3");
                         String option4 = jsonObject.getString("option4");

                         data.add(new Quiz_List(quizNumber,question,option1,option2,option3,option4));

                         quizno.setText("Question numer:"+quizNumber);
                        MainActivity.this.question.setText(question);
                        ans_1.setText(option1);
                        ans_2.setText(option2);
                        ans_3.setText(option3);
                        ans_4.setText(option4);

                    }else {
                        Toast.makeText(MainActivity.this, "Quiz received Fail", Toast.LENGTH_LONG).show();

                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

        }

    }

    LoginAsync la = new LoginAsync();
    la.execute();

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
  }
 }

A: When you need to pass data from one activity to another activity you need to use intent.putExtra() method to send data.
For send data from your main activity ->
Intent intent = new Intent(MainActivity.this,NEXT_ACTIVITY.class); // Change NEXT_ACTIVITY to your option / answer activity.
intent.putExtra("option_1",option1);
intent.putExtra("option_2",option2);
intent.putExtra("option_3",option3);
intent.putExtra("option_4",option4);
intent.putExtra("answer",answer);
startActivity(intent);

To receive data from your next activity ->
Bundle bundle = getIntent().getExtras();
String option1 = bundle.getString("option_1");
String option2 = bundle.getString("option_2");
String option3 = bundle.getString("option_3");
String option4 = bundle.getString("option_4");
String answer = bundle.getString("answer");

Now you can use these data wherever you want in this activity.

A: If you parse json and add data in array list I suggest you make a pojo class and take all values in pojo type array list. When you press next button find array list size and array list index start from 0 to array list size so take a integer (int i = 0 ) and its initial value must be 0(zero).Now use if (i<array.size()) condition and inside it increase integer value (i++) . By this way you can solve your problem.Do not use Intent , all things do in same activity.


text:
Q: Magento Ajax cart On delete redirect to Delete page When I want to delete more than 1 product one by one from AJAX Cart , for 1st product its working fine but when I try to delete the another product the page it redirect to delete page URL like
(SiteURL/checkout/cart/delete/id/012/uenc/aHR0cDovLzEyMi)
and showing some json or html data like    {"message":"Item was removed.","update_blocks":[{"key":".header .links","value":"<div class=\"links\"> ....
Delete Item From Shopping cart function deleteAction()
public function deleteAction() {
        $id = (int) $this->getRequest()->getParam('id');
        if ($id) {
            try {
                $this->_getCart()->removeItem($id)
                        ->save();
            } catch (Exception $e) {
                $_response = Mage::getModel('ajaxcart/response');
                $_response->setError(true);
                $_response->setMessage($this->__('Cannot remove the item.'));
                $_response->send();
                Mage::logException($e);
            }
        }
        $_response = Mage::getModel('ajaxcart/response');
        $_response->setMessage($this->__('Item was removed.'));
        //append updated blocks
        $this->getLayout()->getUpdate()->addHandle('ajaxcart');
        $this->loadLayout();
        $_response->addUpdatedBlocks($_response);
        $_response->send();
    }

I will highly appreciate if i can get some help. Thanks in advance.

A: I got a solution, its related to a Javascript binding problem. The problem is, when you delete a product from the cart all the cart block gets updated. Hence it removes the already bound javascript.
I have added the javascript bind code at the end of updateBlocks function in ajaxcart.js.
So, whenever user tries to delete a item from the cart ajax code gets executed and the response update_blocks will once again gets bind to the cart even after the initial javascript binding.
Added Javascript bind code is
$$('a[href*="/checkout/cart/delete/"]').each(function (e) {
            $(e).observe('click', function (event) {
                setLocation($(e).readAttribute('href'));
                Event.stop(event);
            });
        });

And after adding code to ajaxcart.js updateBlocks function look like ,
updateBlocks: function (blocks) {
        var _this = this;
        if (blocks) {
            try {
                blocks.each(function (block) {
                    if (block.key) {
                        var dom_selector = block.key;
                        if ($$(dom_selector)) {
                            jQuery(block.key, parent.document).each(function (e) {
                                jQuery(this).html(block.value);
                            });
                        }
                    }
                });
                _this.bindEvents();
                _this.bindNewEvents();
                // show details tooltip
                truncateOptions();
            } catch (e) {
                console.log(e);
            }
        }
        $$('a[href*="/checkout/cart/delete/"]').each(function (e) {
            $(e).observe('click', function (event) {
                setLocation($(e).readAttribute('href'));
                Event.stop(event);
            });
        });
    }


text:
Q: Real-valued, differentiable function with bounded derivative is uniformly continuous Real-valued, differentiable function on $\mathbb{R}$ with the bounded derivative is uniformly continuous.

Let $f:\mathbb{R}\rightarrow\mathbb{R}$ be a differentiable function such that there is $M>0$ and $|f'(x)|<M$ for all $x\in\mathbb{R}$.
From Mean Value Theorem we know that for each $x,y$ there is some $c$ between them such that $|f(x)-f(y)|=|f'(c)(x-y)|$. Since $f'$ is bounded by $M$, it means that $|f(x)-f(y)|<M|x-y|$. Now fix $\epsilon>0$. If we set $\delta=\frac{\epsilon}{M}$, we have $|f(x)-f(y)|<\epsilon$ whenever $|x-y|<\delta$. This holds for any $x,y \in\mathbb{R}$, thus we are done.

A: The proof is correct, except that it would be better to write
$$|f(x)-f(y)|\le M|x-y|$$
because the strict inequality fails when $x=y$.
Generally, it is preferable to use non-strict inequalities unless a strict one is needed. They are more robust: can be taken to a limit, or multiplied by $0$.


text:
Q: python 3 jupyter notebook - plot a candle stick chart import pandas_datareader.data as web
from datetime import datetime

start = datetime(2019, 1, 1)
end   = datetime(2019, 12, 15)

dox = web.DataReader('DOX', 'yahoo', start, end)

dox is

saw this - https://plot.ly/python/candlestick-charts/
but it only runs on python code and creates an HTML website, not as a jupyter output
here is desired output (for example)


text:
Q: Referencing lambda environment variable in Cloudformation template throws "circular dependency" error I have an application that uses an AWS lambda function triggered by an implicit http api event, which gets post/get requests from a React app:
"mylambda": {
      "Type": "AWS::Serverless::Function",
      "Properties": {
        "InlineCode": "exports.handler = async (event, context)",
        "MemorySize": {
          "Ref": "LambdaMemorySize"
        },
        "Handler": "backend/index.handler",
        "Role": {
          "Fn::GetAtt": ["myrole", "Arn"]
        },
        "Timeout": {
          "Ref": "LambdaTimeout"
        },
        "Runtime": "nodejs12.x",
        "FunctionName": "myFunction",
        "Events": {
          "httpapi": {
            "Type": "HttpApi",
            "Properties": {
              "Path": "/myApi",
              "Method": "ANY"
            }
          }
        }
      }
    }
  },

I want to add an environment variable inside the Lambda function for the http-api endpoint so that I can use it in lambda's handler:
"Environment": {
          "Variables": {

            "apiEndpoint": {
              "Fn::Join": [
                "",
                [
                  "https://",
                  { "Ref": "ServerlessHttpApi" },
                  ".execute-api.",
                  { "Ref": "AWS::Region" },
                  ".amazonaws.com"
                ]
              ]
            }
          }
        }

The problem is that this throws a circular dependency error and I can see why (lambda relies on api-gateway and api-gateway relies on lambda).
I tried to create the http-api separately but then there seemed to be no way of referencing the api inside lambda as a trigger i.e. when I deploy, the template creates a lambda function that doesn't have my api as a trigger, while my api was created separately.
I know the whole env variables thing can be done easily from the console but my deployment model assumes everything should be done in the CF template.
An answer here suggested:
"You could easily extract the information you need from that event instead of having it as an environment variable, but this depends on your exact use case."
I could do this in the body of the lambda's handler in index.js:
module.exports.apiendpoint = event.requestContext.domainName;

But this will collide with the fact that 1) I can't use index.js variables that are outside React's src folder and 2) I'm not sure how the app will run for the first time since it'll require the get/post request first to trigger lambda.
I think my main problem is simple: I don't know how I can reference the http api endpoint in Lambda's environment variables without throwing an error. Is it that the whole structure of my app is wrong?


text:
Q: Is there any good maildir mail notifier for GNOME3? I'm looking for a maildir capable mail notifier, a'la biff/xbiff, but for GNOME3. I found this, but it gets its settings from Evolution, and I am not using Evolution - I'd simply like it to watch the maildirs I download with offlineimap.
The ability to launch my mail client (gnome-terminal + mutt) via a click would also be nice.
I'm using GNOME 3.16.
Any ideas?

A: Even though it is not directly what you asked for, you should take a look at "Geary", it is an official Gnome App for E-Mail, It works really nicely and is integrated with Gnome.