text:
Q: Rmarkdown plot and image side by side I'm working on a report in R markdown.
I know there is a way to have different plots side by side, and there is also a way to have different images side by side.
But is it also possible to show a plot and an image side by side?
I have a ggplot bar graph that I would like to present next to an image of a map, it takes up too much space if I put the image below the graph.
Thanks,
Regards,
Freya

A: This could work to you. Here is the step by step, with an indication of the code between parentheses.
First, you need to load the image (y), by creating an object (photo).
Second, you create a ggplot with the image (photo_panel).
Finally, after creating your plot (p1), you use the library cowplot to plot a grid (plot_grid).

.Rmd file:
---
title: "Image + graph"
author: bttomio
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

## R Markdown

```{r image_graph}

y = "http://upload.wikimedia.org/wikipedia/commons/5/5d/AaronEckhart10TIFF.jpg"
download.file(y,'y.jpg', mode = 'wb')

library("jpeg")
photo <- readJPEG("y.jpg",native=TRUE)

library(ggplot2)
library(cowplot)
photo_panel <- ggdraw() + draw_image(photo, scale = 0.8)

df <- data.frame(Years=rep(2016:2017, each=4),
                 Quarters=rep(paste0("Q", 1:4), 2),
                 Series1=seq(100, 800, 100))

library(ggplot2)
p1 <- ggplot(df) +
  geom_point(aes(x=Quarters, y=Series1)) +
  facet_wrap( ~ Years, strip.position="bottom", scales="free_x") +
  theme(panel.spacing=unit(0, "lines"),
        strip.background=element_blank(),
        strip.placement="outside",
        aspect.ratio=1)  # set aspect ratio

plot_grid(p1, photo_panel, ncol = 2)
```

Output:


text:
Q: How can I fill an empty JavaScript array? I've looked all over online for something that could aid me to fill an empty array with given values the user inputs from a text box that will get stored inside an array.
So far I have the following code:
var text = document.getElementById("input").value;
var message = document.getElementById("text-here");
message.innerHTML += text + " " + "
" + "
";
  var x = [];
  x.push(text);

  console.log(x);

When I input something in the textbox and see what happens in the console it tends to replace the previous value that was sent there first.
For example, if I wrote "Hello", this will get sent into the array so it'll be seen as:
["Hello"]

But if I type in something again, hoping that the result will continue to store the data being inputted inside, it does this:
*Writes down "Hi" in the text box:
["Hi"]

I want the result to be something like this:
["Hello", "Hi"]

I am aware my code does need tweaking and I am doing something wrong which is causing that result, but I can't seem to figure it out.
I'm looking for an answer in vanilla JavaScript.
Thank you.

A: The problem is you are redeclaring variable x and initializing it with an empty array, every time when you run that code. Make the x a global variable by moving it out of the current function or block
var x = [];

Another Block
var text = document.getElementById("input").value;
var message = document.getElementById("text-here");
message.innerHTML += text + " " + "
" + "
";
x.push(text);
console.log(x);

A:     var x = [];

    function() {
    var text = document.getElementById("input").value;
    var message = document.getElementById("text-here");
    message.innerHTML += text + " " + "
" + "
";

      x.push(text);

  console.log(x);
}

something like this should fix your problem. You were declaring x as an empty array every time you ran your javascript which would reset it to an empty arry.

redpajama_set_name: RedPajamaStackExchange


text:
Q: HBase data persistence I have been trying to understand how Hbase works. Specifically - how data is stored to disk.
I have read articles online and two of which helped me were -
http://th30z.blogspot.com/2011/02/hbase-io-hfile.html?spref=tw
and
http://www.slashdocs.com/iyxmiz/hfile-a-block-indexed-file-format-to-store-sorted-key-value-pairs.html
I still have some questions, may be because I didn't understand HBase very well. Here's what I get from what I read - Every transaction - (Put/Get/Delete) is saved as KeyValue in the memstore and then written off to StoreFiles/Hfiles on flushing. The data that is stored on the disk is actually these HFiles.
Now, the structure of the KeyValue class specifies - the data that needs to be stored(if any), key and the type of operation (Put/Get/Delete). The data blocks in the HFiles themselves represent the KeyValues (with the "rowkey" being a part of the Key).
As I see it, when these KeyValues are persisted, its more like saving a transaction rather than making changes to existing data. When does a transaction of this kind be processed/consolidated to result in a row. I assumed that it could be during the compaction process but then, I don't know how the requests to the data which is written to a HFile but not compacted are handled.
I also did not understand it when the articles said "Before a KeyValue pair is written to a block, the order of the key must be bigger than the previous one."
I think I have made some wrong assumptions in the process of understanding HBase.
Can someone help me understand this.

A:
"Before a KeyValue pair is written to a block, the order ..."

Yes, new data could be treated as transaction, but they are of the same data format/structure as that after compaction. Which means, these "transaction" co-exists with old data and has no difference with the old data except the timestamp.
When requests comes, hbase will look at both previous data and new data (the "transaction" you mentioned), but new data whose timestamp is newer will be returned.

"Before a KeyValue pair is written to a block, the order of the key must be bigger than the previous one"

I guess the point here is, before block is written to disk, keys are sorted in the memstore (a memory cache) to make sure "the order of the key must be bigger than the previous one".


text:
Q: Reachability network change event not firing My iphone app is pretty simple with one view that handles everything, in viewDidLoad I check to see if we have an internet connection and if we do we load from the web and if not we load from a local resource. And this works fine.
//in viewDidOnload
[[NSNotificationCenter defaultCenter] addObserver:self
                                          selector:@selector(handleNetworkChange:)
                                          name:kReachabilityChangedNotification object:nil];
reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus status = [reachability currentReachabilityStatus];

if (status == NotReachable) {
    //Do something offline
} else {
    //Do sometihng on line
}

- (void)handleNetworkChange:(NSNotification *)notice{
 NetworkStatus status = [reachability currentReachabilityStatus];
 if (status == NotReachable) {
  //Change to offline Message
 } else {
  //Relaunch online application
 }

}

To test my handleNetworkChange event I turned off all cellular data but left the wifi on. Within range of the wifi I started the app and everything works perfect. Then I walk outside of the wifi's range, but my handleNetworkChange never fires (tested using an uiAlertView). Standing outside of the wifi's range my app launches the offline message just fine.
My suspicion is that it is an issue with the ViewController's lifecycle, should this code be placed in the AppDelegate function? Possibly that's a better design to start with.

A: Turns out it was a memory management issue, as I was not retaining the reachability variable, so as soon as it would go out of scope the dealloc would be called and that called the stopNotifier method. Hence no updates as I would walk out of range.
So instead of:
reachability = [Reachability reachabilityForInternetConnection];

I do
reachability = [[Reachability reachabilityForInternetConnection] retain];

and everything works!
One cool thing I learned through all of this is that you can simulate a lost connection in the simulator by simply turning Airport Off. No more having to wander around outside. :)

A: Take a look at the reachability example from Apple. I believe they start their notifications in the AppDelegate. In one of my apps, I created a boolean variable which is constantly updated by the AppDelegate connectivity update method so in my other view controllers, I just need to call the delegate and check the value of the IsConnected bool.
Just to through another thought in here... I have noticed issues with the reachability class in which it can freeze your app when your checking for reachability. In my new apps, I skip the reachability class altogether and rather relay on the DidFail delegate methods for NSUrlConnection and UIWebView to determine if I have true connectivity. I no longer have to wait for the reachability class to figure it out and fail for me to then decide what to do, I simply proceed with the web call and use the local as a fall back.
Hope this helps!!

A: Your application is not running in background.
Please add this method in your delegate Class
- (void)applicationDidEnterBackground:(UIApplication *)application
{ UIApplication* app = [UIApplication sharedApplication];

    UIBackgroundTaskIdentifier __block bgTask = [app beginBackgroundTaskWithExpirationHandler: ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [app endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;
        });
    }];

}

Thanks

A: You should include systemconfiguration.framework in to your project.


text:
Q: Disable Dialog in EditTextPreference, Launch Intent Instead I'm trying to write an app using the Google Drive SDK.  I'd like to use a Preference object in a PreferenceActivity that allows the user to select the Google account that they want to upload files to.  I've been trying to use an EditTextPreference to launch the account picker intent.  It works.  However, after selecting the account, the EditText dialog appears.  Is it possible to disable the dialog?  Or am I going about this the wrong way?
preferences.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
  <PreferenceCategory
    android:title="@string/title_upload_category">
    <EditTextPreference
      android:title="@string/title_upload_acct"
      android:key="@string/key_upload_acct"/>
  </PreferenceCategory>
</PreferenceScreen>

PrefsFragment
public static class PrefsFragment extends PreferenceFragment{

@Override
public void onCreate(Bundle savedinstancestate) {
  GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(getActivity().getApplicationContext(), Arrays.asList(DriveScopes.DRIVE));
  EditTextPreference acctValue = (EditTextPreference)findPreference(getString(R.string.key_upload_acct));
  acctValue.setOnPreferenceClickListener(new OnPreferenceClickListener(){

    @Override
    public boolean onPreferenceClick(Preference preference) {
        startActivityForResult(credential.newChooseAccountIntent(), 1);
        return false;
    }
  });
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && data != null){
      String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
      acctValue.setSummary(accountName);
      acctValue.setText(accountName);
    }
}

A: You are doing everything correct except you should use a Preference instead of an EditTextPreference. Then the dialog won't show up, and the functionality of the preference is handled by you when you set the onPreferenceClickListener.


text:
Q: Formula to calculate the sum of timecodes - AppleScript After extensive research on the Internet I could't find a decent formula to calculate (add) timecodes, so I'm building my own script from scratch.
So far I can get a pretty decent result, however I'm having trouble to account for Drop-Frame timelines. According from what I learned, they jump from frame 29 to 02, unless its the 10th (or multiples) minute, in which case the 00 and 01 frames will be there.
Any advice on how to implement this feature?
Also any improvement to the script will be welcome.

global tcSTART
global tcDURATION
global tcFINAL
global frameRATE

on run
    set frameRATE to "23.98" -- test frame rate
    set tcSTART to "04:03:02:01" -- test Value 1
    set tcDURATION to "01:02:03:04" -- teste Value 2

    my calcFinalTC()
    display dialog tcFINAL
end run

on calcFinalTC()
    set FF to (word 4 of tcSTART) + (word 4 of tcDURATION)
    set SS to (word 3 of tcSTART) + (word 3 of tcDURATION)
    set MM to (word 2 of tcSTART) + (word 2 of tcDURATION)
    set HH to (word 1 of tcSTART) + (word 1 of tcDURATION)
    if FF ≥ frameRATE then
        set FF to (FF - (round (frameRATE)))
        set SS to (SS + 1)
    end if
    if SS ≥ 60 then
        set SS to (SS - 60)
        set MM to (MM + 1)
    end if
    if MM ≥ 60 then
        set MM to (MM - 60)
        set HH to (HH + 1)
    end if
    if HH > 23 then
        display dialog "The timeline can't be larger than 24 hours" buttons {"OK"}
        error -128
    end if
    if the length of ((FF div 1) as string) = 1 then
        set FF to "0" & FF
    end if
    if the length of ((SS div 1) as string) = 1 then
        set SS to "0" & SS
    end if
    if the length of ((MM div 1) as string) = 1 then
        set MM to "0" & MM
    end if
    if the length of ((HH div 1) as string) = 1 then
        set HH to "0" & HH
    end if
    set tcFINAL to HH & ":" & MM & ":" & SS & ":" & FF
end calcFinalTC


text:
Q: Add field to observableArray after it has been loaded from API using KnockoutJS I have an observablearray called documents which I load with JSON from the result of an API call. I then use document to load up the currently selected document. Code is as follows:
self.documents = ko.observableArray();

self.document = {
    DocID: ko.observable(),
    DocName: ko.observable(),
    isDocumentEdit: ko.observable(false)
}

function populateDocumentLocations() {
    ajaxHelper(url + '/api/Documents/' + self.businessList.busID().busID, 'GET').done(function (data) {
        self.documents(data);
    });
}

function ajaxHelper(uri, method, data) {
    return $.ajax({
        type: method,
        url: uri,
        dataType: 'json',
        contentType: 'application/json',
        data: data ? JSON.stringify(data) : null
    }).fail(function (jqXHR, textStatus, errorThrown) {
        alert(errorThrown);
    });
}

The two properties that the API returns are DocID and DocName. This all works fine. I added a third field to document (as above), "isDocumentEdit" so I know if the user has clicked the "edit" button or not (to change the GUI accordingly).
However, the value of isDocumentEdit remains as "undefined" rather than false.
I've also tried looping through "documents" and adding "isDocumentEdit = false" for each element but that didn't work.
Is it possible to add another parameter to an observable after it has been loaded? Or is there a way to load it when it makes the API call (this is where I tried to loop through and add in but didn't work)?

A: When the data comes back from the ajax call it needs to be mapped to your model that contains the observables.
First declare the Document viewModel:
function Document (document) {
    var self = this;

    self.DocID = ko.observable(document.DocID);
    self.DocName = ko.observable(document.DocName);
    self.isDocumentEdit = ko.observable(false);
}

Then you can use the jQuery $.map function to map the json response to your documents:
function populateDocumentLocations() {
    ajaxHelper(url + '/api/Documents/' + self.businessList.busID().busID, 'GET').done(function (data) {
        var mappedDocuments = $.map(data, function(document) { return new Document(document) });
        self.documents(mappedDocuments);
    });
}

This is also in the Knockout tutorial which is a good reference: http://learn.knockoutjs.com/#/?tutorial=loadingsaving


text:
Q: POST запрос express Почему на сервер не приходит объект запроса?
Запрос:
fetch('/api/teacher/createTest', {
        method: 'post',
        body: JSON.stringify(this.state)
    })
        .then(() => {
            console.log('create test', JSON.stringify(this.state));
    });

Сгенерированный запрос вроде выглядит нормально:
create test {"id":1497705421652,"forGroups":[],"name":"","subscribers":[],"questionsCount":0,"questions":[]}

Обработчик на сервере:
app.post('/api/teacher/createTest', (req, res) => {
    console.log(req.body);
});

Вот что он выводит(консоль сервера):

body-parser подключен:
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

Где тут моя ошибка?


text:
Q: How does property length work? When i loop in a list with several items and use property length does the length property get only the longest word or does it get length of all items?
function onS() {
var maxLength = 0;
var longestListTitle = "";
var Enum = list.getEnumerator();
while (Enum.moveNext()) {
    var currentItem = Enum.get_current();
    var listTitle = currentItem.get_title();
    if (listTitle.length > maxLength) {
        longestListTitle = listTitle;
        maxLength = longestListTitle.length;
    }
}

A: length works differently on String or Array.
On a string, length is the total length of the string with all caracters. "test test".length will give you 9.
On a array, it can be more tricky. [].length is obvioulsy 0. ['test'].length is 1. But you can do this :
var test = [];
test[0] = 1;
test[10] = 2;
console.log(test.length); // output 11

For an array, length is the maximum index used + 1.

A: If its an array it will give you the length of the array (total elements in array). If its a string, it gives you the length of the string (total characters in the string.)


text:
Q: Custom events in android I have a working android app. In this app I have an activity which displays transactions from SqlServer in a ListView, I've used ListViewAdapter (extends BaseAdapter) and net.sourceforge.jtds.jdbc.Driver to display these Transactions, now I have added a Button to each row in the ListView and I want to delete the transaction from the server whenever user taps on the Button. I don't know where to start.
TransactionActivity.java
public class TransactionActivity extends AppCompatActivity implements   OnClickListener {

private EditText tranDate;
private DatePickerDialog dtpDialog;
private SimpleDateFormat dateFormat;
private ListView lvTransactions;
private Button btnAddNewTransaction;
private TransactionsListViewAdapter adapter;
private ArrayList<HashMap<String, String>> transactionsList;
private Date selectedDate;
private SqlDatabaseHelper sqldb = new SqlDatabaseHelper(this);
private DecimalFormat df = new DecimalFormat("#.00");

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_transaction);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);

    tranDate = (EditText) findViewById(R.id.tranDate);
    tranDate.setInputType(InputType.TYPE_NULL);
    tranDate.requestFocus();

    setDateTimeField();

    lvTransactions = (ListView) findViewById(R.id.lvTransactions);
    transactionsList = new ArrayList<HashMap<String, String>>();

    tranDate.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            refreshTransactions();
        }
    });
}

private void refreshTransactions() {
    transactionsList.clear();
    HashMap<String, String> headerRow = new HashMap<String, String>();
    headerRow.put(FIRST_COLUMN, "Party");
    headerRow.put(SECOND_COLUMN, "Type");
    headerRow.put(THIRD_COLUMN, "Amount");
    headerRow.put(FOURTH_COLUMN, "Status");
    transactionsList.add(headerRow);
    List<Transaction> tranList = sqldb.getTransactionsByDate(selectedDate);
    for (Transaction t : tranList) {
        HashMap<String, String> tranRow = new HashMap<String, String>();
        tranRow.put(FIRST_COLUMN, t.get_party().getName());
        String tTypeStr;
        int tType = t.get_transactionType();
        switch (tType) {
            case 0:
                tTypeStr = "आया";
                break;
            case 1:
                tTypeStr = "दिया";
                break;
            case 2:
                tTypeStr = "जमा";
                break;
            case 3:
                tTypeStr = "नामे";
                break;
            default:
                tTypeStr = "";
        }
        int tStat = t.get_transactionStatus();
        String tStatStr = "";
        switch (tStat) {
            case 0:
                tStatStr = "Fresh";
                break;
            case 1:
                tStatStr = "Synced";
                break;
            case 2:
                tStatStr = "Deleted";
                break;
        }
        tranRow.put(SECOND_COLUMN, tTypeStr);
        tranRow.put(THIRD_COLUMN, df.format(t.get_amount()));
        tranRow.put(FOURTH_COLUMN, tStatStr);
        transactionsList.add(tranRow);
    }
    adapter = new TransactionsListViewAdapter(this, transactionsList);
    lvTransactions.setAdapter(adapter);
    lvTransactions.invalidateViews();
}

private void setDateTimeField() {
    tranDate.setOnClickListener(this);

    Calendar calendar = Calendar.getInstance();
    dtpDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            Calendar newDate = Calendar.getInstance();
            newDate.set(year, monthOfYear, dayOfMonth);
            selectedDate = newDate.getTime();
            tranDate.setText(dateFormat.format(newDate.getTime()));
        }
    }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
}

@Override
public void onClick(View view) {
    if (view == tranDate) {
        dtpDialog.show();
    }
}

}
TransactionListViewAdapter.java
public class TransactionsListViewAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> list;
Activity activity;
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
TextView txtFourth;
Button btnDeleteTran;

public TransactionsListViewAdapter(Activity activity, ArrayList<HashMap<String, String>> list) {
    super();
    this.activity = activity;
    this.list = list;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return list.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return list.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

    LayoutInflater inflater = activity.getLayoutInflater();
    View view = null;
    convertView = null;
    if (convertView == null) {

        convertView = inflater.inflate(R.layout.transaction_list_layout, null);

        txtFirst = (TextView) convertView.findViewById(R.id.txtTranParty);
        txtSecond = (TextView) convertView.findViewById(R.id.txtTranType);
        txtThird = (TextView) convertView.findViewById(R.id.txtTranAmount);
        txtFourth = (TextView) convertView.findViewById(R.id.txtTranStatus);
        btnDeleteTran = (Button) convertView.findViewById(R.id.btnTranDelete);

        convertView.setTag(R.id.txtTranParty, txtFirst);
        convertView.setTag(R.id.txtTranType, txtSecond);
        convertView.setTag(R.id.txtTranAmount, txtThird);
        convertView.setTag(R.id.txtTranStatus, txtFourth);
        convertView.setTag(R.id.btnTranDelete, btnDeleteTran);

    }/* else {
        txtFirst = (TextView) convertView.getTag(R.id.Party);
        txtSecond = (TextView) convertView.getTag(R.id.Opponent1);
        txtThird = (TextView) convertView.getTag(R.id.Opponent2);
        txtFourth = (TextView) convertView.getTag(R.id.Draw);
    }*/

    HashMap<String, String> map = list.get(position);
    txtFirst.setText(map.get(FIRST_COLUMN));
    txtSecond.setText(map.get(SECOND_COLUMN));
    txtThird.setText(map.get(THIRD_COLUMN));
    txtFourth.setText(map.get(FOURTH_COLUMN));

    if (txtFirst.getText().equals("Party")) {
        btnDeleteTran.setVisibility(View.INVISIBLE);
    }

    btnDeleteTran.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
    return convertView;
}

}

A: In your Adapter just add an onclick listener for the button and place the code to delete the entry inside the listener. It may look like:
yourButton.setOnClickListener(new OnClickListener(){
      public void onClick(View v){
         //deletion code here
      }
)};

where yourButton is the button to be clicked.
You should add this code in the getView method of the adapter


text:
Q: what is extjs data store in root parameter I don't have clear idea about extjs 'root' parameter in data store.
  var xxx  = new Ext.data.JsonStore
  ({
     autoLoad: true,
     url: 'www.dataserver.com',
     root: 'data',
     idProperty: 'ID',
     fields: ['ID', 'Name']
  });

i feel this very small thing but i'm very new to extjs please explain to me what is use for this root above data tore

A: It's a config of the JsonReader.
The JsonStore accepts all configs of JsonReader.
In the root config you give the name of the property that'll contain the array of row objects.
In your case it'll be :
{
    data: [
        {ID: 1, Name: "some name"},
        {ID: 2, Name: "another name"}
    ]
}

A: Readers are used to interpret data to be loaded into a Model instance or a Store - often in response to an AJAX request. In general there is usually no need to create a Reader instance directly, since a Reader is almost always used together with a Proxy, and is configured using the Proxy's reader configuration property
Ext.create('Ext.data.Store', {
    model: 'User',
    proxy: {
        type: 'ajax',
        url : 'users.json',
        reader: {
            type: 'json',
            root: 'users'
        }
    },
});

The above reader is configured to consume a JSON string that looks something like this:
{
    "success": true,
    "users": [
        { "name": "User 1" },
        { "name": "User 2" }
    ]
}

See in the above json structure, we have two attribute(with key:value pair) as "success" amd "users. The "users" key has array of object, which we are going to use in store. so in this json we are going to use the "users" attribute for our reader, so only we mention "users" as root for that store.
As recap, root is the config which will tell which part of attribute/object im going to use for my store in consume json.
Thanks


text:
Q: java program to divide an image file into 4 parts I want to divide an image file into 4 parts using java i tried it but i am getting exceptions and also i want to store all the pixel values of image into an array. for this i used pixel grabber class but of no use.please help me

A: Have you tried this?

A: javax.imageio.ImageIO.read() returns a BufferedImage. I think that should be useful.


text:
Q: When did HUP stop getting sent and what can I do about it? Back in the day when I was young and Unix was the new thing, creating a process that did not get killed when you logged out was a challenge. We used the nohup command to protect our persistent processes from the HUP signal. If we weren't careful, our processes would get killed when we logged off, or even closed the shell we started them from.
Fast forward to today and I find I am surprised that the default appears to be exactly the opposite. On both Ubuntu and Red Hat systems I find that I can put nearly any process in the background, kill the parent shell, log off, anything and it just keeps going. I see the same behavior with Bash scripts, Python scripts and C programs. I get the same behavior from xterm or ssh sessions.
For example in an xterm or ssh window, type:
while [ 1 ]; do date; sleep 10; done > /tmp/out &

Now from another window run
tail -f /tmp/out

Watch it print the date every 10 seconds, then close the original parent shell with Ctrl-D. Still running. Log out and back in. Still running.
Send it a HUP signal, it instantly dies.
I can exhibit the same behavior with a Python script or a C program. Sleep or not doesn't matter. For example, this ugly C program behaves the same:
#include <stdio.h>

void main() {
    while(1) {
        printf("*\n");
        fflush(stdout);
        int i, j, k = 0;
        for(i=0; i < 10000; i++) {
            for(j=0; j < 100000; j++) {
                k += i * j;
            }
        }
    }
}

This is completely counter to the ways of my youth. I guess I just didn't notice when it changed? Any historians out there know when this happened? Does HUP even get used for this purpose any more?
If indeed this is the current state of things, my question is: How can I arrange for a process to die when the user logs off or gets disconnected?
I've got a hack that involves watching for the ppid (parent pid) to change but surely there is something more elegant than that.

A: I believe you're looking for the huponexit shell option. You can set this easily with
$ shopt -s huponexit

Some details from the bash man page:

The  shell  exits  by  default upon receipt of a SIGHUP.  Before
  exiting, an interactive shell resends the SIGHUP to all jobs, running
  or
         stopped.  Stopped jobs are sent SIGCONT to ensure that they receive the SIGHUP.  To prevent the shell from sending the signal to
  a  par-
         ticular job, it should be removed from the jobs table with the disown builtin (see SHELL BUILTIN COMMANDS below) or marked to not
  receive
         SIGHUP using disown -h.
If the huponexit shell option has been set with shopt, bash sends a SIGHUP to all jobs when an interactive login shell exits.

A: I still get a SIGHUP. A simple way to test:
#!/usr/bin/env sh

echo "$$"
trap "echo HUPPED $$ > /tmp/willithup" HUP
sleep 1000

Then close the terminal emulator. Now back to your question:

Watch it print the date every 10 seconds, then close the original
  parent shell with Ctrl-D. Still running. Log out and back in. Still
  running.

The process doesn't get a HUP when its parent dies. It gets a HUP when it loses the connection to the controlling terminal or when it is explicitly sent a HUP. This happens for example when you logout of SSH.

If we weren't careful, our processes would get killed when we logged
  off, or even closed the shell we started them from

For the second one: the shell itself can send a HUP to all its children when it exits. However, bash for example has huponexit set to false by default. This may well be what has changed. Note that regardless of the huponexit option, when it receives a HUP the shell also sends a HUP to all its children.

In the words of Stevens:

A session can have a single controlling terminal. This is usually the
  terminal device (in the case of a terminal login) or pseudo terminal
  device (in the case of a network login) on which we log in.
If a modem (or network) disconnect is detected by the terminal
  interface the hang-up signal is sent to the controlling process (the
  session leader).

To further clarify, the initial HUP is not sent by the shell. It is sent by the terminal driver. Afterwards the shell "forwards" it to the children. So indeed, a HUP sent by the terminal driver can "cascade". From TLPI:

When a controlling process loses its terminal connection, the kernel
  sends it a SIGHUP signal to inform it of this fact. (A SIGCONT signal
  is also sent, to ensure that the process is restarted in case it had
  been previously stopped by a signal.) Typically, this may occur in two
  circumstances:

*

*When a "disconnect" is detected by the terminal driver, indicating a    loss of signal on a modem or terminal line.

*When a terminal window is closed on a workstation. This occurs because the last open file descriptor for the master side of the pseudoterminal associated with the terminal window is closed.


text:
Q: How is the this pointer captured? Consider the following code:
struct S
{
  int x;
  void f()
  {
    auto l = [&](){ x = 42; }; //this is implicitly captured here
  }
};

§5.1.2/14 states:

An entity is captured by copy if it is implicitly captured and the capture-default is = or if it is explicitly captured with a capture that does not include an &.

Hence I conclude, that this is not captured by copy. But then by §5.1.2/15:

An entity is captured by reference if it is implicitly or explicitly captured but not captured by copy. It is unspecified whether additional unnamed non-static data members are declared in the closure type for entities captured by reference.

this is captured by reference. But now §5.1.2/17 states:

[...] If this is captured, each odr-use of this is transformed into an access to the corresponding unnamed data member of the closure type, [...]

As far as I understand, this implies that there must be an unnamed data member in the closure type corresponding to the this pointer. But since this is captured by reference the standard doesn't demand that such a member exists. What do I get wrong?

A: The standard does a poor job of making it clear, but this can only be captured by copy. It could not possibly be captured by lvalue-reference since this is an rvalue per C++11 §9.3.2/1.
Note that the standard forbids explicitly capturing this by reference since (a) the grammar does not allow &this in a capture list since this is lexically a keyword and not an identifier, and (b) 5.1.2/8 forbids explicit capture of this when the capture-default is =.
It would seem to be an error in the specification that this can be implicitly captured when the capture-default is &, suggesting that it is captured by reference.

A: I think you've found a specification bug - you're correct in that this is being captured by reference, but the text you found in §5.1.2/17 should only apply if this is captured by copy.
As Casey says though, it doesn't really make much sense to capture this by reference.

A: Of course such a data member exists in the closure type.  Capture by value and capture by reference both require a data member in the closure type.  The only question is its type:
T /* maybe const and/or volatile */ * captured_this;

vs
T /* maybe const and/or volatile */ * const & captured_this;

Since this can't ever change, there is no observable difference between the two.


text:
Q: tab activity not supported in android 2.1 in android application? I am developing an android application in which i have to implement a full url in android device.I have made the application in android 3.2.Now acc to client requirement he wants the same code to be runned in android 2.1. But its crashing when i try to run the same code in android 2.1 updated 1. I have done r & d and done all the formulas suggested,i have changed the sdk version in the manifest file.Added configuration code in java file,,but still crashing.Is dere any way in which the same app can run on android 2.1 updated 1 .What i think is 2.1 updated 1 does not support tab bars.......if anyone has faced the same issue,,can he guide me
Thanks in advance
Tushar

A: Follow the bellow link
https://github.com/johannilsson/android-actionbar
It provides the Sample ActionBar(TabBar) which will run on lower versions also.
By using this code into your project only little bit modifications are enough. good luck...


text:
Q: How could I calculate this limit without using L'Hopital's Rule $\lim_{x\rightarrow0} \frac{e^x-1}{\sin(2x)}$? I want to calculate the limit which is above without using L'hopital's rule ;
$$\lim_{x\rightarrow0} \frac{e^x-1}{\sin(2x)}$$

A: Equivalents: $\;\mathrm e^x-1\sim_0 x$, $\;\sin 2x\sim_0 2x$, so $\;\dfrac{\mathrm e^x-1}{\sin 2x}\sim_0\dfrac{x}{2x}=\dfrac12.$

A: Using the fact that $$\lim _{ x\rightarrow 0 }{ \frac { { e }^{ x }-1 }{ x } =1 } \\ \lim _{ x\rightarrow 0 }{ \frac { \sin { x }  }{ x } =1 } $$ we can conclude that $$\\ \lim _{ x\rightarrow 0 }{ \frac { { e }^{ x }-1 }{ \sin { 2x }  }  } =\frac { 1 }{ 2 } \lim _{ x\rightarrow 0 }{ \frac { { e }^{ x }-1 }{ x } \frac { 2x }{ \sin { 2x }  }  } =\frac { 1 }{ 2 } $$

A: As an alternative and admittedly more mechanical approach, you can series expand top and bottom:
$$\lim _{ x\rightarrow 0 }{ \frac { { e }^{ x }-1 }{ \sin2x }} =\lim _{ x\rightarrow 0 }\frac{1+x+O(x^2)-1}{2x+O(x^3)}=\frac12$$
This will work for most fractions if the variable is tending to $0$. In fact, l'Hopital's rule essentially comes from series expanding $\frac{f(x)}{g(x)}$, so in a sense we are doing the same thing.


text:
Q: Office shared-disk error "We are connecting to \\server, please wait" When browsing a fileserver direclty from Office applications as Excel/Word, it takes a long time to connect to the shared-disk, so opening/saving files are a problem (see screenshot).
error loading "We are connecting to \server\share, please wait."
I have trouble to resolve this. This does not happens if we browse the server apart from Office applications (Windows Explorer, notepad,...). Office is updated(2206). It happens to all computers on the network.
Fileserver is Windows Server 2016 and everything is on LAN.

A: Refer to this article:
https://docs.microsoft.com/en-us/office/troubleshoot/performance/office-slow-or-stop-responding
Try the method: add the EnableShellDataCaching value to the Microsoft Windows registry. To do this, follow these steps:

*

*Close your Office programs.

*Click Start, and then click Run.

*In the Open box, type regedit, and then click OK.

*Locate, and then click to select one of the following registry keys accordingly:

Microsoft 365 Apps, Office LTSC 2021, Office 2019 and Office 2016:
HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Common\Open Find
Office 2013:
HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Common\Open Find
Office 2010:
HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Common\Open Find
Office 2007:
HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Common\Open Find
Office 2003:
HKEY_CURRENT_USER\Software\Microsoft\Office\11.0\Common\Open Find

*After you select the key that is specified in step 4, point to New on the Edit menu, and then click DWORD Value.

*Type EnableShellDataCaching, and then press ENTER.

*Right-click EnableShellDataCaching, and then click Modify

*In the Value data box, type 1, and then click OK.


text:
Q: Configuring quartz failover with spring I have a problem in implementing failover with the configuration in the subject. I have a spring batch job configured in a quartz (2.1.7) cluster. In configuration file, I have set requestsRecovery = true, and my quartz configuration file is this:
org.quartz.scheduler.instanceId=AUTO
org.quartz.scheduler.instanceName = quartzScheduler
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 10
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true

org.quartz.jobStore.useProperties=true
org.quartz.jobStore.isClustered = true

org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX

org.quartz.jobStore.tablePrefix = QRPC_

org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.scheduler.jmx.export=true
org.quartz.jobStore.clusterCheckinInterval = 20000

My spring configuration is as follows:
<context:component-scan base-package="it.myproject.scheduler" />

<bean name="myJob" class="it.myproject.scheduler.CustomJobDetailFactoryBean">
    <property name="jobClass" value="it.myproject.scheduler.SellJob" />
    <property name="requestsRecovery" value="true" />
    <property name="durability" value="true"/>
</bean>

<bean id="cronTrigger" class="it.myproject.scheduler.CustomCronTriggerFactoryBean">
    <property name="jobDetail" ref="myJob"/>
    <property name="cronExpression" value="${sched.expression}"/>
</bean>

<bean id="quartzScheduler"
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="jobDetails">
        <list>
            <ref bean="myJob" />
        </list>
    </property>
    <property name="triggers">
        <list>
            <ref bean="cronTrigger" />
        </list>
    </property>
    <property name="dataSource" ref="myDataSource" />
    <property name="transactionManager" ref="transactionManager" />
    <property name="schedulerName" value="quartzScheduler"/>
    <property name="configLocation" value="file:///quartz.properties" />
    <property name="applicationContextSchedulerContextKey" value="applicationContext" />
    <property name="overwriteExistingJobs" value="true"/>
    <property name="autoStartup" value="true" />
    <property name="jobFactory">
        <bean class="it.myproject.scheduler.AutowiringSpringBeanJobFactory"/>
    </property>
</bean>

Job code:
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailAwareTrigger;

public class CustomCronTriggerFactoryBean extends CronTriggerFactoryBean {

    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
        // Remove the JobDetail element
        getJobDataMap().remove(JobDetailAwareTrigger.JOB_DETAIL_KEY);
    }
}

public class CustomJobDetailFactoryBean extends JobDetailFactoryBean {
    private boolean requestsRecovery;

    public CustomJobDetailFactoryBean() {
        super();
    }

    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
        JobDetailImpl jobDetail = (JobDetailImpl) getObject();
        jobDetail.setRequestsRecovery(isRequestsRecovery());
    }

    public boolean isRequestsRecovery() {
        return requestsRecovery;
    }

    public void setRequestsRecovery(boolean requestsRecovery) {
        this.requestsRecovery = requestsRecovery;
    }
}

public class myJob extends QuartzJobBean {
    @Autowired
    private MyScheduler task;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        task.runJob();
    }
}

I have deployed my application in 2 separate machines on tomcat. Concurrency works fine, when I start the servers only 1 instance acquire the lock and works, but if I stop the machine that has acquired the lock, the second machine does not failover. The same result is observed if I use only one server, stopping this and restarting does not failover.
In the table job detail the column requests_recovery is set to 1. Can anyone help me please?

A: I have the same problem. What I am doing is, wiping out the tables when the instance starts. Especially, the tables that have auto-generated Instance ID. But there must be other solution for this.


text:
Q: Salesforce REST Api Chatter user Request "The requested resource does not exist" I am trying to get a list of users through the chatter user API (services/data/v54.0/chatter/users). I am getting the correct result on one salesforce account. But on the other salesforce account, I am getting this error:
 {
    "errorCode": "NOT_FOUND",
    "message": "The requested resource does not exist"
  }

That is the only API I found in the documentation of salesforce to get a list of all users. Can anybody tell me ? what am I doing wrong here? Thanks


text:
Q: Override Button_click event handler I am developing a WinForms application using the MVP pattern. I would like to pass the button clicked tag value to the presenter. Because I want to get the button.Tag property I need the sender argument to be of type Button. How can I do this with out doing this:
private void button0_Click(object sender, EventArgs e)
{
    if (sender is Button)
    {
        presenter.CheckLeadingZero(sender as Button);
    }
}

I am having to downcast the object to a button in the method parameter.

A: There is no point in checking the type using the is keyword if you're just going to use the as keyword, because as does an is check followed by an explicit cast anyway. Instead, you should do something like this:
Button button = sender as Button;
if (button != null)
{
  presenter.CheckLeadingZero(button);
}


text:
Q: How do you read in a text (.txt) file as a .py file in Python 2.7? I have a shared folder that contains a text file that I want my program to reference as though it were a .py file. For example, my .txt file has a dictionary in it that I reference in my program. How do i import the dictionary from a text file? Do i read it in line by line? Or is there a way to trick python into thinking it is a .py file.
Here is a sample similar to my .txt file:
#There are some comments here and there

#lists of lists
equipment = [['equip1','hw','1122','3344'],['equip2','hp','1133','7777'],['equip3','ht','3333','2745']]

#dictionaries
carts = {'001':'Rev23', '002':'Rev11','003':'Rev7'}

#regular lists
stations = ("1", "2", "3", "4", "11", "Other")

A: Looks like what you need is a JSON file.
Example: consider you have a source.txt with the following contents:
{"hello": "world"}

Then, in your python script, you can load the JSON data structure into the python dictionary by using json.load():
import json

with open('source.txt', 'rb') as f:
    print json.load(f)

prints:
{u'hello': u'world'}

You can also use exec(), but I don't really recommend it. Here's an example just for educational purposes:
source.txt:
d = {"hello": "world"}

your script:
with open('test.txt', 'rb') as f:
    exec(f)
    print d

prints:
{'hello': 'world'}

Hope that helps.

A: If you completely trust the source .txt file, check out execfile.


text:
Q: MySQL Update with PHP not working how i wanted it to Hi this is my first post so please excuse any errors
Background if this helps
i've created several pages for a website
submit form - puts data in to database - all working ok
summary page - pulls through elements of database - all working ok
edit page - this is where my problem is
my problem
when creating a edit page it does not pull through the updated variable from the form and just updates the database with a empty field
so here is the code
edit.php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$var_value = $_GET['id'];

$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form action="/update.php" method="post">
<label>Property Title
<input type="text" name="title" value="<?php echo $row[title]?>" />
<form method='get' action='update.php'>
<input type='hidden' name='id' value= "<?php echo $row[id]?>" >
<input type='submit' class='button radius' value='update' >

</form>

</label>

so that should display whats currently in the database then when a user changes it they click update and it should up date in the database
here is the update.php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$title =$_POST['title'];
$var_value = $_GET['id'];

$result = $conn->query($sql);

$sql = "UPDATE aparthousesalerent SET title='$title' WHERE id  = '$var_value' ";

echo $var_value;
echo $title;

if ($conn->query($sql) === TRUE) {

} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

i added in the extra line of echo $var_value and echo $title; to check if that worked and it did but it still doesn't pass it through to the database
thanks for looking

A: <form action="/update.php" method="post">
<label>Property Title
<input type="text" name="title" value="<?php echo $row[title]?>" />
<form method='get' action='update.php'>
<input type='hidden' name='id' value= "<?php echo $row[id]?>" >
<input type='submit' class='button radius' value='update' >

</form>

as you can see there are nested form
So, remove the form and make method post because you are using $_POST in php file.
<form action="/update.php" method="post">
<label>Property Title
<input type="text" name="title" value="<?php echo $row[title]?>" />
<input type='hidden' name='id' value= "<?php echo $row[id]?>" >
<input type='submit' class='button radius' value='update' >

</form>

and use one either GET or POST
$title =$_POST['title'];
$var_value = $_POST['id'];


text:
Q: Don't understand Django REST Framework KeyError I'm working through the Django REST Framework v.2 tutorial and am getting an error I don't understand.  The tutorial covers creating a simple pastebin code highlighting Web API.  You start by creating the following models and loading it with a few snippets:
# models.py
class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES,
                                default='python',
                                max_length=100)
    style = models.CharField(choices=STYLE_CHOICES,
                             default='friendly',
                             max_length=100)

    class Meta:
        ordering = ('created',)

# Python console
snippet = Snippet(code='foo = "bar"\n')
snippet.save()

snippet = Snippet(code='print "hello, world"\n')
snippet.save()

You then create a serializer class that serializes and de-serializes snippet instances into JSON:
# serializers.py
class SnippetSerializer(serializers.Serializer):
    pk = serializers.Field()  # Note: `Field` is an untyped read-only field.
    title = serializers.CharField(required=False,
                                  max_length=100)
    code = serializers.CharField(widget=widgets.Textarea,
                                 max_length=100000)
    linenos = serializers.BooleanField(required=False)
    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
                                       default='python')
    style = serializers.ChoiceField(choices=STYLE_CHOICES,
                                    default='friendly')

    def restore_object(self, attrs, instance=None):
        """
        Create or update a new snippet instance, given a dictionary
        of deserialized field values.

        Note that if we don't define this method, then deserializing
        data will simply return a dictionary of items.
        """
        if instance:
            # Update existing instance
            instance.title = attrs.get('title', instance.title)
            instance.code = attrs.get('code', instance.code)
            instance.linenos = attrs.get('linenos', instance.linenos)
            instance.language = attrs.get('language', instance.language)
            instance.style = attrs.get('style', instance.style)
            return instance

        # Create new instance
        return Snippet(**attrs)

You also create two CBVs (I won't include them here, the code can be seen at the link above) that contains 'snippet_list' and 'snippet_detail' views that are called via these urlconfs:
# urls.py
urlpatterns = [
    url(r'^snippets/$', views.snippet_list),
    url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),
]

If you then execute these two curl commands, you get a list of snippets or details for a particular snippet:
curl http://127.0.0.1:8000/snippets/
curl http://127.0.0.1:8000/snippets/2/

These commands work just fine.  But the tutorial then goes on to replace the snippet class shown above with a simple ModelSerializer class:
# serializers.py
class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')

However, when I make this replacement and restart my server, I get this error:
KeyError at /snippets/
'id'
Request Method: GET
Request URL:  http://127.0.0.1:8000/snippets/
Django Version: 1.8.4
Exception Type: KeyError
Exception Value:
'id'
Exception Location: /Users/smith/.virtualenvs/django184/lib/python2.7/site-packages/rest_framework/serializers.py in get_fields, line 257
Python Executable:  /Users/smith/.virtualenvs/django184/bin/python
Python Version: 2.7.13

Request Method: GET
Request URL: http://127.0.0.1:8000/snippets/

Django Version: 1.8.4
Python Version: 2.7.13
# ... Application and Middleware stuff

Traceback:
File "/Users/smith/.virtualenvs/django184/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/smith/.virtualenvs/django184/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)
File "/Users/smith/code/django/drf2/snippets/views.py" in snippet_list
  29.         return JSONResponse(serializer.data)
File "/Users/smith/.virtualenvs/django184/lib/python2.7/site-packages/rest_framework/serializers.py" in data
  581.                 self._data = [self.to_native(item) for item in obj]
File "/Users/smith/.virtualenvs/django184/lib/python2.7/site-packages/rest_framework/serializers.py" in to_native
  357.         for field_name, field in self.fields.items():
File "/Users/smith/.virtualenvs/django184/lib/python2.7/site-packages/django/utils/functional.py" in __get__
  60.         res = instance.__dict__[self.name] = self.func(instance)
File "/Users/smith/.virtualenvs/django184/lib/python2.7/site-packages/rest_framework/serializers.py" in fields
  224.         return self.get_fields()
File "/Users/smith/.virtualenvs/django184/lib/python2.7/site-packages/rest_framework/serializers.py" in get_fields
  257.                 new[key] = ret[key]

Exception Type: KeyError at /snippets/
Exception Value: 'id'

Just to make sure I hadn't created a typo, I cut and pasted all the code from the tutorial into my Django files.  I also did an Internet search to see if anyone was having this problem.  In addition, I looked that the tutorial for version 3 of the framework and the module author uses this same ModelSerializer technique in version three.  Have I done something wrong?  Is there an error in the tutorial?


text:
Q: Reassign a field in child classes (clean code) Below, you will find a code snippet I have written for a program simulating a bank account.
I am wondering whether there is a cleaner way to design the inheritance for the friendlyName field?
Ideally, I would have stored it as a const, but it prevents from reasigning its value in child classes.
Thanks a lot!
public abstract class Account
{
   protected string friendlyName;
   public string ShowBalance()
   {
      var message = new StringBuilder();
      message.Append($"Your {friendlyName} balance is {Balance}");
             .Append("See you soon!");
      return message.ToString();
   }
}

public class SavingsAccount : Account
{
    public SavingsAccount()
    {
       friendlyName = "savings account";
    }
}

public class CurrentAccount : Account
{
   public CurrentAccount()
   {
      friendlyName = "current account";
   }
}

A: You cannot make it const as it would need to be initialized when it is declared. You could make it readonly and set it in the children constructors and this gets as close to const as you can with values that aren't compile-time constants.
public abstract class Account
{
   protected readonly string friendlyName;
   // the rest is the same
}

A: You can make it an abstract property. Inheriting, non-abstract classes then must override it
public abstract class Account
{
   protected abstract string FriendlyName { get; }

   ...
}

public class SavingsAccount : Account
{
    protected override string FriendlyName => "savings account";
}

public class CurrentAccount : Account
{
    protected override string FriendlyName => "current account";
}


text:
Q: Nature of force between two permanent magnets When we put two permanent magnets close to each other they repel or attract each other and this process increase their kinetic energy. I know that magnetic force can't increase kinetic energy so plz explain which type of force is this.

A:
I know that magnetic force can't increase kinetic energy so plz explain which type of force is this.

Assuming you meant potential energy when you said, "kinetic energy."
If two magnets are oriented so that they repel each other, then you increase the potential energy of that system when you push them closer together. Conversely, if they are oriented so that they attract each other, then once again, it is you who increases the potential energy of the system when you pull them apart.

A:
When we put two permanent magnets close to each other they repel or
attract each other and this process increase their kinetic energy

If you have two magnets with like poles (north or south) facing each other you have to do work against the repulsive force to push them closer together. That work increases the potential energy between the magnets. If you then let the magnets go, they will fly apart due to work done by the magnetic field, gaining kinetic energy.
Likewise, if you have two magnets with opposite poles facing each other you have to do work to pull them apart against the attraction forces. If you then let the magnets go, they will fly towards each other due to the work done by the magnetic field, gaining kinetic energy.
The second example is equivalent to lifting an object off the ground and then releasing it. The work you do in lifting the object increasing the potential energy between the object and the earth is converted to kinetic energy when released due to the work done by gravity.

I know that magnetic force can't increase kinetic energy so plz
explain which type of force is this.

The magnetic force can give the magnets kinetic energy as described above. The key point is the kinetic energy of the magnets equals the energy you supplied doing work to push them together or pull them apart (ignoring energy dissipative effects like friction and air resistance) increasing their potential energy.
As a final comment, the ability of the magnets to store potential energy will degrade over time. The magnetic field of a magnetic was created by causing the atoms of the iron to line up when placed in a strong magnetic field. But over time, at any temperature above absolute zero, the atoms will move around and randomize their positions causing the magnet field to slowly weaken. The process can be sped up by heating or dropping the magnet.
Hope this helps.

A: "I know that magnetic force can't increase kinetic energy"
That statement applies to the magnetic force on a charged particle.
The magnetic forces on magnetic moments, which are lined up in a magnet, do produce kinetic energy, which will push the magnets apart or attract them.


text:
Q: como hago que en este diagrama el dato "duration" me aparesca a 2 meses

A: El primer ítem Definir el Tema lo tienes a dos meses: 0 es enero y 2 es marzo... Simplemente dale un plazo de dos meses de diferencia al ítem que lo requiera, por ejemplo, en Elegir Metodología pones new Date(2018, 3, 20), new Date(2018, 5, 20), null, 90, 'Tema'],


text:
Q: Confusion about reputation activity? When I review my reputation activity, I can see where I have downvoted posts & lost reputation. When I display the details asssociated the number matches the loss initially displayed

I noticed for one post I had a loss of 2 reputation but when I clicked to view the details it showed a gain of 2 reputation for an edit I had made.

How should I interpret this and/or how did this occur?

A: Try checking the "show removed posts" checkbox on the bottom of your reputation page (Credits: Donald Duck).
Also, removed posts are hidden by default. If there are posts removed the same day it could explain a net result for that day of -2 (Credits: Donald Peat).


text:
Q: ¿Cuál es la diferencia entre acc y val_acc en model.fit()? Intento crear un red neuronal con una capa de memoria larga a corto plazo para clasificar los comentarios tóxicos para la competencia Kaggle. Utilizo model.fit() para entrenar mi modelo, pero hay cosas que aparecen en la pantalla que no entiendo:

Por ejemplo, ¿cuáles son las diferencias entre acc y val_acc?
Me fui a visitar la página oficial sobre model.fit() pero no me dice nada al respecto.

A: La diferencia:

*

*acc es la precisión calculada en el conjunto de entrenamiento (datos que el modelo ha podido ver con anterioridad).

*val_acc es la precisión calculada en el conjunto de validación (es decir, sobre datos que el modelo "nunca ha visto").
Si lo que quieres es estimar la habilidad de tu modelo para generalizar a partir de nuevos datos, entonces tienes que fijarte en la precisión de validación (val_acc) porque el conjunto de validación contiene datos que el modelo nunca ha visto durante el entrenamiento y por lo tanto no los ha podido memorizar.
Si la precisión en los datos de entrenamiento (acc) mejora continuamente, mientras la precisión en los datos de validación (val_acc) empeora, entonces seguramente estás sobreajustando (overfitting), es decir, tu modelo estaría empezando a memorizar los datos.

Fuentes (en inglés):

*

*How to tell which Keras model is better?

*What's the difference between acc and val_acc


text:
Q: Replacing only pronoun, noun, verb and adjective in a sentence with its corresponding tags, how could I do it efficiently in Python? I have sentences and I want to replace only its Pronoun, nouns and adjective with its corresponding POS Tags.
For example my sentence is :

"I am going to the most beautiful city, Islamabad"

and want the result

"PRP am VBG to the most JJ NN, NNP".

A: TL;DR
>>> from nltk import pos_tag, word_tokenize
>>> sent = "I am going to the most beautiful city, Islamabad"
>>> [pos if any(p for p in wanted_tags if pos.startswith(p)) else word for word, pos in pos_tag(word_tokenize(sent))]
['PRP', 'VBP', 'VBG', 'to', 'the', 'RBS', 'JJ', 'NN', ',', 'NNP']

>>> from nltk.corpus import stopwords
>>> stoplist = stopwords.words('english')
>>> [pos if any(p for p in wanted_tags if pos.startswith(p)) and word not in stoplist  else word for word, pos in pos_tag(word_tokenize(sent))]
['PRP', 'am', 'VBG', 'to', 'the', 'most', 'JJ', 'NN', ',', 'NNP']


text:
Q: Spring '19 changes to Lightning communities CSP and visualforce pages Before Spring '19 we were relying on a Visualforce page included in an iframe inside a Lightning community to load static HTML content. That worked without any issue. It still does when the community is viewed in its published form.
But when we try to do the same thing inside the community builder preview mode, or even within the preview in new tab, we get CSP errors blocking content loading because of the difference in domains from the builder preview and the community.
For example, my published community URL is : (it's a scratch org)
https://sandbox-nosoftware-platform-8735-dev-168e27667a4.cs64.force.com/s/
But while viewing the community preview from the builder it is:
https://nosoftware-platform-8735-dev-ed.preview.salesforce-communities.com/s/
Notice the different domains? This causes the url of the visualforce page to be blocked by the default community CSP settings because the visualforce page is served from the first URL inside the second URL.
Am I doing anything wrong or are the CSP rules a bit too strict to be blocking your own Salesforce domain?


text:
Q: Does CSS transition work with positioned elements? This time, I'll include the code (as I've been asked previously).
The problem is that, even when this code does what I need (a CSS modal/lightbox window), I can't get it to animate neither the top nor the translate properties.
I think it's a problem of positioning, because, the original example used no position for the container but, instead, used the :before pseudo-element (I don't like it).
What's wrong with this code.
<!DOCTYPE html>

    <meta charset="iso-8859-1" />
    <title>Pure CSS Modal Window</title>

    Modal 1
    Modal 2

This is the content of Modal 1

This is the content of Modal 1

This is the content of Modal 1

This is the content of Modal 1

This is the content of Modal 1

This is the content of Modal 1

This is the content of Modal 1

This is the content of Modal 1

This is the content of Modal 1

            Close

This is the content of Modal 2

            Close

A: This is because the display state changes from display: none to display: block, meaning there is no previous layout to transition between.
One option would be to replace display: none with visibility: hidden and display: block with visibility: visible.
Working Example:

*
    {
    margin: 0px;
    padding: 0px;
    }
.modal-container
    {
    position: fixed;
    visibility: hidden;
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    background-color: rgba(0, 0, 0, 0.75);
    }
.modal-content
    {
    position: absolute;
    top: -100%;
    left: 50%;
    width: 70%;
    max-width: 400px;
    max-height: 400px;
    transform: translateX(-50%);
    background-color: #fff;
    padding: 20px;
    border-radius: 10px;
    overflow-y: auto;
    transition: all 5s;
    }
.modal-container:target
    {
    visibility: visible;
    }
.modal-container:target .modal-content
    {
    top: 50%;
    transform: translate(-50%, -50%);
    }
Modal 1
Modal 2

This is the content of Modal 1

This is the content of Modal 1

This is the content of Modal 1

This is the content of Modal 1

This is the content of Modal 1

This is the content of Modal 1

This is the content of Modal 1

This is the content of Modal 1

This is the content of Modal 1

        Close

This is the content of Modal 2

        Close

A: The solution provided by Alexander O'Mara works great (& also taught me a little), but I found another answer.
I solved it just separating both DIV's. I mean, instead of:

Content here

I used:

Content here

And for the CSS I used:
.container:target + .content {}

instead of
.container:target .content {}

All this without changing "display: none" for "visibility: hidden", as Alexander suggested, & it worked perfectly.
Thanks for your help. It's great to see that people around the world worries about other one's problems & try to solve them.
Cheers.
Marcelo.


text:
Q: How can I convert a step-down range to array? I have a range like (1000..0) and I was using each but it does not do anything. I was trying to convert it to an array and got an empty array.
I also tried (1000..0).step(-1).each and it tells me step cant be negative...
Is there any way to use (1000..0).each so it will do the repetition, or convert to an array like [1000,999,998,...,0]?

A: 1000.downto(0).each { |i| ... }

A: (0..1000).to_a.reverse
This will create the required array.

A: Two ways you might go about doing this:
(0..1000).each do |i|
  n = 1000 - i
  # Use n for all calculations
end

(0..1000).to_a.reverse.each do |n|
  # Involves creating temporary array, but overhead is usually minor for
  # relatively small numbers.
end

Don't forget you can also do this without a range:
1001.times do |i|
  n = 1000 - i
end

A: #1000 item array
step_down_array = 1000.step(0, -1).to_a

#small enumerator:
step_down = 1000.step(0, -1)


text:
Q: how do i navigate between multiple screens and i get the following error(undefined is not an object(this.props.navigation)) i'm new to react-native and mobile application. I'm trying to build a basic shopping app.i have the sports options such as cricket,football,tennis and whenever the tennis button is pressed, the tennis products will be displayed and there is a buy option which when clicked will lead to the payment page but i"m not able to navigate between my second screen to third screen and i get the following error
(undefined is not an object(this.props.navigation))
i tried using props for the overall function but it doesnt work
1.app.js
import React, { Component } from 'react';
import { Text,  View } from 'react-native';

import { createStackNavigator, createAppContainer } from 'react-
navigation'
import FirstScreen from './src/FirstScreen'
import SecondScreen from './src/cricket'
import ThirdScreen from './src/football'
import FourthScreen from './src/tennis'
import FifthScreen from './src/paymentdetails'

 const Navigation = createAppContainer(createStackNavigator({
 First: {screen: FirstScreen},
 Second: {screen: SecondScreen},
 Third: {screen: ThirdScreen},
 Fourth: {screen: FourthScreen},
 Fifth: {screen: FifthScreen}

 }));

 export default Navigation

2.FirstScreen.js
 import React, { Component } from 'react';
 import { Alert, AppRegistry, Image, Platform, StyleSheet, Text,
 TouchableHighlight, TouchableOpacity, TouchableNativeFeedback,
 TouchableWithoutFeedback, View } from 'react-native';
 import { StackNavigator } from 'react-navigation'
 export default class FirstScreen extends Component {
 //_onPressButton() {
 // Alert.alert('You tapped the button!')
 //}
constructor(props){
super(props)
this._onPressButton1.bind(this)
this._onPressButton2.bind(this)
this._onPressButton3.bind(this)
}

_onPressButton1=()=>{
this.props.navigation.navigate("Second")
}
_onPressButton2=()=>{
this.props.navigation.navigate("Third")
}
_onPressButton3=()=>{
this.props.navigation.navigate("Fourth")
}

static navigationOptions = {
  title: 'First Screen',
};

render() {
return (
  <View style={styles.container}>
     <TouchableOpacity onPress={this._onPressButton1}>

     <View style={styles.button}>
        <Text style={styles.buttonText}>Cricket</Text>
        <Image
        //We are showing the Image from online
        source={{
          uri:
            'http://www.pngmart.com/files/6/Cricket-Transparent-
 Background.png',
        }}
        //You can also show the image from you project directory like
 below
        //source={require('./Images/facebook.png')}
        //Image Style
        style={styles.ImageIconStyle}
      />
      </View>
    </TouchableOpacity>
    <TouchableOpacity onPress={this._onPressButton2}>

     <View style={styles.button}>
        <Text style={styles.buttonText}>Football</Text>
        <Image
        //We are showing the Image from online
        source={{
          uri:
            'http://pngimg.com/uploads/football/football_PNG52793.png',
        }}
        //You can also show the image from you project directory like
 below
        //source={require('./Images/facebook.png')}
        //Image Style
        style={styles.ImageIconStyle}
      />
      </View>
    </TouchableOpacity>
    <TouchableOpacity onPress={this._onPressButton3}>

     <View style={styles.button}>
        <Text style={styles.buttonText}>Tennis</Text>
        <Image
        //We are showing the Image from online
        source={{
          uri:
            'http://pngimg.com/uploads/tennis/tennis_PNG10421.png',
        }}
         //You can also show the image from you project directory like
   below
        //source={require('./Images/facebook.png')}
        //Image Style
        style={styles.ImageIconStyle}
      />
      </View>
    </TouchableOpacity>
  </View>
    );
   }
    }

3.tennis.js
class Greeting extends Component {

  constructor(props){
  super(props)
  this._onPressButton.bind(this)
   }

 _onPressButton=()=>{
   this.props.navigation.navigate("Fifth")
  }

  static navigationOptions = {
   title: 'Fourth Screen',
  };

  render() {
  return (
  <View style={styles.rowContainer}>
    <Text style={styles.text}>{this.props.name}</Text>
    <View style={styles.buttonContainer}>
      <Button
        onPress={this._onPressButton}
        title="BUY"
      />
    </View>
  </View>
  );

  }
  }

  export default class FourthScreen extends Component {

  render() {
  return (
  <ScrollView>
  <View style={{alignItems: 'flex-start', top: 0, flex: 2,
  backgroundColor: 'black'}}>

    <Greeting name='Shoe- 800' />
    <Greeting name='Jersey - 350' />
    <Greeting name='Stockings - 100' />
    <Greeting name='Cones - 50' />
    <Greeting name='Whistle - 80' />
    <Greeting name='Rackets - 7000' />
    <Greeting name='Tennis Ball-6 pack - 800' />
    <Greeting name='Nets - 1500' />

  </View>
  </ScrollView>
  );
  }
  }

4.paymentdetails.js
export default class FifthScreen extends Component {

static navigationOptions = {
    title: 'Fifth Screen',
};

_onPressButton() {
Alert.alert('You tapped the button!')
}

render() {
return (

    <View style={styles.container}>
    <View style={styles.alternativeLayout }>
    <Text>Payment Gateway</Text>
    </View>
    <RadioForm
      radio_props={hobbies}
      initial={1}
      onPress={(value) => {ToastAndroid.show(value.toString(),
ToastAndroid.SHORT)}}
      buttonSize={20}
      buttonOuterSize={40}
      selectedButtonColor={'green'}
      selectedLabelColor={'green'}
      labelStyle={{ fontSize: 15, }}
      disabled={false}
      formHorizontal={false}
    />
     <View style={styles.alternativeLayoutButtonContainer}>
     <Button
        onPress={this._onPressButton}
        title="Proceed"
      />
      <Button
        onPress={this._onPressButton}
        title="Go Back"
        color="#841584"
      />
    </View>
  </View>
  );
  }
  }

i would like the buy option in tennis to navigate to the payment page

A: The problem is that in case of react navigation you need to pass navigation to all those component which are not mentioned in you Stacknavigator
Firstly pass this.props.navigation to your components
Then use this.props.navigation.navigate("Fifth")
This should definitely work.
For more information you can go through the following link.
https://reactnavigation.org/docs/en/navigating.html

A: You missed props. Navigation object is passed to component as a props. So in tennis.js _onPressButton do this instead:
_onPressButton() {
   this.props.navigation.navigate("Fifth")
  }

A: In tennis.js declare constructor(Props) to the Default class otherwise it won't the component wont get props object


text:
Q: Deploy Angular 7 project with Apache server with subfolder Deploy Angular 7 project with Apache server in subfolder
Angular CLI: 7.3.1
Node: 11.1.0
OS: darwin x64
Angular: 7.2.4
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.13.1
@angular-devkit/build-angular     0.13.1
@angular-devkit/build-optimizer   0.13.1
@angular-devkit/build-webpack     0.13.1
@angular-devkit/core              7.3.1
@angular-devkit/schematics        7.3.1
@angular/cli                      7.3.1
@ngtools/webpack                  7.3.1
@schematics/angular               7.3.1
@schematics/update                0.13.1
rxjs                              6.3.3
typescript                        3.2.4
webpack                           4.29.0

Index.html:
<!doctype html>

  <meta charset="utf-8">
  <title>Flightslogic</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

App.routing:-
const routes: Routes = [
  { path: 'home', component: HomeComponent, pathMatch: 'full' },
  { path: '',  redirectTo: 'home', pathMatch: 'full' },
  { path: 'about-us', component: AboutUsComponent,  },
  { path: 'contact-us', component: ContactUsComponent,  },
  { path: 'products/fare-app', component: ProductFareAppComponent,  },
  { path: 'developer', component: ResourceDeveloperProgramComponent,  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes), ],
  exports: [RouterModule]
})

Home page nav:

    Home
      (current)

    About

I want to deploy to apache server with subdirectory. How can I achieve that.
For ex: http://www.example.com and the subdirectory is subdir. So I want to deploy to http://www.example.com/subdir. How can I achieve it.

A: Finally I have solved this. By rewriting the .htaccess file
Rewrite .htaccess file as
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /subdir/
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . index.html [L]
</IfModule>

ng build --base-href=/subdir/ --deploy-url=/subdir/ --prod


text:
Q: FB.login popup no longer working on Safari mac? Anyone else no longer getting popups in Safari?
Here's some sample code that does not work in Safari. It is launched by a click on link so the popup blocker shouldn't block it. Any ideas why it does?
Online example here:
http://users.telenet.be/prullen/fbtest.html
Note that this will not run through the expected behavior since it's on another domain and has an incorrect app ID. But the only thing that matters for this example is the showing of the popup.

Connect With FaceBook

A: Can you check your settings regarding blocking pop-up window?
This issue: Facebook Login not open in Safari/ iPhone the same as you have, I guess.


text:
Q: How to make rails work with vue.js? Well my question is simple, how to make a Ruby on Rails app work with Vue.js?
The details
I first look at the vue-rails gem, but that add Vue to the rails asset pipeline, and I want to work with other npm packages, like browserify. Then I look to that, browserify-rails that enable commonjs in the js folder app/assets/javascript/. Also I'm planning to make a Vuejs app for every rails controller, and access to backend actions with the vue-resource and vue-router (if this isn't a good approach please let me know), so I added the following line to my layout
<%= javascript_include_tag params[:controller] %>

That will add a js file with the name of the controller, so the UsersController will have the users.js file with the main vue app for that controller.
Then, to try this I scaffolded a Users resource with rails, and make it render json format in every action, like this
def index
    @users = User.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @users }
    end
end

That is working fine. Then in the app/assets/javascript/ folder I add users.js with the following content
var Vue = require('vue');
Vue.use(require('vue-resource'));

new Vue({
    ready: function(){
        this.$http.get('users.json').then(function(response){
            console.log(JSON.stringify(response));
        });
    }
});

And when I inspect dev console in chrome, I see that Vue is added, but I don't see any response, and I had already inserted one user. By the way, I'm trying with the https://vuejs-rails-yerkopalma.c9users.io/users url (I'm developing in c9.io) and only the /users/index.html.erb file is rendered. So, waht are my guesses:

*

*I might be using vue-resource in a wrong way, I mean the url passed to the get() function.

*I might be missing some vue-resource configuration.

*Maybe I just should use the vue-rails gem combined with brwoserify-rails but I just don't know how. Any help or guideline would be appreciate.

Here is my application.js file (is also included in my layout file)
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets

A: I managed to make this work with Vue.js.
first I added an el propertie to the object passed to Vue constructor, and I started to get an error saying that body element was not defined. Obviously the body element is always present in an html file, so I though it was a problem about when the Vue instances were created. So I simply wrapped all on a ready event.
$(document).on('ready page:change', function() {
    var Vue = require('vue');

    Vue.use(require('vue-resource'));

    new Vue({
        el: 'body',
        data: {
            users: []
        },
        ready: function(){
            this.$http.get('users.json').then(function(response){

                console.log(JSON.stringify(response.data));
                this.users = response.data;
            }, function(response){
                console.log("fail");
                console.log(JSON.stringify(response));
            });
        }
    });
});

And that works fine!
Because I'm using turbolinks, I also included the page:change event. And in my view index.html.erb I have access to Vue instance. So this make this case working and it's fine for this particular question, however I now have another issue working with .vue components, maybe I'll open another question about it.
Notice that in my index.html.erb view I have access to the Vue instance defined in users.js file in the assets/javascript/ folder, but that I have not access to Vue or any of the js modules loaded with browserify from the views folder

A: Try using the Breakfast Gem. There is an installation section for Vue.js
Basically once you install the gem you can use npm to install Vue, Vuex and the Vue Router quite easily.
And it supports single file Vue components.

A: For Rails 5.1+, it will come with yarn & webpack support.
Also, with this pull request to webpacker, Vue will be supported out of the box.
To get started with Vue on Rails,

*

*Add gem 'webpacker' to gemfile

*bundle install

*Run rails webpacker:install && rails webpacker:install:vue
Alternatively with Rails 5.1x, do rails new app --webpack=vue
You will be ready for Vue on Rails 5

A: Update: gem [vuejs][1] nows ships with vue 2.x and vue-router 2.x.
So I created gem [vuejs][1] because I was using vue.js across multiple projects + prototypes and the gem vuejs-rails doesn't seem to update their gem with the latest version of vue.js.
If you are like me, looking for an easy integration of vue.js with asset pipeline + you want to use the latest vue.js, read on:
Add this line to your application's Gemfile:
   gem 'vuejs'

At application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require vue
//= require vue-router
//= require vue-resource
//= require_tree .

//= require vue-router and //= require vue-resource are optional.
Note that for vue & vue-router 2.x, you need to require these instead
//= require vue2
//= require vue-router2

That's it. You can try writing some javascript in one of the views to test it out.
Try this one:

Hi {{ message }}

  <input v-model="message">

source: https://github.com/ytbryan/vuejs


text:
Q: Angular ng-pattern causes binding to break I've got a form:

    EWS URL
    <input id="url" size="50" ng-model="config.ewsUrl" required >

    Preview timeout (Seconds)
    <input id="PreviewTimeout" type="number" min="15" max="60" required ng-model="config.previewTimeout" style="width: 150px;">

When I add an ng-pattern attribute to the input it breaks the binding:

    EWS URL
    <input ng-pattern="/^((ht|f)tp(s?)\\:\\/\\/)?[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*(:(0-9)*)*(\\/?)([a-zA-Z0-9\\-\\.\\?\\,\\:\\'\\/\\\\\\+=&%\\$#_]*)?$/" id="url" type="url" size="50" ng-model="config.ewsUrl" required>

    Preview timeout (Seconds)
    <input id="PreviewTimeout" type="number" min="15" max="60" required ng-model="config.previewTimeout" style="width: 150px;">

If I remove the reg ex, it goes back to binding again.  What could cause this?

A: It looks like you are trying to validate a url. You don't need to use a regular expression or the ng-pattern option for this. Instead just use the following:
<input type="url" id="url" type="url" size="50" ng-model="config.ewsUrl" required/>

That in mind, the real reason that you aren't getting model binding is probably because the regular expression is not validating the values entered (either because it is incorrect or it is not a valid regular expression). I put together a quick plunker demonstrating what happens with valid and invalid values (on a validated field).
See the plunker here.
EDIT - Version Using ng-pattern
If older browser support is important, you will probably still need to also use ng-pattern. In order to do this you need to make sure the regular expression is in the correct format (leading and trailing slash, but no "g"). For an example I pulled a regular expression for url's from here and implemented it in the following code:
  <input id="url" type="url" size="50" ng-model="config.workingUrl2"
    ng-pattern="/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/"
    required/>

See this working in the updated plunker! Best of luck!


text:
Q: Can't mock method(Class extends SomeClass>) I'm trying mock a Enum:
public enum SomeEnum implements BaseEnum{

    SOME_VALUE("Description", SomeClass.class);

    private Class<? extends IConsignador> integracao;
    private String descricao;

    TipoIntegracao(String descricao, Class<? extends IConsignador> integracao){
        this.descricao = descricao;
        this.integracao = integracao;
    }

    @Override
    public String getDescricao() {
        return descricao;
    }

    public Class<? extends IConsignador> getIntegracao() {
        return integracao;
    }
}

And my mock:
SomeEnum mock = createMock(SomeEnum.class);
expect(mock.getIntegracao()).andReturn( (Class<? extends IConsignador>) eq(ClassWithOutPublicConstructor.class ) );
replay(mock);

But eclipse say:
The method andReturn(Class<capture#1-of ? extends IConsignador>) in the type IExpectationSetters<Class<capture#1-of ? extends IConsignador>> is not applicable for the arguments (Class<capture#2-of ? extends IConsignador>)

he suggested the cast, and still does not accept the value.
What can it be?

A: As with other things tricky to mock, consider extracting the interface out of your Enum and mocking the interface directly. Mocking an Enum is a bad idea because it breaks the general contract of the static and instance methods on your Enum (e.g. ordinal() and values()).
To the EasyMock point, EasyMock apparently has some trouble with bounded wildcards. Try using this syntax:
EasyMock.<Class<? extends IConsignador>>expect(
    mock.getIntegracao())
    .andReturn(ClassWithOutPublicConstructor.class);

You also left an eq in your thenReturn, which EasyMock dislikes. Matchers are only for within expect's parameter. Sorry I didn't see it before.


text:
Q: Manually fire SpeechRecognizedEvent I need to fire the SpeechRecognizedEvent manually for unit testing so I can't  use the EmulateSpeech Method from a SpeechRecognitionEngine
Edit:
I have already encapsulated the SpeechRecognition into a separate Class with its own interface to mock it.
I need to call the Event because I have an AutoResetEvent, which I Set() during the event. The Unit test needs this to proceed.

A: The general idea with unit tests is not to use real things as they either:

*

*Slow (e.g. database)

*Dangerous to poke to often (e.g. Google Search API)

*Not available (e.g. web service or hardware)

For such scenarios you suppose to use mocks/stubs. In other words things that behave identically, but in reality under your full control.
In your case SpeechRecognitionEngine, even if it might be available, would be too cumbersome for unit tests. Who/what would speak things to it? And even if you trigger an event, why to instantiate an instance of real SpeechRecognitionEngine?
Looking at MSDN for SpeechRecognitionEngine definition indicates that it doesn't implement an interface, which means it would be difficult to mock/stub.
For this case, you need to wrap, in other words, encapsulate SpeechRecognitionEngine into your own class which implements your interface. Then, all you need to do is to have two implementations of your interface, one with real SpeechRecognitionEngine for a real speech recognition, and another class for unit tests, which would just mimic your own callback, instead of using SpeechRecognized event.
You just swap one instance for another, and your code won't see a difference, as they are implementing single interface.
If you just want to simulate an event, you just call an event handler, as this is a method. Or another method, if you can't create some EventArgs. But the problem is that you'll have to expose inner methods from outside of your class (e.g. mark it public or internal), and this does looks nasty.
private void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
    this.ProcessSpeechRecognition(e.Result);
}

public void ProcessSpeechRecognition(RecognitionResult result)
{
    // your logic here
}

Then in test you just call something similar to the below:
ProcessSpeechRecognition(new RecognitionResult { Text = "test" });

A: Despite posting an answer before that describes best practices for TDD; here is an answer specific to SpeechRecognitionEngine.
Microsoft has already thought about emulation of speech recognition. Here is MSDN article for SpeechRecognitionEngine.EmulateRecognize Method:
https://learn.microsoft.com/en-us/dotnet/api/system.speech.recognition.speechrecognitionengine.emulaterecognize


text:
Q: Does Dagger2 annotation processor supports the Eclipse incremental compiler? Does Dagger2 annotation processor supports the Eclipse incremental compiler?
I setup Dagger2 with the sample app and after a full compile (after cleaning the project) everything works fine, but after small changes (module or component) and only an incremental compiler run nothing is updated (and errors are shown in the Eclipse log).
Is this normal and if not how could I fix this, because full compiler runs are expensive.
Thanks

A: Yes and no.
Dagger has been written to use only the standard annotation processing API provided as part of the JDK.  There is nothing compiler-specific in its implementation.  So, theoretically, Dagger should work under any compiler.
Unfortunately, in trying to run Dagger with Eclipse's implementation of that API we have bumped up against a significant number of bugs.  Anything based on ECJ (Eclipse's incremental compilation, Android's Jack toolchain, etc.) tends to crash in unexpected ways.
While projects like AutoValue exercise annotation processing in limited enough ways as to build in workarounds for their required functionality, that would be a significantly larger undertaking for Dagger.
So, if/when Eclipse can reliably support annotation processing, Dagger should work.


text:
Q: Adicionar barra no fim da URL com Htaccess Estou tendo um problema com meu .htaccess, pois antes usava .htm no final agora que quero por barra não consigo alterar.
Uso com fim .htm query string:
##### Url Dinamica ###################################
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d

# Exibe a pagina com a extensao em .htm
RewriteRule ^([A-Za-z-]+)\.htm$ index.php?tag=$1 [qsappend]

</ifModule>

Tentei usar
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
RewriteRule ^([A-Za-z-]+)\$ index.php?tag=$1/ [qsappend]

Mas gera erro e não abre normal

A: Tente com essa regex ^([A-Za-z-]+)\\\.htm$.

\\ para verificar \ literal (case sensitive) e
  \. para verificar . literal (case sensitive)


text:
Q: Microsoft Dynamics CRM: Export solution from 2015 to 2013 Is it possible to export a solution from CRM 2015 (7.0) to CRM 2013 (6.1)? Instructions I've found online say there's a step to choose target version in the export wizard but it doesn't appear for me.

A: That's not possible. The only way is manual copying of solution.

A: Andrii is right, there doesn't seem to be a way to import a 2015 solution into 2013. But at least in my case, I was able get an import to work by unzipping and editing XML files in the exported solution. Perhaps this could help someone else:
In solution.xml I set version="6.1.3.125" and SolutionPackageVersion="6.1" in the initial <ImportExportXml> element.
Then using regex find and replace in Notepad++ I removed the following elements throughout customizations.xml to make the schema match:

*

*<SourceType>

*<CanChangeHierarchicalRelationship>

*<EntityHelpUrlEnabled>

*<EntityHelpUrl>

*<IsHierarchical>
Zipped the files back up and it successfully imported into 2013.

A: I was able to hack the solution files and successfully imported a 2015 Update 1 solution into 2013.  Here were my steps:
Change the first line of solution.xml to the following:

Remove the following from customizations.xml (obviously these reference new features not yet available back in 2013)
    0
    0
    0
    1
    0
    …..
    …..
    0
    1
    0
    0
    0
    1
    false
    1
    0
    5.0.0.0
    1.0.0.0
    1.0
    1.0.5.418
Replace

with

Remove IntroducedVersion="5.0.0.0" from SiteMap area
Edit all Workflow XML files
Change Version=7.0.0.0 to Version=5.0.0.0


text:
Q: Filter rows based on window functions Is there a way to filter out rows based on a a window function over row_number in the same select statement?
Currently, what I'm doing is,
SELECT other_columns,row_id_ranked FROM (
  SELECT other_columns, "row_number"() OVER (
        PARTITION BY "uuid"
        ORDER BY "uuid" ASC, "status"."sequence" DESC
    ) "row_id_ranked",
  FROM my_table
  )
WHERE row_id_ranked = 1

But this means Presto will create a temporary inner table to and calculate the "row_id_ranked", which means extra work.
is there a way to filter out the rows within the same select statement?
Something like,
    "status"."sequence" FILTER(
       WHERE (
        "row_number"()
            OVER (
                PARTITION BY "uuid"
                ORDER BY "uuid" ASC,
                    "status"."sequence" DESC
            )
         ) = 1
    ) "sequence_num",


text:
Q: Generic extension method testing I have a really simple extension method which is constrained for IComparable instances:
public static bool Between<T>(this T comparable, T min, T max) where T : IComparable<T>
{
    return comparable.CompareTo(min) >= 0 && comparable.CompareTo(max) <= 0;
}

Which would be the correct approach to test this method? I tried mocking IComparable instances to no avail... I use NUnit and Moq, but I'm really a noob in TDD.

A: There is no need to mock anything. You can use any IComparable object like Integers or Strings.
Check it out:
[TestMethod]
public void YourTestName()
{
    Assert.IsTrue(2.Between(0, 5));
    Assert.IsFalse("a".Between("b", "d"));
}

Keep It Simple.
By the way, I would rename that method to IsBetween instead of just Between. I found it much more fluent.
[TestMethod]
public void YourTestName()
{
    Assert.IsTrue(2.IsBetween(0, 5));
}

A: Try the following in Moq.  This will test the case where the value is actually between the provided values.
var mock = new Mock<IComparable<string>>();
mock.Setup(x => x.CompareTo("a")).Returns(1).Verifiable();
mock.Setup(x => x.CompareTo("z")).Returns(-1).Verifiable();
Assert.IsTrue(mock.Object.Between("a", "z"));
mock.Verify();

You can modify this fairly quickly to test the negative cases


text:
Q: Question: How to get an array index id? in Vuejs Scenario: I have an array which possesses 4 object i need to display the index of the array can someone help me to do this

A: This is as simple as using index in your output:

    {{ index }}
    ...

You are already capturing the index in v-for="(items,index) in addedArray".


text:
Q: Read resource files for android on startup before loading MainPage using xamarin I want to make an application for android, when i start the application
i want an extern xaml file to set colors for mainpage and other static bindings.
I have done this on an windows app with help of stackowerflow, this is the link to the question
My Question
Can this be done?
Im trying to use the same code with wont fork ofcourse.
I tried to put the file in the asset map, and read with
assetmanager but cant access it in the start session !
Example:
                string fileName = Path.Combine(Environment
                .GetFolderPath(Environment.SpecialFolder.LocalApplicationData), $"
                {filename}Colors.xaml");

            bool fileexist = File.Exists(fileName);

It cant even find my file - i have in the file option:
AndroidAsset
Do not copy
I know it require a long answer - but i have a long question in the linq
and i want the same thing in my android app !
Thanks a million if you can help me.


text:
Q: Aurora Postgresql's insert statements aren't recognizing existing key IDs After migrating from RDS Postgresql to RDS Aurora PostgreSQL, I am having an issue to where new inserts are trying to start from key ID 2 instead of the last record.
In my rails app, here's what I'm seeing when I try to create a new record:
ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "global_options_pkey"
DETAIL:  Key (id)=(3) already exists.
):

app/controllers/schedules_controller.rb:45:in `create'

Not sure why this would be the case. To set up Aurora PSQL in Rails, I followed this tutorial: https://guides.rubyonrails.org/active_record_multiple_databases.html. It seems like everything is working fine (auto switching between reader/writer instances, etc.).
With the migration, I specifically used the AWS Schema Conversion Tool (SCT), followed by a migration with the Database Migration Service.
Is this error caused by something that was done incorrectly in the migration process or do I need to some post-migration processes to have this fixed?

A: Definitely a case of when you migrated old data, but not with INSERT and your sequences are still on the initial values.
Use sequence manipulation functions to check what is the current value with lastval(), and set it to max(id) with setval()

A: You can try
ActiveRecord::Base.connection.tables.each do |table_name|
  ActiveRecord::Base.connection.reset_pk_sequence!(table_name)
end


text:
Q: jquery selector result is prevObject: e.fn.e.init[3] how do I get an element from that I have a selector $('.element') is returning prevObject: e.fn.e.init[3]. I looked into the results and the first object there is what I need. 2 questions here. What is prevObject? Also how can I select from the result the first object. Thanks for any help.

A: To access the first element, simply use [0] or .get(0)
prevObject is the result of the previous jQuery function call if the calls were chained together.  It's what allows the .end() call to pop the jQuery chain back to a prior state.