text:
Q: elasticsearch n-gram tokenizer with match_phrase not giving expected result I created a index as follow
PUT /ngram_tokenizer
{
  "mappings": {
    "properties": {
      "test_name": {
      "type": "text",
      "analyzer": "my_analyzer"
    }
  }
},
  "settings": {
    "index": {
      "max_ngram_diff": 20
    },
    "analysis": {
      "tokenizer": {
        "my_tokenizer": {
          "type": "ngram",
          "min_gram": 2,
          "max_gram": 20,
          "token_chars":[
            "letter",
            "digit",
            "whitespace",
            "symbol"
            ]
        }
      },
      "analyzer": {
        "my_analyzer": {
          "tokenizer": "my_tokenizer"
        }
      }
    }
  }
}

Then indexed as follow
POST /ngram_tokenizer/_doc
{
  "test_name": "test document"
}

POST /ngram_tokenizer/_doc
{
  "test_name": "another document"
}

Then I did a match_phrase query,
GET /ngram_tokenizer/_search
{
  "query": {
    "match_phrase": {
      "test_name": "document"

  }
}
}

Above query returns both document as expected, but below query didn't return any document
GET /ngram_tokenizer/_search
{
  "query": {
    "match_phrase": {
      "test_name": "test"

  }
}
}

also, I checked all the tokens it generates by following query
POST ngram_tokenizer/_analyze
{
  "analyzer": "my_analyzer",
  "text": "test document"
}

match query works fine, can you guys help me
Update
when I want to search for a phrase I have to do a match_phrase query right? Then I used n-gram tokenizer on that field because, if there is any typo in the search term, still i can get a similar doc. Also, I know that we can use fuzziness to overcome typo issues in search terms. But when I used fuzziness in match queries or fuzzy queries there was a scoring issue as mentioned here. Actually what I want is, when I do a match query I want to get results even though there is a typo in search terms. And in the match_phrase query, I should get proper results at least when I search without any typos.

A: It's because at search time, the analyzer used to analyze the input text is the same as the one used at indexing time, i.e. my_analyzer, and the match_phrase query is a bit more complex than the match query.
At search time, you should simply use the standard analyzer (or something different than the ngram analyzer) in order to analyze your query input.
The following query shows how to make it work as you expect.
GET /ngram_tokenizer/_search
{
  "query": {
    "match_phrase": {
      "test_name": {
        "query": "test",
        "analyzer": "standard"
      }
    }
  }
}

You can also specify the standard analyzer as a search_analyzer in your mapping
"test_name": {
  "type": "text",
  "analyzer": "my_analyzer",
  "search_analyzer": "standard"
}


text:
Q: Grouping a List of objects by property, split into multiple lists. Current Structure (Cannot change due to requirements of the system)
class Statement
{
    string section;
    string category;
    string statement;
}

Example Statement list
section      category     statement
1            a            apple
1            a            banana
1            b            potato
2            c            car
2            c            bus
2            d            plane

Problem
I start with a List<Statement>, and need to split them up based on Section, and then category into the following (or similar) structure
struct SectionCollection
{
    string sectionName {get{return categories[0].section;}}
    List<CategoryCollection> categories;
}

struct CategoryCollection
{
    string categoryName {get{return statements[0].category;}}
    List<Statement> statements;
}

So, from the List<Statement>, I should have a
List<SectionCollection>, which inside has a
List<CategoryCollection>, which inside has a
List<Statement>
So in the above data example, I would have

*

*List<SectionCollection>

*

*List<CategoryCollection> (Inside)

*

*List<Statement> (Inside)

Notes
It's not impossible that A statement or a category might be the same in a different section - these still need to belong in different SectionCollections
Attempt
My current attempt, which works until a null exception is eventually thrown on the inner for loop. This is one of those problems I've been staring at for a while now, so I know how confused this 'solution' may seem.
var sections = statements.GroupBy(x => x.section).Select(y => y.ToList()).ToList();
foreach(var section in sections)
{
     SectionCollection thisSection = new SectionCollection();
     var categories = section.GroupBy(x => x.category).Select(y => y.ToList()).ToList();

    foreach(var category in categories)
    {
        thisSection.categories.Add(new CategoryCollection({statements = category});
    }
}

A: The reason you're getting a null reference error is because you're not initializing the Categories list in SectionCollection.
Changing:
SectionCollection thisSection = new SectionCollection();

To:
SectionCollection thisSection = new SectionCollection()
{
    Categories = new List<CategoryCollection>()
};

Will fix the error. You're also not capturing the result anywhere, if you update your code to the below it should work:
var sections = statements.GroupBy(x => x.Section).Select(y => y.ToList()).ToList();

var result = new List<SectionCollection>();

foreach (var section in sections)
{
    SectionCollection thisSection = new SectionCollection() { Categories = new List<CategoryCollection>() };

    var categories = section.GroupBy(x => x.Category).Select(y => y.ToList()).ToList();

    foreach (var category in categories)
    {
        thisSection.Categories.Add(new CategoryCollection { Statements = category });
    }

    result.Add(thisSection);
}

But it might be a bit cleaner to give classes proper constructors and properties and move some of the logic there:
internal class Program
{
    static void Main(string[] args)
    {
        var statements = new List<Statement>()
        {
            new Statement(1, "a", "apple"),
            new Statement(1, "a", "banana"),
            new Statement(1, "b", "potato"),
            new Statement(2, "c", "car"),
            new Statement(2, "c", "bus"),
            new Statement(2, "d", "plane")
        };

        var sectionCollections = statements
            .GroupBy(s => s.Section)
            .Select(group => new SectionCollection(group.Key, statements))
            .ToList();
    }

    public class Statement
    {
        public Statement(int section, string category, string statementName)
        {
            Section = section;
            Category = category;
            StatementName = statementName;
        }

        public int Section { get; }

        public string Category { get; }

        public string StatementName { get; }
    }

    public class SectionCollection
    {
        public SectionCollection(int sectionName, List<Statement> statements)
        {
            SectionName = sectionName;

            Categories = statements
                .Where(s => s.Section == sectionName)
                .GroupBy(s => s.Category)
                .Select(group => new CategoryCollection(group.Key, group.ToList()))
                .ToList();
        }

        public int SectionName { get; }

        public List<CategoryCollection> Categories { get; }
    }

    public class CategoryCollection
    {
        public CategoryCollection(string categoryName, List<Statement> statements)
        {
            CategoryName = categoryName;
            Statements = statements;
        }

        public string CategoryName { get; }

        public List<Statement> Statements { get; }
    }
}

You'll end up with following structure:

A: You create a new SectionCollection object with:
SectionCollection thisSection = new SectionCollection();

But you never initialize the value thisSection.categories using new -- neither in the constructor or outside explicitly.
So when you attempt to access thisSection.categories.Add in your inner loop, you generate an exception.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change exported property through MEF? I'm studying MEF, and try to use Export attribute to export a property, and import it in an other class.
But my problem is that I want to change this property and the other class can import a new value.
For example,
[Export]
public class A{
    [Import("Notes")]
    public string Description{get;set;}
}

[Export]
public class B{
    [Export("Notes")]
    public string Text{get;set;}
}

I want once I change the Text of class B, the A.Description can get changed too.
So, how can I implement this?
Any good idea?

A: This approach would work for most reference type but not with string which is immutable. This means that after you change the value of B.Text, the objects referenced by A.Description and B.Text will no longer be the same (you can use Object.ReferenceEquals to test this).
One way to do what you are after using MEF is to export/import a method instead of the property:
[Export]
public class A
{
    public string Description { get { return GetDescription(); } }

    [Import("GetNotes")]
    Func<string> GetDescription;
}

[Export]
public class B
{
    public string Text { get; set; }

    [Export("GetNotes")]
    string GetText()
    {
        return Text;
    }
}

Finally note that there are other ways to do this. The most common in .NET is with events.


text:
Q: Binding rows from synonymous columns I'm importing a lot of different data frames. Due to the fieldworkers using different notations, there are many different synonyms to a column. This creates an issue when I row bind the data.frames together, as there now exists many superfluous columns to describe the same thing. Sometimes they are just misspelt. The order and number of columns in each import varies.
For example: PARCELL may be spelt PAR, PARC, PARCEL, and so on.
             ROWNR may be spelt ROW, ROWNUMBER, etc.
Example data:
Field 1
X1    BLOCK PARCELL ROW SORTNR FUKTIGH PLANTNR KONDI SKADA1 SKADA2 SKADA3 OVRIGT X13
  <lgl> <dbl>   <dbl> <dbl>  <dbl>   <dbl>   <dbl> <dbl>  <dbl>  <dbl>  <dbl> <chr>  <lgl>
1 NA        1       1     1     13       3       1     1     NA     NA     NA NA     NA
2 NA        1       1     1     13       3       2     1     NA     NA     NA NA     NA
3 NA        1       1     1     13       3       3     1     NA     NA     NA NA     NA
4 NA        1       1     1     13       3       4     3    513     NA     NA NA     NA
5 NA        1       1     1     13       3       5     1     NA     NA     NA NA     NA
6 NA        1       1     1     13       3       6     1     NA     NA     NA NA     NA

Field 2
  X1    BL PARC ROWNR SORTNR PLANTNR DOD85  KOND  HOJD SKAD1 SKAD2 X12
  <lgl> <dbl>   <dbl> <dbl>  <dbl>   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <lgl>
1 NA        1       1     1     17       1     0     1    87    NA    NA NA
2 NA        1       1     1     17       2     0     1    83    NA    NA NA
3 NA        1       1     1     17       3     0     1    67    NA    NA NA
4 NA        1       1     1     17       4     0     1    77    NA    NA NA
5 NA        1       1     1     17       5     0     1    50   151    NA NA
6 NA        1       1     1     17       6     0     1    59   151    NA NA

Of course, you can run around this by manually parsing each the proper name when importing the data, or using dplyr::rename but as there are many different imports this becomes unpractical.
I already have all of my data.frames in a named list, data.frame.list, so it might be good to iterate over this: lapply, for?
library(dplyr)

data.frame.list <- mget(ls(pattern="^F"))
finaldf <- data.frame.list %>% bind_rows(.id="id")

I would like to be able to provide R with some identified synonyms before row binding so as to be able to avoid manually correcting these for each data.frame individually.
My expected output would look like the following:
PARCEL; ROWNR;
1;1
1;2
1;3
1;4
2;1
2;2
2;3
I'm not interested in keeping track of how the original field worker spelt parcel or row. I am only concerned with having the values under the correct column.
TLDR; Want to combine data with many mispelt columns, preferably by iterating a rowbind over a list and parsing synonyms to be joined under one column - e.g.
PARCEL = c("PAR", "PA", "PARCELL", "PARCEL")
ROW = c("ROW", "Row", "ROWNR", "ROWNUMBER")

A: data.table::rbindlist() might be what you are looking for.. Though I am not sure because of the lack of sample data and a desired output example.
updated answer based on sample data provided
dt1 <- fread("
X1    BLOCK PARCELL ROW SORTNR FUKTIGH PLANTNR KONDI SKADA1 SKADA2 SKADA3 OVRIGT X13
NA        1       1     1     13       3       1     1     NA     NA     NA NA     NA
NA        1       1     1     13       3       2     1     NA     NA     NA NA     NA
NA        1       1     1     13       3       3     1     NA     NA     NA NA     NA
NA        1       1     1     13       3       4     3    513     NA     NA NA     NA
NA        1       1     1     13       3       5     1     NA     NA     NA NA     NA
NA        1       1     1     13       3       6     1     NA     NA     NA NA     NA")

dt2 <- fread("
X1    BL PARC ROWNR SORTNR PLANTNR DOD85  KOND  HOJD SKAD1 SKAD2 X12
NA        1       1     1     17       1     0     1    87    NA    NA NA
NA        1       1     1     17       2     0     1    83    NA    NA NA
NA        1       1     1     17       3     0     1    67    NA    NA NA
NA        1       1     1     17       4     0     1    77    NA    NA NA
NA        1       1     1     17       5     0     1    50   151    NA NA
NA        1       1     1     17       6     0     1    59   151    NA NA")

l <- mget( ls (pattern = "^dt"))

#only keep columns with names that possibly contain parcels
PARCEL = c("PAR", "PA", "PARCELL", "PARCEL")
ROW    = c("ROW", "Row", "ROWNR", "ROWNUMBER")

l2 <- lapply( l, function(x) {
  rows    <- x[, grepl( paste0( ROW, collapse = "|" ), names(x) ), with = FALSE]
  parcels <- x[, grepl( paste0( PARCEL, collapse = "|" ), names(x) ), with = FALSE]
  ans <- data.table( row = rows, parcel = parcels )
  setnames( ans, names(ans), c("row", "parcel"))
  return(ans)
})

rbindlist( l2, use.names = FALSE, idcol = TRUE)

#    .id row parcel
# 1: dt1   1      1
# 2: dt1   1      1
# 3: dt1   1      1
# 4: dt1   1      1
# 5: dt1   1      1
# 6: dt1   1      1
# 7: dt2   1      1
# 8: dt2   1      1
# 9: dt2   1      1
# 10:dt2   1      1
# 11:dt2   1      1
# 12:dt2   1      1

old answer
This code works, as long as the columns in the data.frames/data.tables in l are always in the same order.
library(data.table)

dt1 <- data.table( parcel = 1:2 )
dt2 <- data.table( parcell = 1:2 )

l <- mget( ls( pattern = "^dt" ) )

rbindlist( l, use.names = FALSE, idcol = "object" )

#    object parcel
# 1:    dt1      1
# 2:    dt1      2
# 3:    dt2      1
# 4:    dt2      2


text:
Q: Playing video in website using codeigniter I am using php codeigniter. I want to store youtube links of movie trailers in my database and when the user clicks on a thumbnail it should start playing in the website. Pleaseee someone give me idea how to implement this. Thanks in advance ...

A: check this integration of jquery and flowplayer it works good check here


text:
Q: Using JARs in WEB-INF/lib with previous versions of Tomcat I'm working on a way to add plugin-like functionality to an application.
What I'd like is to be able to give a client a JAR file and have them drop it into the application and have it be "pulled in" without having to make any changes to config files or whatnot.
I would love to be able to put them into WEB-INF/lib, which works great with Tomcat 7 since it supports Servlet 3.0. The problem is that not all users of this application have Tomcat 7, and this needs to be flexible enough to not force them to update.
Does anyone know of a way to achieve the same functionality, but in a way that's compatible with older versions of Tomcat and the Servlet API?
This is also a Maven project, so pushing it to the repo could work as well, but that involves the client modifying pom.xml which I'd rather stay away from.
Edit:
I think I found a suitable solution using serviceLoader, but if anyone has a better idea let me know. I'm pretty new to this area so I'm open to advice.

A: You can drop JAR files directly into WEB-INF/lib on older versions of Tomcat as well.
You just need to make sure that the JAR files work on the version of Tomcat they are being dropped in. So either

a) Make the JAR file work for all required Tomcat versions
b) Create different versions of the JAR for each tomcat version and
  distribute accordingly.

The problem with this, is that if the web application is redeployed from scratch, the plugin JARs may be deleted.  So you may need to think about how to persist them.

A: You might want to look into Maven WAR overlays if you want to make the customization explicit and repeatable: http://maven.apache.org/plugins/maven-war-plugin/overlays.html


text:
Q: computing the occurences of a number in a list with recursion the task I am doing is:

Given an array of ints, compute recursively the number of times that the value 11 appears in the array. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array.

I need to do this recursively. I'm rather new at this, but I technically made it work.
I have the following:
def array11(arr, index, cnt=0, num=0):
    if(cnt==len(arr)-index):
        print("yay!!! number 11 appears %d times"%num)
        return
    elif(arr[index:][cnt]==11):
        num+=1
        cnt+=1
        array11(arr,index,cnt,num)
    else:
        cnt+=1
        array11(arr,index,cnt,num)

but I feel I did it a cheap way for some reason by adding the "cnt" and "num" parameters with default values. I just didn't know how to go through the "arr" array without a counter!!
So this this something acceptable? Would you have done it the same way?
thanks in advance

A: You normally return the total count:
def array11(arr, index):
    if index == len(arr):
        return 0
    return (arr[index] == 11) + array11(arr, index + 1)

I am using a little Python trick here where bool is a subclass of int and True is equal to 1. As such, adding up booleans (or booleans and integers) results in the boolean values to be interpreted as integer numbers instead.
You'd use print then on whatever the outermost call to array11() returned.

A: This is perfectly acceptable, albeit not the cleanest way to perform tail recursion. What you are doing is called using an accumulator to keep track of your count, which allows you to have tail recursion (the more efficient type of recursion).
However, as BlackVegetable points out, Python doesn't allow you to reap the benefits of tail recursion, but it's definitely noteworthy to understand the difference between using an accumulator vs a top down approach as in Martijn Pieter's answer.

A: In Python 3 it can be as concise as this:
arr = [11, 0, 4, 7, 2, 11, 6, 11, 12]

def count11(arr):
    if not arr:
        return 0
    first, *rest = arr
    return (1 if first == 11 else 0) + count11(rest)

count11(arr) # 3

The list slicing may not be very efficient, but since we're talking about recursion in Python, in assume performance is not a factor.


text:
Q: Lambda Schedule to println from a ArrayList I am trying to create a timer to print out from an ArrayList at a schedule. But I am receiving this error:
Cannot resolve method 'schedule(<lambda expression>,int,java.util.concurret.TimeUnit)'

Why am I receiving this error and what can I do about it?
List<String> finalQuestionsList = questionsList;
timer.schedule(()-> finalQuestionsList.forEach(write::println),120, TimeUnit.SECONDS);

A: JLS asserts type of a lambda expression:

A lambda expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of the ground target type derived from T.

*

*TimerTask is not a Function Interface, so you can't assign a lambda expression  to a TimerTask. but  you can adaptee a Runnable to a TimerTask with an adapter method task.

*Timer.schedule methods can't take a TimeUnit, but you can using TimeUnit.toMills() to convert a duration to milliseconds.

*I can't see any write variable in your code snippet, so I use System.out instead.
List<String> finalQuestionsList = questionsList;
timer.schedule(task(() -> finalQuestionsList.forEach(System.out::println))
         , 120, TimeUnit.SECONDS.toMillis(1));

private TimerTask task(Runnable task) {
    return new TimerTask() {
      @Override
      public void run() {
        task.run();
      }
    };
}


text:
Q: Monochrome Bitmap Should be an easy one.
I'm working on Scala trying to handle long sequences of binary data. That is long lists of 0's and 1's. What is the 'best' way to store/access this kind of data.
The important point here is memory optimisation, so I would like to avoid using an entire byte to store a boolean. Also access is somwhat important, so I would like to avoid paking them into bytes and then into arrays.
Is a BitMap a good idea? Is there such a class in scala?
if not, would it be best to use ByteArray? How would you implement this?
Any other ideas?
Thanks,

A: You can use java.util.BitSet (perhaps with a couple if clever explicits to make it more Scala-like).
If that is still too costly I would write a class that uses an array internally and pack the bits into ints or bytes.

A: If your values are not uniformly distributed have (significantly more 0s than 1s) you can use run-length encoding to encode the image data. This is the encoding used by Fax.
There are two encoding options:

*

*use RLE for black and white

*use only RLE for one color and use a direct encoding if you encode the other color (or mixed sections)


text:
Q: Making javascript function more shorter Ok so I know this heading may be not properly defined, but I am basically interested in making one of my javascript functions in ExtJs 6 more shorter or efficient, here is the code I am talking about
this function is for an on list item tap, its using itemTpl
onMylist2ItemTap: function(dataview, index, target, record, e, eOpts) {
    var company_name = record.get('name');
    var license_idval = record.get('license_id');
    var start_date = record.get('start_date');
    var expiry_date = record.get('expiry_date');
    var product_name = record.get('product_name');
    var mac = record.get('mac_address');
    var server_url = record.get('server_url');
    var end = record.get('end_date');
    var duration = record.get('duration');
    var feature = record.get('feature');
    var invoice = record.get('invoice_number');
    var view = Ext.getCmp('mainview');
    view.setActiveItem(2);
    Ext.getCmp('name').setValue(company_name);
    Ext.getCmp('product_name').setValue(product_name);
    Ext.getCmp('mac').setValue(mac);
    Ext.getCmp('server').setValue(server_url);
    Ext.getCmp('start').setValue(start_date);
    Ext.getCmp('end').setValue(end);
    Ext.getCmp('duration').setValue(duration);
    Ext.getCmp('expiry').setValue(expiry_date);
    Ext.getCmp('features').setValue(feature);
    Ext.getCmp('license_id').setValue(license_idval);
    Ext.getCmp('invoice').setValue(invoice);
},

it is really long, is there a way I can shorten it, make it more efficient
thanks

A: Something like this?
var FIELDS = {
  "name": "name",
  "start_date": "start",
  // ...
};

and then
Object.keys(FIELDS).forEach(function(key) {
  Ext.getCmp(FIELDS[key]).setValue(record.get(key));
});

A: Try removing variables used to assign values from record and set values directly as shown below
onMylist2ItemTap: function(dataview, index, target, record, e, eOpts) {
    var view = Ext.getCmp('mainview');
    view.setActiveItem(2);
    Ext.getCmp('name').setValue(record.get('name'));
    Ext.getCmp('product_name').setValue(record.get('product_name'));
    Ext.getCmp('mac').setValue(record.get('mac_address'));
    Ext.getCmp('server').setValue(record.get('server_url'));
    Ext.getCmp('start').setValue(record.get('start_date'));
    Ext.getCmp('end').setValue(record.get('end_date'));
    Ext.getCmp('duration').setValue(record.get('duration'));
    Ext.getCmp('expiry').setValue(record.get('expiry_date'));
    Ext.getCmp('features').setValue(record.get('feature'));
    Ext.getCmp('license_id').setValue(record.get('license_id'));
    Ext.getCmp('invoice').setValue(record.get('invoice_number'));
},


text:
Q: Disable/Enable HtmlSelect based on checkbox checked in javascript and asp.net Here is the situation. I have a htmlselect control that when loaded needs to be initially enabled or disabled based upon something that is true or not from the database query. Then I need the user to be able to click on a checkbox to disable or enable the same htmlselect control, ALL without a postback.
Is this possible?

A: Should be something like that:
 <input type="checkbox" onclick="document.getElementById('idOfSelect').disabled=(this.checked)?false:true">

A: You will have to generate the HTML dynamically at runtime, either by generating it from your server code or using a template.  Use the code Dr.Molle suggested above, and insert an enabled attribute for the checkbox / disabled style for the SELECT based on the result from the database query:
<INPUT type-"checkbox" checked ...>
<SELECT ...>

if it is supposed to be enabled or
<INPUT type-"checkbox" ...>
<SELECT disabled ...>

if it is not.
Unfortunately, you can't combine the HTML generation to set the initial state and the dynamic change based on user interaction, unless you use a really sophisticated web framework.
Putting it all together, using a common templating convention, your HTML template might look like this:
<INPUT type="checkbox" ${mySelectIsInitallyEnabled ? "checked" : ""} onclick="document.getElementById('mySelect').disabled=(this.checked)?false:true">
<SELECT id="mySelect" ${mySelectIsInitallyEnabled ? "" : "disabled"}>

    <!-- options ... -->

</SELECT>

A: Using javascript and code-behind I was able to get this to work. Thank you all


text:
Q: How to diff two commits (patches) to the same change in Gerrit? I have two patches to the same commit in Gerrit.  The first was made explicitly as a patch (amendment) to the change but the second one came from another change that was built on top of that change and got approved and merged before this change.  So I need to produce a diff between the two patches.  What makes it more difficult is that they were actually pushed from two different local git branches (I have a habit of forking a new branch for each commit I'll be sending to Gerrit).
So my question is:  how to diff two commits (patches) to the same change in Gerrit?

A: In the diff screen, select a different version instead of Base in the Patch Set selector.

A: It is easy. If you want to show diffs between patchsets just go to "Files" section and look for "Diff against:" - see red box in the image-. It will show you the differences between your current patchset against the patchset you select in the combo - see the blue box -

If you need to compare between different old patchsets, just go to "Patch Sets" (usually at the right top corner of the screen), select one of the old patchsets and then repeat the process with "Diff against".

A: Try
git review -m <CHANGE_NUMBER>,<OLD_PS>[-<NEW_PS>]

But git review AFAIK above git version 1.25.x.x.

A: first fetch the submitted change (git fetch) then checkout the first change, then use git diff origin/<branch> where the submitted commit was merged


text:
Q: Line position of a senetence which has two diffrent font sizes I'm using two different font sizes (13px and 30px) in a single sentence. My question is how do I position the text in the normal position as if it all was in font size 13? At the moment it's below the usual position.
Fiddle

 Click - sign

.aa {font-size:13px;}
span {font-size:30px; position: relative; top: 3px;}

EDIT:

A: The problem is the ' - ' (hyphen) :
You have to play with top in CSS to make it work
See this Fiddle, it works with a string without the hyphen

A: Try this Fiddle.
CSS Code:
.aa {font-size:13px;}
span {font-size:30px; position: relative; top: 3px;line-height: 10px;}

A: Try this.
span {position: relative; top: -1px;}

check this

A: The correct css proporty You would use for this wold be:
line-height:30px;

and if there is a span inside the div, set it to be:
vertical-align:top;


text:
Q: PyPDF2 TypeError when trying to run example from lib I've got PyPDF2 lib from here:
https://github.com/mstamy2/PyPDF2/tree/Python3-3
When trying to run script "Example 1:" from from there see it:
PyPDF2 python versions (2.5 - 3.3) compatibility branch

Traceback (most recent call last):

  File "1.py", line 6, in <module>
    input1 = PdfFileReader(open("document1.pdf", "rb"))
  File "C:\Python33\lib\site-packages\PyPDF2\pdf.py", line 595, in __init__
    self.read(stream)
  File "C:\Python33\lib\site-packages\PyPDF2\pdf.py", line 1097, in read
    streamData = StringIO(xrefstream.getData())
TypeError: initial_value must be str or None, not bytes

What is wrong?

A: It was a problem related to the compatibility within PyPDF2 and Python 3.
In my case, I have solved it by replacing pdf.py and utils.py with the ones you will find here, where they basically control if you are running Python 3 and, in case you are, receive data as bytes instead of strings.


text:
Q: Adding options [keepaspectratio=true, scale = 0.75] to \includegraphics{} in Sweave I have the following R code
<<Q1b1, fig=TRUE>>=
qqnorm(resid(model1), main=NULL)
@

and I would like to add the option [keepaspectratio=true, scale = 0.75] to the \includegraphics{} call so that the above R code chunk generates
\begin{figure}[ht]
\caption{}
\begin{center}
\includegraphics[keepaspectratio=true, scale = 0.75]{filename.pdf}
\label{fig:1}
\end{center}
\end{figure}

I know you can specify the width and height using \SweaveOpt{width=x, height=y} but I want to specify the scale and have it keep the aspect ratio of the figure when it's generated.
Is there an easy way to do this?
Thanks

A: You can set the width for every figure in your Sweave document with \setkeys{Gin} instruction. For example, the following in the preamble of your document makes every figure width 80% of the text width on your page :
\setkeys{Gin}{width=0.8\textwidth}

Otherwise you can add the include=FALSE argument to your code chunk and then create the \includegraphics instruction manually. By default, if your Sweave file is called test.Rnw, then the name of the pdf file generated by the code chunk will be test-Q1b1.pdf. So you can do something like :
<<Q1b1,fig=true,include=false,echo=false>>=
qqnorm(rnorm(100))
@

\begin{figure}[ht]
\caption{}
\begin{center}
\includegraphics[keepaspectratio=true,scale=0.1]{test-Q1b1.pdf}
\label{fig:1}
\end{center}
\end{figure}

However, I've made some tests on your example but the scale parameter doesn't seem to have any effect on the figure here. Others like angle do, though.

A: If you do not have \usepackage{Sweave} in your Sweave file preamble, it will be inserted automatically as the last line before the \begin{document} statement.  Therefore you need to put
\setkeys{Gin}{width=0.8\textwidth}

, which is actually the default of Sweave style file as specified in \usepackage{Sweave}.
AFTER the \begin{document} statement.   See Sweave document (http://www.statistik.lmu.de/~leisch/Sweave/Sweave-manual.pdf) section 4.1.2 for detail.


text:
Q: Unable to get laravel to work with aws application load balancer I have set up an application load balancer on AWS. I am able to access my site but when I try to log in, I was redirected to a page with the message "The page has expired due to inactivity. Please refresh and try again I try taking out the ALB and the site work normally but when put on ALB then I keep getting the inactivity page.
I am using Laravel 5.5, hosted on ubuntu 16.04
I set my session and cache on database hope it will solve the issues but I still got the same problem.
I tried to turn off VerifyCsrfToken middleware, I wasn't redirected to the inactivity page but it keeps redirecting me back to the login page.

A: I managed to find a solution to my problem. My APP_KEY was different for all 3 servers, therefore, causing the problem. After changing it to the same APP_KEY in the .env then everything is working fine.
Hope this will help anyone who encounters a similar problem.


text:
Q: Continuous Deployment Tools with database change control We have setup our Continuous Integration using SVN and Bamboo.
I need a tool that will take the artifacts (.war) and deploy them to a number of environments.
The following are requirements:

*

*Tomcat Support

*Windows Server 2008

*Database change control support

*Configuration support.

The deploy needs to deploy the application and database and configuration changes to numerous different client instances (with different databases).
I have set this up with LiveRebel, but I believe the pricing structure will prevent us from doing what is required (ie a lot of client servers = a lot of agents).
Does anyone else have a similar setup and use another tool ?

A: Before looking into other tools you can check first the existing bamboo plugins and deployments plans.
You can use the "deploy Tomcat application" task from deployment plans for the installation of war files, restarting application, etc
The script task can be used for adding a .bat or .ps scripting in relation to the database changes.
If you decide to go for an external tool you can look into rundeck for some automation: http://rundeck.org/
Bamboo deployments plan documentation: https://confluence.atlassian.com/display/BAMBOO/Deployment+projects#Deploymentprojects-Howdodeploymentprojectswork?


text:
Q: c# property SetValue - doesn't take effect in binded controls I used reflection for changing property. Something like this:
if (obj.GetType().GetProperty(propertyName) != null)
{
   obj.GetType().GetProperty(propertyName).SetValue(obj, value,null);

   return true;`enter code here`
}

The problem is, that I am using binding and I have binded controls to this changed object properties. If I change property value by calling SetValue property change correctly, but it doesn't take effect on e.g. textbox binded on this property.
Does someone know how can I solve this problem?
Here is code how am I binding controls:
((Control)comp).DataBindings.Add(new Binding(comp._BindingProperty.ToString(), comp.Unit.Data, comp._DbField,true));


text:
Q: phpMyAdmin error 1064 I have an error with creating a database for taking customers variables. How do I correct the problem?

A: The dialog box seems to be covering over the useful info.  What parameters do you have for Gender?
I think ENUM needs strings, not numbers.


text:
Q: Veracrypt options disabled I would like to encrypt my whole computer with Veracrypt, but when I try to, the buttons are hidden :
I want a normal system encryption, but the whole drive too, which is impossible here.
I tried to uninstall VeraCrypt, install it again, reboot my computer but it hasn't worked.

Also, if this finally work, I was planning to take Twofish Serpent encryption algorithm and SHA-512 hash algorithm.
Do you think it's a good choice ?
Thanks

A: You cannot encrypt the whole volume because you have secureboot enabled or you use some other type of encryption that interferes with the boot loading.
Disable secure boot, set your UEFI in BIOS-compatible mode, install the OS and then you can use whole drive encryption.
If you do need to boot from a partition larger than 2TB then you do need to leave GPT/UEFI boot on, but if not, there is no reason not to use MBR.


text:
Q: how to start one flux after completion of another? how can i start Flux after completion of Flux? Flux doesn't depend on result of Flux.
I thought operation then() should do the work, but it just return mono. So what is the correct operator?

A: Flux.thenMany is the operator that you need
    abstract Flux<Integer> flux1();
    abstract Flux<String> flux2();

    public Flux<String> flux2AfterFlux1(){
        return flux1().thenMany(flux2());
    }

A: My reply is late, so you have probably either figured this out, or moved on.  I need to do the same thing, so I seem to have achieved this by using Flux.usingWhen().  I need to obtain IDs from my database that exhibit a certain property.  After retrieving these IDs, then I need to get some information about these IDs.  Normally, a join would work, but I am using MongoDB, and joins are horrible, so it is better to do separate, sequential queries.  So let's say I have a Mongo reactive repository with a method called Flux<String> findInterestingIds().  I have another method in the same repository called Flux<String> findInterestingInformation(String[] interestingIds) that I need to feed the IDs found in the call to the previous method.  So this is how I handle it:
Mono<List<String>> interestingIdsMono = myRepo.findInterestingIds()
    .collectList();
Flux.usingWhen(interestingIdsMono,
    interestingIds -> myRepo.findInterestingInformation(interestingIds),
    interestingIds -> Flux.empty().doOnComplete(() -> log.debug("Complete"));

The cleanup function (third parameter) was something that I don't quite yet understand how to use in a good way, so I just logged completion and I do not need to emit anything extra when the flux completes.
ProjectReactor used to have a compose function that is now called transformDeferred, and I had some hopes for that, but I do not quite see how it would apply in this type of situation.  At any rate, this is my attempt at it, so feel free to show me a better way!


text:
Q: Não consigo persistir os dados no Banco Acho que estou fazendo algo de errado nesta classe, pois ela é a unica do meu sistema que não está persistindo no Banco de Dados.
O que eu estou esquecendo de fazer para ela funcionar? O método incluir()? Se eu executar um var_dump($log), antes de chamar persist($log), o resultado é uma variável com todos os dados necessários.
E o pior de tudo é que não gera nenhum erro também.
Classe Log.php
namespace JN\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="logs")
* @ORM\HasLifecycleCallbacks
*/
class Log {
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue
 */
private $id;

/**
 * @ORM\Column(type="datetime")
 */
private $data;

/**
 * @ORM\Column(type="string", length=100)
 */
private $tabela;

/**
 * @ORM\Column(type="integer")
 */
private $id_usuario;

/**
 * @ORM\Column(type="string", length=200)
 */
private $usuario;

/**
 * @ORM\Column(type="integer", nullable=true)
 */
private $id_empresa;

/**
 * @ORM\Column(type="string", length=200, nullable=true)
 */
private $empresa;

/**
 * @ORM\Column(type="string", length=20)
 */
private $ip;

/**
 * @ORM\Column(type="string", length=100)
 */
private $evento;

/**
 * @ORM\Column(type="text")
 */
private $sql;

/**
 * @ORM\Column(type="text", nullable=true)
 */
private $valores_antigos;

/**
 * @ORM\Column(type="text", nullable=true)
 */
private $valores_novos;

/**
 * @ORM\Column(type="datetime")
 */
private $created_at;

/**
 * @ORM\Column(type="datetime")
 */
private $updated_at;

/*--------------------------Filters --------------------------------------- */
/**
 *
 * @ORM\PrePersist
 * @ORM\PreUpdate
 */
public function updatedTimestamps()
{
    $this->updated_at =new \DateTime('now');

    if ($this->created_at == null) {
        $this->created_at=new \DateTime('now');
    }
}

/*--------------------------Constructor --------------------------------------- */

/*--------------------------Relations --------------------------------------- */

/*--------------------------Gets and Sets --------------------------------------- */
/**
 * @return mixed
 */
public function getId()
{
    return $this->id;
}

/**
 * @return mixed
 */
public function getData()
{
    return $this->data;
}

/**
 * @param mixed $data
 */
public function setData($data)
{
    $this->data = $data;
}

/**
 * @return mixed
 */
public function getTabela()
{
    return $this->tabela;
}

/**
 * @param mixed $tabela
 */
public function setTabela($tabela)
{
    $this->tabela = $tabela;
}

/**
 * @return mixed
 */
public function getIdUsuario()
{
    return $this->id_usuario;
}

/**
 * @param mixed $id_usuario
 */
public function setIdUsuario($id_usuario)
{
    $this->id_usuario = $id_usuario;
}

/**
 * @return mixed
 */
public function getUsuario()
{
    return $this->usuario;
}

/**
 * @param mixed $usuario
 */
public function setUsuario($usuario)
{
    $this->usuario = $usuario;
}

/**
 * @return mixed
 */
public function getIdEmpresa()
{
    return $this->id_empresa;
}

/**
 * @param mixed $id_empresa
 */
public function setIdEmpresa($id_empresa)
{
    $this->id_empresa = $id_empresa;
}

/**
 * @return mixed
 */
public function getEmpresa()
{
    return $this->empresa;
}

/**
 * @param mixed $empresa
 */
public function setEmpresa($empresa)
{
    $this->empresa = $empresa;
}

/**
 * @return mixed
 */
public function getIp()
{
    return $this->ip;
}

/**
 * @param mixed $ip
 */
public function setIp($ip)
{
    $this->ip = $ip;
}

/**
 * @return mixed
 */
public function getEvento()
{
    return $this->evento;
}

/**
 * @param mixed $evento
 */
public function setEvento($evento)
{
    $this->evento = $evento;
}

/**
 * @return mixed
 */
public function getSql()
{
    return $this->sql;
}

/**
 * @param mixed $sql
 */
public function setSql($sql)
{
    $this->sql = $sql;
}

/**
 * @return mixed
 */
public function getValoresAntigos()
{
    return $this->valores_antigos;
}

/**
 * @param mixed $valores_antigos
 */
public function setValoresAntigos($valores_antigos)
{
    $this->valores_antigos = $valores_antigos;
}

/**
 * @return mixed
 */
public function getValoresNovos()
{
    return $this->valores_novos;
}

/**
 * @param mixed $valores_novos
 */
public function setValoresNovos($valores_novos)
{
    $this->valores_novos = $valores_novos;
}

/**
 * @return mixed
 */
public function getCreatedAt()
{
    return $this->created_at;
}

/**
 * @return mixed
 */
public function getUpdatedAt()
{
    return $this->updated_at;
}
}

Classe LogService.php
namespace JN\Entity;
use Doctrine\ORM\EntityManager;
class LogService {

private $em;
private $app;

public function __construct(EntityManager $em, $app)
{
    $this->em=$em;
    $this->app=$app;
}

public function incluir($sesion=null,$valoresNovos=null)
{
    try{
        $log = new Log();
        $log->setEmpresa('');
        $log->setIdEmpresa(0);
        $log->setIdUsuario(0);
        $log->setUsuario('');
        $log->setData(new \DateTime('now'));
        $log->setIp($_SERVER["REMOTE_ADDR"]);
        $log->setEvento('Inclusão');
        $log->setTabela($sesion['tabela']);
        $log->setSql($sesion['sql']);
        $log->setValoresAntigos('');
        $log->setValoresNovos($valoresNovos);
        $this->em->persist($log);
        $this->em->flush();
        return $log;
    }catch (\Exception $ex){
        $this->app->abort(406, 'Erro: ('.$ex->getCode().') '.$ex->getMessage());
        //return ['sucesso'=>false, 'Erro: '=>$ex->getCode().': '.$ex->getMessage()];
    }
}

A: Achei o problema. Somente para constar nos autos.
O problema estava que eu tinha uma coluna com o nome SQL e Data, estas 2 palavras são reservadas e não poderia ser usadas. Depois de muito tentar se resolveu trocando elas.
Obrigado a todos pela ajuda.


text:
Q: iOS: Problem with my ViewController containing a TableView in a Tab Bar that is displaying in black or with the size bad displayed I have a Tab Bar with some view controllers, and one of the controller contains a TableView. My problem is that it appears in black 90% of the time.
May be it is linked I think to the constraint, the size, because if I touch the constraint, the size, the frame origin, some times it is not black.
Impossible to avoid the blackscreen, and a tableview well displayed with the good size, at the good position. It is very frustrating because all is working on the other 4 viewcontrollers except that view that contains the tableview.
Storyboard viewcontroller:

viewController on simulator with no constraints:

viewControlelr on simulator with constraints (whatever the change I do, it doesn't display correctly. The buttons disappear, the label too).

I tried the solutions in this tickets with no success:
self.definesPresentationContext = true

Link 1
Link 2
Link 3
(I precise that I am trying to find a solution to this, not adding lots of navigationcontrollers after the tabBar or changing the tab bar method itself)
Any suggestions?
EDIT:  Here is all the constraints:

A: You should use the navigationController for each view controller of your tab bar because it is a bug in the storyboard that haven't been resolved until today
1/ Put the line self.definesPresentationContext = true     in each view of the tabbarviewcontroller
2 / Editor/Embed/NavigationController for each view of the tabBarViewController
3 / Remove "Show Navigation Bar " for each Navigation Controller of all the viewControllers of the TabBarViewController
4 / Instead of
let vc = self.tabBarController!.viewControllers![1] as! YourViewController

Put this line :
        let nc = self.tabBarController!.viewControllers![1] as! UINavigationController
        let vc: YourViewController = nc.viewControllers[0] as! YourViewController

5 / resolve all the constaints issues (in red, and in yellow in the storyboard)
6 / Remove the app before compilation on simulator or device
7 / Before the compilation, do a hard clean (Cmd + option + Shift + k)
8 / optional : in some case, close XCode, and relaunch it


text:
Q: AngularJS Clicking on the link is opens the textarea I know that is function in css -> target but she change url address, I need do this effect without no url changes. And here is question, I know that I can do it in pure js, but the most important question is, can I do it in AngularJS ? If yes can someone explain me how to get this effect?
IMAGE HERE
Thanks

A: If you want to hide an item from a div by clicking on it you can use "ngHide".
For more information here


text:
Q: How to convert a JSON into a Tree like object using node.js javascript? How to convert a JSON into a Tree like object using node.js javascript? In Java we have a jackson library that converts a JSON into Tree object and I am trying to find something equivalent in JavaScript?

A: Unless your JSON contains a unicode line separator or paragraph separator it is already a subset of Javascript, and evaulating it as an expression will resolve to an object that is already a tree like data structure. Suppose you had the JSON in a file called config.json:
{
  "test": {
    "foo": {
      "hello": "bob"
    },
    "bar": {
      "world": "cloud"
    }
  }
}
Then you can just include that as JavaScript, EG with require:
const config = require( './config.json' );

and config will be an object with one property (test), which itself is an object with two properties "foo" and "bar", which are both objects themselves (see how it is tree-like):
config.foo.hello === 'bob';

If you don't trust that the file actually contains the JSON you expect (suppose it was uploaded by a user), you can load the file into a string (which I'm assuming you already have), and then use JSON.parse to get the same object as the JSON evaluated to before.


text:
Q: Where are rhev templates stored? I would like to modify a Red Hat Enterprise Virtualization (RHEV) template. I know I could just use an existing machine and create a new template from this machine - but it would require updating other references too. So I thought I could just "mount" the template file, do a few edits on the filesystem and be done.
But I can not find the templates - can anyone enlighten me, where these templates are stored? Or in which format, so I know what to look for.

A: The template disk image is stored on the storage domain along with the VM  disk images and it can be located via the api or the database. However,  if you change anything on the template you will break every VM created as a linked clone which is why there is no built in option to modify templates.


text:
Q: How to find which pom item introduces a specific external dependency? I want to find which pom item imports the following nacos-api:1.0.0

I thought it is this item which depends on it

but the details of it is as below:

so it is probably not? are there any ways to find which pom item introduces a specific external dependency, especially on IDEA?
maven tree doesn't help
    mvn dependency:tree -Dincludes=nacos-client:1.0.0
    [INFO] Scanning for projects...
    [INFO]
    [INFO] ------------------------------------------------------------------------
    [INFO] Building user 0.0.1-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    [INFO]
    [INFO] --- maven-dependency-plugin:3.0.1:tree (default-cli) @ user ---
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 2.172 s
    [INFO] Finished at: 2020-03-30T03:06:07+08:00
    [INFO] Final Memory: 37M/361M
    [INFO] ------------------------------------------------------------------------

A: There is no such single action. But it is possible to find the corresponding for the library pom with these steps:

*

*F4 (Go to source action) on selected item in External library will open this library configuration dialog:

*Then use Alt+F7 (Find usages action) to show the module where this library is used:

*Then you can find this module in Maven tool window (use speed search for example to locate it more easily), select it in the tree and navigate to corresponding pom using F4 (Go to source action) again:


text:
Q: MySQL query caching - what happens if Server runs out of RAM? so I have enabled query caching on my server but now from the 8 GB RAM there is almost non left! CPU is around 3% !
Now what happens when there is no more RAM left?
Will this just increase CPU load?
Thank

A: If no more RAM is left and the server still needs more memory, it will start swapping if not already started. When no more RAM or swap is available, the server will crash. Generally, the CPU load may increase as a result of the more required processing and degraded performance.
The best thing to do is trying to determine the reason for this. You need to check which processes are using more memory.

A: if a server starts swapping, it discards the oldest values or whatever there is policy regarding eviction of stored query cache..query caching is transient type of store.


text:
Q: Printing Memory Address I ran the following program  on Cygwin on Windows8.
#include<iostream>
#include <stdio.h>
using namespace std;
int main(){
char c1 = 'a';
char c2 = 'b';
int i1 = 1;
float l1 = 100;
float f1 = 3.14;
double d1 = 1.424;
int i2;
char c3;
int i3;
printf("&c1 -> %u\n", (unsigned long)&c1);
printf("&c2 -> %u\n", (unsigned long)&c2);
printf("&i1 -> %u\n", (unsigned long)&i1);
printf("&l1 -> %u\n", (unsigned long)&l1);
printf("&f1 -> %u\n", (unsigned long)&f1);
printf("&d1 -> %u\n", (unsigned long)&d1);
printf("&i2 -> %u\n", (unsigned long)&i2);
printf("&c3 -> %u\n", (unsigned long)&c3);
printf("&i3 -> %u\n", (unsigned long)&i3);
}

My laptop gave the results below.
$ ./a.exe
&c1 -> 2337487
&c2 -> 2337486
&i1 -> 2337480
&l1 -> 2337476
&f1 -> 2337472
&d1 -> 2337464
&i2 -> 2337460
&c3 -> 2337459
&i3 -> 2337452

I understand that each data type has its own size and takes up memory addresses according to the size. For example, in this case, since char type has only 1 byte size, the variable c1 takes up 1 memory address(2337487), and the next variable c2 starts from the address 2337486. However, I was confused by that i1 starts from 2337480. If c2 is also a char type variable, shouldn't it take up only one address? And i1 start from 2337485?
I guess it's something to do with a compiler, but don't understand how it works.Would anyone give me some advice?

A: This is because of data structure alignment.
For example, when the computer's word size is 4 bytes (a byte means 8 bits on most machines, but could be different on some systems), the data to be read should be at a memory offset which is some multiple of 4. When this is not the case, e.g. the data starts at the 14th byte instead of the 16th byte, then the computer has to read two 4 byte chunks and do some calculation before the requested data has been read, or it may generate an alignment fault. Even though the previous data structure ends at the 13th byte, the next data structure should start at the 16th byte. Two padding bytes are inserted between the two data structures to align the next data structure to the 16th byte.

A: It's a compiler optimisation: somtimes it's faster when the allocated memory is not a solid block.


text:
Q: React generates infinite errors while fetching from api I am new to React.js, and I am trying to fetch from an api into a state . But when I do this, after a change in the json code from the api or after some time, I get infinite errors: TypeError: Failed to fetch and Posts.js:10 GET http://localhost:3000/data net::ERR_CONNECTION_REFUSED .
My posts controller:
import React, { useState } from 'react';
import Post from './Post';
import axios from 'axios';

const Posts = () => {
    const [posts, setPosts] = useState([]);

    fetch("http://localhost:3000/data")
    .then(res => res.json())
    .then(
      (result) => {
        setPosts((prev) => prev = result);
      }
    )
    .catch((error) => {
        console.log(error);
      });

    return (
        posts.map((post, index) => (
            <Post name={post.name} content={post.content} key={index}/>
        ))
    );
}
export default Posts;

A: First thing you need to wrap api call in function. Otherwise it will re-render every time component renders:
import React, { useState,useEffect } from 'react';
import Post from './Post';
import axios from 'axios';

const Posts = () => {
    const [posts, setPosts] = useState([]);

    useEffect(() => {
    fetchPost();
     },[])

    const fetchPost = () => {
        fetch("http://localhost:3000/data")
        .then(res => res.json())
        .then(
        (result) => {
          setPosts((prev) => prev = result);
         }
        )
        .catch((error) => {
         console.log(error);
        });
     }

    return (
        posts.map((post, index) => (
            <Post name={post.name} content={post.content} key={index}/>
        ))
    );
}
export default Posts;

If you need only api when component than pass empty array as dependency. Otherwise variable in which you want to run fetchApi in useEffect([] <- here).
Posts.js:10 GET http://localhost:3000/data net::ERR_CONNECTION_REFUSED

This error generally comes when your backend is not working


text:
Q: Cplex Python Gaps How can I print the gaps(each iteration) like OPL's engine in Python? I want to keep the gaps like this:
     Nodes                                         Cuts/
   Node  Left     Objective  IInf  Best Integer    Best Bound    ItCnt     Gap

      0     0     5627,2325   167                   5627,2325       11
*     0+    0                         8610,2984     5627,2325            34,65%
      0     0     5627,2325   186     8610,2984     Cuts: 157      158   34,65%
      0     0     5627,2325   186     8610,2984      Cuts: 38      188   34,65%
*     0+    0                         8100,9408     5627,2325            30,54%
*     0+    0                         7058,3430     5627,2325            20,28%
      0     2     5627,2325   186     7058,3430     5678,4051      188   19,55%
Elapsed time = 1,00 sec. (349,63 ticks, tree = 0,02 MB, solutions = 3)
*    86+   13                         7029,5430     5678,5253            19,22%
*   128+   12                         7026,1830     5678,5253            19,18%
*   170+   12                         7025,9430     5724,8207            18,52%
*   227+   78                         6972,1152     5757,6981            17,42%
*   415+  157                         6907,3358     5757,6981            16,64%
*   562+  241                         6787,0188     5757,6981            15,17%

I am using the solve_details.gap, but it returns the solution gap.
>>> model.solve_details.gap

A: In Easy optimization with python I shared get solution 1 by 1
from docplex.mp.model import Model
from docplex.mp.progress import *

mdl = Model(name='buses')
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*500 + nbbus30*400)

mdl.parameters.mip.limits.solutions=1

while (1==1):
    sol=mdl.solve(log_output=False)
    for v in mdl.iter_integer_vars():
       print(v," = ",v.solution_value)

    print("objective = ",sol.get_objective_value())
    print("best bound = ",mdl.solve_details.best_bound)
    print("mip gap = ",mdl.solve_details.mip_relative_gap)

    print("status : ",mdl.solve_details.status)
    if ("optimal solution" in str(mdl.solve_details.status)):
        break

that could help you


text:
Q: Aggregate item data from Zabbix? I would like to have Zabbix monitor different items (on the same host, or on different hosts) and assign a value depending on the outcome, then have it fire (or not) a trigger depending on the aggregation of these values.
For instance, let's imagine a cluster of 3 database nodes.  Zabbix monitors every one of them via ping and increases a global variable by 1 if the node is reachable.  After a round, the variable could have the following values:

*

*3 => (all nodes are up) cluster is OK

*2 => (one node is down) cluster is still working but in degraded state

*1 => (two nodes are down) cluster is working but no replication is done

*0 => (all nodes are down) cluster is down

Then Zabbix fires a trigger with WARNING severity if value is 1, and a trigger with HIGH severity if value is 0.
Is there a way to do this natively or via a module, without having to use the APIs?  Thanks.

A: In order to aggregate data from several items into one, you can either use aggregate items or calculated items. Aggregate items allow to aggregate all items with the same key in the specified host groups, whereas calculated items allow arbitrary operations on items based on a formula.
In order to have two triggers with different severities, you may find trigger dependencies useful. Here, a trigger with a lower dependency would depend on a trigger with a higher dependency.

A: Thanks.  Following your advice, I managed to do what I wanted.  Here are the steps:

*

*create a host group my_DB_cluster and populate it with the nodes' IP addresses;

*create a new template my_template and add it to the host group my_DB_cluster;

*inside my_template, create a new item with key grpsum[my_DB_cluster,icmpping,last,0];

*create a new value mapping and associate it to the item's results, in order to get a message ("cluster is down") instead of a simple value (0);

*inside my_template, create triggers with different severity on key grpsum[my_DB_cluster,icmpping,last,0].


text:
Q: RSA-Encryption and Decryption in Webapp (JavaScript) and iOS-App (Swift) I am building a webapp (JavaScript) and an iOS-App (Swift). The problem is that the iOS-app and the webapp both should create public and private keys and exchange these.
I tried using JSEncrypt (https://github.com/travist/jsencrypt) for the web-part and CryptorRSA for the mobile part.
When creating a public key in JSEncrypt I get something like this:
  -----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC68ROkNzyo01gJCvo94mI/SswF
2FWDk4nvjbkcFeDWUZFd8t/2whnNJv9Nj+Y0VO2LSu5fVm6FIuGiesz1EzaBNkIL
kfphsSJjE8GGRqHYgdUgidv1mgkF+86Uk7hDDYtv4gUTLALXdHwDpsu28ww57ISA
Gxxidh7oyR74+cq46wIDAQAB
-----END PUBLIC KEY-----

Then I try to encrypt it using CryptorRSA:
     let key = try? CryptorRSA.createPublicKey(withPEM: """
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC68ROkNzyo01gJCvo94mI/SswF
2FWDk4nvjbkcFeDWUZFd8t/2whnNJv9Nj+Y0VO2LSu5fVm6FIuGiesz1EzaBNkIL
kfphsSJjE8GGRqHYgdUgidv1mgkF+86Uk7hDDYtv4gUTLALXdHwDpsu28ww57ISA
Gxxidh7oyR74+cq46wIDAQAB
-----END PUBLIC KEY-----
""")

  if let k = key {
        print("1");
        if let text = try? CryptorRSA.createPlaintext(with: "hallo Welt!", using: String.Encoding.utf8) {
            print("2");
            let encryptedData = try? text.encrypted(with: k, algorithm: .sha1)
            print(encryptedData)
            if let d = encryptedData {
                print(try? d.base64String)
            }
        }

    }

Which returns:
chvRmbYpzNFVL5HPW9JP3BrkonSbcmObdfKteXfCr9Yw3Gycr4irqEjxroBFKli+lVF89lWaxTRCy2prn7Athbi7EGdG5y6dITyFWGf/p91NAAbWdQlz+AOsWb6lPs3MfBqHnqG2O1vDrh5yEGImM+40QvZB9yMLGTA1Y2LPRe157ymFOp3C4aW7/+we9a7aQiCw6QavcsUvdhg=

But when I try to decrypt it after that in JSEncrypt it just results in an error.

A: An indirect solution for the problem is to use a library which is made for "easy" crypto usage across different platforms.
I finally decided to use sodium/libsodium/nacl to do symmetric and asymmetric encryption across many platforms.


text:
Q: How to overlay a new image onto a fixed container when scrolling? I'm trying to replicate this overlay phone effect from this website:
https://www.beemit.com.au/
Basically, when you scroll down, the contents inside the fixed div (phone) also change.
I cannot grasp my head around the revealing effect created when you scroll down. I have only managed to create the fixed div and the various sections on the webpage.

A: Here's a simple version of the overlay-on-scroll.
There are 3 elements, the first image you want to be shown in the 'phone', the second image which gradually gets revealed and the footer element. They have different z-indexes so footer is behind both first and second and second is behind first.
The phone has a fixed position so it doesn't move on scrolling. The footer is placed relative to the body (or whatever container you have) just out of view at 100%.
We introduce a simple event listener on scrolling which tests whether there is an overlap between the footer and the phone. If there is then we set the height of the first image element to be its original height minus the overlap. This reveals the bottom part of the second element.
Without seeing your code I can't tell whether you need more sophistication (for example, you have to be aware of stacking contexts if your phone and footer are not in the same one).

const footer = document.querySelector('.footer');
const first = document.querySelector('.first');
const firstBottom = first.getBoundingClientRect().bottom;
const firstHeight = firstBottom - first.getBoundingClientRect().top;

function checkOverlay() {
  const top = footer.getBoundingClientRect().top;
  if ( top < firstBottom) {
    first.style.height = firstHeight - firstBottom + top + 'px';
  }

}
body {
  width:100vw;
  height: 100vh;
  overflow-y: scroll;
  overflow-x: hidden;
}
.first, .second {
  position: fixed;
  top: 50%;
  left: 50%;
  border: 1px solid black;
  width: 20vmin;
  height: 30vmin;
  overflow:hidden;
}

.first {
  background-image: linear-gradient(magenta, pink);
  z-index: 0;
}
.second {
  background-image: linear-gradient(cyan, lime);
  z-index: -1;
}

.footer {
  width: 100%;
  height: 50%;
  background-image: linear-gradient(red,blue);
  position: relative;
  top: 100%;
  z-index: -2;
}


text:
Q: Print large macro block from Lua to TeX I have a rather large block of TeX macro code that is no problem to do in TeX but I'd like to create the macro in Lua instead
The macro contains various TeX macro characters (\, %, [, ])
How can I easily format this macro easily without having to really mess with it much by hand so I can use tex.print to get it into TeX?
I've tried using [[ ]] and \n after the %'s and various other things but nothing makes TeX happy or it can't find the macro if it does work.

A: You probably talking about heredoc syntax in Lua, guessing from your comment

I've tried using [[ ]]

Let us assume you are writing a macro that you need to capture a rather long piece of text.
You can enclose it as:
    [[..]]

If it encloses other square brackets, you need to escape it as:
    ([=[[[Anger Management]]
    ...
    ]=])

Here is a full minimal:
\documentclass{article}
\usepackage[listings]{tcolorbox}
\begin{document}
\begin{tcblisting}{}
\ttfamily \directlua{
 tex.sprint([=[
    [[Anger Management]]Mild-mannered timid businessman Dave Buznik who works for a pet clothing company out of New York City. He's got an abrasive boss named Mr. Frank Head who frequently takes credit for his work and steps on him in return. He's got a loving girlfriend, Linda, whose best friend is her condescending college ex, Andrew. But when a misunderstanding aboard an airplane goes haywire, Dave is ordered by the court to undergo anger management therapy at the hands of specialist Dr. Buddy Rydell, who is an unpredictable, psychopathic character. As the relationship between Dave and Buddy becomes more tense, when the unorthodox treatment wreaks havoc Dave's life, and Buddy might be the only one who can save him from a problem he recognizes right away in his patient, that could only get worse.
]=])
}
\end{tcblisting}
\end{document}

This should produce the following output:

As discussed earlier programming needs patience.

A: While it is unclear from your question what you want to do, I try to answer it.

*

*Never use \directlua, use the environment luacode* from the luacode package.

*When using the lua functions tex.sprint() or tex.print() use "-2" as the first parameter. This is a catcode table with safe catcodes. All characters such as %, $, \ have the meaning "letter" and thus don't do harm.

*If you do need a command name in between, use tex.tprint({},{},{},{}...). In these tables you can optionally give the catcode as the first element: tex.tprint({"\\command{"},{-2,"%$~safe"},{"}"}) which yields:
\command{%$~safe}

with the "meaningless" characters %$~safe


text:
Q: Django Admin Page missing CSS I saw this question and recommendation from Django Projects here but still can't get this to work. My Django Admin pages are not displaying the CSS at all.

This is my current configuration.
settings.py
ADMIN_MEDIA_PREFIX = '/media/admin/'

httpd.conf
<VirtualHost *:80>
    DocumentRoot /home/django/sgel
    ServerName ec2-***-**-***-***.ap-**********-1.compute.amazonaws.com
    ErrorLog /home/django/sgel/logs/apache_error.log
    CustomLog /home/django/sgel/logs/apache_access.log combined
    WSGIScriptAlias / /home/django/sgel/apache/django.wsgi

    <Directory /home/django/sgel/media>
        Order deny,allow
        Allow from all
    </Directory>

    <Directory /home/django/sgel/apache>
        Order deny,allow
        Allow from all
    </Directory>

    LogLevel warn

    Alias /media/ /home/django/sgel/media/

</VirtualHost>

<VirtualHost *:80>
   ServerName sgel.com
   Redirect permanent / http://www.sgel.com/
</VirtualHost>

In addition, I also ran the following to create (I think) the symbolic link
ln -s /home/djangotest/sgel/media/admin/ /usr/lib/python2.6/site-packages/django/contrib/admin/media/
UPDATE
In my httpd.conf file,
User django
Group django

When I run ls -l in my /media directory
drwxr-xr-x 2 root root 4096 Apr  4 11:03 admin
-rw-r--r-- 1 root root    9 Apr  8 09:02 test.txt

Should that root user be django instead?
UPDATE 2
When I enter ls -la in my /media/admin folder
total 12
drwxr-xr-x 2 root root 4096 Apr 13 03:33 .
drwxr-xr-x 3 root root 4096 Apr  8 09:02 ..
lrwxrwxrwx 1 root root   60 Apr 13 03:33 media -> /usr/lib/python2.6/site-packages/django/contrib/admin/media/

The thing is, when I navigate to /usr/lib/python2.6/site-packages/django/contrib/admin/media/, the folder was empty. So I copied the CSS, IMG and JS folders from my Django installation into /usr/lib/python2.6/site-packages/django/contrib/admin/media/ and it still didn't work

A: There's a couple of problems here, both to do with your symbolic link.
Firstly, the source and target needed to be the other way round (I always get that wrong myself).
Secondly, you have used a completely different path to the one you've specified in your Apache conf - djangotest/sgelections vs django/sgel.
Do it like this:
cd /home/django/sgel/media/
ln -s /usr/lib/python2.6/site-packages/django/contrib/admin/media/ admin

A: The easy solution is to change a line in your wsgi.py file
    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()

becomes
    from django.core.wsgi import get_wsgi_application
    from dj_static import Cling

    application = Cling(get_wsgi_application())

Easiest way to have the Admin CSS show properly. Cheers

A: Another method I just found, and it looks like a properly supported method.
Make sure you have the staticfiles module in your settings. Also configure the STATIC_ROOT option.
https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#module-django.contrib.staticfiles
Create your /static/ folder and set permissions.
Configure apache with a /static/ alias.
alias /static <path to project root>/static/
<Directory "<path to project root>/static/">
    Order deny,allow
    Allow from all
</Directory>

then from your project folder run
sudo python manage.py collectstatic [-n to do a dry run]

All this looks like it does is copy the admin static files to your projects folder for web serving.

A: So the first thing you want to do is change directory to your static folder and add a symlink.
I did this with a virtual environment so I use
ln -s ~/virtualenv/my-virtualenv/lib/python2.x/site-packages/django/contrib/admin/static/admin admin

The next step is to edit your httpd.conf

Alias /static/admin/ ~/mysite/static/admin/

Restart your apache server and voila!

A: In Firebug, use the Net tab and see the requests being made by your browser for the css files. see the response for your requests there itself. I think you will find the problem there.
I recently had the same problem. The problem was when my browser requests for the css files, the response contained the contents of my project's login html page. I don't remember now that how i solved my problem. I will try to recollect and post the solution here.
Let me know if you have the same problem.

A: I had the same problem but none of this helped really. Turned out my version of grappelli was outdated. (https://github.com/sehmaschine/django-grappelli) I uninstalled it and then re-installed with a newer version.
        pip install django-grappelli==2.4.4
If you are using an admin skin like me, you might consider updating it.

A: In addition to correcting the symbolic link as Daniel Roseman suggested, you'll need to make sure that the user that is running Apache has read access to the admin media.

*

*If you do ls -l in your media directory, do you see the symbolic link?

*If you cd admin from your media directory, does it work? If you then run ls can you see the admin media?

*Does the user that runs Apache have read access to the admin media?

If all those things work, then please update your question with your current configuration and results of those commands and we'll take another look.
Response to Update: Ok, the permissions look ok. It looks like you've got the directory structure in your media directory a little bit wrong.
The fact that /usr/lib/python2.6/site-packages/django/contrib/admin/media/ was empty is disturbing, too. Once you solve the immediate problem you may want to look into reinstall django in the expected place.
Anyways, here's how the structure should look:
$ cd media
$ ls -la
drwxr-xr-x 2 root root 4096 Apr 13 03:33 .
drwxr-xr-x 3 root root 4096 Apr  8 09:02 ..
lrwxrwxrwx 1 root root   60 Apr 13 03:33 admin -> /usr/lib/python2.6/site-packages/django/contrib/admin/media/
-rw-r--r-- 1 root root    9 Apr  8 09:02 test.txt

That is, inside of the media/ directory their should be a link called admin directly to the /admin/media directory of your django installation.
To fix what you've got, inside of the media/admin/ directory run:
rm media
cd ..
rmdir admin

and then re-create the symlink as suggested in Daniel Roseman's answer.

A: can you run
python
>>> import django
>>> print django.__file__

the other question - does your normal media placed into the /home/django/sgel/media/ work (i.e. served by Apache as expected?)

A: Try to add
Options FollowSymLinks

to your
<Directory /home/django/sgel/media>
    Order deny,allow
    Allow from all
</Directory>

so that you end up with
<Directory /home/django/sgel/media>
    Options FollowSymLinks
    Order deny,allow
    Allow from all
</Directory>

A: I'm not sure if this will help but in my config file I have:
    Alias /adminmedia/ /var/lib/python-support/python2.6/django/contrib/admin/media/

    <Directory "/var/lib/python-support/python2.6/django/contrib/admin/media">
            AllowOverride None
            Options FollowSymLinks
            Order allow,deny
            Allow from all
    </Directory>

It works but I have my server set up for development/testing only.

A: i used to have the same problem, i solved it by using the FireFox plugin firebug, which tells you where is your site looking for the media files, also how did you check the contents of the admin/media folder to see if they were empty ?

A: I know it's been solved but I think it's worthy to share my solution.
I simply added the alias in apache and it worked so far.
    Alias /static/admin/ /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media/
    Alias admin/media/ /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media/

A: Did you try setting the value for
MEDIA_ROOT
MEDIA_URL
ADMIN_MEDIA_PREFIX
correctly?
I mean that the MEDIA_ROOT url and ADMIN_MEDIA_PREFX should have a different value. Please check these values in your settings.py and try again.
Hope this helps.

A: I encountered the same problem while running the Bitnami Django Stack on Win32  (builtin development server)
I solved the issue by finding the missing CSS folders in the installation and changing settings.py.
# Additional locations of static files
STATICFILES_DIRS = (
    'C:/Program Files/BitNami DjangoStack/apps/django/django/contrib',
)

This will help you get started developing... It's not optimal. Don't forget the trailing comma :)

A: If nothing helps, add the following to urls.py
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {

            'document_root': '/usr/lib/python2.4/site-packages/django/contrib/admin/media/',

           'show_indexes' : True,

        }),

This is independent of apache or nginx

A: when we talked about django, we should know which edition we run on. "ADMIN_MEDIA_PREFIX" is used in django before edition of 1.4, see
The included administration app django.contrib.admin has for a long time
shipped with a default set of static files such as JavaScript, images and
stylesheets. Django 1.3 added a new contrib app django.contrib.staticfiles
to handle such files in a generic way and defined conventions for static
files included in apps.
Starting in Django 1.4, the admin's static files also follow this convention,
to make the files easier to deploy. In previous versions of Django, it was
also common to define an ADMIN_MEDIA_PREFIX setting to point to the URL where
the admin's static files live on a Web server. This setting has now been deprecated
and replaced by the more general setting STATIC_URL. Django will now expect to
find the admin static files under the URL <STATIC_URL>/admin/.

https://docs.djangoproject.com/en/dev/releases/1.4/.
I am using django 1.4, and still confusing about this.

A: If you're using virtualenvwrapper like me, then this is how you can find your admin media files and fix it:
workon <project_name>
export DJANGO_BASEFILE=`python -c 'import django; print django.__file__'`
export DJANGO_BASEDIR=$(dirname ${DJANGO_BASEFILE})
ln -s $DJANGO_BASEDIR/contrib/admin/media <project_dir>/media/admin

Replace the <project_name> to your virtualenvwrapper environment name and project_dir to your working directory. :)

A: In my case, this issue occured after setting up the nginx on Ubuntu server. On analyzing the file structure, I found that admin folder was missing from the staticfile directory (the location where django looks for static files to add to STATIC_ROOT). So, I copied the admin folder (inside static directory) to the server's static folder.
Then run
python manage.py collectstatic

And now, django collects the 130 files required for admin page styling.

A: I want to add to Adam's Solution,
first you need to install dj-static in cpanel. So add dj-static==0.0.6 in requirements.txt then install
dj-static==0.0.6

and then edit the project wsgi.py file:
from django.core.wsgi import get_wsgi_application
from dj_static import Cling

application = Cling(get_wsgi_application())

then restart the cpanel. Hope Admin will have a Proper Look. Thanks

A: a simple answer for this problem is moving admin and static folder to public_html
I had this problem and it worked
try it

A: I am Ansh Sharma. I also faced this same issue, and it was just too scary. Here I have something which can solve the problem. Go to Your setting file and make
DEBUG = TRUE

I hope this solves your issue
Happy Coding.
Ansh Sharma


text:
Q: How to get the current directory the file executed is in using batch of windows? I'm not familiar with this programming language,in PHP it's getcwd().

A: Not entirely sure I understand your question but:
The current directory is held in the pseudo-variable %CD%
Getting the directory that the Batch file is located in can be done as follows:
%~dp0

%0 is the name of the batch file. ~dp gives you the drive and path of the specified argument.


text:
Q: Android: How to remove map features for Amazon AppStore & Kindle I have an app which is published on both Google Play and Amazon AppStore.  I recently added map API features to this app, so I had to use the Google APIs SDK to build it.  I have successfully published my new version on Google Play, but having problems on Amazon.
The app was rejected by Amazon AppStore because they said the Kindle line of devices would not support it.  After further research I downloaded the new Kindle emulators and found that they do not support the Google APIs.  Since Kindle Fire tablets seem to be the primary devices for people purchasing apps through Amazon AppStore, I realized that I need to submit a version of my app which does not include the map features, but otherwise is the same app.
So my question is:  how do I create a second version of the App which is based on the standard Android SDK and does not include the mapping API, but uses the same Java source files?  As a long-time C++ programmer I could easily do this in C++ using conditional compile flags, but I've come to realize that Java does not support conditional compilation.  And I certainly don't know how to exclude libraries from one Android Eclipse build and include them in another build.
Can anyone give me some tips on how to achieve my desired result in Android?  I know I could create two separate apps but there would be a lot of code overlap which would be a lot more work for me when I have to do updates, I really don't want to have to maintain two separate codebases just to support Kindle Fires!

A: You could either check for the Build.Manufacturer being equal to "Amazon" or check to see if the app was installed from the Amazon AppStore (eg on a Fire device or now on Blackberry) and if it was don't initialize or call the Google Maps functionality (doesn't seem to hurt if the libraries are there, as long as they're not active)
boolean isAmazonDevice = Build.MANUFACTURER.equalsIgnoreCase("amazon");

final Application application = getApplication();
String installerName = application.getPackageManager().getInstallerPackageName(application.getPackageName());
boolean fromAmazonStore = installerName != null && installerName.equalsIgnoreCase("com.amazon.venezia");

and then checking the value for:
isAmazonDevice || fromAmazonStore


text:
Q: iOS webview crashing only with iOS13 Im aware that the UIWebView it's going to be deprecated for iOS13 soon and they wont accept apps with that on the store, but we are still working with it, and my main concern is, that while i can make it work in iOS 12 and lower, i can't with iOS 13, but it doesn't crash giving me a crash log or something, it just stops working without giving me anything, i don't know if that's what happens with this being deprecated soon or it's something inside my code or even Xcode.
Im working with OSX High Sierra and Xcode 9.2, the app it's configured for iOS 9 as target.

A: This issue basically with the pushing the controller. So, try with present the controller.
webviewcontroller.modalPresentationStyle = .fullScreen

self.present(webviewcontroller, animated: animated, completion: nil)

if It works that nice otherWise present the webviewcontroller over the window.