text:
Q: DataSet does not support System.Nullable<>.' Entity Framework I need my property to allow null, so I declare it as
Nullable<double> Nat_Salary

but when doing so, I get this error

DataSet does not support System.Nullable<>.

This is my code to call the stored procedure and pass table to Crystal Report
if (Report_Number == "2")
{
   var Employee_Data = db.Database.SqlQuery<SR1_Result>("SR1").ToList();
   bs.DataSource = Employee_Data;
}

ReportDocument rpt = new ReportDocument();
rpt.Load(Application.StartupPath + "\\Report\\Arabic\\" + "R" + Report_Number + ".rpt");

rpt.SetDataSource(bs);

This is my class
public partial class SR1_Result
{
    public int EmployeeCode { get; set; }
    public string EmployeeName { get; set; }
    public string JobName { get; set; }
    public System.DateTime Date_Hiring { get; set; }
    public Nullable <double> Nat_Salary { get; set; }
    public string AdministrationName { get; set; }
    public string DepartmentName { get; set; }
    public string BranchName { get; set; }
}

This is the stored procedure:
ALTER PROCEDURE [dbo].[SR1]
AS
BEGIN
    SELECT
        EmployeeCode,EmployeeName,
        JobName,
        Date_Hiring,
        Nat_Salary,
        AdministrationName,
        DepartmentName,
        BranchName
    FROM
        Employee_List_Code_Name_Jop_DateHiring s
END

How can I fix this error without removing the nullable from the Nat_Salary ?

A: At a guess, because the code you've shown doesn't actually mention or use a DataSet/DataTable at all, Crystal Reports is internally unpacking your List<SR1_Result> to a DataTable, and automagically creating the columns but is blindly passing the Nullable<double> SR1_Result.Nat_Salary to a datatable.Columns.Add("Nat_Salary", typeof(Nat_Salary)) (or its reflective equivalent, and DataTable is objecting to a column being declared as Nullable
You'll have to fix up the shape of the object you pass in, and most sensibly it'll probably look like a DataTable that you create rather than leaving it to CR to do
Drop the ToList call and write a loop/some code that creates a datatable and populates it to pass to CR. The column can be declared as having a typeof(double) and also AllowDbNull = true then as you're populating, if the Nat_Salary is null, don't set a value for that column
Simplistically:
var dt = new DataTable();
...
dt.Column.Add("Nat_Salary", typeof(double)).AllowDbNull = true;
...

foreach(var x in db.Database.SqlQuery<SR1_Result>("SR1"))
  var ro = dt.Rows.NewRow();
  ...
  if(x.Nat_Salary.HasValue)
    ro["Nat_Salary"] = x.Value;
  ...
}

Or if there is a sensible conversion for Nat_Salary to a non nullable type you can .Select an anonymous type for CR to convert that uses a substitute value for Nat_Salary
var r = db.Database.SqlQuery<SR1_Result>("SR1").Select(x =>
  ...,
  Nat_Salary = x.Nat_Salary.GetValueOrDefault(0),
  ...
);

This will change the SR1_Result into an anonymous type that has a Nat_Salary that is no longer a Nullable<double> but just a normal double and CR won't explode when it is internally converting to datatable

In both these code samples the ... are your other columns in SR1_Result. You're gonna have to list them out unless you want to get into doing the same reflective "look at the object, list its property names and types and turn it into a datatable but apply some custom logic if the property is nullable" process

Or, perhaps CR already ran into this broken behaviour and put out a version of CR that checks if the property is nullable, and makes a column that allows nulls of the type that Nullable wraps - check for updates/speak to CR (whoever owns them now)


text: Q: Import matplotlib.pyplot in python 2.7 I am using Anaconda (python 2.7) spyder interface. I am new in python. I want to "import matplotlib.pyplot as plt" but it says "No module named matplotlib.pyplot". I already installed matplotlib from command line using "conda install matplotlib" ! I don't know how it works !

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dropdownlist in gridview's EmptyDataTemplate is not populating <EmptyDataTemplate>
                  <asp:DropDownList ID="ddlRateCode" runat="server" DataSourceID="odsRateCode" DataTextField="RateCode"
                        DataValueField="RateCodeID" SelectedValue='<%# Bind("RateCodeID") %>'>
                    </asp:DropDownList>
   </EmptyDataTemplate>

A: Try to force a manually DataBind()
Like this:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.EmptyDataRow)
        {
            DropDownList ddl = (DropDownList)e.Row.FindControl("ddlRateCode");
            if (ddl != null)
            {
                ddl.DataBind();
            }
        }
    }


text:
Q: macOs Android Emulator: qemu-system-i386 - image not found When I try to start the emulator from AVD manager, shows a message:
emulator: Android emulator version 30.5.3.0 (build_id 7196367) (CL:N/A)
dyld: Library not loaded: /System/Library/Frameworks/IOUSBHost.framework/Versions/A/IOUSBHost
  Referenced from: /Users/<UserName>/Library/Android/sdk/emulator/qemu/darwin-x86_64/qemu-system-i386
  Reason: image not found

Where is problem ?
Thank you in advance for any help.

A: Check if you have the latest Android emulator version installed - 30.5.4.  SDK Manager > SDK Tools > Android Emulator
It was happening for me with the previous versions of the emulator.
Now it works as they have released a new update.


text:
Q: Check self-updated file (C++) I've written a script that should continuously check whether a file has increased in size or not.
I tried simply linking to a file which I can update from another desktop, but nothing happens.
Does anyone know how to check the file I've updated through ssh without having to restart the program?
I'm looking for answers that I can use on a Linux system (Raspberry Pi 3B).
Thank you in advance!
Code that checks the files:
streampos fileSizeReference = 0;
fatream fileReader("some/random/file.txt", ios::int | ios::out);

fileReader.seekg(0, ios::end);

if( fileReader.tellg() > fileSizeReference ) {
    update();
}


text:
Q: Emulating a LEFT JOIN in Spring Entity In effect, what I am trying to do is this...
SELECT a.*, b.description, c.description FROM a
LEFT JOIN b ON b.code = a.b_code
LEFT JOIN c ON c.code = a.c_code

I would like to map this entirely using Spring/JPA framework. I've played around with @SecondaryTable only to find out that it will not work in thie case, and I've been getting a number of errors while trying to map it using @OneToOne or @JoinColumn. Here are my current entity classes...
@Entity
@Table(name = "a")
public class a {
    @Id
    @Column(name = "id")
    private String id;

    @Column(name = "b_code")
    private String bCode;

    //I'd like to have b.description here

    @Column(name = "c_code")
    private String cCode;

    //I'd like to have c.description here
}

@Entity
@Table(name = "b")
public class b {
    @Column(name = "code")
    private String code;

    @Column(name = "description")
    private String description;
}

@Entity
@Table(name = "c")
public class c {
    @Column(name = "code")
    private String code;

    @Column(name = "description")
    private String description;
}

A: You need to use @JoinColumn with referencedColumnName as shown below.
@Entity
@Table(name = "a")
public class a {
    @Id
    @Column(name = "id")
    private String id;

    @Column(name = "b_code")
    private String bCode;

    //I'd like to have b.description here

    @Column(name = "c_code")
    private String cCode;

    //I'd like to have c.description here

    @OneToOne // this should be based on your joining
    @JoinColumn(name = "b_code", referencedColumnName = "code", insertable = false, updatable = false)
    B b;

    @OneToOne// this should be based on your joining
    @JoinColumn(name = "c_code", referencedColumnName = "code", insertable = false, updatable = false)
    C c;
}

@Entity
@Table(name = "b")
public class B {
    @Column(name = "code")
    private String code;

    @Column(name = "description")
    private String description;
}

@Entity
@Table(name = "c")
public class C {
    @Column(name = "code")
    private String code;

    @Column(name = "description")
    private String description;
}


text:
Q: Oracle : Is there a way to grant the ability to run a job to a role? We have several dbms_scheduler jobs in an 11.2 database that we would like users with a certain role to be able to run.  As such, we don't want to grant the ability to run directly to the users, as it will be more difficult to maintain.
Based on Oracle's documentation, granting ALTER JOB to the user will allow them to run the job.  Unfortunately, it doesn't appear this extends to roles: I can run the GRANT statement just fine, and the job shows up in ALL_SCHEDULER_JOBS for the user, but attempting to run the job results in the following error:
ORA-27476: "S1.J1" does not exist
ORA-06512: at "SYS.DBMS_ISCHED", line 185
ORA-06512: at "SYS.DBMS_SCHEDULER", line 486
ORA-06512: at line 1

Given that DBMS_SCHEDULER is AUTHID USER, but DBMS_ISCHED is AUTHID DEFINER, am I just out of luck?  Or is there a way I can grant it to the role and not the user?

A: This sounds like the usual problem with stored procedures: when they are compiled by developer A in his schema, the compiler only considers the privileges DIRECTLY granted to A - as if the roles were all stripped off before compiling.  This is often addressed by writing your procedure as AUTHID CURRENT_USER, but if the procedure calls another procedure granted through a role, it can fail.
Generally it seems anything you want to compile into a PL/SQL object has to be directly granted to you.  I've written a number of scripts to turn role-granted privileges into direct GRANT statements to the procedure owner so that it would compile.
Note this does not apply to anonymous blocks - they compile and run just fine with the benefit of your current roles' privileges.
So I think the scheduler is another case where you have to code as if the roles weren't there.  It's a pain and I hate it, but that's how it is.


text:
Q: Sitefinity multilingual site - Dynamic module related image showing (not translated) even after translating the content item Sitefinity multilingual site - Dynamic module related image showing (not translated) even after translating the content item - issue
I am currently working on Sitefinity multilingual (English & Hindi) web application where I am getting a very strange issue regarding related media upload.
In my image gallery, I have a custom field for upload image. When I am adding a Hindi content for an image for the Hindi translation, the image is showing the (not translated) message and the image is not showing in the Hindi site after publish.

A: If you are using related media in a dynamic module on a multilingual site - you will need to have translated versions of that media available, in order for them to show on the translated version of that content type on the front end.
So if the item you're editing is for Hindi here, then your screenshot shows the second two images you have were created in English but don't have a Hindi version. You'll need to go into the image library, and translate that image.
As far as I can tell, you can't default to an image (or any kind of content) from another culture. This makes sense even for images though, because even if the images are the same, you should have different Alt text available for accessibility reasons.
What is nice though, is when you translate the image, you do not need to re-upload the image (unless you want to).


text:
Q: how to add sub array in main array in swift {
    "firstName": "AA",
    "lastName": "BB,
    "shortName": "CC",
    "nric": "12/AAA(N)123456",
    "gender": "F",
    "dob": "1.1.2000",
    "password": "admin123",
    "photo": {
        "image": "hello",
        "thumb": "world"
    }
}

Is there anyway how to add photo array in main array? I've done as follow
let photoArray = [
    "image": imageBase64,
    "thumb": imageBase64
]

let param = [
    "firstName": txtFirstName.text as! AnyObject,
    "lastName": txtLastName.text as! AnyObject,
    "shortName": txtShortName.text as! AnyObject,
    "nric":"",
    "gender": genderCode,
    "dob":txtDOB.text as! AnyObject,
    "photo": photoArray
]

but output is awful. Please let me how to do it.

A: Instead of making the param let make it var and do the following. You do need to specify the dictionary type as below
let photoArray : [String : AnyObject] = [
            "pic" : "myPhoto"
        ]
var param : [String : AnyObject] = [
            "name" : "UserName"
        ]

param["photo"] = photoArray

A:     let photoArray = [[
        "image": "a",
        "thumb": "b"],[
            "image": "a",
            "thumb": "b"]
    ]
let param = [
"firstName": txtFirstName.text as! AnyObject,
"lastName": txtLastName.text as! AnyObject,
"shortName": txtShortName.text as! AnyObject,
"nric":"",
"gender": genderCode,
"dob":txtDOB.text as! AnyObject,
"photo": photoArray

]
Hope you want like this.

A: let photoArray:[String:UIImage] = [
    "image": UIImage.init(named: "a.png")!,
    "thumb": UIImage.init(named: "b.png")!
]

let param:[String:AnyObject] = [
    "firstName": "AA",
    "lastName": "BB",
    "shortName": "CC",
    "nric": "",
    "gender": 0,
    "dob": "DD",
    "photo": photoArray
]

You can do it like this


text:
Q: Divide by zero error encountered. When Unıon Code i am pulling data to excel from sql server
Like : https://prnt.sc/to9ntg
but ı have to problem now,
because of Divide by zero error encountered
ı am login to sql and

---select * from [dbo].[TLP_CEK]

SELECT * FROM TLP
UNION
SELECT * FROM TLP_S1
UNION
SELECT * FROM TLP_S2

sql returning to me

Msg 8134, Level 16, State 1, Line 3
Divide by zero error encountered.

how can i fix this i am just  getting data(columns,tables)  sql-->to Excel


text:
Q: Unable to save file after recovery from backup I have a Windows Server 2003 that acts as the file server. I have moved a lot of files from a backup (different domain) to the new shares.
The strange thing is that people can open the files, but they can't save over it. Then it asks for a new filename (no overwrite).
I have tried to take ownership as administrator, and removing the read-only (gray) checkbox from the folder (incl. subfolders and files).
Someone knows what to do?

A: This sounds like your NTFS ACLs are incorrect. What I would do (which may work for you or may not, I'm not guaranteeing anything) would be this:

*

*Edit the properties for the folder containing the files, and set the permissions to what I want them to be

*Go into the Advanced section, and tick the "Replace permissions on child items" box
Click OK and wait while the permissions are updated

This will reset the permissions on everything inside the parent folder to be whatever the parent folder is. This answer does assume you know about NTFS permissions, if not then I would suggest reading up on them first so that you're comfortable with the concept.


text:
Q: Jquery validation, setup error message on the element that shall be validated I would like to customize the Jquery validation plug-in, so i can set up the error message on the element that shall be validated. And then insert the error message in a div placed under the element that is validated (Because i have the div, is to avoid the the design is changed when the error messages is shown) Fx.:
<asp:TextBox ID="Firstname" CssClass="required" errorMessage="Please fill out firstname" runat="server" />

I have tried this, but it isn't working (no erroe message is shown):
$("#form1").validate({
    onsubmit: false,

    errorElement: 'div',
    errorPlacement: function (error, element) {
        error[0].innerHTML = element.attr('errorMessage');
        error.insertAfter(element.closest('.divErrorMessage'));
    }
});

Thanks very much in advance!


text:
Q: How do I get only the first number without brackets in a list? I have a list l1 this is structured according to the scheme [(number1, number2), ... (number1n, number2n]. I would like to always only want the very first number and remove the brackets. How do I do that?
l1 = [(285, 1.0000001), (3614, 0.93460923), (671, 0.78742), (1351, 0.72903967), (3883, 0.6139718)]
l2 = [285, 3614, 671, 1351, 3883]

A: Try this:
l1 = [(285, 1.0000001), (3614, 0.93460923), (671, 0.78742), (1351, 0.72903967), (3883, 0.6139718)]

l2 = [i[0] for i in l1]

or
l2 = [i for i,j in l1]

Also you can do it with zip.
l2 = list(zip(*l1))[0]

Using map:
l2 = list(map(lambda x:x[0], l1))


text:
Q: How can I get the button title for each selected cell in a UICollectionView? I have a collectionView of buttons as pictured below. I want to be able to select multiple of these cells, and in doing so pass the title of each selected button into an array of Strings.
UICollectionView - each cell has a button with a title
The UICollectionView is in WordViewController class
class WordViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout

And the UICollectionViewCell is in it's own file.
import UIKit

class WordCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var wordView: UIButton!

@IBAction func buttonTapped(_ sender: UIButton) {
    if wordView.isSelected == true {
        wordView.isSelected = false
        wordView.backgroundColor = UIColor.blue
    }else {
        wordView.isSelected = true
        wordView.backgroundColor = UIColor.green
    }
}

}

I'm very new to Swift and I have been trying to find an answer to this for days, but I can't figure it out. I suspect I may have to use indexPathsForSelectedItems but I have tried this and can't get it working.
func indexSelected () {
        let collectionView = self.collectionView
        let indexPath = collectionView?.indexPathsForSelectedItems?.first
        print(indexPath!)
        let cell = collectionView?.cellForItem(at: indexPath!) as? WordCollectionViewCell
        let data = cell?.wordView.currentTitle
        print(data!)

}

I'm not sure if I have something fundamental wrong in the way I have set up my CollectionView or if it is something to do with me using buttons within the CollectionViewCells.
Any help would be very appreciated.

A: This is one way you could do it. First get the indexPaths for the selected cells. Then loop through the indexPaths and get your cell for each IndexPath (cast them as your custom CollectionViewCell to access your button). Now you can append each title to an array to save them.
var titleArray = [String]()

    guard let selectedIndexPaths = collectionView.indexPathsForSelectedItems else { return }

    for indexPath in selectedIndexPaths {
        if let cell = collectionView.cellForItem(at: indexPath) as? WordCollectionViewCell {
            self.titleArray.append(cell.yourButton.titleLabel?.text)
        }
    }

A: Welcome to SO. This sounds a bit like an X/Y problem: A case where you are asking about how to implement a specific (often sub-optimal) solution rather than asking about how to solve the problem in the first place.
You should not treat the views in your collection view as saving data. (buttons are views.)
You should use the button to figure out the indexPath of the cell the user tapped and then look up the information in your data model.
You should set up an array of structs (or an array of arrays, if your collection view is in sections of rows.) Each of those structs should contain the current settings for a cell.
Your collectionView(_:cellForItemAt:) method should use the array of structs to configure your sell for display.
As the user taps buttons and selects cells, you should update the struct(s) at the appropriate IndexPath(s) and then tell the collection view to update those cell.
If you need to do something with the selected cells, you should ask the collection view for an array of the selected cells, you should use those IndexPaths to index into your model array and fetch the struct for each IndexPath, and then look up teh data you need.
EDIT:
You can use a really simple extension to UICollectionView to find the indexPath of any view inside your collection view (and a button is a view, as mentioned...)
extension UICollectionView {
    func indexPathForCellContaining( view: UIView) -> IndexPath? {
        let viewCenter = self.convert(view.center, from: view.superview)
        return self.indexPathForItem(at: viewCenter)
    }
}


text:
Q: How to set text of multiple buttons using a for loop and the contents of an ArrayList - Java - Android I currently have 35 buttons, not all of which will be used by the final product.
I also have an arraylist with a variety of items:
ArrayList textBlobs = new ArrayList();

textBlobs.add("text");
textBlobs.add("two");
textBlobs.add("tt");
textBlobs.add("txt");
textBlobs.add("te");
textBlobs.add("tet");
textBlobs.add("go");
textBlobs.add("eat");
textBlobs.add("spring");
textBlobs.add("rolls");
textBlobs.add("egu77$");

I also have 35 buttons called buttonx with x being a number 0 through 34 (35 total)
private Button button0, button1, button2, button3, button4, button5, button6, button7, button8, button9, button10, button11, button12, button13,
        button14, button15, button16, button17, button18, button19, button20, button21, button22, button23, button24, button25, button26, button27,
        button28, button29, button30, button31, button32, button33, button34;

These buttons have already been initialized and declared using root.findByViewId(R.id.button_)
Here I have a for loop that simply runs through the textBlobs ArrayList. As of right now, all the buttons have no text (""). I want to use this for loop to set buttons 0 through textBlobs.size() to the text contained within textBlobs at that index.
for(int i = 0; i < textBlobs.size(); i++ ) {

        }

Not all of the buttons will be used and that is the goal, this should be able to be used with an ArrayList of any length up to 35. I am stuck as to how I should be setting the text. As far as I know the only way to set the text of a button is to use
button0.setText("insert text");

which would not work in my case because I cannot make the number part of the name change between each instance of the for loop.
Does anyone know how I can accomplish my goal?

A: the best solution whould be using an array of Buttons
ArrayList<Button> btns = new ArrayList<Button>();

A: You can just add all the buttons to an ArrayList and work with it.


text:
Q: What's wrong with this JavaScript object literal assignment? Perhaps I'm just being dense, but I don't understand why Netbeans is telling me this is bad syntax:
var events = {
    'onkeyup'  : 0,
    'onchange' : 0,
    'onclick'  : 0
};

Lines 2-4 are squiggled red.

A: I did a quick test in my netbeans 6.9, and i did not get any warnings or errors. You should probably try and install the "Web Applications" plugin and see. Which version are you using?

A: D'oh! I failed to realize that this JavaScript is being parsed by PHP and contains some PHP code prior to the object literal assignment. Apparently the JavaScript Debugger is not too happy about statements like:
var foo = <?php print $bar ?>;

Go figure. :P


text:
Q: Regex matching whats inside quotes but not the same quote inside the line I've been trying this regex/(['])((?:(?!\1)[^\\]|(?:\\\\)*\\[^\\])*)\1/ to gather in an array of list of "variables" from a GET response.
The string looks like :
  "var chatbox_messages='
[20:46:07] You are disconnected.
';var chatbox_memberlist='
Online

@ Admin

';var chatbox_last_update=1392687967.7403; "

The strings above are together just the have x overflow and it's annoying...
Anyways the user who code this code before me was using eval and I don't use eval so I'm trying to fix the code and get the parameters so that I can just do
var response = responseText.match(/(['])((?:(?!\1)[^\\]|(?:\\\\)*\\[^\\])*)\1/g);
    var message = response[0];
    var second_message = response[1];

Though none of the regex I am using will get exactly what I need! It either separates the variable from string into pieces of the array or it still grabs the first quotes ' and I don't want them at all...
Can anyone help me or lead me in the right direction.

A: just do this on your match:
var newMatchWithoutQuotes=match.replace("'","");

This will remove the quotes;

A: I believe that you mean to escape the double quotes:
"var chatbox_messages='
[20:46:07] You are disconnected.
';var chatbox_memberlist='
Online

@ Admin

';var chatbox_last_update=1392687967.7403; "

You can simply use this regex if the string will always end in ';:
/'.*?';/


text:
Q: Generating OpenXML Excel file doesn't apply date formatting
Possible Duplicate:
Open Xml and Date format in Excel cell

I'm trying to take data from a DataGridView and generate an Excel file with the contents. I have a problem with dates though.
The problem is that, having written the worksheet, saved and opened it in Excel, my date cell has a date value in it and, if I do "Format cells", has the format I requested, yet Excel hasn't applied that format. For example, if I export the date value using ".ToOADate()", I get something like "40690.5270454051" in the cell. If I click into the cell, and then out again, the correct formatting is applied.
I've tried omitting the "ToOADate" call, and the same thing happens (I get a recognisable date value, but only formatted using my custom format after I click in and out of the cell).
I've tried setting the DataType of the OpenXml.Spreadsheet.Cell object to CellValues.Date (or EnumValue(CellValues.Date)) but then I get an error about "unreadable content" when I try and open the xlsx file.
Thanks,
Ross

A: What you need to do is set a value that is a floating point number (number of days since Jan 1, 1900 or 1904 - there is a setting in the file to decide which). The hh:mm:ss is the fraction part of the number.
You then set the cell format to be the datetime format you want. Excel will then display the number as the formatted date. This is how Excel stores all dates.
What I think is happening in your case is you are setting the value to a string. When you click on the cell, Excel parses the string, sees that it can be turned into a date, and then saves it as the floating point value.
Save the file after clicking and then look at the cell contents to see the difference.


text:
Q: How to concatenate multiple data frames with long index without error? I have a directory ".../dados" in which have multiple subdirectories whose names are a serial number plus some useless information - e.g. "17448_2017_Jul_2017_Oct", where the first number on it is the serial number. Inside each subdirectory, I have four ".txt" files whose lines/rows have the information of date and time, and an attribute of a certain type, say humidity, all named the same way in each subdirectory - e.g. "2019-01-29 03:11:26 54.7".
I want to concatenate all of them in order to generate a dataset with date index.
path = "/.../dados/"

df = pd.DataFrame()

for fld in os.listdir(path):
    subfld = path + fld
    if os.path.isdir(subfld):
        aux = pd.DataFrame()
        sn = fld.split('_')[0]
        for file in os.listdir(subfld):
            filepath = os.path.join(subfld, file)
            if os.path.isfile(filepath):
                new_col = pd.read_fwf(filepath, colspecs=[(0, 19), (20, -1)], skiprows=8, names=[file.split('_')[2][:-4]], parse_dates=[0], nrows=9999999)
                aux = pd.concat([aux, new_col], axis=1,  sort=False)
        aux['Machine'] = sn
        df = df.append(aux)

This is a print of df.head(10):
HumTechRoom  TempTechRoom  TempExamRoom  HumExamRoom Machine
2018-03-04 00:45:11         82.6           NaN           NaN          NaN   22162
2018-03-04 00:45:47         80.0           NaN           NaN          NaN   22162
2018-03-04 00:45:53         78.0           NaN           NaN          NaN   22162
2018-03-04 00:46:04         75.9           NaN           NaN          NaN   22162
2018-03-04 00:46:20         73.7           NaN           NaN         51.3   22162
2018-03-04 00:46:58         71.7           NaN           NaN          NaN   22162
2018-03-04 00:47:40          NaN           NaN           NaN         53.4   22162
2018-03-04 00:47:41          NaN          14.5           NaN          NaN   22162
2018-03-04 00:47:54         74.3           NaN           NaN          NaN   22162
2018-03-04 00:47:59         76.6           NaN           NaN          NaN   22162

THis is the error message that I get:
...
line 31, in <module>
    aux = pd.concat([aux, new_col], axis=1,  sort=False)

  File ".../concat.py", line 226, in concat
    return op.get_result()

  File ".../concat.py", line 423, in get_result
    copy=self.copy)

  File ".../internals.py", line 5425, in concatenate_block_managers
    return BlockManager(blocks, axes)

  File ".../internals.py", line 3282, in __init__
    self._verify_integrity()

  File ".../internals.py", line 3493, in _verify_integrity
    construction_error(tot_items, block.shape[1:], self.axes)

  File ".../internals.py", line 4843, in construction_error
    passed, implied))

ValueError: Shape of passed values is (2, 19687), indices imply (2, 19685)

A: Your DataFrames are of incompatible shape:
ValueError: Shape of passed values is (2, 19687), indices imply (2, 19685)

In other words, the problem is that 19687 != 19685. Whatever answer you come across is going to come out of the specifics of your data, which is probably not practical to share, given its size. You need to, at least, add or delete 2 rows somewhere. You'll need to investigate to determine what and where.

A: It seems that you are using pd.concat over the wrong axis. Remove axis=1 out of your pd.concat.. line, since axis=0 is the default as can be found in the docs
Just for your convencience. To get a cleaner dataframe, use ignore_index=True as well:
aux = pd.concat([aux, new_col], ignore_index=True,  sort=False)

Which gives a reset index back.


text:
Q: coercing argument is not an atomic vector (repeating endlessly) Newbie question here. I'm trying to run some code that will extract the usernames and dates from a list of assembled web pages. This was working perfectly fine before, but now when I run the code I keep getting the error "coercingargument is not an atomic vector" which repeats endlessly.
I've tried reviewing previous answers here but nothing seemed to quite work. I can't understand why it suddenly stopped working even though nothing has changed. My feeling is I either removed a library it needed or something hasn't quite reset. Any help would be warmly appreciated.
# COLLECT THE DATES
for (i in urls3) {
  addurl <- i
  discussion <- read_html(i, timeout = 1000000000)
  usernames <- discussion %>%
  html_nodes(".lia-component-message-view-widget-author-username a") %>%
  html_text()
  all.usernames <- append(all.usernames, usernames)
  datetime <- discussion %>%
  html_nodes(".local-friendly-date")
  datetime <- str_extract(datetime, "[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2} [A-Z]{2}")
  datetime <- parse_date_time(datetime, "%Y-%m-%d %H:%M:%p", tz = "US/Eastern")
  datetime <- as.character(datetime)
  date.posted <- datetime[1]
  date.replied <- datetime[2]
  date.difference <- difftime(datetime[2],datetime[1], units=c("mins"))

  new.table <- rbind(new.table,c(addurl, date.posted, date.replied, date.difference))
}

The expected results would be a table with the URL, date posted, date replied, and date difference.
The actual results are "argument is not an atomic vector; coercingargument is not an atomic vector; coercingargument is not an atomic vector; coercingargument is not an atomic vector; ..."

A: You need these packages to make your code work :
library(textreadr)
library(dplyr)
library(rvest)
library(stringr)
library(lubridate)

You could ckeck where in the for loop it is bugging and last be careful when you concatenate to have the same object in the two sides.
append, c, rbind

You have two package with read_html function be careful. You will gained clearness to give a more syntetic example. I hope it will help you.


text:
Q: ASP.NET 4.0 JSON from WebService - Removing Escape Slashes Hi I'm hitting my head against the wall here...
I'm using DataContractJsonSerializer to encode data that I'm retrieving from the database which I'm sending back to an AJAX call...
I have this extension:
public static string ToJSON<T>(this T obj) where T : class
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
        using (MemoryStream stream = new MemoryStream())
        {
            serializer.WriteObject(stream, obj);
            return Encoding.Default.GetString(stream.ToArray());
        }
    }

and I'm calling it from the ASMX:
return _webServiceService.GetSponsors().ToJSON();

Passing in the resultset from a Stored Procedure using Entity Framework
It's all work kinda working, except this is part of what's being returned:
{"d":"[{\"FileID\":296,\"IconUrl\":\"\\/Files\\/Banners\\/20119\\/00B56BAC.jpg\",\"ImageUrl\":....

How on earth to I get rid of the slashes so that it returns the following:
{"d":"[{"FileID":296,"IconUrl":"/Files/Banners/20119/00B56BAC.jpg","ImageUrl":....

I'm trying to implement the JQuery UI Autocomplete. Well I'm guessing this will sort it, not sure if I need the FileID value within quotes?

A: You don't need to JSON serialize the return value by hand, because ASP.NET will handle it for you automatically in that scenario. What you're seeing there is ASP.NET applying a second level of JSON serialization to your manually generated string, which requires escaping double quotes with backslashes.
Change your ASMX method to return something like List<Sponsor> and return _webServiceService.GetSponsors() directly, without the ToJSON() extension.


text:
Q: Pandas ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() I have a column PART_TRAN_TYPE whose unique values are Credit and Debit.
Now I want to create a new column money and append -Debit and +Credit to it. but I get the above error which I don't get when I try to check if dataframe is greater than a certain value like df["PART_TRAN_TYPE"][i] > 100
I also tried using if (df["PART_TRAN_TYPE"] == 'D').all() buy the loop runs for ever
def money(df):
    '''
    Creates a column for depicting the Credit and Debit numerically
    '''
    money = []
    for i in df.index:

        if df["PART_TRAN_TYPE"][i] == 'Debit':
            money.append(-df["PART_TRAN_TYPE"][i])
        else:
            money.append(df["PART_TRAN_TYPE"][i])

    return (pd.concat([df, pd.DataFrame(money, columns=["flow"])], axis=1))

Traceback
ValueError                                Traceback (most recent call last)
<ipython-input-11-b7c676b1323b> in <module>
----> 1 money = money(clean_data)

<ipython-input-10-28fb0733adb8> in money(df)
      6     for i in df.index:
      7
----> 8         if df["PART_TRAN_TYPE"][i] == 'Debit':
     10             money.append(-df["Debit"][i])

/opt/conda/lib/python3.8/site-packages/pandas/core/generic.py in __nonzero__(self)
   1327
   1328     def __nonzero__(self):
-> 1329         raise ValueError(
   1330             f"The truth value of a {type(self).__name__} is ambiguous. "
   1331             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

A: It's much simpler to do a vectorised solution
import numpy as np
s = 10
df = pd.DataFrame({"PART_TRAN_TYPE":np.random.choice(["Debit","Credit"],s),
             "VALUE":np.random.randint(1,100,s)})

df.assign(money=df["VALUE"]*np.where(df.PART_TRAN_TYPE.eq("Credit"), 1,-1))

PART_TRAN_TYPE
VALUE
money

0
Debit
65
-65

1
Debit
51
-51

2
Debit
61
-61

3
Credit
36
36

4
Credit
21
21

5
Debit
51
-51

6
Debit
69
-69

7
Debit
9
-9

8
Debit
89
-89

9
Debit
60
-60


text:
Q: reset button not getting enabled on invalid form error Here is my form which is working okay but there is 2 issues which confusing me
1) when user click on required input box and move away, it gives error below the text, but reset button is still disabled; how to enable reset button on error so that I can remove that error beneath input box. I have added
ng-disabled="movieForm.$pristine" ; on reset button; do I need to add anything else
2) when I write invalid entry in movie year box i.e. string instead of year than error appears; I click on reset button ; it clear the box value but than save button enabled. that is not desired.
Please help to fix this form issue

A: Change required to ng-required="true" and you're done.
EDIT:
For Reset button issue in my opinion you should just leave it enabled at all times. It doesn't help user in any way if it's disabled when form is empty.
The problem here is that you want to use this button to "hack" the behavior. After Reset the form is still invalid, you just want to hide the messages by setting $untouched. You can either add more logic to check if the form is invalid and empty, or just invalid, or was just reset etc. Or leave the button enabled and keep things simple. You can check how it works in updated plunker.
Corrected example

A: You need to do two things:

*

*To change your code of reset button, it should be:
         <input type="button" value="Reset" class="btn btn-info" ng-disabled="movieForm.$pristine && movieForm.mName.$untouched && movieForm.mStar.$untouched && movieForm.mYear.$untouched" ng-click="reset()"/>

*You need to change your reset function of controller, it should be like:
        $scope.reset = function() {
         $scope.movie = { name : '', star: '', year: ''};
         //setvalidity is removed
         $scope.movieForm.$setPristine();
         $scope.movieForm.$setUntouched();
     };


text:
Q: wpf Update TreeView checkboxes during loop I'm starting out in wpf.
I have a TreeView in which each item has a checkbox.
I'm trying to create an animation in which The checkboxes are checked programmatically inside a loop.
After researching the topic for some time, I came up with the following method -
    private void Traverse_Click(object sender, RoutedEventArgs e)
    {
        ItemCollection items = tvMain.Items;
        Task.Factory.StartNew( ()=>
            Dispatcher.Invoke( (Action)(() =>
            {
                foreach (TreeViewItem item in items)
                {
                    UIElement elemnt = getCheckbox();
                    if (elemnt != null)
                    {
                        CheckBox chk = (CheckBox)elemnt;
                        chk.IsChecked = !chk.IsChecked;
                        tvMain.Items.Refresh();
                        tvMain.UpdateLayout();
                        Thread.Sleep(500);
                    }
                }
            })));

And yet despite all of my attempts the the tree doesn't update inside the loop, only at the end. so the checkboxes are all checked at once.
How can I make the tree update inside the loop?
Thanks

A: Replace Thread.Sleep with Task.Delay to "sleep" asynchronously:
private async void Traverse_Click(object sender, RoutedEventArgs e)
{
    ItemCollection items = tvMain.Items;
    foreach (TreeViewItem item in items)
    {
        UIElement elemnt = getCheckbox();
        if (elemnt != null)
        {
            CheckBox chk = (CheckBox)elemnt;
            chk.IsChecked = !chk.IsChecked;
            await Task.Delay(500);
        }
    }
}


text:
Q: CDOSys vs SMTPsvg.Mailer I've the following classic ASP code to send email using SMTPsvg.Mailer :
Set Mailer = Server.CreateObject("SMTPsvg.Mailer")
Mailer.FromName   = "From Name"
Mailer.FromAddress= "someone@test.com"
Mailer.RemoteHost = "mail.test.com"
Mailer.AddRecipient "inquiry", "test@test.com"
Mailer.Subject    = "Contact Request"

I'm trying to convert it to use CDOsys, but the CDOsys object doesn't seem to have FromName, RemoteHost attributes as per the documentation here:
http://msdn.microsoft.com/en-us/library/ms526367(v=exchg.10).aspx
Is it possible that the remote host is automatically included when using CDOsys ?

A: For the from address you can specify a from name and address using the "From" property, like this:
myMail.From="""Sender Name"" <email@sender.com>"

Note that the name is enclosed in double quotes.
If you don't specify a mail server, CDOSYS uses the default server (localhost, port 25). To specify a different server you need to use ConfigurationFields, like this:
myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"
myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
myMail.Configuration.Fields.Update


text:
Q: Undefined variable error when using defined variable in PHP? I'm making a website where i login, press a button and then some information is loaded from a database. The code works fine expect for one thing which is: I get this error:
Notice:  Undefined variable: error in /character-load.php on line 42

But the variable is defined here:
if ($user["banned"] == 1){
$error = 1;
}
if (mysql_num_rows($character) == 0){
$error = 1;
}
if (mysql_num_rows($username) == 0){
$error = 1;
}
if (empty($charid)){
$error = 1;
}

Is there anything wrong with this? I dont understand why it says that the variable error is undefined? I can add more information on request as i don't really know what more to add.

A: try this -
$error = 0;
if ($user["banned"] == 1){
  $error = 1;
}
if (mysql_num_rows($character) == 0){
  $error = 1;
}
if (mysql_num_rows($username) == 0){
  $error = 1;
}
if (empty($charid)){
  $error = 1;
}

and add check at the time of use.

A: The variable is only defined if one of these 4 situations occurs. In a situation where none of this occurs, it won't exist.
Easiest fix is to define it as 0 at the top of the block.
Remember; in PHP a variable is only defined if one of the assignment lines is actually executed. Simply being inside the file but being skipped over doesn't count.


text:
Q: Why is NSLayoutConstraint's identifier property not working in code? I am trying to write some conditions where the same constraint is not added twice. For example if a view already has a bottom anchor constraint do not add it again. So I tried using the layout constraint identifier to uniquely identify a constraint so that if it is already exists dont add another constraint again. I do not have a storyboard, so I have written the below code:
class PDFViewer: UIViewController {
     var quickLookController = QLPreviewController()

     override func viewDidLoad()

     if let quickView = quickLookController.view {
            self.view.addSubview(quickView)
     }

     {
        quickLookController.view.translatesAutoresizingMaskIntoConstraints = false
        quickLookController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        quickLookController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        quickLookController.view.topAnchor.constraint(equalTo: navView.bottomAnchor).isActive = true

        setPDFViewHeight(height: 100)
        setPDFViewHeight(height: 100)

    }

    open func setPDFViewHeight(height: CGFloat) {

        var isBottomAnchorSet = false

        if let superView = quickLookController.view.superview {
            for constraints in superView.constraints {
                if constraints.identifier == "bottom" {
                    isBottomAnchorSet = true
                }
                else {
                    print(false)
                }
            }
        }

        if !isBottomAnchorSet {
            quickLookController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).identifier = "bottom"
            quickLookController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        }
    }
}

But both times I am calling setPDFViewHeight method it says there is not identifier named "bottom" but it should the second time. I have also tried to get the constraints of the super view directly like below but the same issue there as well.
        for constraints in view.constraints {
            if constraints.identifier == "bottom" {
                isBottomAnchorSet = true
            }
        }

What am I doing wrong or does this identifier cannot be used this way?
Even an entirely different answer on how to avoid duplication of Layout constraints would also help. Thanks in advance.

A: I think in your situation it's better to keep the bottom constraint and just update the constant later on, when needed, like this:
class PDFViewer: UIViewController {
     var quickLookController = QLPreviewController()
     var bottomConstraint: NSLayoutConstraint?

     override func viewDidLoad()

     if let quickView = quickLookController.view {
            self.view.addSubview(quickView)
     }

     quickLookController.view.translatesAutoresizingMaskIntoConstraints = false
     bottomConstraint = quickLookController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
     NSLayoutConstraint.activate([
        quickLookController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        quickLookController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        quickLookController.view.topAnchor.constraint(equalTo: navView.bottomAnchor),
        bottomConstraint
     ])

     setPDFViewHeight(height: 100)
     setPDFViewHeight(height: 100)

    open func setPDFViewHeight(height: CGFloat) {
        bottomConstraint.constant = height
    }
}

Also the naming of the setPDFViewHeight may be misleading, because what it really does is that it set's the offset from the anchor, not the absolute height.

A: The issue is that you are creating TWO bottom constraints:
// this creates a constraint
//  with an identifier
//  but does not activate it
quickLookController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).identifier = "bottom"

// this creates a constraint
//  WITHOUT an identifier
//  and activates it
quickLookController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

Give this a try:
open func setPDFViewHeight(height: CGFloat) {

    var isBottomAnchorSet = false

    if let superView = quickLookController.view.superview {
        for constraint in superView.constraints {
            print("constraint identifier:", constraint.identifier ?? "no id", constraint)
            if constraint.identifier == "bottom" {
                isBottomAnchorSet = true
                print("Bottom Anchor already set")
            }
        }
        if !isBottomAnchorSet {
            print("Creating Bottom Anchor")
            let c = quickLookController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
            c.identifier = "bottom"
            c.isActive = true
        }
    }

}

To test it, replace your double call with:
print("First call")
print()
setPDFViewHeight(height: 100)

print()
print("Second call")
print()
setPDFViewHeight(height: 100)

Here's the output I get:
First call

constraint identifier: no id <NSLayoutConstraint:0x600002086030 H:|-(0)-[UIView:0x7fbfa5407fa0]   (active, names: '|':UIView:0x7fbfa54084d0 )>
constraint identifier: no id <NSLayoutConstraint:0x600002085fe0 UIView:0x7fbfa5407fa0.trailing == UIView:0x7fbfa54084d0.trailing   (active)>
constraint identifier: no id <NSLayoutConstraint:0x600002085f40 V:|-(0)-[UIView:0x7fbfa5407fa0]   (active, names: '|':UIView:0x7fbfa54084d0 )>
Creating Bottom Anchor

Second call

constraint identifier: no id <NSLayoutConstraint:0x600002086030 H:|-(0)-[UIView:0x7fbfa5407fa0]   (active, names: '|':UIView:0x7fbfa54084d0 )>
constraint identifier: no id <NSLayoutConstraint:0x600002085fe0 UIView:0x7fbfa5407fa0.trailing == UIView:0x7fbfa54084d0.trailing   (active)>
constraint identifier: no id <NSLayoutConstraint:0x600002085f40 V:|-(0)-[UIView:0x7fbfa5407fa0]   (active, names: '|':UIView:0x7fbfa54084d0 )>
constraint identifier: bottom <NSLayoutConstraint:0x60000208bc00 'bottom' UIView:0x7fbfa5407fa0.bottom == UIView:0x7fbfa54084d0.bottom   (active)>
Bottom Anchor already set


text:
Q: Listbox Component with advanced formatting options? I am looking for a listbox style component that offers advanced text formatting options.
I know you can ownerdraw regular listboxes using the OnDrawItem procedure, but for the requirements I need I think it would be better to use a control that may already offer what I am looking for.
Look at this sample screenshot:

Word Styling - Allow individual characters/words to be styled differently.
Text Links - certain items entered into the listbox could be recognised as a link (not necessarily a url link though). In this example brown fox is marked as link, when the mouse moves over the brown fox text the font becomes underlined. Selecting this could do anything such as show a message, open a form etc.
Note, when a list item is selected the font styles should remain the same. Additionally if the listbox could support images (especially several images in a row) that would be a bonus.
I was thinking a HTML listbox or similar could be just what I need. That would allow inputting the items into the listbox like as code with tags for example.
Could anyone recommend a component that offers this type of capabilities?
Thanks.

A: The THTMListbox by TMS Software can do all of this. It can support images and even animated gifs.
It is not free though and is actually part of a bundle (HTML Controls Pack). I think it is well worth looking at though and the support is second to none + you receive full source code.


text:
Q: Loop through JSON object, return specific object I'm using Azure Devops and I want to loop through a list of pull requests. I'm using this API request to retrieve a list of pull requests.
When I check the URL I see:

Which is correct. I have 3 open pull requests. What I want to do is check each object for a specific attribute called sourceRefName.
When there's a match I want to return the complete object:

I've tried:
$listOfPullRequestsURL = "https://dev.azure.com/*****/*****/_apis/git/repositories/*****/pullrequests?api-version=5.0"
$listOfPullRequests = Invoke-RestMethod -Uri $listOfPullRequestsURL -Headers @{Authorization = $pat } -Method Get
Write-Host $listOfPullRequests
Write-Host $listOfPullRequests | ConvertFrom-Json

ForEach ($object in $listOfPullRequests) {
    Write-Host "### OBJECT ###"
    Write-Host $object
    Write-Host $object.sourceRefName
}

And the result is:

How do I go through each object? And is it possible to return the whole object based on 1 attribute?

A: $listOfPullRequestsURL = "https://dev.azure.com/****/****/_apis/git/repositories/****/pullrequests?api-version=5.0"
$listOfPullRequests = Invoke-RestMethod -Uri $listOfPullRequestsURL -Headers @{Authorization = $pat } -Method Get

$listOfPullRequests.value | ForEach-Object {
    if ($_.sourceRefName -eq $env:BUILD_SOURCEBRANCH) {
        Write-Host $_
    }
}

This shows the correct JSON object.

A: I understood you already took care of it.
Just wanted to add here - to avoid these stuff, I personally think it's more clean and creates less trouble to use hashtables.
In Powershell v6 It's easy to convert to hashtable with the built-in ConvertFrom-Json flag -AsHashtable.
$hashPullRequests = $listOfPullRequests | ConvertFrom-Json -AsHashtable

and then loop over $hashPullRequests like any other hashtable.


text:
Q: Reenabling default installation of trackpad on Dell XPS13 I have been having a lot of issues with the mouse cursor jumping all over the screen on my Dell XPS13 with Ubuntu 14.04 LTS.
One of the things I did was install some "upstream" drivers using the guide from this answer: https://askubuntu.com/a/462830/340104.  Unfortunately, my trackpad experience has been much worse since applying this patch and now I need to basically hold my fingers vertically while touching the trackpad extremely lightly in order for them to not register as too wide.  Moreover, the trackpad cursor still continues to jump around the screen.  The trackpad on Win8 works perfectly though without any cursor jumping so it leads me to believe that it is in fact a driver issue.
The link within this answer (http://xps13-9333.appspot.com/#touchpad) says that if there are any problems, I can undo the changes by reinstalling the default synaptics driver:
aptitude install xserver-xorg-input-synaptics

I did this and restarted but now the trackpad is still just as bad as after having applied the first patch.  Is there any way I can purge all trackpad settings/drivers/etc. and do a fresh install of the original drivers/settings?


text:
Q: Auto refresh when server-side progress is complete? Okay, I'm trying to do this
a mission form, once visitor presses begin, it pops up a new tab with a registration form ( not my actual website ) after they register, this second website will send something to let me know this visitor completed his registration,
okay but this is not the thing, i want to receive registration result live from the main webpage which the user started the mission from, how to do this without having to refresh  specific page several times to check current status, i want to receive it live once registration is completed from the main page
using jquery, javascript or php or just any possibility to do this

A: In the first page, you could use $.ajax (http://api.jquery.com/jQuery.ajax/) to post the registration informations to the database and later retrieve it on the second page (using $.ajax as well). The question is how is the second page going to know if the user has finish their business on the first page (which is identified by "window.opener" method)? To do this you could do a setTimeout() ever certain second to see if the registration has been completed. If yes, retrieve the information from the database.
Although using $.ajax may rely too much on the user's internet connection and I personally find it slow. A faster way would be to use cookies to check if the user has finished their registration.
There's also this relatively new HTML5 method called "local storage", which acts as a client-side database (unlike cookie, it is can support large amt. of data and you can store your whole registration form on it). It is also relatively faster than polling relational database.

A: You could do it like this:

*

*Listen for the message from the second website

*Make the mission form ask your service (every second or what suits your need) with ajax

*When the message has arrived, return "true". If it hasn't return "false"

*Perform your actions on the client side when the client recieves a "true".

A: You'll still need to poll home to check if work is done, because server can't initiate connection to client. To prevent page refresh, use AJAX for polling.

A: Use jQuery  ajax to send the registration data to server and return some response once the transaction (saving user to database) is completed. grab it in the call back function and do further things ( show a message/ reload some part of the page etc...)
so send your registration data to server page like this
$(function(){

   $("form").submit(e){
    e.preventDefault();
       $.post("yourRegistrationProcess.php",$("form").serialize(),function(data){
          //You have the response from server in data variable.
          // Do whatever you want next with that.
       });
   });

});

Assuming you send some response back from yourRegistrationProcess.php (echo "saved"; etc..)once you save the user registration data to the tables.


text:
Q: E[E[A|B]|C], law of total expectation with two conditional expectations I have a conditional expectation inside of a conditional expectation.
Let A, B, C be real-valued random variables.
I am trying to simplify E[E[A|B]|C]. I am not sure much can be done in general; however, in this case, I know that C$\in$B.
I also know from TLOTE: E[E[A|B]]= E[A].
Intuition tells me that since C is a subspace of B, then I should wind up with E[A|C], but I am short on ideas to show it mathematically.
Thank you.

A: One may show that if $\mathbb{E}[\lvert X \rvert] < \infty$, then for $\mathcal{G}_1\subset\mathcal{G}_2\subset\mathcal{F}$ it holds that
$$
\mathbb{E}\!\left[\left. \mathbb{E}\!\left[X \, | \, \mathcal{G}_2\right] \, \right| \mathcal{G}_1\right] = \mathbb{E}\!\left[X \, | \, \mathcal{G}_1\right].
$$
To proof this, note e.g. that for $G \in \mathcal{G}_1$,
$$
\int_G \mathbb{E}\!\left[\left. \mathbb{E}\!\left[X \, | \, \mathcal{G}_2\right] \, \right| \mathcal{G}_1\right] \mathrm{d}\mathbb{P}
=
\int_G \mathbb{E}\!\left[X \, | \, \mathcal{G}_2\right]\mathrm{d}\mathbb{P}
=
\int_G X \, \mathrm{d}\mathbb{P},
$$
since $\mathbb{E}\!\left[\left. \mathbb{E}\!\left[X \, | \, \mathcal{G}_2\right] \, \right| \mathcal{G}_1\right]$ is the conditional expectation of $\mathbb{E}\!\left[X \, | \, \mathcal{G}_2\right]$ given $\mathcal{G}_1$, since $\mathbb{E}\!\left[X \, | \, \mathcal{G}_2\right]$ is the conditional expectation of $X$ given $\mathcal{G}_2$, and since $\mathcal{G}_1 \subset \mathcal{G}_2$ implies $G \in \mathcal{G}_2$.


text:
Q: SqlExpress Db Is in use by system I have a strange problem that is reoccurring. My app is a MVC5 application using EF code first and SQLExpress. My solution uses 4 databases - 3 of which work without a problem. The fourth database is constantly 'acquired' by 'System'. Everyday for the last week when I boot up I have a problem.
When I run the app and the DatabaseInitializer runs I get this exception :

Cannot open database "databaseName" requested by the login. The login failed. Login failed for user 'Computer\UserName'.

Weird. I read some S.O. articels about changing permision, but that smells to me. This database shouldent be in someone elses domain in the first place! The other databases work fine !
So I go about deleting the database. I get this error.

Error deleting file 'database.mdf'. The process cannot access the file because it is being use by another process.

So I reboot and go to delete the database directly from the windows explorer.

The action can't be completed because the file is open in System

I was finally able to delete the file by running my PC in safe mode and deleting it there. Im not sure what the cause of this is. I am running SQL express and I don't see any SQL background services running.


text:
Q: C# refreshing textbox from BindingSource I am having difficulty refreshing windows forms controls that are using a BindingSource object. We have a CAB/MVP/SCSF client that I (actually "we" since it is a team effort) are developing that will interact with WCF services running on a remote server.  (This is our first attempt at this, so we are in a learning mode).   One of the calls (from the Presenter) to the service returns a DataSet that contains 3 DataTables, named "Contract", "Loan" and "Terms".  Each table contains just one row.  When the service returns the dataset, we store it in the SmartPart/View in a class member variable, by calling a function in the view called BindData() and passing the dataset in to the view from the presenter class;
private System.Data.DataSet _ds = null;
public void BindData(System.Data.DataSet ds)
{
    string sErr = "";
    try
    {
        _ds = ds;  // save to private member variable

        // more code goes down here
    }
}

We are trying to bind each of the three DataTables to an assortment of Windows Forms TextBoxes, MaskedEditBoxes, and Infragistics UltraComboEditor Dropdown comboboxes We created three BindingSource objects, one for each DataTable using the VS2008 IDE.
private System.Windows.Forms.BindingSource bindsrcContract;
private System.Windows.Forms.BindingSource bindsrcLoan;
private System.Windows.Forms.BindingSource bindsrcTerms;

We are binding the values like this
if (bindsrcContract.DataSource == null)
{
    bindsrcContract.DataSource = _ds;
    bindsrcContract.DataMember = "contract";

    txtContract.DataBindings.Add(new Binding("Text", bindsrcContract, "contract_id", true));

    txtLateFeeAmt.DataBindings.Add(new Binding("Text", bindsrcContract, "fee_code", true));

    txtPrePayPenalty.DataBindings.Add(new Binding("Text", bindsrcContract, "prepay_penalty", true));

    txtLateFeeDays.DataBindings.Add(new Binding("Text", bindsrcContract, "late_days", true));
}

if (bindsrcLoan.DataSource == null)
{
    bindsrcLoan.DataSource = _ds;
    bindsrcLoan.DataMember = "loan";

    mskRecvDate.DataBindings.Add(new Binding("Text", bindsrcLoan, "receive_date", true));

    cmboDocsRcvd.DataBindings.Add(new Binding("Value", bindsrcLoan, "docs", true));
}

This works when we do the first read from the service and get a dataset back.  The information is displayed on the form's controls, we can update it using the form, and then "save" it by passing the changed values back to the WCF service.
Here is our problem.  If we select a different loan key and make the same call to the service and get a new DataSet, again with 3 tables with one row each, the controls (textboxes, masked edit boxes, etc.) are not being updated with the new information.  Note that the smartPart/View is not closed or anything, but remains loaded in between calls to the service.  On the second call we are not rebinding the calls, but simply trying to get the data to refresh from the updated DataSet.
We have tried everything we can think of, but clearly we are missing something.  This is our first attempt at using the BindingSource control. We have tried
bindsrcContract.ResetBindings(false);

and
bindsrcContract.ResetBindings(true);

and
bindsrcContract.RaiseListChangedEvents = true;

and
for (int i = 0; i < bindsrcContract.Count; i++)
{
    bindsrcContract.ResetItem(i);
}

As well as resetting the DataMember property again.
bindsrcContract.DataMember = "Contract";

We've looked at a lot of examples.  Many examples make reference to the BindingNavigator but since the DataTables only have one row, we did not think we needed that. There are a lot of examples for grids, but we're not using one here.  Can anyone please point out where we are going wrong, or point us to resources that will provide some more information?
We're using VisualStudio 2008, C# and .Net 2.0, XP client, W2K3 server.
Thanks in advance
wes

A: I was having a similar issue today and found this works.
private void btnCancel_Click(object sender, EventArgs e)
{
    this.MyTable.RejectChanges();
    this.txtMyBoundTextBox.DataBindings[0].ReadValue();
    this.EditState = EditStates.NotEditting;
}

A: The underlying problem in both your questions is that the Binding-Manager keeps the links to the original objects.
When you assign _ds as the DataSource, the Binding-Manager analyzes the DataSet and acts accordingly. If you assign some other DataSet to _ds, the Binding-Manager has no way of knowing this. It still has the reference on the original DataSet-object. So this explains why you have to reset the DataSource-property to the new DataSet.
It also explains why the removing and adding of the table doesn't lead to your expected result. Again, the Binding-Manager holds the reference to the old table (or the first row in that table). The new table is never bound. Also in this case the reassigning of _ds does not help, because _ds points to the same DataSet-object as before. The Binding-Manager is smart enough to notice that it's the same object and does no rebinding action.
You either have to modify the contents of your bound objects (which fires a PropertyChanged-Event to which the Binding-Manager subscribes) or you have to trigger a complete rebind by assigning a different object to the DataSource-property.
This is a simplified description of what actually happens, but I hope it's enough to explain and solve your problem. Unfortunately I have yet to find a comprehensive explanation of WinForms databinding on the web (or elsewhere).

A: Failing all else, you can reassign the DataSource every time you receive a new dataset, doing something like this:
bindsrcContract.DataSource = typeof(System.Data.DataSet);
bindsrcContract.DataSource = _ds;

(Also, initializing DataMember first and then DataSource will give you better performance.)

A: Wes, I'm very glad I could help. I still remember an issue very similar to yours taking me weeks to figure out in the wild...
Regarding your questions, here's all I know:

*

*If you set the DataSource first, then the DataMember, your data source will be scanned twice, since setting the DataMember subsequently changes the existing (valid) binding. If you do it the other way around, setting DataMember first (with DataSource being null or better, typeof(YourData)), binding only takes place once when you set the DataSource.

*I think you can apply the same solution here. Instead of just
bindsrcContract.DataSource = _ds;

in your last line, you should write
bindsrcContract.DataSource = typeof(System.Data.DataSet);
bindsrcContract.DataSource = _ds;

*Sorry to disappoint, but I learned all I know about data binding from MSDN as well as trial-and-error. It was quite painful. Hopefully someone else can chime in with a useful link or two.

A: try combination :
bindingsource.EndEdit() // writting data to underlying source
bindingSource.ResetBindings(false)  // force controls to reread data from bindingSource

use this whenever you write something to controls.


text:
Q: Как распаковать архив? Функция принимает путь к папке с архивами и должна распаковывать в эту же папку с таким же названием. Например был архив с именем archive.zip -> распаковалось в папку archive. Но почему-то не работает, никаких действий не происходит при запуске этой функции.
def unpack_archives(path_to_archives):
for archive in path_to_archives.rglob('*'):
    shutil.unpack_archive(archive, archive.name)


text:
Q: How to programmatically 'substitute' a ListView by a progress bar while it loads? I have a simple ListView like this:
listView = view.findViewById(R.id.elements_list);

but I do not have access to the layout, so I cannot place a progress bar there. Can I make listView invisible and then make a progressBar appear in front of it? I can at least think on how to do it for the entire screen where listView is contained, but what if I want my progressBar to appear exactly in the middle (horizontally and vertically) of listView?

A: This is in Kotlin, but it can be easily translate to Java.
I think you can re-use what the Android API provides for free, to display a `Progress Circle indicator for example showing the idea that something is loading:
package com.example.myapplication

import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity

class MainActivity: AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val dialog = Dialog(this)
        val progressBar = ProgressBar(this)

        progressBar.isIndeterminate = true
        progressBar.visibility = View.VISIBLE

        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.setContentView(progressBar)
        dialog.show()
    }
}

The output would be something like this:


text:
Q: Android - Using outputstream and Mat buffer to create a mp4 Video I have a buffer which has the Mats from which i want to create a video
I transform those mats into byte array and write them to the outputstream
 yet for some reason whenever I watch the video only one image is shown heres the code
try {

    File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File (sdCard.getAbsolutePath() + "/ran");
    dir.mkdirs();
    File file = new File(dir, "goal_ran.mp4");
    FileOutputStream out = new FileOutputStream(file);

    for(int i=0;i<buffer.size();i++)
    {

        Mat mat = buffer.get(i);
        MatOfByte matOfByte = new MatOfByte();
        Imgcodecs.imencode(".png", mat, matOfByte);
        byte[] byteArray = matOfByte.toArray();
        out.write(byteArray);
        out.flush();
        /*byte[] return_buff = new byte[(int) (buffer.get(i).total() * buffer.get(i).elemSize())];
        buffer.get(i).get(0, 0, return_buff);*/
        /*int length = (int) (mat.total() * mat.elemSize());
        byte buffer[] = new byte[length];
        mat.get(0, 0, buffer);
        out.write(buffer);*/
    }

    out.close();
    Log.d("Video","Successful"+ buffer.size());

    } catch (Exception e) {
        e.printStackTrace();
    }


text:
Q: Why are letters overlapping in the terminal? I installed Oneiric as a guest OS in VirtualBox using the Mini CD. I installed the ubuntu-desktop package and everything seems to work fine - well, except for a font issue with the terminal:

As you can see, some of the letters overlap and it's difficult to read. I checked the settings and it the checkbox "Use the system fixed width font" is checked with "Monospace | 12" selected underneath it.

Edit: running the commands mentioned in the comments:
$ fc-match "Monospace"
DejaVuSansMono.ttf: "DejaVu Sans Mono" "Book"
$ gconftool --get /desktop/gnome/interface/monospace_font_name
Monospace 10
$ debsums ttf-dejavu-core
/usr/share/doc/ttf-dejavu-core/AUTHORS                                        OK
/usr/share/doc/ttf-dejavu-core/BUGS                                           OK
/usr/share/doc/ttf-dejavu-core/NEWS.gz                                        OK
/usr/share/doc/ttf-dejavu-core/README                                         OK
/usr/share/doc/ttf-dejavu-core/changelog.Debian.gz                            OK
/usr/share/doc/ttf-dejavu-core/copyright                                      OK
/usr/share/doc/ttf-dejavu-core/langcover.txt.gz                               OK
/usr/share/doc/ttf-dejavu-core/status.txt.gz                                  OK
/usr/share/doc/ttf-dejavu-core/unicover.txt.gz                                OK
/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf                      OK
/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf                           OK
/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono-Bold.ttf                  OK
/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono.ttf                       OK
/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif-Bold.ttf                     OK
/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif.ttf                          OK

A: Open your terminal Go to Edit-->Profile Preferences and in general tab check "Use System fixed width font"

A: I have seen this kind of problem in my friend's gnome terminal..
just go to edit --> profiles and change the settings of the font of your terminal..
it should solve your problem.. :)

A: Had the same problem. This may be related. Bug #1166125
Removing package pango-graphite fixed the problem for me:
sudo apt-get purge pango-graphite

A: Turns out the ttf-ubuntu-font-family  package somehow didn't get installed. Immediately after installing that package, the terminal font switched to the Ubuntu Monospace font and everything was readable again.

A: *

*sudo apt-get install gnome-tweak-tool

*goto tweak tool

*goto fonts>monospace>
select ubuntu mono regular 13pts

A: I use ZSH and this was happening to me when using autocomplete.
The solution was to add this to ~/.zshrc.:
export LC_CTYPE=en_US.UTF-8
If you'd like to understand more, I recommend reading https://stackoverflow.com/questions/30479607/explain-the-effects-of-export-lang-lc-ctype-lc-all

A: Go to Software Center and remove 'monospace font for pretty code listings and for the terminal'.
If that doesn't do it for you, try to remove Terminal (gnome_terminal), log out and log in and install the Terminal(gnome-terminal).

A: I fixed this issue by running:
gconf-editor /apps/gnome-terminal/profiles/Default
and unchecking  "Use System Font"

A: I fixed mine by using custom font monospace regular on all fronts.


text:
Q: Pootle - issues exporting properties files I am using pootle for localization.
I imported source translations from Java properties files.
the property file looks like:
STR_TEXT1 = Hello

Than I imported other language files. I paid translators to translate those other languages.
Now I need to export those translations from pootle back to JAVA property files.  Problem is, that it randomly exports it to UTF8 other time to to \uXXXX escape Encoding.  There is no way how to setup the encoding for export files.  Second problem is, that those export files are corrupted. It renders them like many rows without problem and some rows are cut, like this:
STR_TEXT1 = HELLSTR_TEXT2 = bye

Than I accidently deleted property files from /po/my_project directory.  When I did this, exports stoped to work. But all translations are still wisible on the pootle web.  So, i suppose those translations are saved in some other files, maybe mo files.  Is there a way how to get those translations to java property files? how to force pootle to replace those original texts from original property files by fresh texts from pootle?

A: Pootle should export you files as Latin1 not UTF-8, it will escape non-Latin characters using \uXXXX syntax.  Newer Pootle's allow you to export in UTF-8.
The best is to attach your source and translated files to a bug over at bugs.locamotion.org so that the Pootle developers can look at your source files.
The translations are kept in a database.  Pootle makes use of you template file usually en.properties to create translated versions. I haven't tested what happens if you delete this template file.


text:
Q: Why the IRtcEngine instance is not created? i'm trying to implement a voice chat in my Unity game using agora.io. I followed the official start up tutorials and I put the code below in a script attached to an empty Gameobject in the scene:
My simple start up script
So, at the Start, the IRtcEngine instance should be created as I call the IRtcEngine.GetEngine(agoraAppID) method. The problem is that, instead od returnig the instance, this method prints an error log: "Create engine failed, error code: -7"
I looked up what the error code 7 means: "A method is called before the initialization of RtcEngine. Ensure that the RtcEngineinstance is created and initialized before calling the method".
So I tried commenting everything but the line in which the IRtcEngine.GetEngine(agoraAppID) method is called, but the error still pops up. It pops up even when I play the agora demo scene "HelloUnity".
I also tried removing the agora package and importing it again. It worked because after that the instance was created correctly, but after a few times, the error started popping up again.
Unity version: 2020.3.3f1
Agora version: 3.3.1.71
What could the problem be? Is it a bug?

A: I had the same issue with the same error code. Closing all Unity instances and rebooting my computer was helped me.
Usually, it happens if you don't leave the channel properly. So, putting

rtcEngine?.LeaveChannel()

to

OnDestroy()

may be a good solution.

A: should look something like this.  don't forget the variable declaration up top.
public class Launch : MonoBehaviour
{
    public IRtcEngine mRtcEngine;

    void Start()
    {
        string agoraAccountId = "4ca78bc86f23hhhhhhhhh4444444444";

        if (mRtcEngine != null)
        {
            Debug.Log("Agora engine exists already!!");
            return;
        }
        mRtcEngine = IRtcEngine.GetEngine(agoraAccountId);

I suggest you join the Agora slack channel (it is easy to join) where you can get answers quickly.

A: Please take a look at the Demo project code and watch out how the sample app handles the life cycle in Unity.  In your simple script, there is no clean up code on destroy.  You left certain socket/ports open on the system. That's why when you get some success on a fresh install but not the subsequent run.


text:
Q: WP filter to alter admin CSS styles? I want to change the CSS background definition for #wpadminbar in the new WordPress 3.8 admin themes. I can (and have) updated the /wp-admin/css/colors/theme/colors.min.css file but wonder if there is a cleaner way? Is there a filter that I could use in functions.php to update this specific style?
I found this approach but it is a blunt instrument, replacing the entire CSS file:
http://wp-snippets.com/custom-admin-css/
If it matters, I find the single color for the top bar and left column visually odd so I've manually updated #wpadminbar to use the medium color shade assigned to the background of #adminmenu.wp-submenu style. That makes the top bar slightly darker than the left column.
Thanks for any ideas how I might do this more cleanly.

A: You can use the wp_add_inline_style() function to override styles in an already-enqueued stylesheet:
add_action( 'admin_enqueue_scripts', 'wpse127850_css_overrides' );
function wpse127850_css_overrides() {
     wp_add_inline_style( 'color', '.mycolor { background: #ccc; }' );
}

You'll need to find the handle of the stylesheet you want to affect -- I've guessed at color but there's no guarantee I'm right.

References

*

*wp_add_inline_style()

*admin_enqueue_scripts hook
Edited to answer questions from the comments

*

*The function name can be whatever you want -- it just has to match the 2nd parameter of the add_action() call.

*color is the CSS file's "handle" -- if you View Source of your admin page, you'll see that all the stylesheets are called like this:
<link rel='stylesheet'
 id='the-erudite-css'
 href='http://example.com/wp-content/themes/the-erudite/css/erudite.css?ver=3.8'
 type='text/css' media='all' />

The id part contains the CSS file's handle, followed by -css. So in my example, the handle is the-erudite.

*I know this because I went looking for this ability one day, and figured it out by a combination of Google and Codex searching.  The WordPress Codex is a fantastic resource for any WordPress development you're trying to do. If you haven't yet, you should visit -- and probably bookmark -- it.


text:
Q: Run failed (QT) I'm using QT.
I have two classes, one inherited from the other one. The issue is when I add an new attribute (specifically either string or Qstring) even if I don't use it in any method
I've got the following message when  I execute my program:
RUN FAILED (exit value -1,073,741,819, total time: 22s)
Thanks


text:
Q: Unable to get form validity I'm unable to get form validity using $scope.myform.$valid & I get a undefined message "Cannot read property '$valid' of undefined".

  <form name="myform">
    Name: <input type="text" ng-model="user.name" />

    Email: <input type="email" ng-model="user.email" />

 </form>

app.controller('MainCtrl', function($scope) {
  console.log($scope.myform.$valid);
});

Plnkr : http://plnkr.co/edit/P2kg1l64d4t7k7X4d4jh?p=preview

A: That's because, when your controller is instanciated and this line of code is executed, the form has not been added to the scope yet.
Add this function to your controller instead:
$scope.click = function() {
    alert($scope.myform.$valid);
};

and add this to your form:
 <button type="button" ng-click="click()">is form valid?</button>

and you'll see that, when clicking the button, you'll be able to get the validity of the form.
Here's the updated plunker.


text:
Q: How to remove trailing slash in folder URL without breaking index I've read so many posts and tried to get my .htaccess file to work but without success.
Situation - I have an index.php file in a /watch directory that contains a dynamic video player. I want to make my URL look like this.
//example.com/watch?v=Hghj12
currently I have this...
//example.com/watch/?v=Hghj12
That trailing slash after the /watch/ folder needs to go. I want any link to example.com/watch/ to resolve to example.com/watch without breaking the page. Currently I get a 403 error.
My current .htaccess for the /watch folder:
DirectorySlash Off
RewriteEngine On

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)index\.php($|\ |\?)
RewriteRule ^ /%1 [R=301,L]
DirectoryIndex index.php

Many thanks!

A: If you're simply trying to remove the trailing slash and using a .htaccess file within /watch then you could use:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]

Make sure you clear your cache before you test this.


text:
Q: Multiple variations of TKInter fonts I am trying to get a better understanding of using fonts in tkinter and ttk.
My plan is to have two different styles for headings, each with their own font size. I used nametofont() to create an instance of the font and then set the size in two different styles:
labelFont = tkinter.font.nametofont('TkTextFont')
labelFont.config(weight='bold')

ttk.Style().configure("TLabel", font=labelFont, size=12)
ttk.Style().configure("heading.TLabel", font=labelFont, size=48)

then apply the styles to headings:
heading = ttk.Label(root, text="Heading", style="heading.TLabel")
label = ttk.Label(root, text="Label", style="TLabel")   #   is style redundant?

Unfortunately, I don't get two different sizes, so this is obviously the wrong approach.
I also tried something like this:
labelFont = tkinter.font.nametofont('TkTextFont')
headingFont = tkinter.font.nametofont('TkTextFont')
# etc

thinking that I would get two independent instance of the font, but they appear to be the same instance. If they were independent, I could have used configure() to give each of them their own font size.
I took this approach because I wanted to use the built-in named font, and use variables to maintain consistency. What is the correct approach to this?

A: You need to use .config(size=...) on the different instances of Font:
labelFont = tkinter.font.nametofont('TkTextFont')
labelFont.config(weight='bold', size=12)

# create a clone of labelFont using Font.copy()
headingFont = labelFont.copy()
headingFont.config(size=48)

s = ttk.Style()
s.configure('TLabel', font=labelFont) # apply to all instance of ttk.Label
s.configure('heading.TLabel', font=headingFont, size=96)

heading = ttk.Label(root, text='Heading', style='heading.TLabel')
label = ttk.Label(root, text='Label') # style='TLabel' is not necessary


text:
Q: Linting imports or de-structured variables onto separate lines We are looking to implement a linting rule which will catch any imports or destructured variables to make them display on different lines.
e.g.
// bad (ok, so not so much bad as not what we want)
import { Component1, Component2, Component3 } from 'some-library';

const { variable1, variable2, variable3 } = structuredVariable;

// good (or preferred format)
import {
  Component1,
  Component2,
  Component3,
} from 'some-library';

const {
  variable1,
  variable2,
  variable3,
} = structuredVariable;

Is this possible through es-lint/any other method?


text:
Q: Get url from java class I have this singleton class which will start when the application starts and the method invokes itself for every 30 seconds.
@Singleton
@Startup
public class myClass{
    @Schedule(second="*/30", minute="*", hour="*")
    public void serviceRequest(){
        String url = "";
        //send request
    }
}

the url will be something like http://localhost:7001/webapp/rest/tasks/mytask. I don't want to hardcode the url. Instead, I want to somehow get that from the system (or somewhere). I've tried injecting resource like HttpServletRequest but that didn't work.
Thanks in advance.

A: In case you're using JAX-RS, then this will work:
@RequestScoped @Path("tasks")
public class TaskResource {

    @GET @Path("{id}")
    public Response getTask(@PathParam("id") String id) {
         /* whatever */
    }

}

URI uri = UriBuilder.fromResource(TaskResource.class)
    .segment("{id}").build("mytask");

A: The url will be provided by an external service so I dont need to worry about host and port number since ill get full url to that rest service. Because the service isn't available so I made an in house rest service to test my functionality. I guess I will harcode the url for now.


text:
Q: Android Interface Webview I want to create an interface for my project that has a button and when the button is clicked it begins the activity from another java file which is a library but am having some difficulty. The referenced java file opens a webview. Here is what I have
    package com.dcu;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.news.*;

public class DCU extends Activity
{
    private Button somebutton;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initControls();
    }
    protected void initControls()
    {
        somebutton = (Button)findViewById(R.id.News);
        somebutton.setOnClickListener(new Button.OnClickListener()
        {
            public void onClick (View v)
            {
                News n = new News();
                n.onCreate(null);
            }
        });
}

}
Then I have a main.xml
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Button android:text="Button" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="news" android:id="@+id/News"></Button>
</LinearLayout>

And news.xml
    <?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>

Here is the News.java
package com.news;

import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class News extends Activity {
    WebView mWebView;
    String test2 = "
";
    Document docs;
    Document writing;

    String text(String link)
    {
        String full ="

";;
        try {
             writing = Jsoup.connect(link).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Elements classname = writing.getElementsByClass("news");
        Element heading = classname.select("h2").first();
        Elements items = classname.select("p");

        full = full + "
" + heading.text()+ "
" + "
" + items.get(0).toString() + "
" + "
";
        Element imgs2 = writing.select("div.News img").first();

        String picture = imgs2.absUrl("src");
        String newImg = "";
        full = full + "
" + newImg + "
";
        full = full + "

";

        for (int i = 1; i< items.size(); i++)
        {
            full = full + items.get(i).toString();
        }

        full = full + "

";
        return full;
    }
    public void main(String... args)
    {
        try
        {
             docs = Jsoup.connect("http://www.dcu.ie/news/index.shtml").get();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        Elements imgs = docs.select("div.news-feature img");

        Elements txt = docs.select("h2");

        Elements article = docs.getElementsByClass("date");
        Elements links = article.select("a[href]");

        for (int i = 0; i < imgs.size(); i++){
            String url = imgs.get(i).absUrl("src");
            String temp = links.get(i).absUrl("href");

            String temp2 = "";
            String newImg = temp2 + ""+ "";
            test2 = test2 + "
";

            test2 = test2 + "";
            test2 = test2 + " " + newImg + " ";
            test2 = test2 + "	";
            test2 = test2 + "";
            test2 = test2 + "
" + txt.get(i).text() + "
";
            test2 = test2 + "	";
            test2 = test2 + "
";

            }
        test2 = test2 + "
";
        test2 = test2 + "";

    }

    public void onCreate(Bundle savedInstanceState) {
        main();

        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.main );

        // Makes Progress bar Visible
        getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.setWebViewClient(new NewsClient());
        mWebView.setInitialScale(1);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.loadData(test2, "text/html", "utf-8");

        final Activity MyActivity = this;
        mWebView.setWebChromeClient(new WebChromeClient() {
         public void onProgressChanged(WebView view, int progress)
         {
          //Make the bar disappear after URL is loaded, and changes string to Loading...
          MyActivity.setTitle("Loading...");
          MyActivity.setProgress(progress * 100); //Make the bar disappear after URL is loaded

          // Return the app name after finish loading
             if(progress == 100)
                MyActivity.setTitle(R.string.app_name);
           }
         });

        //mWebView.loadUrl("http://www.google.com");
        //mWebView.loadDataWithBaseURL("", test2,"text/html", "utf-8", "");

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
        {
            mWebView.goBack();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private class NewsClient extends WebViewClient {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (view.canGoBack() == false)
            {
                String newUrl = text(url);
                view.loadData(newUrl, "text/html", "utf-8");
            }
            else
            {
                view.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
                view.loadUrl(url);
            }

            //view.loadDataWithBaseURL("", newUrl,"text/html", "utf-8", "");

            return true;
        }
    }
}

Thanks

A: Use a Intent to start your activity. Instead of:
News n = new News();
n.onCreate(null);

Use:
Intent i = new Intent(DCU.this, News.class);
DCU.this.startActivity(i);


text:
Q: How do I display specific string instead of model value in template using Ember.js? I have an Ember route displaying an array of records. The model includes status like so:
status: DS.attr('number'),

The value of status will be returned as either: -1, 0 or 1.
I have no problem displaying that value for each record in the template using handlebars: {{modelName.status}}. This way, the status for each record reflects as either: -1, 0, 1.
I would like to do the following:

If the value of status is -1 display the string "Error".
  If the value of status is 0 display the string "Completed".
  If the value of status is 1 display the string "Pending".

Is this possible?

A: How about:
status: DS.attr('number'),
statusLabel: function(){
  var statuses = ['Error', 'Completed', 'Pending'];
  return statuses[this.get('status') + 1];
}.property('status')

Then in your template:
{{modelName.statusLabel}}

A: your question is not to much clear, for my options Ember trust helper will help you.
https://github.com/jmurphyau/ember-truth-helpers.
you need to install Ember trust helper.
{{if (not-eq modelName.status -1 )}} Error

A: A small addition to the first answer- let's say my needs are:

If the value of status is -1 display the string "Error".
   If the value of status is 0 display the string "Completed".
If the value of status is anything greater than 0 display the string "Pending".

statusLabel: function() {
  var currentStatus = this.get('status');
  var statuses = ['Error', 'Completed', 'Pending'];
  if (currentStatus > 0) {
    return statuses[2];
  } else {
    return statuses[this.get('status') + 1];
  }
}.property('status'),


text:
Q: Read private key from apache SSL_CLIENT_CERT in java I've an apache protected with client authentication like this:
SSLCACertificateFile "..."
<Location ~ "...">
SSLVerifyClient require
SSLVerifyDepth 10
    RequestHeader set SSL_CLIENT_CERT ""
    RequestHeader set SSL_CLIENT_VERIFY ""

    # add whatever SSL_* variables needed to pass to web application
    RequestHeader set SSL_CLIENT_CERT "%{SSL_CLIENT_CERT}s"
    RequestHeader set SSL_CLIENT_VERIFY "%{SSL_CLIENT_VERIFY}s"
</Location>

I can read the content of header variable SSL_CLIENT_CERT in my Servlet via
String sslFromheader = httpServletRequest.getHeader( "SSL_CLIENT_CERT" );

But it seems that there is no section with -----BEGIN RSA PRIVATE KEY----- only the part
-----BEGIN CERTIFICATE-----...-----END CERTIFICATE-----

is provided in sslFromheader.
Is there anything wrong with my configuration/setup or is this still not possible and "%{SSL_CLIENT_VERIFY}s" contains not the whole client certificate?


text:
Q: MrSid nodata cells in Lizardtech I have an odd shaped (not square) raster .tiff file that I converted to MrSid using Lizardtech's GeoExpress. It converts the nodata to black. This is applying a value to no data.
Eventually I want to overlay this MrSid image on top of other layers, so the nodata cells need to be transparent.
How do I do this?

A: After a few trials and errors we came up with this solution. As with most GIS processing there are multiple ways to do things so although I am sure there are other, maybe better, ways this worked efficiently enough for us with the tools we had on hand and are most familiar with.
We took the raster.tiff and opened it in Global Mapper. We exported the raster to GeoTiff format, ensuring 24 bit and toggle on the "Make Background (Void) pixels transparent" option under TIFF Format Options.
When we used LizardTech to compress the file we toggled on lossless. This time when we loaded the MrSid image back into Global Mapper and ArcGIS 10.4 the image looked as we wanted. Now we can load it into our tablet software and the transition layers show up nicely.

A: If your wanting to view in GeoViewer, go to the Layer Controls for the raster and in this window scroll down to 'No Data Value' set this to 0 and all 0 values will become transparent.
You can do the same viewing in QGIS by going to layer properties, selecting the transparency tab and you have 3 sections to choose either global, no data or custom transparency ranges. In the No Data Value section, just set to 0 and all 0's will be transparent. Alternatively you can set ranges from say 0-100 as transparent in the Custom Transparancey Options section,


text:
Q: RuntimeException when camera is tilted from portrait to landscape I have a Fragment which uses a CameraPreview like so:
    mCamera = getCameraInstance();
    mPreview = new CameraPreview(getActivity(), mCamera);
    FrameLayout preview = (FrameLayout) rootView.findViewById(R.id.camera_preview);
    preview.addView(mPreview);

This works fine - opens up a camera view as intended. However, when I tilt the camera from portrait to landscape I get a RuntimeException
java.lang.RuntimeException: Fail to connect to camera service
        at android.hardware.Camera.native_setup(Native Method)
        at android.hardware.Camera.<init>(Camera.java:413)
        at android.hardware.Camera.open(Camera.java:384)
        at com.example.sv_laptop03.myApp.CameraPreview.surfaceCreated(CameraPreview.java:36)
        at android.view.SurfaceView.updateWindow(SurfaceView.java:610)
        at android.view.SurfaceView.access$000(SurfaceView.java:93)
        at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:182)
        at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:864)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2142)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1249)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6364)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
        at android.view.Choreographer.doCallbacks(Choreographer.java:591)
        at android.view.Choreographer.doFrame(Choreographer.java:561)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
        at android.os.Handler.handleCallback(Handler.java:730)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:5419)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
        at dalvik.system.NativeStart.main(Native Method)

and it specifically complains about the first line in the else block of this method:
    public void surfaceCreated(SurfaceHolder holder) {
    try {
        if(mCamera != null) {
            mCamera.setDisplayOrientation(90); // WITHOUT THIS MY CAMERA AXIS' ARE FLIPPED
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } else {
            mCamera = Camera.open(); // RUNTIME EXCEPTION HERE
            mCamera.startPreview();
        }
    } catch (IOException e) {
        Log.d("TAG", "Error setting camera preview: " + e.getMessage());
    }
}

I included permissions in AndroidManifest
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus"/>

Does anybody know what could be causing the crash? It seems to work fine on a Galaxy S6 but crashes on my S3. Any help is highly appreciated.
Edit:
I added this in my Activity, now the app crashes before the camera loads.
 @Override
public void onPause() {
    super.onPause();
    mCamera.release();
}

@Override
public void onResume() {
    super.onResume();
    mCamera.open();
}

A: Have you tried to call release() when you are being destroyed?
From: http://developer.android.com/reference/android/hardware/Camera.html
Important: Call release() to release the camera for use by other applications. Applications should release the camera immediately in onPause() (and re-open() it in onResume()).