text:
Q: Using Extension to send email with scraped data Need help please!
After crawling a site and returning processing the data through pipelines, I need to send the scraped data via email. I've tried and read everything but can't seem to connect the dots.
In Pipelines I've tried the following:
class EmailPipeline(object):
    def close_spider(self, spider):
        from_email = "myemail@email.com"
        to_email = "anotheremail@email.com"

        msg = MIMEMultipart()
        msg['From'] = from_email
        msg['To'] = to_email
        msg['Subject'] = 'Scrapper Results'

        intro = "Summary stats from Scrapy spider: \n\n"

        body = spider.crawler.stats.get_stats()
        body = pprint.pformat(body)
        body = intro + body
        msg.attach(MIMEText(body, 'plain'))

        server = smtplib.SMTP("mailserver", 465)
        server.startssl()
        server.login("user", "password")
        text = msg.as_string()
        server.sendmail(from_email, to_email, text)
        server.quit()

Should I be sending the email from a pipeline or an extension or is it preference? How would I implement it??
Thanks all!

A: Scrapy provides MailSender module (which is based on smtplib):
from scrapy.mail import MailSender
mailer = MailSender()
mailer.send(to=["someone@example.com"], subject="Some subject", body="Some body", cc=["another@example.com"])

A: Here is a file you can use and import this send_mail function. You will need to change some things in order to make it work for your situation. You are including it in the correct way through a pipe line.
import smtplib

# For guessing MIME type
import mimetypes
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# Import the email modules we'll need
import email

def send_mail(filename):
    sender = 'sender@email.com'
    reciever = 'receiver@email.com'
    marker = "AUNIQUEMARKER"
    msg = MIMEMultipart()
    msg['Subject'] = 'Subject text here'
    msg['From'] = sender
    msg['To'] = reciever
    # Read a file and encode it into base64 format
    fo = open(filename, "rb")
    att = MIMEApplication(fo.read(),_subtype="pdf")
    msg.attach(att)
    fo.close()
    try:
        smtpObj = smtplib.SMTP(host='smtp.host.com', port=587)
        smtpObj.ehlo()
        smtpObj.starttls()
        smtpObj.login(sender, 'your password')
        smtpObj.sendmail(sender, reciever, msg.as_string())
        print('SUCCESSFULLY SENT EMAIL')
        return
    except Exception as e:
        print("SEND E-MAIL FAILED WITH EXCEPTION: {}".format(e))
        return

Another piece to find the last modified file in your output directory
import os
import glob

download_dir = "/full/path/to/files/"

def get_newest_file():
    print("Finding latest pdf file")
    file_list = glob.glob('{}*.pdf'.format(download_dir))
    latest_file = max(file_list, key=os.path.getctime)
    if latest_file:
        print("Latest file: {}".format(latest_file))
        return latest_file


text:
Q: Are Session implicit objects examples of Models in MVC? I have read that the Model is responsible for maintaining state among HTTP requests, for example in this article:

The Model is responsible for maintaining state between HTTP requests.
Basically any data whether on a database, in a file, stored in the Session, or cached inside APC must be preserved between requests and thus forms part of the state of the application at the time the last request was completed. So always remember that the Model is not just the database. Even the data you get from web services can be expressed as a Model! Yes, even Atom feeds! Frameworks which rattle off introductions to the Model, almost never explain this upfront which only exacerbates misunderstandings.

When we use some implicit Session objects (say in PHP, JSP etc.,) does it mean that this Session is a Model object?

A: From Wikipedia:

The model manages the behaviour and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller). In event-driven systems, the model notifies observers (usually views) when the information changes so that they can react.

That's the simplest definition of what a model is. If your session object has the facilities to respond to requests for information about its state and to instructions to change state, then you can definitely call it a Model.
It doesn't matter what the data storage is, remember that patterns are high level abstractions that are not supposed to be tied to specific implementations. You can build your models around every data storage facility, whether it's a database, some text files, LDAP, etc.
If it has the above discussed functionality, it's a model. Now, if it's a good / useful / efficient model it's a whole other discussion that greatly depends on how you use it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: excess white space at the end of my text in my widget I have been trying a lot of ways to try to get rid of the excess space at the end of my sentence which is supposed to be unpredictable. does anyone know how to make sure the length of the widget ends at the end of the last text, especially when used with pageview or list view widget?. it works fine without the use of any scrollable widget but anytime I use a scrollable widget I have to add a height which makes it hard to define a boundary.
class FeedsDetailView extends StatelessWidget {
  const FeedsDetailView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final String text2 = lorem(paragraphs: 9, words: 500);
    final String text3 = lorem(paragraphs: 10, words: 1000);
    final String text4 = lorem(paragraphs: 8, words: 5000);
    final String text5 = lorem(paragraphs: 12, words: 500);
    final textList = [
      text3,
      text4,
      text5,
    ];
    return Scaffold(
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.only(top: 45),
          child: Column(
            children: [
              Container(
                height: 380,
                width: double.maxFinite,
                decoration: const BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/images/night building.jpeg'),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              const SizedBox(height: 8),
              Divider(
                color: Theme.of(context).colorScheme.secondary,
                indent: 50,
                endIndent: 50,
              ),
              Container(
                height: double.maxFinite,
                child: PageView.builder(
                  itemCount: textList.length + 1,
                  itemBuilder: ((context, index) {
                    if (index == 0) {
                      return Column(
                        children: [
                          const Text('bla bla bla'),
                          const SizedBox(height: 12),
                          Padding(
                            padding: const EdgeInsets.only(left: 8, right: 8),
                            child: SizedBox(width: 350, child: Text(text3)),
                          ),
                        ],
                      );
                    } else {
                      return Column(
                        children: [
                          const Text('bla bla bla'),
                          const SizedBox(height: 12),
                          Padding(
                            padding: const EdgeInsets.only(left: 8, right: 8),
                            child: SizedBox(
                              width: 350,
                              child: Text(
                                textList[index - 1],
                              ),
                            ),
                          )
                        ],
                      );
                    }
                  }),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

I am also using the flutter_lorem package to generate long texts.

A: Remove this line
height: double.maxFinite,


text:
Q: Dynamic Ng-model name I am dynamically creating textboxes, therefor I would also need dynamic model names, I figured I should use it's Id, since it's identical.
I have this Textbox:
<input type="text" ng-init="scope[child.Root.Id] = ''" ng-model="scope[child.Root.Id]" />

The Textbox should bind to the value of Child.Root.Id, this seems to work, as the following samples work perfectly fine:

This is a test.

This is a test.

Both of these Id's have the same value. And the text hides when '123' is typed in the textbox.
However, I need to hide something else, and in this place I can't use child.Root.id, but I do have a child.Root.ParentId with the same value:

This is also a Test!

This doesn't work, What am I doing wrong?
This is my first project in Angular, so I don't have much experience with it.
Thanks in advance.
edit:

@*Start myApp-html-html*@

@*End myApp*@

QuestionEntrypartialView contains:

    <input type="text" ng-init="scope[child.Root.Id] = ''" ng-model="scope[child.Root.Id]"/>

This is a test.

This is a test.


text:
Q: How to set download filename on Google Chrome for iOS by javascript I could not manage to work the download attribute when downloading vcards via data URL by Chrome on IOS. I use code below
function download(filename, text) {
        var element = document.createElement('a');
        element.setAttribute('href', 'data:text/vcard;charset=utf-8,' + encodeURIComponent(text));
        element.setAttribute('download', filename);
        element.style.display = 'none';
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
    }

It works fine with Safari on IOS and Chrome on Android. But Chrome on IOS just ignore file name and download file just with name "document" so in not opened by contact app.


text:
Q: how to determine noise tolerance to use it in freeze detect filter in ffmpeg I'm trying to use freeze detect filter in ffmpeg.
ffmpeg -i Trial.mp4 -vf "freezedetect=n=-60dB:d=0.5,metadata=mode=print:file=freeze.txt" -map 0:v:0 -f null -

Used the above command and output says no freeze. But the Video is a standstill video taken in mobile.
If I adjust the noise level to 0.05, there are freezes reported.
How to determine this value?

A: You can determine this only by trial and error.
The filter calculates the difference between two frames as the ratio between their sum of absolute differences (SAD). In pseudocode:
is_frozen(reference, frame) {
    sad = 0
    count = 0
    for plane in planes[frame] {
        sad += sad_of_plane(plane, reference, frame)
        count += width[plane] * height[plane]
    }
    ratio = sad / count
    return ratio <= noise
}

Since the actual difference between two frames is determined by its noisiness, it will be very content-dependent. Note that even if the subject did not change, "noise" could mean camera/sensor noise, which will always be different between two captured frames.
Only for computer-generated content the difference between frames with the same subject will be zero (or very close to zero).


text:
Q: Float right moves the span element up? Hi i have beeen trying to make span and h1 element on the same line. However float:right will result span to move top. I have tried with different approach, i dont want to use margin property. Any sugesstions on this?

.pull-left {
  float: left;
  width: 70%;
}

.pull-right: {
  float: right;
  width: 20%;
}

Carl

  $4.81

Any help would be appreciated.

A: Its just the default margin of h1 tag that is doing this, you need to remove that.
If you wanna vertically center the span based on h1 then just use line-height:font-size of h1
Fiddle Here

.block h1
    {
      margin:0px;
    }
    .block span
    {
      line-height:2em;
    }
    .pull-left{
      float:left;
      width:70%;
    }
    .pull-right:{
      float:right;
      width:20%;
    }

Carl

  $4.81

A: You have applied pull-left class on
 and all html headings have some margin applied by browsers by default. If you will apply pull-left to a
 then you will not see any extra space but if you will use
 or some other heading then you need to remove default margin from heading.

.pull-left {
  float: left;
  width: 70%;
}
h1.pull-left {
  margin: 0;
}
span.pull-right {
  padding-top: 10px;
}
.pull-right {
  float: right;
  width: 20%;
}

Carl

    $4.81

If you wants heading and span as middle aligned then better to use inline-block as follows:

.block h1,
.block span {
  vertical-align: middle;
  display: inline-block;
}

.block h1 {
  width: 70%;
  margin: 0;
}

.block span {
  width: 20%;
}

Carl

  $4.81

A: Use display inline css value:

Carl

$4.81

A: Use line-height to make different sized texts in same level.

.pull-left {
  float: left;
  width: 70%;
  line-height: 30px;
  margin: 0;
}
.pull-right {
  float: right;
  width: 20%;
  line-height: 30px;
}

Carl

    $4.81

What we've done here is, we made both h1 and span same height even though they have different font-size.
Check the MDN link:
https://developer.mozilla.org/en/docs/Web/CSS/line-height

A: Use table-cell & vertical align that's equally vertically align your text

.block{
display:table;
width:100%;
}
.pull-left{
  width:70%;
  display:table-cell;
  vertical-align:middle;
}
.pull-right{
   width:20%;
   display:table-cell;
  vertical-align:middle;
}

Carl

    $4.81

A: Add this at the start of your css file :

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
 margin: 0;
 padding: 0;
 border: 0;
 font-size: 100%;
 font: inherit;
 vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
 display: block;
}
body {
 line-height: 1;
}
ol, ul {
 list-style: none;
}
blockquote, q {
 quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
 content: '';
 content: none;
}
table {
 border-collapse: collapse;
 border-spacing: 0;
}


text:
Q: SFINAE for cast operator I have a class, which wraps an enum and provides string conversion for it. Now I introduced the template parameter 'fastStringConvert' which controls how the conversion made using SFINAE (found here: how can I use std::enable_if in a conversion operator?). The code compiles under MSVC, but fails under GCC and Clang.
error: no type named 'type' in 'struct std::enable_if<false, void>'

What could be the problem and how should I change the code?
The relevant parts of the code below or here: http://rextester.com/SYC74124
#include <map>
#include <string>
#include <type_traits>

template <
    class SubClass,
    typename EnumType,
    bool fastStringConvert = true
>
class SmartEnum
{
public:
    template <
        typename SFINAEPostponer = EnumType,
        typename = typename std::enable_if<fastStringConvert, void>::type
    >
    explicit operator const std::string&() const
    {
        auto name = SubClass::names().find((int)value);
        if (name != SubClass::names().end())
        {
            return name->second;
        }
        else
        {
            static const std::string na("n.a.");
            return na;
        }
    }

    template <
        typename SFINAEPostponer = EnumType,
        typename = typename std::enable_if<!fastStringConvert, void>::type
    >
    explicit operator const std::string() const
    {
        auto name = SubClass::names().find((int)value);
        if (name != SubClass::names().end()) return name->second;
        else return std::to_string((int)value);
    }

protected:
    typedef const std::map<int, std::string> Names;
    EnumType value;
};

enum class Foo_type : int { a, b, c };

struct Foo : SmartEnum<Foo, Foo_type, true>
{
    typedef SmartEnum<Foo, Foo_type, true> Base;

    static const Base::Names &names()
    {
        static const Base::Names names = { { 0, "a" }, { 1, "b" }, { 2,"c" }};
        return names;
    }
};

A: You have to use template argument from the method, else you have a hard error, something like:
template <
    typename SFINAEPostponer = EnumType,
    bool Cond = !fastStringConvert,
    typename = typename std::enable_if<Cond, void>::type
>
explicit operator const std::string() const

BTW, better to use enable_if as type instead of default value (to allow disable part):
template <
    typename SFINAEPostponer = EnumType,
    bool Cond = !fastStringConvert,
    typename std::enable_if<Cond, void>::type* = nullptr
>
explicit operator const std::string() const


text:
Q: Getting ESLint to ignore unused Angular $log variable For JavaScript I'm using ESLint in Atom with Angular 1.5. I have the following excerpt in my .eslintrc file:
"rules": {
    "no-unused-vars": ["warn", {
        "varsIgnorePattern": "\\$log"
    }]

The ESLint no-unused-vars documentation says I can use a regular expression. Yet ESLint still gives me a warning for the $log variable I have injected in an Angular controller. (I've tried "$log" as well with no escaping, and the same thing happens.)

A: Try to use argsIgnorePattern instead of varssignorepattern


text:
Q: TypeError: plugin.warn is not a function at SQLitePluginTransaction.addStatement Getting below error while inserting data into the a table in React native Sqlite DB
Possible Unhandled Promise Rejection (id: 0):
TypeError: plugin.warn is not a function
TypeError: plugin.warn is not a function
at SQLitePluginTransaction.addStatement (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:416247:18)
at SQLitePluginTransaction.executeSql (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:416228:10)
at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:415677:42
at tryCallTwo (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27207:7)
at doResolve (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27371:15)
at new Promise (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27230:5)
at SQLitePluginTransaction.plugin.. [as executeSql] (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:415656:23)
at SQLitePluginTransaction.fn (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:415583:15)
at SQLitePluginTransaction.start (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:416184:12)
at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:415866:32
Below is the code to insert data into DB
        return new Promise((resolve, reject) => {
            db.transaction((trans) => {
                trans.executeSql(
                    sql,
                    params,
                    (trans, results) => {
                        resolve(results);
                    },
                    (error) => {
                        reject(error);
                    }
                );
            });
        });
    }; ```


text:
Q: Processing formData from alpine js form I have the following html

<form method="post" enctype="multipart/form-data" @submit.prevent="postFormData()">

First Name<input x-model="form.firstname" name="firstname" type="text" required  />

Second Name<input x-model="form.secondname" name="secondname" type="text" required />

Images<input  name="images" type="file" x-on:change="selectFile($event)" accept="image/png, image/jpg, image/jpeg" multiple required />

<button class="btn btn-primary mt-5">Submit Form Data</button>
</form>

and alpine js code

In the backend i have this laravel code
public function alpine_form(Request $request){

        header('Access-Control-Allow-Origin: *');

        header('Access-Control-Allow-Methods: GET, POST');

        header("Access-Control-Allow-Headers: X-Requested-With");

        $data = $request->all();
        $firstname = $data['firstname'];
        $secondname = $data['secondname'];
        $images = $data['images'];
        $ai = '';

        $uploaded_images_array = [];

            //images

        if($request->hasfile('images'))
            {

            foreach($request->file('images') as $fil)
            {
                $nam = mt_rand().uniqid().'.'.$fil->extension();
                $fil->move(public_path().'/uploads/', $nam);
                $uploaded_images_array[] = $nam;
            }

        $ai = json_encode($uploaded_images_array);

            DB::table('form')->insert(
             array(
                    'firstname'     => $firstname,
                    'secondname'   => $secondname,
                    'images'   =>  $ai
             )
        );

            }

    }

I am able to receive firstname and secondname but he images array is always empty when i insert the data into the database. Am i acquiring the images posted correctly?

A: I appended my images like this
postFormData(){

                  //Create an instance of FormData
                const data = new FormData()
                data.append('firstname', this.form.firstname);
                data.append('secondname', this.form.secondname);

                let input_file = document.querySelector('input[type="file"]')

                Array.from(input_file.files).forEach((f) => {
                    data.append('images[]', f)
                })

                let url = 'http://localhost:8000/alpine_form'

                fetch(url, {
                        method: 'POST',
                        /**
                        headers: {
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        */
                        body: data
                    })
                    .then(response => {
                        console.log(response);
                    })
                    .finally(() => {

                    });

                },

and no other modification was necessary.


text:
Q: Can I access a Sharepoint calendar using Microsoft Graph? I need to extract events from a shared calendar on SharePoint.
Using Microsoft Graph I've found the calendar:
https://graph.microsoft.com/v1.0/sites/company.sharepoint.com/lists/CALENDAR_ID
Which includes a list array. I then tried:
https://graph.microsoft.com/v1.0/sites/company.sharepoint.com/lists/CALENDAR_ID/list
Which returns:
 [_decodedBody:Microsoft\Graph\Http\GraphResponse:private] => Array
    (
        [@odata.context] => https://graph.microsoft.com/v1.0/$metadata#sites('company.sharepoint.com')/lists('CALENDAR_ID')/list
        [contentTypesEnabled] => 1
        [hidden] =>
        [template] => events
    )

There are no events listed. I've also tried /sites/{site-id}/lists/{list-id}/items as shown on Microsoft's API reference docs. This does not show the events. Is it possible to extract the events this way?

A: First, for question you've mentioned "/sites/{site-id}/lists/{list-id}/items"
This is only available in graph api beta version, and yes, don't use it in production version of your product.

https://.sharepoint.com/site//_api/web/lists/getbytitle('Calendar')/items

Please try the above code to retrieve your calendar items.

A: Regarding

There are no events listed. I've also tried
  /sites/{site-id}/lists/{list-id}/items as shown on Microsoft's API
  reference docs. This does not show the events

most likely it occurs since Item Level permissions is enabled per Calendar.
How to verify

*

*Go to  Calendar settings in SharePoint UI:
/_layouts/15/listedit.aspx?List={list-id}

*under Advanced Settings verify whether Read items that were
created by the user is selected

If Read items that were created by the user option is selected, then endpoint https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items  will only return events that has been created by current user

In order to return all the events the following options could be considered:
1) disable Item-level Permissions per Calendar by setting it to Read all items
2) or utilize SharePoint API endpoint to retrieve all events: https://server/_api/web/lists/getbyid('<list-id>')/items
Depending on user permissions, you might need to enable Override List Behaviors permission level

otherwise users with restricted permissions will not be able to retrieve all the events


text:
Q: Vote kick after the game has started I know you can vote to kick people before starting a game but is this possible after a game has already started? Specifically kicking people for being AFK unless there is a time out type thing for inactive players.

A: No, you can't kick people while in the game, you can only kick in the lobby. There's really nothing you can do to prevent players from doing something stupid or going AFK in the game except to only play private games.


text:
Q: Eloquent eager loading with hasMany relation doesn't work My code currently doesn't work, but my relations are correct.
Project model
public function timeEntries()
{
    return $this->hasMany('App\Model\TimeEntries');
}

$array_of_project = Project::with('timeEntries')
    ->whereBetween('spent_on', [($request->debut)), ($request->fin))])
    ->get();

It doesn't find 'spent_on.'

A: It looks like you are trying to constrain the relation's records. I suggest looking at the documentation for constraining eager loading. Here is a code sample of what I think you are trying to accomplish:
$projects = App\Model\Project::with(['timeEntries' => function ($query) use ($request) {
    $query->whereBetween('spent_on', $request->debut, $request->fin);
}])->get();

https://laravel.com/docs/5.8/eloquent-relationships#constraining-eager-loads

A: Like @aynber wrote, if your spent_on attribute is part of the related model, it should be included in the query with a closure.
$array_of_project = Project::with(['timeEntries' => function ($time_entry) use ($request) {
    $time_entry->whereBetween('spent_on', [$request->input('debut'), $request->input('fin')]);
}])->get();

A: If spent_on is a column in the time_entries table then your whereBetween is not correct since it will look inside the projects table. But you can add it to with instead:
$array_of_project = Project::with(['timeEntries' => function($query) use ($request) {
    return $query->whereBetween('spent_on', [$request->input('debut'), $request->input('fin')]);
})->get();


text:
Q: Wiping files found by PhotoRec After running PhotoRec, the report.xml file gives a summary of every file that could potentially be restored from my hard disk, for example:
  <fileobject>
    <filename>/place/recup_dir.2/f1234567.png</filename>
    <filesize>47944</filesize>
    <byte_runs>
      <byte_run offset='0' img_offset='825906883201' len='49120'/>
    </byte_runs>
  </fileobject>

Is there any possibility to use these data to specifically wipe the original files from the free space of my hard disk, so it won't be able to restore the file?
Use case: I forgot to wipe a sensitive file that should not be recovered.
Thank you!


text:
Q: my mule application for active mq is not working. Getting error like jar is missing I am new to mule and trying to create mule flow with ActiveMQ. I have added all the related components and configured JMS component also. all seems fine but when I am running the application it is showing required jar is missing.
any help will be useful....thanks in advance

A: I think you are missing here to add the external jar for the acitveMQ.
Try adding activemq-all-5.15.0.jar or latest one in mule using add external jar.
I think that will work out.


text:
Q: Using a function to increment a given number in Python I am trying to simulate a simple game in python. In this game, the player would throw a dice and would move from their current position towards the end line (located in position 100), depending on the dice (which is numbered from 1 to 6).
I'm trying to come up with a function that would do the following: add the current position and the result of the dice. However, if this function gives a number higher than 100, the function would ignore it and throw the dice again, since there's no positions after 100.
Below you can find the 'pseudo-code' I've come up with (half real code, half my ideas/comments):
import random

def movement(current_position, distance):
        current_position = 0 #a counter should be added here I guess to increment the position
        distance = random.randint(1,6)
        move = current_position + distance
              if move > 100; do:
                  #function telling python to ignore it and throw the dice again
              elif move = 100; do:
                  print("You reached position 100")
              else:
                  return move

Could you help me figure out how to do this?

A: You could set up conditions like this where if the dice roll pushes the current value over 100 it is ignored until a dice roll creates a value equal to 100
from random import randint

current = 0
while current != 100:
    r = randint(1, 6)
    if current + r > 100:
        continue
    else:
        current += r
    print(current)

4
8
...
89
93
96
98
99
100

A: you could always check if it's over 100 and then revert to the old position. Then you'd call movement from your main function say def playGame():
def playGame():
    position = 0
    while(position != 100):
         position = movement(position)

def movement(current_position):
    distance = random.randint(1,6)
    current_position += distance
          if move > 100:
              current_position -= distance
          else:
              return current_position


text:
Q: Different repositories for each module in intellij IDEA I'm not sure how to select a different git repo for each different module I have in my IDEA project, I'm not seeing any option for that, all the git options seem to only relate to one git repo.
Is there a way to differentiate them?, so:
(All inside the same project)
Module A -> repo A
Module B -> repo B

?.

A: You might have to edit the vcs.xml manually:

*

*open the vcs.xml of the top module / project
ex.: ~/[Top module folder]/.idea/vcs.xml

*Add the vcs entry:
<mapping directory="$USER_HOME$/sub_module01" vcs="Git" />
<mapping directory="$USER_HOME$/sub_module02" vcs="Git" />

A: Go to Settings/Version Control, there you can configure different VCS roots per directory. So in your case define one VCS root per directory containing the module. You should remove the VCS entry <Project> and just add entries for individual modules so that it looks something like this:

If you have files modified in several different repositories and hit CTRL+K or otherwise open the commit dialog all changed files will be selected and when you commit your changes a new commit with the same message will be created in all repositories containing the changed files.
If you want to commit files from just a single module either manually select them in the commit dialog or right click your module, go to Git and select Commit Directory.
To push the commits just hit CTRL+SHIFT+K and you should see something like this (notice that both modules are included).

A: Okay I think I cracked this one for my circumstance anyway... very confusing as there doesn't seem to be specific instructions on how to set this up anywhere. I have a project that houses an Angular-CLI client-side app and a Grails API server-side app.
So if you are trying to set up CVS using GIT for a multi-moduled project and want to use a separate git repository for each module, not the entire project, then....

*

*Add additional roots by File > Settings > Version Control >

*Click the '+' symbol > browse to the project root and select the module
folder > OK > VCS: select Git > OK

*Repeat step 2 for all other modules

*Once all modules are add that you wish to commit to individual repositories > click the settings OK

*YES, YES, you will immediately be alerted with a 'VCS root mapping' error!!!

*Don't panic. Select the module from the Intellij 'Project/Solution' browser.

*Right-click > select Git > Commit Directory > Unversioned Files  click the 'browse' link and select the module directory and click the green '+' icon.

*You will be warned that that the module is already under Git control but go ahead and add it anyway.

*Repeat steps 7-9 for all other modules.

*This will remove the 'VCS root mapping' error.

*Now go to your version control window which should be located a the bottom of the Intellij application window. There should be an unversioned folder > expand > and you will see all modules listed here.

*Add each of the modules by clicking the '+' button... again???!!! :-)

*Right-click the default tree and select 'commit and push'.

*This will commit all the modules to the local VCS Git

*Once the commit has completed a dialogue 'Push Commits' will appear where you will see that each module has an open to add your remote repo url for each module!!!!

*Yey!!!!

Hope this is helpful for all :-)


text:
Q: ORA-00904: "TIMESTAMP": invalid identifier on perl script DBI->connect using 'old-style' syntax is deprecated and will be an error in future
versions at /home/dbadmin/perl/adm_audit_mhs line 43
Can't prepare SQL statement: ORA-00904: "TIMESTAMP": invalid identifier (DBD ERROR:
error possibly near <*> indicator at char 281 in
   'SELECT OS_USERNAME, USERNAME, TERMINAL, TIMESTAMP,
           SQL_TEX,0,'Successful','Failed') RETURNCODE
    FROM unified_audit_trail
    WHERE action IN (43,51,53)
      AND <*>timestamp between Trunc(SYSDATE-1) AND Trunc(SYSDATE)')

Please help I'm getting this error while running a perl script to pull information from  unified_audit_trail view. Thanks in advance

A: As the error indicates, there is no timestamp column in unified_audit_trail.  There is an event_timestamp column which is what I'm guessing you meant to reference.


text:
Q: Magento 2 - Enable the authorisation login popup modal How do I activate the authorize Login popup modal for Magento 2?
Like shown below. Is this a Extension or can I activate this by configuration or by edits in my Theme?


text:
Q: iPad SwiftUI landscape orientation only I've created a swiftUI app and noticed that no matter what settings I change, the iPad version of the app will always allow portrait orientation. The iPhone version of the app works as expected.
Here are some screenshots of my settings:

How can I get the iPad app to only allow landscape orientation in SwiftUI?
I am running Xcode 12.4

A: Yes you can change SwiftUI app landscape orientation only

*

*Select iPad and deselect iPhone

*Set the orientations support as required

*Un-set Supports multiple windows if you want

*Switch back to iPhone and iPad

Here is the video demo

A: Unfortunately this does not seem to be supported with the SwiftUI application lifecycle, even with use of UIApplicationDelegateAdaptor. This may be an intentional design decision to encourage developers to design resizable window applications (for multitasking & macOS).
If you switch to the UIKit lifecycle by replacing your App struct with UIApplicationDelegate/UISceneDelegate, you'll be able to allow only landscape orientation.


text:
Q: change json structure of column data frame pandas with nested json sorry i want to ask i want to change json structure of pandas data frame column with nested json
but after trying to search in several sources have not found a solution. Maybe someone here can help, please help!
thanks
for the code like this:
import pandas as pd
import json
d = {'id': ['xxx'], 'user': ['asdam']}
df = pd.DataFrame(data=d)
result = df.to_json(orient="records")
parsed = json.loads(result)
json.dumps(parsed, indent=4)

for the json I want it to appear something like this:
{'id':'xxx','user':{'display_name':'asdam'}}

A: you can use a lambda function (a little strange but it works):
import pandas as pd
import json
d = {'id': ['xxx'], 'user': ['asdam']}
df = pd.DataFrame(data=d)
df['user']=df['user'].apply(lambda x: {'display_name':x}) # create a dictionary with row value
result = df.to_json(orient="records")
parsed = json.loads(result)
parsed =json.dumps(parsed, indent=4)
print(parsed)
'''
[
    {
        "id": "xxx",
        "user": {
            "display_name": "asdam"
        }
    }
]
'''


text:
Q: Make JPopupMenu NOT close on item selection Here's what I want to do. I am making a popup that suggests words, 10 at a time, with the option to display the next 10 suggestions. I designed this as a JPopupMenu with 11 items; 10 suggestions and one "Show more..." option.

The code that is run on the "Show more..." removes all the previous items, and adds the new ones (simple enough).
The problem is that when I press "Show more..." the JPopupMenu closes (as I suppose is the default behaviour). I have tried working my way around this, even by creating a whole new popup and display it on the same location.
Is there a simple way to make a JPopupMenu NOT disappear when pressing one of its items?
Thanks in advance!

A: I've been using this for checkbox items:
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.MenuSelectionManager;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicCheckBoxMenuItemUI;

public class StayOpenCheckBoxMenuItemUI extends BasicCheckBoxMenuItemUI {

    @Override
    protected void doClick(MenuSelectionManager msm) {
        menuItem.doClick(0);
    }

    public static ComponentUI createUI(JComponent c) {
        return new StayOpenCheckBoxMenuItemUI();
    }

}

Then, register it:
myJCheckBoxMenuItem.setUI(new StayOpenCheckBoxMenuItemUI());

Depending on what type of menu item your 'Show more' item is, similar solution should work. Just subclass the proper UI instead of BasicCheckBoxMenuItemUI.


text:
Q: gsl gnu scientific library segmentation fault when calling gsl_blas_ddot When I compile the code below there are no errors reported by gcc :
#include <stdio.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>

int main (void)
{
  int i;

  gsl_vector * v = gsl_vector_alloc (3);

  for (i = 0; i < 3; i++)
    {
      gsl_vector_set (v, i, 1);
    }

  gsl_vector * v2 = gsl_vector_alloc (3);

  for (i = 0; i < 3; i++)
    {
      gsl_vector_set (v2, i, 2);
    }

  double *result ;

  gsl_blas_ddot(v, v2, result) ;

  printf("result of dot product is %f\n", *result );

  return 0;
}

But i get runtime error :
Segmentation fault (core dumped)

referred to the call to gsl_blas_ddot. I can't realize what is the problem. The v and v2 vectors are correctly allocated.

A: I'm not familiar with that library, however, the posted source code has this statement:
double *result ;

however, the pointer result is never set to point to any memory that the application owns.
Suggest changing to :
double result;

and modifying the following line:
gsl_blas_ddot(v, v2, result) ;

to
gsl_blas_ddot(v, v2, &result) ;


text:
Q: Why does Y do the same thing as yy? I've been using vim for several months now and I've gotten used to using C and D to change and delete everything from the cursor to the end of the line.
Consider the line below where the cursor is on the 'b' in 'bar':
foo.bar("hello world")

Hitting D at this point will yield:
foo.

While hitting C will do the same plus start insert mode with the cursor after the period.
However, pressing Y doesn't do the intuitively similar thing (copying everything from the cursor to the end of the line). Instead, it copies the entire line (just like yy).
How do I make Y copy the characters from the cursor to the end of the line instead of copying the entire line like yy?

A: From this configuration:
" make Y effect to end of line instead of whole line
map Y y$

I suspect the default behaviour is simply due to some historical inconsistency.

A: nmap Y y$
Does that do what you want?
EDIT
The reason why Y does the same thing as yy probably has something to do with this:
{Visual}["x]y           Yank the highlighted text [into register x] (for
                        {Visual} see |Visual-mode|).  {not in Vi}

                                                        *v_Y*
{Visual}["x]Y           Yank the highlighted lines [into register x] (for
                        {Visual} see |Visual-mode|).  {not in Vi}

Y is meant to act on lines, y is meant to act on individual characters?


text:
Q: onchange event on input type=range is not triggering in Firefox while dragging When I played with <input type="range">, Firefox triggers an onchange event only if we drop the slider to a new position where Chrome and others triggers onchange events while the slider is dragged.
How can I make it happen on dragging in Firefox?

function showVal(newVal){
    document.getElementById("valBox").innerHTML=newVal;
}

<input type="range" min="5" max="10" step="1" onchange="showVal(this.value)">

A: Andrew Willem's solutions are not mobile device compatible.
Here's a modification of his second solution that works in Edge, IE, Opera, FF, Chrome, iOS Safari and mobile equivalents (that I could test):
Update 1: Removed "requestAnimationFrame" portion, as I agree it's not necessary:
var listener = function() {
  // do whatever
};

slider1.addEventListener("input", function() {
  listener();
  slider1.addEventListener("change", listener);
});
slider1.addEventListener("change", function() {
  listener();
  slider1.removeEventListener("input", listener);
});

Update 2: Response to Andrew's 2nd Jun 2016 updated answer:
Thanks, Andrew - that appears to work in every browser I could find (Win desktop: IE, Chrome, Opera, FF; Android Chrome, Opera and FF, iOS Safari).
Update 3: if ("oninput in slider) solution
The following appears to work across all the above browsers. (I cannot find the original source now.) I was using this, but it subsequently failed on IE and so I went looking for a different one, hence I ended up here.
if ("oninput" in slider1) {
    slider1.addEventListener("input", function () {
        // do whatever;
    }, false);
}

But before I checked your solution, I noticed this was working again in IE - perhaps there was some other conflict.

A: Apparently Chrome and Safari are wrong: onchange should only be triggered when the user releases the mouse. To get continuous updates, you should use the oninput event, which will capture live updates in Firefox, Safari and Chrome, both from the mouse and the keyboard.
However, oninput is not supported in IE10, so your best bet is to combine the two event handlers, like this:

<input
  type="range"
  min="5"
  max="10"
  step="1"
  oninput="showVal(this.value)"
  onchange="showVal(this.value)"
/>

Check out this Bugzilla thread for more information.

A: SUMMARY:
I provide here a no-jQuery cross-browser desktop-and-mobile ability to consistently respond to range/slider interactions, something not possible in current browsers. It essentially forces all browsers to emulate IE11's on("change"... event for either their on("change"... or on("input"... events. The new function is...
function onRangeChange(r,f) {
  var n,c,m;
  r.addEventListener("input",function(e){n=1;c=e.target.value;if(c!=m)f(e);m=c;});
  r.addEventListener("change",function(e){if(!n)f(e);});
}

...where r is your range input element and f is your listener. The listener will be called after any interaction that changes the range/slider value but not after interactions that do not change that value, including initial mouse or touch interactions at the current slider position or upon moving off either end of the slider.
Problem:
As of early June 2016, different browsers differ in terms of how they respond to range/slider usage. Five scenarios are relevant:

*

*initial mouse-down (or touch-start) at the current slider position

*initial mouse-down (or touch-start) at a new slider position

*any subsequent mouse (or touch) movement after 1 or 2 along the slider

*any subsequent mouse (or touch) movement after 1 or 2 past either end of the slider

*final mouse-up (or touch-end)

The following table shows how at least three different desktop browsers differ in their behaviour with respect to which of the above scenarios they respond to:

Solution:
The onRangeChange function provides a consistent and predictable cross-browser response to range/slider interactions. It forces all browsers to behave according to the following table:

In IE11, the code essentially allows everything to operate as per the status quo, i.e. it allows the "change" event to function in its standard way and the "input" event is irrelevant as it never fires anyway. In other browsers, the "change" event is effectively silenced (to prevent extra and sometimes not-readily-apparent events from firing). In addition, the "input" event fires its listener only when the range/slider's value changes. For some browsers (e.g. Firefox) this occurs because the listener is effectively silenced in scenarios 1, 4 and 5 from the above list.
(If you truly require a listener to be activated in either scenario 1, 4 and/or 5 you could try incorporating "mousedown"/"touchstart", "mousemove"/"touchmove" and/or "mouseup"/"touchend" events. Such a solution is beyond the scope of this answer.)
Functionality in Mobile Browsers:
I have tested this code in desktop browsers but not in any mobile browsers. However, in another answer on this page MBourne has shown that my solution here "...appears to work in every browser I could find (Win desktop: IE, Chrome, Opera, FF; Android Chrome, Opera and FF, iOS Safari)". (Thanks MBourne.)
Usage:
To use this solution, include the onRangeChange function from the summary above (simplified/minified) or the demo code snippet below (functionally identical but more self-explanatory) in your own code. Invoke it as follows:
onRangeChange(myRangeInputElmt, myListener);

where myRangeInputElmt is your desired <input type="range"> DOM element and myListener is the listener/handler function you want invoked upon "change"-like events.
Your listener may be parameter-less if desired or may use the event parameter, i.e. either of the following would work, depending on your needs:
var myListener = function() {...

or
var myListener = function(evt) {...

(Removing the event listener from the input element (e.g. using removeEventListener) is not addressed in this answer.)
Demo Description:
In the code snippet below, the function onRangeChange provides the universal solution. The rest of the code is simply an example to demonstrate its use. Any variable that begins with my... is irrelevant to the universal solution and is only present for the sake of the demo.
The demo shows the range/slider value as well as the number of times the standard "change", "input" and custom "onRangeChange" events have fired (rows A, B and C respectively). When running this snippet in different browsers, note the following as you interact with the range/slider:

*

*In IE11, the values in rows A and C both change in scenarios 2 and 3 above while row B never changes.

*In Chrome and Safari, the values in rows B and C both change in scenarios 2 and 3 while row A changes only for scenario 5.

*In Firefox, the value in row A changes only for scenario 5, row B changes for all five scenarios, and row C changes only for scenarios 2 and 3.

*In all of the above browsers, the changes in row C (the proposed solution) are identical, i.e. only for scenarios 2 and 3.

Demo Code:

// main function for emulating IE11's "change" event:

function onRangeChange(rangeInputElmt, listener) {

  var inputEvtHasNeverFired = true;

  var rangeValue = {current: undefined, mostRecent: undefined};

  rangeInputElmt.addEventListener("input", function(evt) {
    inputEvtHasNeverFired = false;
    rangeValue.current = evt.target.value;
    if (rangeValue.current !== rangeValue.mostRecent) {
      listener(evt);
    }
    rangeValue.mostRecent = rangeValue.current;
  });

  rangeInputElmt.addEventListener("change", function(evt) {
    if (inputEvtHasNeverFired) {
      listener(evt);
    }
  });

}

// example usage:

var myRangeInputElmt = document.querySelector("input"          );
var myRangeValPar    = document.querySelector("#rangeValPar"   );
var myNumChgEvtsCell = document.querySelector("#numChgEvtsCell");
var myNumInpEvtsCell = document.querySelector("#numInpEvtsCell");
var myNumCusEvtsCell = document.querySelector("#numCusEvtsCell");

var myNumEvts = {input: 0, change: 0, custom: 0};

var myUpdate = function() {
  myNumChgEvtsCell.innerHTML = myNumEvts["change"];
  myNumInpEvtsCell.innerHTML = myNumEvts["input" ];
  myNumCusEvtsCell.innerHTML = myNumEvts["custom"];
};

["input", "change"].forEach(function(myEvtType) {
  myRangeInputElmt.addEventListener(myEvtType,  function() {
    myNumEvts[myEvtType] += 1;
    myUpdate();
  });
});

var myListener = function(myEvt) {
  myNumEvts["custom"] += 1;
  myRangeValPar.innerHTML = "range value: " + myEvt.target.value;
  myUpdate();
};

onRangeChange(myRangeInputElmt, myListener);
table {
  border-collapse: collapse;
}
th, td {
  text-align: left;
  border: solid black 1px;
  padding: 5px 15px;
}
<input type="range"/>

range value: 50

row	event type                     	number of events

A	standard "change" events         	0

B	standard "input" events          	0

C	new custom "onRangeChange" events	0

Credit:
While the implementation here is largely my own, it was inspired by MBourne's answer. That other answer suggested that the "input" and "change" events could be merged and that the resulting code would work in both desktop and mobile browsers. However, the code in that answer results in hidden "extra" events being fired, which in and of itself is problematic, and the events fired differ between browsers, a further problem. My implementation here solves those problems.
Keywords:
JavaScript input type range slider events change input browser compatability cross-browser desktop mobile no-jQuery

A: For a good cross-browser behavior, and understandable code, best is to use the onchange attribute in combination of a form:

function showVal(){
  valBox.innerHTML = inVal.value;
}
<form onchange="showVal()">
  <input type="range" min="5" max="10" step="1" id="inVal">
</form>

The same using oninput, the value is changed directly.

function showVal(){
  valBox.innerHTML = inVal.value;
}
<form oninput="showVal()">
  <input type="range" min="5" max="10" step="1" id="inVal">
</form>

A: I'm posting this as an answer because it deserves to be it's own answer rather than a comment under a less useful answer. I find this method much better than the accepted answer since it can keep all the js in a separate file from the HTML.
Answer provided by Jamrelian in his comment under the accepted answer.
$("#myelement").on("input change", function() {
    //do something
});

Just be aware of this comment by  Jaime though

Just note that with this solution, in chrome you will get two calls to the handler (one per event), so if you care for that, then you need to guard against it.

As in it will fire the event when you have stopped moving the mouse, and then again when you release the mouse button.
Update
In relation to the change event and input event causing the functionality to trigger twice, this is pretty much a non-issue.
If you have a function firing off on input, it is extremely unlikely that there will be a problem when the change event fires.
input fires rapidly as you drag a range input slider. Worrying about one more function call firing at the end is like worrying about a single drop of water compared to the ocean of water that is the input events.
The reason for even including the change event at all is for the sake of browser compatibility (mainly with IE).

A: UPDATE: I am leaving this answer here as an example of how to use mouse events to use range/slider interactions in desktop (but not mobile) browsers. However, I have now also written a completely different and, I believe, better answer elsewhere on this page that uses a different approach to providing a cross-browser desktop-and-mobile solution to this problem.
Original answer:
Summary: A cross-browser, plain JavaScript (i.e. no-jQuery) solution to allow reading range input values without using on('input'... and/or on('change'... which work inconsistently between browsers.
As of today (late Feb, 2016), there is still browser inconsistency so I'm providing a new work-around here.
The problem: When using a range input, i.e. a slider, on('input'... provides continuously updated range values in Mac and Windows Firefox, Chrome and Opera as well as Mac Safari, while on('change'... only reports the range value upon mouse-up. In contrast, in Internet Explorer (v11), on('input'... does not work at all, and on('change'... is continuously updated.
I report here 2 strategies to get identical continuous range value reporting in all browsers using vanilla JavaScript (i.e. no jQuery) by using the mousedown, mousemove and (possibly) mouseup events.
Strategy 1: Shorter but less efficient
If you prefer shorter code over more efficient code, you can use this 1st solution which uses mousesdown and mousemove but not mouseup. This reads the slider as needed, but continues firing unnecessarily during any mouse-over events, even when the user has not clicked and is thus not dragging the slider. It essentially reads the range value both after 'mousedown' and during 'mousemove' events, slightly delaying each using requestAnimationFrame.

var rng = document.querySelector("input");

read("mousedown");
read("mousemove");
read("keydown"); // include this to also allow keyboard control

function read(evtType) {
  rng.addEventListener(evtType, function() {
    window.requestAnimationFrame(function () {
      document.querySelector("div").innerHTML = rng.value;
      rng.setAttribute("aria-valuenow", rng.value); // include for accessibility
    });
  });
}

50
<input type="range"/>

Strategy 2: Longer but more efficient
If you need more efficient code and can tolerate longer code length, then you can use the following solution which uses mousedown, mousemove and mouseup. This also reads the slider as needed, but appropriately stops reading it as soon as the mouse button is released. The essential difference is that is only starts listening for 'mousemove' after 'mousedown', and it stops listening for 'mousemove' after 'mouseup'.

var rng = document.querySelector("input");

var listener = function() {
  window.requestAnimationFrame(function() {
    document.querySelector("div").innerHTML = rng.value;
  });
};

rng.addEventListener("mousedown", function() {
  listener();
  rng.addEventListener("mousemove", listener);
});
rng.addEventListener("mouseup", function() {
  rng.removeEventListener("mousemove", listener);
});

// include the following line to maintain accessibility
// by allowing the listener to also be fired for
// appropriate keyboard events
rng.addEventListener("keydown", listener);

50
<input type="range"/>

Demo: Fuller explanation of the need for, and implementation of, the above work-arounds
The following code more fully demonstrates numerous aspects of this strategy. Explanations are embedded in the demonstration:

var select, inp, listen, unlisten, anim, show, onInp, onChg, onDn1, onDn2, onMv1, onMv2, onUp, onMvCombo1, onDnCombo1, onUpCombo2, onMvCombo2, onDnCombo2;

select   = function(selctr)     { return document.querySelector(selctr);      };
inp = select("input");
listen   = function(evtTyp, cb) { return inp.   addEventListener(evtTyp, cb); };
unlisten = function(evtTyp, cb) { return inp.removeEventListener(evtTyp, cb); };
anim     = function(cb)         { return window.requestAnimationFrame(cb);    };
show = function(id) {
 return function() {
    select("#" + id + " td~td~td"   ).innerHTML = inp.value;
    select("#" + id + " td~td~td~td").innerHTML = (Math.random() * 1e20).toString(36); // random text
  };
};

onInp      =                  show("inp" )                                      ;
onChg      =                  show("chg" )                                      ;
onDn1      =                  show("mdn1")                                      ;
onDn2      = function() {anim(show("mdn2"));                                   };
onMv1      =                  show("mmv1")                                      ;
onMv2      = function() {anim(show("mmv2"));                                   };
onUp       =                  show("mup" )                                      ;
onMvCombo1 = function() {anim(show("cmb1"));                                   };
onDnCombo1 = function() {anim(show("cmb1"));   listen("mousemove", onMvCombo1);};
onUpCombo2 = function() {                    unlisten("mousemove", onMvCombo2);};
onMvCombo2 = function() {anim(show("cmb2"));                                   };
onDnCombo2 = function() {anim(show("cmb2"));   listen("mousemove", onMvCombo2);};

listen("input"    , onInp     );
listen("change"   , onChg     );
listen("mousedown", onDn1     );
listen("mousedown", onDn2     );
listen("mousemove", onMv1     );
listen("mousemove", onMv2     );
listen("mouseup"  , onUp      );
listen("mousedown", onDnCombo1);
listen("mousedown", onDnCombo2);
listen("mouseup"  , onUpCombo2);
table {border-collapse: collapse; font: 10pt Courier;}
th, td {border: solid black 1px; padding: 0 0.5em;}
input {margin: 2em;}
li {padding-bottom: 1em;}

Click on 'Full page' to see the demonstration properly.

	event	range value	random update indicator

A	input                                	100	-

B	change                               	100	-

C	mousedown                            	100	-

D	mousedown using requestAnimationFrame	100	-

E	mousemove                            	100	-

F	mousemove using requestAnimationFrame	100	-

G	mouseup                              	100	-

H	mousedown/move combo                 	100	-

I	mousedown/move/up combo              	100	-

<input type="range" min="100" max="999" value="100"/>

The 'range value' column shows the value of the 'value' attribute of the range-type input, i.e. the slider. The 'random update indicator' column shows random text as an indicator of whether events are being actively fired and handled.

To see browser differences between input and change event implementations, use the slider in different browsers and compare A and B.

To see the importance of 'requestAnimationFrame' on 'mousedown', click a new location on the slider and compare C (incorrect) and D (correct).

To see the importance of 'requestAnimationFrame' on 'mousemove', click and drag but do not release the slider, and compare E (often 1 pixel behind) and F (correct).

To see why an initial mousedown is required (i.e. to see why mousemove alone is insufficient), click and hold but do not drag the slider and compare E (incorrect), F (incorrect) and H (correct).

To see how the mouse event combinations can provide a work-around for continuous update of a range-type input, use the slider in any manner and note whichever of A or B continuously updates the range value in your current browser. Then, while still using the slider, note that H and I provide the same continuously updated range value readings as A or B.

To see how the mouseup event reduces unnecessary calculations in the work-around, use the slider in any manner and compare H and I. They both provide correct range value readings. However, then ensure the mouse is released (i.e. not clicked) and move it over the slider without clicking and notice the ongoing updates in the third table column for H but not I.

A: I'm posting this as an answer in case you are like me and cannot figure out why the range type input doesn't work on ANY mobile browsers. If you develop mobile apps on your laptop and use the responsive mode to emulate touch, you will notice the range doesn't even move when you have the touch simulator activated. It starts moving when you deactivate it. I went on for 2 days trying every piece of code I could find on the subject and could not make it work for the life of me. I provide a WORKING solution in this post.
Mobile Browsers And Hybrid Apps
Mobile browsers run using a component called Webkit for iOS and WebView for Android. The WebView/WebKit enables you to embed a web browser, which does not have any chrome or firefox (browser) controls including window frames, menus, toolbars and scroll bars into your activity layout. In other words, mobile browsers lack a lot of web components normally found in regular browsers. This is the problem with the range type input. If the user's browser doesn't support range type, it will fall back and treat it as a text input. This is why you cannot move the range when the touch simulator is activated.

Read more here on browser compatibility

jQuery Slider
jQuery provides a slider that somehow works with touch simulation but it is choppy and not very smooth. It wasn't satisfying to me and it probably wont be for you either but you can make it work more smoothly if you combine it with jqueryUi.
Best Solution : Range Touch
If you develop hybrid apps on your laptop, there is a simple and easy library you can use to enable range type input to work with touch events.
This library is called Range Touch.
DEMO

For more information on this issue check this thread here

Recreating the HTML5 range input for Mobile Safari (webkit)?

A: Yet another approach - just set a flag on an element signaling which type of event should be handled:
function setRangeValueChangeHandler(rangeElement, handler) {
    rangeElement.oninput = (event) => {
        handler(event);
        // Save flag that we are using onInput in current browser
        event.target.onInputHasBeenCalled = true;
    };

    rangeElement.onchange = (event) => {
        // Call only if we are not using onInput in current browser
        if (!event.target.onInputHasBeenCalled) {
            handler(event);
        }
    };
}

A: This work for me in React-bootstrap
           <Form.Control
              type="range"
              className="slider"
              min="0.1"
              max="10"
              step={0.1}
              value={intensity}
              onChange={(e: any) => {
                if (!e.target.onInputHasBeenCalled) {
                  setIntensity(parseFloat(e.target.value.toString()));
                  e.target.onInputHasBeenCalled = true;
                } else {
                  e.target.onInputHasBeenCalled = false;
                }
              }}
            />

A: You could use the JavaScript "ondrag" event to fire continuously. It is better than "input" due to the following reasons:

*

*Browser support.

*Could differentiate between "ondrag" and "change" event. "input" fires for both drag and change.
In jQuery:
$('#sample').on('drag',function(e){

});

Reference:
http://www.w3schools.com/TAgs/ev_ondrag.asp


text:
Q: Why is my Drupal 8 module show Page not found? I'm following the Modules, Routes and Controllers tutorial. However, I kept getting "Page not found" regardless of "Clear all cache".
dino_roar.info.yml file:
name: Dino ROAR
type: module
description: "ROAR at you"
package: Custom
core: 8.x

dino_roar.routing.yml
dino_says:
  path: /the/dino/says/
  defaults:
    _controller: Drupal\dino_roar\Controller\RoarController::roar
  requirements:
    _permission: 'access content'

and src/Controller/RoarController.php file:
<?php

namespace Drupal\dino_roar\Controller;
use Symfony\Component\HttpFoundation\Response;

class RoarController
{
    public function roar(){
        return new Response('ROOOOAR');
    }
}

When accessing through: http://drupal-8.dd:8083/the/dino/says/ I get the page not found error. Any suggestion is much appreciated.
Below is my folder structure:

And this is what it looks when I collapsed the src folder.

A: The main module info yml file has to be named after the following scheme:
module_name.info.yml

So it's dino_roar.info.yml for your module. Also you need to enable your module, but as far as I know when the correct named info yml file is not present Drupal doesn't even know about your module.
Also make sure your folder structure is correct:
dino_roar
  --> src
    --> Controller
           RoarController.php
  dino_roar.info.yml
  dino_roar.routing.yml

A: Got some help from Shashwat Purav at Drupal.org. Below is the routing file I've changed to that works.
dino_roar.dino_says:
    path: /dino/says
    defaults:
        _controller: '\Drupal\dino_roar\Controller\RoarController::roar'
    requirements:
        _permission: 'access content'

A: I think it is because of your original routing issue,
 you should change "path: /the/dino/says/"  to "path: /the/dino/says"
after remove the last slash,  should be fine .


text:
Q: Using plyr::mapvalues with dplyr plyr::mapvalues can be used like this:
mapvalues(mtcars$cyl, c(4, 6, 8), c("a", "b", "c"))

But this doesn't work:
mtcars %>%
dplyr::select(cyl) %>%
mapvalues(c(4, 6, 8), c("a", "b", "c")) %>%
as.data.frame()

How can I use plyr::mapvalues with dplyr? Or even better, what the dplyr equivalent?

A: I was a heavy plyr::mapvalues() user. I used it for replacing old values in strings with new ones. Something like:
set.seed(1)
data <- data.frame(name = sample(letters[1:5], 100, replace = TRUE))
check_list <- data.frame(old = letters[1:5], new = LETTERS[1:5])

data$name
#> [1] "a" "d" "a" "b" "e" "c" "b" "c" "c" "a" "e" "e" "b" "b"

plyr::mapvalues(data$name, check_list$old, check_list$new)
#> [1] "A" "D" "A" "B" "E" "C" "B" "C" "C" "A" "E" "E" "B" "B" ...

Please correct me if I am wrong, but there is not an equally short and tidy dplyr way of doing this. You can still do it with dplyr::recode(), however:
dplyr::recode(data$name, !!!setNames(check_list$new, check_list$old))
#> [1] "A" "D" "A" "B" "E" "C" "B" "C" "C" "A" "E" "E" "B" "B" ...

As it says in the documentation, the order for the named vector is old (name) = new (value), which is the opposite to dplyr::mutate() and dplyr::rename() functions (when writing, might have been fixed later).
Adding this as an answer because I keep Googling how to do it when I forget and could not find the answer quickly. Perhaps now I can. The solution is modified from the last two lines of Examples in the function documentation.

A: 2020 Update:  plyr is now a "retired" package and its official guidance suggests using the actively-improved and maintained dplyr package instead. So it's preferable to use only dplyr, in this case dplyr::recode() as in the other answer, and avoid plyr entirely.
To use plyr::mapvalues() with dplyr:
To use it and return a one-column data.frame:
mtcars %>%
  transmute(cyl = plyr::mapvalues(cyl, c(4, 6, 8), c("a", "b", "c")))

Or if you want a single vector output, like in your working example, use pull:
mtcars %>%
  pull(cyl) %>%
  plyr::mapvalues(., c(4, 6, 8), c("a", "b", "c"))

If you are using both dplyr and plyr simultaneously, see this note from the dplyr readme:

You'll need to be a little careful if you load both plyr and dplyr at
the same time. I'd recommend loading plyr first, then dplyr, so that
the faster dplyr functions come first in the search path. By and
large, any function provided by both dplyr and plyr works in a similar
way, although dplyr functions tend to be faster and more general.

Though note that you can call mapvalues using plyr::mapvalues if dplyr is loaded without needing to load plyr.

A: As the questions also mentions

Or even better, what the dplyr equivalent?

The equivalent is recode.
http://www.cookbook-r.com/Manipulating_data/Renaming_levels_of_a_factor/
name <- c("John", "Clara", "Smith")
sex <- c(1,2,1)
age <- c(30,32,54)
df <- data.frame(name,sex,age)
df %>% mutate(sex=recode(sex,
`1`="Male",
`2`="Female"))

This will "mapvalues" 1 to Male and 2 to Female.


text:
Q: Why is jsp used at client side? I am working on a project on spring MVC which has the code in the client side in jsp instead of javascript and html. I would really appreciate if you could explain why this is used and not javascript and html. Can this be replaced by javascript and html without loss of functionality

A: JSP is executed on server side and it renders an HTML page (including embedded javascript and css). So on your browser Javascript and HTML code is executed, not the JSP code.
You can verify the same by using developer tools of your browser, you wont find any JSP code there.
And yes, all your work can be done by Javascript/HTML as well. Just that you will have to use AJAX to get the dynamic data that you need to show of your page.


text:
Q: PostgreSQL server user-admin roles to approve changes to db from a lower-role admin Server administrative roles for PostgreSQL need to be configured in a way that there are high-level/role admins that will approve/allow all of the changes made to a database by lower-level/role admins.
I know there are roles for admins but the question is how to create that approval mechanism?
Also, can that be done better with Firebird database?

A: There are no facilities in PostgreSQL for something like this.
You can of course write triggers that record the attempted changes in a second "approval table" instead, plus a function that applies changes from that approval table.


text:
Q: How to stream video in gopro HERO4 with firmware 2.0.0 For older version of firmware working this solution:
Start streaming: http://10.5.5.9/gp/gpControl/execute?p1=gpStream&c1=start
and download streaming data using port UDP 8554.
Unfortunately this solution working only with old software version. With last one 02.00.00 not working. Gopro sending some data on UDP port but data is not correct and does not contain streaming informations (only about 1kB/sec). Also streaming method from HERO3 not working.

A: These are the working commands for Hero4:

*

*Start Streaming:
http://10.5.5.9/gp/gpControl/execute?p1=gpStream&c1=start

*Restart Streaming:  http://10.5.5.9/gp/gpControl/execute?p1=gpStream&c1=restart

*Stop Streaming: http://10.5.5.9/gp/gpControl/execute?p1=gpStream&c1=stop
Video can be streamed by using aplay or ffplay on udp://:8554, connection must be kept alive using a script.


text:
Q: Video converting into mp3 on Java, Android I need to convert mp4/flv files info mp3 in my Android application, but I don't know C/C++ and Android NDK. Do you know libraries/methods for easy converting on Java? Thank you for anyway.

A: Your question is how to extract audio from MP4/ FLV files and save as mp3 file. Right ?
Then, very sorry, Android SDK does not provide any API for transformating or track extraction.
Also using available media framework to achieve the same is also not trivial (and even if you do, you will lose portability).
What I would suggest is to use your MP4 & FLV Parser to extract audio track, do transcoding (if audio track is non-mp3), and save the transcoded (if audio track extracted is mp3, then extracted data) data.
Or you can port FFMPEG code base and use the same. This again may be overkill for your small task.
Suppose you just want to extract mp3 track from MP4, then you understand the native mp4 parser and use the APIs for extraction. You may have to replicate some code from stagefright / opencore.
Shash

A: it's probably irrelevant for you anymore but if some one still need a mp4 to mp3 parser here's an api that can do the job


text:
Q: GRUB strange behaviour I have Ubuntu 18.04 Server. I find the behaviour of GRUB is strange.
When I uncomment line in /etc/default/grub:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash intel_iommu=on"

intel_iommu isn't loaded in the kernel.
And when I uncomment line:
GRUB_CMDLINE_LINUX="intel_iommu=on"

intel_iommu is loaded in the kernel.
My config:
GRUB_DEFAULT=0
#GRUB_TIMEOUT_STYLE=hidden
GRUB_TIMEOUT_STYLE=menu
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
#GRUB_CMDLINE_LINUX_DEFAULT="maybe-ubiquity"
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash intel_iommu=on"
GRUB_CMDLINE_LINUX=""
#GRUB_CMDLINE_LINUX="intel_iommu=on"

I know that GRUB_CMDLINE_LINUX_DEFAULT is loaded when is normal mode only. Contrarywise GRUB_CMDLINE_LINUX is loaded when is normal mode or recovery mode.
Do it seems my ubuntu load in recovery mode?
Why intel_iommu do not load with GRUB_CMDLINE_LINUX_DEFAULT?
Where can I look for a log of GRUB loading?
EDIT:
After that, I didn't forget about sudo update-grub.
UPDATE:
1. When so:
GRUB_CMDLINE_LINUX_DEFAULT="maybe-ubiquity"
#GRUB_CMDLINE_LINUX_DEFAULT="quiet splash intel_iommu=on"
#GRUB_CMDLINE_LINUX=""
GRUB_CMDLINE_LINUX="intel_iommu=on"

Result:
# sudo virt-host-validate
...
QEMU: Checking if IOMMU is enabled by kernel                               : PASS
...

# dmesg | grep -E "IOMMU"
[    0.000000] DMAR: IOMMU enabled
[    0.000000] DMAR-IR: IOAPIC id 8 under DRHD base  0xfed91000 IOMMU 1

# cat /etc/modules
# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored.

2. And when so:
#GRUB_CMDLINE_LINUX_DEFAULT="maybe-ubiquity"
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash intel_iommu=on"
GRUB_CMDLINE_LINUX=""
#GRUB_CMDLINE_LINUX="intel_iommu=on"

Result:
# sudo virt-host-validate
...
QEMU: Checking if IOMMU is enabled by kernel                               : WARN (IOMMU appears to be disabled in kernel. Add intel_iommu=on to kernel cmdline arguments)
...

# dmesg | grep -E "IOMMU"
[    0.000000] DMAR-IR: IOAPIC id 8 under DRHD base  0xfed91000 IOMMU 1

# cat /etc/modules
# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored.


text:
Q: how to use a variable value in my email template that fetch from database My Email Format like
$confirmationcode = rand(10, 1000);
$unumber = uniqid();
$message= '

'.$fetch_tration.'

 ';

        $config['protocol'] = 'smtp';
        $config['smtp_host'] = 'ssl://smtp.gmail.com';
        $config['smtp_port'] = 465;
        $config['smtp_user'] = 'example@example.com';
        $config['smtp_pass'] = '************';
        $config['charset'] = 'utf-8';
        $config['wordwrap'] = TRUE;
        $this->load->library('email');
        $this->email->initialize($config);
        $this->email->set_newline("\r\n");
        $this->email->from('example@example.com', 'Admin Team');
        $this->email->to(example@example.com);
        $this->email->subject('Confirm  Registration');
        $this->email->message($message);
        $this->email->set_mailtype('html');
        $this->email->send();

in email code $fetch_tration is email template that look like

Please CONFIRM your registration with www.doamin.Com

where Confirm text has a link like
    http://example.com/mycon/emailconfirmation/'.$confirmationcode.'/'.$unumber.'
I want To replace $confirmationcode and $unumber with value which assign at mail time.
when someone register than email send successfully but the variable $confirmationcode and $unumber not assign in the link. when user click on confirm link thank get an error like

The URI you submitted has disallowed characters.

Please help
Thank In Advance

A: If you are use CodeIgniter as your framework then u can directly allowed permitted character from config file.
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-=';

Can you please upload full link so, it's easy to understand exact issue.
http://example.com/mycon/emailconfirmation/'.$confirmationcode.'/'.$unumber.'

If you get upper link as a on click button, then it's totally wrong and you have to use "str_replace" function for replace url from template.
EXA:
$emaildata['message'] = file_get_contents(ASSETS_URL.'email_templates/filename');
$emaildata['message'] = str_replace('ReplacetagName', $YourVariable, $emaildata['message']);


text:
Q: Yahoo oauth issue with hybridauth I'm using example with Yahoo oauth from hybridauth http://oyanix.com/opensource/hybridauth/social_hub/login.php but it doesn't work with the following message "Original error message: User id request failed! Yahoo returned an invalid response."
How it could be fixed ?

A: solution how to fix it from hybridauth https://github.com/hybridauth/hybridauth/issues/174#issuecomment-38408597


text:
Q: How to make Outlook show inline attachments? I send an email from Mac Mail (Mail 8.2 on 10.10.4), as either RTF or Plain Text, with embedded inline pictures & files, as this example…

It arrives at Outlook mail with everything after the first picture moved out to separate attachments.

Is there anything I can do at either send or receive to stop Outlook doing this? It really should not be making it's own unilateral decisions on formatting.
I believe this is Office 2010. Though overall I'm going to have less control over which version of Office is at the receiving end, has this improved with later versions of Office (anything I can do to persuade people to be on something made this decade, perhaps) ?
I've read that sending as HTML might prevent it, but I don't have that option from Mail, plain or rtf only.


text:
Q: setting a selector in a destination view controller when preparing to segue i want to move from viewControllerA to viewControllerB and in my prepareForSegue assign the selector of a navigation item in viewControllerB.
in viewControllerA.m
prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    vcB = (viewControllerB *)segue.destinationViewController;
    vcB.navigationItem.leftBarButtonItem.title = @"cancel";
    vcB.navigationItem.leftBarButtonItem.selector(unwindWithCancel);
}

and still in viewControllerA.m
-(void)unwindWithCancel
{
    NSLog(@"unwindWithCancel");
}

the navigationItem.leftBarButtonItem's title does change but the selector doesn't work. i know you can drag and drop the button on viewControllerB's "Exit" to trigger this selector but in future i want to change the selector depending on which sender in viewControllerA has triggered the segue.
any help is much appreciated.
thanks.

A: I think you also need to set the target of the selector:
...
    vcB.navigationItem.leftBarButtonItem.target = self
...


text:
Q: Difference between grep on a file and strings? I am searching for patterns in a binary file on linux, and am not sure if I should use the "grep" or "strings" command to parse the file. I can do:
grep *pattern* *file*

or
strings *file* | grep *pattern*

Which is more robust?

A: In my opinion, cat --show-nonprinting is better suited to this task
cat --show-nonprinting | grep pattern

Or
cat -v | grep pattern

How to grep a text file which contains some binary data?


text:
Q: lipsum as caption The following fails to compile:
\documentclass{article}
\usepackage{lipsum}

\begin{document}
\begin{figure}
\caption{\lipsum[1]}
\end{figure}
\end{document}

giving the following error:
! Argument of \@caption has an extra }.
<inserted text>
                \par
l.11 \caption{\lipsum[1]}

I assume the problem is related to this (and this), but here I don't have nested square brackets.
What am I doing wrong?

A: Try with this one.
\documentclass{article}
\usepackage{lipsum}

\begin{document}
\begin{figure}
\caption{\protect\lipsum[1]}
\end{figure}
\end{document}


text:
Q: Import values from rows of one table to header of another table I want to import values from a row of one table to the header of another table. The issue is that my code copies the selected row to a div where table 2 is present.
Also, the row has an input field in which I can enter a value. It copies the input field as a whole and not just the value. How can I import only the value of the input field?

var table;

$('#createPlist').click(function plrList() {
  count = Number($('#noofTiks').val());
  caption = $('
');
  table = $('
');
  table = $(table).css({
    "border": "1px solid black"
  });

  var thead = $('
');
  var htr = $('
');
  var tbody = $('
');
  for (var a = 0; a < count; a++) {
    var row = $('
');
    for (var b = 0; b < 2; b++) {
      var td = $("");
      td = $(td).css({
        "border": "1px solid black"
      });
      if (b == 0) {
        var srNo = a + 1;
        td.append(srNo);
      } else {
        var input = $('<input>');
        td.append(input);
      }
      row.append(td);
    }
    tbody.append(row);
  }
  var th = $('');
  th.append("Sr. No.");
  htr.append(th);
  th = $('');
  th.append("Player Name");
  htr.append(th);
  thead.append(htr);
  table.append(thead);
  table.append(tbody);
  caption.append("Player List");
  $('#pList').append(caption);
  $('#pList').append(table);
});

$('#createPlist').on('click', function() {
  $(this).prop('disabled', true);
});

$('#giveTik').click(function() {
  count = Number($('#noofTiks').val());
  for (h = 0; h < count; h++) {
    var table = $('
');
    table = $(table).css({
      "border": "1px solid black",
      "margin": "20px auto",
      "width": "500px",
      "height": "250px"
    })
    var thead = $('
');
    var tbody = $('
');

    for (var i = 0; i < 3; i++) {
      // append new row to body
      var row = $('
');
      //var row = '';
      for (var j = 0; j < 9; j++) {
        // append new td to row
        var td = $("");
        td = $(td).css({
          "border": "1px solid black",
        })

          td.append("");

        row.append(td);
      }
      tbody.append(row);
    }

    var showTable = $('#pList').find('tr').eq(h + 1);  //NEED HELP HERE
    console.log(showTable)

    // For "selected" row of table1 ..
    var rowFromTable1 = showTable;

    // .. Take a clone/copy of it ..
    var clonedRowFromTable1 = rowFromTable1.clone();   //NEED HELP HERE

    // .. And append the cloned row to the thead of table2
    $('#div').append(clonedRowFromTable1);

    // thead.append(h + 1);
    // table.append(thead);
    table.append(tbody);
    $('#div').append(table);
  }
});

<input type="text" id="noofTiks">

<button class="btn btn-error" id="createPlist">OK</button>

<button id="giveTik">CREATE TICKETS</button>

A: Your current code was appending row to div because you where directly appending the clone row to #div instead you should append the cloned row to thead and then append this thead to table.Also i have replace cloned row td with th and added colspan .
Demo Code :

var table;

$('#createPlist').click(function plrList() {
  count = Number($('#noofTiks').val());
  caption = $('
');
  table = $('
');
  table = $(table).css({
    "border": "1px solid black"
  });

  var thead = $('
');
  var htr = $('
');
  var tbody = $('
');
  for (var a = 0; a < count; a++) {
    var row = $('
');
    for (var b = 0; b < 2; b++) {
      var td = $("");
      td = $(td).css({
        "border": "1px solid black"
      });
      if (b == 0) {
        var srNo = a + 1;
        td.append(srNo);
      } else {
        var input = $('<input>');
        td.append(input);
      }
      row.append(td);
    }
    tbody.append(row);
  }
  var th = $('');
  th.append("Sr. No.");
  htr.append(th);
  th = $('');
  th.append("Player Name");
  htr.append(th);
  thead.append(htr);
  table.append(thead);
  table.append(tbody);
  caption.append("Player List");
  $('#pList').append(caption);
  $('#pList').append(table);
});

$('#createPlist').on('click', function() {
  $(this).prop('disabled', true);
});

$('#giveTik').click(function() {

  count = Number($('#noofTiks').val());
  for (h = 0; h < count; h++) {
    var table = $('
');
    table = $(table).css({
      "border": "1px solid black",
      "margin": "20px auto",
      "width": "500px",
      "height": "250px"
    })

    var thead = $('
');
    var tbody = $('
');
    for (var i = 0; i < 3; i++) {
      // append new row to body
      var row = $('
');
      //var row = '';
      for (var j = 0; j < 9; j++) {
        // append new td to row
        var td = $("");
        td = $(td).css({
          "border": "1px solid black",
        })

        td.append("");

        row.append(td);
      }
      tbody.append(row);
    }

    var showTable = $('#pList').find('tr').eq(h + 1); //NEED HELP HERE
    // For "selected" row of table1 ..
    var rowFromTable1 = showTable;

    // .. Take a clone/copy of it ..
    var clonedRowFromTable1 = rowFromTable1.clone();
    //finding input value
    var input_value = clonedRowFromTable1.find("input").val();
    //getting sr.no
    var texts = clonedRowFromTable1.find("td:first").text();
    //replace td with th and add sr.no and input value
    clonedRowFromTable1.find("td:first").replaceWith("" + texts + " " + input_value + "	")
    clonedRowFromTable1.find("td:last").remove()//remove next td
   //append cloned elemnt to thead
    thead.append(clonedRowFromTable1);
    table.append(thead)//append to table
    table.append(tbody);
    $('#div').append(table);
  }
});

<input type="text" id="noofTiks">

<button class="btn btn-error" id="createPlist">OK</button>

<button id="giveTik">CREATE TICKETS</button>


text:
Q: Wpf sort or crud on datagrid cause reset checkbox I added column that has checkbox and when checkbox checked I get average of some numbers that selected.
The problem is when sorting data or do something to database cause all checkbox check status to false. How to fix it?
The only way I know is store that checkbox as boolean in database and everytime I run the program set all boolean to false. But that is not good way. Because in large data cause slowly down the performance of program.
Every time the database changed this code called for update DataGrid.
using DataContextTest dc=new();

DgTest.ItemsSource= dc.TestTable.ToList();

A: Make sure you are using a ObservableCollection and once necessary action complete, SaveChages to the database. Then do your refresh or reload whatever. It seems, you are reloading the data, which is not necessary as long as the context is alive. Just make sure you are saving the new state of the collection to you DB (use that same context you used to load the data)
I hope it helps


text:
Q: Plugin "react" was conflicted between "package.json Every time when i change on JSX. This error throw on my terminal and project UI.

Plugin "react" was conflicted between
"package.json » eslint-config-react-app » C:\projects\end-game-project\sporte\node_modules\eslint-config-react-app\base.js"
"BaseConfig » C:\Projects\end-game-project\sporte\node_modules\eslint-config-react-app\base.js".
Then when I do CTRL+S on package.json, It temporary fixed.

But how can I permanently fix it?

A: When you started your react app in the terminal, it looks like you entered a path using a capital 'P' in C:Projects\end-game-project, even though the actual path does not have a capital 'p'  and should be C:projects\end-game-project (or vice-versa).
Note that some terminals, like the one VS offers, aren't case sensitive, and they will let you 'cd' into folders even if you misuse an upper or lowercase letter.
To fix this, the solution is rather simple. Open the command terminal where you launch your React app and use 'cd..' to navigate out of the project folder, going as far back as your C drive. Then, navigate back to your project folder, this time ensuring you use the correct uppercase and lowercase letters in your file path. Then launch your app again and the problem should be resolved.


text:
Q: Gmail API send message utf-8 header I've been trying to use Gmail API for python for some code and I ran into some problem. I try so send some mail through this API to myself so I wrote the following minimal code:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header

mime = MIMEMultipart()
mime['To'] = Header("example@example.com") #Works
#mime['To'] = Header("example@example.com", 'utf-8') #Error: Invalid To header
mime['From'] = "me"
mime['Subject'] = "Hello World"
output =  {'raw': base64.urlsafe_b64encode(mime.as_string().encode()).decode()}
service.users().messages().send(userId='me', body=output).execute()

where service is the object created by this guide and I based my code on this guide.
As you can see the code runs or fails based on the encoding of the 'To' header. This is weird because changing the encoding of the 'From' Header or of the 'Subject' doesn't have this effect.
(I know that in this case a utf-8 encoded string isn't needed for the 'To' header but in my case it is needed)


text:
Q: Laravel One To Many Relationship Trying To Get Property Of Non-object I'm building relationship model between Siswa (student) and Kelas (class), which one Kelas has many Students (hence One to Many). Here is the code :
Show.php view

    Kelas
    {{$siswa->kelas->nama_kelas}}

Siswa.php model
class Siswa extends Model
{
    protected $table = 'siswa';

    protected $fillable = [
        'nisn',
        'nama_siswa',
        'tgl_lahir',
        'jns_klmin',
        'id_kelas',
        'id_hobi',
    ];

    public function kelas(){
        return $this->belongsTo('App\Kelas', 'id_kelas');
    }
}

Kelas.php model
class Kelas extends Model
{
    protected $table = 'kelas';

    protected $fillable = [
        'nama_kelas'
    ];

    public function siswa(){
        return $this->hasMany('App\Siswa', 'id_kelas');
    }
}

I think I'm already called method kelas in model Siswa accordingly, but $siswa->kelas->nama_kelas is defined as a non-object. Anyone can give some enlightment? Any help appreciated.
UPDATE
This is the show controller :
public function show(Siswa $siswa){
    return view('siswa.show', compact('siswa'));
}

In show parameter I'm using route model binding to find passing $id in RouteServiceProvider, which I modified :
public function boot(Router $router)
{
    parent::boot($router);
    $router->model('siswa', 'App\Siswa');
}

public function map(Router $router)
{
    $router->group(['namespace' => $this->namespace, 'middleware' => 'web',
        ], function ($router) {
            require app_path('Http/routes.php');
        });
    //
}

A: The belongsTo() method will return Illuminate\Database\Eloquent\Relations\BelongsTo instance. In order to get the Kelas instance you have to do it like so:
$siswa->kelas->first()->nama_kelas

Hope this help!


text:
Q: How to write soap client if Request and Response classes are not provided I am new at spring framework and web programming. I need to write client using spring boot. I was provided api and functions I need to use. As I discovered, provided web service uses soap which is new to me. I tried to follow the official spring guide: https://spring.io/guides/gs/consuming-web-service/
As I understood, I need to use Request and Response classes generated from wsdl to specify request and response objects for exchange. But in wsdl there are no such classes. I see similar names like getCarsListRequest and this is not xsd type(which are generating) but < message >
wsdl link


text:
Q: Get directory with or without trailing slash of a URL? Here's my current code:
var loc = window.location.pathname;
var str = loc.substring(0, loc.lastIndexOf('/'));
var subid = str.replace("/", "");

When I go to http://example.com/12345/, then subid equals 12345.
But when I go to http://example.com/12345, then subid is blank.
How can I make this work with or without the trailing slash?

A: If you consider regex,
var loc = window.location.pathname;
var subid = loc.match(/^http[s]?:\/\/.*?\/([a-zA-Z-_]+).*$/)[1];

Test with different cases
var url1 = "http://google.com/abc-1";
var url2 = "http://google.com/abc-2/";
var subid1 = url1.match(/^http[s]?:\/\/.*?\/([a-zA-Z-_]+).*$/)[1];
var subid2 = url2.match(/^http[s]?:\/\/.*?\/([a-zA-Z-_]+).*$/)[1];
console.log(subid1);
console.log(subid2);

A: You can take a benefit of inbuilt function URL
(new URL('http://example.com/12345/')).pathname.replace(/\//g,'') // output 12345
(new URL('http://example.com/12345')).pathname.replace(/\//g,'') // output 12345

The one who are looking for the last segment only can use this
  function

var allPartsOfURL = 'http://example.com/12345/12/98/567'.split('/');
// handle potential trailing slash
var lastSegment = allPartsOfURL.pop() || allPartsOfURL.pop();

console.log(lastSegment);

For old browsers

// create an anchor tag
const url = document.createElement('a');
// set the href attribute and then use the `pathname`
url.setAttribute('href', 'http://example.com/12345/');
url.pathname.replace(/\//g,''); // output 12345

url.setAttribute('href', 'http://example.com/12345');
url.pathname.replace(/\//g,''); // output 12345

A: Try this one.
    var loc="http://example.com/12340/";
    if((loc.length-1)==loc.lastIndexOf('/'))
    {

        var newloc=loc.substring(0,loc.length-1);
        var subid=newloc.substring((newloc.lastIndexOf('/')+1),newloc.length);
    }
    else
    {
        var subid=loc.substring((loc.lastIndexOf('/')+1),loc.length);
    }
    console.log("sub is "+subid);

A: So much overkill and code that doesn't work in older browsers in other answers. It's as simple as this:
var subid = location.pathname.match(/^\/([^\/]*)/)[1];

You can assign the result of match to another variable and add more groupings to the regex if you need to capture other segments, too.

A: if you want to extract last part of string then you can use
loc.substring(loc.lastIndexOf('/')).replace('/','');

in case of last '/ first check with .endsWith('/') method and then remove last '/' using
if(loc.endsWith('/')) {
   loc.substring( -1, loc.lastIndexOf('/')).replace('/','');
}

alternative way is
 loc.split('/').filter( path => !path).pop();


text:
Q: Does deleting rows from a table distrupts indexes? I need to know that if we delete some rows (I am talking for sql server) from a table which has some indexes (clustered or non-clustered, for both situation) can give any damage to indexes or not? What happens to indexes when we delete rows? Which one is better for performance, deleting rows from a table after processing them, or mark up them as processed (When we will need to reuse them like 20 times more). Thanks for the answers.

A: I don't know what you mean by "damage".  When you delete rows from the table, the index entries need to be deleted as well.  This does not "damage" the index per se.  At least, the index continues to be useful.
If you have lots of deletes, updates, and inserts, then over time the index will be fragmented.  This does affect performance.  At some point it becomes useful to re-build the index for performance purposes.  You can read about this in the documentation.
I would not worry about rebuilding the indexes because of a handful of deletes.  It takes a bit of work to really fragment an index.

A: My answer is YES.
Index is created on data in the tables and in short if data is deleted from the tables then the levels of fragmentation rise.
Rise in fragmentation levels effects the data retrieval in many ways.


text:
Q: Throwing a fault inside a behavior and returning it to client I'm writing some services in WCF to be called by a Silverlight client. I change status code to 200 every time a fault is to be returned, via a IDispatchMessageInspector.
It works almost perfect, but sometimes it keeps returning error 500: NotFound.
I have just written another IDispatchMessageInspector to commit changes in a ObjectContext. But when this fails, the error handler is not called.
I think by the time UnitOfWorkMessageInspector runs, the message was already been set up as a non-fault-response. How can I do both things work?
    public class UnitOfWorkMessageInspector : IDispatchMessageInspector
    {
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (!reply.IsFault)
            {
                try
                {
                    UnitOfWorkBase.Commit();
                }
                catch (OptimisticConcurrencyException)
                {
                    throw new FaultException("It was changed by another user. Try again.");
                }
            }
        }

A: Code 500 is Internal Error.
Some error is occuring and it is not caught on the server side.
In your code you only catch OptimisticConcurrencyException you need to also catch Exception.

A: I managed to make it work. I figured out my IDispatchMessageInspector for switching from status code 500 to 200 wouldn't work because the message was already built, then I replaced the message.
    public class UnitOfWorkMessageInspector : IDispatchMessageInspector
    {
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (!reply.IsFault)
            {
                try
                {
                    UnitOfWorkBase.Commit();
                }
                catch (OptimisticConcurrencyException)
                {
                    FaultException fe = new FaultException("It was changed by another user. Try again.");
                    reply = Message.CreateMessage(reply.Version, fe.CreateMessageFault(), fe.Action);
                }
            }
        }


text:
Q: Storing and Retrieving Dynamic 2-D Array in Session or ViewBag MVC C# I have this chunk of code in my controller that makes two separate lists of ID's and Name's but I will turn that into a dynamic 2-D array eventually once I understand a few things:
var UserEntitiesID = db.tblUserEntities.Where(x => x.UserID == userid).ToList(); //userid comes from aad
var IDList = new List<int?>();
var NameList = new List<string>();
foreach (var entitiesitem in UserEntitiesID)
{
    foreach (var item in db.tblEntitiesGroups.Where(x => x.EntitiesID == entitiesitem.EntitiesID))
    {
        IDList.Add(item.EntitiesGroupID);
        NameList.Add(db.tblGroups.Where(x => x.GroupID == item.GroupID).First().GroupName);
    }
}
Session["IDList"] = IDList;
Session["NameList"] = NameList;

My question is this: How do I insert this possible dynamic 2-D array into a Session variable or Viewbag item, then pass that off to a view and then read the first and second value for the first record, separately? I do not know how to correctly dynamically index the array on the view to read each value out separately.
Currently I have this code in my view to display the ID's and Name's separately:
@if (!String.IsNullOrEmpty(Session["IDList"] as string))
{
    foreach (var IDs in (IEnumerable<int?>)Session["IDList"])
    {

@IDs.ToString()

    }
    foreach (var names in (IEnumerable<string>)Session["NameList"])
    {

@names.ToString()

    }
 }

Basically I want this layout in the array:
0{"ID", "Name"}
1{"ID", "Name"}
And so on...
Thanks!