text:
Q: Laravel test preserving records in SQLite while rolling back migrations? I am working on a Laravel 5.2 app.  I am trying to set up testing using an SQLite in-memory database.
I'm aware of the SQLite problems related to changing columns that are NOT NULL without specifying a default, (for example described in this question).  An apparent workaround is to make the field first nullable, and then immediately undo that, in a separate transaction.  So I've spent many hours going over all my migrations and doing things like:
Schema::table('customers', function (Blueprint $table) {
    $table->string('first', 128)->after('id')->nullable();
});
Schema::table('customers', function (Blueprint $table) {
    $table->string('first', 128)->after('id')->nullable(false)->change();
});

I'm also aware of the SQLite problem where you can't drop more than 1 column per transaction (eg described here).  I spent many more hours updating my migrations to do that.
All migrations now successfully run and rollback without errors using SQLite and :memory:; they also run fine in MySQL.
So I added a test, using migrations.  The first and only thing the test does is use a Factory to create a customer:
<?php
namespace Tests\Unit;
use TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class PromoTest extends TestCase
{
    use DatabaseMigrations;

    /** @test */
    public function dummy_test() {
        factory('App\Customer')->create();
        print_r(\DB::select('select * from customers'));
    }
}

The output of the query right after creating the customer shows that it worked fine (fake data comes from Faker):
$ ./vendor/bin/phpunit --filter PromoTest
PHPUnit 4.8.24 by Sebastian Bergmann and contributors.

EArray
(
    [0] => stdClass Object
        (
            [id] => 1
            [email] => nRyan@example.net
            [zipcode] => 47049-6020
            [subscribe] => 0
            [created_at] => 2017-08-25 15:47:28
            [updated_at] => 2017-08-25 15:47:28
            [first] => Syble
            [last] => Hahn
            [phone] => (761)073-7794x8624
            [invalid_email] =>
        )
)

But immediately after that output, the test crashes and throws the following error:

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: customers.name (SQL: INSERT INTO customers (id, email, zipcode, subscribe, created_at, updated_at, name) SELECT id, email, zipcode, subscribe, created_at, updated_at, name FROM __temp__customers)

Notice the name field causing the problem does not appear in the created record above.  The name field did exist in this table in the past, but not any more - I removed it (with a migration) and now use first and last.  And clearly that migration worked, as the record created, inserted and dumped out above has the right, current fields.
So why is Laravel trying to insert records into an older version of the table, after it has already successfully created a record in the current one?
I am only guessing, but it looks like after the test is done, and the migrations are being rolled back, the data is being preserved and copied or re-inserted into each historical iteration of the schema?  There's no way that can work though ... ?
Has anyone seen this?  Is it expected or am I doing something wrong?
UPDATE The problem goes away if I simply switch to using MySQL for the tests.  Looks like I'll have to do that for now, as I'm stumped.  I'd much rather use SQLite in memory as it is faster.


text:
Q: Create a nested element with blank namespace in a schema definition I have a remote system that returns an XML similar to the one below.
<BalanceResponse xmlns="http://example.com/balance">
  <BalanceResult>
    <Balance xmlns="">
      <amount>10</amount>
    <Balance>
  </BalanceResult>
</BalanceResponse>

I created an xsd to match it
<s:schema elementFormDefault="qualified" targetNamespace="http://example.com/balance">
   <s:element name="BalanceResponse">
        <s:complexType>
            <s:element minOccurs="0" maxOccurs="1" name="BalanceResult">
            <s:complexType>
                      <s:element minOccurs="0" maxOccurs="1" name="Balance">
                         <s:complexType>
                <s:element minOccurs="0" maxOccurs="1" name="amount" type="s:decimal" />
                          </s:complexType>
                      </s:element>
                </s:complexType>
            </s:element>
        </s:complexType>
</s:schema>

I use JAXB to generate the stub classes. However, I know that my (un/)marshaller cannot bind the Balance element because the namespace is different.
Question is, how can i declare a different (blank)namespace for my element Balance?

A: You could do something like the following.  Since elementFormDefault is unqualified all global elements (BalanceResponse and BalanceResult will be namespace qualified and all local elements (Balance and amount) won't be.
<?xml version="1.0" encoding="UTF-8"?>
<schema
    xmlns="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://example.com/balance"
    xmlns:tns="http://example.com/balance"
    elementFormDefault="unqualified">

    <element name="BalanceResponse">
        <complexType>
            <sequence>
                <element ref="tns:BalanceResult"/>
            </sequence>
        </complexType>
    </element>

    <element name="BalanceResult">
        <complexType>
            <sequence>
                <element name="Balance">
                    <complexType>
                        <sequence>
                            <element name="amount" type="int"/>
                        </sequence>
                    </complexType>
                </element>
            </sequence>
        </complexType>
    </element>

</schema>

If as in the XML Schema in your question put elementFormDefault as qualified then it would expect all of the XML elements to be namespace qualified.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove Characters and Everything After from String I am aware of replacing Strings of a String, but that only works if I know exactly what I want to remove.
If I have a String like the following:
"hi-there-this-is-a-test&feature=hi-there"
How do I remove '&feature' and everything that comes after that?
Any help would be greatly appreciated. Thanks in advance!
EDIT: If absolutely necessary to use REGEX, could someone show me how to use it? I am aware it is 10.7 onwards but I'm fine with that. Even better, an example of String trimming or using the NSScanner?
Thanks again everyone.
EDIT: The solution posted below is the correct one, but resulted in a crash for me. This is how I solved the problem:
NSString *newString = [[oldString componentsSeparatedByString: @"&feature="] objectAtIndex:0];

A: It can be done without REGEX like this:
NSString *string = @"hi-there-this-is-a-test&feature=hi-there";
    NSRange range = [string rangeOfString:@"&feature"];
    NSString *shortString = [string substringToIndex:range.location];

A: Look up pattern-matching, aka regular expressions.
Oh, wow, TIL there's no built-in way to do regular expressions in an Objective-C Cocoa? according to Regular expressions in an Objective-C Cocoa application
Anyway, there are libs mentioned in that question.


text:
Q: How to implement Django like 'contains' filter query with Google App Engine? Is there some way to implement Django like contains or icontains filters with Google App Engine as well? I am using app engine patch.
I have used the below query earlier to match the start of a string but now the requirement is to find a string pattern within Datastore.
Employee.all().filter('name >=',value).filter('name <',unicode(value) + u'\ufffd')

Basically the requirement is to implement a search functionality with all the strings containing the search string as a result.
Please suggest.
Thanks in advance.

A: What you need to do is create a string list property with the different string permutations and query on that list.
Take a look at appengine.ext.search.SearchableModel for an example implementation.
You can also check out nonrel-search.

A: No, a true substring search isn't really possible in the datastore.
The best you could do would be to add a keyword index and do the "begins with" type query from your question on that, but even then for an entity like  "foo bar baz" you could match when searching for "ba" but not "ar b".
This sounds like a great job for BigQuery, which is in preview right now with a wait list to get access.

A: Recently I ran into the same problem and made my own model manager with an overriden filter function that also understands __contains. I'm assuming you're using Django.
class UserFeedManager(models.Manager):
    def filter(self, *args, **kwargs):
        keywordargs = {}
        for (arg, val) in kwargs.items():
            if '__contains' in arg:
                contains.append((arg.split('__')[0], val))
            else:
                keywordargs[arg] = val

        result = []
        if len(contains) > 0:
            for entry in super(UserFeedManager, self).filter(*args, **keywordargs):
                if all(map(lambda (attr, val): val in entry.__getattribute__(attr),
                           contains)):
                    result.append(entry)
        else:
            result = super(UserFeedManager, self).filter(*args, **keywordargs)

        return result

Essentially it builds a list of arguments that have a __contains, then fetches the whole result and filters it to only hold the results that pass all criteria.

A: querySet = Entity.objects.all()
ids = []
for i,obj in enumerate(querySet.iterator()):
    str_to_search =obj.name
    if str_to_search.find('blahblah') != -1:
        ids.append(obj.id)
querySet = querySet.filter(id__in = ids)


text:
Q: Applescript and 'notes': Open note in new window In 'Notes' it is possible to open a certain note in a new window (and without the note-overview at the left side visible) by double clicking on it in the list of notes.
There must be a way to do that via applescript... I couldn't find anything referring to that problem, even after a pretty long research.
Is there anybody who knows how to do it?

A: Using plain vanilla AppleScript there is not a programmatic way other then to use UI Scripting. Note that this will also require giving e.g. Script Editor, or whichever app is running the AppleScript code, accessibility privileges for this to work properly.
You need to tell Notes to show the note by name or id and then use System Events to click the Float Selected Note menu item on the Window menu of Notes.
tell application "Notes"
    show note "Foobar"
    activate
end tell

delay 0.5

tell application "System Events" to ¬
    tell application process "Notes" to ¬
        click menu item "Float Selected Note" of ¬
            menu 1 of ¬
            menu bar item "Window" of ¬
            menu bar 1

Note: Change Foobar to the name of the note you want to open in a separate window or use its id, e.g.:
note id "x-coredata://C48EA527-911C-49D0-950F-A15229B7D58F/ICNote/p55"

You can also tell Notes to show a note by number and also include the name of an account as well as the name of a folder (if applicable), e.g.:
tell application "Notes"
    tell account "Name"
        tell folder "Name"
            show note 1
        end tell
    end tell
end tell

Note: Replace Name with the actual name of the object. Change the number of the note as needed.
Then use the System Events command as shown further above to click the target menu item.

Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors.


text:
Q: Log4j default placeholder value I use log4j with this appender:
<appender name="fileAppenderRoot" class="org.apache.log4j.FileAppender">
    <param name="file" value="${log.location}/logFile.log" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
    </layout>
</appender>

If I start the server with -Dlog.location=/path/to/logs, log4j will log into /path/to/logs/logFile.log but if I specify nothing, log4j will fail appending to /logFile.log.
Is it possible to specify a default placeholder value?

A: No. you need to provide a location to write the log file.
If you need to generate the logs in the folder where you war is deployed ,
<param name="file" value="../logs/logFile.log" />

will create logfile in the folder where you have deployed
Read more here

A: I know this doesn't directly answer your question, but I find a better solution is to use a whole server-specific log4j configuration file. This allows customization of specific logger levels, etc. on a per-server basis.
Both WebLogic and GlassFish (and probably other servers) provide mechanisms to place extra files on the classpath for one specific application. You can use these mechanisms to override a default log4j.xml baked into the WAR. WebLogic provides File Loading Overrides and GlassFish Application-Specific Class Loading.

A: The simplest way is add the default value in the code
private static void configureLogger() {
    String logLocation = System.getProperty("log.location");
    if (logLocation == null) {
        System.setProperty("log.location", "/path/to/logs");
    }

    // if a logger is needed in the current class, create it after

    log = Logger.getLogger(SomeClass.class);
}

You need to add this code before all code that uses the logger. It can be added in a startup servlet, for example. Please, don't create a logger in the usual way, with a static field initializer, in such servlet.


text:
Q: Map.containsKey is not working correctly I have the following code:
List<Lead> lList = [select id, email, company from Lead];
Set<String> aSearchSet = new Set<String>();
    for (Lead l : lList) {
      aSearchSet.add(l.company);
    }

Map<String,Account> companyToAccountMap = new Map<String,Account> ([select id, Name from Account where name IN :aSearchSet]);

 for (Lead l : lList) {
             if (companyToAccountMap.containsKey(l.company)){
                 system.debug(LoggingLevel.INFO, l.company + ' exist');
             } else {
                system.debug(LoggingLevel.INFO, l.company + ' does not exist');
             }
         }

It just tells me the Company does not exist
The companyToAccountMap has the following data:
 (Account:{Name=My First Company,  Id=001Z00e000evIAG})

(Account:{Name=My Second Company, Id=001Z00e000eIAG})

(Account:{Name=My Third Company,  Id=001Z00w000ePEAG})

(Account:{Name=My First Company,  Id=001Z00s000evIAG})

When i use:
companyToAccountMap.containsKey(inquery.company)

I always get false
And im printing out the inquery.company
And it has 'My First Company', 'My Second Company', ...etc
Does anyone know why?

A: When you do
Map<String,Account> companyToAccountMap = new Map<String,Account> ([select id, Name from Account where name IN :aSearchSet]);

The created map always has Id as the key, so you won't be able to lookup company name in there. If you want a mapped keyed from company name, you'll need to construct it yourself.
   Map<String, Account> m = new Map<String,Account>()
   for (Account a: [select .... ])
       m.put(a.name, a)


text:
Q: @aspnet/signalr Angular triggering signal function for testing I'm facing following problem in Angular and @aspnet/signalr: I can't trigger functions which are called when a SignalR has been received. I want this for test purpose so I can manipulate data local in frontend and trigger a signal.
I'm listening to functions like this in code:
public addUserChangeListener() {
  this.hubConnection.on('user/changed', user => {
  // Do awesome stuff here
  });
}

And here is how I added this function to my signal:
this.signalRService.startConnection();
this.signalRService.addUserChangeListener();

Then there is a initializing part for the service:
  public startConnection() {
    this.hubConnection = new signalR.HubConnectionBuilder()
        .withUrl('/signalrtest')
        .build();

    this.hubConnection
        .start()
        .then(() => console.log('Connected'))
        .catch(err => console.error(err));
  }

And here is the first problem: I'm trying to do this offline and so I can errors. I don't want to use the backend server at all. So SignalR service should work offline and I want to trigger the functions from other services or controllers.
How can I do this? Is there any way?

A: You dont want to use Signal-R if you only want to update your client-side.
You can achieve data sharing between any component by using RxJS
import { Subject } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class DataService{
    public $data = new Subject<any>();

    constructor(injector: Injector) {
       super(injector);
    }

    public publishData(data: any) {
       this.$data.next(data);
    }

}

Then you can get updates from any component in your application
by subscribing to the Subject as following:
constructor(private dataService: DataService) {
   this.getData()
}
private getData() {
   this.dataService.$data.subscribe(data => {
      // This will be hit every time the publishData method sends new data
   }
}

A: Maybe the easiest way is to have a wrapper for creating the hub, and mock that:
@Injectable({
    providedIn: 'root'
})
export class SignalRHubConnectionGetterService {
    constructor() {}

    public getHubConnection(): HubConnection {
        return new signalR.HubConnectionBuilder()
            .withUrl('/signalrtest')
            .build();
}

This doesn't need much testing. You can inject this in your main SignalRService:
@Injectable({
    providedIn: 'root'
})
export class SignalRService {
    constructor(private hubConnectionGetter: SignalRHubConnectionGetterService) {}

    public startConnection() {
        this.hubConnection = this.hubConnectionGetter.getHubConnection();
        this.hubConnection
            .start()
            .then(() => console.log('Connected'))
            .catch(err => console.error(err));
    }
}

When testing the SignalRService, you can easily insert a mock object instead of the real SignalRHubConnectionGetterService, which can trigger whichever events you need for testing.


text:
Q: printing label at specific position I have 11 inch X 8.5 inch paper to print labels. The paper is divided into two columns i.e 4.25 width of each column containing 11 labels in each.
So, Size of each label is 1 inch X 4.25 inch.
Now my Question is: I'm using Northwind DB in MS Access 2010, in that considering the table dbo_Products, I want to print Product ID and Product Name on each label.
I could join the label report to form but i couldn't get output.
As said earlier The sheet contains two columns, if user wants to print label on specific label position it should be able to print on that.
(Ex. User wants to print Product ID: 10 on the position 5, the corresponding product info must be print on the label located on the 5th position of the page. (the positioning of labels on the page is shown below)
1     |     2

3     |     4

5     |     6

7     |     8

...... till 22

It would be great if anyone could help me out in this issue by showing the connectivity between the form to label and print it in specific label place.
Thank you

A: Start with the instructions found at http://www.techrepublic.com/blog/how-do-i/how-do-i-start-an-access-label-report-with-any-label-on-the-sheet/
Next I modified that to have three textboxes instead of one. They are named 'txtStart', 'txtEnd', 'txtLabelPos'. Use the code below for that form.
Note the 'WHERE' clause in the SQL... change the tables / field names to suit your own needs.
Option Compare Database
Option Explicit

Private Sub cmdCancel_Click()
    'Reset and take no further action.
    Me!txtStart.Value = 1
End Sub

Private Sub cmdPrint_Click()
'Pass table with label data, position for first label, and label report.

Dim bytPosition As Variant
Dim bytCounter As Byte
Dim rst As New ADODB.Recordset

If IsNull(Me.txtStart) Or Me.txtStart = "" Then
    MsgBox "You must enter a starting range for the data.", vbOKOnly + vbCritical, "Missing Start Range"
    Exit Sub
End If

If IsNull(Me.txtEnd) Or Me.txtEnd = "" Then
    MsgBox "You must enter an ending range for the data.", vbOKOnly + vbCritical, "Missing End Range"
    Exit Sub
End If

If IsNull(Me.txtLabelPos) Or Me.txtLabelPos = "" Or Not IsNumeric(Me.txtLabelPos) Then
    MsgBox "You must enter the starting label position to print on.", vbOKOnly + vbCritical, "Missing Label Position"
    Exit Sub
End If

Set rst.ActiveConnection = CurrentProject.Connection
rst.Open "SELECT * FROM tblCustomerLabels" _
        , , adOpenDynamic, adLockOptimistic

'Delete previous label data.
DoCmd.SetWarnings False
DoCmd.RunSQL "DELETE FROM tblCustomerLabels"

'Add one empty record for each missing label.
bytPosition = Nz(Me!txtLabelPos.Value, 0)

For bytCounter = 2 To bytPosition
    rst.AddNew
    rst.Update
Next

'Update label data.
Dim strSQL  As String
strSQL = "INSERT INTO tblCustomerLabels ( Company, [Last Name], [First Name], Address, City, [State/Province], [ZIP/Postal Code], [Country/Region] ) " & _
            "SELECT Customers.Company, Customers.[Last Name], Customers.[First Name], Customers.Address, Customers.City, Customers.[State/Province], Customers.[ZIP/Postal Code], Customers.[Country/Region] " & _
            "FROM Customers " & _
            "Where [Last Name] >= '" & Me.txtStart & "' AND [Last Name] <= '" & Me.txtEnd & "';"
DoCmd.RunSQL strSQL

'Open label report.
DoCmd.SetWarnings True
DoCmd.OpenReport "rptCustomerLabels", acViewPreview

rst.Close
Set rst = Nothing

Exit Sub

errHandler:
MsgBox Err.Number & ": " & Err.Description, vbOKOnly, "Error"
rst.Close
Set rst = Nothing
DoCmd.SetWarnings True

End Sub


text:
Q: How do I search a XElement with an specific attribute value? I need to search a child node by a value of one of its attribute, for example say that I have this XML
<Root>
    <Child Name="1" foo="a"/>
    <Child Name="2" foo="a"/>
    <Child Name="3" foo="b"/>
    <Child Name="4" foo="c"/>
    <OhterTag/>
</Root>

I want to extract the node Child with the attribute Name with value 2 . . .  I want the full node not just the tag of the node.
I have tried something like this
root.Elements("Attr").Where(child => child.Attribute("Name").Value == "2");

but I have not work

A: Use the element name, which is "Child" and it should work the way you have it... And since .Where in this case returns an IEnumerable<XElement>, to get just that Element, use .First() at the end.
root.Elements("Child")
    .Where(child => child.Attribute("Name").Value == "2")
    .First()

... or you can just use the predicate with .First()
root.Elements("Child")
    .First(child => child.Attribute("Name").Value == "2")

Finally you can use .FirstOrDefault() in case the node doesn't exist, to avoid null reference exceptions, as per discussion in below comments, suggested by @HamletHakobyan
root.Elements("Child")
    .FirstOrDefault(child => child.Attribute("Name").Value == "2")

A: You can, if you want to, achieve the same using XPath -
using System.Xml.XPath;

// ...

XElement result = root.XPathSelectElement("//Child[@Name='2']");


text:
Q: AAR class library stored in bintray doesn't link to the extended class I created an Android library made by a class named WordUtils2 which extends the Java class WordUtils.
The entire project can be found in github here:
https://github.com/dequadelisonz/WordUtils2
I also published the generated aar file into BinTray so to be able to use it through Gradle in other Android projects.
The project builds fine and there seems to be no problems.
But when I include it in other Android projects by adding this row in the gradle.build file of the module:
compile(group: 'it.code.martin', name: 'wordutils2', version: '1.0.0', ext: 'aar')
I get the following error in gradle messages:

Error:(56, 36) error: cannot access WordUtils class file for
  org.apache.commons.lang3.text.WordUtils not found

It looks like the original Wordutils class from where I extended my class cannot be reached.
Here below I report the Activity code:
package code.martin.it.wordutilstest;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import it.code.martin.WordUtils2;

public class MainActivity extends Activity implements View.OnClickListener {

    private EditText mEditText;
    private TextView mTextview;
    private Button mOkBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEditText=(EditText)findViewById(R.id.editText);
        mTextview=(TextView)findViewById(R.id.textView);
        mOkBtn=(Button)findViewById(R.id.button);
        mOkBtn.setOnClickListener(this);

    }

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

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

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        String response= WordUtils2.wordToNumberIt(mEditText.getText().toString());
        mTextview.setText(response);
    }
}

and the build.gradle file:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion '21.1.2'

    defaultConfig {
        applicationId "code.martin.it.wordutilstest"
        minSdkVersion 21
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile(group: 'it.code.martin', name: 'wordutils2', version: '1.0.0', ext: 'aar')
}

Of course I can send further details of my code if needed.
What I'm doing wrong? Android studio is updated to the latest version.
Thanks for help.

A: It looks like transitive dependencies aren't working.  Try replacing the dependencies in your build.gradle with this
    dependencies {
        compile fileTree(include: ['*.jar'], dir: 'libs')
        compile(group: 'it.code.martin', name: 'wordutils2', version: '1.0.0', ext: 'aar'){
    transitive=true}
}

If that doesn't work, I'd recommend downloading the correct apache commons Jar and building the library with that instead of using gradle dependencies.


text:
Q: Xquery delete with Xpath from sql:variable I am having Xpath to delete from XML in an VARCHAR(MAX) variable, but XML.modify('delete '+@MyXpath) give an error ,

The argument 1 of the XML data type method "modify" must be a string
  literal.

DECLARE @myXML XML,
        @MyXpath VARCHAR(MAX)

-- Processing of Xpaths for components needed to remove
-- Adding those in @XpathsToRemove

SELECT TOP(1) @MyXpath = [XPATH]
FROM @XpathsToRemove

SET @myXML.modify('delete '+@MyXpath)

Is there any way to remove those components with Xpath available in @MyXpath variable ?
-- Edit Example XML
DECLARE @myXML XML ='<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Dont forget me this weekend!</body>
</note>'
      ,@MyXpath VARCHAR(MAX) = '//note/from'

      -- There are many Xpaths and dynamically generated with some processing so I don't want to hardcode Xpath there
      SET @myXML.modify('delete '+@MyXpath)

       --This doesn't works too
      -- SET @myXML.modify('delete "sql:variable("MyXPath")"')
      SELECT @myXML

A: Thanks guys, I got solution by EXEC to generate dynamic queries.
Following is link that solved my issue,
How to using for loop using XQuery to delete xml nodes [duplicate]
Solution,
DECLARE @str nvarchar(MAX)
SET @str = 'SET @MyXML.modify('+char(39)+'delete '+@MyXPath+'/*'+char(39)+'); '
EXEC sp_executesql  @str, N'@MyXML xml output', @MyXML output


text:
Q: web2py - trouble building a query I am having troubles building a query that does the following:
Vehicle
* make
* model
* trim
* part_number
* accuracy
First I do a query that finds the highest level of accuracy for each part number. I create a dictionary such that dic[part_number] = highest accuracy for this part_number
Then I want to do a second query. I match up make, model, and trim so some values. What I want to do next is check to see if the current record's accuracy is equal to the highest known accuracy level. Basically I only want records with the highest level of accuracy (that matches to the make, model, trim obviously)
What I've tried:
query &= (db.vehicle.accuracy == dict[db.vehicle.part_number])
I get the following error:
type 'exceptions.KeyError' gluon.dal.Field object at 0xsomeval
Is this the best way to approach this problem? Perhaps there is another way to get the result I want.

A: A couple of things worth noting there. First of all, to keep things neat, you may want to build a list of queries, and then reduce them using a function like the following:
def reduce_query_list(query_list, operator = 'and'):
    if operator == 'or':
        return reduce(lambda q01, q02:q01|q02, query_list)
    elif operator == 'and':
        return reduce(lambda q01, q02:q01&q02, query_list)

Second, it looks like in the code above, you're trying to use an actual db field as a key, rather than using some value that's stored in a table in that field (which may account for that Exception). Are you sure that this is what you want to do?
EDIT:
If I understood correctly, your error comes from attempting to use Field objects as keys. Try to use the following as your list of keys instead:
part_number_list = [value['part_number'] for value in db(db.vehicle).select()]


text:
Q: Hide store prices if not logged in - Magento 2.3.1 I have 3 stores on the same website, and I would like for one of the stores, the prices do not show if the customer has not logged in. Any idea how to do it?

A: Please install below module which is provide like this features. Store owner to hide the product price and add to cart button from guests or certain customer groups.
https://github.com/karliuka/m2.ProductAvailable
after install put below command via ssh.
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy
I hope its very helpful to you..

A: Does his work with 2.35p
If so manual install using ssh expanded the memory limit first check php ran ssh commands reindexed clean cache
Restarted admin but can not find even in Stores > Configuration > Catalog > Product Available.
Was really good with 1.3.-1.7 Been I while since, so it would be good to find a solution


text:
Q: How to read the last line in CSV line in GATLING I use feeders from a csv file, and i want to read always the last line in this file:
val actors= csv("./src/test/resources/Data/ksp-acteurs.csv").circular

      .feed(actors)
  .exec(http("K_actors")
    .get("https://URL/ksp-acteurs/${Col1}")    //need to extract the last value in this column
    .header("Authorization","Bearer ${jwtoken}")
    .check(status is 200))

A: You could just do something like this:
val feeder = csv("./src/test/resources/Data/ksp-acteurs.csv")
val lastLine = feeder.readRecords.last.values

but the important thing is that you call readRecords before you call circular, because in this case readRecord will not be able to find last line and test will fail with out-of-memory exception.


text:
Q: auth_ldap: ldap initialization failed I'm working on a recently (slightly) upgraded Apache installation.
SSO Authentication using Kerberos worked fine before the upgrade, but now I'm getting:
AH01711: auth_ldap authorise: User DN not found, LDAP: ldap initialization failed

which means that any Require ldap-group  directive fails, even though Require valid-user works fine.
Does anyone have any suggestions at all about what "ldap initialization failed" might mean?
Apache is now 2.4.53, having upgraded from 2.4.46, on Solaris.
Using LDAPSearch from the command line doesn't reveal any issues.
SNOOPing the network shows no LDAP traffic at all, to the Windows DC.


text:
Q: Incorrect display of data on the screen while performing filter in Recycle View Discription:
I have an android app, and in one of parts of it user can choose his skills, like tags in https://stackoverflow.com

So when user taps on plus button, he can see all available skills and choose
what he wants

As you see there is a filter in the top of the screen, to find skills that user wants to add. And here comes the problem, and it has many impacts
For example if i type "Eng" to find "English", the result will be "Spanish"

Do not hurry to tell me, that the problem is in filtring algorithm, because
my console logs, say, that result is correct, and filter find only "English"
What is more if i choose this option, the correct answer "English" is displayed under the "Spanish"

What is more is if a i save changes, in my account is shown that i actually choose "English"

So filtring is correct, and saving data is correct to, the problem is in displaying skills names. Why i call it magic? because console logs right before displaying the result show correct name
And i noticed that if i will go back to full list of skills it will be wrong displayed too

But as in previous cases, my console logs says, that all is OK, and i have normal skill list without duplicates
Here is my code samples :
search - is simple EditText field
search.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            chipAdapter.getFilter().filter(charSequence);
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

Adapter :
@Override
public void onBindViewHolder(final ChipAdapterAllSkills.ChipViewHolder holder, final int position) {

    String skill = filtredSkillList.get(position).getName();
    System.err.println("SKILL "+skill+" position "+position);
    holder.skillChip.setChipText(skill);
    holder.skillChip.setSelectable(true);
    holder.skillChip.setSelected(true);
    holder.skillChip.setTextColor(MainAplication.getContext().getResources().getColor(R.color.accent));
    holder.skillChip.changeBackgroundColor(MainAplication.getContext().getResources().getColor(R.color.blue));
    holder.skillChip.setOnSelectClickListener(new OnSelectClickListener() {
        @Override
        public void onSelectClick(View v, boolean selected) {

            System.err.println(selected);
            if(!selected) {
                SelectSkills.getSkillsToAdd().add(filtredSkillList.get(position));
            }else {
                SelectSkills.getSkillsToAdd().remove(filtredSkillList.get(position));
            }
        }
    });
}

@Override
public int getItemCount() {
    return  filtredSkillList.size();
}

@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {

            String target = charSequence.toString();
            if (target.isEmpty()) {
                filtredSkillList = skillList;
            } else {
                List<Skill> list = new ArrayList<>();
                for (Skill s : skillList) {
                    if (s.getName().toLowerCase().contains(target.toLowerCase())) {
                        list.add(s);
                        System.err.println(s.getName());
                    }
                }
                filtredSkillList = list;
            }
            FilterResults results = new FilterResults();
            results.values = filtredSkillList;
            return results;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            filtredSkillList = (ArrayList<Skill>) filterResults.values;
            notifyDataSetChanged();

        }
    };
}

I really don`t know what is going on, maybe some of you can help)
I have suspicions that maybe problem is in threading, but i didn`t do any changes in them in this piece of code

A: The problem was not in my code.
There is some Issues in Library that i`m using to create skill -chips.
Because with other libraries all works fine)


text:
Q: Propagating base class errors in Swift I wanted NSTextField which will replace empty string with 0 (or minimum allowed value), so I have created custom NSNumberFormatter:
class NonEmptyNumberFormatter: NSNumberFormatter {
    override func getObjectValue(obj: AutoreleasingUnsafeMutablePointer<AnyObject?>, forString string: String, range rangep: UnsafeMutablePointer<NSRange>) throws {
        if string.isEmpty {
            obj.memory = self.minimum ?? 0
        } else {
            try super.getObjectValue(obj, forString: string, range: rangep)
        }
    }
}

It works fine for empty strings, however if I set minimum property, then entering a value smaller than minimum crashes the application.
Is something wrong with try super.getObjectValue(...) call?
I want to preserve the base class (NSNumberFormatter) behavior for non-empty strings.
Here's a sample gist to test it in the playground: https://gist.github.com/iskeld/a6ba57b145f2f9208fa63efc69d2c517
- I don't understand why OverridenFormatter causes error when it's only delegating the call to the base class.


text:
Q: Running IntelliJ Inspections via Gradle/TeamCity I am attempting (unsuccessfully) to run IntelliJ Inspections on a java Gradle project in TeamCity.  The documentation is a bit confusing; specifically, it states "To run inspections for your project, you must have either an IntelliJ IDEA project file (.ipr) or a project directory (.idea) checked into your version control."  However, it also claims support for both Maven (see this post) and Gradle projects, which seems inconsistent with a requirement to commit the IntelliJ project files.
Our team prefers not to commit the IntelliJ project files, and therefore I am attempting to use my build.gradle file and an inspection profile. However, even for the simplest gradle project I can create, I am unable to get IntelliJ inspections to run successfully on TeamCity.  Instead, I get this in the log:

[Step 2/2] [   6968]   WARN - .manage.ContentRootDataService - Can't import content roots. Reason: target module (ModuleData: module ':d9cc8a1592d04689:unspecified') is not found at the ide.

Am I attempting the impossible?


text:
Q: Como documentar/descrever colunas no Swagger Estou realizando a documentação de uma API utilizando o Swaggwer, porém, não encontrei uma forma de descrever o que é cada campo do json.
Seguindo o exemplo abaixo, esse é o json que o Swagger gera de exemplo com os dados da minha api:
Json exemplo gerado pelo Swagger
Mas precisaria descrever o que é cada campo, pois o outro desenvolvedor nem sempre saberá o que significa um "cd_emp" ou um "qtde_pend_pedv" por exemplo.
Mais ou menos o que eu queria, seria algo assim, como um comentário em frente a cada campo:
Exemplo de descrição dos campos
É possível ou há alguma maneira parecida que possa usar para descrever cada coluna?


text:
Q: how to fix error - No module named 'cryptography' when I run command python manage.py runserver I got an error
also I try to install cryptography on virtual environment by command pip install cryptography. It says successfully installed the cryptography with following message.
But still I am not able to avoid the message No module named 'cryptography' when I run the server on AWS instance. Please help me to fix this issue.


text:
Q: Configuring Homestead to work with MySQL Workbench I just started using Homestead today and so far I don't think I know what I am doing, previously I was using the inbuilt PHP server that comes with Laravel and I had MySQL server and workbench installed separately on my computer.
With this setup I was able to connect to my database with ease, however since I got my Homestead running I can't seem to access that database again. This error keeps popping up:
3/3 ErrorException in Connector.php line 47: SQLSTATE[HY000] [1045]
Access denied for user 'myproject_db101'@'localhost' (using password: YES)
(View: /home/vagrant/Projects/myproject/resources/views/layout/index.blade.php)
(View: /home/vagrant/Projects/myproject/resources/views/layout/index.blade.php)

How can I fix this?

A: I was facing the same issue and I tried below steps to fix it. Please let me know if they work for you.

*

*Note the homestead ip address for your vagrant box. It is available in Homestead.yaml file under ~/.homestead directory. This directory location would be different on different OS. But since you have already installed vagrant with homestead you should know its location. For me the ip address was 192.168.10.10.

*Open up the Mysql Connection wizard and provide the below settings

hostname  = 192.168.10.10
port = 3306
username = homestead
password = secret

*Test Your connection

For me these settings worked. Check if they work for you.

A: These other answers might have worked for you guys, but in case anyone has a case like mine, I'm just going to provide what worked for me. Hopefully it helps someone out. I'm working on a brand new homestead installation as of today, but on a very old mac in case thats relevant.
What worked for me was using the regular localhost ip of my machine as the host, and then the homested/secret combination for the password, and using the default port but with a 0 at the end.
This adds up to be the following settings:
Connection method: Standard (TCP/IP)
Host: 127.0.0.1
Username: homestead
Password: secret
Port: 33060
Hopefully this helps someone out. Its the only configuration that worked for me.

A: Try using homestead's default MySQL credentials: User: root Password: secret
If you are accessing the database from your computer via MySQL Workbench (not from within the homestead VM), you can use localhost:33060 (note: non-standard port). This is mapped to port 3306 within your VM.
From your application and any time you're working from within the homestead VM, you can connect to the database normally as localhost on port 3306.

A: Very likely a configuration issue. Either the user 'myproject_db101'@'localhost' has no password set or is not allowed to connect from localhost. You need another user with proper rights (e.g. the root user) to fix permissions for that user.


text:
Q: Finding the number of minimizers of a sextic polynomial From the Indian Joint Entrance Examination – Main:

Find the number of minimizers of the following sextic univariate polynomial $$f(x) = 10x^6 - 24x^5 + 15x^4 - 40x^2 + 108$$

I know the general method for cubic polynomials is finding roots of $f'(x)$ and checking for sign of $f''(x)$ at those points, but I am not able to solve for degree $6$.


text:
Q: Can .vtuexe files of vteststudio be executed on something which is not CANOE? I have some .vtuexe files from vteststudio studio and my project doesn't use canoe
Can I execute the test cases with no canoe?
Debugger is Isystem winidea

A: The .vtuexe file is designed to work only with CANoe. It is not an open source file which you can use in other tools. If your project doesn't use CANoe, then you should not use vTESTstudio.


text:
Q: Prevent Qt from generating shortcuts? I am creating a QPushButton as follows, with no explicit shortcut (&):
testButton = new QPushButton(tr("Start"));
I can correctly read the button's text just after its construction:
testButton.text() returns 'Start' (without single quotes)
Then I create a signal/slot connection:
QObject::connect(
  testButton, &QPushButton::clicked,
  this, &Dialog::actionRequest
);
In the Dialog::actionRequest slot, testButton.text() returns '&Start', as if a shortcut had been created "somewhere", under the hood.
If I name the button 'Foo', the same phenomenon occurs, but testButton.text() would return 'F&oo'. That's because I already have a "File" menu, that has an explicit shortcut -- created as:
fileMenu = new QMenu(tr("&File"), this);
and, possibly, Alt+O would be the next "available" shortcut?
I do not want this implicit shortcut creation for my QPushButton. What's the solution to this problem? I'm running Fedora 22 ( with plasma 5), with stock qt 5.5 packages.

A: There is a default QShortcut object associated with menu options, buttons, etc. Unfortunately there is no way to directly access and disable them after creation that I know of.
You can attempt to call the Qt global function qt_set_sequence_auto_mnemonic(false); to disable this behavior dynamically but I'm not sure if it's available on every platform.


text:
Q: Handling time-zone between client and server for date-only DateTime I have a custom validation attribute in my ASP.NET Web API application that checks if the date is in the future or not (dates in the future are not allowed). Here's the code:
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    if (value != null)
    {
        var date = (DateTime)value;
        if (date != null)
        {
            if(date.Date > DateTime.UtcNow.Date)
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
            }
        }
    }

    return ValidationResult.Success;
}

I can't figure out how to make the comparison so it works for all time-zones. Using DateTime.UtcNow is not the solution, because if the client and the server are in the same timezone, in the hours close to midnight, the date will be the day after. And, of course DateTime.Now wouldn't work for other time-zones. So, what's the solution?
Update:
In my WebApiConfig.cs file, I have this code to set the DateTimeZoneHandling to Utc:
jsonFormatter.SerializerSettings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver(),
    DateFormatHandling = DateFormatHandling.IsoDateFormat,
    DateTimeZoneHandling = DateTimeZoneHandling.Utc
};

This will format the date in the JSON response like this: "2018-03-02T00:00:00Z".
And, all the DateTime values coming from the client will have their Kind property set to Utc. Then, I can compare the date with UtcNow, but now the problem is the date "2018-03-02T00:00:00Z" is displayed as March 1, 2018 in my browser, because it is converted to local time (UTC -5).

A: There are only two viable approaches.

*

*Convert to UTC on the client before sending the value to the server for comparison.

*Try to determine the client's time zone id (or offset if just for a single point in time), and pass that from the client to the server.  The server can then use that information to do the conversion to UTC before comparison.

If you take neither of these options, passing only a client-local-time value to the server without any offset or time zone information, then there is no way to accomplish your goal.  There is no magic the server has about what the client's time zone may be.
Also, if you are comparing whole dates (ex 2018-03-02, not 2018-03-02T00:00:00), then you will need to decide which time zone is relevant for your use case.  For example, if you compare against UTC day, that is not going to work well for a business in Los Angeles unless they have aligned their business processes to UTC.
Update per our chat:
Since you only need to work with whole dates, then don't do any time zone conversions.  Make sure whatever date is chosen from your datepicker is exactly what is sent - rather than going through the Date object.  If your datepicker doesn't offer this value directly, then create it from the Date object - either manually or with a library like moment.js.  Don't call .toISOString() because in addition to ISO format, it will also assume you meant midnight local time and do a UTC conversion.
Also don't set any of JSON.Net's date settings - just use the defaults.

A: try this:
var date = (DateTime)value;
var utcDate = date.ToUniversalTime();

and than compere like this:
if(utcDate .Date > DateTime.UtcNow.Date)

A: var timezoneOffset = new Date().getTimezoneOffset(); - You can get this information from client to server (any web API call)
With the help of timezoneoffset details you can achiele the same. Here in my case i converted UTC DateTime to my client local datetime in Server side.
DateTime clientDateTime = DateTime.UtcNow - new TimeSpan(timezoneOffset / 60, timezoneOffset % 60, 0);


text:
Q: Issue on image size, while adding it programmatically I have a little (& bit tricky) problem and could not solve from many hours by myself. The problem scenario is:
I'm adding TextView s (i.e. Titles) and related (click-able) ImageView s programmatically (from database). The margin between them is already very large (I have not added any margin or padding betwwen them). I want to set margin to only 1dp. But I can't.
I used the following code:
LinearLayout linearLayout = (LinearLayout) this.findViewById(R.id.linearLayout);

//No params and margins used for it
TextView tvTitle = new TextView(this); // getting from json (dynamically)
tvTitle.setTextSize(17) ;
tvTitle.setText(title) ;
linearLayout.addView(tvTitle) ;

ImageView image = new ImageView(this) ;
// here getting the image from url

LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) ;
params.setMargins(5, 0, 5, 0) ;
image.setLayoutParams( params );
linearLayout.addView(image) ;

As here topMargin and bottomMargin are 0 but when app runs; there is almost 20dp margins above and below the images.
When I increase the margin from 20dp i.e. When I replace any 0 to 30 or 40 then margin increases but when I decrease it up to 5 or 1 or 0 then it does not decrease. It remains near about 20 dp. Anyone having idea about it...

A: Sounds like the viewbounds on the ImageView are not getting adjusted correctly.
Try settings this on your ImageView:
image.setAdjustViewBounds(true);


text:
Q: How to initialize Facebook Pixel with data that will be populated after the initialization? I have a one-pager campaign site which should collect PageView and LEAD event data for Facebook targeting with "advanced matching".
For PageView, I need to initialize the Pixel on page load. For advanced matching, I need to provide user data for initialization script — however, I only have user data available after user has submitted the data, which is when the LEAD event should be sent.
Is it possible to provide the initialization script with a "pointer" to a javascript variable that is used when sending the LEAD event? Help page hints at this, but all the examples have e.g. email parameter provided as plain text or sha256 hash; not as JS variable nor as a textual pointer to one.
From the "Advanced Matching with the Pixel" help page:

To enable this feature, modify the default FB pixel code to pass data
  into the pixel init call.
fbq('init', '<FB_PIXEL_ID>', {
    em: '{{_email_}}',
    // Data will be hashed automatically via a dedicated function in FB pixel
    ph: '{{_phone_number_}}',
    fn: '{{_first_name_}}'
    ....
})

In the example above, you will need to replace email, phone_number,
  first_name with the names of the variables on your website that
  capture this data.

Let's say I have user_email variable in the same scope as fbq-init:
var user_email = '';

Later, after the form is submitted, this variable will be populated like
user_email = "john@example.com";

How should I reference the variable in fbq? (1) Like this?
fbq('init', 123456, { em: '{{_user_email_}}' });

(2) Or like this?
fbq('init', 123456, { em: 'user_email' });

(3) Or should I provide it simply with the variable:
fbq('init', 123456, { em: user_email }); // nb: user_email === false when this is run

(4) Or should I initialize the pixel without any matching data and later enrich it? (How?)
A reputable ad agency sent me with instructions to submit the name of the variable as in my example 2, but the help page hints at 1 without actually providing any real world examples.

I tried all the options 1–3, and it seems variables won't get re-evaluated in subsequent fbq('track', …); calls after the initialization. If user_email is blank to start with, none of the events will include hashed user data.
Moreover even if I start with a valid email user_email = "john@example.com"; (also tried real domains instead of example.com) only method 3 will work — but, as expected, this is not dynamic, ie. if user_email changes the hashes won't.
It is as if there is no string-variable replacement to begin with.
Would the more proper question be: how do I submit user data for advanced matching after the pixel initialization? Instead of trying to make the initialization lazy/dynamic.

A: As a workaround it is possible to generate a Lead event with email user data by loading the pixel (image) via javascript:
// here the user email is unknown, so PageView is generated without email
fbq('init', 123456, {});
fbq('track', 'PageView');

// Later the form is submitted via ajax, so the user email is known
$.ajax(…).done(function(data) {
    // I decided to sha256 hash the email address in the backend and return it for the javascript handler
    var pixel = document.createElement('img');
    pixel.src = 'https://www.facebook.com/tr/?id=123456&ev=Lead&ud[em]=' + data;
    document.body.appendChild(pixel);
    // confirmed by the Pixel helper Chrome extension, this does generate a valid tracking event
    // (ironically, we're loading the noscript version via javascript)
});

Of course, a pure fbq version would be more desirable. Also, I'm yet unaware of possible drawbacks, should there be any.


text:
Q: iTextPDF: License File issue I am using the commercial version of iTextPDF(7.2.3) and html2pdf(4.0.3) to generate a PDF file. But when checking the license key I get the following error:
Caused by: java.lang.NoSuchFieldError: _objectFieldValueSeparatorWithSpaces
        at com.itextpdf.licensing.base.util.JsonUtil$CustomPrettyPrinter.<init>(JsonUtil.java:138)
        at com.itextpdf.licensing.base.util.JsonUtil.serializeToString(JsonUtil.java:47)
        at com.itextpdf.licensing.base.util.SigningUtil.getExpectedSignature(SigningUtil.java:67)
        at com.itextpdf.licensing.base.util.SigningUtil.checkSignature(SigningUtil.java:52)
        at com.itextpdf.licensing.base.actions.LoadLicenseEvent.validateLicenceFile(LoadLicenseEvent.java:118)
        at com.itextpdf.licensing.base.actions.LoadLicenseEvent.getProperLicenseFile(LoadLicenseEvent.java:100)
        at com.itextpdf.licensing.base.actions.LoadLicenseEvent.<init>(LoadLicenseEvent.java:42)
        at com.itextpdf.licensing.base.LicenseKey.loadLicenseFile(LicenseKey.java:151)
        at com.itextpdf.licensing.base.LicenseKey.loadListOfLicenses(LicenseKey.java:216)
        at com.itextpdf.licensing.base.LicenseKey.loadLicenseFile(LicenseKey.java:129)
        at com.itextpdf.licensing.base.LicenseKey.loadLicenseFile(LicenseKey.java:88)

pom.xml:
<repositories>
        <repository>
            <id>itext</id>
            <name>iText Repository - releases</name>
            <url>https://repo.itextsupport.com/releases</url>
        </repository>
</repositories>
...
<properties>
     <itextpdf.version>7.2.3</itextpdf.version>
     <html2pdf.version>4.0.3</html2pdf.version>
     <itext.licensekey.version>4.0.3</itext.licensekey.version>
</properties>
<dependencies>
<dependency>
      <groupId>com.itextpdf.licensing</groupId>
      <artifactId>licensing-base</artifactId>
      <version>${itext.licensekey.version}</version>
</dependency>
<dependency>
      <groupId>com.itextpdf</groupId>
      <artifactId>itext7-core</artifactId>
      <version>${itextpdf.version}</version>
      <type>pom</type>
</dependency>
<dependency>
      <groupId>com.itextpdf</groupId>
      <artifactId>html2pdf</artifactId>
      <version>${html2pdf.version}</version>
</dependency>

The method that performs the conversion to PDF:
private byte[] getPdfWithLocalesFontSupport(StringBuilder fileText) throws IOException {
        LicenseKey.loadLicenseFile(new File("/path/key.json"));
        FontProvider fontProvider = new FontProvider(addCertificateFonts(), "");
        fontProvider.addStandardPdfFonts();

        ConverterProperties properties = new ConverterProperties().setFontProvider(fontProvider);
        properties.setBaseUri(getBaseProjectUri());
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            HtmlConverter.convertToPdf(fileText.toString(), out, properties);
            return out.toByteArray();
        }
    }

What is the problem and how to fix it?


text:
Q: Computation of size in titlespacing Consider the following example:
\documentclass[11pt,a4paper]{book}
\usepackage{lipsum}
\usepackage{titlesec}

\newlength{\textsize}
\makeatletter
\setlength{\textsize}{\f@size pt}
\makeatother

\titlespacing*{\section} {0pt}{3.5ex plus 1ex minus .2ex}{2.3ex plus .2ex} % WORK
\titlespacing*{\section} {0pt}{\dimexpr(3.5ex-1.\textsize)\relax plus 1ex minus .2ex}{2.3ex plus .2ex} % FAIL

\begin{document}
\section{Section}
\lipsum
\end{document}

and the error:

How to make the failing expression work in order to reduce the space by a textsize?

A: The \titlespacing command uses some tricks for extracting the plus and minus dimensions and doing some computations; the \relax token disturbs the processing, because \relax is used as terminator of an argument in one of the internal macros.
\documentclass[11pt,a4paper]{book}
\usepackage{lipsum}
\usepackage{titlesec}

\newlength{\textsize}
\makeatletter
\setlength{\textsize}{\f@size pt}
\makeatother

\titlespacing*{\section}
  {0pt}
  {\glueexpr (3.5ex-\textsize) + 0pt plus 1ex minus .2ex}
  {2.3ex plus .2ex}

\begin{document}
\section{Section}
\lipsum
\end{document}

Alternatively, use
\the\dimexpr 3.5ex-\textsize\relax  plus 1ex minus .2ex

which will remove the unwanted \relax when evaluating \dimexpr.


text:
Q: R - how to make barplot plot zeros for missing values over the data range? Lets say I have 10 observations of 200 points of integers between one and ten:
mysample = sample(rep(seq(1,10),20),10);

and I want to barplot it
barplot(table(mysample));

barplot

In this example, there are no observations of 7. Is there a quick way of telling barplot to set the x-axis range to all integers between 1 and 10, or do I have to manually edit the table?

A: Try
barplot(table(factor(mysample, levels=1:10)));

By using a factor, R will know which levels are "missing"


text:
Q: IP_HDRINCL option is not supported with IPv6 , how to set ipv6 src addr? I need setting ipv6 src addr to "::0", but system will set the addr to link-local addr.
I use a raw socket, however, i cant't construct the IP header by myself, IP_HDRINCL option is only supported with IPv4, so how should i do ??


text:
Q: Will MySQL reuse deleted ID's when Auto Increment is applied http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
That document I'm reading seems to say something like:
"In this case (when the AUTO_INCREMENT column is part of a multiple-column index), AUTO_INCREMENT values are reused if you delete the row with the biggest AUTO_INCREMENT value in any group."
I don't really understand what's being said there. Aren't the values supposed to be reused automatically?
Thanks in advance...

A: InnoDB resets the auto_increment field when you restart the database.
When InnoDB restarts, it finds the highest value in the column and then starts from there.
This won't happen in MyISAM because it caches the last incremented id.
Update
This feature/bug has been around since 2003 and can lead to serious issues. Take the example below,

*

*Table t1 has an auto-inc primary key.

*Table t2 has a column for the primary key in t1 without a foreign key "constraint". In other words, when a row is deleted in t1 the corresponding rows in t2 are orphaned.

*As we know with InnoDB restart, an id can be re-issued. Therefore orphaned rows in t2 can be falsely linked to new rows in t1.

This bug has been finally fixed in MySQL 8.0.0 WL#6204 - InnoDB
persistent max value for autoinc columns.
InnoDB will keep track of the maximum value and on restart preserve
that max value and start from there.

A: As described with the InnoDB engine the last PK utilised will be reused if the row is deleted prior to a reboot as it is not cached. If this PK is a Foreign Key (FK) in another table problems can arise (FK hell). This is how I discovered the problem when a little old lady shot up to 195 cm(!) as the deleted person's additional data was picked up. The work around for this is either to implement 'ON DELETE CASCADE' for the child tables or (not my preferred option) to code around this issue.

A: When you have a primary key field that is also auto_increment, no matter how many rows (or in what order) are removed, the ids that no longer exist are not used again, and the field is incremented continuously for each row.
However, when your primary key consists of multiple fields (E.G. an auto_increment field and another field), the auto_increment field is reused, and only when the deleted id is the last id. What this means is if you have values like 1, 2, 3, 4, and 5, and you remove the row with the field value of 5, the next row will have an id of 5. However, if you remove the row with the id of 2, this will, again, not be used, and the next row will have an id of 6.

A: As mentioned in answer :

InnoDB resets the auto_increment field when you restart the database.
When InnoDB restarts, it finds the highest value in the column and then start from there.

and this behavior could lead to Foreign key problem.
Fortunately from MySQL 8.0.0 it will be fixed.
More info:
Bug #199   Innodb autoincrement stats los on restart
WL#6204: InnoDB persistent max value for autoinc columns

See BUG#199 on MySQL bugs.
Currently InnoDB does the following when a table
  is opened: SELECT MAX(c) FROM t; where c is the AUTOINC column name.
  This step is used to initialise the column's next autoinc value and
  allocation of autoinc values starts from this point. InnoDB also does this
  when it executes 'ALTER TABLE AUTO_INCREMENT=N;'.
...
InnoDB should keep track of the maximum value and on restart preserve
  that max value and start from there.

A: If the table is of InnoDB type, then the deleted ids are reused in certain scenarios. Here is what I did to test it:

*

*Table user has id column as primary key, with auto_increment set
CREATE TABLE user (
  id bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (id),
) ENGINE=InnoDB AUTO_INCREMENT=2108 DEFAULT CHARSET=latin1;

*My createUser API call, creates a entry in user table. Lets say user with id = 1 was created.

*Call deleteUser API which just deletes row from user table.

*Stop and start the database

*Call createUserAPI call again. It creates user with same id (id = 1).
So, it does uses the deleted id, if the server is restarted.
I got this issue because I had another table called user_rules which stored user_id in a column, but it did not have FK reference to user table (which was wrong). Another issue was that when user was getting deleted, entry from user_rules table was not getting deleted and since it had no FK set, db also didn't complain.
And when server got restarted, user rules were messed up!


text:
Q: How to Mock a missing attribute I have a line of code that is:
if not hasattr(class.a, u'c'):
    return

How do I mock out class so that class.a.c returns False for hasattr?
If I do this:
>>> from mock import MagicMock
>>> mock_class = MagicMock(spec=[u'a'])
>>> hasattr(mock_class, u'a')
True
>>> hasattr(mock_class, u'b')
False
>>> hasattr(mock_class.a, u'c')
True

Although I dont spec class.a.c, its being mocked!!!

A: You can delete the attribute, which will cause hasattr to return False.
From the Documentation:
>>> mock = MagicMock()
>>> hasattr(mock, 'm')
True
>>> del mock.m
>>> hasattr(mock, 'm')
False
>>> del mock.f
>>> mock.f
Traceback (most recent call last):
    ...
AttributeError: f

For your specific example, since mock_class.a is another Mock, you can do del mock_class.a.c.

A: Actually mock_class.a will create another MagicMock, which don't have a spec. The only way I can think of is to assign the attribute a of the mock_class with another MagicMock with spec, like this:
mock_class = MagicMock(spec=[u'a'])
mock_class.a = MagicMock(spec=[u'a'])
hasattr(mock_class.a, u'c')  # returns False

Also if you have some real objects you want to mock, there is a possibility to do some recursive autospecing.


text:
Q: How to access fragment variable into main activity class I have 1 main activity class and 1 fragment class:
I want to access variable of fragment class into my main activity class:
Myfragment class:
public class DemoFragment extends Fragment {

Public String mydata="hello";
.. //other code
}

Mainactivity class:
public class MainActivity extends ActionBarActivity {

   ..//other code
   DemoFragment df;

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;

        df = new DemoFragment();

        String newdata = df.mydata; //access from fragment but it shows null

    }

}

So how can i access fragment class variable values into main activity?

A: In your fragment create
(a) Two fields:
listener mCallback;
Activity mActivity;

(b) Interface:
interface mydataBack(){
   public void bringBackString(String stringSentBack);
}

(c) Method
@Override
        public void onAttach(Activity activity) {
            mActivity=activity;
            super.onAttach(activity);
        mCallback = (listener) mActivity;
        }`

Then in the Fragment call the method bringBackString(String) when you wish to send back the string.
In your mainactivity:
(a) add in the "implements.. ...listener" in the class declaration
public class MainActivity extends ActionBarActivity implements DemoFragment.listener {  etc   and

(b) implement the interface method:
public void bringBackString(String stringBroughtBack){
....  do something with the string
}

A: you have yo use
 public static String mydata = "hello "
and then get it in activity by using df.mydata


text:
Q: Diffeomorphisms of generic foliations Given a "generic" foliation with 1-dimensional leaves on a closed manifold M, I would like to claim that there are no diffeomorphisms of the manifold fixing the foliation, other than flowing along the leaves.
I am pretty sure that such a statement should be true (although it may require some additional hypotheses), but don't know how to prove it.
Could anyone suggest some relevant references (preferably ones which avoid going too deeply into the theory of foliations)?


text:
Q: How to print a string on the same window I typed and not in a popup in Java So, this is my code:
import java.awt.*;
import javax.swing.*:

public class NewClass extends JFrame{
    private JTextField item1;
    private JTextField item3;
    private JTextField item4;

    public NewClass(){
        super("The title");
        setLayout(new FlowLayout());

        item3 = new JTextField("Agrega el nombre del evento y da Enter", 22);
        item3.setEditable(false);
        add(item3);

        item1 = new JTextField(22);
        add(item1);

        thehandler handler = new thehandler();
        item1.addActionListener(handler);
        item3.addActionListener(handler);
        item4.addActionListener(handler);

    }

    private class thehandler implements ActionListener{

        public void actionPerformed(ActionEvent event){

            String string = "";

            if(event.getSource()==item1)
                string=String.format("Process ready: %s", event.getActionCommand());
            else if(event.getSource()==item3)
                string=String.format("field 3:%s", event.getActionCommand());

            JOptionPane.showMessageDialog(null, string);
        }
    }

}

And this is my main:
import javax.swing.JFrame;

public class ProyectoSOD {
    public static void main(String[] args) {

        NewClass odioSOD = new NewClass();
        odioSOD.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        odioSOD.setSize(300, 350);
        odioSOD.setVisible(true);
    }

}

What I want to do, is to have the text in the TextField(from item3) saved unto another TextField with .setEditable(false) in the same window so I can write a text line(on item3), press enter, and have it saved in the same window, then rewrite the line, press enter, and have it shown with the previous text. I wanna be able to stack all this text everytime I press enter.
My current program has the message shown in a popup window, but I need to stack multiple lines.
Thanks :)

A: I'm not sure what you're looking to do.  If you want to keep track of everything entered into the textfield, like a history of input, you could do what Eric Jablow said and use a JTextArea.  So when the user enters input into the textfield and hits enter, it'll append the text from the textfield into the textarea.
http://docs.oracle.com/javase/tutorial/uiswing/components/textarea.html
That might be a good place to start.


text:
Q: Changed load behavior in WPF app after upgrading PRISM from 4 to 6.1? (This is a version of a question that I posted earlier ( deleted post ). That question got deleted because I have been away for a month and unable to respond to comments. I would like to thank the users @StepUp and @Brian Lagunas for the comments they made there, and apologize for not responding to them.)
A month ago I test upgraded an WPF application from using PRISM 4.0 to using PRISM 6.1. For the most part I have just changed the references to the new assemblies, and changed the parts where base-classes and methods had gotten new names.
The application has a main menu that consists of a AnimatedTabControl that is the MainRegion. Then different modules are registered with the main region. These can again consist of different views containing even more views.
What I see after the upgrade to PRISM 6.1, is that switching between views in the AnimatedTabControl takes a lot longer time (the first time) with PRISM 6.1 than it did with PRISM 4. (For one of the modules that has a lot of views in it, the first click has gone from 1,3 seconds (prism 4) to over 5 seconds (prism 6.1).
After some more investigating, I have found that a probable cause for this change in performance, is that the time for when the different constructors for the ViewModels are called, has changed. In the old app with PRISM 4, all the viewmodels under the different views seems to be called at start up of the application, so that loading of look up collections from DB is done then. After upgrading to PRISM 6.1, this loading seems to have been deferred to when the user clicks on a specific menu item the first time.
I wonder if anyone has some pointers as to where I should start looking for a setting that has changed this. Brian Lagunas says that there are no changes in the PRISM framework from 4 to 6.1, so it must be in my application. That might very well be the case, all though I tried not to change any thing else while upgrading. Any pointers are welcome.
regards Gert


text:
Q: selenium webdriver in python So basically I'm trying to make script in python that uses selenium webdriver to open and login to a website called marketsworlds and retrieve the market value of a stock. I have the script able to open and login into the page. I just cant figure out how to capture/get the market value and have it print out. I used inspect element to find the class:
<p class="market_value">

</p>

in between the open and close brackets inspect element displays the market value, which constantly changes.
I tried setting driver.find_element_by_class("market_value") to a variable and printing the variable. I get a print out of " at object 0x" and what ever comes after the x. any way to return what it actually displays?

A: If you have to use Selenium for navigation, such as on JavaScript-heavy sites, It would suggest acquiring the page source and using an HTML parser to extract the data you want.
BeautifulSoup is a great choice of parser. For example:
html = driver.page_source
soup = BeautifulSoup(html)

# Get *all* 'p' tags with the specified class attribute.
p_tags = soup.findAll('p',{'class':'market_value'})
for p in p_tags:
    print p.text

This should print to screen the text contained in the <p> tags with the class market_value. Its hard to give specifics without knowing the exact page source, however.
However, if you're determined to use strictly Selenium, you can find these elements by:
# Get *all* 'p' tags with the specified class attribute.
elements = driver.find_elements_by_class_name('market_value')
for element in elements:
    print element.text

# or

# Get a *single* 'p' tag with the specified class attribute.
element = driver.find_element_by_class_name('market_value')
print element.text


text:
Q: How to filter specific messages received from a websocket api in python as they stream in and write them to CSV I am VERY new to coding and Python and I am trying to just receive live trade data from the Bitfinex API, and filter out specific messages as they come in because it gives duplicates. I want to take these filtered messages and then output them to a csv file continuously.
Specifically, I want to save the messages titled "te" (see output from API below) because these are the trades that are executed as they are executed. The stream gives "tu" as well, which are duplicates. I want to just take the "te" and download them live into a csv for other processing and saving.
Here is my code, which is a stripped down version of one that I found online:
import websocket
import time
import sys
from datetime import datetime, timedelta, timezone

import sched, time
import json
import csv
import requests

class BitfinexWebSocketReader():
    endpoint = "wss://api.bitfinex.com/ws/2"
    def __init__(self):
        #websocket.enableTrace(True)
        self.ws = websocket.WebSocketApp(
                BitfinexWebSocketReader.endpoint,
                on_message = self.on_message,
                on_error = self.on_error,
                on_close = self.on_close
         )
        self.ws.on_open = self.on_open

        try:
            self.run()
        except KeyboardInterrupt:
            self.ws.close()

    def run(self):
        self.ws.run_forever()
        print("### run ###")
        pass

    def on_message(self, ws, message):
        print(message)

    def on_error(self, ws, error):
        print(error)
        sys.exit()

    def on_close(self, ws):
        print("### closed ###")

    def on_open(self, ws):
        #print("### open ###")
        ws.send(json.dumps({"event": "subscribe", "channel": "Trades", "symbol": "tBTCUSD"}))

if __name__=="__main__":
    BitfinexWebSocketReader()

And here is an example of a couple seconds of the output:
{"event":"info","version":2,"serverId":"88c6df7e-5159-4a8e-b1c4-f08904aeeb0a","platform":{"status":1}}
{"event":"subscribed","channel":"trades","chanId":23,"symbol":"tBTCUSD","pair":"BTCUSD"}
[23,[[281534165,1534448458635,0.005,6401.5],[281534164,1534448457975,0.01999998,6401.5],[281534139,1534448438766,-0.31749096,6401.4],[281534132,1534448438051,0.005,6401.5],[281534116,1534448432624,-0.051,6401.4],[281534099,1534448425380,0.18699482,6401.5],[281534097,1534448424900,0.013558,6401.5],[281534096,1534448424718,0.0514726,6401.5],[281534083,1534448415788,0.005,6401.8],[281534080,1534448415568,-1,6400.8],[281534079,1534448415566,-1,6401.8],[281534073,1534448409395,-0.0325,6403],[281534053,1534448398108,-0.2498,6405.1],[281534048,1534448396370,-0.25,6404.9],[281534043,1534448394675,0.42406762,6400],[281534029,1534448390257,0.30000001,6400],[281534028,1534448390236,0.30000001,6400],[281534027,1534448389714,1,6400],[281534025,1534448389033,1.18922278,6400],[281534024,1534448389030,0.41523564,6399.7],[281534023,1534448389028,0.39554158,6399.7],[281534013,1534448384920,0.025,6399.7],[281534011,1534448382885,0.018794,6399.7],[281534008,1534448380817,-1.49155951,6399.6],[281534007,1534448380815,-2.5,6399.6],[281534006,1534448380813,-0.34,6399.6],[281534005,1534448380811,-0.15098794,6399.6],[281534004,1534448380808,-0.29899445,6399.6],[281534000,1534448379152,-0.005,6399.6],[281533999,1534448377821,-0.16825162,6399.6]]]
[23,"hb"]
[23,"te",[281534199,1534448478028,-0.00937287,6401.4]]
[23,"te",[281534200,1534448478031,-0.29062714,6401.4]]
[23,"te",[281534201,1534448478036,-0.30000001,6401.4]]
[23,"tu",[281534201,1534448478036,-0.30000001,6401.4]]
[23,"tu",[281534199,1534448478028,-0.00937287,6401.4]]
[23,"tu",[281534200,1534448478031,-0.29062714,6401.4]]
[23,"te",[281534204,1534448478180,-0.65915285,6401.4]]
[23,"tu",[281534204,1534448478180,-0.65915285,6401.4]]
[23,"hb"]
[23,"te",[281534224,1534448479402,-0.114,6399.9]]
[23,"tu",[281534224,1534448479402,-0.114,6399.9]]
[23,"te",[281534232,1534448480466,-0.00012512,6399.9]]
[23,"tu",[281534232,1534448480466,-0.00012512,6399.9]]

Bonus question: why does that super long first entry pop up every time I execute the code?

A: You can initialize some kind of data structure in the constructor, like a list() or a set() to store the desired messages and then filter them in the on_message method.
So in your constructor
def __init__(self):
    #websocket.enableTrace(True)
    self.ws = websocket.WebSocketApp(
            BitfinexWebSocketReader.endpoint,
            on_message = self.on_message,
            on_error = self.on_error,
            on_close = self.on_close
     )
    self.ws.on_open = self.on_open
    self.store = []

    try:
        self.run()
    except KeyboardInterrupt:
        self.ws.close()

And in your on_message method
def on_message(self, ws, message):
    if "te" in message:
        self.store.append(message)
    print(message)


text:
Q: WIFI not working Acer Aspire 3690 - BCM4311 WIFI still does not work, I tried several options. Is there something that will work 100%? I expected that linux will be easier!
I have LUBUNTU 14.10.
First I tried:
sudo apt-get remove --purge bcmwl-kernel-source
sudo apt-get install linux-firmware-nonfree

And ... does not work.
Then I found the discussion to another command. For this to me disappeared and LAN, so that I was completely cut off from the internet and I had to reinstall the whole Lubuntu again :(
linux-headers-generic

On the contrary, the third time I found a script that ZEPRO works. And ... does not work.
sudo apt-get install firmware-b43-installer b43-fwcutter

I tried to insert the * .inf driver of WIN7 for my wifi card via WINE - Ndiswrapper. Hardware not found, but the configuration - adding wifi, again nothing.
WIFI is working  and even finds SSID, but when I enter the correct WPA password, it does not connect WIFI. I also tried to reset the password of the  WIFI router , but the notebook does not connect via WIFI.

A: First of all, ndiswrapper is not required. Let's remove it:
sudo apt-get purge ndiswrapper-common
sudo rm -rf /etc/ndiswrapper

Make sure that the needed driver is loaded:
lsmod | grep b43

If not, let's load it:
sudo modprobe b43

If it didn't load automatically, it is probably blacklisted somewhere; check:
ls /etc/modprobe.d

Once you post the result, we'll find and remove the blacklist.
Finally, be certain the wireless switch or key combination is set to enable wireless:
rfkill list all


text:
Q: vb 6.0 Background color in Printer object the code is writing in white on black but the black background is always printing and what should I do thanks
Private Sub Command1_Click()

CommonDialog1.Action = 5

 Dim Txt As String
 Dim PosX As Single
 Dim PosY As Single
 Txt = "TEST TEST TEST"
 PosX = 1
 PosY = 1
 Printer.Line (PosX, PosY)-(PosX + TextWidth(Txt), PosY + TextHeight(Txt)), vbBlack, BF
 Printer.CurrentX = PosX
 Printer.CurrentY = PosY
 Printer.ForeColor = vbWhite
 Printer.Print Txt

Printer.EndDoc

End Sub

Sample output:


text:
Q: Cartographer Unlock A Map Does anyone know how to Unlock A Map/complete the Cartographer objective? I have completed all other challenges but can't seem to complete this one.

A: To unlock a map, simply tap Map at the bottom of the screen in the menu, and using gems (500), unlock a map.
If you have already unlocked a level, the achievement will automatically unlock in the objective screen after the next run you complete.


text:
Q: Calculating the number of disconnected components of a NetworkX graph Starting with a randomly generated tree, I want to consider each node of the tree and potentially remove it with some probability p. Since trees have no cycles and there is a unique path between any pair of nodes, the removal of a node should leave d disconnected trees in its wake, where d is the degree of that node.
My question is, once I've done this for the whole graph, how can I check how many of these unconnected segments there are?
import networkx as nx
import random as rand

n = 20
p = 0.1

G = nx.random_tree(n)
for i in range(0, n):
    if rand.random() < p:
        G.remove_node(i)

x = G.count_disconnected_components() # is there anything that accomplishes this?

For example, for this graph, G.count_disconnected_components() should return 3.

A: It seems to me you actually want to count the number of connected parts. Try number_connected_components:
print(list(nx.connected_components(G)))
print(nx.number_connected_components(G))


text:
Q: java @Inject annotation returns null I am trying to inject a method from another class, but it returns null and throws a NullPointerException. Please let me know what mistake am I doing here.
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/")
public class Employee {
    @Inject
    EmployeeService employeeService;

    @GET
    @Path("/empXml")
    @Produces({ "application/xml" })
    @RolesAllowed({"employee"})
    public String getHelloWorldXML() {
        return "<xml><result>" + employeeService.createHelloMessage("Employee") + "</result></xml>";
    }

    public static void main(String[] args){
        Employee em=new Employee();
        System.out.println(em.getHelloWorldXML()); //gives NPE
    }

}

public class EmployeeService {
    int x = 10;

    String createHelloMessage(String name) {
        return "Hello " + name + "!";
    }

}

A: I added bean.xml file to my project's WEB-INF folder. And that solved the issue.
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

      <!-- An application that uses CDI must have a file named beans.xml.
      The file can be completely empty (it has content only in certain
      limited situations), but it must be present. -->

</beans>


text:
Q: Uploadify will not work in ssl I am using a coldfusion upload page to upload pictures to a server. I cannot put the script in the root of the ssl path. The uploader finishes with no error, but the upload script is not being called. (I have an email sent as soon as page loads) Works only in ie8.
<script type="text/javascript">
$(document).ready(function() {
$('#fileInput').uploadify({
'uploader'        : 'uploadify.swf',
'script'          : 'upload.cfm?id=<cfoutput>#NewId#</cfoutput>',
'cancelImg'       : 'uploadify/cancel.png',
'auto'            :  true,
'sizeLimit'       : '2097152',
'fileExt'         : '*.jpg;*.gif;*.png;*.docx;*.doc;*.xlsx;*.xls;*.pdf',
'fileDesc'        : 'Image Files',
'multi'           : true,
'removeCompleted' : false,
'onComplete'      :
  function(event, queueID, fileObj, response, data) {
      if(response == "hello") {
       $('#mydiv').html("hello"); }
       }                    });
                    });
</script>

UPLOAD
<!--- -------------------------------------------->
<cfset dest_dir = "c:\test\">

<cffile action="UPLOAD" filefield="Filedata" destination="#dest_dir#"  result="fileRes" nameconflict="MAKEUNIQUE">

<cfoutput>hello</cfoutput>

A: I have done this also in coldfusion - my uploadify.cfm has within the CFFILE tag a result="result" and I output the file name from the finished upload:
<CFOUTPUT>#result.serverfilename#</CFOUTPUT>


text:
Q: Hashing in MySQL I want to hash some text along with the value of a table column in mysql. I am doing this but it gives a different value on comparing to which i expect.
SELECT SHA1('a='+p.ItemID) FROM Items p WHERE p.ItemID = 412

The above query gives some different result, but i need the results which the below query yields:
SELECT SHA1('a=412')

Why do the results differ?
Please help.
Are these two queries not the same?

A: SELECT SHA1(CONCAT('a=', p.ItemID)) FROM Items p WHERE ItemID = 412

A: Try this:
SELECT SHA1(CONCAT('a=',p.ItemID)) FROM Items p WHERE p.ItemID = 412

See this page in the MySQL manual for more on CONCAT(), which is different from +, the addition operator. This is why your results differ.


text:
Q: How To alert user they have not saved before leaving a page. Ignore Postbacks Requirement: I am attempting to alert the user when they leave a page that their changes will be lost.
Problem: I am using webforms and the only solution I have seen to alert the user is using javascript's 'window.onbeforeunload'. This would work great if it didn't fire every time a postback occurred.
Page description: This is a page inherits in a masterpage. The master page is simply a navigation bar with a few hyperlinks. The content page consist of numerous text boxes and a few drop down select boxes.
Question: How do I determine if the javascript event window.onbeforeunload is fired by a postback or not (dirty or not)?
Thank you guys, this is my first question asked. Hopefully I was descriptive enough. I am not allowed to share all of the code due to company policy. Any question I will be happy to answer.

A: For this We need to check whether any Input fields or form got edited.
Example:
function isDirty(form) {
for (var i = 0; i < form.elements.length; i++) {
    var element = form.elements[i];
    var type = element.type;
 switch (type) {

        case "checkbox":
        case "radio":{
            if (element.checked != element.defaultChecked) {
                return true;
            }
            break;
        }
      }

}


text:
Q: Less than equal to (<=) relation as morphism between natural numbers (objects) How can I prove that "less than equal to" relation is valid morphism between natural numbers in category theory i.e it composes associatively.

A: Natural numbers are totally ordered with regards to $ \leq $.  Due to this $ \leq $ is transitive for all triples of natural numbers.  That is $ a \leq b \land b \leq c \implies a \leq c $.  Composition flows from this.


text:
Q: pgfplots - function doesn't reach x-axis I'm unable to reach the x-axis with my function. Doesn't anyone have an idea how to solve this problem?

%%%%%%%%%%%%%%%%%% INTRODUCTION %%%%%%%%%%%%%%%%%%
\documentclass[]{standalone}
%%%%%%%%%%%%%%%%%% INPUT %%%%%%%%%%%%%%%%%%
%\input{preamble.tex}
%\input{parameters.tex}
%%%%%%%%%%%%%%%%%% PACKAGE %%%%%%%%%%%%%%%%%%
\usepackage{tikz, tkz-euclide}%  permet de dessiner des figures, des graphiques
\usetikzlibrary{%
    matrix,
    arrows,
    arrows.meta,
    bending,
    calc,
    math,
    shapes,
    backgrounds,
    decorations.markings,
    }

\usepackage{pgfplots}
%%  FONT
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
%
\usepackage{tgadventor}% paquet de police de caractère TGadventor
\usepackage{sansmath}%  Copie-colle la police active dans
%                       \sfdefault (/!\ N'EST PAS UNE POLICE DE CARACTÈRES)
\usepackage{xcolor}

\tikzset{%
    graphpgf/.style={%
        font={\sansmath\sffamily\Large},
        line cap=round, line join=round,
        >={Latex[length=3mm]},
        x=1.0cm, y=1.0cm,
        background rectangle/.style={fill=white, shift={(-5pt,-5pt)}},
        show background rectangle,
        inner frame sep=10pt
    }
}

\pgfplotsset{%
    /pgfplots/graphxy/.style={%
        %%%%%%%%%%  Dimensionnement de l'image  %%%%%%%%%%
        width=13.5cm,
        height=13.5cm,
        unit vector ratio=1 1 1,
        %%%%%%%%%%  esthétique des axes  %%%%%%%%%%
        xlabel=$\mathrm{x}$,         ylabel=$\mathrm{y}$,
        axis lines = middle,
        enlargelimits=false,
        line width=0.4mm,
        every major grid/.append style={black!20, line width=0.35mm,},
        every minor grid/.append style={black!15, line width=0.15mm,},
        every major tick/.append style={line width=0.4 mm, major tick length=7pt, black},
        every minor tick/.append style={line width=0.15mm, minor tick length=4pt, black},
        %axis background/.style={fill=white},
        grid=both,
        axis line style = {shorten >=-12.5pt, shorten <=-12.5pt, -{Latex[length=3mm]}},
        xlabel style={at={(ticklabel* cs:1)},yshift=-3.5pt, anchor=north west, font=\sansmath\sffamily\Large},
        ylabel style={at={(ticklabel* cs:1)},xshift=-3.5pt, anchor=south east, font=\sansmath\sffamily\Large},
        title style = {font=\sansmath\sffamily\Large, align=center, inner sep=12pt,},
        extra x ticks={0},
        extra x tick style={%
            grid= none,
            xticklabel style={%
                below right,
            },
            every major tick/.append style={%
                scale=1,
                draw=none,
                postaction={decorate},
                decoration={%
                    markings,
                    mark=between positions 3.5pt and 1 step 7pt with{%
                      \draw[fill] (0, 0) circle (1.5pt);
                    },
                },
            },
        },
    }
}
%%%%%%%%%%%%%%%%%% DOCUMENT %%%%%%%%%%%%%%%%%%
\begin{document}
\begin{tikzpicture}[graphpgf]

%%%%%%%%%%%%%%%%%% Data Table %%%%%%%%%%%%%%%%%%
    \begin{axis}[%
        graphxy,
        %minor tick num=1,
        %%%     Axe x
        xmin=-5-0.3, xmax=5+0.3,
        xtick={-100,-99,...,100},
        %xticklabels=(,-6,,-4,,-2,,),
        %minor xtick={-10,...,8},
        %domain=-6:6,
        %%%     Axe x
        ymin=-2-0.3,ymax=8+0.3,
        ytick={-100,-99,...,100},
        %minor ytick={-8,...,8},
        %restrict y to domain=-3:7,
               ]%
                \addplot[%
                    color=orange,
                    opacity=0.8,
                    line width=0.4mm,
                    samples =2048,
                    domain=-4.606715:1.356715,
                    restrict y to domain=-0.00001:5.9635,
                    smooth,
                    ]%
                    {sqrt(-4* x^2 -13 * x +25)}
                    %node [right , pos=0.04, scale=1.2] {f(x)}
                ;
        ;
    \end{axis}
\end{tikzpicture}
\end{document}

From time to time I encounter this problem and finding a solution is always laborious. Would you have any tips?

A: You need a Minimal Working Example: I've just been asked to write a minimal working example (MWE), what is that?
I do not know what you try to obtain with the options domain=-4.606715:1.356715 and restrict y to domain=-0.00001:5.9635. One would normally use round numbers for these.
For a symmetric plot, you need an odd number of samples. I do not know how to make the end start at the exact correct point but you can cheat by pulling the ends down, when they are small enough with y filter like this:
\documentclass[tikz]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[%
  grid=major,
  xmin=-5, xmax=3,
  ymin=-2, ymax=8,
]%
\addplot[%
  orange,
  samples=2047,
  domain=-5:2,
  smooth,
  y filter/.expression={y<0.1 ? 0 : y}
]%
   {sqrt(-4* x^2 -13 * x +25)};
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: AVPlayer unable to play video from NSDocuments Directory on iOS8 I'm trying to get my app to play a video that has been downloaded to the Documents Directory.
My code works when tested on the iOS 7.1 simulator but not on iOS 8.0 devices or the iOS 8.0 simulator. There isn't any error, AVPlayer does not play the video and shows a Black View.
I also checked the Document's folder of my device with XCode's Organizer and the file appears to be successfully downloaded.
Here is a simplified version of my code.
// file_path is a string that stores the path to the video file a println of it shows
// "/var/mobile/Containers/Data/Application/83C7837C-59B5-4767-A579-7CE758A93C6F/Documents/og4gr.mp4"
var path:NSURL = NSURL.fileURLWithPath(file_path, isDirectory: false);
_player = AVPlayer(URL: path);

Has anyone else encountered this? Thank you for your time!

A: So the problem was that the Application Documents Folder Path changes every time you launch the app and I was storing the absolute path of the video file.
According to this article here:
http://pinkstone.co.uk/where-is-the-documents-directory-for-the-ios-8-simulator/, this is how it is now in iOS 8, which is why while my method worked in iOS7 it was failing on iOS8 devices and Simulators. Thank you @RoboticCat for pointing me in the right direction!


text:
Q: Is there a way to unwrap from optional variable? Is there a way to "unwrap" variables returned by reload method?
let reloadProps: ReloadProps | undefined;

if (useClientSide() === true) {
    reloadProps = reload(props.eventId);
}

const {
    isTiketAdmin,
    jwt,
    userFbId,
    organizationId,
    organization,
    event,
    enableSaleSwitch,
    enableSaleSwitchOnWordpress,
    permission,
} = reloadProps;

Now I got this error:
./pages/[lang]/event/[...eventId].tsx:72:5
Type error: Property 'isTiketAdmin' does not exist on type 'ReloadProps | undefined'.

  70 |   }
  71 |   const {
> 72 |     isTiketAdmin,
     |     ^
  73 |     jwt,
  74 |     userFbId,
  75 |     organizationId,
error Command failed with exit code 1.

A: The main problem is, that the values you want to get out of reloadProps are not available if is undefined. You have to check that the value is not undefined beforehand:
if (reloadProps !== undefined) {
  const {
    isTiketAdmin,
    jwt,
    userFbId,
    organizationId,
    organization,
    event,
    enableSaleSwitch,
    enableSaleSwitchOnWordpress,
    permission,
  } = reloadProps;
}

This way the compiler can infer, that the type is not ReloadProps | undefined  anymore but ReloadProps only and then you can access the values.