text:
Q: Save  content to html file I have a <div> on my page that is constantly updated every 3 seconds. I'm using setInterval and AJAX to do this and update the <div>.
I've added a button that saves the current <div>'s data and writes it into a .html` file and then downloads it, but it's not working well across browsers.
In Chrome this works:
$("#save").click(function () {
    $('<a/>').attr({
          download: 'export.html',
          href: "data:text/html," + $('#result').html()
    })[0].click()
});

But it doesn't work in IE11, Firefox or Edge, it fails to do anything. In Safari it works but changes the current active page to export.html instead of downloading the export.html file.
Is there a way to do this that will work across browsers. Have the <div> output written to a html file and have it downloaded?
Thanks.

A: I've updated my script to write the output shown in the DIV to a temp file on the server.  The page then shows a download link and a backend download script gets the temp file and downloads it. This seems to work OK.


text:
Q: How to dynamically re-render template? Currently I am trying to create a dynamic filter for listing model objects in a template. Here is the django view:
def view_data(request):
    text = request.GET.get('text')
    persons = None
    if text:
        try:
            persons = models.Person.objects.get(code__regex=text)
        except models.Person.DoesNotExist:
            pass
    return render(request, 'view_data.html',
                  {'persons': persons if not isinstance(persons, models.Person) else [persons]})

The related part from the template:

  <form>
    Alanyok szűrése
    <input id="filter" type="text" placeholder="Keresett alany">
  </form>

      {% for person in persons %}
        {{person.code}}
      {% endfor %}

          <canvas id="Canvas1" width="540" height="250" style="border:1px solid #202020;">
          </canvas>

The input field with filter id has a callback on keyup event which sends a request to django with the content of the input field which is used in the view for query.
Here is the callback:
$( "#filter" ).keyup(function() {
    $.get("", {text: $('#filter').val()});
});

When I checked it with Pycharm debugger, the render returns the correct html but on the client side the html doesn't change. How to re-render with the new object list?

A: Take a part of your html code that you want to replace and place it inside a new html file like this:
new_html:

  {% for person in persons %}

       {{person.code}}

  {% endfor %}

now in your view replace the name of your old html file ( that you are rendering )  with the new html file like this:
 return render(request, 'new_html.html',
             {'persons': persons if not isinstance(persons,models.Person) else [persons]})

and now in your ajax you can dynamically load this new_html like this :
 $( "#filter" ).keyup(function() {
    $.get("",
          {text: $('#filter').val()},
          function(data){
              $( "#list-tab" ).replaceWith( data );
          }
    );
});

A: You are not doing nothing with the returned data. Add a callback function in the get method call. You get the response from the server in the first argument. Use that to hide and show contents on the page. Or you can even replace elements in the DOM. See jquery.replaceWith.
$( "#filter" ).keyup(function() {
    $.get("", {text: $('#filter').val()}, function(response){  });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP What is the problem? Last uploaded picture gets upladed again on page refresh So i'm working on a project where i have to upload something to a database. In my case i upload pictures. Now the problem is, if i upload a picture and refresh the page the picture gets uploaded again. If i upload 3 pictures then the last picture gets uploaded again and again every time i refresh the page.
?php
if (isset($_POST['upload'])){
    $target = "images/".basename($_FILES['image']['name']);

    $db = mysqli_connect("localhost", "root", "", "aawebprog");

    $image = $_FILES['image']['name'];
    $text = $_POST['text'];
    $uploader = $_SESSION['username'];

    if($text > 50){
        $msg = "You have to write at least 50 characters!";
    }

    $sql = "INSERT INTO pictures (image, text, uploader) VALUES ('$image', '$text', '$uploader')";
    mysqli_query($db,$sql);

    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)){
        $msg = "Image upluaded succesfully";
    } else{
        $msg = "There was a problem during the upload, try again";
    }
    echo ("$msg");
}

?
Any ideas what can be the problem?


text:
Q: Working with multiple databases (DAO Pattern) I am creating a project which should be able to use different databases for the persistence of data. I have implemented a DAO pattern, but I have a problem when working with the ID in the struct, since for example MongoDB uses BSON whereas SQL databases use uint.
What solution do you recommend to implement the ID field in the struct.
What I can think of is to create an ID object that contains fields for BSON and uint IDs with GetBSON, GetUint methods and a GetID method that encodes either BSON or uint to MD5 (or some other encoding) I would use the GetBSON and GetUint methods to work with the Databases and the GetID method to work on the application as well as to send it through the REST API.

A: Cases like this your best bet is to use a universal identifier (UID) There are many ways to do this, though my personal favorite is just UUID v4. You can read the full UUID spec here https://www.rfc-editor.org/rfc/rfc4122.
Just configure your SQL tables and code to ensure uniqueness with this identifier and you can easily do lookups between databases using whichever access pattern you wish to implement.
e.g.
SQL

ID(Primary Key) | UID (unique)
         0      |   xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

MONGO

{
  _id: ObjectID(),
  uid: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}

now just lookup on uid only and you can be database agnostic at the higher level.


text:
Q: transition between pages using indicators in the flutter I have 2 pages, on one of them I have placed the code which displays indexers, I want to swipe on indexes to pass between pages. I can't figure out how to set it up. I will be grateful for your help.

 Container(
               child: SmoothPageIndicator(
                 controller: _pageController,
                 count:  _pages.length,
                 effect: JumpingDotEffect(
                   dotHeight: 16,
                   dotWidth: 16,
                   jumpScale: .7,
                   verticalOffset: 15,
                ),
                   onDotClicked: _onchanged
              ),
            ),

List of pages:

  List<Widget> _pages = [
    Form_scan(),
    Form_ttn()
  ];

Image indecators

I will be grateful if someone helps me to go from the first page to the second (swipe right) with these indicators

A: Try out below code:-
import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:sizer/sizer.dart';
import 'package:livekeeping/Common/Constant.dart';
import 'package:livekeeping/Common/IconNames.dart';
import 'package:livekeeping/Common/Reusable.dart';
import 'package:livekeeping/Controller/Authentication/LoginWithOtpScreen.dart';
import 'package:lottie/lottie.dart';

class Onboarding extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return OnboardingState();
  }
}

class OnboardingState extends State<Onboarding> {
  int _current = 0;

  Widget widgetChange = firstWidget();

  var i = 0;

  @override
  void initState() {
    super.initState();

  }

  @override
  void dispose() {

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: double.maxFinite,
        width: double.maxFinite,
        child: Stack(
          children: <Widget>[
            PageView.builder(
              onPageChanged: (pageIndex) {
                setState(() {
                  _current = pageIndex;
                });
              },
              itemCount: 4,
              itemBuilder: (context, index) {
                if (index == 0) {
                  return firstWidget();
                } else if (index == 1) {
                  return secondWidget();
                } else if (index == 2) {
                  return thirdWidget();
                } else {
                  return fourthWidget();
                }
              },
            ),
            Positioned(
              bottom: 120,
              left: 0,
              right: 0,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [1, 2, 3, 4].map((url) {
                  int index = [1, 2, 3, 4].indexOf(url);
                  return Container(
                    width: 8.0,
                    height: 8.0,
                    margin:
                        EdgeInsets.symmetric(vertical: 10.0, horizontal: 2.0),
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: _current == index
                          ? Color.fromRGBO(0, 0, 0, 0.9)
                          : Color.fromRGBO(0, 0, 0, 0.4),
                    ),
                  );
                }).toList(),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(bottom: 30.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  ButtonTheme(
                    height: 45,
                    minWidth: 150,
                    child: new Center(
                        child: RaisedButton(
                      color: AppTextStyle.mainThemeColor(),
                      onPressed: () {

                        Navigator.of(context).pushAndRemoveUntil(
                            CupertinoPageRoute(
                                builder: (context) => Login()),
                            (route) => false);

                      },
                      child: new Text(
                        "Get Started".toUpperCase(),
                        style: GoogleFonts.openSans(
                          color: Colors.white,
                          fontSize: 15,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(50)),
                    )),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

class firstWidget extends StatefulWidget {
  @override
  _firstWidgetState createState() => _firstWidgetState();
}

class _firstWidgetState extends State<firstWidget>{

  @override
  void initState() {
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          height: double.maxFinite,
          width: double.maxFinite,
          child: Image.asset(
           SplashBG,        // You can put your Background image as well
            fit: BoxFit.cover,
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [

                Container(
                  height: 45.0.h,
                  width: 75.0.w,
                  child: Image.asset(Icon1),
                ),

              ],
            ),
          ],
        ),
      ],
    );
  }
}

class secondWidget extends StatefulWidget {
  @override
  _secondWidgetState createState() => _secondWidgetState();
}

class _secondWidgetState extends State<secondWidget>{

  @override
  void initState() {
    super.initState();
    }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          height: double.maxFinite,
          width: double.maxFinite,
          child: Image.asset(
            SplashBG,  // You can put your Background image as well
            fit: BoxFit.cover,
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [

                Container(
                  height: 45.0.h,
                  width: 75.0.w,
                  child: Image.asset(Icon2),
                ),

              ],
            ),
          ],
        ),
      ],
    );
  }
}

class thirdWidget extends StatefulWidget {
  @override
  _thirdWidgetState createState() => _thirdWidgetState();
}

class _thirdWidgetState extends State<thirdWidget> {

  @override
  void initState() {
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          height: double.maxFinite,
          width: double.maxFinite,
          child: Image.asset(
            SplashBG,  // You can put your Background image as well
            fit: BoxFit.cover,
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [

                Container(
                  height: 45.0.h,
                  width: 75.0.w,
                  child: Image.asset(Icon3),
                ),

              ],
            ),
          ],
        ),
      ],
    );
  }
}

class fourthWidget extends StatefulWidget {
  @override
  _fourthWidgetState createState() => _fourthWidgetState();
}

class _fourthWidgetState extends State<fourthWidget> {

  @override
  void initState() {
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          height: double.maxFinite,
          width: double.maxFinite,
          child: Image.asset(
            SplashBG,  // You can put your Background image as well
            fit: BoxFit.cover,
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [

                Container(
                  height: 45.0.h,
                  width: 75.0.w,
                  child: Image.asset(Iconn4),
                ),

              ],
            ),
          ],
        ),
      ],
    );
  }
}

A: use PageView, :
PageView(
        controller: _pageController,
        children: [
          Form_scan(),
          Form_ttn()
        ],
      ),

make a PageController :
final PageController _pageController = PageController();

onDotClicked: _onchanged
void _onchanged(){
_pageController.animateToPage(
          indexHalaman,
          duration: Duration(milliseconds: 500),
          curve: Curves.fastOutSlowIn
      );
}

indexHalaman = page index, if you have 2 widget on pageView children then first page index = 0, next index page = 1, if you use stateful widget, dont forget to use setState, or maybe you can use bloc pattern for this


text:
Q: getElementsByClassName doesn't work inside div element I have 2 HTML files Home.html & test.html. I'm loading test.html using javascript into a DIV in Home.html. When i try to use getElementsByClassName to get a element in Test.html, it doesnt return anything. What am I doing wrong here? When I click on URLs in the Home.html page it should load as below right? Why doesn't it?
1.jpg
2.jpg

I went through the other questions posted here, but I couldn't find the problem.
I ran this on chrome in windows 7.
I am new to HTML designing, please be gentle!
Home.html

     HOME
     URLs

Test.html
aaaaaaaaaaaaaaaaaaaaaaaaaa

A: There are a few things wrong.
txt needs to be initialized to an empty string because you are appending to it.
x has no property named elements; rather it is the array of elements returned by getElementsByClassName(), in this case they are  elements which have a src property.
I am not sure why you are using the <object> tags since you are building an HTML string in your loop. Give this a shot:
    var x;
    var i;
    var txt = "";
    function foo() {
        x = document.getElementsByClassName("gallery");
        for (i = 0; i < x.length; i++) {
            //txt = txt + x.elements[i].src + "
";
            txt = txt + x[i].src.replace(/^.*[\\\/]/, '') + "
";    // use this regex to get only the filename as in your example
        }
        //document.getElementById("txt").innerHTML = '<object type="text/html" data=txt ></object>';
        document.getElementById("txt").innerHTML = txt;
    }
    function load_test() {
        document.getElementById("content").innerHTML = '<object type="text/html" data="test.html" ></object>';
    }

A: There is no property called elements in your array x. As you iterate over your elements, the line to set the var txt needs to be the following:
txt = txt + x[i].src + "
";

A: Not sure what the load_test() function is supposed to do but I changed the html a bit for what I think you are trying to do?

 HOME
 URLs

What I basically changed is the fact that your txt variable was not initialized, that you were using a non-existant "elements" property on an array where you simply needed to use the index to access.

A: There are a couple of issues:

*

*The variable "txt" needs to be defined within the function "foo()"; you're trying to define it outside the function, but actually you're defining it here: txt = txt + x.elements[i].src + "
"; But if you define it here, the definition of itself contains itself (txt = txt + ...), so it will contain the word "undefined". (Hope that made sense.)

*The code you're using to get the image sources isn't correct; instead of x.elements[i].src, use x[i].src.

*The content from your second HTML file needs to be fetched with ajax. For this I would create a hidden div, so you can load the content from your second HTML file into there, and then use it in your script. (In the example below, I gave the hidden div the id="ajaxContent".)
Here's how I would change your script:
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        xmlhttp.responseText;
        document.getElementById("ajaxContent").innerHTML = xmlhttp.responseText;
    }
}
xmlhttp.open("GET","test.html",true);
xmlhttp.send();

function foo()
{
    x = document.getElementsByClassName("gallery");
    txt = '';
    for (i = 0; i < x.length; i++) {
        txt = txt + x[i].src + "
";
    }
    document.getElementById("txt").innerHTML = txt;
}

And the "new" HTML for Home.html (just the hidden div at the bottom):

     HOME
     URLs

And here's a fiddle (without the ajax part - I don't think you can do ajax with JSFiddle): http://jsfiddle.net/Niffler/pnv1jy1m/
(I didn't know what you were doing with the "object" thing, so in my script I changed it to just output the text...)

A: It can't find your foo function because of JavaScript's scoping rules.
If you want foo to be accessible globally, define it like this:
document.foo = function()
{
//...etc


text:
Q: 100% of page height app homescreen CSS I'm trying to make an app homescreen in CSS. Think of the layout of the iphone where you select the app. Basically a 3x2 grid that's 100% of the device page.
The problem I'm having is that this is used by lots of different devices so the height/width changes depending on the device.
The width is working fine, but the height is adding a scroll sometimes on some devices. Basically I want the page to go full screen on the app and have no scrolling.
Heres my HTML:

Heres my CSS:
.outer{
    width: 100%;
    height: 100%;
}

.row {
    width: 100%;
}

.iconL {
    float: left;
    width: 50%;
}

.iconL img {
    float: left;
    width: 100%;
}

.iconR {
    float: left;
    width: 50%;
}

.iconR img {
    float: right;
    width: 100%;
}

i've made a JSFilddle: http://jsfiddle.net/QrbKh/
As you can see it scrolls in there

A: The problem with percents is that they're always relative to the elements parent. If you take a look inside the Developer Tools you'll realise that .outer has an actual height of 0 (zero). That's because the body as .outer's parent has no height set which is interpreted as zero (100% of zero are still zero).
To solve that problem, just add
html,
body {
    height:100%;
    width:100%;
}

to your CSS. That makes html and body fill the entire page.
Then add
.row {
    height:33.3%;
}

.iconL,
.iconR,
.iconL img,
.iconR img {
    height:100%;
}

That works fine for me. But since you can't divide 100 by 3 without a rest, also add
body {
    overflow:hidden;
}

Another solution could be using the viewport-values.
.row {
    height:33.3vh;
}

where "vh" stands for "viewport height". So 33.3vh refers to "1/3 of the viewports height". Actually the viewport-values have an acceptable support: http://caniuse.com/#search=viewport

A: You can add a max-height to the img element. Is that what you want? jsFiddle
img {
max-height: calc(100%/3); // or 33.33%
}

A: I think the following CSS may achieve what you need:
html, body {
    height: 100%;
    padding: 0;
    margin: 0;
}
.outer{
    height: 100%;
}
.row {
    height: 33.333333333%;
    overflow: hidden;
}
.iconL {
    float:left;
    width: 50%;
    height: 100%;
    text-align: center;
    background-color: yellow;
}
.iconL img {
    height: 100%;
    vertical-align: top;
}
.iconR {
    float:left;
    width: 50%;
    height: 100%;
    text-align: center;
    background-color: beige;
}
.iconR img {
    height: 100%;
    vertical-align: top;
}

As stated earlier, you need to specify height: 100% to your html and body elements to set a reference value that can be inherited by the descendant elements.
The key is to scale the images to a height of 100% of the row height, which is set to 33.33% of the screen height.
Adding vertical-align: top to the images cleans up a sliver of whitespace below the baseline.
Since you only have two elements floated in the row, you can float both to the left or the left to the left and the right to the right.
Adding overflow: hidden to .row will keep the row's floats within their own block formatting context.
See demo at: http://jsfiddle.net/audetwebdesign/ZYL2C/
In Firefox, the result looks like:

You can align the left image to the right and the right image to the left and add some right/left margin values to control the spacing between the images.  Your mark-up allows for quite a bit of flexibility in this design.


text:
Q: Mono: application not running when web.config in subfolder I run ASP.NET on Mono.
I wanted to run blogengine:
http://www.dotnetblogengine.net/

I downloaded, put it in /var/www/blogengine, on the console went to /var/www/blogengine and started xsp2.
I went to http://localhost:8080, and it ran without problems.
Then I stopped xsp2, went to /var/www and started xsp2.
I went to http://localhost:8080/blogengine
It ended with a strange  error:

The section  can't be defined in this configuration file (the allowed definition context is 'MachineToApplication'). (/var/www/blogengine/Web.Config line 9)

The problem seems to be that it stops working as soon as the xsp2 root folder is anything else than the application root folder...
Do I have to config anything? Or what else is wrong?

A: This is expected behaviour. You must run xsp in the root of your web application or specific a path to be root.
For example...
xsp2 --root /var/www/blogengine


text:
Q: meteor upsert failing when insert works I am having problems making upsert save data as expected or at all.
Attempt 1:
Video.upsert({
  user: videoData.user,
}, {
  $push: {
    video: videoData.video,
  }
});

Result 1:

Exception in Mongo write: TypeError: Cannot read property 'indexOf' of
  undefined I20170816-12:32:05.868(2)?     at
  Function.MongoConnection._isCannotChangeIdError
  (packages/mongo/mongo_driver.js:641:7)

Attempt 2:
Video.upsert({
  user: videoData.user,
}, {
  $addToSet: {
    video: videoData.video,
  }
});

Result 2:

Exception in Mongo write: TypeError: Cannot read property 'indexOf' of
  undefined I20170816-12:39:54.709(2)?     at
  Function.MongoConnection._isCannotChangeIdError
  (packages/mongo/mongo_driver.js:641:7)

Attempt 3:
Video.upsert({
  user: videoData.user,
}, {
  $set: {
    video: videoData.video,
  }
});

Result 3:

Exception in Mongo write: TypeError: Cannot read property 'indexOf' of
  undefined I20170816-12:42:18.915(2)?     at
  Function.MongoConnection._isCannotChangeIdError
  (packages/mongo/mongo_driver.js:641:7)

Attempt 4:
Video.update({
  user: videoData.user,
}, {
  $set: {
    video: videoData.video,
  }
}, {
  upsert: true,
});

Result 4:
Keeps creating the following document each run (not updating existing) and is missing the video field:
{
    "_id" : "Gs5of657ZqKa4ec3h",
    "user" : "testUser"
}
Attempt 5:
Video.update({
  user: videoData.user,
}, {
  $addToSet: {
    video: videoData.video,
  }
}, {
  upsert: true,
});

Result 5:

Exception in Mongo write: TypeError: Cannot read property 'indexOf' of
  undefined I20170816-13:06:13.250(2)?     at
  Function.MongoConnection._isCannotChangeIdError
  (packages/mongo/mongo_driver.js:641:7)

Attempt 6:
Trying to just insert the binary.
Video.insert({
  user: videoData.user,
  video: videoData.video,
});

Result 6:
Adds the following documents each time ran which proves to me that the object passed is OK:
{
    "_id" : "ceg3dXWXZoHjcy4AT",
    "user" : "testUser",
    "video" : { "$binary" : "a long string goes here", "$type" : "00" }
}
Any idea for why I am failing all attempts? I interpret the error message as if it's not finding any document to update using the user field but should it then not insert one when it's an upsert?
What I want is user document that contains an array of video data docs.

A: Ok, first you should create unique index on your user field.
Next, use upsert like this:
Video.upsert({
  user: videoData.user
}, {
  $set: {
    video: videoData.video
  },
  $setOnInsert: {
    _id: Random.id(),
    user: videoData.user,
    video: videoData.video
  }
});


text:
Q: IB, Keep ImageView centre, but grow as the screen size, keeping the aspect ratio Since I could do the same thing easily in Android and WPF, I thought XCode's Interface Builder would be easy, too. But I was wrong. I have spent hours on the storyboard resetting the constraints multiple times. I know this question seems stupid, but please give me a hint.
I want something like this on the storyboard. What constraints should I set?

*

*The ImageView's aspect ratio should be kept.

*The ImageView is centred horizontally.

*The ImageView grows as the screen width, for example 90% of screen width on a vertical phone. Optionally, I wish I could set a maximum, for example, not bigger than say, 400. I mean, 90% on an iPad is too large.

*The ImageView's top margin should be reasonable to the screen size. I mean, a hard-coded margin 20 would make it too close to the top on an iPad, and a hard-coded margin 200 would look good on an iPad but not on an iPhone SE.

A: *

*Constrain the width and height to keep the aspect ration (one constrain:
imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor, multiplier: 0.6).isActive = true

*Constrain the centerX to viewController's view centerX:
imageView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: 0).isActive = true

*Constrain the imageView width (or height) to width of the viewController's view using some ratio (90% here):
imageView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.9).isActive = true

*This is the only problem, what is a reasonable offset? Too vague requirement. But if your only problem is to set a proper offset depending on the given UI, I would use size classes to provide different constraints based on the given size class - see documentation.

A: If you want to achieve this in your storyboard, do the following:

*

*Put your imageView at the desired size and position

*Add Aspect Ratio constraint to your imageView

*Add center horizontally constraint to your imageView

*Add width constraint to your imageView equal to its superview's width; then change the Multiplier to (desired width) / (width of the superview). Change the priority to 999

*Add width constraint to your imageView and set the relation to Less Than or Equal. Put your maximum value here (400)

*For the top offset, add an UIView with clear background in your superView. Set its top, left and right equal to the top left and right of your superview and add a vertical spacing of 0 to your imageView. Then add a height constraint equal to its superview height and change the Multiplier to (desired space) / (height of the superview). (Its the pink view in the attachment)


text:
Q: The Product of two rising factorials Let $(x)_{2 n}$ is a rising factorial of 2n terms ,$\left(\frac{x}{2}\right)_{n}$ and $\left(\frac{1+x}{2}\right)_{n}$ are rising factorial of n terms.
From https://mathworld.wolfram.com/PochhammerSymbol.html there is a following known formula as you see;
$(x)_{2 n}=2^{2 n}\left(\frac{x}{2}\right)_{n}\left(\frac{1+x}{2}\right)_{n}$
I want to ask for instance as a special case  $x=1$
$(1)_{2 n}=2^{2 n}\left(\frac{1}{2}\right)_{n}\left(1\right)_{n}$
But i want the left side to be a rising factorial in n terms. I mean the product of 2 rising factorial of n terms are equal a rising factorial in n terms ,too.
$(1)_{2 n}$=$(c)_{n}$ Is it possible? If it is So how can c be here?

A: You're somewhat overlooking the definition and meaning of the symbols. Since
$$(1)_{2n} = 1 \cdot 2 \cdot \ldots \cdot 2n$$
we have that
$$(1)_{2n} = (2n)!$$
Hence, if we want a product of $n$ consecutive terms (that being $(c)_n$) starting at $c$ that equals this, we simply need $c=n+1$.

A: We can find $c$ for small $n$ and at least approximately for large $n$. We consider
\begin{align*}
(2n)!=(1)_{2n}=(c)_n=c\cdot (c+1)\cdots (c+n-1)\tag{1}
\end{align*}
where the right hand side is a polynomial in $c$ of degree $n$.

Solving (1) for small values of $n$ we obtain
\begin{align*}
\color{blue}{(1)_2}&=2!=2\color{blue}{=(2)_1}\\
\color{blue}{(1)_4}&=4!=24\color{blue}{=\left(\frac{\sqrt{97}-1}{2}\right)_2}=(4.4244\ldots)_2\\
\color{blue}{(1)_6}&=6!=720\color{blue}{=(8)_3}\\
\color{blue}{(1)_8}&=8!=40\,320=\color{blue}{\left(\frac{\sqrt{5+4\sqrt{40\,321}}-3}{2}\right)_4}=(12.714\ldots)_4\\
\color{blue}{(1)_{10}}&=10!=3\,628\,800\color{blue}{=(18.5582\ldots)_5}
\end{align*}
with some help of Wolfram Alpha.

For large $n$ we can employ Stirling's approximation formula
of $n!$ and we obtain a rough estimation by taking the $n$-th root of it.

We so get
\begin{align*}
\color{blue}{(1)_{2n}}&=(2n)!\sim \left(\frac{2n}{e}\right)^{2n}\sqrt{4\pi n}\\
&\,\,\color{blue}{\simeq \left(\left(\frac{2n}{e}\right)^{2}\left(4\pi n\right)^{\frac{1}{2n}}\right)_n}\tag{2}
\end{align*}

Calculating for instance the value for $n=10$ we get $(1)_{10}\simeq(20.4\ldots)_5$.


text:
Q: Event fired when hidden form is showed I have 2 forms, and I want to hide one when the other one is CORRECTLY displayed. I've been using something like this code:
FormA form1 = new FormA();
FormB form2 = new FormB();

private void displayOne()
{
   form1.Show();
   form1.btn.Click += this.showForm2;
   form2.VisibleChanged += this.hideForm1;
}

private void hideForm1 (object sender, EventArgs e)
{
    if (this.form2.Visible)
        this.form1.Hide();
}

private void showForm2 (object sender, EventArgs e)
{
    this.form2.Show();
}

But using VisibleChanged hides form1 before form2 shows.
By the way, I can't use Shown event as forms are shown and hidden and not disposed. Shown is only fired on the first time Form is shown.

A: By what you wrote I got that, you want to, get to show second form, after certain event, right?
then why don't you define it below your button onClick event?
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f = new Form2();
        this.Hide();
        f.ShowDialog();
        this.Close();
    }

Am I right?


text:
Q: Unit testing React component ref Right now a component that looks like this:
  class Notification extends Component {
      constructor(props, context) {
        super(props,context);
      }

      render() {
        return (<NotificationSystem ref="notificationSystem"/>);
      }
   }

   export default Notification;

And my unit test is:
    it('should make react notification system referencable', () => {
        const wrapper = mount(renderComponent(Notification));
        expect(wrapper.ref('notificationSystem').length).toEqual(1);
    })

My renderComponent is:
function renderComponent(ComponentClass, props = {}, state = {}) {
    let store = createStore(reducer, state);
    return (
     <Provider store={store}>
        <ComponentClass { ...props } />
     </Provider>
    );
}

Currently running this test is giving me:
Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded

Any idea how properly test if a component is referenceable?


text:
Q: break up array into little arrays i am sending out email to a list of people.  I have the list of recipients in array but the list can get up to 500 people.  There is a limitation on the number of recipients that my mail server sends out at once (50 recipients)
so if the list is > 50 i need to break it up in to different mails.
What is the best way to take one array and break it up into arrays of 50
for example:
if array is 120 long, i would expect 3 arrays returned, one with 50, another with 50 and a third with 20.

A: You could use the Batch operation from MoreLINQ:
Person[] array = ...;

var arrays = list.Batch(50).Select(x = x.ToArray());

foreach (Person[] shorterArray in arrays)
{
    ...
}

(If you're happy with IEnumerable<Person> instead of arrays, you don't need the Select call of course.)

A: Maybe ArraySegment<T> works for you? You'd have to split it up manually though, but this is not hard in a loop.
int recipient = 0;
while (recipient < recipients.Count) {
  ArraySegment<string> recipientSegment = new ArraySegment<string>(recipients, recipient, Math.Min(50, recipients.Count-recipient));
  // build your message here, using the recipientSegment for the names
  recipient += 50;
}

A: I would simply iterate over the complete array, building up the recipients string, then sending out an email when the limit is reached, then resetting the string and continuing on with the iteration until the next limit event or until the end of the array is reached.

A: If you can use LINQ when you may find this useful: Linq: How to group by maximum number of items

A: A common method for "paging" results from a set is to combine the Skip and Take methods provided by LINQ.  This solution is great because it can be further combined with other LINQ methods to implement filtering, ordering, etc. as needed.
I'm not sure what the performance considerations are for your application, so keep in mind that this may not perform very well for sets where the number of pages is relatively large (i.e., batch size is significantly smaller than the total size of the set), but it's at least fairly straightforward for anyone familiar with this style of coding.
Here's an example of what this implementation might look like:
List<EmailAddress> list = new List<EmailAddress>();
const int BATCH_SIZE = 50;

for (int i = 0; i < list.Count; i += BATCH_SIZE)
{
   IEnumerable<EmailAddress> currentBatch =
      list.Skip(i).Take(BATCH_SIZE);

   // do stuff...
}

A: Shouldn't LINQ be the right stuff for this?


text:
Q: Index Section in viewForHeaderInSection i have UITableView header custom like Instagram where my section acts header, in this tableview i also using paging to get the data from server.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    if (currentPage == 0) {
       return 1;

   }

    if (currentPage < totalPages) {
       return myObject.count+1;
    }

    return myObject.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
   return 1;

 }

 -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection (NSInteger)section

 {

    myTimeline = [myObject objectAtIndex:section];
    //the rest of my code to display text in UILabel cell, etc

 }

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

   if (cell.tag == kLoadingCellTag) {
     currentPage++;
    [self getTimeline];
   }
}

Now the problem is, I already make sure that my paging is working and myObject array count is increase.
But when i do the scroll it crash in method viewForHeaderInSection with reason "index 10 beyond bounds [0 .. 9]'" (i set the paging in in server with 10 items per page)
I think the section in ViewForHeaderInSection not updating with numberOfSectionsInTableView method that i already setup.
So how to make the section in ViewForHeaderInSection updated?
Thanks..

A: Your numberOfSectionsInTableview has return myObject.count+1;, so the table view is dutifully asking for the header for the last section, which is beyond the bounds of your myObject array.  You need either to remove the +1 or, if it's there for a reason, to include code in viewForHeaderInSection to handle that special case:
if (currentPage > 0 && currentPage < totalPages && section == myObject.count) {
    // create whatever header view is appropriate for the final section
} else {
    myTimeline = ... etc
}


text:
Q: Big o notation from formula When you have a formula like this : 3n2 + 10n.log(n) + 1000n + 4.log(n) + 9999.
Do you pick the fastest growing function for the big-o-notation? In this case big  O of n2.
Can someone help me understand what this is asking? Suppose you have a computer that requires 1 minute to solve problem instances of size n = 1,000. Suppose you buy a new computer that runs 1,000 times faster than the old one. What instance sizes can be run in 1 minute, assuming the following time complexities T(n) for our algorithm?

*

*T(n) = n

*T(n) = n3

*T(n) = 10n

A: Let's say that T(n) is the time required to perform n operations (op).
We know that T(1000) = 1' in the old machine and T(1000) = 1'/1000 in the new one (because the new one is 1000 faster.)
a) T(n) = n
This means 1000 op in 1' in the old machine. In the new machine (1000 times faster) is 1000 op in 1'/1000. So 1000000 op in 1' in the new machine, and the answer is 1 million. In other words, the new machine will compute 1000000 operations in 1' (this is 1000 times more operations per minute.)
b) T(n) = n^3
Here we have 1000^3 op in 1' (old machine) and 1000^3 op in 1'/1000 (new machine). So, in the new machine: 1000^3 1000 op in 1', or 1000^3 10^3 op in 1', i.e., 10000^3 op in 1', and the answer is ten thousand.
c) T(n) = 10n
We have 10 * 1000 op in 1' (old), 10 * 1000 op in 1'/1000 (new). So, 10 * 1000000 op in 1', and the answer is again 1 million.
As we can see the answers for T(n) = n and T(n) = 10 n are the same. In fact, they would also be equal to the answer for T(n) = C n, no matter the value of C > 0. To see this, we only have to replace 10 with C above:
C 1000 op in 1' (old), C 1000 op in 1'/1000 (new) or C 1000000 in 1', and the answer is 1000000.
This is why we talk about O(n), O(n^2), O(nˆ3), etc., regardless of the constant hidden inside the O.

A: *

*Yes, 3n^2, or just n^2, would be the "biggest" component.

*For each equation, set T(n) to 1/1000 min and n to 1000 (the relation for the time it takes the new computer to solve an n=1000 size problem).  What do you have to do to get the left side to be 1 min?  If you do the same thing to the right, what value of n does that represent?

A: this is my answer to my homework:


text:
Q: Symfony2 collection field for simple list of emails to be sent I'm trying to accomplish a very basic task: I'd like to have a form with one field (an email address), and an "add" button so that you can add other email addresses. I'll later send emails to each of the addresses passed.
I came across this, which in theory is exactly what I need. I'm fine creating the form inside the controller directly, as I'll use it only here. Here is the function inside the controller:
public function createHRAction(Request $request)
{

$data = array();
$form = $this->createFormBuilder($data)
    ->add('emails', 'collection', array(
// each item in the array will be an "email" field
'type'   => 'email',
// these options are passed to each "email" type
'options'  => array(
    'required'  => false,
    'attr'      => array('class' => 'email-box'),
    'prototype' => true,
    'allow_add' => true,
    ),
))->getForm();

$form->handleRequest($request);

if ($form->isValid())
    {
    //$form->bind($request);

    // $data is a simply array with your form fields
    $data = $form->getData();
    return $this->render('HR/invitationSent.html.twig', array('data' => $data,));
    }
return $this->render('HR/createForm.html.twig', array('form' => $form->createView(),));
}

And here is the twig:

{% extends "internal.html.twig" %}

{% block content %}
{{ form_start(form) }}
    {#

    {# store the prototype on the data-prototype attribute #}

    {% for emailField in form.emails %}

            {{ form_errors(emailField) }}
            {{ form_widget(emailField) }}

    {% endfor %}

    Add another email

     #}
{{ form_end(form) }}

{% endblock content %}

{% block javascripts %}

{% endblock %}

I get the following error:

Key "prototype" for array with keys "value, attr, form, id, name,
  full_name, disabled, label, label_format, multipart, block_prefixes,
  unique_block_prefix, translation_domain, cache_key, read_only, errors,
  valid, data, required, max_length, pattern, size, label_attr,
  compound, method, action, submitted, allow_add, allow_delete" does not
  exist in HR/createForm.html.twig at line 8

I thought I solved it by adding the lines:

    'prototype' => true,
    'allow_add' => true,

but in effect it did not change anything :(
Tips?

A: The 'prototype' and 'allow_add' are their own options.  The 'options' is the array passed to the form type you specify in 'type' (so what each 'email' option would have, in this case).  See the documentation here:  http://symfony.com/doc/current/reference/forms/types/collection.html
Your form creation should look like this:
$this->createFormBuilder($data)
    ->add('emails', 'collection', array(
        'type'      => 'email',
        'prototype' => true,
        'allow_add' => true,
        'options'   => array(
            'required'  => false,
            'attr'      => array('class' => 'email-box'),
        )
    )
)->getForm();


text:
Q: Changing size of JFrame in an argument Alright, so I have a class called Ball, where I'm putting some arguments inside the constructor. Here I have intial position, size and speed, but I also need to be able to set the size of the window (the JFrame) in the argument, so that when I call e.g. ball(xpos,ypos,size,speed,windowx,windowy) it will set the size of the JFrame according to what I put in windowx and windowy.
Right now I'm just trying stuff like a headless chicken without really knowing what I'm doing :P, so if someone could point me in the right direction, I would be very grateful!
package com.company;

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class Main extends JPanel {

    static Ball[] balls = new Ball[20];
    Random rand = new Random();

    Main() {

        for(int i = 0; i<20;i++){
            float r = rand.nextFloat();
            float g = rand.nextFloat();
            float b = rand.nextFloat();
            Color randomColor = new Color(r, g, b);
            balls[i] = new Ball(Ball.randInt(100, 500),Ball.randInt(100, 500),Ball.randInt(10, 50),rand.nextInt(6-1)+1,randomColor,600,600);

        }
    }

    public void paintComponent(Graphics g) {

        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        for(int i=0;i<20;i++) {
            balls[i].draw(g);
        }

    }

    public static void main(String[] args) throws InterruptedException{

        Main m = new Main();
        JFrame frame = new JFrame("Title"); //create a new window and set title on window
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set the window to close when the cross in the corner is pressed
        frame.setSize(600,600);
        frame.add(m); //add the content of the game object to the window
        frame.setVisible(true); //make the window visible

        while(true){

            Thread.sleep(10);
            for(int i= 0;i<balls.length;i++){
                balls[i].update();
            }

            m.repaint();
        }

    }

}

Ball class:
 package com.company;

    import javax.swing.*;
    import java.awt.*;
    import java.util.Random;
    /**
     * Created by John on 25/02/2015.
     */

    public class Ball extends JPanel{
        float _speedX;
        float _speedY;
        int _size;
        float _x;
        float _y;
        float _speed;
        Color _color;
        int _windowX;
        int _windowY;

        Ball(int x, int y, int sz, float speed, Color c, int windowX, int windowY){
            _x = x;
            _y = y;
            _speed=speed;
            _speedX = speed;
            _speedY = speed;
            _size = sz;
            _color = c;
            _windowX = windowX;
            _windowY = windowY;

        }

        public void update(){

                _x += _speedX;
                _y += _speedY;

                if (_x+_size<0 || _x+_size>_windowX-_size){
                    _speedX*=-1;
                }

                if (_y+_size<0 || _y+_size>_windowY-_size){
                    _speedY*=-1;
                }

    this.repaint();

        }
        public static int randInt(int min, int max) {
            Random rand = new Random();
            int randomNum = rand.nextInt((max - min) + 1) + min;
            return randomNum;
        }

        public void draw(Graphics g) {
            g.setColor(_color);
            g.fillOval((int)_x,(int) _y, _size, _size);

        }

        public void setPreferredSize(int wX, int wY) {
            _windowX=wX;
            _windowY=wY;
            setPreferredSize(new Dimension(_windowX,_windowY));
        }
    }


text:
Q: How can I resize a watermark on an image with PHP? Hi i'm trying to resize watermark png on uploaded images, but just can't figure it out, what i'm doing wrong.
Here is my code:
// BEGIN WATERMARK

$watermark = imagecreatefrompng ('watermark.png');
$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);
$image = imagecreatetruecolor($watermark_width, $watermark_height);
$_Dim[x] = imageSX($destImage);
$_Dim[y] = imageSY($destImage);
$logo_Dim[x] = imageSX($watermark);
$logo_Dim[y] = imageSY($watermark);
$x = $_Dim[x] - $logo_Dim[x];
$y = $_Dim[y] - $logo_Dim[y];
imagecopy ($destImage, $watermark, $x, $y, 0, 0, $watermark_width, $watermark_height);
imagedestroy ($watermark);

// END WATERMARK

A: You can use this function for resize your stamp. Don't use the imagecopyresized because it corrupts your image and you will take lower quality. Better is imagecopyresampled.
imagesavealpha and imagealphablending provide you make the transparent background for you stamp
$image = imagecreatefromstring(file_get_contents('The_img.jpg'));
$stamp = imagecreatefrompng('the_watermark.png');

$stamp_new = imagecreatetruecolor(100,50);
imagealphablending($stamp_new, false);
imagesavealpha($stamp_new, true);
imagecopyresampled($stamp_new, $stamp, 0, 0, 0, 0, 100, 50, imagesx($stamp),imagesy($stamp));

$margin = ['right' => 20, 'bottom' => 20]; // Смещение от края
imagecopy($image, $stamp_new,
imagesx($image) - imagesx($stamp_new) - $margin['right'],
imagesy($image) - imagesy($stamp_new) - $margin['bottom'],
0, 0, imagesx($stamp_new), imagesy($stamp_new));
$imageName = 'newimage.jpg';
$dirName = 'test_folder';
if(!file_exists($dirName)){
    mkdir($dirName, 0755, true);
    imagepng($image, $dirName.'/'.$imageName);
} else {
    imagepng($image, $dirName.'/'.$imageName);
}

ImageDestroy($image);
ImageDestroy($stamp);

A: Use: imagecopyresized or imagecopyresampled

$watermark = imagecreatefrompng ('watermark.png');
$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);

// this is an example to resized your watermark to 0.5% from their original size.
// You can change this with your specific new sizes.
$percent = 0.5;
$newwidth = $watermark_width * $percent;
$newheight = $watermark_height * $percent;

// create a new image with the new dimension.
$new_watermark = imagecreatetruecolor($newwidth, $newheight);

// Retain image transparency for your watermark, if any.
imagealphablending($new_watermark, false);
imagesavealpha($new_watermark, true);

// copy $watermark, and resized, into $new_watermark
// change to `imagecopyresampled` for better quality
imagecopyresized($new_watermark, $watermark, 0, 0, 0, 0, $newwidth, $newheight, $watermark_width, $watermark_height);

$_Dim[x] = imageSX($destImage);
$_Dim[y] = imageSY($destImage);
$logo_Dim[x] = imageSX($new_watermark);
$logo_Dim[y] = imageSY($new_watermark);
$x = $_Dim[x] - $logo_Dim[x];
$y = $_Dim[y] - $logo_Dim[y];
imagecopy ($destImage, $new_watermark, $x, $y, 0, 0, $newwidth, $newheight);
imagedestroy ($new_watermark);

Note: I'm assuming you have another imageSX & imageSY functions, because the built-in functions are in all low-case: imagesx & imagesy.
Edit 1: function name in php are not case-sensitive, but its a good practice to call functions as they appear in their declaration.
Edit 2: Add more code to retain transparency.


text:
Q: ArrayIndexOutOfBoundsException during generating benchmarking report in OptaPlanner So I want to run OptaPlanner's benchmarking and I have been able to succesfully implement this for various problems (tsp, vrp).
Now I am running it for a more complicated vrp, but I am being faced with an ArrayIndexOutOfBoundsException during the generation of the benchmark report.
// start benchmark
PlannerBenchmarkFactory plannerBenchmarkFactory = PlannerBenchmarkFactory.createFromXmlFile(
    new File("src/main/resources/vehiclerouting/benchmark/vrpBenchmarkConfig.xml"));

PlannerBenchmark plannerBenchmark = plannerBenchmarkFactory.buildPlannerBenchmark();
plannerBenchmark.benchmark(); //exception is thrown here.

Drilling down I found out it occurs in writeBestScoreSummaryChart() in BenchMarkReport.
private void writeBestScoreSummaryChart() {
    // Each scoreLevel has it's own dataset and chartFile
    List<DefaultCategoryDataset> datasetList = new ArrayList<>(CHARTED_SCORE_LEVEL_SIZE);
    for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) {
        String solverLabel = solverBenchmarkResult.getNameWithFavoriteSuffix();
        for (SingleBenchmarkResult singleBenchmarkResult : solverBenchmarkResult.getSingleBenchmarkResultList()) {
            String planningProblemLabel = singleBenchmarkResult.getProblemBenchmarkResult().getName();
            if (singleBenchmarkResult.hasAllSuccess()) {
                double[] levelValues = ScoreUtils.extractLevelDoubles(singleBenchmarkResult.getAverageScore());
                for (int i = 0; i < levelValues.length && i < CHARTED_SCORE_LEVEL_SIZE; i++) {
                    if (i >= datasetList.size()) {
                        datasetList.add(new DefaultCategoryDataset());
                    }
                    datasetList.get(i).addValue(levelValues[i], solverLabel, planningProblemLabel);
                }
            }
        }
    }
    bestScoreSummaryChartFileList = new ArrayList<>(datasetList.size());
    int scoreLevelIndex = 0;
    for (DefaultCategoryDataset dataset : datasetList) {
        String scoreLevelLabel = plannerBenchmarkResult.findScoreLevelLabel(scoreLevelIndex);
        CategoryPlot plot = createBarChartPlot(dataset,
                "Best " + scoreLevelLabel, NumberFormat.getInstance(locale));
        JFreeChart chart = new JFreeChart("Best " + scoreLevelLabel + " summary (higher is better)",
                JFreeChart.DEFAULT_TITLE_FONT, plot, true);
        bestScoreSummaryChartFileList.add(writeChartToImageFile(chart, "bestScoreSummaryLevel" + scoreLevelIndex));
        scoreLevelIndex++;
    }
}

In the above method datasetList reaches a size of 7. (We have 7 score levels -> 6 hard, 1 soft).
When plannerBenchmarkResult.findScoreLevelLabel(scoreLevelIndex); is called in the second loop findScoreLevelLabel() only returns 5 score levels. Namely: hard 0 score, hard 1 score hard 2 score hard 3 score and  soft 0 score.
So once the scoreLevelLabel has a value >4 an ArrayIndexOutOfBoundsException is thrown. Any ideas / hints on why Optaplanner registers 5 score levels, whilst there should be 7.
EDIT
Stacktrace:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at org.optaplanner.benchmark.impl.result.PlannerBenchmarkResult.findScoreLevelLabel(PlannerBenchmarkResult.java:242)
at org.optaplanner.benchmark.impl.report.BenchmarkReport.writeBestScoreSummaryChart(BenchmarkReport.java:365)
at org.optaplanner.benchmark.impl.report.BenchmarkReport.writeReport(BenchmarkReport.java:241)
at org.optaplanner.benchmark.impl.DefaultPlannerBenchmark.benchmarkingEnded(DefaultPlannerBenchmark.java:306)
at org.optaplanner.benchmark.impl.DefaultPlannerBenchmark.benchmark(DefaultPlannerBenchmark.java:104)
at benchmark.BenchMarker.main(BenchMarker.java:57)

A: I have found the issue.
@PlanningScore(bendableHardLevelsSize = 4, bendableSoftLevelsSize = 1)
public BendableLongScore getScore() {
    return score;
}

The appropriate score levels were not updated when more levels were added.
I don't know how a wrong declaration affects Optaplanner though. Are these levels used for other things other than (de)serialization ?


text:
Q: Running commands on multiple servers I want to execute a process on multiple servers. I am using the following wrapper script.  The script moves to servers one at a time.  I would like to change it so it can execute on multiple servers. Is there way to do it?
#!/bin/bash
for ip in $(<ALL_SERVERS_IP); do
    # Tell the remote server to start bash, but since its
    # standard input is not a TTY it will start bash in
    # noninteractive mode.
    ssh -q "$ip" bash <<-'EOF'
        printf "%s\n" ================== "$(hostname) ::: Current date : $(date)" \
                            ==================
        ./remote
    EOF
done

A: Yes.  Try pdsh, which will execute a command on multiple remote hosts simultaneously.  Your task could be written like so:
pdsh -w ssh:$(echo $(<ALL_SERVERS) | sed -e 's/ /,/g') 'printf "%s\n" ...'

A: Sounds like you're looking for GNU Parallel. That's pretty much exactly what it was written for. In your case, you would do:
parallel ./remote --sshloginfile ALL_SERVERS_IP

The above assumes that ALL_SERVERS_IP is a text file with one IP or hostname per line. If they can have different logins, make the list like so:
user@server.example.com
foo@server2.example.com
bar@server3.example.com

A: I know some tools for that, but the easiest is Fabric. Take a look and tell me what do you think.


text:
Q: c# use user settings in multiple datagridview I am a new self taught programmer and I feel like there is a better way to accomplish this, so here I am asking.  Thanks.
I have a c# program I am writing, uses windows forms, I have multiple forms with datagridview on them.
I have created another form that allows the user to set preferences about how the view them
ex: font, background color, alt row color, etc.
So, at each grid I end calling the same code to retrieve these settings, I am just trying to see if there is a more central streamlined approach.
Here is the code I use at each grid to give you a better idea.
        //pull the custom user settings for the datagridview
        dgvAds.AlternatingRowsDefaultCellStyle.BackColor = Properties.Settings.Default.AltRowColor;
        dgvAds.DefaultCellStyle.BackColor = Properties.Settings.Default.RowColor;
        dgvAds.Font = Properties.Settings.Default.RowFont;

A: The most direct way is to call a common function that does these preprarations. You can put it at a level where you can call it from everywhere, like a static Utlities class..:
public static class Utilities
{
    public static void loadDGVSettings(DataGridView DGV)
    {
        if (DGV != null)
        {
            //pull the custom user settings for the datagridview
            DGV.AlternatingRowsDefaultCellStyle.BackColor =
                Properties.Settings.Default.AltRowColor;
            DGV.DefaultCellStyle.BackColor = Properties.Settings.Default.RowColor;
            DGV.Font = Properties.Settings.Default.RowFont;
            // ...
        }
    }
}

You would call it from each Form with the respective DataGridView, after maybe InitializeComponents()..:
public Form1()
{
    InitializeComponent();
    Utilities.loadDGVSettings(dataGridView1);
}

To create a class: right-click the project, choose  add class, give it the name you like and replace the class stub with code like above. You will need to add a using System.Windows.Forms; clause to such a class file.


text:
Q: Azure Storage Gui I'm trying to create a GUI based script so that i can easily select same as web interface selecting from List View . Trying to acheive this using powershell .  I would like to create azure resource group directly using the location i selected . The same approach would be for creating Azure Storage account as well . Let me know if there are any resources / pointing websites where i can check on sample script which has already implemented such option for Azure .
I tried hard coding all the values that i need as a part of power shell script under parameters but would want to use it in a GUI .
Any pointers would be greatly helpful . I tried using Windows forms
New-Object System.Windows.Forms.Label  that has been throwing errors .
I tried below approach but the form loads but fails to use the parameters i have selected :
Add-Type -Assembly Name System.Windows.Forms
Add-Type -Assembly Name System.Drawing
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Select a Resource Group'
$form.Size = New-Object System.Drawing.Size(300,200)
$form.Start Position = 'Center Screen'
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = 'OK'
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = 'Cancel'
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = 'Please select a Resource Group:'
$form.Controls.Add($label)
$listBox = New-Object System.Windows.Forms.ListBox
$listBox.Location = New-Object System.Drawing.Point(10,40)
$listBox.Size = New-Object System.Drawing.Size(260,20)
$listBox.Height = 80
[void] $listBox.Items.Add('West Europe')
[void] $listBox.Items.Add('East US')
[void] $listBox.Items.Add('West US')
$form.Controls.Add($listBox)
$form.Topmost = $true
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult   ]::OK)
{
 New-AzureRmResourceGroup -Name $resourceGroupName -Location
 $resourceGroupLocation
 }

A: Update
 Add-Type -AssemblyName system.drawing
 $form = New-Object System.Windows.Forms.Form
 $form.Text ='Select a Resource Group'
 $form.Size = New-Object System.Drawing.Size(300,200)
 $form.StartPosition ='CenterScreen'
 $OKButton = New-Object System.Windows.Forms.Button
 $OKButton.Location = New-Object System.Drawing.Point(75,120)
 $OKButton.Size = New-Object System.Drawing.Size(75,23)
 $OKButton.Text = 'OK'
 $OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
 $form.AcceptButton = $OKButton
 $form.Controls.Add($OKButton)

 $CancelButton = New-Object System.Windows.Forms.Button
 $CancelButton.Location = New-Object System.Drawing.Point(150,120)
 $CancelButton.Size = New-Object System.Drawing.Size(75,23)
 $CancelButton.Text = 'Cancel'
 $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
 $form.CancelButton = $CancelButton
 $form.Controls.Add($CancelButton)

 $label = New-Object System.Windows.Forms.Label
 $label.Location = New-Object System.Drawing.Point(10,20)
 $label.Size = New-Object System.Drawing.Size(280,20)
 $label.Text ='Please select a Resource group'
 $form.Controls.Add($label)

 $listBox = New-Object System.Windows.Forms.ListBox
 $listBox.Location = New-Object System.Drawing.Point(10,40)
 $listBox.Size = New-Object System.Drawing.Size(260,20)
 $listBox.Height=80

 #get all the available location
 $mylocations = Get-AzureRmLocation | select DisplayName
 foreach($location in $mylocations){[void]$listBox.Items.Add($location.displayname)}
 $form.Controls.Add($listBox)
 $form.TopMost = $true
 $result = $form.ShowDialog()

 $selectedLocation = $listBox.SelectedItem
 Write-Output $selectedLocation

 if($result -eq [System.Windows.Forms.DialogResult]::OK)
 {
    New-AzureRmResourceGroup -Name "your_resource_group_name" -Location $selectedLocation
 }

If you use powershell, you just need make some changes in your code.
1.use Get-AzureRmLocation | select DisplayName to get all the locations, then add all of the locations to the listbox:
$mylocations = Get-AzureRmLocation | select DisplayName

foreach($location in $mylocations){[void]$listBox.Items.Add($location.displayname)}

2.after select the location in the dialog, then use $listBox.SelectedItem to get the selected location.
$selectedLocation = $listBox.SelectedItem

#use the selected location to create resource group
New-AzureRmResourceGroup -Name $resourceGroupName -Location $selectedLocation

Please let me know if any more issues.


text:
Q: Ant: Check if two numbers are equal I have an ant task which should compare two values for equality. If the two values are not equal, I'd like to fail:
<condition property="versionDoesNotMatch">
  <not>
    <equals arg1="applicationVersion" arg2="releaseNotesVersion"/>
  </not>
</condition>
<fail if="versionDoesNotMatch" message="Version of Application and Release notes does not match."/>

According to the ant output, both values, releaseNotesVersion and applicationVersion have the same value 1.7 but the condition always evaluates to true - which because of the not would mean, that the numbers are not equal. Which makes me wonder, if ant would have troubles comparing those kind of values ?

A: You're matching two literal strings in your example; these will never be equal and so your condition always evaluates to true.  Assuming that your args are Ant properties, you need to evaluate the property values like this:
<condition property="versionDoesNotMatch">
  <not>
    <equals arg1="${applicationVersion}" arg2="${releaseNotesVersion}"/>
  </not>
</condition>
<fail if="versionDoesNotMatch" message="Version of Application and Release notes does not match."/>


text:
Q: Rail3 Blog Engine I have an existing Rails3 web application and would like to add a blog to it.  Just something basic, but with slugs (/blog/2011/07/permalink-to-entry).
Thoughts?

A: You can create and mount Refinery cms as an engine in your existing app.
https://github.com/resolve/refinerycms

A: Refinery also has a blog engine: https://github.com/resolve/refinerycms-blog


text:
Q: detecting scroll event on a page-scoped div When a css file contains an instruction like this:
body {
  width: 100%;
  height: 100%;
}

A JS code like the following does not detect the scrolling event.
$(window).on('scroll', function(){
   alert('this alert does not fire');
});

I guess with that css, there is no possibility of a scroll event and hence the reason why the scrolling event does not fire.
So I wrapped the entire page body content into a div, like this:

      the entire page content here

In this case, what would be the correct version of the JS code below so we can catch these alerts in a timely fashion?
$(window).on('scroll', function(){

   if( $(window).scrollTop()>50 ){
       alert('1');
   }
   else {
       alert('2');
   }
});

A: When a page is styled like:
body {
    width: 100%;
    height: 100%;

}
you cannot listen for the window scroll event because there is nothing to scroll.
Instead, you may use mouse wheel event:

$(window).on('wheel', function(){
  console.log('this alert fires');
});
body {
  width: 100%;
  height: 100%;
}

UPDATE
You may  handle the following events:

*

*wheel (when you use the mouse wheel)

*mousedown (when you click on the scroll bar of the doc to scroll)

*keydown (ctrl+home, ctrl+hend, down-up arrow, pgdown and pgup: keyboard scrolling)

The new snippet:

$(document).on('wheel mousedown keydown', function(e){
  if (e.type == 'wheel' || (e.target.id == 'full-content-div' && e.type == 'mousedown' && e.clientX >= $('div[canvas="container"]').width()) ||
      (e.type == 'keydown' && ((e.ctrlKey && (e.keyCode  == 36 || e.which == 35)) ||
                               (!e.ctrlKey && (e.keyCode  == 33 || e.which == 34 || e.which == 38|| e.which == 40))))
     ) {
    console.log(e.type + ' event');
  }
});
div[canvas="container"]{
  width: 100%;
  height: 100vh;
  overflow: scroll;
}

    the entire page content here


text:
Q: Formatting a cell based on a list in Excel I'm trying to format a single cell within a worksheet, so that it is highlighted if a postcode contained within a long list of postcodes is entered. The cell I'm trying to conditionally format is E26, and the list of postcodes is A63:A2559, and the postcodes are all entered without a space (e.g. SW1A0AA).  I've tried a number of ways and formulas to conditionally format the cell (=MATCH, etc), but I keep getting error messages, or it just doesn't format the cell.  Is anyone able to help me with a formula?
Thanks in advance

A: I just tested this formula, if I understand your requirements correctly, it works.
=NOT(ISERROR(MATCH($E$26,$A$63:$A$2559,0)))

My picture below uses different ranges, but just you so how I laid the data - to mimic what I understood as your data set. If it's different, let me know.
E6 passes the test, F6 does not.


text:
Q: How to create dynamic methods using method_missing in ruby modules I have a module that has a few methods that help find database entries, and I'm trying to create dynamic methods of this sample method:
def find_by(db_attribute, value)
  rows = connection.execute <<-SQL
    SELECT #{columns.join ","} FROM #{table}
    WHERE #{db_attribute} = #{Record::Utility.sql_strings(value)};
  SQL
end

I want to figure out how to get a call object.find_by_*( * star here being the db_attribute that would normally be in the parameter of find_by) like this: klass.find_by_name('bob') to return the same thing as find_by(:name, 'bob').

A: A very simple solution
def method_missing(method_name, *args, &block)
  if method_name.to_s =~ /^find_by_(.+)$/
    find_by($1.to_sym => args)  # find_by_name, the $1 is `name`
  else
    super(method_name, *args, &block)
  end
end


text:
Q: Jenkins is running but service says it is failed Since I have installed jenkins 2.319.1 on CentOS7 via yum update jenkins I have the problem, that I can start jenkins as service via sudo systemctl start jenkins.
Then jenkins will start an I can access it via the browser..
However if I try to get the status of the service via  sudo systemctl status jenkins.
I get first:
PROD [root@abmrndplje001 grafra1969]$ systemctl status jenkins
● jenkins.service - LSB: Jenkins Automation Server
   Loaded: loaded (/etc/rc.d/init.d/jenkins; bad; vendor preset: disabled)
  Drop-In: /etc/systemd/system/jenkins.service.d
           └─00-proxy.conf
   Active: activating (start) since Wed 2021-12-15 19:42:42 CET; 1min 54s ago
     Docs: man:systemd-sysv-generator(8)
  Control: 969 (jenkins)
   CGroup: /system.slice/jenkins.service
           ├─ 969 /bin/sh /etc/rc.d/init.d/jenkins start
           ├─1004 runuser -s /bin/bash jenkins -c ulimit -S -c 0 >/dev/null 2>&1 ; /etc/alternatives/java ...
           ├─1035 bash -c ulimit -S -c 0 >/dev/null 2>&1 ; /etc/alternatives/java -Djava.awt.headless=true...
           └─1041 /etc/alternatives/java -Djava.awt.headless=true -Xmx8g -XX:MaxPermSize=1024m -DJENKINS_H...

Dec 15 19:42:42 abmrndplje001.pass-consulting.com systemd[1]: Starting LSB: Jenkins Automation Server...
Dec 15 19:42:42 abmrndplje001.pass-consulting.com runuser[1004]: pam_unix(runuser:session): session open...0)
Dec 15 19:42:42 abmrndplje001.pass-consulting.com jenkins[969]: Starting Jenkins OpenJDK 64-Bit Server V....0
Dec 15 19:42:55 abmrndplje001.pass-consulting.com jenkins[969]: WARNING: An illegal reflective access op...ed
Dec 15 19:42:55 abmrndplje001.pass-consulting.com jenkins[969]: WARNING: Illegal reflective access by co...n)
Dec 15 19:42:55 abmrndplje001.pass-consulting.com jenkins[969]: WARNING: Please consider reporting this ...$2
Dec 15 19:42:55 abmrndplje001.pass-consulting.com jenkins[969]: WARNING: Use --illegal-access=warn to en...ns
Dec 15 19:42:55 abmrndplje001.pass-consulting.com jenkins[969]: WARNING: All illegal access operations w...se
Hint: Some lines were ellipsized, use -l to show in full.
PROD [root@abmrndplje001 grafra1969]$

After about 5 min. The status changes from activating to failed and as reason is given a timeout. However the processes are still runing and jenkins is working and can be accessed via the browser.
PROD [root@abmrndplje001 grafra1969]$ systemctl status jenkins -l
● jenkins.service - LSB: Jenkins Automation Server
   Loaded: loaded (/etc/rc.d/init.d/jenkins; bad; vendor preset: disabled)
  Drop-In: /etc/systemd/system/jenkins.service.d
           └─00-proxy.conf
   Active: failed (Result: timeout) since Wed 2021-12-15 19:47:42 CET; 5min ago
     Docs: man:systemd-sysv-generator(8)
  Process: 969 ExecStart=/etc/rc.d/init.d/jenkins start (code=killed, signal=TERM)
   CGroup: /system.slice/jenkins.service
           ├─1004 runuser -s /bin/bash jenkins -c ulimit -S -c 0 >/dev/null 2>&1 ; /etc/alternatives/java -Dj                                                                   ava.awt.headless=true -Xmx8g -XX:MaxPermSize=1024m -DJENKINS_HOME=/var/lib/jenkins -jar /usr/lib/jenkins/jenk                                                                   ins.war --logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war --daemon --httpPort=8080 --ht                                                                   tpListenAddress=localhost --debug=5 --handlerCountMax=100 --handlerCountMaxIdle=20
           ├─1035 bash -c ulimit -S -c 0 >/dev/null 2>&1 ; /etc/alternatives/java -Djava.awt.headless=true -X                                                                   mx8g -XX:MaxPermSize=1024m -DJENKINS_HOME=/var/lib/jenkins -jar /usr/lib/jenkins/jenkins.war --logfile=/var/l                                                                   og/jenkins/jenkins.log --webroot=/var/cache/jenkins/war --daemon --httpPort=8080 --httpListenAddress=localhos                                                                   t --debug=5 --handlerCountMax=100 --handlerCountMaxIdle=20
           └─1041 /etc/alternatives/java -Djava.awt.headless=true -Xmx8g -XX:MaxPermSize=1024m -DJENKINS_HOME                                                                   =/var/lib/jenkins -jar /usr/lib/jenkins/jenkins.war --logfile=/var/log/jenkins/jenkins.log --webroot=/var/cac                                                                   he/jenkins/war --daemon --httpPort=8080 --httpListenAddress=localhost --debug=5 --handlerCountMax=100 --handl                                                                   erCountMaxIdle=20

Dec 15 19:42:42 abmrndplje001.pass-consulting.com jenkins[969]: Starting Jenkins OpenJDK 64-Bit Server VM war                                                                   ning: Ignoring option MaxPermSize; support was removed in 8.0
Dec 15 19:42:55 abmrndplje001.pass-consulting.com jenkins[969]: WARNING: An illegal reflective access operati                                                                   on has occurred
Dec 15 19:42:55 abmrndplje001.pass-consulting.com jenkins[969]: WARNING: Illegal reflective access by com.goo                                                                   gle.inject.internal.cglib.core.$ReflectUtils$2 (file:/var/cache/jenkins/war/WEB-INF/lib/guice-4.0.jar) to met                                                                   hod java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
Dec 15 19:42:55 abmrndplje001.pass-consulting.com jenkins[969]: WARNING: Please consider reporting this to th                                                                   e maintainers of com.google.inject.internal.cglib.core.$ReflectUtils$2
Dec 15 19:42:55 abmrndplje001.pass-consulting.com jenkins[969]: WARNING: Use --illegal-access=warn to enable                                                                    warnings of further illegal reflective access operations
Dec 15 19:42:55 abmrndplje001.pass-consulting.com jenkins[969]: WARNING: All illegal access operations will b                                                                   e denied in a future release
Dec 15 19:47:42 abmrndplje001.pass-consulting.com systemd[1]: jenkins.service start operation timed out. Term                                                                   inating.
Dec 15 19:47:42 abmrndplje001.pass-consulting.com systemd[1]: Failed to start LSB: Jenkins Automation Server.
Dec 15 19:47:42 abmrndplje001.pass-consulting.com systemd[1]: Unit jenkins.service entered failed state.
Dec 15 19:47:42 abmrndplje001.pass-consulting.com systemd[1]: jenkins.service failed.

How can one start the service correctly?
I just found out that the same jenkins version is running on different CentOS7 server and the service status is active.
The only difference I have seen so far, ist that the working version is not using runuser as the first command
[root@jenkins2-rnd grafra1969]# systemctl status jenkins
● jenkins.service - LSB: Jenkins Automation Server
   Loaded: loaded (/etc/rc.d/init.d/jenkins; bad; vendor preset: disabled)
   Active: active (running) since Thu 2021-12-16 15:57:56 CET; 18min ago
     Docs: man:systemd-sysv-generator(8)
  Process: 4436 ExecStop=/etc/rc.d/init.d/jenkins stop (code=exited, status=0/SUCCESS)
  Process: 4448 ExecStart=/etc/rc.d/init.d/jenkins start (code=exited, status=0/SUCCESS)
   CGroup: /system.slice/jenkins.service
           ├─ 1883 ssh-agent
           ├─ 3329 ssh-agent
           ├─ 4452 /etc/alternatives/java -Djava.awt.headless=true -Dhudson.plugins.active_directory.ActiveDirectorySecurityRealm.forceLdaps=f...
           ├─ 5150 ssh-agent
           ├─ 8365 ssh-agent
           ├─12083 sh -c ({ while [ -d '/var/lib/jenkins/workspace/Pam4Web_master@tmp/durable-8b6bf811' -a \! -f '/var/lib/jenkins/workspace/P...
           ├─12084 sh -c ({ while [ -d '/var/lib/jenkins/workspace/Pam4Web_master@tmp/durable-8b6bf811' -a \! -f '/var/lib/jenkins/workspace/P...
           ├─12085 sh -xe /var/lib/jenkins/workspace/Pam4Web_master@tmp/durable-8b6bf811/script.sh
           ├─12088 /usr/lib/jvm/java-11-openjdk/bin/java -classpath /var/lib/jenkins/tools/hudson.tasks.Maven_MavenInstallation/Maven-3.6/boot...
           ├─12969 sleep 3
           ├─13279 ssh-agent
           ├─14595 ssh-agent
           ├─15882 ssh-agent
           └─17056 ssh-agent

A: I had exactly the same problem and fix it.
The problem comes from your /etc/init.d/jenkins.
You probably modify it and the update process (yum on rhel7) is not able to replace it.
This 'old file' is not more compatible with the new version of jenkins. It's why systemctl commands are not working correctly.

A: The problem was that yum wanted to install a new version of /etc/init.d/jenkins. However since I hat edited it before. The new file has been installed in /etc/init.d/jenkins.rpmnew instead and systemd still used the old one. What I did was to take over my changes form the old /etc/init.d/jenkins to the new file. Then delete the old /etc/init.d/jenkins, rename /etc/init.d/jenkins.rpmnew to /etc/init.d/jenkins and restart the service.


text:
Q: Sqoop teradata table whith same columns title I've got an error importing data from teradate to an Hadoop cluster using Sqoop.
My tera table have 2 columns title (not columns name)equivalent. Is there an automatic way to use col name instead of col title in my sqoop job ?
I've tried to use a "Select * from table" as a query but does not work.
And I can't change col title in teradata.
Here my job code :
sqoop job -Dmapred.job.queue.name=shortduration \
             --create inc_My_Table \
             -- import \
             --connect jdbc:teradata://RCT/DATABASE=DWHBIG \
             --driver com.teradata.jdbc.TeraDriver \
             --username MBIGDATA -P \
             --query "select a.* from My_Table a where \$CONDITIONS" \
             --target-dir /data/source/fb/$i \
             --check-column DAT_MAJ_DWH \
             --incremental  append \
             --last-value 2001-01-01 \
             --split-by ID
Any idea ? Thanks

A: Since Teradata JDBC Driver 16.00.00.28, you can use connection URL parameter COLUMN_NAME to control the behavior of the getColumnName and getColumnLabel to return the column name, column title, or As-clause name, That should resolve your problem.

*

*COLUMN_NAME=OFF (the default) specifies that the
ResultSetMetaData.getColumnName method should return the AS-clause
name if available, or the column name if available, or the column
title, and specifies that the ResultSetMetaData.getColumnLabel method
should return the column title.

*COLUMN_NAME=ON specifies that, when StatementInfo parcel support is
available, the ResultSetMetaData.getColumnName method should return
the column name if available, and specifies that the
ResultSetMetaData.getColumnLabel method should return the AS-clause
name if available, or the column name if available, or the column
title. This option has no effect when StatementInfo parcel support is
unavailable.

A: I finally found a solution. I aliased the column that was causing the issue using the AS SQL command!


text:
Q: How do I search a file then output a line with the keyword searched to a new file I'm trying to search a large file with a keyword in perl, then output ALL the lines the keyword appears in, each into a new line.

A: The following will print all lines containing keyword to outputFile.txt. The input files are passed as arguments to the script.
findkeyword.pl
#!/usr/bin/perl
use strict;
use warnings;

open OUTPUT, ">outputFile.txt";
while (my $line = <>) {
     if($line =~ m/keyword/){
     print OUTPUT $line;
     }
}

Input:
./findkeyword.pl inputfile1 inputfile2 ...

Edit: As said by @Kenosis in the comments,
It might be better to use a lexically scoped $fh as file-handle like open(my $fh, ">", "outputFile.txt"). Reference: open()
If you are storing keyword in a variable, you might want to call quotemeta on it first, or enclose it in \Q...\E.


text:
Q: Change TableViewCell Text Color Here is a situation.
I have a TableCell with a Icon and a Label.
I want that when a PRESS the Cell, only my Label change Colors, without change the Background or anything, just the Text.
How I do that?
The effect is like the one on Spotify app.

A: You can use delegate methods of the UITableView for this.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell;
    // Initialize cell
    // If you want to use custom label, don't forget to set it a unique tag.
    cell.textLabel.text = @"Label";
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * selectedCell = [tableView cellForRowAtIndexPath:indexPath];
    // If you created a custom label, get it like the next line and then change the color of it;
    // UILabel * label = (UILabel *) [selectedCell viewWithTag: UNIQUE_TAG];
    selectedCell.textLabel.textColor = [UIColor redColor]; // Or which color you'd like.
}


text: Q: Resizing QGIS custom form I have followed this tutorial to create custom forms in QGIS (I work with version 2.18). However, I seem to be unable to control the shape and size of the form window. Thus, widgets are frequently out of scope or the window is oversized. Am I missing something ?


text:
Q: Ansible Preferred Way Of Running An Ad Hoc Command I'm pretty new to Ansible, just a day old and while trying out some basic ad hoc commands, I noticed that in order to create a directory on a group named nodes, both of the following commands worked.
METHOD 1
ansible nodes -a "mkdir /BYANSIBLE_2"

METHOD 2
ansible nodes -m file -a "path=/BYANSIBLE_3 state=touch"

According to the documentation, -a means module arguments, so why does METHOD 1 work ?
According to my understanding merely providing the arguments of a module without specifying the module itself shouldn't work (unless there is some implicit default).

Also, as a newbie, should I focus on METHOD 1 or METHOD 2 when using adhoc commands ?

A: Ansible uses the module ansible.builtin.command by default if no module is provided in the command line . This module just runs commands on the remote nodes command line, which is why "mkdir path" works. for you. The argument for this module is, well, a command.
On method 2 you are actually calling a specific module "file" that has its own definition of the arguments required. The argument for this module is just the path that needs to be created.
The method that you use depend on the case. If you are testing commands on remote nodes, method 1 would be my go to, since is faster than explicitly adding the module name. Method 2 is better in the sense that is more explicit in intention.
But more importantly, i try to keep ad hoc commands for very small tests and tasks. Ansible is about automating and scaling to me, so i try to create playbooks whenever possible.
You can read more in the following link:
https://docs.ansible.com/ansible/latest/user_guide/intro_adhoc.html


text:
Q: Custom Annotation view for userlocation not moving the mapview Can we have custom annotation view for the users current location in iOS?
I need to remove the blue dot (with circles) with my own custom view (say some ping pin). Is it possible to do this?
If we do, does this pin move to new location when there is change in user's location? Or do we need to handle it programmatically?
I observed that if we use  default blue dot for user's current location, then its gets updated in the map when there is change in user location.
I just want to know if this can be done with our own custom view.

A: Yes, you can have a custom view for the user's location.
Unfortunately, it's harder to implement than it should be because even though the documentation for the viewForAnnotation delegate method claims that you can just supply your own view if the annotation class is MKUserLocation, the custom view does not then continue to move with the user's location.  In fact, when a custom view is returned for MKUserLocation, the map view stops updating the user location entirely (the map view's didUpdateUserLocation delegate method no longer fires).  I believe this is a bug.
A workaround is to use CLLocationManager and a custom annotation...

Make sure showsUserLocation is NO or unchecked on the map view.
Declare properties for a CLLocationManager and a custom annotation using a custom class that implements the MKAnnotation protocol (or you could just use the generic MKPointAnnotation class).
In viewDidLoad or some other appropriate place, create the CLLocationManager, set its delegate and call startUpdatingLocation.
In the location manager's didUpdateToLocation delegate method (not the map view's didUpdateUserLocation delegate method), create or update your custom annotation:
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    if (myUserLocAnnot == nil)
    {
        self.myUserLocAnnot = [[[MyUserLocClass alloc] init] autorelease];
          //remove the autorelease if using ARC
        myUserLocAnnot.title = @"You are here";
        myUserLocAnnot.coordinate = newLocation.coordinate;
        [mapView addAnnotation:myUserLocAnnot];
    }
    else
    {
        myUserLocAnnot.coordinate = newLocation.coordinate;
    }
}

Finally, in the map view's viewForAnnotation delegate method, you would return a custom annotation view if the annotation is your custom user location annotation.

A: Here is the answer in 2021.
Swift 5, XCode 12.
if annotation.isKind(of: MKUserLocation.self) {
            let userIdentifier = "user_location"

            if let existingView = mapView
              .dequeueReusableAnnotationView(withIdentifier: userIdentifier) {
              return existingView
            } else {
              let view = MKAnnotationView(annotation: annotation, reuseIdentifier: userIdentifier)
              view.image = #imageLiteral(resourceName: "dark_haulerIcon")
              return view
            }

        }

And you don't need to write logic for moving the annotation. Come on, It will automatically get done. Just use the above logic.


text:
Q: Only one page of product got with rest admin api I have so many pages of products on my development store.But when I try to use products.json to get all of my products, it only take 50 listings(one page).Could anybody solve my doubt?
<?php
 $url = 'https://myshopifystore/admin/api/2019-07/products.json';
 $result = file_get_contents($url);
 $data = json_decode($result, true);
 dd($data);

my result like this picture:

A: The limit property on the request has a default of 50 up to 250. In case you want more use a loop to search though every page until the end.
GET /admin/api/2019-07/products.json?limit=250?page=1

Use
GET /admin/api/2019-07/products/count.json

to get the total product you want to search.
More info about paginated page here
EDIT 1 : The paginated ?page= is now deprecated. It will be remove in version 2020-07. You should use  cursor-based pagination.

A: Below function can help to fetch resources with cursor based pagination in new shopify API
public function request($method,$url,$param = []){
    $client = new \GuzzleHttp\Client();
    $url = 'https://'.$this->username.':'.$this->password.'@'.$this->domain.'/admin/api/2019-10/'.$url;
    $parameters = [
        'headers' => [
            'Content-Type' => 'application/json',
            'Accept' => 'application/json'
        ]
    ];
    if(!empty($param)){ $parameters['json'] = $param;}
    $response = $client->request($method, $url,$parameters);
    $responseHeaders = $response->getHeaders();
    $tokenType = 'next';
    if(array_key_exists('Link',$responseHeaders)){
        $link = $responseHeaders['Link'][0];
        $tokenType  = strpos($link,'rel="next') !== false ? "next" : "previous";
        $tobeReplace = ["<",">",'rel="next"',";",'rel="previous"'];
        $tobeReplaceWith = ["","","",""];
        parse_str(parse_url(str_replace($tobeReplace,$tobeReplaceWith,$link),PHP_URL_QUERY),$op);
        $pageToken = trim($op['page_info']);
    }
    $rateLimit = explode('/', $responseHeaders["X-Shopify-Shop-Api-Call-Limit"][0]);
    $usedLimitPercentage = (100*$rateLimit[0])/$rateLimit[1];
    if($usedLimitPercentage > 95){sleep(5);}
    $responseBody = json_decode($response->getBody(),true);
    $r['resource'] =  (is_array($responseBody) && count($responseBody) > 0) ? array_shift($responseBody) : $responseBody;
    $r[$tokenType]['page_token'] = isset($pageToken) ? $pageToken : null;
    return $r;
}

using above function in controller
$ids = [];
$nextPageToken = null;
  do{
    $response = $shop->request('get','products.json?limit=250&page_info='.$nextPageToken.'&rel=next');
     foreach($response['resource'] as $product){
        array_push($ids, $product['id']);
     }
            $nextPageToken = $response['next']['page_token'] ?? null;
    }while($nextPageToken != null);


text:
Q: Cannot find module when calling fork using ts-jest and esm I'm trying to write some tests using jest on an typescript application built with ESM. At some point, the application starts a child process by calling the child_process.fork() method. This works fine as long as the application is started in a standalone way.
The fork call is done with the following code:
    const child = fork(
      "/workspace/my-project/src/child/index.js",
    );

However, when instantiated through the test code, the fork call fails:
node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module '/workspace/my-project/src/child/index.js'
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

This is how jest.config.ts looks like:
module.exports = {
  preset: "ts-jest/presets/default-esm",
  testEnvironment: "node",
  transform: {},
  testPathIgnorePatterns: ["node_modules", "dist"],
  extensionsToTreatAsEsm: [".ts"],
  globals: {
    "ts-jest": {
      useESM: true,
    },
  },
  moduleNameMapper: {
    "^(\\.{1,2}/.*)\\.js$": "$1",
  },
};

And this is how I'm starting the test:
node --experimental-vm-modules ./node_modules/.bin/jest test --verbose --detectOpenHandles --forceExit

When calling fork while using jest, it seems that the CJS loader is being used. I was however expecting the ESM loader to be used as I've configured ts-jest to use ESM.


text:
Q: Does solidity optimize gas usage based on total storage used before and after a contract method is called? Here is a simple contract to demonstrate what I am asking:
contract Example {
  uint256 intOne;
  uint256 intTwo;

  function test1()
    public
    payable
  {
    intOne = 300;
  }

  function test2()
    public
    payable
  {
    intOne = 0;
    intTwo = 300;
  }
}

After freshly deploying the contract, I first called test1() and it used 41527 gas.
This made sense to me since writing intOne from zero to non-zero will use 20,000 gas, plus base line gas usage (however that works).
I then called test2 which surprisingly used only 31453 gas.
Shouldn't changing intOne from non-zero to zero cost 5000, then another 20,000 to change intTwo from zero to non-zero?
Or is solidity able to calculate the difference in total storage used before and after the transaction to determine the amount of gas used?

A: Answer found in question https://ethereum.stackexchange.com/questions/32419/is-refunded-gas-for-freed-storage-given-to-the-contract-the-allocator-or-t
I was not aware of gas being refunded for zeroing out a word.


text:
Q: Flow query isn't getting a record that a SOQL query has no problem getting I have multiple queries in the flow that are set up the exact same. Im not getting an error, the flow runs through fine and does what it's supposed to. It's just not getting the records needed, and therefore leaving items out that need to be iterated over.
SOQL Query getting the correct list of Ids


text:
Q: How to resolve TokenMismatchException in Laravel 5 App I have developed a laravel 5 app and everything works fine except that I occationally get TokenMismatchException in VerifyCsrfToken.php line 53. I can't seem to figure out the cause. This happens mostly during login. I used the laravel built-in trait to implement authentication. Below is my sample logout method.
public function getLogout()
    {
        Auth::logout();
        Session::forget('cart_id');
        Session::forget('is_supervisor');
        Session::forget('is_manager');
        return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
    }

Each time the exception occurs, I have to reload the page and login again before this works. Below is a sample of my login form:
{!! Form::open(array('class' => 'form-horizontal', 'role' => 'form')) !!}

         {!! Form::label('username', trans('home.username'), array('class' => 'col-sm-3 control-label')) !!}

                {!! Form::text('username', null, array('required' => 'required', 'class' => 'form-control input-sm')) !!}

{!! Form::close() !!}

When I check the page source, the csrf token is always available. What could possibly be the problem. I am using laravel 5.1.* and SESSION_DRIVER=file in .env.
Edit
// Authentication routes...
Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', 'Auth\AuthController@getLogout');

A: CSRF Protection (Cross-Site-Request-Forgery) saves you from unwanted actions on web application.
The token is generated when rendering form and expired after some time.
If you have the form opened too long, you get TokenMismatchException.
Did you notice the problem shortly after reload page (form)?
Try to add
{{ csrf_field() }} to your form and check if it helps.


text:
Q: What year does Portal and its sequel, Portal 2, take place in? Can anyone confirm a date or a time period that Portal and subsequently Portal 2 take place in?
It's probable that Portal 1 takes place in around the modern day, but I couldn't find a date for when the timeline begins. Portal 2 is much more difficult to find the time period, as the only clue we are given is that we are

 9999999 somethings from when Chell was dragged back into the Aperture facility at the end of the first game.

Any ideas about this?

A: According to the timeline on Half Life's Wikia, Portal takes place around 2010.  However, I could not find a reference to an exact date.
Going by the same sources, and this question, Portal 2 takes place hundreds of years after Portal.  Again, I could not find a reference to an exact date.
Note that there is no official source of an exact date.  Looking at other sources (including the talk pages on the Half Life Wikia timeline page) you can see a lot is based on fragmented, and often speculated, details.
Because Portal and Portal 2 are very much isolated environments from the outside world, there isn't a great deal of concern with trying to fix the timelines to real dates.  We know that Portal 2 provides a lot of backstory to events prior to Portal, and that Portal 2 occurs a long time after Portal.
I'm surprised that the systems in place during Portal 2 can actually see past the year 2038.

A: I think the year is 47,010 calculated by the plant growth in the facility. And by how decayed it is.

A: If you think of it this way, when a digital clock is unplugged and plugged back -- it will flash '12:00' indefinitely until its reset, A few dozen years is all it takes to wear down wood, and upholstery from under use and bad conditions. My answer is that, Aperture Science suffered a catastrophic power failure and reverted to a backup generator, which in turn borked the system clock, and woke up all of the... still alive test subjects. Since we know that Rattman is still alive, it seriously could not have been that long. Rattman has been around from Portal 1 to Portal 2. We see him in the ending credits, along with evidence of him living in all of his dens throughout the game. If it has truly been longer than 60 years, Rattman would have died, and all of his murals would have been more decrepit and grown over. Could be wrong, but I'm pretty sure humans don't live longer than 114 years Doug would be past his due point, and would be too old to move at all if so much time has elapsed (since we someone sprinting on the elevator ride up from GLaDOS' Chamber, and there only being two known living humans in Aperture Science that we know of.) I Estimate 30-40 years, enough time if we talk about plant growth along with possible radiation leakage (if there is a nuclear reactor hidden somewhere)and Chells' science experiment, that could explain the overgrowth. Machines also degrade quickly with out power, and maintenance. No power, no central intelligence, no nanobots (jerry and his crew) All personality constructs working at low voltage levels, The breaker room underneath GLaDOS's chamber looks almost untouched and not corroded (Also Switched off). Can't have been too long, or you wouldn't be able to flip any of the breakers to turn anything on, or to divert power. (better question-- WHY WERE ALL THE BREAKERS SWITCHED OFF?!)

A: I say between 25-38 years like since they are running on emergency power from what I search back up generators last 20-40 years depending on how well they are maintained (if read correctly) and besides the narrator voice was very old due to the glitches on him saying 9 repeatedly


text:
Q: Connect New Server to Static IP and To DNS Server I have a strange setup. I have drawn a pretty crude diagram so it may be easier to explain.

Usually, all the new servers we add just go into the HPC cluster and we assign an IP address through our main DNS server.
MyMainServer is the host to all other computers. For instance you have to ssh into that server, before you can ssh into anything on the HPC cluster. That is pretty simple.
I now added a new server with it's own static IP using the interface em1. It works great if I don't connect p5P1. However, I still want to mount the storage array and be able to get onto nodes on the HPC server so I thought I would also connect that computer to MyMainServer through the p5p1 interface (those are 10 GB/s cards). However, ssh stops working when I connect p5p1. That is, it only works if I first ssh into MyMainServer, then ssh MyServer. It is still registering the correct IP address, but for some reason it wants to go through MyMainServer. Is there anyway to be able to still connect to the Storage Arrays through the 10 GB/s p5p1 interface and be able to have my primary IP be through em1?
MyServer is using Centos7, MyMainServer is using Ubuntu 14.04 Server. Both are DELL R720.
-J

A: You need to check route table on your new server and make sure that your default route goes through em interface.