text:
Q: how to retreive a photo user from the user.list api of the google admin SDK? I have trouble understanding the problem to recover the user photo from google.
First, the photo user is authorized for everyone. Normally it is saved in Account google(people), see screenshot, below.
In my test procedure, there is no account id in the account google  (people).
so, I take another solution: user.list at admin google.
I found the photo url: user.thumbnailPhotoUrl.
it doesn't display because "private" is in that URL. yet in the google account, the photo is public.
so How to get the real url?

function doGet() {

var emailadresse = 'testbertrand@radiopresence.com';
var id_user = '117966962362496071521';

var parm_table = UserPhotoTest (id_user);
Logger.log('parm_table  :'+parm_table );

}

function UserPhotoTest (user_id) {
var accountId =user_id;
Logger.log ('function userphoto  - N°account id  :'+accountId );

  var val_photoUrl = "";
  var val_namefile = "";

try
{ var person = People.People.get('people/' + accountId, {personFields: 'names,photos,phoneNumbers,addresses,birthdays,sipAddresses,organizations,genders'});
  //** var val_displayName_P = person.names[0].displayName;
   var val_photoUrl = person.photos[0].url.replace("=s100","=s128");
   var val_namefile = get_namefile(val_photoUrl);
  }
  catch (err)
  {
  Logger.log ('function userphoto  - Error : '+err);

 var user = AdminDirectory.Users.get(emailadresse);

 var val_photoUrl = user.thumbnailPhotoUrl
    if (val_photoUrl.indexOf("private") > -1)
    {
    var testphotoadmin  = AdminDirectory.Users.Photos.get(emailadresse);
    // in document, I didn't understand it for AdminDirectory.Users.Photos.get(emailadresse);
    // May you help me to developp here
    //   how to retreive a real url ?
    // val_photoUrl = ...
    }

  }

  var parm_photo = val_photoUrl;
return parm_photo;
}

A: What I have noticed is that photos uploaded from the Admin console as an Admin if you have a Google Workspace account they remain as private when retrieving the thumbnailPhotoUrl. This function should allow you to check whether the URL is private or not:
function retrievePhoto(){
  var user = 'youremail@yourdomain.com';
  var photo = AdminDirectory.Users.get(user,{fields:'thumbnailPhotoUrl'});
  console.log(photo);
}

Using the above code should retrieve your thumbnailPhotoUrl when using the Admin SDK in App Script. If the profile picture was updated from the Admin console most likely the URL will show as private. If the thumbnailUrl still shows as private try allowing this setting in the Workspace console and update the profile picture in aboutme.google.com as this should set the picture as public.


text:
Q: Why Array.reverse_each is faster than Array.reverse.each I hardly use reverse_each method, instead I call upon reverse.each when I need to traverse an array backwards. So I just did some benchmarking and apparently reverse_each is significantly faster than reverse.each.

*

*Is this because there is an element of time associated with creating a reverse array before iterating through it when using reverse.each?

However in my example (below) of 10 million iterations TIME(reverse) + TIME(each) - TIME(reverse.each) ~ 1.2 seconds for an array of size 4. And this time difference more or less stays stable irrespective of the size of array. I have tested it for upto 100 elements.

*

*What accounts for this one second difference?

require 'benchmark'

number = 10000000
arr = (1..4).to_a

Benchmark.bm(13) do |x|
    x.report("reverse.each") { number.times { arr.reverse.each {|x| x} } }
    x.report("reverse_each") { number.times { arr.reverse_each {|x| x} } }
    x.report("reverse")      { number.times { arr.reverse } }
    x.report("each")         { number.times { arr.each {|x| x} } }
end

A: I would definitely say it has to do with the time associating with creating the reverse array! You've only tried really small arrays (an array with 100 elements is still a small array). If you try with bigger arrays (for instance 10k elements), I think you will really notice the difference.

A: It's pretty straight forward:

*

*reverse.each creates a new array then loops each element

*reverse_each loops in reverse order (no intermediate array created)
See source code in doc: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-reverse_each

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display picture in gallery I looked trough google and SO but did not find an answer to my question. I found a lot of topics about the Picker but I want to display an Image and not select one.
I have a Storyboard with various data, one of them being an ImageView with a scaled Image I receive from my database with Parse.
Now I want to display the full image when it is pressed. I know I could create a new View for this, but I was wondering if it would be possible to open this with Apple's Gallery or if there is alternative solution with Cocoapod that would simplify the displaying of the image.
I don't want to build a GUI just to view the full image and being able to zoom/share etc. if there is an already existing solution.

A: You could look into UIImagePickerController should only take a short time to implement and easy to get the image the user picks but you cannot change the appearance or extend the functionality.
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImagePickerController_Class/
EDIT: Due to my misunderstanding.
This GitHub has a very good and easy solution for simply displaying an image in a full screen manner with built in gesture control.
https://github.com/bufferapp/buffer-ios-image-viewer
One of the best parts is that you can initialise it with URL/ALAsset/PHAsset/UIImage all through the same initialiser.
BFRImageViewController *imageVC = [[BFRImageViewController alloc] initWithImageSource:@[image]];


text:
Q: EF Core: Parameterized Query Expects the parameter '@responseMessage' which was not supplied I have the following stored procedure that I'm trying to call from my asp.net core MVC web application:
CREATE PROCEDURE [dbo].[uspLogin]
(
    @pUserName VARCHAR(150),
    @pPassword VARCHAR(150),
    @responseMessage NVARCHAR(250)='' OUTPUT
)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON

    DECLARE @userID INT

    IF EXISTS (SELECT TOP 1 ID FROM dbo.[User] WHERE UserName = @pUserName)
    BEGIN
        SET @userID = (SELECT ID FROM dbo.[User] WHERE UserName = @pUserName AND PasswordHash=HASHBYTES('SHA2_512', @pPassword+CAST(Salt AS NVARCHAR(36))))

        IF(@userID IS NULL)
            SET @responseMessage='Incorrect password'
        ELSE
            SET @responseMessage='Success'
    END
    ELSE
        SET @responseMessage = 'Invalid Login'
END

I can call this procedure perfectly fine from within my DB, however I'm trying to call it with this code:
[HttpPost]
public IActionResult Index(User user)
{
    var userName = user.UserName;
    var password = user.Password;
    var message = new SqlParameter
    {
        ParameterName = "responseMessage",
        SqlDbType = SqlDbType.NVarChar,
        Size = 250,
        Direction = ParameterDirection.InputOutput,
    };
    _context.Database.ExecuteSqlCommand("dbo.uspLogin @p0, @p1, @responseMessage", userName, password, message);

    return RedirectToAction("Success", "Home", new { email = message.SqlValue });
}

When testing out this action, I get the following error:

SqlException: The parameterized query '(@p0 nvarchar(4000),@p1 nvarchar(4000),@responseMessage nvarchar' expects the parameter '@responseMessage', which was not supplied.

What is the right way to get the output of this procedure from EF Core?

A: Change param direction,
var message = new SqlParameter
{
    ParameterName = "responseMessage",
    SqlDbType = SqlDbType.NVarChar,
    Size = 250,
    Direction = ParameterDirection.Output,
};

And execution line as below and try,
_context.Database.ExecuteSqlCommand("dbo.uspLogin @p0, @p1, @responseMessage OUT", userName, password, message);

A: Please check spaces for each parameter which were defined in the stored procs and in your repository methods.
We would need to trim the whitespaces and rerun the program. In our case, We had to remove the whitespaces, once done, the API method was successfully executing....


text:
Q: CSRF Guard - Implementing it across .war files? I have implemented CSRF Guard in one of the module of a project (aaaa.war) and it's working fine as excepted with in it. Now I have to implement the same in other modules also.
I have done the same steps in other bbbb.war file also (included csrf.jar, js file, change the web.xml and properties file) however in this case tokenfromsession is not matching because in the project there are calls from one .war file to another .war file. (might be the reason)
Any idea why I'm getting this or how can I fix this?
Is it possible to use the same implemented CSRF guard (aaaa.war) in other bbbb.war file also?
Thanks.

A: why not make your csrf guard abstracted to both of your wars and forward all requests to the csrf guard implementation then post the requests to the particular war.


text:
Q: How to set up a file that works only on a particular computer I need to protect a file or folder and prevent it from being copied. I mean, when users try to copy it on external drive or send the file via email - it won't work on theirs machines.
Windows 7 and XP are my targets.

A: One way to do so would make the file a system file; if it doesn't need to be edited make system32 the owner of the file. When you do that' it's almost invisible so the user won't know it exists....Unfortunately, it's not possible to prevent copying of a file if it's executable.


text:
Q: How to split the string i.e ('data+demo+on+saturday) using re in python. I want to use + for splitter but it thowing an error How to split the string (e.g. 'data+demo+on+saturday') using re in Python.
I want to use + for splitter but it throwing an error.

A: By using (,), you are capturing the group, if you simply remove them you will not have this problem.
>>> str1 = "data demo on saturday"
>>> re.split(" +", str1)
['data', 'demo', 'on', 'saturday']

A: You should read the comments and listen to them:
>>> import re
>>> a = 'data+demo+on+saturday'
>>> re.split( r'\+', a)
['data', 'demo', 'on', 'saturday']

A: You have to use '\+'
import re

s = "a+b+c"
s = re.split('\+', s)
print(s)


text:
Q: Discount Price is not being added into my Windows Forms C# In my code, I am supposed to add a 10% discount if the user clicks on the Pay in Advanced button (btnAdvanced) in my form. So let's say the user chooses 3 adults, 0 children, and 1 day pass with no parking pass. The total should add up $132.20, but it is getting stuck on $147.
Below is my code.
private void btnAdvance_Click(object sender, EventArgs e)
        {
            double dblAdultPrice = 0; //adult price
            double dblChildPrice = 0; //child price
            double dblDiscountPercent = .10;

            if (lstAdult.SelectedIndex == -1)
            {
                //User Selected no Adult
                MessageBox.Show("Please choose an Adult value");
            }
            else
            {
                dblAdultPrice = 49 * lstAdult.SelectedIndex; // this could require a data type conversion
            }

            // get child prices
            if (lstChildren.SelectedIndex == -1)
            {
                //User Selected no Adult
                MessageBox.Show("Please choose a Child value");
            }
            else
            {
                dblChildPrice = 42 * lstChildren.SelectedIndex;
            }

            // calculate day
            double dblSecondaryPrice = 0;
            double dblSecondDayPrice = 0;

            if (rdoTwo.Checked)
            {
                dblSecondDayPrice = 25.00;
            }

            //parking pass
            double dblParkingPrice = 0;

            if (ChkParking.Checked)
            {
                dblParkingPrice = 15.00;
            }

            //calculate
            double dblGrandTotal = dblAdultPrice + dblSecondaryPrice + dblChildPrice + dblSecondDayPrice + dblParkingPrice *10;

            lblTotal.Text = dblGrandTotal.ToString("N2");
        }
    }
}

A:   private void btnAdvance_Click(object sender, EventArgs e)
        {
            double dblAdultPrice = 0; //adult price
            double dblChildPrice = 0; //child price

            if (lstAdult.SelectedIndex == -1)
            {
                //User Selected no Adult
                MessageBox.Show("Please choose an Adult value");
            }
            else
            {
                dblAdultPrice = 49 * lstAdult.SelectedIndex; // this could require a data type conversion
            }

            // get child prices
            if (lstChildren.SelectedIndex == -1)
            {
                //User Selected no Adult
                MessageBox.Show("Please choose a Child value");
            }
            else
            {
                dblChildPrice = 42 * lstChildren.SelectedIndex;
            }

            // calculate day
            double dblSecondaryPrice = 0;
            double dblSecondDayPrice = 0;

            if (rdoTwo.Checked)
            {
                dblSecondDayPrice = 25.00;
            }

            //parking pass
            double dblParkingPrice = 0;

            if (ChkParking.Checked)
            {
                dblParkingPrice = 15.00;
            }

            //calculate
            double dblGrandTotal = dblAdultPrice + dblSecondaryPrice + dblChildPrice + dblSecondDayPrice + dblParkingPrice;
            double dblDiscountPercent = dblGrandTotal * .10;
            double dblGrandTotalDiscount = dblGrandTotal - dblDiscountPercent;

            lblTotal.Text = dblGrandTotalDiscount.ToString("N2");
        }
    }
}

Figured it out, I added more DBLs at the end which is
double dblGrandTotal = dblAdultPrice + dblSecondaryPrice + dblChildPrice + dblSecondDayPrice + dblParkingPrice;
            double dblDiscountPercent = dblGrandTotal * .10;
            double dblGrandTotalDiscount = dblGrandTotal - dblDiscountPercent;

            lblTotal.Text = dblGrandTotalDiscount.ToString("N2");


text:
Q: can we add .shp file in iphone sdk? Actually i need to add SharpMap file as a mapView which has extension .shp so does any one have any kind of help about how we can use this .shp file as a mapview in ios.

A: .shp files are Shapefiles which is an ESRI standard, SharpMap is an opensource .Net project which provides spatial feature and map display using various map formats including Shapefiles.
To read/parse shapefiles and display their geometry in the ios you can try the following:
grgcombs / iOS-Shapefile


text:
Q: Adding navigation to QGIS Shapefile? I'm looking to create an APP with Navigation Offline.
The problem is my point of interest is not offered by OpenStreetMap (OSM).
I would like to know if can i add navigation to a shapefile (mine) or should i add the new area to OSM?


text:
Q: Convert Array to Json
Possible Duplicate:
Serializing to JSON in jQuery
Convert Object to JSON string

I want to  convert array to json object in js or jquery.
     Is there any function is available or lib
Thanks in advance

A: In modern browsers you can simply use JSON.stringify(someJSObject) to convert any JavaScript object (that includes arrays) to a JSON string.
To ensure it also works in less modern browsers, include https://github.com/douglascrockford/JSON-js/blob/master/json2.js on your page.

A: How about
var jsonString = JSON.stringify(myArray);


text:
Q: Update data, but nothing change in ASP.NET I need help, I am developing an ASP.NET app, there are 2 problems,
Problem #1: when I click the "update" button, it says success, but nothing happened in the database, the data is still the same as before...
Problem #2: when I click select on gridview, all of my input fills with data from database except password input
Here is my code
Update code:
try
{
    con.Open();
    MySqlCommand cmd = new MySqlCommand("UPDATE datauser SET Password = @b, Nama = @c, Role@d WHERE Username = @a", con);
    cmd.Parameters.AddWithValue("@a", uname.Value.Trim());
    cmd.Parameters.AddWithValue("@b", pwd.Value.Trim());
    cmd.Parameters.AddWithValue("@c", nama.Value.Trim());
    cmd.Parameters.AddWithValue("@d", ddlrole.SelectedItem.Text);

    cmd.ExecuteNonQuery();
    con.Close();

    lblok.Text = "Perbarui " + ddlrole.SelectedItem.Text + " Berhasil";
    okm.Visible = true;
    ClientScript.RegisterStartupScript(this.GetType(), "alert", "HideLabel();", true);
    reset();
}
catch (Exception ex)
{
    con.Close();
    lbleror.Text = ex.Message.ToString();
    errm.Visible = true;
}

Gridview "SelectionChanged" event:
string pas;
GridViewRow gvrow = griduser.SelectedRow;
uname.Value = gvrow.Cells[0].Text.ToString();
pwd.Value= gvrow.Cells[1].Text.ToString();
nama.Value = gvrow.Cells[2].Text.ToString();
ddlrole.SelectedValue = gvrow.Cells[3].Text;
invokeedit();

Gridview ASPX markup:
<asp:GridView ID="griduser" CssClass="table table-bordered table-striped" runat="server"
     AutoGenerateColumns="False" Width="100%"
     CellPadding="4" ForeColor="#333333" GridLines="None"
     AllowPaging="True"
     OnSelectedIndexChanged="griduser_SelectedIndexChanged">
     <Columns>
         <asp:BoundField DataField="Username" HeaderText="Username" />
         <asp:BoundField DataField="Password" HeaderText="Password" />
         <asp:BoundField DataField="Nama" HeaderText="Nama" />
         <asp:BoundField DataField="Role" HeaderText="Role" />
         <asp:TemplateField HeaderText="Aksi">
             <ItemTemplate>
                  <asp:LinkButton ID="link" CommandName="Select" ToolTip="Edit"
                       runat="server" CssClass="icon-edit"></asp:LinkButton>
                  <asp:LinkButton ID="lnkremove" CommandArgument='<%# Eval("Username")%>'
                       ToolTip="Hapus" runat="server" CssClass="icon-remove"
                       OnClientClick="return confirm('Do you want to delete?')"
                       OnClick="hapusdata"></asp:LinkButton>
             </ItemTemplate>
         </asp:TemplateField>
    </Columns>
</asp:GridView>


text:
Q: setup from usb not disc I only have 700 MB CD.  Tried to save to USB but still asks to burn image CD and I don't have CD big enough.  Can I bypass burn image CD? how? if not how big does CD have to be? disc burner only has DVD drive option so I cant select USB as option even when USB in computer.  Computer has all necessary hardware called for by ubuntu.

A: There are plenty of guides to show you how to create a bootable USB. You can refer to one of them. e.g.  how to make a bootable usb for ubuntu 16.04

A: You can not create a bootable USB with a disc burner.
I would recommend using Etcher to create a bootable USB, because it is open source, very easy to use, and available for almost any platform.
Alternatively you can follow the official Tutorials to create a bootable USB with Ubuntu on Windows, Ubuntu or Mac.
Good Luck!


text:
Q: How do I validate hmac properly in nodejs for callrail API? Not sure how to properly verify a request with the callrail API key using nodeJS
I keep getting different hex results than the example provided.

A: I was able to figure this out using How do I validate the Hmac using NodeJS?
The code that validates the example provided in the callrail documentation in nodejs is
const request_payload = {"answered":false,"business_phone_number":"","call_type":"voicemail","company_id":155920786,"company_name":"Boost Marketing","company_time_zone":"America/Los_Angeles","created_at":"2018-02-19T13:41:00.252-05:00","customer_city":"Rochester","customer_country":"US","customer_name":"Kaylah Mills","customer_phone_number":"+12148654559","customer_state":"PA","device_type":"","direction":"inbound","duration":"13","first_call":false,"formatted_call_type":"Voicemail","formatted_customer_location":"Rochester, PA","formatted_business_phone_number":"","formatted_customer_name":"Kaylah Mills","prior_calls":16,"formatted_customer_name_or_phone_number":"Kaylah Mills","formatted_customer_phone_number":"214-865-4559","formatted_duration":"13s","formatted_tracking_phone_number":"404-555-8514","formatted_tracking_source":"Google Paid","formatted_value":"--","good_lead_call_id":715587840,"good_lead_call_time":"2016-06-17T10:23:33.363-04:00","id":766970532,"lead_status":"previously_marked_good_lead","note":"","recording":"https://app.callrail.com/calls/766970532/recording/redirect?access_key=aaaaccccddddeeee","recording_duration":8,"source_name":"Google AdWords","start_time":"2018-02-19T13:41:00.236-05:00","tags":[],"total_calls":17,"tracking_phone_number":"+14045558514","transcription":"","value":"","voicemail":true,"tracker_id":354024023,"keywords":"","medium":"","referring_url":"","landing_page_url":"","last_requested_url":"","referrer_domain":"","conversational_transcript":"","utm_source":"google","utm_medium":"cpc","utm_term":"","utm_content":"","utm_campaign":"Google AdWords","utma":"","utmb":"","utmc":"","utmv":"","utmz":"","ga":"","gclid":"","integration_data":[{"integration":"Webhooks","data":null}],"keywords_spotted":"","recording_player":"https://app.callrail.com/calls/766970532/recording?access_key=aaaabbbbccccdddd","speaker_percent":"","call_highlights":[],"callercity":"Rochester","callercountry":"US","callername":"Kaylah Mills","callernum":"+12148654559","callerstate":"PA","callsource":"google_paid","campaign":"","custom":"","datetime":"2018-02-19 18:41:00","destinationnum":"","ip":"","kissmetrics_id":"","landingpage":"","referrer":"","referrermedium":"","score":1,"tag":"","trackingnum":"+14045558514","timestamp":"2018-02-19T13:41:00.236-05:00"};
const crypto = require('crypto');
const cipher = 'sha1';
const payloadstring =  JSON.stringify(request_payload);

const hash = crypto.createHmac(cipher, key)
               .update(payloadstring)
               .digest('base64');

console.log(hash);

This results in the proper hash response of
UZAHbUdfm3GqL7qzilGozGzWV64=


text:
Q: The provider is not compatible with the version of oracle (ASP.NET Core MVC) I'm really frustrated and i do not know what to do.
I'm trying to connect to an Oracle 11g database but every time I try to connect Visual Studio 2019 throws an error message. I already tried a lot of different things but nothing really helped me.
I have already made sure the app set to run in 32 bit mode in the IIS console. I still can't figure out why is not working.
By the way, here is my code:
readonly string connectionString = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxxxxxx)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=PROD)));User Id=xxx;Password=xxxx;"

public IEnumerable<Person>GetPersonList
{
    var listPerson = new List<Person>();

    using (OracleConnection con = new OracleConnection(connectionString))
    {
        OracleCommand cmd = new OracleCommand("select * from myview", con);
        cmd.Connection = con;
        cmd.InitialLOBFetchSize = 1000;
        cmd.CommandType = CommandType.Text;

        con.Open();

        OracleDataReader dr = cmd.ExecuteReader();

        while (dr.Read())
        {
            var list = new Person();
            list.CODE = Convert.ToInt32(dr["CODE"].ToString());
            list.NAME = dr["NAME"].ToString();
            list.LASTNAME = dr["LASTNAME"].ToString();

            listPerson.Add(list);
        }

        con.Close();
    }

    return listPerson;
}

What should I do?

A: My problem was solved: needed to install instant client for Oracle 11g and everything worked just fine


text:
Q: Apache POI 3.16 Excel Download Open issue There is an error when I download and open the Excel file. I haven't worked this out for three days. I want you to help me.
poi 3.16
poi-ooxml 3.16
poi-ooxml-schemas 3.16
poi-scratchpad 3.16
1. Download and open file normally
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("sheet1");
        Row row = null;
        Cell cell = null;
        int rowNum = 0;

        row = sheet.createRow(rowNum++);
        cell = row.createCell(0);
        cell.setCellValue("no");

        for (int i=0; i<3; i++) {
            row = sheet.createRow(rowNum++);
            cell = row.createCell(0);
            cell.setCellValue(i);
        }

        response.setContentType("ms-vnd/excel");
        response.setHeader("Content-Disposition", "attachment;filename=example.xls");

        // Excel File Output
        wb.write(response.getOutputStream());
        wb.close();

2. Download and don't open the file
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("sheet1");
        Row row = null;
        Cell cell = null;
        int rowNum = 0;

        row = sheet.createRow(rowNum++);
        cell = row.createCell(0);
        cell.setCellValue("no");

        for (int i=0; i<3; i++) {
            row = sheet.createRow(rowNum++);
            cell = row.createCell(0);
            cell.setCellValue(i);
        }

        response.setContentType("ms-vnd/excel");
        response.setHeader("Content-Disposition", "attachment;filename=example.xlsx");

        // Excel File Output
        wb.write(response.getOutputStream());
        wb.close();

errorImage
And I've also written this on "xlsx" -> application/vnd.openxmlformats-offered document.spreadsheetml.sheet
It doesn't open the same way.
Is there a bug in 3.16?
It sounds a little weird, but I tried one more thing.
3. Open but abnormally open
OutputStream out = null;
        ByteArrayOutputStream bout = null;

        try {
            bout = new ByteArrayOutputStream();
            wb.write(bout);

            setHeader(request, response, fileName);
            response.setContentLength(bout.size());

            autoSizeColumns(wb);

            out = response.getOutputStream();

            wb.write(out);

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

            try {
                if (out != null) bout.close();
                if (out != null) out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

Workbooks are created elsewhere.
If I write it like this, there will be an error as below.
errorImage
When I press Yes, the file opens and the contents are visible, but the style is broken.


text:
Q: Importing CSV file to a SQL Server table using SSIS I have a requirement where I need to load data into a SQL Server table from a .CSV file. The file has around 20 columns, with each of them having the datatype set to General.
However, there are a few columns which are of the type Currency. I am trying to load the file through a DFT in the SSIS. On loading the file, the SSIS fails at the source task, with the error message showing

Conversion could not be done as it could lead to a potential loss of data

for one of the amount columns (let's call it cAmount) which has amounts in US $. This is failing the SSIS. It failed with the column's Metadata in the SSIS set to DT_CR(currency), DT_STR. However, if I change this type to numeric or general in the .CSV file, it succeeds without any issue.
Is there something I am not doing correctly or is it just not possible to load currency type into the SQL Server table?
Please let me know if the above query is confusing and if I need to share a screenshot of the same.

A: Please check whether you amount data contains currency symbols such as ($).
You can't insert currency symbols into a money field (which underlying implementation in sql server is decimal(19,4)).
If you want to insert data with currency symbols then first insert into a temporary table, where "money" field is defined as a varchar. Then update this field and remove all currency symbols.Then write another SQL statement to move the data from the temporary table to the real table.


text:
Q: Finding a whole word in text file by using 4-7 letters I am newbie in C and I will be glad for any help with this program:
Task:
User will enter 4-7 letters (for example 'ADFG').
I have detached text file which contains about several thousand of words
(for example:

*

*BDF

*BGFK

*JKLI

*NGJKL

*POIUE

etc.)
-its written in list without that marks
I want to make program, which find words from this text file, which are same as letters which user entered (In this case, when I entered ADFG it will find and display BDF, BGFK, NGJKL).
This is my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char enter[8],row[80];

    printf("4-7 different letteres: ");
    gets(enter);

    if (strlen(enter)>7 || strlen(enter)<4)
    {
        puts("incorrect number of letters");
        return 1;
    }

    typedef struct structure
    {
        char row[50];
    }Row;

    Row textrow[40000];

    FILE *file;
    file = fopen("words.txt","r");

    if (file==NULL)
    {
        printf("Error! File %s can not be opened.","words.txt");
        return 1;
    }

    int i=0;
    char words[30];

    while (!feof(file))
    {
        fscanf(file,"%s",&textrow[i].row[0]);
        for(int j=0;j<strlen(enter);j++)
        {
            for(int k=0;k<strlen(textrow[i].row);k++)
            {
                words=strchr(textrow[i].row[k],enter[j]);
                printf("%s",words);
            }
        }
        i++;
    }

    fclose(file);
    return 0;
}

Thanks for any help.

A: e.g. use strpbrk
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    char *words[] = {
        "BDF", "BGFK", "JKLI", "NGJKL", "POIUE", NULL
    };
    char enter[8] = "ADFG";
    char **p;
    for(p = words; *p ; ++p){
        char *word = *p;
        if(strpbrk(word, enter)!=NULL){
            printf("%s\n", word);
        }
    }
/*
BDF
BGFK
NGJKL
*/
    return 0;
}

A: As others have commented, given your code is possibly able to compile and build as is,  your problem is with the approach, you need to identify the steps necessary to accomplish what you desire.  Create the algorithm.  Here are some steps to do what I think you want to do:
Problem statement:  Given a text file with many words, and user input of 1 or more characters, find all words in file that contain one or more of the characters user entered.
Steps:  (approach)
1)  Read all words of text file into a string array
2)  Get user input string into char array
3)  In Loop: Check each char of user input to each char of each string
len = strlen(userInputStr);

for(i=0;i<numWords;i++)  //numWords is number of words in file
{
    len2 = strlen(word[i]);//length of next word in file
    for(j=0;j<len;j++)
    {
        for(k=0;k<len2;k++)
        {
             //check each char of user input against each char of current word
        }
    }
}


text:
Q: Disable the cache? I've looked around the web and found you can clear the cache via:
php artisan cache:clear

I am looking for a solution where you can turn off the cache in a dev environment. I do not want to run the above cmd everytime.
 return Cache::remember('my-key', 60, function() {
        //get page
    });

So above I check the cache, this occurs throughout my app, is there a simple way to disable it in a dev environment?

A: Set your cache driver to array in .env file for your DEV environment. This way cache will be wiped out at the end of every request, but you'll be able to use Cache facade.
CACHE_DRIVER=array


text:
Q: Migrate large database from MySQL 8 to MariaDB I need a solution to migrate a large database from MYSQL 8 to MariaDB (any version, but preferably 10.4)
I have already searched the MariaDB site and I have done Google searches on the subject but I have not found anything yet.
Unfortunately, the solution to run a mysqldump seems to me not very feasible, because the database that I have to migrate is at least 40 GB large (of physical disk space).

A: In general MariaDB is designed as a drop-in replacement for MySQL.
Since MySQL 8.0 it's unfortunately not possible anymore to simply replace MySQL with MariaDB and use the same data-files as before.
The only way to move to MariaDB from MySQL 8.0 or higher is using mysqldump.
See here for reference: https://mariadb.com/kb/en/upgrading-from-mysql-to-mariadb/

If you are using MySQL 8.0 or above, you have to use mysqldump to move your database to MariaDB.

Another solution that came to my mind was downgrading from MySQL 8.0 to MySQL 5.7 - unfortunately that is not possible either:

Downgrade from MySQL 8.0 to MySQL 5.7, or from a MySQL 8.0 release to a previous MySQL 8.0 release, is not supported. The only supported alternative is to restore a backup taken before upgrading. It is therefore imperative that you backup your data before starting the upgrade process.

https://dev.mysql.com/doc/refman/8.0/en/downgrading.html
I think you have to take the time for a mysqldump.
Sorry m8.

A: Plan A:
mysqldump -h mysql_8_host ... | mysql -h mariadb_10_host ...

That avoids instantiating the intermediate file that you say might be 160GB.
Plan B:
mysqldump -h mysql_8_host ... | gzip >dump.gz
gunzip <dump.gz | mysql -h mariadb_10_host ...

The compressed file will probably be less than 40GB.  For one thing, it will not have the indexes.  (They will be rebuilt in the second step.)
In either case...
There may be incompatibilities between the two versions.  Check out the parameters of both mysql's mysqldump, which might have backward-compatibility options, and mariadb's mysqldump, which might be prepared to accept 8.0 input.


text:
Q: NEST connecting: ConnectionSettings does not have parameter 'defaultIndex'  public class Class1
    {
        public static Uri node;
        public static ConnectionSettings settings;
        public static ElasticClient client;

        public static void Main(string[] args)
        {
            node = new Uri("http://localhost:9200");
            settings = new ConnectionSettings(node, defaultIndex: "my-application");
            var client = new ConnectionSettings(settings);
        }
    }

I get this error when i build this code. I am referring:
Elastic search doc: elastic search nest doc
Nest doc: Nest doc
I have NEST 2.0.2 version with VS Express 2015 for web. I think documentation is for old versions of NEST. Can someone please suggest me some latest doc or what can be solution for this?

A: The default index can be set by a method of ConnectionSettings:
public class Class1
{
    public static Uri node;
    public static ConnectionSettings settings;
    public static ElasticClient client;

    public static void Main(string[] args)
    {
        node = new Uri("http://localhost:9200");
        settings = new ConnectionSettings(node);
        settings.DefaultIndex("my-application");
        var client = new ElasticClient(settings);
    }
}


text:
Q: Lining up divs side by side and div exceeding container div I need your help,
My problem is two fold, firstly BoxB exceeds the height of its main (parent) box, and secondly, I can't seem to be able to line up BoxB and BoxC neatly, side by side of each other.
Here is a quick screenshot:

* {
    font-family: Segoe UI;
    font-size: 9pt;
}
#main {
    border: 1px solid #000;
    width: 800px;
    height: 600px;
    font-weight: bold;
}
#boxA {
    padding: 5px;
    border-bottom: 1px solid rgb(180,180,180);
}
#boxB {
    height: 100%;
    width: 250px;
    border: 1px solid red;
    float: left;
}
#boxC {
    background: rgb(240,240,240);
    height: 100%;
    width: 545px;
    border: 1px solid blue;
    float:left;

}

Application Title

A: So as pointed out you didn't close the DIVs properly. As for the other 2 issues. If you remove the floats and use display: inline-block the divs will be on same line. Also if you make content box-sizing: border-box; this will help because it keeps borders/padding as a part of the total width/height of elements. And I suggest if you know the main content will always be 600px in height as you defined in CSS you should just give the top div a set height and give remaining height to bottom two divs as well.
HTML:

Application Title

CSS:
* {
    font-family: Segoe UI;
    font-size: 9pt;
    box-sizing: border-box;
}
#main {
    border: 1px solid #000;
    width: 800px;
    height: 600px;
    font-weight: bold;
}
#boxA {
    padding: 5px;
    border-bottom: 1px solid rgb(180,180,180);
    height: 25px;
}
#boxB {
    height: 575px;
    width: 250px;
    border: 1px solid red;
    display: inline-block;
}
#boxC {
    background: rgb(240,240,240);
    height: 575px;
    width: 545px;
    border: 1px solid blue;
    display: inline-block;
}

Fiddle: http://jsfiddle.net/hpuywg42/

A: The problem with #boxC not being in the right place is easier to solve. This:

should be

You were opening new divs instead of closing them as you intended. Faced with three opening divs in a row, the browser built new divs so that #boxC was inside a box without id which was inside #boxB, then it closed them all when it got to the end of your html markup and couldn't find the closing tags it was waiting for.
As for #boxB (and now #boxC) overflowing #main, the problem is that you've set them to be 100% of their parent's height, but also included another div which takes up vertical space (that being #boxA). There are many solutions to this, but the easiest may be to decrease the height of boxB and boxC to account for the vertical space taken up by #boxA.


text:
Q: Delete Pointer in C++ got me confused **struct ListNode {
        int val;
      ListNode *next;
         ListNode(int x) : val(x), next(NULL) {}
     };
ListNode* Merge(ListNode* list1, ListNode* list2){//list1 2; list2 4
    ListNode* result = new ListNode(0);
    ListNode* travel = result;
    while(list1 || list2){
        cout << "hereWhile" << endl;
        //cout << list1->val << list2->val << endl;
        if(!list1){
            travel->val = list2->val;
            list2 = list2->next;
            travel->next = new ListNode(0);
            travel = travel->next;
        }
        else if(!list2){
            travel->val = list1->val;
            list1 = list1->next;
            travel->next = new ListNode(0);
            travel = travel->next;
        }
        else{
            if(list1->val <= list2->val){
                travel->next = new ListNode(0);
                travel->val = list1->val;
                list1 = list1->next;
                travel = travel->next;
            }
            else{
                travel->next = new ListNode(0);
                travel->val = list2->val;
                list2 = list2->next;
                travel = travel->next;
            }
        }
    }
    cout << "travel at the end: " << (travel == result->next->next) << endl;
    delete result->next->next;
    //delete travel;
    cout << travel->val << endl;
    cout << result->val << endl;
    cout << result->next->val << endl;
    cout << "val: " << result->next->next->val << " end" << endl;

    return NULL;
}**

in my case, the above delete method never works.
I have updated my whole code in order to provide more details. This is part of implementing a MergeSort by linked list. And my testcase is this recursion and this Merge function is list1 = {2} and list2 = {4} , so the Merge function is designed to return the head of a linked list {2,4} which has a size of two nodes.
In my code above, I declared a new node to travel->next in each of my if statement and I move travel one step further. Hence after the while loop, my linked list becomes {2,4,0} and I have a pointer "travel" pointing to ListNode{0}. However, it cannot be deleted! I have tried both by "delete result->next->next" and "delete travel" but it can still return result->next->next->val, which is 0! (my last cout statement)
WHY?
I declared this new ListNode (which is a struct) in my heap memory. And I want to delete this ListNode out of the while loop. But my delete never works. Maybe the travel was in heap in the brackets, but came out as stack memory after the while loop because I declare the dynamic memory in my loop?

A: use this in the loop to prevent memory leak
<pointer to struct for list2> tmp1 = list2;
list2 = list2->next;
delete tmp1;
<pointer to struct for travel> tmp2 = travel; travel = travel->next;
delete tmp2;

A: I have some questions.

*

*Do you want to remove the whole list of travel or a single node?

*What is the initialize value for travel?

*you are checking the list1, but not using it inside the loop. Give more details about it.

I assume you need to delete the whole list of travel (list1), and travel is iterator of list1.
travel = list1;
while(list1 != NULL)
{
    list1 = list1->next;
    delete travel;
    travel = list1->next;
}


text:
Q: Traditional Computer Vision techniques for analyzing LiDAR data I am currently looking into LiDAR data, and I was wondering are there any Computer Vision only techniques for object recognition/reconstruction for this kind of data? All the methods I have looked into have some form of Machine Learning/Deep Learning involved. I am still a novice so pardon me if my question seems weird.

A: It's true that your question looks very weird. Maybe you're searching for the tradition approach (hand-designed feature, ransac, etc). If it's the case then pcl_tutorials (old but good) or open3d (new and good too) is your friend here. Go there and find the method you need.
To be honest, you need to have a brief knowledge of point cloud data processing first. Before lurking into the above document, I recommend reading the matlab point cloud data processing or better grabbing some book about point cloud data processing.
Good luck


text:
Q: API: SenderProfile Object - What is the DataType "TriggeredSendDefinition"? Documentation Link: https://developer.salesforce.com/docs/atlas.en-us.noversion.mc-apis.meta/mc-apis/senderprofile.htm
If you look at the above documentation link, 'AutoForwardTriggeredSend' and 'AutoReplyTriggeredSend' are both of DataType = "TriggeredSendDefinition". What is this?
For context, I would like to create some Sender Profiles via the SOAP api (utilising WS Proxy) that use custom RMM settings in order to select pre-created triggered sends and populate these fields in the Sender Profile RMM Setup:

*

*Triggered send to forward: _________

*Triggered send to auto reply with: _________

Platform.Load("core","1.1.5");
var api = new Script.Util.WSProxy();
var profile = {
    Name: "test_001",
    CustomerKey: "test_001",
    Description: "test_001",

    FromName: "From_Name",
    FromAddress: "newsletter@test.test.com",

    UseDefaultRMMRulesSpecified: true,
    UseDefaultRMMRules: false,
    DirectForward: false,

    AutoForwardToName: "Test Support",
    AutoForwardToEmailAddress: "support@test.zendesk.com",

    AutoForwardTriggeredSend: ?????,

    AutoReply: true,
    AutoReplyTriggeredSend: ????
}
var request = api.createItem("SenderProfile", profile);
var response =request.Results;
Write(Stringify(request));
</script>


text:
Q: can't output html content to a page from foreach callback in javascript I have a function that loops over each element of the array and outputs the html content to the page while modifying some properties with elements from the array. I'm using forEach to loop over elements of the array and innerHTML to print content to the page.
I keep getting the following error: netdata.html:41 Uncaught TypeError: Cannot set property 'innerHTML' of null. I'm not sure what's causing it as I do have an element with the proper id,

const clusterIPs = [
      { name: "eco-cluster-1", ip: "192.168.50.101" },
      { name: "eco-cluster-2", ip: "192.168.50.102" },
      { name: "eco-cluster-3", ip: "192.168.50.103" },
      { name: "eco-cluster-4", ip: "192.168.50.104" },
      { name: "eco-cluster-6", ip: "192.168.50.105" },
      { name: "eco-cluster-7", ip: "192.168.50.106" },
      { name: "eco-cluster-8", ip: "192.168.50.107" },
      { name: "eco-cluster-9", ip: "192.168.50.108" },
      { name: "eco-cluster-10", ip: "192.168.50.110" },
      { name: "eco-cluster-11", ip: "192.168.50.111" },
      { name: "eco-cluster-12", ip: "192.168.50.112" },
      { name: "eco-cluster-13", ip: "192.168.50.113" }
    ];

    clusterIPs.forEach(pc => {
      console.log(pc);

      //   $("body").html

      document.getElementById("info").innerHTML = `

${pc.name}

        `;
    });
    //   console.log(clusterIPs)

A: You are

*

*Adding HTML before the container exists.

*Replacing HTML each time in the loop instead of appending

To use innerHTML you can do
window.addEventListener("load",function() {
  const container = document.getElementById("info");
  clusterIPs.forEach(pc => container.innerHTML += `....`);
})

Or use jQuery to append since you already load it
$(function() { // on page load
  const $container = $("#info");
  $.each(clusterIPs,(i, pc) => {
    $container.append(`....`);
  });
});

    const clusterIPs = [
      { name: "eco-cluster-1", ip: "192.168.50.101" },
      { name: "eco-cluster-2", ip: "192.168.50.102" },
      { name: "eco-cluster-3", ip: "192.168.50.103" },
      { name: "eco-cluster-4", ip: "192.168.50.104" },
      { name: "eco-cluster-6", ip: "192.168.50.105" },
      { name: "eco-cluster-7", ip: "192.168.50.106" },
      { name: "eco-cluster-8", ip: "192.168.50.107" },
      { name: "eco-cluster-9", ip: "192.168.50.108" },
      { name: "eco-cluster-10", ip: "192.168.50.110" },
      { name: "eco-cluster-11", ip: "192.168.50.111" },
      { name: "eco-cluster-12", ip: "192.168.50.112" },
      { name: "eco-cluster-13", ip: "192.168.50.113" }
    ];

$(function() { // on page load
  const $container = $("#info");
  $.each(clusterIPs,(i, pc) => {
    $container.append(`

${pc.name}

`)
  });
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />

A: The div#info element is not available when the script runs. There are several ways to solve this:

*

*Add the DOMContentLoaded event listener to the document object, then in the callback run the existing script.

*Add the


text:
Q: How to automatically expose all .rs files in a directory in a module? I have module files generated from protobuf definitions. There are a lot of files and they will grow with time. This is the structure:
proto_rust/src/lib.rs
proto_rust/src/protos/{lots of auto generated .rs files}
proto_rust/src/protos/mod.rs

Since there are lots of files in proto_rust/src/protos/, it does not make sense for me to manually put them in mod.rs. Is there a way to expose all them to lib.rs? Something like pub mod *.

A: Use dtolnay's automod crate.

automod::dir!("path/to/directory");

This macro expands to one or more mod items, one for each source file
in the specified directory.
The path is given relative to the directory containing Cargo.toml.


text:
Q: Moving out before brackets with XOR If I had the sum of products like z*a + z*b + z*c + ... + z*y, it would be possible to move the z factor, which is the same, out before brackets: z(a + b + c + ... y).
I'd like to know how it is possible (if it is) to do the same trick if bitwise XOR is used instead of multiplication.
z^a + z^b + ... z^y -> z^(a + b + ... + y)
Perhaps a, b, c ... should be preprocessed, such as logically negated or something else, before adding? z could change, so preprocessing, if it's needed, shouldn't depend on particular z value.

A: To prove that a general formula does not hold you only need to prove a contradiction in a limited case.
We can reduce it to show that this does not hold:
(a^b) * c = (a^c) * (b^c)
It is trivial to show that one base case fails as such:
a = 3
b = 1
c = 1

(a^b) * c = (3^1) * 1 = 2
(a^c) * (b^c) = 2 * 0 = 0

Using the same case you can show that (a*b) ^ c = (a^c) * (b^c) and (a + b) ^ c = (a^c) + (b^c) do not hold either.
Hence, equality does not hold in a general case.
Equality can hold in special cases though, which is an entirely different subject.

A: From Wikipedia:

Distributivity: with no binary function, not even with itself

So, no, unfortunately, you can't do anything like that with XOR.


text:
Q: Kotlin - How to split the string into digits and string? I want to split a long string (containing digits and characters) into different substrings in Kotlin?
eg:- Buy these 2 products and get 100 off
output needed -> "Buy these ","2 ","products and get ","100 ","off"

A: Use a regular expression that will match either a group of digits, or a group of non-digit characters.
I used \d+|\D+.

*

*\d+ will match groups of digits, like 2 and 100

*\D+ will match any sequence of characters that doesn't contain digits

*The | indicates that the pattern should match either \d+ or \D+
Use findAll to find each part of the string that matches the pattern.
val regex = Regex("""\d+|\D+""")
val input = "Buy these 2 products and get 100 off"
val result = regex.findAll(input).map { it.groupValues.first() }.toList()

The result I get is:
["Buy these ", "2", " products and get ", "100", " off"]

The spacing isn't quite the same as what you're looking for, so you could trim the results, or adjust the regex pattern.

A: this code also works well in this example:
val str = "Buy these 2 products and get 100 off"
val result = str.split(regex = Regex("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"))


text:
Q: Are alpha and beta rays also generating electromagnetic rays? To discover radio waves in 1886, Hertz used electric sparks between two iron balls. These sparks caused radio waves which generated a current between other balls.
The oscillating charges caused a electromagnetic wave.
But alpha and beta rays also has charged particles, so do they also generate electromagnetic rays? If so, how do they do that?


text:
Q: How to delete a specific line and replace it in python I have a python game that writes user data like this: Bob 3 on to at text file. I'm trying to code so if a player reaches a certain point it will delete the level number (in the example: 1) and write the new level. I have split the line with this:
name, level = line.split()

Is there any to do this?

A: "updating" a plain file really mean writing a new file then replace the old one with the new one - you cannot just do an "inplace" update. While technically possible and not really difficult it might not be the most efficient solution for your needs, since you'll have to go thru the whole read + parse old file / write the new one / rename for each update (and possibly have to deal with concurrent access too depending on your application). Using some kind of database (key/value, relational, document, whatever...) would probably be a better solution, since it will take care of most of the housekeeping.
For a very naive answer to your question, it would look like this:
def update_level(username, new_level):
   inpath = "/path/to/your/file"
   outpath = "path/to/tmpfile"
   with open(inpath) as infile:
       with open(outpath, "w") as outfile:
           for line in infile:
               line = line.strip()
               name, level = line.split()
               if name == username:
                   line = " ".join((username, new_level))
               outfile.write("%s\n" % line)
   os.rename(outpath, inpath)


text:
Q: Do we specify in FBD whether the force is pull or push?
There are two cases when drawing FBD of a block resting on friction or frictionless surface.We draw at the back of it a force of 20N in the right direction or we draw of force of 20N in the front of the block I.e front side (Not the top side ) in the right direction.Now , I see that in case 1 there is a push force and in case 2 there is a pull force.Is it right to think that.Like we can draw a push force or pull force in either directions.Shouldn't it affect the FBD because in case 1 , The force goes through the body and case 2 , it is just pull.

A: If the objective is to determine the net force acting on the body, then cases 1 and 2 can be considered equivalent.
If the surface is frictionless, then the net force acting on the body is 20 N to the right, regardless of whether it is a push or pull.
If there is friction then the net force acting on the body will be 20 N to the right minus the friction force acting to the left. Again, it doesn't matter if the 20 N applied force is a push or pull.
Hope this helps.

A: In general it doesn't matter which side of the object you draw the arrow on. For example, in the case of your block resting on a surface there is a normal force that the surface exerts on the block. You could draw this arrow underneath the block (pointing into it) or coming out of the top of the block (pointing away from it).
For the case of an applied force it might be better to draw the arrow on the side that the force is being applied on (eg on the left if it is a push and on the right if it is a pull) but this is just a matter of preference.


text:
Q: Make the panels go onto the new line when the resolution changes I have a few panels which work fine but when i resize the browser they don't look quite right, I want something like this:
|1|  |2|  |3|  |4|
|5|  |6|

Then when the browser resizes it should go
|1|  |2|  |3|
|4|  |5|  |6|

But with the current code it's doing this
|1|  |2|  |3|
          |4|

Here is my code:

Driveways

                Blockpaving

                Indian stone

                Shingle

                Concrete

                Crossovers

                Drainage

                Drive Cleaning

Patios

                Slabs

                Indian stone

                York stone

                Brick surrounds

                Drainage

Paths

                Blockpaving

                Slab

                Indian stone

                Concrete

Decking

                Timber

                Composite

                Balustrades

                Steps

                Pergolas

                Shed/Bar Conversions

Here is a screenshot:

A: Add before 3 and 4 block div:

http://getbootstrap.com/css/#grid-responsive-resets


text:
Q: How to implement read and write methods of Chronicle Map SizedWriter and SizedReader interfaces for class with string member I have created a simple class:
public class Example
{
   private String name;
   private int age;
   // With getters and setters.
}

that I would like "put" into a chronicle map:
            ChronicleMap<String,Example> map = ChronicleMapBuilder
                    .of(String.class, Example.class)
                    .name("example-map")
                    .entries(5_000)
                    .averageValue(new Example())
                    .valueMarshaller(ExampleSerializer.getInstance())
                    .averageKey("Horatio")
                    .createPersistedTo(new File("../logs/example.txt"));

However, I do not fully understand how to implement the ExampleSerializer class because I am not sure how the string member variables should be handled. How do I size strings? In the read and write methods, how do I read the string member variable, and how do I write the string member variable respectively. Pls note that on average, the name member string length will be between 7-10 characters. I have created the serializer below:
public class ExampleSerializer implements SizedReader<Example>,SizedWriter<Example>
{
    private static ExampleSerializer INSTANCE = new ExampleSerializer();

    public static ExampleSerializer getInstance() { return INSTANCE; }

    private ExampleSerializer() {}

    @NotNull
    @Override
    public Example read(Bytes in, long size, @Nullable Example using)
    {
        if (using == null)
            using = new Example();

        using.setAge(in.readInt());
        using.setName(in.readUtf8()); // NOT SURE IF THIS IS CORRECT FOR A STRING
        return using;
    }

    @Override
    public long size(@NotNull Example toWrite)
    {
        return Integer.BYTES + ???; // NOT SURE WHAT THE SIZE SHOULD BE FOR STRING MEMBER?
    }

    @Override
    public void write(Bytes out, long size, @NotNull Example toWrite)
    {
        out.writeInt(toWrite.getAge());
        out.writeUtf8(toWrite.getName()); // NOT SURE IF THIS IS CORRECT FOR A STRING
    }
}


text:
Q: How to get result out from xpath using php? Im trying to get the text out xpath/html using php..but not successful any idea.
Example:
https://safeweb.norton.com/report/show?url=google.com
My xpath (This is correct i already double check)
//*[@id="bodyContent"]/div/div/div[3]/div[1]/div[1]/div[2]/div[1]/div/b
I want to get a result to appear here <div> result </div> using php
Below is my code:
<?php
public function getNortonSafe($domain)
{
  try
  {
    $callback_url = "https://safeweb.norton.com/report/show?url=google.com"; //. $domain;

    $curl_response = $this->curl->get($callback_url);

    if ($curl_response->headers['Status-Code'] == "200") {

      libxml_use_internal_errors(TRUE);
      $this->dom_doc->loadHTML($curl_response);
      libxml_use_internal_errors(FALSE);

      $xpath = new DOMXPath($this->dom_doc);
      $tmp = $xpath->query('//*[@id="bodyContent"]/div/div/div[3]/div[1]/div[1]/div[2]/div[1]/div/b')->item(0)->textContent);

      $tmp = explode(' ', trim($tmp));
      $norton_site_test = str_replace(",", "", $tmp[0]);

    } else {
      $norton_site_test = "0";
    }

    $response = array(
      'status' => 'success',
      'data' => array(
        'norton_site_test' => filter_var($norton_site_test, FILTER_SANITIZE_STRING)
      )
    );

  }
  catch (Exception $e)
  {
    $response = array(
      'status' => 'error',
      'msg' => $e->getMessage()
    );
  }
  return $response;
}
?>

HTML
<body>
<p id="norton_site_test">  result-text-here </p>
</body>

A: When executing the $xpath->query('some xpath here')->text(0) line an error occurs: Fatal error: Call to undefined method DOMNodeList::text(). Please check your PHP error reporting settings.
DOMXPath::query method returns DOMNodeList object that has only item method (see DOMNodeList).
You need to call:
$xpath->query('some xpath here')->item(0)->textContent
to get the text content of the first node from the received DOMNodeList object.

A: Just an Update regarding this code, and thank you to @camelsWrite - its working Now! with this clean code and tested:

    public function getNortonSafe($domain)
    {
        try
        {
            $callback_url = "https://safeweb.norton.com/report/show?url= . $domain; //e.g $url: "https://safeweb.norton.com/report/show?url=google.com

            $curl_response = $this->curl->get($callback_url);

            if ($curl_response->headers['Status-Code'] == "200") {

                libxml_use_internal_errors(TRUE);
                $this->dom_doc->loadHTML($curl_response);
                libxml_use_internal_errors(FALSE);

                $xpath = new DOMXPath($this->dom_doc);
                $tmp = $xpath->query('//*[@id="bodyContent"]/div/div/div[3]/div[1]/div[1]/div[2]/div[1]/div/b')->item(0)->textContent);

                $tmp = explode(' ', trim($tmp));
                $norton_site_test = str_replace(",", "", $tmp[0]);

            } else {
                $norton_site_test = "0";
            }

            $response = array(
                'status' => 'success',
                'data' => array(
                    'norton_site_test' => filter_var($norton_site_test)
                )
            );

        }
        catch (Exception $e)
        {
            $response = array(
                'status' => 'error',
                'msg' => $e->getMessage()
            );
        }
        return $response;
    } ?>


text:
Q: I want to retrieve a current user's ID from firebase and write it in another node, but it just keeps denying So basically I made a String mojID which is equal to firebase's current user, I want to pass it as a child in a node but it says it is a null pointer exception and I have already used it in another parts of a code which does not return the fault.
I am attaching some of my code.
final DatabaseReference chatRef1 = FirebaseDatabase.getInstance().getReference("ChatLista");
    chatRef1.child(mojID);
    chatRef1.child(userID);
    chatRef1.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if(!dataSnapshot.exists()){
                chatRef1.child("id").setValue(userID);

            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

    final DatabaseReference chatRef2 = FirebaseDatabase.getInstance().getReference("ChatLista");

                chatRef2.child(userID);
                chatRef2.child(mojID);

            chatRef2.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if(!dataSnapshot.exists()){

                chatRef2.child("id").setValue(mojID);

            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

Then there is function that takes the ID:
private void ProvjeriStatus(){
    FirebaseUser user = firebaseAuth.getCurrentUser();
    if(user!=null){
        //user ulogovan
        mojID = (String)user.getUid();
    }
    //ako nije vraca na login
    else {
       startActivity(new Intent(this,login.class));
       finish();
    }
}

I even tried casting it as you can see it and it just says I don't need a cast, because it is already a String? Then why does it return null? The only explanation I have come up with is that it is an object not a string and by that .child wants a string as a argument not an object.

A: You can add UserId via FirebaseUser.. You can refer Below code .. maybe it will help
    you
 FirebaseUser currentFirebaseUser;
 DatabaseReference databaseReference;

 currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
 databaseReference = FirebaseDatabase.getInstance().getReference();

 databaseReference.child("Users").child(currentFirebaseUser.getUid()).child("User
 Id").setValue(currentFirebaseUser.getUid());

If you want to retrieve UserId from database Refer Below code..
DatabaseReference myRef = database.getReference("Users");

myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if ((dataSnapshot.child(currentFirebaseUser.getUid()).child("UserId").getValue() == null)) {
                databaseReference.child("Users").child(currentFirebaseUser.getUid())
                        .child("UserId").setValue(currentFirebaseUser.getUid());
            } else {
                String Id= (String) dataSnapshot.child(currentFirebaseUser.getUid()).child("UserId").getValue();

            }


text:
Q: how to make google crypto.js cypher output a string? I want to have an offline webpage containing javascript that will encrypt a string with a key and result in another string. Then I want to do the reverse.
This is a simple tool that I would run offline so I would prefer to keep the conversation away from client side encryption.
For now i've chosen google crypto.js as my cypher and for this example I'm using Rabbit
here is my jdfiddle
http://jsfiddle.net/Pz3ab/
which uses jquery and the following external resource
http://code.google.com/p/crypto-js/#Rabbit
Where am I going wrong?

key
<input class="key" type="text">

readout
<input class="readout" type="text">

encrypt

decrypt

var key,readout;
$('.encrypt').on('click', function(){
    if (init()) {
        console.log('-- encrypt clicked --');
        console.log('key = ', key);
        console.log('readout = ', readout);
        var answer = CryptoJS.Rabbit.encrypt(readout, key);
        answer = answer.toString();
        console.log('answer = ',answer);
        $('.readout').val(answer);
    }
});
$('.decrypt').on('click', function(){
    if (init()) {
        console.log('-- decrypt clicked --');
        console.log('key = ', key);
        console.log('readout = ', readout);
        var answer=CryptoJS.Rabbit.decrypt(readout, key);
        answer = answer.toString();
        console.log('answer = ',answer);
        $('.readout').val(answer);
    }
});
function init(){
    key = '' + $('.key').val();
    readout = '' + $('.readout').val();
    console.log('-- init, error check, get key and readout --');
    console.log('key = ', key);
    console.log('readout = ', readout);
    $('.error').empty();
    var success = true;
    if (key=="") {$('.error').append('key is empty
');success=false;}
    if (readout=="") {$('.error').append('readout is empty
');success=false;}
    return success;
}

A: Short answer: answer.toString( CryptoJS.enc.Utf8 );
Long answer: The decrypted otuput you're seeing is the original readout string encoded as hex. The reason it's encoded as hex is because the cipher algorithms have no way to know the original character encoding. Was it Latin1? Utf8? Utf16? Etc. By passing the Utf8 encoder to the toString method, we can tell it to use that character encoding.


text:
Q: Jquery to load dropdown on selected index change of another drop down in sharepoint 2010 I have 2 dropdowns.  On Selected Index change event of ddlTaskFrequency dropdown i want to load another drop down.
For example: If ddlTaskFrequency text= Daily or Weekly i have to load another dropdown
ddlDayofMonth with 1,2,3,4,.....31. If it is of Monthly then ddlDayofMonth with 1,2,3,4..12. I want to achieve this using Jquery.Can any one help me on the same.Below is my jQuery
**Jquery**

    <script language="javascript" type="text/javascript">
        $(document).ready(function () {

            $('#' + '<%=this.Panel2.ClientID  %>').hide();

            $('#' + '<%=this.ddlTaskFrequency.ClientID  %>').change(function () {

                dropdown = $('#' + '<%=this.ddlTaskFrequency.ClientID  %>').val();
                if (dropdown == "Day's(at)")
                {
                    $('#' + '<%=this.Panel1.ClientID  %>').show();
                    $('#' + '<%=this.Panel2.ClientID  %>').hide();
                }
                if (dropdown == "Week's(at)") {
                    $('#' + '<%=this.Panel1.ClientID  %>').show();
                    $('#' + '<%=this.Panel2.ClientID  %>').hide();

                }
                if (dropdown == "Month's(at)")
                {
                    $('#' + '<%=this.Panel1.ClientID  %>').hide();
                    $('#' + '<%=this.Panel2.ClientID  %>').show();
                }
                $('#' + '<%=this.lblNameChange.ClientID  %>').text($('#' + '<%=this.ddlTaskFrequency.ClientID  %>').val());
                return false;
            })
        });

    </script>

**1st dropdown**
    <td>
                <asp:DropDownList ID="ddlTaskFrequency" runat="server" onselectedindexchanged="ddlTaskFrequency_SelectedIndexChanged" AutoPostBack="true">
                    <asp:ListItem Selected="True" Text="Daily" Value="Day's(at)"></asp:ListItem>
                    <asp:ListItem Text="Weekly" Value="Week's(at)"></asp:ListItem>
                    <asp:ListItem Text="Monthly" Value="Month's(at)"></asp:ListItem>
                </asp:DropDownList>
            </td>

**2nd dropdown**

    <asp:DropDownList ID="ddlDayofMonth" runat="server" Height="18px" Width="80px" AutoPostBack="true"></asp:DropDownList>

A: you need to use a event so when you'll change the value on ddlTaskFrequency the other dropdown with the values appear.
You can find thousand of example in the network, like this: http://jsfiddle.net/krustev/xuZn9/

A: I tried Like this But it is not loading the data
  <script language="javascript" type="text/javascript" src="/_layouts/js/jquery-1.10.2.js"></script>
    <script language="javascript" type="text/javascript">
        $.ajax({
            type: "POST",
            url: "/AlertSchedular/TaskAlertSettings.aspx/BindDatatoDropdown",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var Dropdown = $('#<%=ddlDayofMonth.ClientID %>');
                alert(Dropdown);
                Dropdown.append(new Option("SELECT", 0));
                $.each(response.d, function (index, item) {
                    Dropdown.append(new Option(item.dayCount, item.dayId));
                });
            },
            error: function () {
                alert("Failed to load data");
            }
        });

        $(document).ready(function () {

            $('#' + '<%=this.Panel2.ClientID  %>').hide();

            $('#' + '<%=this.ddlTaskFrequency.ClientID  %>').change(function () {

                mydropdown = $('#' + '<%=this.ddlTaskFrequency.ClientID  %>').val();
                if (mydropdown == "Day's(at)") {
                    $('#' + '<%=this.Panel1.ClientID  %>').show();
                    $('#' + '<%=this.Panel2.ClientID  %>').hide();
                }
                if (mydropdown == "Week's(at)") {
                    $('#' + '<%=this.Panel1.ClientID  %>').show();
                    $('#' + '<%=this.Panel2.ClientID  %>').hide();

                }
                if (mydropdown == "Month's(at)") {
                    $('#' + '<%=this.Panel1.ClientID  %>').hide();
                    $('#' + '<%=this.Panel2.ClientID  %>').show();
                }
                $('#' + '<%=this.lblNameChange.ClientID  %>').text($('#' + '<%=this.ddlTaskFrequency.ClientID  %>').val());
                return false;
            })
        });

    </script>

aspx:
public partial class TaskAlertSettings : LayoutsPageBase
    {

        public string dayCount { get; set; }
        public int dayId { get; set; }

 public static DataTable GetTable()
        {

            DataTable table = new DataTable();
            table.Columns.Add("Dayid", typeof(int));
            table.Columns.Add("Days", typeof(string));
            table.Rows.Add(1, "1");
            table.Rows.Add(2, "2");
            table.Rows.Add(3, "3");
            table.Rows.Add(4, "4");
            table.Rows.Add(5, "5");
            table.Rows.Add(6, "6");
            table.Rows.Add(7, "7");
            table.Rows.Add(8, "8");
            table.Rows.Add(9, "9");
            table.Rows.Add(10, "10");
            table.Rows.Add(11, "11");
            table.Rows.Add(12, "12");
            table.Rows.Add(13, "13");
            table.Rows.Add(14, "14");
            table.Rows.Add(15, "15");
            table.Rows.Add(16, "16");
            table.Rows.Add(17, "17");
            table.Rows.Add(18, "18");
            table.Rows.Add(19, "19");
            table.Rows.Add(20, "20");
            table.Rows.Add(21, "21");
            table.Rows.Add(22, "22");
            table.Rows.Add(23, "23");
            table.Rows.Add(24, "24");
            table.Rows.Add(25, "25");
            table.Rows.Add(26, "26");
            table.Rows.Add(27, "27");
            table.Rows.Add(28, "28");
            table.Rows.Add(29, "29");
            table.Rows.Add(30, "30");
            table.Rows.Add(31, "31");
            return table;
        }

        [WebMethod]
        public static TaskAlertSettings[] BindDatatoDropdown()
        {

            DataTable dt = GetTable();
            List<TaskAlertSettings> details = new List<TaskAlertSettings>();
            foreach (DataRow dtrow in dt.Rows)
            {
                TaskAlertSettings myobj = new TaskAlertSettings();
                myobj.dayId = Convert.ToInt32(dtrow["Dayid"].ToString());
                myobj.dayCount = dtrow["Days"].ToString();
                details.Add(myobj);
            }
            return details.ToArray();
        }

A: At last i made very simple going to Ajax methods instead of calling from a webservice method.
Looks like if the return type of the webmethod is partialclass there is a problem.
Simplified my method with this and it started working :-)
 <script language="javascript" type="text/javascript">
       var days = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'];
       var months = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];

       //var dateSelected = $('input[id*="ff_Order_dFAsset_DeliveryDate"]');

        $(function Dailyweekly() {
            var options = '';
            for (var i = 0; i < days.length; i++) {
                options += '<option value="' + days[i] + '">' + days[i] + '</option>';
            }
            var Dropdownvalues = $('#' + '<%=this.ddlDayofMonth.ClientID%>');
            Dropdownvalues.append(options);
        });

        $(function monthly() {
            var options = '';
            for (var i = 0; i < months.length; i++) {
                options += '<option value="' + months[i] + '">' + months[i] + '</option>';
            }
            var Dropdownvalues = $('#' + '<%=this.ddlDayofMonth.ClientID%>');
            Dropdownvalues.append(options);
        });

        $(document).ready(function () {

            $('#' + '<%=this.Panel2.ClientID  %>').hide();

            $('#' + '<%=this.ddlTaskFrequency.ClientID  %>').change(function () {

                mydropdown = $('#' + '<%=this.ddlTaskFrequency.ClientID  %>').val();
                if (mydropdown == "Day's(at)") {
                    $('#' + '<%=this.Panel1.ClientID  %>').show();
                    $('#' + '<%=this.Panel2.ClientID  %>').hide();
                    var Dropdownvalues = $('#' + '<%=this.ddlDayofMonth.ClientID%>').empty();
                    Dailyweekly();
                }
                if (mydropdown == "Week's(at)") {
                    $('#' + '<%=this.Panel1.ClientID  %>').show();
                    $('#' + '<%=this.Panel2.ClientID  %>').hide();
                    var Dropdownvalues = $('#' + '<%=this.ddlDayofMonth.ClientID%>').empty();
                    Dailyweekly();
                }
                if (mydropdown == "Month's(at)") {
                    $('#' + '<%=this.Panel1.ClientID  %>').hide();
                    $('#' + '<%=this.Panel2.ClientID  %>').show();

                    var Dropdownvalues = $('#' + '<%=this.ddlDayofMonth.ClientID%>').empty();
                    monthly();
                }
                $('#' + '<%=this.lblNameChange.ClientID  %>').text($('#' + '<%=this.ddlTaskFrequency.ClientID  %>').val());
                return false;
            })
        });

    </script>


text:
Q: How can I modify a file that is owned by root? I installed a program that runs in a browser. I would like to change the background picture it puts up on the screen or modify the existing one. The properties for that file tell me that it is owned by root.
I am running Ubuntu 12.04 really using Linux for the 1st time.
I am trying to make the switch from Windows and finding it laborious :-)
How can I change that picture file using the GUI? How do I do this with root privileges?

A: Assuming you are the owner of the operating system in question then you can do something relatively simple. Also assuming the current file is owned by root and group of root then in a terminal you can:
sudo chown your_user:root /path/to/file

You may now edit this file using your normal GUI login.
Once you're done, remember to set it back
sudo chown root:root /path/to/file

To find out more about changing ownership of files see:
man chown

Opening a terminal can be as simple as opening the application bar (name?) and typing "terminal". Using sudo you will be asked for your password to grant you elevated privileges for making the change. See:
man sudo

A: Its simple, By default in ubuntu nautilus is the file manager.
So open the file manager with root privileges and change your file
sudo nautilus

A: Whenever you need to edit something as root, you can use sudo. Press Ctrl+Alt+T to open a terminal and then write this command and hit enter:
sudo gedit /path/to/file

Obviously, make sure to change /path/to/file with the actual location of your file. This will open a gedit (a simple text editor) window run by root (the administrator) and will allow you to edit your file.

A: I'm trying to understand which problem (use case) you actually want to solve.
It looks like you do not actually intend to modify your system files, but to change something in your GUI.
If that's right, see below.

Usually, the best way to make personal changes to files that are part of Ubuntu, is to make a copy of it to your personal files, and modify that. If you can read the file owned by root, you can create a copy, which is owned by you.
Some GUI features even do this automatically in some cases.
As a simple example, if you want to make a change to an existing desktop wallpaper image,
you could find the file, copy it, and modify your copy.
Now you can use it as wallpaper image.

(Doing it this way has various advantages, like keeping the original, not creating conflicts when updating the package it belongs to, allowing to do the same for multiple users (and probably more).)


text:
Q: batch requests with credentials using React Apollo

How do you batch requests with credentials? I'm using an http-only JWT cookie and HttpLink allows me to pass a credentials: 'include' option which will forward the cookie through to my graphene server. When I try to switch to BatchHttpLink, it no longer accepts that option for configuration. Looking through the source, it doesn't appear there's an easy way to configure this. Anyone know how to handle this?

Here's how I was doing it without batching:
window['app-react'].GRAPHQL_URL = window['app-react'].GRAPHQL_URL || 'http://backend.app.local/graphiql'
const httpLink = new HttpLink({
  uri: window['app-react'].GRAPHQL_URL,
  credentials: 'include'
})
const client = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache(),
})

Here's how I wish it worked:
const batchHttpLink = new BatchHttpLink({
  uri: window['joor-react'].GRAPHQL_URL,
  credentials: 'include'
})
const client = new ApolloClient({
  link: batchHttpLink,
  cache: new InMemoryCache(),
})

When I do it this way though, the JWT cookie isn't passed in the header.

A: Right now apollo-link-batch-http is behind in its API compared to apollo-link-http. Here is a note from the docs (as of 2017-12-07)

Note: This package will be updated to remove the dependency on apollo-fetch an use the same options / API as the http-link

Using BatchHttpLink with apollo-fetch
The current API of apollo-link-batch-http requires a custom apollo-fetch if you want to make customizations to things like credentials. Here's a couple of options.

*

*Provide a customFetch to createApolloFetch and define credentials in the fetch options.

*Use apollo-fetch middleware
fetch.batchUse(({ options }, next) => {
  options.credentials = 'include';
  next();
});


text:
Q: Single instance of class in Python I am creating a Python application that includes socket communication with a server. I would like to have a module which can be used throughout my entire application (several other modules). Currently my module look like this:
class SocketCommunication:

    def __init__(self):
        self.socketIO = SocketIO(settings.ADDRESS, settings.PORT, Namespace)

    def emit(self, message, data):
        json_data = json.dumps(data.__dict__)
        self.socketIO.emit(message, json_data)

class Namespace(BaseNamespace):
    def on_connect(self):
        print '[Connected]'

    def on_disconnect(self):
        print "[Disconnected]"

When I use this in other modules I do the following:
import SocketCommunication
self.sc = SocketCommunication()

The problem is that every time I do this, a new connection is created which will be displayed as a new client on the server, and that is undesirable.
From what I can read, Singletons should be avoided in Python and therefore I am curious about what is best practice for this type of problem?

A: Singletons are controversial because they're often used as a way to wrap up global variables. This is why some people advocate for their avoidance. Globals make testing harder, they limit access control, and often lead to strong coupling between variables. (see http://wiki.c2.com/?GlobalVariablesAreBad for more details as to why globals are generally bad practice)
In your particular scenario, using a singleton is most likely appropriate because you are simply trying to stop SocketCommunication being initialised multiple times (for good reason), rather than trying to use it as a container for a global state.
See Are Singletons really that bad? and What is so bad about singletons? for some discussion on Singletons.

A: The following are three ways to use singleton in Python.
Using metaclass and decorator to reach the goal.

*

*use __new__
 class Singleton(object):
     def __new__(cls, *args, **kw):
         if not hasattr(cls, '_instance'):
             orig = super(Singleton, cls)
             cls._instance = orig.__new__(cls, *args, **kw)
         return cls._instance

 class MyClass(Singleton):
     a = 1

 one = MyClass()
 two = MyClass()

 two.a = 3
 print one.a
 #3
 print id(one)
 #29097904
 print id(two)
 #29097904
 print one == two
 #True
 print one is two
 #True

*use __metaclass__
class Singleton2(type):
    def __init__(cls, name, bases, dict):
        super(Singleton2, cls).__init__(name, bases, dict)
        cls._instance = None

    def __call__(cls, *args, **kw):
        if cls._instance is None:
            cls._instance = super(Singleton2, cls).__call__(*args, **kw)
        return cls._instance

    class MyClass2(object):
        __metaclass__ = Singleton2

    one = MyClass2()
    two = MyClass2()

    two.a = 3
    print one.a
    #3
    print id(one)
    #31495472
    print id(two)
    #31495472
    print one == two
    #True
    print one is two
    #True

*use decorator
  def singleton(cls, *args, **kw):
     instances = {}
     def _singleton(*args, **kw):
        if cls not in instances:
             instances[cls] = cls(*args, **kw)
        return instances[cls]
     return _singleton

 @singleton
 class MyClass3(object):
     a = 1
     def __init__(self, x=0):
         self.x = x

 one = MyClass3()
 two = MyClass3()

 two.a = 3
 print one.a
 #3
 print id(one)
 #29660784
 print id(two)
 #29660784
 print one == two
 #True
 print one is two
 #True
 one.x = 1
 print one.x
 #1
 print two.x
 #1

I prefer to use decorator.


text:
Q: writing a code for a basic form in react with a submit button in react When I hit submit for the form, alert popup should be displayed, the submit button should be disabled till we close the the popup and then it should be enabled again .
Tried setting the initial state to false and then setting the state in submit function to true , but it is not working as the button gets disabled permanently unless I reload the page.
Not much is written as I don't know how to solve this issue.
I expect the submit button to be disabled till we close the alert popup and then get enabled but the submit button gets disabled permanently.

A: Use Window confirm() Method and setstate on its response. for more detail click here

A: Try this
class App extends React.Component {
    constructor(props) {
        super(props);
        this.click = this.click.bind(this);
        this.state = {
            buttonState: false
        }
    }

    click(event) {
        this.setState({
            buttonState: true
        });
        setTimeout(() => this.setState(
            {buttonState: false}),
            1000
        );
    }

    render() {
        return (
            <div className="button-state">
                <button disabled={this.state.buttonState} onClick={this.click}>Click Me</button>
            </div>
        );
    }
}

export default App;


text:
Q: error TS6044: Compiler option 'types' expects an argument i'm facing with the following error error TS6044: Compiler option 'types' expects an argument. when trying to set "types": [] in tsconfig.json.
We are using grunt-ts
This is recommended by official TS documentation in order to get rid of the following errors: node_modules/@types/angular/index.d.ts(14,9): error TS2403
Here is the link to TS documentation
Specify "types": [] to disable automatic inclusion of @types packages.
But instead of disabling automatic inclusion of @types i see error error TS6044: Compiler option 'types' expects an argument.
Can someone help me?

A: I would recommend using tsconfig.json passthrough with that parameter and grunt-ts.  Several of the new features in the TypeScript 2.x timeframe don't work very well or at all from the command-line.  Alternatively, you could try using the additionalFlags feature of grunt-ts and pass "" as the types value.  I'm not near a computer to test that, but it could work.

A: Finally i've solved my problem specifying jasmine in types
 "types" : ["jasmine"]


text:
Q: JSP - error getting class enum type property I have a problem accesing public enum class properties inside my JSP page. I am able to access all other's invite class properties except invite.status attribute. I am doing something wrong, but i just can't figure why it is wrong and how i can access my returned list's enum values. Thanks for your help solving my issue!
Error what I get The class ...domain.jpa.meeting.Invite' does not have the property status.
This is JPA class that I have
@Entity
public class Invite implements PersistentEntity  {

    @Id @GeneratedValue
    private Long id;

    @ManyToOne
    private User inviter;

    @ManyToOne
    private User invitee;

    @ManyToOne
    private Meeting meeting;

    /**
     * Date when this invite has been created
     */
    private Date created;

//      @Column(nullable=false, length=1)
//  @Enumerated(EnumType.STRING)
    private InviteStatus status;

    public Long getId() {
        return id;
    }

    public User getInviter() {
        return inviter;
    }

    public void setInviter(User inviter) {
        this.inviter = inviter;
    }

    public User getInvitee() {
        return invitee;
    }

    public void setInvitee(User invitee) {
        this.invitee = invitee;
    }

    public Meeting getMeeting() {
        return meeting;
    }

    public void setMeeting(Meeting meeting) {
        this.meeting = meeting;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public InviteStatus getInviteStatus() {
        return status;
    }

    public void setInviteStatus(InviteStatus status) {
        this.status = status;
    }
}

This is enum type public class that i have
/**
 * Values for tracking invite status
 */
public enum InviteStatus {

    // invite is created and invitee have not responded yet
    CREATED,

    // invitee accepted this invite
    ACCEPTED,

    // invitee declined this invite
    DECLINED
}

I am saving in database such way (with success as EnumType.ORDINAL)
// adding invites (table invite)
Invite invite = new Invite();
invite.setInviter(creator);
User invitee = jpaDAO.getById(User.class, Long.parseLong(friends[i]));
invite.setInvitee(invitee);
invite.setInviteStatus(InviteStatus.CREATED); //CREATED = 0, ACCEPTED = 1, ..
Date dateNow = new Date(); //yyyy-MM-dd HH:mm:ss
invite.setCreated(dateNow);
Meeting meeting = jpaDAO.getById(Meeting.class, meetingId);
invite.setMeeting(meeting);
jpaDAO.save(invite);

And i have a method which retrieves invites from database.
@SuppressWarnings({ "unchecked", "null" })
public List<Invite> getUserInvites(Long userId){
// getting invites for current user with status CREATED
Query query = jpaDAO.getEntityManager().createNamedQuery(JPQConst.InviteJpq.QUERY_GET_BY_USER);
query.setParameter("userId", userId);
List<Invite> invites = (List<Invite>) query.getResultList();
return invites;
}

Inside controller it looks like this:
/**
 * Display Notifications tab
 */
@RequestMapping(value = "/home/notifications", method = RequestMethod.GET)
public String displayNotifications(ModelMap model, HttpSession session) {
    User user = getCurrentUser(session);
    List<Invite> invites = notificationService.getUserInvites(user.getId());
    model.addAttribute("invites", invites);
    return "home";
}

Method itself works, and I am able to access all invite's property fields except status property inside jsp.
<c:forEach var="meeting" items="${inviteeMeetings}">
    <c:forEach var="invite" items="${invites}">
        <c:choose>
        <c:when test="${meeting.id == invite.meeting.id}">

                    <c:out value="${meeting.startTime}" />

                    <c:out value="${meeting.title}" />

                    <c:out value="${invite.status}" />
                    <form action="../meeting/attendance" method="post">
                        <input type="hidden" name="venue" value="${meeting.id}" />
                        <input type="submit" name="attendance" value="attend" />
                        <input type="submit" name="attendance" value="reject" />
                    </form>

        </c:when>
        </c:choose>
    </c:forEach>
</c:forEach>

A: Effectively, your class does not have such property. It does have the inviteStatus property.
public InviteStatus getInviteStatus() {
    return status;
}

PROPERTIES ARE BASED IN GETTERS. The name of the internal value that stores the data is not relevant.


text:
Q: Copiar rama a otra git Resulta que he estado trabajando en la rama A mientras otra persona desde otro equipo realizo 2 commits a la misma rama e hizo push, ahora yo desde mi equipo no me deja hacer push con mis cambios sin antes hacer pull y traer esos 2 commits, como puedo deshacerlos o eliminarlos o pasar el contenido mio local a otra rama para finalmente hacer push e intregrar ?

A: Suponiendo que el ancestro común entre tu versión local de la rama A y la suya sea el commit con sha #asdfgh
Si tu colega quiere preservar sus commits de prueba, puede moverlos a otra rama (lo mismo tú para mover los tuyos a una copia de ramaA si quieres seguir ese camino):
 git checkout ramaA
 git checkout -b RamaAModificada

Después puede pushear forzando a que el HEAD del remoto sea el ancestro común
git checkout ramaA
git reset --hard asdfgh
git push -f

Luego de eso, tú puedes traerte ese remoto que volvió a estar limpio y pushear sin inconvenientes:
git checkout ramaA
git fetch origin/ramaA
git push

Podría ser más corto que tú mismo hicieras desde ya
git push -f

Y con eso pisar lo que está en el remoto con lo que tienes en tu local, saliendo así los commits erróneos de la historia. Pero este camino deja abierto un flanco en donde tu colega no podrá trabajar con esa rama mientras siga teniendo los commits sucios.

A: si lo que debes hacer es reintegran tus cambios en la misma rama A eliminando esos dos commits del repositorio remoto, primero partes de tu HEAD local en la rama A con tus commits actuales a una de respaldo:
git checkout -b ramaB

ahora la ramaA debe actualizar en el HEAD de origin, para eso debes devolverte al commit comun de donde parten los commits de la otra persona y los tuyos, si haces un git log, deberia de marcarse donde tienes tu origin actualmente ya que no has hecho pull, supongamos que es "abc123"
git checkout ramaA
git reset --hard abc123

ahora debes limpiar el repo remoto
git push origin ramaA --foce

integrar tus cambios
git merge ramaB

y por ultimo actualizar de nuevo el repo con tus cambios
git push origin ramaA


text:
Q: How to exit a program when user inputs a special character i'm curently doing a simple program that consists of a while-loop that reads in two ints and then prints them out. My question is, how can I exit the program when the user inputs the caracter "|"? Here is this little super simple program:
int main()
{
    int var1 = 0;
    int var2 = 0;

    while(cin>>var1>>var2)
    {
        cout << var1 << " " << var2 << endl;
    }

    return 0;
}

I know that you can define an argument to getline that does exactly what I want to do, but I don't know how to implement this in a while-loop. Thanks for the help.

A: Your loop will already exit as soon as someone enters something istream cannot << into an integer. Anyway to exit specifically at |, I would use the peek function like so:
int main()
{
  int var1 = 0;
  int var2 = 0;
  while( cin.good() )
  {
    char c;
    c = cin.peek();

    if( c == | )
      break;
    else
    {
      cin >> var1 >> var2;
      cout << var1 << " " << var2 << endl;
    }
  }

  return 0;
}

It avoids using c-style input or complex line parsing.

A: All you have to do is to check if the value that was input was | in an if-block and then use the break keyword to stop the loop.
Something in the lines like this:
#include <stdio.h>
int main() {
    char c;
    for(;;) {
        printf( "\nPress any key, Q to quit: " );

        // Convert to character value
        scanf("%c", &c);
        if (c == 'Q')
            break;
    }
 } // Loop exits only when 'Q' is pressed

A: As written, you'll exit the loop if the user enters |.  Or
anything else that cannot be interpreted as an int (after
skipping leading white space).
If you want more precise control, you'll have to read line by
line (and parse the line), or character by character (and build
up the values).


text:
Q: DateTools timeAgoSinceNow. How to limit the number of days? I'm using MatthewYork/DateTools in my project to show date user friendly.
Using it with code:
date.timeAgoSinceNow

For example for 04.05.2017 it will show Yesterday.
For 03.05.2017 - 2 days ago
For 02.05.2017 - 3 days ago
For 27.04.2017 - Weak ago or something like this.
I can't find in the documentation how to limit number of days, when timeAgoSinceNow will work. I want it to work only for 3 last days for example.
Like:
For 04.05.2017 show Yesterday.
For 03.05.2017 - 2 days ago
For 02.05.2017 - 3 days ago
For 27.04.2017 - 27 april.
Looking for standard solution from this framework.


text:
Q: How can I remove the Static Front Page option from the Customizer In Wordpress 4.1's Theme Customizer there's a Static Front Page option.
I've set up my theme to have a custom front page (via front-page.php in the theme) so I don't want this option to be available here.

How can I remove it?

A: This code will do the job.
add_action('customize_register', 'themename_customize_register');
function themename_customize_register($wp_customize) {
  $wp_customize->remove_section( 'static_front_page' );
}

It will remove Static Front Page option.
Details here


text:
Q: Code below for Tabulator filter does not work I am using jquery pluggin called Tabulator and  trying to put a simple text box below all column headers in order to filter data. Seems like it can be done easily looking at the documentation but this just doesn't work for me
Link : http://tabulator.info/examples/4.5?#filter-header
There is no error but I simply do not see the text box where I can start inputting text to filter
 <!DOCTYPE html>

<link href="https://unpkg.com/tabulator-tables@4.5.3/dist/css/tabulator.min.css" rel="stylesheet">

Any suggestions what I could be doing wrong.

A: You are calling a different source

 <!DOCTYPE html>

<link href="https://unpkg.com/tabulator-tables@4.5.3/dist/css/tabulator.min.css" rel="stylesheet">


text:
Q: Bel in PuTTYwhen it is waiting for input? I often have to download, update and build large projects due to which there is a long waiting period between 2 commands. The projects are stored and used on a linux machine, and i connect remotely to it using PuTTY.
Looking for a way to be alerted when a command is done, while i keep working on something else.
I am not expecting below approach, as the command itself may wait for input.
<command> && tput bel

Thanks.

A: PuTTY doesn't know when a remote command is waiting for input. As far as the terminal (or the SSH client) is concerned, input can always be sent. (Even trying to guess based on shown text is futile since many progress displays are indistinguishable to a computer from input prompts.)
Given your requirements, the only option I can think of is a LD_PRELOAD library that prints a bell whenever any program tries to read from a tty device. Something like:
#define _GNU_SOURCE
#include <dlfcn.h>
#include <unistd.h>

ssize_t read(int fd, void *buf, size_t count) {
    static ssize_t (*real_read)(int fd, void *buf, size_t count);

    if (isatty(fd))
        write(fd, "\a", 1);

    if (!real_read)
        real_read = dlsym(RTLD_NEXT, "read");

    return real_read(fd, buf, count);
}

(Well, it doesn't work for any statically-linked binary, but close enough.)
Then again, if a command waits for input, then it is by definition not done, so the requirements are somewhat contradictory.

A: As a 90% solution, you can tell your shell to echo a bell when a command completes. For instance, in bash, simply include \a in your PS1.
If you'd like a bell when the command stops to ask for input, a 99% solution is available in non-Linux Unixen: hit Ctrl-Y after running your command. Lacking support for that, though, try looking for program-specific configurations. For instance, in Vim, you can add norm \ to your .vimrc to echo a bell whenever it is launched.


text:
Q: Basic assembly excercise I cant solve I just started learning Assembly x86 and I have to make an exercise, which I can't solve.
The idea is to make a program in which you ask the user to type in a number using Scanf. Then the program adds 1 to the number and outputs that number (so basically output = input +1).
When I use my code, the console shows me a Segmentation Fault.
The code:
mystring:   .asciz "name_of_the_programmer\nLast_Name\nAssignment 2:inout\nGive a number:\n"    #Creëert een stuk tekst
nrstring:   .asciz "%d"

.global main

main:

    movq        $0, %rax                                #Geeft de locatie %rdi een waarde van 0, maakt %rdi leeg
    movq        $mystring, %rdi                             #Voegt de waarde van mystring (het stuk tekst) toe aan %rdi
    call        printf                                  #Print de waarde van  %rdi
    call        inout                                   #roept inout op

inout:

        pushq %rbp
        movq %rsp , %rbp

        subq $8, %rsp                                   #Plaatst stackPointer goed
        leaq -8(%rbp), %rsi                             #Laad het adres in rsi

        movq $0, %rdi                                   #Maakt rdi leeg
        movq $nrstring, %rdi                                #Verplaatst string nrstring naar rdi    (1e arg. scanf)
        movq $0, %rax                                   #Maakt RAX leeg   (2e arg. scanf)
        call scanf                                  #Roept Scanf op

        incq %rdi
        movq %rdi, %rax
        call printf

        movq %rbp, %rsp
        popq %rbp
        ret

end:
    mov         $0, %rdi                                #Maakt %rdi leeg
    call        exit                                    #Sluit het programma af

I am from holland so please dont worry about the comments and I apologize for my bad english.