text:
Q: Regex expression in plain english I'm working on a new Java project and therefore im reading the already existing code. On a very important part of the code if found the following regex expression and i can't really tell what they are doing. Anybody can explain in plain english what they do??
1)
 [^,]*|.+(,).+

2)
(\()?\d+(?(1)\))

A: 1)
[^,]* means any number of characters that are not a comma
.+(,).+ means 1 or more characters followed by a comma followed by 1 or more characters
|  means either the first one or the second one

2)
(\()? means zero or one '('  note* backslash is to escape '('
\d+ means 1 or more digits
(?(1)\)) means if back-reference \1 matched, then ')' note* no else is given

Also note that parenthesis are used to capture certain parts of the regular expression, except, of course, if they are escaped with a backslash

A: Next time you need a regex explained, you can use the following explain.pl service from Rick Measham:
Regex: [^,]*|.+(,).+

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  [^,]*                    any character except: ',' (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
 |                        OR
--------------------------------------------------------------------------------
  .+                       any character except \n (1 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    ,                        ','
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  .+                       any character except \n (1 or more times
                           (matching the most amount possible))

Regex: (\()?\d+(?(1)\))

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  (                        group and capture to \1 (optional
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    \(                       '('
--------------------------------------------------------------------------------
  )?                       end of \1 (NOTE: because you're using a
                           quantifier on this capture, only the LAST
                           repetition of the captured pattern will be
                           stored in \1)
--------------------------------------------------------------------------------
  \d+                      digits (0-9) (1 or more times (matching
                           the most amount possible))
--------------------------------------------------------------------------------
  (?(1)                    if back-reference \1 matched, then:
--------------------------------------------------------------------------------
    \)                       ')'
--------------------------------------------------------------------------------
   |                        else:
--------------------------------------------------------------------------------
                             succeed
--------------------------------------------------------------------------------
  )                        end of conditional on \1

Links

*

*http://rick.measham.id.au/paste/explain.pl

Note on conditionals
JAVA DOES NOT SUPPORT CONDITIONALS! An unconditionalized regex for the second pattern would be something like:
\d+|\(\d+\)

i.e. a non-zero repetition of digits, with or without surrounding parentheses.
Links

*

*regular-expressions.info/If-then-else conditionals

Conditionals are supported by the JGsoft engine, Perl, PCRE and the .NET framework.

The patterns in depth
Here's a test harness for the first pattern
    import java.util.regex.*;
    //...

    Pattern p = Pattern.compile("[^,]*|.+(,).+");
    String[] tests = {
        "",       // [] is a match with no commas
        "abc",    // [abc] is a match with no commas
        ",abc",   // [,abc] is not a match
        "abc,",   // [abc,] is not a match
        "ab,c",   // [ab,c] is a match with separating comma
        "ab,c,",  // [ab,c,] is a match with separating comma
        ",",      // [,] is not a match
        ",,",     // [,,] is not a match
        ",,,",    // [,,,] is a match with separating comma
    };
    for (String test : tests) {
        Matcher m = p.matcher(test);
        System.out.format("[%s] is %s %n", test,
            !m.matches() ? "not a match"
            : m.group(1) != null
               ? "a match with separating comma"
               : "a match with no commas"
        );
    }

Conclusion

*

*To match, the string must fall into one of these two cases:

*

*Contains no comma (potentially an empty string)

*Contains a comma that separates two non-empty strings

*On a match, \1 can be used to distinguish between the two cases

And here's a similar test harness for the second pattern, rewritten without using conditionals (which isn't supported by Java):
    Pattern p = Pattern.compile("\\d+|(\\()\\d+\\)");
    String[] tests = {
        "",       // [] is not a match
        "0",      // [0] is a match without parenthesis
        "(0)",    // [(0)] is a match with surrounding parenthesis
        "007",    // [007] is a match without parenthesis
        "(007)",  // [(007)] is a match with surrounding parenthesis
        "(007",   // [(007] is not a match
        "007)",   // [007)] is not a match
        "-1",     // [-1] is not a match
    };
    for (String test : tests) {
        Matcher m = p.matcher(test);
        System.out.format("[%s] is %s %n", test,
            !m.matches() ? "not a match"
            : m.group(1) != null
               ? "a match with surrounding parenthesis"
               : "a match without parenthesis"
        );
    }

As previously said, this matches a non-zero number of digits, possibly surrounded by parenthesis (and \1 distinguishes between the two).

A: 1) Anything that doesn't starts with a comma, or anything that contains a comma in between.
2) Any number that ends with a 1, and is between parenthesis, possible closed before and opened again after the number.


text:
Q: Firebase Analytics user_engagement events not captured I have integrated firebase analytics in my android application. Screen views are captured correctly. But user_engagement events are not captured which is supposed to be captured automatically as user stay on the screen for every 10 second by default.

A: The user_engagement event will automatically be triggered when the app is in the foreground state for a period of time. To verify if your implementation is correct, please enable the verbose logging for your app and use the DebugView console. Switching the app from foreground state to background state to foreground state should trigger the event. If the issue persists, then reach out to Firebase support.

redpajama_set_name: RedPajamaStackExchange


text:
Q: OpenLayers - Essential polygon data to save in a database I have a project where I need to save polygons to a database. I found that you can get the coordinates array from a feature using: feature.getGeometry().getCoordinates(). This returns an array of all the coordinate points. Is this the bare minimum I have to save to a database in order to redraw this feature from scratch again later?
I don't need a PostGIS database to save all of the other feature data. The other information is not needed for my application. All I need is too redraw the exact same feature that was saved into the database.
I also only use EPSG:3857. But I would also save this with a feature just to be sure.

A: You can easily dump Openlayers Layer to GeoJSON saving not only geometry but all the attributes as well. GeoJSON can be store anywhere, as a file or in a database.
import GeoJSON from 'ol/format/GeoJSON.js'

const format = new GeoJSON({ featureProjection: 'EPSG:3857' });
const layers = map.getLayers(); // map is 'ol/Map' object
const source = layers.item(0).getSource(); // grab first layer
const features = source.getFeatures();
const json = format.writeFeatures(features);

// dump json to file or save in database


text:
Q: bind not working for required input field I've this AngularJS HTML using Bootstrap:

    <form name="myForm">

            <input type="text" name="input" class="form-control" ng-model="input" maxlength="{{inputMaxLength}}" ng-minlength="{{inputMaxLength}}" ng-maxlength="{{inputMaxLength}}" placeholder="Type input.." aria-describedby="basic-addon2" required />

            <button type="button" class="btn btn-default btn-primary" ng-disabled="myForm.$invalid">Submit</button>

    </form>

and this controller:
function MyController($scope) {
    $scope.input = "";
    $scope.inputMaxLength = 18;
}

The Bootstrap addon in the field, should always count the remaining characters. The Submit button should be disabled as long the form is not valid.
The button works as aspected, but the "count down" in the add on is always 18.
Why?
See this JSFiddle.

A: You have a typo in ng-min-length, you should have:
ng-minlength="{{inputMinLength}}"

instead of
ng-minlength="{{inputMaxLength}}"

Oh and you should lose the curly braces on ng-bind, you can use one or the other but not both
So either:

or
{{inputMaxLength-input.length}}

(same applies for ng-minlength="{{inputMaxLength}}" ng-maxlength="{{inputMaxLength}}", no need for interpolation here, use ng-minlength="inputMaxLength" ng-maxlength="inputMaxLength" instead)
Note that while the input does not fulfill the requirements ie. larger than minLength and shorter than maxLength input will not have a value.
In this case you can get the value using myForm.input.$viewValue
I have updated you fiddle http://jsfiddle.net/29m5tdsc/9/

A: This can't work : your ng-validation (ng-minlength) will set $scope.input to null. So your counter wont work.
Besides, you wrote :
ng-bind="{{inputMaxLength - input.length}}"

When angular will work he will replace variables with values. You should wrote :
ng-bind="(inputMaxLength - input.length)"

JS Fiddle


text:
Q: What JS library would you use to create an interactive custom map I am building an interactive map view of a local area that shows multiple warehouses.
What I would like to know is, what are JS libraries or technologies I can use to achieve:

*

*Select a building

*View warehouse information such as (Size, Owner etc..)

*Update warehouse information (Rent etc..)

*Be able to draw more warehouses or select a sub area inside a warehouse to rent.

I will be using Angular for frontend and Java Cuba Platform backend.

A: I have used the Plotly JavaScript Open Source Graphing Library and it is very amazing with graphs and maps.
Start from here

A: *

*Google Maps: easy, well-documented support

*ArcGIS: advanced, layers of secondary data


text:
Q: How to stop onDraw() methods causing jerky scrolling of a ListView I have a ListView, and its child Views contain many calls to the Canvas on their onDraw() methods (such as drawPath() etc). I have found that when you scroll the ListView, the calls to onDraw (which are frequent) cause really jerky scrolling. I have found that you can eliminate this problem by replacing each View in the ListView by an ImageView where the image Bitmap is created from the original View using code like this.
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int bitmapWidth = view.getMeasuredWidth();
int bitmapHeight = view.getMeasuredHeight();
view.layout(0, 0, bitmapWidth, bitmapHeight);
Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);

This solves the problem of jerky scrolling. However the problem is that the method Bitmap.createBitmap() seems prone to throw an OutOfMemoryError. I have read advice on this site that you should never use this method. Does anyone know how I can best get around these problems?

A: A few things:
1) Post more source
2) read http://developer.android.com/training/improving-layouts/smooth-scrolling.html
3) consider using an ArrayAdapter http://developer.android.com/reference/android/widget/ArrayAdapter.html
You may want to track the number of times you call create bitmap, and how garbage collection is being handled there.  If you're not properly recycling your views, and you're creating lots of these bitmaps you going to very rapidly overwhelm your available memory.
For efficiency in this regard you can look at bitmap caching, ala:
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html

A: Months later I have found a solution. Before I started using Bitmaps I was unwittingly allocating a large number of objects in the onDraw() methods. I was not getting any warnings from Android Studio because the new keyword was being used in a method called from onDraw rather than onDraw itself. I discovered that if you accidentally write new Paint() in a loop rather than reusing a Paint object, it seriously harms the performance of scrolling.
I now only have a handful of Paint objects and a single Path object in my application (and no Bitmaps at all) and all these problems have disappeared. Hopefully somebody reading this will learn from my mistake!


text:
Q: how to call inner class method or variable from outer jsp? this is my index.jsp page:
<html>

<body>
<%!
public class myclass{
  private final int foo = 42;

  public int getFoo() {
    return foo;
  }
}
%>
</body>
</html>

how to call myclass method or variable in other jsp page ?
please help me .

A: You don't from any "other" JSP. Those declarations should be treated as local to the JSP. If you need a class to be used by multiple JSPs, write it as a separate Java source file, compile it, and include it in your webapp in WEB-INF/classes.

A: Did you try to use something like
<%@ include file="/myFile.jsp" % >
???


text:
Q: Unresolved external symbol (OpenGL and c++) OK, so I'm writing a little project, nothing complex, it just has several classes.
As the title implies, it uses OpenGL. At the moment, there's no "real" main function.
I have included glew.h wherever I've used gl* function calls, and added to the linker input glew32.lib.
And yet, it gives me this:

Error 2   error LNK2019: unresolved external symbol
  _imp_glBindTexture@8 referenced in function "public: void __thiscall Texture2D::Bind(unsigned int)"
  (?Bind@Texture2D@@QAEXI@Z)    Texture.obj Licenta

... and a host of other unresolved external symbol errors regarding OpenGL texture functions. But it doesn't complain about this:
glBindVertexArray(m_VAO);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Buffers[INDEX_BUFFER]);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Indices[0]) * Indices.size(), &Indices[0], GL_STATIC_DRAW);

or this:
glDrawElementsBaseVertex(GL_TRIANGLES,
                             m_Entries[i].NumIndices,
                             GL_UNSIGNED_INT,
                             (void*)(sizeof(unsigned int) * m_Entries[i].BaseIndex),
                             m_Entries[i].BaseVertex);

So, what's the deal? If one gl* function call failed linking, wouldn't ALL have to fail?

A: glBindTexture is a "core" OpenGL feature. This function resides in opengl32.dll, so just add the opengl32.lib to your linker input.
glDrawElementsBaseVertex and glBindVertexArray are extensions and GLEW defines these as function pointers (with dynamic late binding done in runtime), thus no "unresolved symbol" errors.

A: You'll need to include the library in the linkers input.
For VS:

*

*Put the library's file in the solution's root folder. (you might not have to do this in general for some libraries)

*At Visual Studios menu go to Project --> [SolutionName] properties.

*A dialog will open. navigate to Configuration Properties --> Linker --> Input

*At "Additional Dependencies" add the name of the library. (it'll probably be *.lib)


text:
Q: Adding a note to a cell in Google Drive spreadsheet using C# I'm currently working on a C# program to write a set of test results to a spreadsheet on Google Drive, and under the current format the cell to which I'm writing has one data value in the cell and the other 5 in a note (not a comment) on the cell.
EX: 1.8 visible in the cell, and when the cursor hovers over said cell, a small box appears to the side containing
Average: 1810 ms
Highest: 1921 ms
Lowest: 1708 ms
StdDev: 78 ms
Median: 1787 ms
My program currently can access and write to the cells in the Google spreadsheet, but I can't find a way to create a note for the cell and write to that. Any help is welcome.

A: If you take a look at this, setting a comment in the described way will actually add a note to the cell. This might be a known issue for them but I guess works in your favor. Hope this helps. :)


text:
Q: leinigen repl with profile This question is a follow up to How does one pre-load a clojure file in the leiningen repl?.
My ~/.lein/profiles.clj looks as follows:
{
  :user {:source-paths ["C:/Users/username/.lein/src"] }
}

My ~/.lein/src/user.clj might look as follows:
(ns user)

(println "user file loaded")

When I run lein repl within a folder containing a project.clj, then the user.clj file is executed, but when I run lein repl from another folder it doesn't load my user profile. Is there a workaround for this or is this behavior by design? In fact, I know that Leinigen is indeed loading my profile.clj (even when there is no project.clj) because there are also other things inside (taken from the excellent pimp my repl article). Leinigen is just having problems with my additional source-paths setting.
One other question related to this is the fact that I need to specify the full path of the folder for my user.clj file : "C:/Users/username/.lein/src". When I change that to "~/.lein/src" leiningen fails to load my file.

A: It sounds like you just want some code loaded for your lein repl sessions. This is done with the :init key of the :repl-options in your profiles.clj. You can load-file other files in init if you want to organize in that fashion.
{:user
  {:repl-options
    {:init (load-file "path-to-file/user.clj")}
     ...}}

Note: If you are using Windows-style path delimiters /, you'll need to escape them //.


text:
Q: PostgreSQL Inner Join Where Get IDs of 3 Products I have these 5 tables which is sale_order directly connected to sale_order_line that has the products of the order of course which is connected to product_product that is connected to product_template where a table called mrp_bom can connect to product template and a table connected to it which is bom_line. I am trying to Output the products that contain the word 836g
Here is what I have so far:
Select      so.name,
    pt.name,
    sol.name
From    sale_order so

Inner   Join sale_order_line sol
On  so.id = sol.order_id
Inner   Join product_template pt
On  sol.product_id = pt.id
Inner   Join mrp_bom bom
On  pt.id = bom.product_tmpl_id
Inner   Join mrp_bom_line boml
On  bom.id = boml.bom_id

Where   boml.product_id = (Select id From product_template Where name Like '%836g%'

Order   By so.name

This code outputs an error because I have 3 items with 836g. I tried changing the = in the condition into IN so it will grab all the ids it will return. But still it's giving me an error. This is the best I have so far, I have tried so many times, but I can't figure it out.

A: I have the feeling that something along these lines is what you actually want:
SELECT so.name,
       pt.name,
       sol.name
FROM sale_order so
INNER JOIN sale_order_line sol
    ON so.id = sol.order_id
INNER JOIN product_template pt
    ON sol.product_id = pt.id
INNER JOIN mrp_bom bom
    ON pt.id = bom.product_tmpl_id
INNER JOIN mrp_bom_line boml
    ON bom.id = boml.bom_id
WHERE pt.name LIKE '%836g%'     -- just add a WHERE condition directly in your query
ORDER BY so.name

A: OMG! I just had the answer. I don't think this will help anyone but i'll post the answer i have
SELECT so.name,
   pt.name PT,
   sol.name SOL,
   (Select pp1.name_template From product_product pp1 Where boml.product_id = pp1.id) BOML,
   boml.product_id

FROM sale_order so
INNER JOIN sale_order_line sol
    ON so.id = sol.order_id
INNER JOIN product_template pt
    ON sol.product_id = pt.id
INNER JOIN mrp_bom bom
    ON pt.id = bom.product_tmpl_id
INNER JOIN mrp_bom_line boml
    ON bom.id = boml.bom_id
WHERE (Select pp1.name_template From product_product pp1 Where boml.product_id = pp1.id) LIKE '%836g%'
ORDER BY so.name
Thank you all for the effort of helping me! Great community we got here! :D


text:
Q: Dynamic radio button generated using jquery is not working with unique name I have created a set of radio buttons. On a button click i have created, the set of controls. But radio button selection is not working seperately for each individual dynamically created set. By using unique name ony we can save all dynamic row input in a single column by considering as single value.
HTML

<button id="sitebutton" class="button big float-left blue-gradient margin-top-5x">Click Me</button>

<input type="radio" name="site[]" />first
<input type="radio" name="site[]" />second

<input type="text" name="sign[]" />

Jquery
$(document).ready(function() {
    var MaxInputs = 100; //Maximum input boxes allowed

    var FieldCount = 0;

    var InputsWrapper = $("#InputsWrapper"); //Input box wrapper ID

    var x = InputsWrapper.length; //Initial field count

    var sitefield = $("#sitebutton");

    $(InputsWrapper).sortable();

    $(sitefield).click(function()
                {

    if (x <= MaxInputs)
                    {
                        FieldCount++;

                        $(InputsWrapper).append( '
'+
                '<input type="radio" "id="one_' + FieldCount + '" name="site[]" />first
<input type="radio" "id="two_' + FieldCount + '" name="site[]" />second
	'+
                '<input type="text" "id="sign_' + FieldCount + '" name="sign[]" />	'+
            '
');
                        x++;
                        }
                        return false;
                });

});

PHP
<?php
    if(!empty($_POST["save"])) {
        $conn = mysql_connect("localhost","root","");
        mysql_select_db("sample",$conn);
        $itemCount = count($_POST["site"]);
        $itemValues=0;
        $query = "INSERT INTO mytable (site,sign) VALUES ";
        $queryValue = "";
        for($i=0;$i<$itemCount;$i++) {
            if(!empty($_POST["site"][$i]) || !empty($_POST["sign"][$i])) {
                $itemValues++;
                if($queryValue!="") {
                    $queryValue .= ",";
                }
                $queryValue .= "('" . $_POST["site"][$i] . "', '" . $_POST["sign"][$i] . "')";
            }
        }
        $sql = $query.$queryValue;
        if($itemValues!=0) {
            $result = mysql_query($sql);
            if(!empty($result)) $message = "Added Successfully.";
        }
    }
?>

A: I've worked with your code. I think You have to append the set of controls with table body.
InputsWrapper.find("tbody").append( '
<input type="radio" id="one_' + FieldCount + '" name="site[]" />first
<input type="radio" id="two_' + FieldCount + '" name="site[]" />second
	<input type="text" id="sign_' + FieldCount + '" name="sign[]" />
');

Fiddle Kindly Check the URL:

A: check link:https://jsfiddle.net/rymgxfvh/
p
lease put following code on Your js file:
    $(document).ready(function() {
    var FieldCount = 0;
        $('#sitebutton').click(function(){
            $(InputsWrapper).append( '
'+
                    '<input type="radio" "id="one_' + FieldCount + '" name="site' + FieldCount + '[]" />first
<input type="radio" "id="two_' + FieldCount + '" name="site' + FieldCount + '[]" />second
	'+
                    '<input type="text" "id="sign_' + FieldCount + '" name="sign' + FieldCount + '[]" />	'+
                '
');
            FieldCount++;
        })

    });


text:
Q: How to Animate Twitter Bootstrap 3 progress bar in Internet Explorer 9, 10: How can I get Twitter Bootstrap 3 progress bar to animate and display progress in Internet Explorer 9, 10:
When displayed in Mozilla or Chrome I can see the progress indicator moving and stripped animation but not in IE
Here is the div for the progress bar:

I am using the default jQuery file upload UI to show progress:

A: Stripped animation in progress bar is not an available feature on IE
From the Docs:
Animated
Add .active to .progress-striped to animate the stripes right to left. Not available in all versions of IE.
UPDATE
Bootstrap 3.0.3 - Not available in IE9 and below.

A: Use jQuery animate method if browser IE lte 9.
Example:
jQuery('#myprogress').animate({width:'1%'});

Similarly increase width percentage to show increment.
And for animated strip add below selector for IE specific css file.
Create a new CSS file ie.css if not exists or anything suitable.
Add this selector:
.progress-striped .progress-bar {
  background-image: url("an-animated-stripped-image.gif");
  background-repeat: repeat-x;
}

A: Here is the link to Github repository by Minddust
https://github.com/minddust/bootstrap-progressbar
A bootstrap jquery plugin which extends the basic twitter-bootstrap progressbar. It provides the ability to animate the progressbar by adding Javascript in combination with the preexisting css transitions. Additionally you can display the current progress information in the bar or get the value via callback.
You can use it with any Event as per your Convenience.


text:
Q: Maven release plugin ignores releaseVersion attribute I'm trying to create a svn branch from the trunk which has the version of TRUNK-SNAPSHOT in its pom and children's pom files with this command:
mvn --batch-mode release:branch -DbranchName=15.1 -DupdateBranchVersions=true -DupdateWorkingCopyVersions=false -DreleaseVersion=15.1
However I'm getting this error:
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Error parsing version, cannot determine next version: Unable to parse the version string: "TRUNK-SNAPSHOT"

While it's obvious that it was not able to calculate the next version of TRUNK-SNAPSHOT, why would the plugin ignore the releaseVersion argument that I wanted it to use for the new branch instead of trying to calculate the next version from the trunk's version identifier?
Although running in interactive mode allows me to provide the version for the new branch, I'll need it work in the batch mode. Is there any other way I can specify the new branch version in the batch mode regardless of what the branching source (trunk) version is?
Update 1: The plugin version I use is 2.0-beta-8

A: This was fixed in 2.4 as part of https://issues.apache.org/jira/browse/MRELEASE-511


text:
Q: Authentication error nodemailer when using Mandrill as SMTP provider I am trying to send email by using nodemailer in my nodejs application. I tried to send with gmail and everything was ok but when I use Mandrill as my SMTP provider I got an Authentication error.
here is my code:
var smtpTransport = nodemailer.createTransport("SMTP",{
    service: "Mandrill",
    auth: {
        user: "username@mydomain.com",
        pass: "*****"
    }
});

module.exports.sendEmail = function(to, subject, body, callback){
    smtpTransport.sendMail({
        from: "username@mydomain.com",
        to: to,
        subject: subject,
        html: body
    }, function(error, response){
        if(error){
            console.log(error); callback(error, response);
        }else{
            callback(null, response);
        }
    });
};

};

and thats the error I got
{ [AuthError: Invalid login - 435 4.7.8 Error: authentication failed:]
    name: 'AuthError',
        data: '435 4.7.8 Error: authentication failed:',
    stage: 'auth' }

A: I encountered a similar problem. In my case the authentication error was because mandrill does not accept your mandrill account password as the smtp authentication password, rather an api key which you can generate on your dashboard. The username is the same as you account username. The misconception arises probably because of the examples on mandrill's home-page, but it is explicitly mentioned under the SMTP & API credentials page (once you login) that smtp password is an api key.
Hopefully this helps.


text:
Q: Capturing Timestamp whenever List Item Set to Value I'm attempting to automate a field that tracks In Progress Change Request tickets, at the moment it relies on manual entry of the In-Progress start date to calculate the age of the field in days.
What I'm trying to set up is an automated workflow using SharePoint Designer that would grab the timestamp whenever a ticket is changed in status from New to In-Progress.
There is no automated action for this in SharePoint as far as I can tell, so any suggestions are welcomed.

A: Using a designer workflow is quite easy and hassle free. The only thing you really need to take care of is to create a "shadow" field of the old value before the user change.
Consider a list with a choice field "Status" you would need to make another field (Perfeably a single line of text) "Status_system". Now setup your workflow to run on every change.
Add an if statement like this If Status != Status_system inside this you add the part where you update the field to current date and time. Now also update the Status_system: Status_system = Status
And you're basically done. Now every time the workflow run it will check if the status has changed since last time a workflow was completed (Which in turn is last time the item was changed). If that's the case it will update the data field and set the system-field to the new value.

A:
After searching around for ways to initiate a null value, you were on the right path, but the value kept getting rejected as a null. This is the method that I have tested and found to work excellently. The Progress Start date will not be set if it finds that a date already exists in that field, and will populate the current date whenever the Status of an Item is moved from NEW to In Progress.
Using SharePoint Designer 2013, 2010 Workflow


text:
Q: IndexError: List index out of range, only when performing operations 2 list items - Python I have the following code:
infile = open("sitin.txt", "r")
r = int(infile.readline().split()[0])
s = int(infile.readline().split()[1])
totalseats = r * s
print(totalseats)

my input file, "sitin.txt" is a text file with nothing but 10 10. Printing either r or s by itself returns the correct value, and printing either r or s multiplied by 10 returns the correct value, but this code, attempting to multiply r and s returns "IndexError: list index out of range". What is happening here?

A: you read your input file too many times; you will get r for the first line; s for the second line (and so on)... fix:
infile = open("sitin.txt", "r")
split = infile.readline().split()  # read once only!
r = int(split[0])
s = int(split[1])
totalseats = r * s
print(totalseats)

you may need to check that split has the correct form for your input.

A: Every time your readline() the "cursor" moves to the next line. Thus you should probably only read that line once or shift back offset. Try doing this instead:
infile = open("sitin.txt", "r")
t = infile.readline().split()
r = int(t[0])
s = int(t[1])
totalseats = r * s
print(totalseats)

A: You appear to be doing readline() twice, which is going to read two lines. Do it once, grab the results, split that. Also, would help to put your file access inside a with, so that the file is automatically closed for you after reading, not left open as a dangling resource. E.g.:
with open("sitin.txt", "r") as infile:
    line = infile.readline()
r, s = map(int, line.split())
totalseats = r * s
print(totalseats)


text:
Q: Is there a way to write a message in kafka with some timeout per message I am new to kafka and I know that we can give e.g. delete.retention.ms on topic creation, and all messages that match to this criterion will be deleted.
I would like to know whether there's a way to give this criterion per message? Or maybe there's any hack to achieve the goal?

A: Given that Kafka messages are an ordered log, it is not possible to have messages removed from the middle of the log. Therefore, I do not believe that what you are asking for is possible.


text:
Q: Unable to write data (addRow) into Excel file in Nodejs I'm trying to write data into an Excel file using ExcelJS library. I was successfully able to create worksheet and add column data.
However, while trying to implement addRow() or addRows() method, the data is not added into the Excel worksheet.
Here is the code I tried:
 const ExcelJS = require('exceljs');
 var workbook = new ExcelJS.Workbook();
 var worksheet = workbook.addWorksheet('Payment Data');
 worksheet.columns = reportHeaders; //reportHeaders is an array of header objects

I'm able to see the columns created successfully in the excel sheet. The trouble starts from below, where I'm trying to add data (into rows):
1st method :
  worksheet.addRows(excelData);//excelData is an array of data objects

2nd method:
  for(var rowItem in excelData){
  worksheet.addRow(excelData[rowItem]);}

However, it seems either of these methods aren't working for me.
Finally, the file is saved:
  workbook.xlsx.writeFile('PaymentData.xlsx')

Is there anything I'm missing? Any help will be appreciated.

A: So the issue with your code was, you were trying to add the data to the columns without specifying the key property in the columns array and hence it was unable to add the data.
I modified the worksheet.columns array to look something like the following:
worksheet.columns = [
    { header: "A", key: "a" },
    { header: "B", key: "b" },
];

This will solve your problem

A: I managed to convert the object to an array and passed it to the addRow method.
This worked for me.
I'm still not sure why I'm not able to pass an array of objects to addRow method.


text:
Q: Linked List Wrong Output Java Hey ya'll I am having a little trouble with my singly linked list. I decided to create a simple one because we do not get enough practice during my data structures class and cannot seem to find why I am not getting the right output.
The code is:
package linked_list;

public class LinkedList {

    private Node head;
    private Node tail;   // After figuring out head, come back to this FIXME
    private int listSize;

    public LinkedList() {
        head = new Node(null);
        tail = new Node(null);
    }

    public void addLast(String s) {
        Node newNode = new Node(s);
        if (head == null) {
            addFirst(s);
        } else {
            while (head.next != null) {
                head = head.next;
            }
            head.next = newNode;
            tail = newNode;
        }
        listSize++;
    }

    public void addFirst(String s) {
        Node newNode = new Node(s);
        if (head == null) {
            head = newNode;
            tail = newNode;
        }
        else {
            newNode.next = head;
            head = newNode;
        }
        listSize++;
    }

    public Object getFirst() {
        return head.data;
    }

    public Object getLast() {
        return tail.data;
    }

    public void clear() {
        head = null;
        tail = null;
        listSize = 0;
    }

    public Object peek() {
        try {
            if (head == null) {
                throw new Exception ("The value is null");
            }
            else {
                return head;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    public int size() {
        return listSize;
    }

    // This class has the ability to create the nodes that are used
    // in the Linked List.

    private class Node {
        Node next;
        Object data;

        public Node(String value) {
            next = null;
            data = value;
        }

        public Node(Object value, Node nextValue) {
            next = nextValue;
            data = value;
        }

        public Object getData() {
            return data;
        }

        public void setData(Object dataValue) {
            data = dataValue;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node nextValue) {
            next = nextValue;
        }
    }
}

Now here is my driver that I created to run a simple little operation:
package linked_list;

public class LinkedListDriver {

    public static void main(String[] args) {

        LinkedList list1 = new LinkedList();

        list1.clear();

        list1.addLast("This goes last");
        list1.addFirst("This goes first");
        list1.addLast("Now this one goes last");

        System.out.println(list1.getFirst());
        System.out.println(list1.getLast());
    }

}

My output is this:
This goes last
Now this one goes last

I guess my question is why am I not getting the answer This goes first from my getFirst() method. It seems to be something wrong with the order or structure of that method but I cannot pinpoint it.

A: When you are in the else in the addLast, you are changing the reference to head. You should use another reference pointer to traverse the list when adding in the else.
Also, your list size should only be incremented in the else in addLast because you are incrementing twice otherwise (once in addFirst and again after the if-else in addLast).


text:
Q: How to distinguish between attribute and element nodes returned from a Saxon XPathSelector Given the XML:
<root name="value">
  <level1>
    <level2>Text</level2>
  </level1>
</root>

I want the XPath /root/@name to return value, and the XPath /root/level1 to return the XML serialisation of the <level1> node:
  <level1>
    <level2>Text</level2>
  </level1>

I'm using the a9api interface from Saxon 9.6 in Java.
I've found that I can call XdmValue.toString() to get the XML serialisation of the result of the evaluation of the XPath, which gets me the desired result for selecting an element, but returns name="value" when selecting an attribute. And I can call XdmItem.getStringValue() to get the string value, which gets me the right value for the attribute, but returns the textual content of the element.
Michael Kay has previously said "Saxon's s9api interface ... returns XdmValue objects whose type you can interrogate". I can see that I could perform an instanceof check to determine whether it is an XdmAtomicValue, XdmExternalObject, XdmFunctionItem, or XdmNode, but elements and attributes are both instances of XdmNode. How do I distinguish between the two?
(I can't modify the XPaths, as they're provided by the user.)

A: I discovered the answer just as I finished writing the question, so I'll share it for others.
After casting the XdmItem to an XdmNode, you can call XdmNode.getNodeKind(), which returns a value from the XdmNodeKind enumeration specifying which type of node it is:
        XdmValue matchList = xPathSelector.evaluate();
        XdmItem firstItem = matchList.itemAt(0);
        if (firstItem instanceof XdmNode) {
           XdmNode xdmNode = (XdmNode) firstItem;
           XdmNodeKind nodeKind = xdmNode.getNodeKind();
           if (nodeKind == XdmNodeKind.ELEMENT) {
              return xdmNode.toString();
           }
        }
        return firstItem.getStringValue();


text:
Q: Get the index of an array item based on the value I have a string array defined in arrays.xml that references two strings in strings.xml:
<string-array name="my_options">
  <item>@string/my_string_one</item>
  <item>@string/my_string_two</item>
</string-array>

<string name="my_string_one">Value 1</string>
<string name="my_string_two">Value 2</string>

I need to get the position of an item in the array, based on the value of the string. I.e string "Value 2" has an index of 1. I can obviously just hard code the positional values (0, 1, etc.), but it will break if the order of the strings is changed. I want the code to be positionally independent. The following works:
int value = Arrays.asList((getResources().getStringArray(R.array.my_options))).indexOf(getString(R.string.my_string_one));

Is there a more compact, simpler way to do this?

A: The code you show in your question is basically what you need to do.
However, you could refactor it somewhat to make it more readable:
Refactor Arrays.asList((getResources().getStringArray(R.array.my_options))) into a List (i don't know how your app's code looks like, but you may be able to store this List as a instance field or even as a static (class) field).
static List<String> myOptions;

....
    if (myOptions == null) {
        myOptions = Arrays.asList((getResources().getStringArray(R.array.my_options)));
    }

...

    int value = myOptions.indexOf(getString(R.string.my_string_one));

A: Maybe a HashSet might help you or something like that, where you put your name of your string as the key and the value as the value. Then you can select the value with the name of the key.


text:
Q: How to create a property binding in Qt/C++? In QML, it's easy write create a property binding, such as:
Rectangle {
    width: parent.width
}

Is it possible to do this in C++ too?

A: In Qt, some QObjects have certain properties that can be "bound" using signals and slots:
auto *someWidget = QPushButton(/* ... */);
auto *otherRelatedWidget = QLabel( /* ... */ );
// windowTitle is a property for both QWidgets
QObject::connect(someWidget, &QWidget::windowTitleChanged,
                 otherRelatedWidget, &QWidget::setWindowTitle);

Apart from this, you can still connect other signals and slots, even if they're not associated to properties.
I've got to point out that there is no syntax sugar for doing this. See the properties documentation for more info.

A: In Qt6 you can use QProperty to achieve c++ property bindings.
Check out this blog post:
https://www.qt.io/blog/property-bindings-in-qt-6
They're slightly different than QML binding since they execute lazily. QML binding execute eagerly on every signal. Under the hood QProperty uses thread local storage (TLS) to keep track of dependancies while executing value(). It's definitely an interesting piece of technology and adds a declarative programming paradigm to c++.


text:
Q: Python: Stop a while when a condition do if it's true? I need to make an algorithm in which the person types a login and password and he has three attempts, I did a "while x <= 3" (ox has a value of 0) and then an if inside the while with the login and password condition . But how do I stop while asking for login and password 3 times even hitting the login and password on the first or second attempt?

A: What about the break keyword. When you want to stop the loop just use the break

A: Try this:
attemps = 0
password = "test"

while attemps <= 0 :
    guess = input("what is your password?")
    if guess == password:
        print("You are now signed in")
        break
    else:
        attemps += 1
    if attemps >= 3:
        print("You have guessed too many times")
        break

A: Here is a solution that hopefully helps you learn how to use break inside a loop:
correct_login = "person's name"
correct_password = "correct password"
for attempt in range(3):
    login = input('Please enter your login name: ')
    password = input('Please enter your password: ')
    if login == correct_login and password == correct_password:
        print('you have entered the correct credentials')
        break

A: it can be something like:
# a dictionary of logins and passwords for example
logins = {'lothr': 'lothr2021', 'overflow_fan': 'overflower'}

def ask_to_proceed(login_dictionary):
    """
        function for asking user login and password, has tree attempts.
        :param login_dictionary: dictionary containing the registered logins and respective passwords
        """
    counter = 0  # we set the first count
    while True:
        counter += 1  # e sum up a count of attempt
        if counter == 4:
            print('Login failed')
            exit()
        print('*** Input your User and Password credentials ***')
        answer_login = input('Enter your User name: ')
        if answer_login in login_dictionary:
            answer_password = input('Enter your Password: ')
            if answer_password == login_dictionary[answer_login]:
                print(f'Wellcome {answer_login}')
                break
        if answer_login not in login_dictionary:
            print('User not in records')

ask_to_proceed(logins)

maybe you can fin a way to hide the inputs from screen, so it improoves.


text:
Q: Не переносятся зоны Master > slave Поднял slave сервер, использую rndc. Сервер находится за NAT.
При попытке перенести зону выдает следующую ошибку:
06-Jan-2017 13:00:59.593 general: info: zone domain.com/IN: Transfer started.
06-Jan-2017 13:00:59.594 xfer-in: info: transfer of 'domain.com/IN' from <master DNS IP>#53: connected using 10.0.2.4#42991
06-Jan-2017 13:00:59.896 xfer-in: error: transfer of 'domain.com/IN' from <master DNS IP>#53: failed while receiving responses: NXDOMAIN
06-Jan-2017 13:00:59.896 xfer-in: info: transfer of 'domain.com/IN' from <master DNS IP>#53: Transfer completed: 0 messages, 0 records, 0 bytes, 0.302 secs (0 bytes/sec)

При этом все порты открыты (как TCP, так и UDP, 953 и 53). Master сервер исправно работает.
lsof на slave
root@admindns:/var/log/bind# lsof -Pni :53
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
named   20620 bind   20u  IPv4 392123      0t0  TCP 127.0.0.1:53 (LISTEN)
named   20620 bind   21u  IPv4 392125      0t0  TCP 10.0.2.4:53 (LISTEN)
named   20620 bind  512u  IPv4 392122      0t0  UDP 127.0.0.1:53
named   20620 bind  513u  IPv4 392124      0t0  UDP 10.0.2.4:53
root@admindns:/var/log/bind# lsof -Pni :953
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
named   20620 bind   22u  IPv4 392128      0t0  TCP *:953 (LISTEN)
root@admindns:/var/log/bind#

lsof на master
[root@panel ~]# lsof -Pni :953
COMMAND   PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
named   29304 named   21u  IPv4 445846      0t0  TCP *:953 (LISTEN)
[root@panel ~]# lsof -Pni :53
COMMAND   PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
dnsmasq  1112 nobody    4u  IPv4  27041      0t0  UDP *:53
dnsmasq  1112 nobody    5u  IPv4  27042      0t0  TCP *:53 (LISTEN)
dnsmasq  1112 nobody    6u  IPv6  27043      0t0  UDP *:53
dnsmasq  1112 nobody    7u  IPv6  27044      0t0  TCP *:53 (LISTEN)
named   29304  named  512u  IPv6 445837      0t0  UDP *:53
named   29304  named  513u  IPv6 445837      0t0  UDP *:53
named   29304  named  514u  IPv4 445840      0t0  UDP 127.0.0.1:53
named   29304  named  515u  IPv4 445840      0t0  UDP 127.0.0.1:53
named   29304  named  516u  IPv4 445842      0t0  UDP 10.0.0.4:53
named   29304  named  517u  IPv4 445842      0t0  UDP 10.0.0.4:53
named   29304  named  518u  IPv4 445844      0t0  UDP 172.17.0.1:53
named   29304  named  519u  IPv4 445844      0t0  UDP 172.17.0.1:53
[root@panel ~]#

A: Проблема была в dnsmasq, надо было его просто выключить.


text:
Q: HTML Nav bar links not clickable This past week I've been learning HTML and CSS and decided to mess around with a navigation bar. I have it all set up but now the links up top are not clickable?
I've checked to make sure I didn't miss anything basic like a closing tag but couldn't find anything like that.

* {
  margin: 0;
  padding: 0;
}

html {
  background-color: #808080;
  background-image: url("https://hdqwalls.com/download/simple-gray-abstract-background-wi-1920x1080.jpg");
  background-repeat: no-repeat;
}

#landing__container {
  height: 100vh;
  width: 100%;
}

header {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 0, 0, 0.4);
}

header h1 {
  color: white;
  font-family: impact;
  font-weight: normal;
}

header ul {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 30px;
}

header ul li {
  list-style: none;
}

header a {
  font-family: helvetica;
  font-weight: bold;
  font-size: 18px;
  text-decoration: none;
  color: white;
  margin: 30px;
}

#landing__center {
  display: flex;
  flex-direction: column;
  text-align: center;
  justify-content: center;
  align-items: center;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  position: absolute;
}

#landing__center h2 {
  padding-bottom: 20px;
  color: white;
  font-family: Impact;
  font-weight: normal;
  font-size: 40px;
}

#landing__center p {
  padding-top: 20px;
  color: white;
  font-family: helvetica;
  font-weight: normal;
  font-size: 20px;
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Navigation Bar Practice</title>
    <link rel="stylesheet" type="text/css" href="style.css" />

Home

Documentation

About

Contact

Testing

          Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rem
          voluptatum asperiores illum maiores aliquid quo perferendis,
          blanditiis facere temporibus laudantium!

I know the code may not be perfect and/or clean but keep in mind I have been doing this for a week.

A: You had made this section #landing__center position:absolute and top:0 that is why it was coming on top of navbar. I have increased the top to 30. Thanks

* {
  margin: 0;
  padding: 0;
}

html {
  background-color: #808080;
  background-image: url("https://hdqwalls.com/download/simple-gray-abstract-background-wi-1920x1080.jpg");
  background-repeat: no-repeat;
}

#landing__container {
  height: 100vh;
  width: 100%;
}

header {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 0, 0, 0.4);
}

header h1 {
  color: white;
  font-family: impact;
  font-weight: normal;
}

header ul {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 30px;
}

header ul li {
  list-style: none;
}

header a {
  font-family: helvetica;
  font-weight: bold;
  font-size: 18px;
  text-decoration: none;
  color: white;
  margin: 30px;
}

#landing__center {
  display: flex;
  flex-direction: column;
  text-align: center;
  justify-content: center;
  align-items: center;
  top: 30; /*changed*/
  bottom: 0;
  left: 0;
  right: 0;
  position: absolute;
}

#landing__center h2 {
  padding-bottom: 20px;
  color: white;
  font-family: Impact;
  font-weight: normal;
  font-size: 40px;
}

#landing__center p {
  padding-top: 20px;
  color: white;
  font-family: helvetica;
  font-weight: normal;
  font-size: 20px;
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Navigation Bar Practice</title>
    <link rel="stylesheet" type="text/css" href="style.css" />

Home

Documentation

About

Contact

Testing

          Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rem
          voluptatum asperiores illum maiores aliquid quo perferendis,
          blanditiis facere temporibus laudantium!

A: You need to add z-index along with position: relative to your code
header{
  z-index: 1;
  position: relative;
}

A: The problem is caused by the #landing__center covering the navigation bar, because it selected #landing__container as the element to be relative with
One way is to create a wrapper that will act as the container of #landing__center, instead of
 #landing__container. So that it is relative to its own container rather than its parent, not interfering with its siblings

* {
  margin: 0;
  padding: 0;
}

html {
  background-color: #808080;
  background-image: url("https://hdqwalls.com/download/simple-gray-abstract-background-wi-1920x1080.jpg");
  background-repeat: no-repeat;
}

#landing__container {
  height: 100vh;
  width: 100%;
}

header {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 0, 0, 0.4);
}

header h1 {
  color: white;
  font-family: impact;
  font-weight: normal;
}

header ul {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 30px;
}

header ul li {
  list-style: none;
}

header a {
  font-family: helvetica;
  font-weight: bold;
  font-size: 18px;
  text-decoration: none;
  color: white;
  margin: 30px;
}

.wrapper {
  position: relative;
  height: 95%;
}

#landing__center {
  display: flex;
  flex-direction: column;
  text-align: center;
  justify-content: center;
  align-items: center;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  position: absolute;
}

#landing__center h2 {
  padding-bottom: 20px;
  color: white;
  font-family: Impact;
  font-weight: normal;
  font-size: 40px;
}

#landing__center p {
  padding-top: 20px;
  color: white;
  font-family: helvetica;
  font-weight: normal;
  font-size: 20px;
}

Home

Documentation

About

Contact

Testing

          Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rem voluptatum asperiores illum maiores aliquid quo perferendis, blanditiis facere temporibus laudantium!


text:
Q: ILIKE over two columns slow in joined tables I have two tables:
products:

*

*product_id int

*producer varchar

*status char(1)

product_names:

*

*name_id int

*product_id int fk

*name vharchar

*lang char(2)

products has around 500 000 entries. product_names around 1 000 000
        SELECT p.*, n.name, n.lang
        FROM products p
        INNER JOIN product_names n ON
            n.product_id = e.product_id

        WHERE
                p.status IN ('A', '1', '5', '9')

            AND (
                    n.name ILIKE 'nestle%'
                 OR p.producer ILIKE 'nestle%'
            )
        LIMIT 1

If I run ILIKE only on n.name OR only p.product, it takes around 15ms to find results.
If I run ILIKE on both columns in the same time, it takes around 1.2 seconds... 1000x longer!
I tried all possible indexes I know:
products:
"p_producer_index20" btree (producer)
"p_producer_index22" btree (producer text_pattern_ops)
"p_producer_index23" gist (producer gist_trgm_ops)
"p_producer_index24" gin (producer gin_trgm_ops)

product_names:
"p_names_name_index2" btree (name text_pattern_ops)
"p_names_name_trgm_index" gin (name gin_trgm_ops)

Am I missing something here or doing something totally wrong?

A: You could put an index on products.status to get some benefit of an index.
Since because of the OR it probably doesn't make full use of the indexes on those producer and name fields.
And try out:
    SELECT p.*, n.name, n.lang
    FROM products p
    LEFT JOIN product_names n
      ON (p.product_id = n.product_id AND n.name ILIKE 'nestle%')
    WHERE
        p.status IN ('A','1','5','9')
        AND (p.producer ILIKE 'nestle%' OR n.name IS NOT NULL)
    LIMIT 1

And you could also ANALYZE the tables to help the query planner.

A: Maybe try something like this:
SELECT *
FROM   (
        SELECT p.*, n.name, n.lang
        FROM products p
        JOIN product_names n ON n.product_id = e.product_id
        WHERE p.status IN ('A', '1', '5', '9') AND
              n.name ILIKE 'nestle%'
        UNION ALL
        SELECT p.*, n.name, n.lang
        FROM products p
        JOIN product_names n ON n.product_id = e.product_id
        WHERE p.status IN ('A', '1', '5', '9') AND
              p.producer ILIKE 'nestle%') t
LIMIT 1


text:
Q: Constraint Layout child goes offscreen Constraints of ConstraintLayout Behaves something different. Contraint bottom to bottom of parent behave like bottom to top of parent and End to end of the parent behave like End to Start of parent.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".ui.splash.SplashScreen">

    <androidx.cardview.widget.CardView
        android:layout_width="150dp"
        android:layout_height="150dp"
        app:cardElevation="10dp"
        app:cardCornerRadius="25dp"
        app:cardBackgroundColor="@color/hiranya_red"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent">

    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>

and if I set like this
app:layout_constraintBottom_toTopOf="parent"

Dependencies and Config Version:

    minSdkVersion = 21
    targetSdkVersion = 30
    compileSdkVersion = 30

    // App dependencies
    appCompatVersion = "1.2.0"
    constraintLayoutVersion = "2.0.0"
    coroutinesVersion = "1.3.9"
    dataStoreVersion = "1.0.0-alpha04"
    espressoVersion = "3.3.0"
    fragmentVersion = "1.3.0-beta01"
    gradleVersion = '4.1.1'
    hiltAndroidXVersion = "1.0.0-alpha02"
    hiltVersion = "2.28.3-alpha"
    junitVersion = "4.13.1"
    kotlinVersion = "1.4.20"
    ktxVersion = "1.3.2"
    lifecycleVersion = "2.2.0"
    materialVersion = "1.3.0-alpha04"
    navigationVersion = "2.3.1"
    retrofitVersion = "2.9.0"
    roomVersion = "2.2.5"
    testExtJunitVersion = "1.1.2"


text:
Q: T-SQL: Find Position of First a-zA-Z in a String In a Select statement, I need to strip leading and trailing commas from one column.
It has values like:
,,Value1,Value2,,,,

There are no spaces between the commas.
I have tried using CharIndex to find the first occurrence of [a-zA-Z] but I don't know how to make that work.
Here's an example of my Code:
Select CustID, SaleDate, TargetColumn, CharINDEX('a-z', TargetColumn) [Position]

Every row in the [Position] column returns a 0.
I was hoping to be able to locate the first and last instance of [a-zA-Z] and then remove everything before and after those positions, respectively.
I appreciate that this may have been asked before, but I was not able to find tsql code that I can use in a Select statement.
I'd appreciate any help/pointers.
Thanks!

A: If you ... need to strip leading and trailing commas from one column ... and you use SQL Server 2017+, TRIM() is an option:
SELECT TRIM(',' FROM TargetColumn) AS TargetColumn
FROM (VALUES (',,Value1,Value2,,,,')) t (TargetColumn)

But, if you want to make more complicated parsing (as mentioned in the comments ... the column in question can also have a string of commas between actual values ...), a JSON-based approach (with appropriate transformations and string splitting) is a possible solution (SQL Server 2016+ is needed). The idea is to split the text, remove the empty substrings and then aggegate the parts again:
SELECT TargetColumn = (
   SELECT STRING_AGG([value], ',') WITHIN GROUP (ORDER BY CONVERT(int, [key]))
   FROM OPENJSON(CONCAT('["', REPLACE(TargetColumn, ',', '","'), '"]'))
   WHERE [value] <> ''
)
FROM (VALUES
  (',,Value1,Value2,,,,'),
  ('Food Resources,,,,,,,,,Department'),
  ('No commas')
) t (TargetColumn)

Result:
TargetColumn
-------------------------
Value1,Value2
Food Resources,Department
No commas

A: For the first occurrence of A-Z you need 'PATINDEX' not 'CHARINDEX'.
PATINDEX('%[a-z]%' TargetColumn)

To find the last position you could go with
LEN(TargetColumn)-PATINDEX('%[^,]%', REVERSE(TargetColumn))


text:
Q: Agregar elementos dinámicamente Estoy intentando hacer un modulo para creación de encuestas dinámicamente, quiero tener un formulario donde vaya agregando las preguntas y las posibles respuestas de la misma.  El asunto es que no me funciona el agregar opciones (respuestas) de la segunda pregunta en adelante, no se qué estoy haciendo muy mal, porque al hacer click en el boton ni siquiera entra al llamado de la función.

$(document).ready(function() {

    var i = $("#i").val();
    //var n = i++;
    //agregado de otro codigo
    $('.add-answer').on('click', function(e) {
  var el = $('
');
  el.append($('<input>', {
   type: "text",
   name: "new_answers[]"
  }))
  el.append($('', {
   "class": "delete-new-answer btn-danger btn",
   "href": "#",
   "text": "Eliminar"

  }));
  $('.answers-list').append(el);
        e.preventDefault();
        console.log("iiiii "+i);
        $('.answers-list').append('
');
        $('.answers-list').append('
');
        //agregando los botones de opciones respuestas
        $('.answers-list').append('
');
        $('.answers-list').append('<input type=\"button\" value=\"Preview form_'+i+'\" class=\"add_ \" id=\"preview'+i+'\" />');
        $('.answers-list').append('<input type=\"button\" value=\"Add a field_'+i+'\" class=\"add_ \" id=\"add'+i+'\" />');
        $('.answers-list').append('
');
        var intId = $("#yourform"+i+" div").length + 1;
        //console.log(intId);
        var fieldWrapper = $("
");
        $("#yourform"+i).append(fieldWrapper);
        //hasta aquí
        //console.log("elemento "+$("#add"+i));

 })
    //hasta aquí
    console.log("salida "+i);
    $(".add").click(function() {
        alert("hola");
        //$(".add").click(function() {
            var intId = $("#yourform"+i+" div").length + 1;
            //console.log(intId);
            var fieldWrapper = $("
");
            var fName = $("<input type=\"text\" class=\"fieldname\" />");
            var fType = $("<select class=\"fieldtype\"><option value=\"checkbox\">Checked</option><option value=\"textbox\">Text</option><option value=\"textarea\">Parrafo</option></select>");
            var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
            removeButton.click(function() {
                $(this).parent().remove();
            });
            fieldWrapper.append(fName);
            fieldWrapper.append(fType);
            fieldWrapper.append(removeButton);
            $("#yourform"+i).append(fieldWrapper);
        });

    $("#add").click(function() {
    //$(".add").click(function() {
        var intId = $("#buildyourform div").length + 1;
        //console.log(intId);
        var fieldWrapper = $("
");
        var fName = $("<input type=\"text\" class=\"fieldname\" />");
        var fType = $("<select class=\"fieldtype\"><option value=\"checkbox\">Checked</option><option value=\"textbox\">Text</option><option value=\"textarea\">Parrafo</option></select>");
        var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
        removeButton.click(function() {
            $(this).parent().remove();
        });
        fieldWrapper.append(fName);
        fieldWrapper.append(fType);
        fieldWrapper.append(removeButton);
        $("#buildyourform").append(fieldWrapper);
    });
    $("#preview").click(function() {
        console.log("preview");
        $("#yourform").remove();
        //$("#yourform").children().remove();
        var fieldSet = $("<fieldset id=\"yourform\"><legend>Form</legend></fieldset>");
        console.log(fieldSet);
        $("#buildyourform div").each(function() {
            var id = "input" + $(this).attr("id").replace("field","");
            console.log("el id "+id);
            var label = $("" + $(this).find("input.fieldname").first().val() + "");
            var input;
            switch ($(this).find("select.fieldtype").first().val()) {
                case "checkbox":
                    input = $("<input type=\"checkbox\" id=\"" + id + "\" name=\"" + id + "\" />
");
                    break;
                case "textbox":
                    input = $("<input type=\"text\" id=\"" + id + "\" name=\"" + id + "\" />
");
                    break;
                case "textarea":
                    input = $("<textarea id=\"" + id + "\" name=\"" + id + "\" ></textarea>
");
                    break;
            }
            fieldSet.append(label);
            fieldSet.append(input);
        });
        //$("body").append(fieldSet);
        $("#your").append(fieldSet);

        console.log($("#i").val(i++));
    });
});

Encuesta

Administración

Crear Encuesta

Registrar Encuesta

                    <form action="http://test-gestionventa.badamax.cl/encuesta/store" method="POST">
                        <input type="hidden" name="_token" value="nwbOb8QL1exLJzYIatQR6uIVw1NrloqMTC9VfVZ0">

                        <input type="hidden" name="i" id="i" value="1">

                            Descripcion:
                            <input type="text" class="form-control" name="des_encuesta" id="encuesta.des_encuesta" placeholder="Encuesta sobre..." required>

Preguntas

                                    <input type="text" name="new_answers[]" placeholder="Texto de la pregunta">
                                    Eliminar

                                        <legend>Opciones/respuestas</legend>

                                        <input type="button" value="Preview opciones" class="add" id="preview" />
                                        <input type="button" value="Agregar opción" class="add" id="add" />

                                Añadir Pregunta

                            <button type="submit" class="btn btn-primary btn-block">Guardar</button>

                    </form>

A: Tu codigo es complicado porque esta muy desordenado, pero para arreglar facil tu problema, solo tienes que cambiar el selector del click y usar .on en lugar de .click.  Ademas estabas agregando un _ a la clase add.  Quedaria asi:

$(document).ready(function() {

    var i = $("#i").val();
    //var n = i++;
    //agregado de otro codigo
    $('.add-answer').on('click', function(e) {
  var el = $('
');
  el.append($('<input>', {
   type: "text",
   name: "new_answers[]"
  }))
  el.append($('', {
   "class": "delete-new-answer btn-danger btn",
   "href": "#",
   "text": "Eliminar"

  }));
  $('.answers-list').append(el);
        e.preventDefault();
        console.log("iiiii "+i);
        $('.answers-list').append('
');
        $('.answers-list').append('
');
        //agregando los botones de opciones respuestas
        $('.answers-list').append('
');
        $('.answers-list').append('<input type=\"button\" value=\"Preview form_'+i+'\" class=\"add_ \" id=\"preview'+i+'\" />');
        $('.answers-list').append('<input type=\"button\" value=\"Add a field_'+i+'\" class=\"add \" id=\"add'+i+'\" />');
        $('.answers-list').append('
');
        var intId = $("#yourform"+i+" div").length + 1;
        //console.log(intId);
        var fieldWrapper = $("
");
        $("#yourform"+i).append(fieldWrapper);
        //hasta aquí
        //console.log("elemento "+$("#add"+i));

 })
    //hasta aquí
    console.log("salida "+i);
    $(".answers-list").on("click", ".add", function() {
        alert("hola");
        //$(".add").click(function() {
            var intId = $("#yourform"+i+" div").length + 1;
            //console.log(intId);
            var fieldWrapper = $("
");
            var fName = $("<input type=\"text\" class=\"fieldname\" />");
            var fType = $("<select class=\"fieldtype\"><option value=\"checkbox\">Checked</option><option value=\"textbox\">Text</option><option value=\"textarea\">Parrafo</option></select>");
            var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
            removeButton.click(function() {
                $(this).parent().remove();
            });
            fieldWrapper.append(fName);
            fieldWrapper.append(fType);
            fieldWrapper.append(removeButton);
            $("#yourform"+i).append(fieldWrapper);
        });

    $("#add").click(function() {
    //$(".add").click(function() {
        var intId = $("#buildyourform div").length + 1;
        //console.log(intId);
        var fieldWrapper = $("
");
        var fName = $("<input type=\"text\" class=\"fieldname\" />");
        var fType = $("<select class=\"fieldtype\"><option value=\"checkbox\">Checked</option><option value=\"textbox\">Text</option><option value=\"textarea\">Parrafo</option></select>");
        var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
        removeButton.click(function() {
            $(this).parent().remove();
        });
        fieldWrapper.append(fName);
        fieldWrapper.append(fType);
        fieldWrapper.append(removeButton);
        $("#buildyourform").append(fieldWrapper);
    });
    $("#preview").click(function() {
        console.log("preview");
        $("#yourform").remove();
        //$("#yourform").children().remove();
        var fieldSet = $("<fieldset id=\"yourform\"><legend>Form</legend></fieldset>");
        console.log(fieldSet);
        $("#buildyourform div").each(function() {
            var id = "input" + $(this).attr("id").replace("field","");
            console.log("el id "+id);
            var label = $("" + $(this).find("input.fieldname").first().val() + "");
            var input;
            switch ($(this).find("select.fieldtype").first().val()) {
                case "checkbox":
                    input = $("<input type=\"checkbox\" id=\"" + id + "\" name=\"" + id + "\" />
");
                    break;
                case "textbox":
                    input = $("<input type=\"text\" id=\"" + id + "\" name=\"" + id + "\" />
");
                    break;
                case "textarea":
                    input = $("<textarea id=\"" + id + "\" name=\"" + id + "\" ></textarea>
");
                    break;
            }
            fieldSet.append(label);
            fieldSet.append(input);
        });
        //$("body").append(fieldSet);
        $("#your").append(fieldSet);

        console.log($("#i").val(i++));
    });
});

Encuesta

Administración

Crear Encuesta

Registrar Encuesta

                    <form action="http://test-gestionventa.badamax.cl/encuesta/store" method="POST">
                        <input type="hidden" name="_token" value="nwbOb8QL1exLJzYIatQR6uIVw1NrloqMTC9VfVZ0">

                        <input type="hidden" name="i" id="i" value="1">

                            Descripcion:
                            <input type="text" class="form-control" name="des_encuesta" id="encuesta.des_encuesta" placeholder="Encuesta sobre..." required>

Preguntas

                                    <input type="text" name="new_answers[]" placeholder="Texto de la pregunta">
                                    Eliminar

                                        <legend>Opciones/respuestas</legend>

                                        <input type="button" value="Preview opciones" class="add" id="preview" />
                                        <input type="button" value="Agregar opción" class="add" id="add" />

                                Añadir Pregunta

                            <button type="submit" class="btn btn-primary btn-block">Guardar</button>

                    </form>


text:
Q: Adding a view above a navigation bar I'm trying to achieve an effect similar to that seen in the new Messages app (Safari, too) on iOS 7, whereby there is a progress bar within the navigation bar itself:

I've tried a few approaches, and found one that almost works. I'm using is a custom subclass of UINavigationBar that adds my custom progress bar as a subview at initialisation time. This works almost fine, but the app crashes when I try to add NSLayoutConstraints to it.
Working code (without layout constraints, so therefore doesn't adjust to orientation changes):
- (void)commonInit
{
    if (!self.progressIndicator) {
        self.progressIndicator = [[ECourseProgressIndicatorView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 3, self.bounds.size.width, 3)];
        [self addSubview:self.progressIndicator];
    }
}

Code I would expect to be able to use (with NSLayoutConstraints added), but crashes:
- (void)commonInit
{
    if (!self.progressIndicator) {
        self.progressIndicator = [[ECourseProgressIndicatorView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 3, self.bounds.size.width, 3)];
        [self addSubview:self.progressIndicator];

        self.progressIndicator.translatesAutoresizingMaskIntoConstraints = NO;
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[progressIndicator]-0-|" options:0 metrics:nil views:@{@"progressIndicator": self.progressIndicator}]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[progressIndicator(==3)]-0-|" options:0 metrics:nil views:@{@"progressIndicator": self.progressIndicator}]];
    }
}

The error that I experience when running the code with the layout constraints is included in a Gist here. If I don't set translatesAutoresizingMaskIntoConstraints = NO, then the code works, but the layout constraints I specified are ignored in favour of the autoresizing mask constraints.
Can anyone shed any light?
P.S. I did initially think of adding the progress bar as a view above the UINavigationBar (so not in its hierarchy at all), but I can find no information of how to position a view visually above the navigation bar (in Z co-ordinate terms, not Y).
Note: I posted this in the Apple developer forums, but got no reply.

A: The trick is to add a view to the titleView of navigationItem. Set that view's cliptobounds to NO, and add the progress view inside that.
UIView *test = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 128, 33)];
[test setBackgroundColor:[UIColor redColor]];
[test setClipsToBounds:NO];

// Add the progress view
UIProgressView *progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
[progressView setFrame:CGRectMake(-96, 36, 320, 2)];
[progressView setProgress:1.0];
[progressView setProgressTintColor:SYSTEM_BLUE];

[test addSubview:progressView];

self.navigationItem.titleView=test;

A: Just put this view into the NavigationController, not the NavigarionBar.

A: you can set Titleview for your navigation bar...just set any UIView as navigation bar titleview..then you can set any subview on that UIView..
UIView *viewBar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 800, 44)];
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(50, 0, 50, 50)];
[label setText:@"Sending"];
[viewBar addSubview:label];
self.navigationItem.titleView=viewBar;

Happy Coding....


text:
Q: First Haskell IO program isn't working Sorry, this is probably really dumb, but can someone explain me why this program doesn't compile? I get Couldn't match expected type 'a1 -> String' with actual type 'IO String'.
import System.Environment

main = do
  [first, last] <- getArgs
  firstnames <- lines . readFile "firstnames_male"
  lastnames <- lines . readFile "lastnames"
  print firstnames

A: You can't do lines . readFile "lastnames".
The readFile function returns an IO String, not a String.
You can, however, use the fmap function (or the <$> operator) to achieve this:
main = do
  [first, last] <- argArgs
  firstnames <- lines `fmap` readFile "firstnames_males"
  ...

This works because IO is a functor.


text:
Q: Bounded integral of absolute value of derivative squared Old qual question:
Let $f$ be a $C^1$ function on $[0,1]$ and assume
$$\int_0^1 |f'(s)|^2\,ds\leq A.$$
Show that, for all $x,y\in[0,1]$,
$$|f(x)-f(y)|\leq A^{1/2}|x-y|^{1/2}.$$
I really don't know where to go with this one. I'm guessing using the mean value theorem somewhere, but I don't know.

A: The basic idea is using the fundamental theorem of calculus, we have
$$ f(x) - f(y) = \int_y^x f'(\xi)\, d\xi $$
The triangle inequality gives, wlog $y<x$
$$ \def\abs#1{\left|#1\right|}\abs{f(x)-f(y)}\le \int_y^x \abs{f'(\xi)}\,d\xi$$
The Cauchy-Schwartz inequality applied for $\abs{f'}$ and $1$, gives
$$
 \int_y^x \abs{f'(\xi)}\, d\xi\le \left(\int_y^x \abs{f'(\xi)}^2\, d\xi\right)^{1/2} \left(\int_y^x \abs{1}^2\,d\xi\right)^{1/2}
  \le A^{1/2}\abs{x-y}^{1/2} $$


text:
Q: Is there a difference between embedded and nested loops in JavaScript? Are embedded and nested loops just synonyms? An example of each would be greatly appreciated!

A: There is no such thing as an "embedded" loop.  A nested loop is a loop within a loop.  For example:
for(i = 0; i < length; i++)
{
    for(j = 0; j < length; j++) // <----- nested loop
    {
      //do something
    }
}

A: "Embedded" and "nested" both imply "something inside something else".
Loop inside a loop.
I'm not sure what other meaning "embedded loop" would imply.

A: nested loops is loops inside a loop right? sure embedded loops is also a nested loop. samething which can be used to tell the below snipped:
for( var i=0; i<someValue; i++){ // parent loop
  for(var j=0; j<someValue; j++){ // loop within a loop
     //some code
  }
}


text:
Q: Create groups based on countries in dc.js I have a csv file and one of the field is country which have list of countries.
How to do a pie chart named as continents (not in my csv field) and i need to group the countries to continents in the code?

A: You will need a mapping from countries to continents, something like:
var continent = {
    USA: 'North America',
    France: 'Europe',
    Belgium: 'Europe',
    India: 'Asia',
    China: 'Asia',
    Kenya: 'Africa'
    // ...
};

Then you can define your dimension to key on continents instead of countries by using the map:
var cf = crossfilter(data);
var continentDimension = cf.dimension(d => continents[d.country]),
    continentGroup = continentDimension.group();

And the rest is as usual; take a look at the pie chart example for some hints on configuring the chart.


text:
Q: SVN or SCP creating .tmp files So we have two automated processes on our build system.  The first performs an svn export which exports a project to directory A.  The second performs an scp which scps a project from directory A to a different machine.  Sometimes, possibly due to a race condition, a situation arises in which a whole bunch of .tmp files are created, almost as if one of the transfers is stuck in a loop.
My question is simple, do either of these processes create .tmp files in their execution?  I'm trying to figure out which step is misbehaving.

A: Found my answer.  This can occur in svn when exporting symbolic links.  If the directory you are exporting to exists you have to use the --force command.  However, if that directory A contains a directory A/B and you have a symbolic link in A named B it will fail to export and it will leave a file named B.tmp behind.  If B.tmp exists it will create B.1.tmp and so on...

A: Subversion definitely does. There's subversion-commit.tmp for failed commits, there are probably others created during normal operation.


text:
Q: Drag, Drop and Clone - Flash AS3 I am a teacher trying to make a simple Flash AS3 game where students can drag any letter from a-z(movieclips) out to the middle of the stage to create words.
I am a total amateur with Flash and so using code snippets, I have been successful in allowing users to drag and drop letters but what I would really like is for users to be able to drag and drop a letter leaving the original letter movieclip in place and clone a new one as many times as is necessary.
Is anyone able to help me with the AS3 I would need to achieve this? Many thanks.

A: Here is a quick sample. FLA | SWF
CODE:
import flash.display.MovieClip;

for (var i=1; i<5; i++)
{
    this["object" + i].addEventListener(MouseEvent.MOUSE_DOWN, onStart);
    this["object" + i].addEventListener(MouseEvent.MOUSE_UP, onStop);
}

var sx = 0,sy = 0;

function onStart(e)
{
    sx = e.currentTarget.x;
    sy = e.currentTarget.y;
    e.currentTarget.startDrag();
}

function onStop(e)
{
    if (e.target.dropTarget != null &&
    e.target.dropTarget.parent == dest)
    {
        var objectClass:Class =
        getDefinitionByName(getQualifiedClassName(e.currentTarget)) as Class;
        var copy:MovieClip = new objectClass();
        this.addChild(copy);
        copy.x = e.currentTarget.x;
        copy.y = e.currentTarget.y;
    }

    e.currentTarget.x = sx;
    e.currentTarget.y = sy;
    e.currentTarget.stopDrag();
}

Hoping you could take it ahead & turn into something useful for your kids.

A: first, you can use a property for your letters called like "type" and "letter" for assuming is it original or a copy and which letter is it.
then initialize an empty object variable to use when clicked
var draggingObj:Object;

then you can check if user clicking on orginal letter to make a copy and move or clicking a copy just to move
if (Letter(clickedLetter).type == "original")
{
draggingObj = new Letter();
draggingObj.type = "copy";
draggingObj.letter = Letter(clickedLetter).letter;
}
else draggingObj = Letter(clickedLetter);

draggingObj.x = mousex;
draggingObj.y = mousey;

if you cannot implement this codeflow to your codeflow, you can write your own code here so we can help you properly


text:
Q: mailgun email configuration with parse.com I am using parse.com and Mailgun to send emails. But when I tried to send email I see the error that says

"The domain is unverified and requires DNS configuration. Log in to
  your control panel to view required DNS
  records\\"\n}\",\"data\":{\"message\":\"The domain is unverified and
  requires DNS configuration. Log in to your control panel to view
  required DNS records\"

I could see that my DNS is not verified in Mailgun dashboard as well.
If I use a custom domain I can do these configurations with the domain provider panel.
But I am using default xxx.parseapp.com as my domain for now.
How to do the setting for this scenario. I couldn't find any place to do the TXT settings in parse.com


text:
Q: Please tell me my data isn't gone... lie to me even In a moment of ignorance I setup my webserver to auto backup all data to another machine.
not a problem except I just mearly cp -R /var/lib/mysql so all I ended up getting was hundreds and hundreds of backups of DB.opt and table.frm files
From my understanding I didn't pull any data in these files. Is this true?
If so are these any good to me at all?

A: I'm not sure I understand your question, or even what you did, but let's walk this through.
If all you did was to issue a cp -R /var/lib/mysql /path/to/backup, then this does not harm your existing data.
It is also an incorrect backup method. Your backup itself is probably useless (unless all tables are MyISAM and you issued a FLUSH TABLES WITH READ LOCK).
What's further unclear is your description of .opt and .frm files. Is that all you got? That's strange, because you should have also got some *.MYD files, and some *.ibd files or an ibdata1 file.
Which storage engines are you using for your tables? What is the output of
mysql> select @@datadir;
mysql> show global variables like 'innodb_data_file_path' ;
mysql> show global variables like 'innodb_data_home_dir' ;

?
Last, I don't understand from your question whether data has been deleted from your webserver (containing your MySQL data).


text:
Q: What's wrong with this line of wordpress PHP code? (from a tutorial) I know this is normally frowned upon, but I took this from a tutorial, so I am a little surprised as to why it isn't working.
Here is the impacted line of code:
$document_root = rtrim(str_replace(array('/', '\'), '/', $_SERVER['DOCUMENT_ROOT']), '/');

Error messages in apache's error log:
[Sun Jul 27 01:01:47 2014] [error] [client 24.62.230.8] PHP Parse error:  syntax error, unexpected 'DOCUMENT_ROOT' (T_STRING), expecting ')' in /home/folder/wp/wp-config.php on line 8
[Sun Jul 27 01:01:47 2014] [error] [client 24.62.230.8] PHP Stack trace:
[Sun Jul 27 01:01:47 2014] [error] [client 24.62.230.8] PHP   1. {main}() /home/folder/wp/index.php:0
[Sun Jul 27 01:01:47 2014] [error] [client 24.62.230.8] PHP   2. require() /home/folder/wp/index.php:3
[Sun Jul 27 01:01:47 2014] [error] [client 24.62.230.8] PHP   3. require_once() /home/folder/wp/wp-blog-header.php:12

Context: Here is the tutorial that I followed to achieve this. Check out wp-config.php - http://polycademy.com/blog/id/148/modern_wordpress_workflow_with_composer

A: Try something like this :
$document_root = rtrim(str_replace(array('/', '\\'), '/', $_SERVER['DOCUMENT_ROOT']), '/');


text:
Q: How to import Google Fonts on a Stylus file? I'd like to know how can I import Google Fonts from a stylus (.styl) file.
I tried:
@import url(http://fonts.googleapis.com/css?family=Overlock:400,700,400italic,700italic|Calligraffitti)

...but it failed on my console when compiling with the following error:
Potentially unhandled rejection [2] ParseError: C:\Users\Coutinho\Documents\GitHub\bespoke-theme-fancy\lib\theme.styl:5
   1| // Bespoke Classes: https://github.com/markdalgleish/bespoke-classes
   2| // Stylus: http://learnboost.github.io/stylus
   3|
   4| @import 'normalizecss/normalize.css'
 > 5| @import url(http://fonts.googleapis.com/css?family=Overlock:400,700,400italic,700italic|Calligraffitti)
   6|
   7| $font-family-serif 'Calligraffitti', cursive
   8| $font-family-sans 'Overlock', Helvetica, sans-serif

expected ")", got "selector |Calligraffitti)"

Thanks!

A: Wrap the url in quotes:
    @import url('http://fonts.googleapis.com/css?family=Overlock:400,700,400italic,700italic|Calligraffitti')


text:
Q: Как правильно сверстать такой блок Как правильно сверстать такой блок только на HTML и CSS не используя Bootstrap и т.п.? Затруднение больше вызывает как сделать черту между блоками и соблюсти все отступы и выравнивания как в примере.
Сам верстку только учу, и захотел скопировать данный сайт. Вот на этом блоке просто застрял.
Ссылка на сам сайт

A: Предлагаю воспользоваться flexbox и всю сетку строить на нём
Раверните пример на всю страницу а браузер сожмите до предела

body {
  margin: 0;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.items {
  box-sizing: border-box;
  display: flex;
  max-width: 768px;
  margin: auto;
  font-family: sans-serif;
  padding: 0 8px;
}

.item1 {
  width: 40%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item2 {
  width: 60%;
  display: flex;
  flex-wrap: wrap;
}

.item2-outer {
  width: 49%;
  margin: 2px;
}

.item1 h3,
.item2-outer h3 {
  text-transform: uppercase;
  font-size: 14px;
}

.item1 p,
.item2-outer p {
  font-size: 12px;
  width: 90%;
}

.item2-outer:nth-child(1),
.item2-outer:nth-child(2) {
  border-bottom: 1px solid #ccc;
}

@media(max-width: 768px) {
  .item2-outer:nth-child(1),
  .item2-outer:nth-child(2) {
    border-bottom: none;
  }
  .item1,
  .item2 {
    width: 100%;
  }
  .item2-outer {
    width: 90%;
    margin: auto;
  }
}

@media(max-width: 540px) {
  .items {
    width: 90%;
    margin: auto;
    flex-direction: column;
  }
  .item1-top,
  .item1-bottom {
    width: 90%;
    margin: auto;
  }
  h3 {
    background: #ccc;
    padding: 4px 0 4px 4px;
    color: #fff;
  }
  svg {
    display: block;
    margin: auto;
  }
}
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Scills

        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Soluta, dolore? Odio sit cupiditate veritatis placeat quibusdam impedit, corrupti saepe adipisci.

      <svg viewBox=" 0 0 200 50" width="100px">
        <g><path d="M0,0 20,20 40,0 60,20 80,0 100,20 120,0 140,20"  fill="none" stroke="#ccc" stroke-width="3"/>
        </g>
        <g transform="translate(0,20)">
          <path d="M0,0 20,20 40,0 60,20 80,0 100,20 120,0 140,20"  fill="none" stroke="blue" stroke-width="3"/>
        </g>
      </svg>

web development

 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Soluta, dolore? Odio sit cupiditate veritatis placeat quibusdam impedit, corrupti saepe adipisci.

ui/ux design

 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Soluta, dolore? Odio sit cupiditate veritatis placeat quibusdam impedit, corrupti saepe adipisci.

Frontend development

 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Soluta, dolore? Odio sit cupiditate veritatis placeat quibusdam impedit, corrupti saepe adipisci.

Cansalding & seo audit

 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Soluta, dolore? Odio sit cupiditate veritatis placeat quibusdam impedit, corrupti saepe adipisci.

A: Вот html:

Skills.

I am inspired by creating great work with people who are as passionate as I am about building something awesome.

Web Development

Javascript, Coffeescript, JAVA, Python, PHP, Go, Node.js, MongoDB, Redis, PostgreSQL, WebStorm.

UI\UX Design

Photoshop, Illustrator, Sketch, Axure, XMind, Prototyping, Wireframing, User Research, Usability Testing.

Frontend Development

HTML, CSS, LESS, SASS, Bootstrap, Wordpress, Drupal, Phonegap / Cordova, Ionic, Foundation, Angular.js.

Consulting & SEO Audit

Screaming Frog, Woorank, Raventools, Semrush, Moz, WebCEO, Google Analytics, ChartBeat, CrazyEgg.

вот css:

* {
   margin: 0;
   padding: 0;
   box-sizing: border-box;
  }

  .place {
   width: 100%;
   height: 625px;
  }

  .container1 {
   height: 300px;
   width: 100%;
   font-family: 'Manrope', sans-serif;
   font-weight: 200;
   border-top: 1px solid darkgrey;
   border-bottom: 1px solid darkgrey;
   margin-top: 1%;
   padding-top:2%;
  }

  .container1 .box1 {
   float: left;
   width: 450px;
   height: 300px;
   font-family: 'Manrope', sans-serif;
   margin-top: 1%;
   position: relative;
   padding-left: 1%;
  }

  .container1 .box1 p {
   padding-top: 10px;
  }

  .container1 .box1 span {
   font-style: bold;
   color: purple;
   font-size: 40px;
   padding: 1%;
  }

  .container1  .box2 , .box3 , .box4 , .box5{
   float: right;
   width: 400px;
   height: 120px;
   margin: 1%;
  }

  .container1 .box2 , .container1 .box3 {
   border-bottom: 1px solid darkgrey;
  }

A: Примерно вот так:

* {
 box-sizing: border-box;
 padding: 0;
 margin: 0;
 font-family: sans-serif;
}

section {
 display: flex;
 flex-direction: column;
 justify-content: space-around;
 height: 330px;
}

.top,
.bottom {
 display: flex;
 justify-content: space-around;
}

.top > div {
 padding-bottom: 50px;
 border-bottom: 1px solid #000;
}

.bottom {
    margin-top: 50px;
}

h2 {
 font-size: 1.5em;
 margin-bottom: 20px;
}

.first,
.second {
 width: 40%;
}

Web Development

Javascript, Coffeescript, JAVA, Python, PHP, Go, Node.js, MongoDB, Redis, PostgreSQL, WebStorm.

UI\UX Design

Photoshop, Illustrator, Sketch, Axure, XMind, Prototyping, Wireframing, User Research, Usability Testing.

Frontend Development

HTML, CSS, LESS, SASS, Bootstrap, Wordpress, Drupal, Phonegap / Cordova, Ionic, Foundation, Angular.js.

Consulting & SEO Audit

Screaming Frog, Woorank, Raventools, Semrush, Moz, WebCEO, Google Analytics, ChartBeat, CrazyEgg.

Также если нужно будет делать адаптивную верстку, достаточно будет добавить для .top и .bottom display: block; и убрать margin-top: 50px; у .bottom.
Если надо, вот линия:

<?xml version="1.0" encoding="utf-8"?>

<svg version="1.1" id="Слой_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  viewBox="0 0 105 20" style="enable-background:new 0 0 105 20;" xml:space="preserve">

<g>
 <g>
  <polyline class="st0" points="2.5,5 16.8,15 31.1,5 45.3,15 59.6,5 73.9,15 88.2,5 102.5,15   "/>
 </g>
</g>
</svg>

Она слегка другого цвета, так как в атрибутике у неё не было указанно fill, но это можно исправить в её коде.


text: Q: Javascript have a form submit just update html in a div tag Hi there I have a webpage that lets some people add info to their webpage by clicking a button, or thats the goal anyways. They click the button and the display part of the page changes to a form with Javascript. Now then, this form only allows them to select which part of the info they want to change, and on submit I don't want in to redirect, I don't want it even send anything to the server. The form only has one value, and I want that to be passed into a function that stores the value of the first form, puts a new form where the old one was based on the previous form, and then after that finally submits the info to the server where php handles the rest and updates the DB. So I have this so far,


text:
Q: Ubuntu IP Tables Redirect I'm trying to do a simple redirect with IP tables.  Basically what I want to do is make it so when I try to wget or curl something from the IP address of 192.100.1.105:80 it will redirect me to 192.100.1.64:8080.
We recently switched around the IP address in our infrastructure so that they are all sequential but some of our server admins are having trouble remembering to type the new IP.

A: As Iain points out this looks like a job for DNS.
The iptables solution will probably be something like this, if you want to stick to it:
iptables -t nat -I PREROUTING -d 192.100.1.105 -p tcp --dport 80 -j DNAT --to 192.100.1.64:8080
iptables -t nat -I POSTROUTING -d 192.100.1.64 -j SNAT --to 192.100.1.105

The first rule does the actual redirect, the second one masks the source IP address so 192.100.1.64 returns the packets to 192.168.1.105 and the connection thus actually works. Do note that all packets will go through 192.168.1.105 at all times - it's a low level (TCP) redirect.
A nicer way to do this would be to set up a web server on 192.100.1.105 to force an HTTP redirect to 192.100.1.64:8080. This is probably much better because it doesn't mask the redirect and the users may become (probably slowly) aware of it. Also, you only have to process the initial connection on 192.100.1.105 - the rest goes directly to 192.100.1.64.
About the IPs - you aren't using 192.100.1.0/24 as a private network, right? It isn't private.


text:
Q: Impossible to get mouse input from a window in my own process I've been trying to add video support to my image viewer application which I made in .Net 4. After long research and many tests I've decided for LibVLC, which is free and supports a large number of file formats (more than Windows Media Player, for instance). There's a wrapper library for .Net called Meta.VLC which seems to work alright. For simplicity, I keep everything within the 32 bit realm. The problem comes when I want to process mouse events on the video frame, which is drawn into one of my controls (I give the library my HWND and it apparently uses Direct3D for rendering).
The library doesn't expose any mouse events, but I said "Hey! No problem! I know enough Win32 API to sort this out". First, I've thought I could intercept mouse messages from my form by overriding its WndProc. Nope. Then I thought I could implement IMessageFilter.PreFilterMessage. Nope again. WM_LMOUSEDOWN and other related mouse events do not reach my form. Somehow they're "eaten up" by the child window. I've used Spy++ and I established that the video window is indeed within my process and is a descendant of my form:
My control HWND contains
    Caption: "VLC (Direct3D output)", Class: "VLC video main 087CCA50"
which contains
    Caption: "", Class: "VLC video output 087CCA50"
which receives all the mouse input.

With Spy++ I can see that mouse events are indeed being generated and are sent to the video output window no problem. However, I cannot see them from my form. Then! I thought I could subclass either the child or the grandchild window by using SetWindowsLong(GWL_WNDPROC), but although I succeeded in subclassing the windows, mouse messages are still hidden to me!
A local Windows hook for WH_MOUSE (SetWindowsHookEx) didn't work either. I can see my thread's mouse events but not the video window's. I think I could do this with a global hook (WH_MOUSE_LL) but that would require administrator access rights and I'd like to keep my app low profile.
As a final note, I do get WM_PARENTNOTIFY messages, but only for WM_LMOUSEDOWN; I'd like full mouse support, like WM_LMOUSEUP, WM_RMOUSEDOWN, WM_MOUSEWHEEL, WM_MOUSEMOVE, etc. which I don't receive. Also, I don't want to use mouse capture (SetCapture() function): mouse should remain free to come and go between windows.
I'm astonished there's no way to obtain the mouse input from this video frame. I think I must be missing something really obvious but I can't find it.
So, the question is: using .Net or Win32 API calls, how do I get mouse input from a window that refuses to cooperate, given that the window runs within my very own process and I have its handle. Or -if it can't be done- why can't I?

A: Perhaps you can try adding a transparent window over the VLC window and getting the mouse input from that window.

A: Mouse hook worked for me. Look sources of VLC Web Plugin: https://code.videolan.org/videolan/npapi-vlc/blob/master/common/win32_fullscreen.cpp


text:
Q: Running into a '__resizeListeners__' of undefined with react and Semantic-UI accordion I am using Semantic-UI accordion for the Segment react component that is  wrapped around an eCharts line plot (using echarts-for-react). I currently have a button that allows me to collapse the line plot, as seen in the "collapsed" variable.
I also have a button that allows me to change the size of the component from half screen to full screen.
The problem is when the component is already "collapsed" and I trigger the resize from half screen to full screen then "uncollapse" the component, the chart does not resize to the new container size.

Uncaught TypeError: Cannot read property 'resizeListeners' of
  undefined

The resize does work when the line plot is not collapsed though.
class PlotSegmentsList extends Component {
   //no life cycle methods yet
  render() {
    const state = store.getState();
    const view = state.fullOrHalfScreen;

    const activeCategory = this.props.categories.find(p => p.category === this.props.Id);
    const activePlotsArray = activeCategory.plots;

    const plotsList = activePlotsArray.map((p) => (

       <Segment
        legend={p.legend}
        plotTitles={p.titles}
      />

      )
    );

    return (

        {plotsList}

    )
  }
}

class Segment extends Component {

  render () {
    const state = store.getState();
    const collapsed = state.collapseOrUncollapseAll;

    return (

              {this.props.plotTitles.main}

            <Toolbar plot_ID={this.props.plotTitles.main}/>
            <Plot
              data={this.props.data}
              legend={this.props.names}
              plotType='line'
              plotTitles={this.props.plotTitles}
            />

class Plot extends React.Component {

I have tried to add event listeners to Plot in the components lifeCycle methods but I am pretty new to react and redux and unsure how to properly update this components size if it is collapsed in the accordion. Any suggestions on this problem and using react life cycle methods with redux would be great! Thank you

A: I am the author of echarts-for-react.
Upgrade to the latest version of package, can solve the problem above by switching element-size-listener to size-sensor.