text:
Q: Initializing with useState after UseEffect returns : Is that possible? I have two React questions.
Using useEffect I am calling an api:
React.useEffect(() => {
  //API get call
},[]);

The result of the api is stored in array.
Question 1: I know useEffect is asynchronous method, but is there any way for me to use useState to initialize values of  dropdown after useEffect returns?
Question 2: How can I initialize the values of  inside a forEach loop with the values of the array?

A: After the API call in useEffect call the set state for the useState you are saving to. For example:
const [state, setState] = useState([]);

const someFetch = async () => {
 // using JS fetch API
 const result = await fetch("getFetchSomeData");
 // assuming the state is in the form of an array
 setState(result.json())
}

useEffect(() => }{
   someFetch();
});

return (
  // rendering the array of fetched state this will update on next render after fetch

{state}

):

A: Question 1
I would probably do something like this:
function MyComponent() {
  const [isLoading, setIsLoading] = useState(false);
  const [data, setData] = useState(undefined);

  useEffect(() => {
    async function getData() {
      setIsLoading(true);
      const data = await /* API call */
      setData((prevVal) => data);
      setIsLoading(false);
    }

    getData();
  }, []);

  if (loading) return
Loading...
;

  if (!loading && !data) return
Error!
;

  return (
    /* your component */
  );
}

In essence, you have to play around the "asynchrony" aspect of the hooks.
Question 2
You did not say what you want to initialize, but I am assuming a component of some sort requires the values from the API. The following example uses HTML select element.  Use map().
<select>
{
  data && data.map(({value, label}, index) => (
    <option key={index} value={value}>{label}</option>
  ))
}
</select>

A:
Question 1: I know useEffect is asynchronous method, but is there any way for me to use useState to initialize values of dropdown after useEffect returns?

No, we can't initialize the useState after the useEffect runs. useEffect hook always runs both after the first render and after every update. We need to have the initialized value for the state at first render as well. Then later when useEffect run we can simply update the state by setting it.
function App(){

 const [stateVariable, setStateVariable] = useState(null);

 useEffect(() => {

   async function fetchApiCall(){
    fetch('http://example.com/movies.json')
       .then(response => response.json())
       .then(data => setStateVariable(data));
   }
  fetchApiCall(); // function call

 },[]);

}

Question 2: How can I initialize the values inside a forEach loop with the values of the array?

Now we have our data in our stateVariable. Most probably the data which comes from the API is in an array of objects[JSON].
Array.prototype.map() function might be helpful here. According to mdn docs,

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

function processEachElement(element, index){
  return
{element}
;
}

const newData = data.map(processEachElement);
// Now the newData is an array of `JSX.Elements`. Remember, not an array of objects.

so, the final code is given below,
function App() {
  const [stateVariable, setStateVariable] = useState(null);

  useEffect(() => {
    async function fetchApiCall() {
      fetch("http://example.com/movies.json")
        .then((response) => response.json())
        .then((data) => setStateVariable(data));
    }
    fetchApiCall(); // function call
  }, []);

  function processEachElement(element, index) {
    return
{element}
;
  }

  const newData = data.map(processEachElement);

  return
{newData}
;
}


text:
Q: Problemas com python 3 Boa noite!
Estou tendo um pequeno problema com python 3.x no meu linux mint 19.03

Código:
#!/usr/bin/env python3
#-*-coding: utf-8-*-
from tkinter import *
win = Tk()
def msg():
  m = val.get()
  Label(win, text=m).pack()
win.geometry("250x250+250+250")
win.title("aula excript")
val = Entry(win).pack()
Button(win, text="ok", command=msg).pack()
win.mainloop()

O código acima, está gerando a seguinte exceção:
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
  File "./tt.py", line 6, in msg
    m = val.get()
AttributeError: 'NoneType' object has no attribute 'get'

Agradeço desde já =D

A: O erro ocorre, pois você está inserindo o retorno do método pack na variável val, sendo que pack não possui um retorno (None):
val = Entry(win).pack()

Gerando assim o erro:

AttributeError: 'NoneType' object has no attribute 'get'

Quando na verdade, val deveria conter apenas o retorno de Entry, e com esse valor então, chamar o método pack:
val = Entry(win)
val.pack()

Com isso, o método get vai retornar o valor corretamente, deixando de ocorrer o erro.

Seu código então, ficaria da seguinte forma:
#!/usr/bin/env python3
#-*-coding: utf-8-*-

from tkinter import *

win = Tk()

def msg():
  m = val.get()
  Label(win, text=m).pack()

win.geometry("250x250+250+250")
win.title("aula excript")
val = Entry(win)
val.pack()
Button(win, text="ok", command=msg).pack()
win.mainloop()

redpajama_set_name: RedPajamaStackExchange


text:
Q: react routing taking too long import React, { Component } from "react";
import { Col, Image, Nav } from "react-bootstrap";
import { NavLink } from "react-router-dom";

class Sidebar extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  componentDidMount() {
    console.log("sidebar");
  }
  render() {
    return (
      <Col md={3} lg={2} className="sidebar">

          <NavLink to="/admin/dashboard" className="active">
             DASHBOARD
          </NavLink>
          <NavLink to="/admin/deliveryagentlist">
             DELIVERY AGENTS
          </NavLink>
          <NavLink to="/admin/customerlist">
             CUSTOMERS
          </NavLink>

      </Col>
    );
  }
}

export default Sidebar;

The above is the code of sidebar in my project.
The issue I am facing is when I change the page by clicking on sidebar items routing takes place. But it takes too long to redirect the page
I am on the dashboard. I click the customer in the sidebar. then the URL in the browser will change from http://localhost:3000/admin/dashboard to http://localhost:3000/admin/customerlist within no time. But the page loading takes too long. The customer list page contains some initial consoled text in its componentDidMount, like  componentDidMount() { console.log("hey. Customer"); this.getList();}
and I observed the text hey. Customer also get consoled too late. The API calling inside this.getList() is also taking longer to start.
I am providing my routing code. It may be linked with routing.
MainRouting.js
import React, { Component } from "react";
import { Switch, Route } from "react-router-dom";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

// Route
import PrivateRouteAdmin from "./PrivateRouteAdmin";
import PublicRoute from "./PublicRoute";

// admin
import Login from "../Component/admin/login/Login";
import AdminDashboard from "../Component/admin/dashboard/Dashboard";
import AdminCustomerTable from "../Component/admin/customer/CustomerTable";
import DeliveryAgentTable from "../Component/admin/DeliveryAgent/DeliveryAgentTable";

class MainRoute extends Component {
  render() {
    return (
      <>
        <Switch>
          <PublicRoute exact path="/" component={Login} />

          <PrivateRouteAdmin
            path="/admin/dashboard"
            component={AdminDashboard}
          />
          <PrivateRouteAdmin
            path="/admin/customerlist"
            component={AdminCustomerTable}
          />

          <PrivateRouteAdmin
            path="/admin/deliveryagentlist"
            component={DeliveryAgentTable}
          />
          <PublicRoute path="/admin/login" component={Login} />
        </Switch>
      </>
    );
  }
}
export default MainRoute;

PrivateRouteAdmin
import React from "react";
import { Route, Redirect } from "react-router-dom";
import { getLocalStorage } from "../common/helpers/Utils";

const PrivateRouteAdmin = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      getLocalStorage("adminInfo") ? (
        <Component {...props} {...rest} />
      ) : (
        <Redirect
          to={{ pathname: "/admin/login", state: { from: props.location } }}
        />
      )
    }
  />
);

export default PrivateRouteAdmin;

PublicRoute
import React from "react";
import { Route, Redirect } from "react-router-dom";

import { getLocalStorage } from "../common/helpers/Utils";

const PublicRoute = ({ component: Component, restricted, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props =>
        getLocalStorage("adminInfo") ? (
          <Redirect to="/admin/dashboard" />
        ) : (
          <Component {...props} />
        )
      }
    />
  );
};

export default PublicRoute;


text:
Q: PHP find out student record using functions
*

*Table: student

*student.php
<?php
function findStudentRecord()
{
      //Db connection

      $q1 = "select * from student where gender = 'F'";
      $r1 = mysqli_query($dbc, $q1);
      $total_records = mysqli_num_rows($r1);

      $record = array();
      if($total_records > 0)
      {
          while($row1 = mysqli_fetch_array($r1, MYSQLI_ASSOC))
          {
              $record[] = $row1;
          }
      }
      else
      {
          //[HERE]
      }

      return $record;
}

$record = findStudentRecord();
//[HERE]
?>

*I want to find female student record but there is no record from my database. How do I return 0 value from function and display "No record found" on my web page in [HERE] section?

A: if($total_records > 0)

add no else block so it will return an empty array now you can do something like this
$records = findStudentRecord();
if(count($records) === 0) {
    echo "No record found";
}

A: I would not change your function. It returns an array (may be empty) in any case wich is quite consistent.
Instead look at the number of array items returned:
$record = findStudentRecord();
//[HERE]
if(count($record) == 0) {
  echo "No record found";
} else {
  // what ever
}


text:
Q: Where can I find visible/radio telescopic observations of the center of the Milky Way galaxy? I recently stumbled across this time-lapse telescopic image (radio image, I believe) of the center of the galaxy.
Here's a still image. Link to time-lapse video below.

I haven't been able to find this image anywhere else.
My only source is this obscure YouTube link (timestamp included, to make it easier for you)
https://www.youtube.com/watch?v=Dk2-lH9ewuA&t=143
I don't recall ever seeing this image in the past, and I'm interested to know where it came from.
Is there any publicly-available research around these observations?
The fringe claim is that these images show no evidence of gravitational tidal forces, nor gravitational lensing.
I'd like to read some proper research, explaining what we are supposed to be looking at.

A: It's infrared optical interferometry with ESO's Very Large Telescope at the Paranal Observatory.
Have a look at How did they make a video of the center of the galaxy, and what is it exactly that's flashing there? (GIF) and ESOcast 173: First Successful Test of Einstein's General Relativity Near Supermassive Black Hole (video).
This answer explains further.

Screenshots from video, click for full size:

A: These are the stellar orbits around Sagittarius A$^*$. The original work and a discussion is available on the Arxiv as the paper Stellar Orbits Near Sagittarius A$^*$ by Eckart, Genzel, Ott and Schoedel. This paper is from 2002 to there have been another seventeen years of observation since. The animation you describe was presumably done using all the recent data. Offhand I don't know where the very latest data can be downloaded. A quick Google failed to locate it but I imagine it's not beyond a more determined search.


text:
Q: how to put php and node.js togther I have test node.js + socket.io with port 8080 yesterday
i found that the frontend page which receive the data and send request must defined as HTML
which mean, i can use a mvc php combine with node.js and socket.io
is there any way to do that?
more if i define the node server as localhost:8080
i cant call the web server by other place, such as localhost
unlike nature websocket, i can use the socket anywhere, and i just need to define the socket address as localhost:8080
anyway to solve out?

A: Run node on port 8080 run php on port 8081. Use php to run your frontend HTML and JavaScript include the frontend socket.io library and connect to localhost:8080 (the node server)
// client side code
var socket = io.connect('http://localhost:8080');

This is untested, and I don't know if this is what you want, or if it will work.


text:
Q: How to remove second class of html element in javascript? I have multiple span tags.
example:

how can i remove second class without using class name like span.classList.remove('three');
i just need something like span.classList.remove(1); to remove only second class from all span elements

A: I found answer
span.classList.remove(span.classList.item(1));


text:
Q: React + Express + Twitter API to Heroku get 405 Not Allowed I'm new in React and Express, and i'm trying to create small app that will show Twitter Timeline for specific User(username taken from text-input).
It's work locally, but on Heroku i have an Error in method: 'POST'
405(Not Allowed)

    handleSubmit(event) {
        event.preventDefault();
            fetch('./', {
                method: 'POST',
                headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({name: event.target.elements.name.value})
            }).then(res => res.json())
            .then(twitter => this.setState({twitter}));
        }

Full code here https://github.com/oslyvtc/react-express-heroku
You can see error here https://polar-fjord-91508.herokuapp.com/

A: Thank you all guys. As i thought it was just misspelling issue.
I named Procfile.txt instead of Procfile, thats why heroku didn't run node server.js


text:
Q: Simple AngularJS running on JSFiddle How do I make a jsfiddle out of the following code:

                {{num}}

My non working attempt: http://jsfiddle.net/zhon/3DHjg/ shows nothing and has errors.

A: You've defined your controller in a function scope that is not accessible to angular (angular is not yet loaded). In other words you are trying to call angular library's functions and helpers like below example before getting angular library loaded.
function onload(){
 function MainCtrl(){}
}

To resolve this, switch your angular load type to be No wrap - in  like shown in screenshot.

here is a working example in jsfiddle

A: You need to set some things up in jsFiddle for this to work.
First, on the left panel, under "Frameworks & Extensions", select "No wrap - in ".
Now, under "Fiddle Options", change "Body tag" to
In the JS panel, initiate your module:
var app = angular.module('myApp', []);

Check it out: http://jsfiddle.net/VSph2/1/

A: @pkozlowski.opensource has a nice blog post about how to use jsFiddle to write AngularJS sample programs.

A: Click JAVASCRIPT button, choose angular version and place where u want include loaded script:

Then click HTML button and add ng-app in body tag. Its all:)

A: I am writing my answer for those who land on this page , I was used to use ng-module directive but in jsfiddle after half an hour I realized that ng-module is not allowed and you see no error , and when changed that ng-module to ng-app fiddle worked very well .I just wanted to share this .And no wrap (body) is required too.

{{greeting}}

var app=angular.module("appX",[]);
console.log(app);
app.controller("appCtrl",function($scope){
$scope.greeting="Hello World";
});

https://jsfiddle.net/cloudnine/trgrjwf1/7/

A: Since Angular 1.4.8 has been chosen by JSFiddle as the top option for Angular V1 in its JAVASCRIPT setting panel, more restriction applies: both ng-app and ng-controller should be declared in HTML to make it work.
Sample HTML:

  <input type="text" ng-model="sample" placeholder="type something here...">
  {{sample}}

Sample JS:
angular.module('myApp', [])
  .controller('myCtrl', function($scope) {});

https://jsfiddle.net/y170uj84/
Also tested with the latest Angular 1.6.4, by setting as External Resource.

A: For little experiments in angular 5, you can use https://stackblitz.com/.
This site is used in angular documentation to run live demo. For example, https://stackblitz.com/angular/eybymjopmav


text:
Q: Use of __getattr__ in Python How frequently should you use __getattr__ in Python, rather than normal methods?
Which of these would be considered better?
class A:
    def __getattr__(self, attribute):
        if attribute == "spam":
            return self._spam * 100
        elif attribute == "eggs":
            return "fried" + self._eggs
        raise AttributeError

or
class B:
    def get_spam(self):
        return self._spam * 100

    def get_eggs(self):
        return "fried" + self._eggs

A: Instead of __getattr__ or accessor methods, use the @property decorator:
class B(object):
    @property
    def spam(self):
        return self._spam * 100

    @property
    def eggs(self):
        return "fried" + self._eggs

Use __getattr__ only to support dynamic attributes, where the number and names of the attributes are not known at class definition time.


text:
Q: Create a tar.gz from an image file (Linux or Mac) Hi I have an img of a custom linux distro and I would like to convert it to a tar.gz file. (I am using Mac or Linux OS)
What is the most straight forward way to do it?
Thank you

A: Convert isn't quite what it does. You can compress the image into a tar.gz file with:
tar -cvzf linuximage.tar.gz linuximage

You can uncompress/unzip with:
tar -xvzf linuximage.tar.gz

Just replace linuximage with the actual filename or folder.


text:
Q: Como criar um número aleatório de 5 dígitos iniciando do 1? Tenho que criar uma conta bancária com alguns requisitos, no meio deles preciso ter um número contante de 5 dígitos iniciados do 00001.
Porém ao colocar "00001" na hora de exibir só exibe o 2, 3 em diante. minha solução foi usar o número 10000. Porém queria saber como fazer de acordo com o enunciado.
public abstract class Account implements IBaseRate {

    String name;
    String sSN;
    double balence;
    String accountNumber;
    double rate;
    static int index = 00001;

...

private String setAccountNumber() {

    String lastSSN = sSN.substring(sSN.length()-2, sSN.length());
    int uniqueID = index++;
    int randomNumber = (int) (Math.random()*Math.pow(10, 3));

    return lastSSN + uniqueID + randomNumber;
}
}

A: O problema aí é que é preciso formatar o número da conta com zeros à esquerda para preencher a quantidade de casas que descreve.
Uma das formas de se fazer isto é usando o método String.format, desta forma
class Main {
    public static void main(String[] args) {
        int num = 1;
        String strNum = String.format("%05d", num);
        System.out.println(strNum); // Saída: 00001
    }
}

Veja funcionando no repl.it


text:
Q: failed to restart after installation I'm trying to install a 64 bits ubuntu desktop 12.10 to my new asus g75vw from a dvd.
Everything worked slowly but fine until it finished, then the installation program prompted me to restart.I clicked restart button after which the computer freezes and finally I have to power it off. Now I can only boot into windows 7 not grub. Where did I go wrong and how do i fix it?

A: Have you tried to do another re-install? That should fix it. And are you dual booting or was a a full on install?

A: Although I didn't know why.
But i think it doesn't matter too much.
After the screen freeze when i click the restart button.
I power the computer off.
I went into the Windows 7 OS, AND add the ubuntu entry through easybcd.
Then I restart the computer, and select the ubuntu.
Everything just goes fine. and I can get into both windows 7 and ubuntu systems based on my selection.
Hope that would help.


text:
Q: SyntaxError: unexpected EOF while parsing in python I am getting the above error in python.
w=[]
h=[]
l=int(input())
t=int(input())

for i in range(t):
    n=raw_input()
    w.append(n)
    n=int(input())
    h.append(n)

for i in range(t):
    if w<l and h<l:
        print ("UPLOAD ANOTHER")
    elif w>l and h>l and w!=h:
        print ("CROP IT")
    elif w>=l and h>=l and w==h:
        print("ACCEPTED")

A: You probably given a empty input or '\n' for the n=int(input()) part. Try to give the number as input.
put this line in your terminal
x = int(input()). and give empty input, (just tap enter). vola..
SyntaxError: unexpected EOF while parsing

A: You might be running the script on some online IDE. This also appeared to me while I was submitting my solution. The best way to deal with this is don't run your script on online ide rather directly submit it.
If the answer is correct it would get accepted else show the wrong answer.


text:
Q: Android ContentProvider calls bursts of setNotificationUri() to CursorAdapter when many rows are inserted with a batch operation I have a custom ContentProvider which manages the access to a SQLite database. To load the content of a database table in a ListFragment, I use the LoaderManager with a CursorLoader and a CursorAdapter:
public class MyListFragment extends ListFragment implements LoaderCallbacks<Cursor> {
    // ...
    CursorAdapter mAdapter;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mAdapter = new CursorAdapter(getActivity(), null, 0);
        setListAdapter(mAdapter);
        getLoaderManager().initLoader(LOADER_ID, null, this);
    }

    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(getActivity(), CONTENT_URI, PROJECTION, null, null, null);
    }

    public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
        mAdapter.swapCursor(c);
    }

    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);
    }
}

The SQLite database gets updated by a background task which fetches a number of items from a web service and inserts these items into the database through ContentProvider batch operations (ContentResolver#applyBatch()).
Even if this is a batch operation, ContentProvider#insert() gets called for each row is inserted into the database and, in the current implementation, the ContentProvider calls setNotificationUri() for each insert command.
The result is that the CursorAdapter receives bursts of notifications, resulting in the UI being updated too often with consequent annoying flickering effect.
Ideally, when a batch operation is in progress, there should be a way to notify ContentObserver only at the end of any batch operation and not with each insert command.
Does anybody know if this is possible? Please note I can change the ContentProvider implementation and override any of its methods.

A: To address this exact problem, I overrode applyBatch and set a flag which blocked other methods from sending notifications.
    volatile boolean applyingBatch=false;
    public ContentProviderResult[] applyBatch(
        ArrayList<ContentProviderOperation> operations)
        throws OperationApplicationException {
    applyingBatch=true;
    ContentProviderResult[] result;
    try {
        result = super.applyBatch(operations);
    } catch (OperationApplicationException e) {
        throw e;
    }
    applyingBatch=false;
    synchronized (delayedNotifications) {
        for (Uri uri : delayedNotifications) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
    }
    return result;
}

I exposed a method to "store" notifications to be sent when the batch was complete:
protected void sendNotification(Uri uri) {
    if (applyingBatch) {
        if (delayedNotifications==null) {
            delayedNotifications=new ArrayList<Uri>();
        }
        synchronized (delayedNotifications) {
            if (!delayedNotifications.contains(uri)) {
                delayedNotifications.add(uri);
            }
        }
    } else {
        getContext().getContentResolver().notifyChange(uri, null);
    }
}

And any methods that send notifications employ sendNotification, rather than directly firing a notification.
There may well be better ways of doing this - it certainly seems as though they're ought to be - but that's what I did.

A: I found a simpler solution that I discovered from Google's I/O app. You just have to override the applyBatch method in your ContentProvider and perform all the operations in a transaction. Notifications are not sent until the transaction commits, which results in minimizing the number of ContentProvider change-notifications that are sent out:
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
        throws OperationApplicationException {

    final SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    db.beginTransaction();
    try {
        final int numOperations = operations.size();
        final ContentProviderResult[] results = new ContentProviderResult[numOperations];
        for (int i = 0; i < numOperations; i++) {
            results[i] = operations.get(i).apply(this, results, i);
        }
        db.setTransactionSuccessful();
        return results;
    } finally {
        db.endTransaction();
    }
}

A: In a comment to the original answer, Jens directed us towards SQLiteContentProvider in the AOSP. One reason why this isn't (yet?) in the SDK may be that the AOSP seems to contain multiple variations of this code.
For example com.android.browser.provider.SQLiteContentProvider seems to be a slightly more complete solution, incorporating the "delayed notifications" principle proposed by Phillip Fitzsimmons while keeping the provider thread-safe by using a ThreadLocal for the batch-flag and synchronizing access to the delayed notification set.
Yet even though access to the set of URI's to be notified of change is synchronized, I can still imagine that race conditions may occur. For example if a long operation posts some notifications, then gets overtaken by a smaller batch operation, which fires the notifications and clears the set before the first operation commits.
Still, the above version seems to be the best bet as a reference when implementing your own provider.


text:
Q: Laravel dependency inject service into service I am trying to find the best way to access the InvoiceService from the PaymentService. I have considered DI the InvoiceService like so:
protected InvoiceServiceInterface $invoiceService;

public function __construct(InvoiceServiceInterface $invoiceService)
{
    $this->invoiceService = $invoiceService;
}

The issue I have with this method is not all the functions within my PaymentService need the InvoiceService. Is there a way I can get access to the InvoiceService inside the PaymentService a similar way without tightly coupling them together?
I can get the code working by bypassing the interface altogether but this isn't the approach I want to take (new InvoiceService)->generateInvoice($account, $items, $totalAmount, $totalAmount);


text:
Q: Define a Custom EditText I'm a beginner. I want to define the xml for a custom EditText and then programmatically add those custom edittexts at runtime without using a bunch of code to customize the editTexts. This could be similar to implementing custom buttons, textviews, etc. from libraries...although it would be my own. What is the best way to approach this?
Thanks!

A: Alternative code apart from code shared in above comment link is below :
basically this code makes easy for user to customize the fonts etc.
public class MyEditText extends EditText {

    public MyEditText(Context context) {
        super(context);
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        parseAttributes(context, attrs);
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        parseAttributes(context, attrs);
    }

    private void parseAttributes(Context context, AttributeSet attrs) {
        TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.Simplified);

        int typefaceValue = values.getInt(R.styleable.Simplified_typeface, 0);
        values.recycle();

        setTypeface(MyFontUtil.obtaintTypeface(context, typefaceValue));
    }

}

XML
 <com.my.mtetno.widget.MyEditText
  android:id="@+id/uname"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_weight="1"
  android:background="@drawable/lh_edit_field_without_border"
  android:inputType="textEmailAddress"
  android:maxLines="1"
  android:overScrollMode="always"
  android:textSize="@dimen/login_page_edit_text_size"
  app:typeface="simplified_regular" />


text:
Q: jasper report integrate in laravel 5 I have a problem with this integration in Laravel 5:

Exception in JasperPHP.php line 178:
  Your report has an error and couldn't be processed! Try to output the command using the function output(); and run it manually in the console.

Code where exception happens:
\JasperPHP::process(
'D:\wamp\www\laravel-Project\reports\center_report.jasper',
false,
array("pdf", "rtf"),
array("php_version" => phpversion()),
$database
)->execute();

A: They Don't provide a specific package for Laravel5 but you can easily use JasperPHP by following their  instructions https://github.com/cossou/JasperPHP


text:
Q: JQuery function not getting applied to every div First of all here is my code http://codepen.io/akshay-7/pen/Ggjxwb
I am trying to shoot down the enemies, but as you can see i am able to shoot only one enemy at a time.
Why can't i shoot down each enemy? The divs that i created using jquery have the id enemy-plane but still it is not working
I am not posting the entire code here but i am posting the part which i think is causing the problem
var inter=setInterval (function(){
  var clone = [];
  clone.push('
');
  clone.push('1000');
  clone.push(' ');
  clone.push('

');
  $('#holder').append(clone.join(''));
},2000);
setTimeout(function(){
  clearTimeout(inter);
},10000);

EDIT
i changed the ids to class but now all of the enemies explode if i shoot down one of them

A: The enemy-plane is not a class it's an ID :

switch

Edit
Suppose you click on the image the code should look like this :
$(".enmy").click(function () {
   //get the closest plane from the image clicked
   $(this).closest(".enemy-plane").MakeItExplode();
});

A: you can't use multiples IDs all with same value,Ids should be unique,
change id to class
change it every where as class in js,css and html
JS
var $div2 = $('.enemy-plane');

and
 clone.push('
');

and
  var lef=$('.enemy-plane');

CSS
.enemy-plane{
  height:80px;
  width:80px;
  left:500px;
  animation:eny-move 5s 1;
  -webkit-animation:eny-move 10s;
  -moz-animation:eny-move 10s;
  -o-animation:eny-move 10s;
  -ms-animation:eny-move 10s;
  top:100px;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select:none;
  user-select:none;
  -o-user-select:none;
  position:relative;
  -webkit-animation-fill-mode:forwards;
}

HTML

    1000

FORKED PEN


text:
Q: JQGrid set value in cell based on condition I need to set the JQgrid cell value based on the condition, suppose the variable value is one then i need to set a bike, if it is 2 then i need to set as car, and so on.
Can anyone please explain how to achieve this?

A: You can achieve this using the formatter
<script>
jQuery("#grid_id").jqGrid({
...
   colModel: [
      ...
      {name:'price', index:'price', width:60, align:"center", editable: true, formatter:vehicalFmatter},
      ...
   ]
...
});

function vehicalFmatter (cellvalue, options, rowObject)
{
   if (cellvalue == 1)
    return "Bike";
   else if (cellvalue == 2)
    return "Car";
}
</script>

Reference: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:custom_formatter

A: You need to use formatter to get the work done. Include this into following line and start developing the function.
Eg.
{name:'vehicle', index:'vehicle', width:100, align:"center", editable: true, formatter:formatvehicle}

Method Development:
function formatvehicle (cellvalue, options, rowObject)

    {
       if (cellvalue == 1)
        return "Bike";
       else if (cellvalue == 2)
        return "Car";
       else {
       }

    }

OR try using Switches.
function formatvehicle (cellvalue, options, rowObject) {

 switch (cellvalue) {
        case 1:
          return "Bike";
            break;
        case 2:
         return "Car";
            break;
    }
}


text:
Q: How to target first img in every wordpress post with CSS I am trying to target first image in every post. The example post where I am trying to perform this is here.
So I tried to use first-of-type like this
.single-post .entry-content img.aligncenter:first-of-type {

width: 80% !important;
float: left;

}

And also tried to replace first-of-type with first-child and I get the same result and that is every image is selected instead of first one. I think that this should only select the first image with occurrence of .aligncenter class.

A: Firstly i would say this is off-topic here as it purely relates to css/js, but let me try to give some pointers.
Here you markup is :

    ....

    ....

    ....

first-of-type means selecting the first child of the selector parent.
In the above markup , the targeted selector is image with class align-center and the selector parent is p. So selecting the first child of the selector parent matches both images. That's why both images are being styled.
first-child means select an element if it is an image with class align-center and and is the first child of a parent selector. So it matches both images.
I would recommend using JavaScript selectors here.
document.querySelector(".single-post .entry-content img.aligncenter")

returns first element in the result.
If you are using jQuery use :first filter.
References:
first-of-type
first-child
SO


text: Q: What files can I move to a small (16GB) SSD to speed up Windows 7? I have a 16GB SSD. It's too small to install Windows on. A discussion about ReadyBoost made me think of putting it in my Core2 Duo with 4 gig of ram and put pagefile.sys on it. What else can be moved to the SSD to speed up the system? Would moving temp and tmp help, and would they fit? Any other suggestions?


text:
Q: How to troubleshoot crashes in malloc I have a large body of legacy code that I inherited. It has worked fine until now. Suddenly at a customer trial that I cannot reproduce inhouse, it crashes in malloc. I think that I need to add instrumentation e.g on top of malloc I have my own malloc that stores some meta information about each malloc e.g. who has made the malloc call. When it crashes, I can then look up the meta information and see what was happening. I had done something similar years ago but cannot recall it now...I am sure people have come up with better ideas. Will be glad to have inputs.
Thanks

A: Is memory allocation broken?
Try valgrind.
Malloc is still crashing.
Okay, I'm going to have to assume that you mean SIGSEGV (segmentation fault) is firing in malloc. This is usually caused by heap corruption. Heap corruption, that itself does not cause a segmentation fault, is usually the result of an array access outside of the array's bounds. This is usually nowhere near the point where you call malloc.
malloc stores a small header of information "in front of" the memory block that it returns to you. This information usually contains the size of the block and a pointer to the next block. Needless to say, changing either of these will cause problems. Usually, the next-block pointer is changed to an invalid address, and the next time malloc is called, it eventually dereferences the bad pointer and segmentation faults. Or it doesn't and starts interpreting random memory as part of the heap. Eventually its luck runs out.
Note that free can have the same thing happen, if the block being released or the free block list is messed up.
How you catch this kind of error depends entirely on how you access the memory that malloc returns. A malloc of a single struct usually isn't a problem; it's malloc of arrays that usually gets you. Using a negative (-1 or -2) index will usually give you the  block header for your current block, and indexing past the array end can give you the header of the next block. Both are valid memory locations, so there will be no segmentation fault.
So the first thing to try is range checking. You mention that this appeared at the customer's site; maybe it's because the data set they are working with is much larger, or that the input data is corrupt (e.g. it says to allocate 100 elements and then initializes 101), or they are performing things in a different order (which hides the bug in your in-house testing), or doing something you haven't tested. It's hard to say without more specifics. You should consider writing something to sanity check your input data.

A: Try Asan
AddressSanitizer (aka ASan) is a memory error detector for C/C++. It finds:
Use after free (dangling pointer dereference)
Heap buffer overflow
Stack buffer overflow
Global buffer overflow
Use after return
Use after scope
Initialization order bugs
Memory leaks

Please find the links to know more and how to use it
https://github.com/google/sanitizers/wiki/AddressSanitizer and
https://github.com/google/sanitizers/wiki/AddressSanitizerFlags

A: I know this is old, but issues like this will continue to exist as long as we have pointers. Although valgrind is the best tool for this purpose, it has a steep learning curve and often the results are too intimidating to understand.
Assuming you are working on some *nux, another tool I can suggest is electricfence. Quote:
Electric Fence helps you detect two common programming bugs:
software that overruns the boundaries of a malloc() memory allocation,
software that touches a memory allocation that has been released by free().
Unlike other malloc() debuggers, Electric Fence will detect read accesses
as well as writes, and it will pinpoint the exact instruction that causes
an error.

Usage is amazingly simple. Just link your code with an additional library lefence
When you run the application, a corefile will be generated when memory is corrupted, instead of when corrupted memory is used.


text:
Q: Angular 8 : Check array contains value of string in component view not work in IE I have angular 8 application. I want to check if array contains the given string in component view. I have used Array.includes which work in chrome but IE gives error Object doesn't support property or method 'includes'
Component view Look like :
<div [ngClass]="{'is-invalid': invalidProps?.includes('errorprop')}">
  Error message
</div>

A: Try to add line below in the polyfills.ts file.
import 'core-js/es6/array';

It may help you to fix your error.

A: I added below line to polyfills.ts file and it working
import "core-js/es/array";
Thanks for hint.


text:
Q: How to check if a sub-document exist before pushing to array I have tried searching but found non that fits my query,
I have a JSON output like this that exist in database
{ _id: 59c255f1f3e91433b4d4b58e,
  name: 'example name';,
  __v: 52,
  contacts:
   [ { contactId: '59c255f1f3e91433b4d4b58e', //duplicated
        _id: 59c2a9f0471ffb202c3771d2,
       added: 2017-09-20T17:48:32.328Z },
      { contactId: '59c255f1f3e91433b4d4b58e', //duplicated
       _id: 59c2ac524fc91235a0d89195,
       added: 2017-09-20T17:58:42.956Z }
      { contactId: '59c255f1f3e91433b4234eff',
       _id: 59c2ac524fc91235a0d89195,
       added: 2017-09-20T17:58:42.956Z }
       ],
}

How can I check if all contacts.contactId exist with this contactId "59c255f1f3e91433b4d4b58e"  before trying to push another contactId,
it keeps appending to array, I need to make sure that only one contactId with "59c255f1f3e91433b4d4b58e" get pushed to the contacts array, no matter what.
I don't have any clue on how to do that, I have tried:
User.findOne({_id: req.user.id}, function(err, newadd) {
if(!newadd === req.req.params.to){ // also tried "indexOf" ^^ "lastIndexOf"
newadd.contacts.push({
    contactId:req.params.to
    })
newadd.save()
}else{
res.end('already exist try again')
}
  })

(I am using mongoose)
I will really appreciate any help :(

A: You may use $addToSet this will not allow duplicates in resulting array
for more info checkout  $addToSet
the above was for mongoose and to answer your approch
 User.findOne({_id: req.user.id}, function(err, newadd) {
     if(!newadd._id === req.params.to){
         newadd.contacts.push({
             contactId:req.params.to
         })
         newadd.save()
     }else{
         res.end('already exist try again')
     }
  })

A: hmmmm mybe just like this
User.findOne({_id: req.user.id}, function(err, newadd) {
var test = newadd.contacts.filter(function(result){
   if ((result.contactId === req. !.....) === true){
       console.log()
   }else{
       console.log()
   }
})


text: Q: Hasse diagram relation i am conflicted with my professors solution here because by definition show in red in the picture, the {1} subset of the bottom set is not a subset of the {2,3} subset of the middle far right set. i have my diagram set up so that the set at the top is related to everything else below it and there is only one level of relation.


text:
Q: Coloring of standard deviation shading using geom_ribbon I am working with a data frame, where I have columns:
     species  replicate  position DOY   RED.PEAK RED.PEAK.SD FAR.RED.PEAK FAR.RED.PEAK.SD
1 LINGONBERRY         1      LOW   1 0.10218177 0.050779465   0.14498610      0.04848566
2 LINGONBERRY         1      LOW  10 0.12089622 0.039990500   0.18177440      0.03263417
3 LINGONBERRY         1      LOW   2 0.10861619 0.039823347   0.20582430      0.05709061
4 LINGONBERRY         1      LOW   3 0.05398631 0.006064099   0.10750730      0.01954550
5 LINGONBERRY         1      LOW   4 0.08722205 0.017874483   0.14446139      0.03133565
6 LINGONBERRY         1      LOW   5 0.04872162 0.028601630   0.09535204      0.02216967

Where species, replicate, position and time are my cases, RED.PEAK and FAR.RED.PEAK are my values and RED.PEAK.SD and FAR.RED.PEAK.SD are standard deviations of RED.PEAK and FAR.RED.PEAK.
I am using ggplot to plot different species (3) with facet_grid,
different positions (2) with linetype,
and different replicates (3) with colors.
NEW.gridplot <- ggplot(new.plot.table,aes(DOY, RED.PEAK, group=interaction(position, replicate)))+
  scale_x_discrete(limit = c("II Feb", "I Mar", "II Mar", "I Apr", "II Apr", "I May", "II May", "I Jun", "II Jun", "I Jul"))+
  facet_grid(.~species)+
  geom_line(aes(color=replicate, linetype=position), size=2)+
  scale_linetype_manual(values=c("dashed", "solid")) +
  scale_color_manual(values = c('black', 'red', 'blue')) +
  geom_ribbon(aes(ymin = RED.PEAK - RED.PEAK.SD,
                  ymax = RED.PEAK + RED.PEAK.SD), alpha = 0.1) +
  myplotting

print(NEW.gridplot)

see an example of ggplot I am having now
and it works well. I would like to, however, colour the shading to black, blue and red in geom_ribbon as well.
 geom_ribbon(aes(ymin = RED.PEAK - RED.PEAK.SD,
                  ymax = RED.PEAK + RED.PEAK.SD), alpha = 0.1, fill=(values = c('black', 'red', 'blue')))

did not work, delivering error
Error: Aesthetics must be either length 1 or the same as the data (150): fill
Then:
geom_ribbon(aes(ymin = ORANGE.PEAK - ORANGE.PEAK.SD,
                  ymax = ORANGE.PEAK + ORANGE.PEAK.SD), alpha = 0.1, fill=replicate)+
                  scale_fill_manual(values = c('black', 'red', 'blue'))

did not work either, delivering error
Error in rep(value[[k]], length.out = n) :
attempt to replicate an object of type 'closure'
Looking for a solution to have my shadings from geom_ribbon the same colors as their corresponding lines from geom_line.

A: I think your second try is almost correct. However the fill=... should be inside the aes function and then you need another ```scale_fill_manual````:
  geom_ribbon(aes(ymin = RED.PEAK - RED.PEAK.SD,
                  ymax = RED.PEAK + RED.PEAK.SD, fill = c("black","red","blue")), alpha = 0.1, show.legend = F) +
  scale_fill_manual(values = c("black","red","blue"))


text:
Q: Tangent curve is geodesic on unit sphere I wonder if some one can help me with the following problem:

Let $\gamma: \mathbb{R} \to \mathbb{R}^3$ be a regular curve
  parametrized by arclength. Show that if the tangent curve
  $\dot{\gamma}: \mathbb{R} \to \mathbb{R}^3$ is a non-constant geodesic
  on the unit sphere $S^2$, then the curvature $\kappa$ and torsion
  $\tau$ are constant.

If $\dot{\gamma}$ is a non-constant geodesic on $S^2$, then its second derivative $\gamma^{(3)}$, satisfies $\lVert \gamma^{(3)} \rVert^{\text{tan}}=0$ (it's tangential part is 0). Then it must be parallel to the normal (which on the unit sphere is just the coordinate) so $\gamma^{(3)}=r (x,y,z)$ for some $r$. Is this correct? If yes, how can I proceed from here?


text:
Q: jQuery - Select parent li from Div contents I am trying to select a parent LI depending on what is inside of a div, here is where I am currently...
http://jsfiddle.net/qYdwR/1257/

        Myitem

        John Resig

$( "div:contains('John')" ).css( "text-decoration", "underline" );

This correctly underlines the div containing the word John, I now want it to apply some styling to the parent li that contains this div

A: Use closest to travel up and find the nearest ancestor that matches the selector:
$( "div:contains('John')" ).closest('li').css("text-decoration", "underline")

A: Use .parents() or .parent()
$( "div:contains('John')" ).parents("li:first").css( "text-decoration", "underline" );

another way: use ":has"
$( "li:has(div:contains('John'))" ).css( "text-decoration", "underline" );

A: $( "div:contains('John')" ).css( "text-decoration", "underline" ).parent().css("background-color", "green");

Should do the trick


text:
Q: Google Maps Streetview working on web and emulator. But not working real device black screen Street view that works on web and Android Emulator does not work on real device. I also tested Android 12, Android 9 and Android 13.
Google Maps version on emulator:
11.28.7
Google Maps version on device:
11.60.0703
The result is the same.
For example: 40.036716,42.171997

http://maps.google.com/maps?q=&layer=c&cbll=40.036716,42.171997
String destinationCoord = "40.036716,42.171997";
Uri uri = Uri.parse("google.streetview:cbll=" + destinationCoord);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, uri);
mapIntent.setPackage("com.google.android.apps.maps");
mContext.startActivity(mapIntent);


text:
Q: Is int? thread safe? I know that in .Net all 32-bit types (e.g, int, bool, etc) are thread safe. That is, there won't be a partial write (according to the specifications).
But, does the same apply for int? (nullable int)?

A: The question is poorly worded, and hence the confusion in the answers so far. The question should be "are reads and writes to a variable of type int? guaranteed to be atomic?"
No, absolutely not. The spec is extremely clear on this point:

Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. In addition, reads and writes of enum types with an underlying type in the previous list are also atomic. Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, are not guaranteed to be atomic.

It is entirely possible for a thread to read a partially written value from a shared-memory variable of nullable type.
For example, suppose you have an int? variable x which at present has the value null. It therefore contains an int, set to zero, and a bool, set to false. Now on another thread you write the nullable int "5" to x. It is perfectly legal for another thread to read the non-nullable int zero from x, because the "true" in the bool could be set before the 5 is set to the int.

A: From http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any
  instance members are not guaranteed to be thread safe.

A: No, since an int? is actually a struct (Nullable<int>) composed of an int and a bool.


text:
Q: Summation of a series with certain property The sequence $\{a_n\}$ has the property that $a_1 + a_2+\cdots+a_n = n ^3~~\forall n$. Compute the value of $\frac{1}{a_2} + \frac{1}{a_3}+\ldots+ \frac{1}{a_{2014-1}}$.
I know that I have to somehow a arrange the denominators in such a order that I could take advantage of the property. To add them, I have to multiply the denominators to obtain a common denominators.

A: First observe that
$$
a_n=(a_1+\cdots+a_{n-1}+a_n)-(a_1+\cdots+a_{n-1})=n^3-(n-1)^3=3n^2-3n+1.
$$
Thus
\begin{align}
\frac{1}{a_2-1}+\cdots+\frac{1}{a_{2014}-1}&=\frac{1}{3 (2^2-2)}+\cdots+\frac{1}{3 (2014^2-2014)}=\frac{1}{3}\sum_{k=2}^{2014}\frac{1}{k(k-1)}\\ &=\frac{1}{3}
\sum_{k=2}^{2014}\left(\frac{1}{k-1}-\frac{1}{k}\right)
=\frac{1}{3}\left(\frac{1}{1}-\frac{1}{2014}\right)=\frac{671}{2014},
\end{align}
since
$$
\frac{1}{k(k-1)}=\frac{1}{k-1}-\frac{1}{k}.
$$

A: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left( #1 \right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large a}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$$
a_{n} = \pars{a_{1} + \cdots + a_{n}} - \pars{a_{1} + \cdots + a_{n - 1}}
=n^{3} - \pars{n - 1}^{3} = 3n^{2} - 3n + 1
$$

$$
\sum_{k = 1}^{m}{1 \over a_{k}}
=\sum_{k = 1}^{m}{1 \over 3k^{2} - 3k + 1}
={1 \over 3}\sum_{k = 1}^{m}{1 \over \pars{k - z}\pars{k - z*}}\,,\qquad
z \equiv {1 \over 6}\pars{3 + \root{3}\ic}
$$

\begin{align}
\sum_{k = 1}^{m}{1 \over a_{k}}
&={1 \over 3}\,{1 \over z - z^{*}}
\sum_{k = 1}^{m}\pars{{1 \over k - z} - {1 \over k - z^{*}}}
={1 \over 3}\,{1 \over 2\ic\,\Im\pars{z}}
2\ic\,\Im\sum_{k = 1}^{m}{1 \over k - z}
\\[3mm]&={1 \over 3}\,{1 \over \root{3}/6}\Im\sum_{k = 1}^{m}{1 \over k - z}
={2\root{3} \over 3}\,\Im\sum_{k = 1}^{m}{1 \over k - z}
={2\root{3} \over 3}\,\Im\bracks{\Psi\pars{1 + m - z} - \Psi\pars{1 - z}}
\end{align}

$$\color{#00f}{\large%
\sum_{k = 2}^{m}{1 \over a_{k}}
=
{2\root{3} \over 3}\,\Im\bracks{%
\Psi\pars{m + \half - {\root{3} \over 6}\,i} - \Psi\pars{\half - {\root{3}
\over 6}\,i}} - 1}
$$

$\ds{\Psi\pars{z}}$ is the Digamma Function.


text:
Q: How to add and delete a view in UIscrollview at runtime? My project needs to add and delete a uiwebview to uiscrollview at runtime. Means, when we scroll it horizontally (left or right) when paging is enabled, then a new view get added to the uiscrollview and it traverse to it.
Is it possible to detect the left or right scrolling in uiscrollview?
Plz tell me the best possible solution, sample code or any tutorial.
Thanks in advance

A: In such cases, we should have paging enabled in our scroll view.
Lets say you have scroll view of size 320x480, and it is supposed to show 10 pages, where size of each page is 320x480, making content size of scroll view as 320*10 x 480.
The best way to determine the current page is by using the content offset value of the scroll view.
 So, in the beginning, when scrollview is showing 1st page, its content offset would be x=0, y=0.
For 2nd page x=320, y=0.
 Thus we can get the current page value by dividing the contentOffset.x by page-width.
 Thus, 0/320 = 0, means 1st page. 320/320 = 1, means 2nd page, and so on.
Thus, if we have current page value with us, we can determine in which direction the scroll view is moving, as follows:
-(void) scrollViewDidScroll:(UIScrollView *)scrollView{

    int currentPageOffset = currentPage * PAGE_WIDTH;
    if (self.pageScrollView.contentOffset.x >= currentPageOffset + PAGE_WIDTH) {
        // Scroll in right direction. Reached the next page offset.
        // Settings for loading the next page.
        currentPage = self.pageScrollView.contentOffset.x/PAGE_WIDTH;
    }else if (self.pageScrollView.contentOffset.x <= currentPageOffset - PAGE_WIDTH) {
        // Scroll in left direction. Reached the previous page offset.
        // Setting for loading the previous page.
        currentPage = self.pageScrollView.contentOffset.x/PAGE_WIDTH;
    }

}


text:
Q: Delete file after sharing via intent I'm trying to delete a temporary file after sharing it via android's Intent.ACTION_SEND feature. Right now I am starting the activity for a result and in OnActivityResult, I am deleting the file. Unfortunately this only works if I am debugging it with a breakpoint, but when I let it run freely and say, email the file, the email has no attachment.
I think what is happening is my activity is deleting the file before it had been emailed. What I don't get is why, shouldn't onActivityResult only be called AFTER the other activity is finished?
I have also tried deleting the file in onResume, but no luck.
Is there a better way to do this?

A: I noticed the same behavior with a similar approach. While watching logcat for errors I saw gmail complaining that it couldnt find the attachment. So, yes, it seems the intent returns BEFORE gmail has actually read the file for attachment.
I havent gotten around to a solution yet but it's likely going to be something like:

*

*move the file to some directory so I know it's one I've decided to send

*send it as attachment via ACTION_SEND

*at next onResume for my start screen activity, delete files in the "sent" directory that are older than some time frame that's reasonably long enough for the send to actually have happened

Choosing an appropriate time frame might be tricky since it's probably the case that gmail (or other ACTION_SEND providers) dont actually read the file until it has a network connection. I'm thinking 24 hours should be reasonable and in my case I'm dealing with diagnostic logs so there's no real harm in deleting one too soon if the user has been off network for a long period of time.
If the content of your file is text and it's not obscenely large a simpler approach may be to read the contents of the file and use Intent.putExtra(android.content.Intent.EXTRA_TEXT, yourText) to inline it into the body of the message.

A: What I did is the following.
I used the:
myfile.deleteOnExit();

However, as D.R. mentioned in the comment below correct answer, this does not guarantee the file deletion. This is why I am also deleting the file after the Shared Activity returns. I delete the file if file exists. Because the app crashed sometimes, I put it inside try{} and it works.
I do not know why it does not work for you, but for me it works at least for Gmail attachement, TextSecure, Hangouts.
In class delcaration:
static File file;

In method that calles the Intent:
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("image/png");

        // Compress the bitmap to PNG
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);

        // Temporarily store the image to Flash
        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File (sdCard.getAbsolutePath() + "/FolderName");
        dir.mkdirs();

        // This file is static.
        file = new File(dir, "FileName.png");

        try {
            file.createNewFile();
            FileOutputStream fo = new FileOutputStream(file);
            fo.write(bytes.toByteArray());
            fo.flush();
            fo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Share compressed image
        share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///"+file.getPath()));

        /** START ACTIVITY **/
        startActivityForResult(Intent.createChooser(share,"Share Image"),1);

        // Delete Temporary file
        file.deleteOnExit();     // sometimes works

In an extra method:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Because app crashes sometimes without the try->catch
        try {
            // if file exists in memory
            if (file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            Log.d(LOG,"Some error happened?");
        }

    }

A: This is my working solution. Before startActivity() execute this:
    FileObserver fo = new FileObserver(file,FileObserver.CLOSE_NOWRITE) {
        @Override
        public void onEvent(int event, @Nullable String path) {
            if(event==FileObserver.CLOSE_NOWRITE) {
                file.delete();
                this.stopWatching();
                // HERE: remove the saved reference to 'fo'
            }
        }
    };
    fo.startWatching();
    // HERE: save a reference to 'fo'

Important: You should save the reference to 'fo' so that the FileObserver is not garbage-collected.

A: I have managed to get it to work with:
File tbd = new File(sharePath);
tbd.deleteOnExit();

This seems to delete the file when the activity closes.

A: Another potential answer would be to create a new thread when your app resumes, immediately mark the current time, sleep the thread for however long you feel is reasonable for the file to be sent, and when the thread resumes, only delete files created before the previously marked time. This will give you the ability to only delete what was in the storage location at the time your app was resumed, but also give time to gmail to get the email out. Code snippet: (I'm using C#/Xamarin, but you should get the idea)
public static void ClearTempFiles()
{
    Task.Run(() =>
    {

        try
        {
            DateTime threadStartTime = DateTime.UtcNow;
            await Task.Delay(TimeSpan.FromMinutes(DeletionDelayMinutes));
            DirectoryInfo tempFileDir = new DirectoryInfo(TempFilePath);
            FileInfo[] tempFiles = tempFileDir.GetFiles();
            foreach (FileInfo tempFile in tempFiles)
            {
                if (tempFile.CreationTimeUtc < threadStartTime)
                {
                    File.Delete(tempFile.FullName);
                }
            }
        }
        catch { }
    });
}

@Martijn Pieters This answer is a different solution that handles multiple questions.  If anything, the other questions that I posted on, should be marked as duplicates because they are the same question.  I posted on each of them to ensure that whoever has this problem, can find the solution.


text:
Q: ESLint in class with fat arrow using airbnb rules The following code located in a class that extends React.Component
  nextState = () => {
    this.setState({
      state : this.state.state + 1
    });
  };

However ESLint with airbnb rules catches this and throws the following error:
error  Parsing error: Unexpected token =
I would like to keep this syntax as it allows me to avoid binding this in the constructor.

A: You need to specify Language options. For ref: http://eslint.org/docs/user-guide/configuring#specifying-language-options
You can do this with a single command also inside your .eslintrc file.
{
    "env": {
        "es6": true,
        "node": true
    }
}

A: I struggled with this problem for quite a while.
I found that this configuration of .eslintrc works for your problem.
{
  "extends": "airbnb",
  "parser": "babel-eslint"
}

It works nicely with Sublime Text 3 with SublimeLinter-contrib-eslint.
Note that you need to npm install -g eslint babel-eslint
put .eslintrc in ~/ for global config, put .eslintrc in app folder to overwrite global config.
also note that: Assignment operation inside class is not part of es6, see this link for discussion


text:
Q: Build generator for model predict I'm trying to use generator as the input for model predict function,
prediction = model.predict(generator)

I created my generator in this way
generator = tf.keras.preprocessing.sequence.TimeseriesGenerator(x_feature,y_target, length=n_input,batch_size = 1024)

My question are:
1.Is this a correct way of creating generator for predict function ?
2.If it is, why it takes target value as input, if it's not, what kind of generator is expected here?
I'm using generator since my dataset does not fit my memory, as suggested here, but this question does not show how to create a generator.
Thank you!


text:
Q: How to set permissions with xcacls.vbs We are using xcacls.vbs to modify NTFS permissions (support.microsoft.com/kb/825751) .
syntax:
xcacls.vbs C:\TestFolder /G  DOMAIN\USER: RW /E

RW -Read and Write
F  -Full access
How to give only Read,Write,Modify,Read & Execute permissions ??

A: It's in the document that accompagnes xcacls.vbs, i'll paste it here but you need the following
xcacls.vbs C:\TestFolder /G  DOMAIN\USER: RWMX /E

Here the syntax
    Syntax for the Xcacls.vbs Command
The following output of the xcacls.vbs /? command describes the Xcacls.vbs command syntax:
Usage:
XCACLS filename [/E] [/G user:perm;spec] [...] [/R user [...]]
                [/F] [/S] [/T]
                [/P user:perm;spec [...]] [/D user:perm;spec] [...]
                [/O user] [/I ENABLE/COPY/REMOVE] [/N
                [/L filename] [/Q] [/DEBUG]

   filename            [Required] If used alone, it displays ACLs.
                       (Filename can be a filename, directory name or
                       wildcard characters and can include the whole
                       path. If path is missing, it is assumed to be
                       under the current directory.)
                       Notes:
                       - Put filename in quotes if it has spaces or
                       special characters such as &, $, #, etc.
                       - If filename is a directory, all files and
                       subdirectories under it will NOT be changed
                       unless the /A is present.

   /F                  [Used with Directory or Wildcard] This will change all
                       files under the inputted directory but will NOT
                       traverse subdirectories unless /T is also present.
                       If filename is a directory, and /F is not used, no
                       files will be touched.

   /S                  [Used with Directory or Wildcard] This will change all
                       subfolders under the inputted directory but will NOT
                       traverse subdirectories unless /T is also present.
                       If filename is a directory, and /S is not used, no
                       subdirectories will be touched.

   /T                  [Used only with a Directory] Traverses each
                       subdirectory and makes the same changes.
                       This switch will traverse directories only if the
                       filename is a directory or is using wildcard characters.
   /E                  Edit ACL instead of replacing it.

   /G user:GUI         Grant security permissions similar to Windows GUI
                       standard (non-advanced) choices.
   /G user:Perm;Spec   Grant specified user access rights.
                       (/G adds to existing rights for user)

                       User: If User has spaces in it, enclose it in quotes.
                             If User contains #machine#, it will replace
                             #machine# with the actual machine name if it is a
                             non-domain controller, and replace it with the
                             actual domain name if it is a domain controller.

                             New to 3.0: User can be a string representing
                             the actual SID, but MUST be lead by SID#
                             Example: SID#S-1-5-21-2127521184-160...
                                      (SID string shown has been shortened)
                                      (If any user has SID# then globally all
                                       matches must match the SID (not name)
                                       so if your intention is to apply changes
                                       to all accounts that match Domain\User
                                       then do not specify SID# as one of the
                                       users.)

                       GUI: Is for standard rights and can be:
                             Permissions...
                                    F  Full control
                                    M  Modify
                                    X  read and eXecute
                                    L  List folder contents
                                    R  Read
                                    W  Write
                             Note: If a ; is present, this will be considered
                             a Perm;Spec parameter pair.

                       Perm: Is for "Files Only" and can be:
                             Permissions...
                                    F  Full control
                                    M  Modify
                                    X  read and eXecute
                                    R  Read
                                    W  Write
                             Advanced...
                                    D  Take Ownership
                                    C  Change Permissions
                                    B  Read Permissions
                                    A  Delete
                                    9  Write Attributes
                                    8  Read Attributes
                                    7  Delete Subfolders and Files
                                    6  Traverse Folder / Execute File
                                    5  Write Extended Attributes
                                    4  Read Extended Attributes
                                    3  Create Folders / Append Data
                                    2  Create Files / Write Data
                                    1  List Folder / Read Data
                       Spec is for "Folder and Subfolders only" and has the
                       same choices as Perm.

   /R user             Revoke specified user's access rights.
                       (Will remove any Allowed or Denied ACL's for user.)

   /P user:GUI         Replace security permissions similar to standard choices.

   /P user:perm;spec   Replace specified user's access rights.
                       For access right specification see /G option.
                       (/P behaves like /G if there are no rights set for user.)

   /D user:GUI         Deny security permissions similar to standard choices.
   /D user:perm;spec   Deny specified user access rights.
                       For access right specification see /G option.
                       (/D adds to existing rights for user.)

   /O user             Change the Ownership to this user or group.

   /I switch           Inheritance flag.  If omitted, the default is to not touch
                       Inherited ACL's. Switch can be:
                          ENABLE - This will turn on the Inheritance flag if
                                   it is not on already.
                          COPY   - This will turn off the Inheritance flag and
                                   copy the Inherited ACL's
                                   into Effective ACL's.
                          REMOVE - This will turn off the Inheritance flag and
                                   will not copy the Inherited
                                   ACL's.  This is the opposite of ENABLE.
                          If switch is not present, /I will be ignored and
                          Inherited ACL's will remain untouched.

   /L filename         Filename for Logging. This can include a path name
                       if the file is not under the current directory.
                       File will be appended to, or created if it does not
                       exit. Must be Text file if it exists or error will occur.

                       If filename is omitted, the default name of XCACLS will
                       be used.

   /Q                  Turn on Quiet mode.  By default, it is off.
                       If it is turned on, there will be no display to the screen.

   /DEBUG              Turn on Debug mode. By default, it is off.
                       If it is turned on, there will be more information
                       displayed and/or logged. Information will show
                       Sub/Function Enter and Exit as well as other important
                       information.

   /SERVER servername  Enter a remote server to run script against.

   /USER username      Enter Username to impersonate for Remote Connections
                            (requires PASS switch).  Will be ignored if it is for a Local Connection.

   /PASS password      Enter Password to go with USER switch
                            (requires USER switch).

Wildcard characters can be used to specify more than one file in a command, such as:
                                *       Any string of zero or more characters
                                ?       Any single character

You can specify more than one user in a command.
You can combine access rights.

back to the top
Use Xcacls.vbs to View Permissions

You can also use Xcacls.vbs to view permissions for files or folders. For example, if you have a folder that is named C:\Test, type the following at a command prompt to view the folder permissions, and then press ENTER:
xcacls.vbs c:\testThe following example is a typical result:
C:\>XCACLS.VBS c:\test
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

Starting XCACLS.VBS (Version: 3.4) Script at 6/11/2003 10:55:21 AM

Startup directory:
"C:\test"

Arguments Used:
        Filename = "c:\test"

**************************************************************************
Directory: C:\test

Permissions:
Type     Username                Permissions           Inheritance

Allowed  BUILTIN\Administrators  Full Control          This Folder, Subfolde
Allowed  NT AUTHORITY\SYSTEM     Full Control          This Folder, Subfolde
Allowed  Domain1\User1           Full Control          This Folder Only
Allowed  \CREATOR OWNER          Special (Unknown)     Subfolders and Files
Allowed  BUILTIN\Users           Read and Execute      This Folder, Subfolde
Allowed  BUILTIN\Users           Create Folders / Appe This Folder and Subfo
Allowed  BUILTIN\Users           Create Files / Write  This Folder and Subfo

No Auditing set

Owner: Domain1\User1

Note The output of the xcacls.vbs c:\test command in this example matches the text that is shown in the graphical user interface (GUI). Some words are incomplete in the command window.

The output also gives the version of the script, the startup directory, and the arguments that were used.

You can also use wildcard characters to display matching files under the directory. For example, if you type the following, all files with an extension of ".log" that are in the C:\Test folder are displayed:
xcacls.vbs c:\test\*.logback to the top

Examples
The following Xcacls.vbs commands provide some examples of Xcacls.vbs usage.
xcacls.vbs c:\test\ /g domain\testuser1:f /f /t /e

This command edits existing permissions. It grants Domain\TestUser1 full control
on all files under C:\Test, it traverses subfolders under C:\Test, and then it
changes any files that are found. This command does not touch directories.
xcacls.vbs c:\test\ /g domain\testuser1:f /s /l "c:\xcacls.log"

This command replaces existing permissions. It grants Domain\TestUser1 full
control on all subfolders under C:\Test, and it logs to C:\Xcacls.log. This
command does not touch files, and it does not traverse directories.
xcacls.vbs c:\test\readme.txt /o "machinea\group1"

This command changes the owner of Readme.txt to be the group MachineA\Group1.
xcacls.vbs c:\test\badcode.exe /r "machinea\group1" /r "domain\testuser1"

This command revokes the permissions to C:\Test\Badcode.exe for MachineA\Group1
and for Domain\TestUser1.
xcacls.vbs c:\test\subdir1 /i enable /q

This command turns on inheritance on the folder C:\Test\Subdir1. It suppresses
any screen output.
xcacls.vbs \\servera\sharez\testpage.htm /p "domain\group2":14

This command remotely connects to \ServerA\ShareZ by using Windows Management
Instrumentation (WMI). It then obtains the local path for that share, and under
that path, it changes the permissions on Testpage.htm. It leaves the existing
permissions of Domain\Group2 intact, but it adds permissions 1 (read data) and
4 (read extended attributes). The command drops other permissions on the file
because the /e switch was not used.
xcacls.vbs d:\default.htm /g "domain\group2":f /server servera /user servera\admin /pass password /e

This command uses WMI to remotely connect as ServerA\Admin to ServerA and then
grants full permissions on Default.htm to Domain\Group2. Existing permissions
for Domain\Group2 are lost and other permissions on the file remain.back to
the top


text:
Q: New everyplay game Ads SDK (Unity ads) gives error Well Yesterday (13,06,2014) Everyplay send a email and they said "new SDK published" but after establishing this SDK it gives this error and dont show any ads. in past it didnt give this error.

06-14 10:42:00.460: E/UnityAds(32338): com.unity3d.ads.android.d.a.a() (line:-1) :: Couldn't get isDestroyed -method
  06-14 10:42:06.055: E/UnityAds(32338): com.unity3d.ads.android.campaign.UnityAdsCampaign.shouldCacheVideo() (line:-1) :: Key not found for campaign: 000000000000000000000001
  06-14 10:42:06.055: E/UnityAds(32338): com.unity3d.ads.android.campaign.UnityAdsCampaign.shouldCacheVideo() (line:-1) :: Key not found for campaign: 000000000000000000000001
  06-14 10:42:06.055: E/UnityAds(32338): com.unity3d.ads.android.campaign.UnityAdsCampaign.shouldCacheVideo() (line:-1) :: Key not found for campaign: 000000000000000000000002
  06-14 10:42:06.055: E/UnityAds(32338): com.unity3d.ads.android.campaign.UnityAdsCampaign.shouldCacheVideo() (line:-1) :: Key not found for campaign: 000000000000000000000002
  06-14 10:42:19.318: E/UnityAds(32338): com.unity3d.ads.android.UnityAds.show() (line:-1) :: Could not find activity: [Ljava.lang.StackTraceElement;@4230b028

A: Make sure you've double checked the migration guide, "Could not find activity:" sounds like you've upgraded the JAR used, but not the new AndroidManifest.xml contents.
SDK internals, build system and integration have been polished a bit when upgrading from Applifier Impact/Everyplay GameAds era to Unity Ads SDK.
With Android version, it means that there's a new Android project library that's preferred to be used instead of manually fiddling with JAR's and adding stuff to AndroidManifest.xml, with library projects it's handled automatically. The base class initialisation and singleton pattern has also been upgraded to be safer and easier to use
Importing new library project: https://github.com/Applifier/unity-ads/wiki/Integration-Guide-for-Android
Migration guide: https://github.com/Applifier/unity-ads/wiki/Transition-from-Applifier-Impact-and-Everyplay-GameAds


text:
Q: Get parameter names collection from Java/Android url It's absolutely strange, but I can't find any Java/Android URL parser that will be compatible to return full list of parameters.
I've found java.net.URL and android.net.Uri but they are can't return parameters collection.
I want to pass url string, e.g.
String url = "http://s3.amazonaws.com/?AWSAccessKeyId=123&Policy=456&Signature=789&key=asdasd&Content-Type=text/plain&acl=public-read&success_action_status=201";

SomeBestUrlParser parser = new SomeBestUrlParser(url);
String[] parameters = parser.getParameterNames();
// should prints array with following elements
// AWSAccessKeyId, Policy, Signature, key, Content-Type, acl, success_action_status

Does anyone know ready solution?

A: This static method builds map of parameters from given URL

private Map<String, String> extractParamsFromURL(final String url) throws URISyntaxException {
    return new HashMap<String, String>() {{
        for(NameValuePair p : URLEncodedUtils.parse(new URI(url), "UTF-8"))
            put(p.getName(), p.getValue());
    }};
}

usage

extractParamsFromURL(url).get("key")

A: Have a look at URLEncodedUtils

A: There is way to get collection of all parameter names.
String url = "http://domain.com/page?parameter1=value1&parameter2=value2";
List<NameValuePair> parameters = URLEncodedUtils.parse(new URI(url));
for (NameValuePair p : parameters) {
    System.out.println(p.getName());
    System.out.println(p.getValue());
}

A: UrlQuerySanitizer added in API level 1
        UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(url_string);
        List<UrlQuerySanitizer.ParameterValuePair> list =  sanitizer.getParameterList();
        for (UrlQuerySanitizer.ParameterValuePair pair : list) {
            System.out.println(pair.mParameter);
            System.out.println(pair.mValue);
        }

A: The urllib library will parse the query string parameters and allow you to access the params as either a list or a map. Use the list if there might be duplicate keys, otherwise the map is pretty handy.
Given this snippet:
String raw = "http://s3.amazonaws.com/?AWSAccessKeyId=123&Policy=456&Signature=789&key=asdasd&Content-Type=text/plain&acl=public-read&success_action_status=201";
Url url = Url.parse(raw);
System.out.println(url.query().asMap());
for (KeyValue param : url.query().params()) {
  System.out.println(param.key() + "=" + param.value());
}

The output is:
{Policy=456, success_action_status=201, Signature=789, AWSAccessKeyId=123, acl=public-read, key=asdasd, Content-Type=text/plain}
AWSAccessKeyId=123
Policy=456
Signature=789
key=asdasd
Content-Type=text/plain
acl=public-read
success_action_status=201


text:
Q: Get Value of Variable stops appending on last call & sets result to only that last variable I have created a simple workflow in Automator to ask questions & send an email. I followed the tutorial at https://macmost.com/create-customizable-text-inserts-using-automator.html. This has worked for me in different usages, but in this workflow, I have an issue. Near the end of the workflow, multiple variables are retrieved using "Get Value of Variable" to create a message consisting of them all. As each variable is retrieved, it is added to the last variables. However, the last get value of the variable I use deletes all of the other variables which were previously shown in "results" and the result becomes only that variable.
I have attached an image for reference. As you can see it continues to increase (4 items, 5 items), but when the last variable is got, it deletes all of the other items & is set to 1 item.
I have tried deleting the ask for text/set variable for the last statement, and it results in the issue occurring on the "new" get value of variable.

A: Running your workflow unedited...
In the fifth Get Value of Variable action, when running the original workflow, its Results, with the list button selected, was, e.g.,:
(
  "<NSAppleEventDescriptor: [ 'utxt'("Hey") ]>",
  "What's Up?",
  "1-3",
  "<NSAppleEventDescriptor: [ 'utxt'("Full QA") ]>",
  "<NSAppleEventDescriptor: [ 'utxt'("aren't") ]>"
)

In the sixth Get Value of Variable action, when running the original workflow, its Results, with the list button selected, was, e.g.,:
(
  "<NSAppleEventDescriptor: [ 'utxt'("Thank you") ]>"
)

When it would have beed expected to be, e.g.,:
(
  "<NSAppleEventDescriptor: [ 'utxt'("Hey") ]>",
  "What's Up?",
  "1-3",
  "<NSAppleEventDescriptor: [ 'utxt'("Full QA") ]>",
  "<NSAppleEventDescriptor: [ 'utxt'("aren't") ]>"
  "<NSAppleEventDescriptor: [ 'utxt'("Thank you") ]>"
)

Just to test something out, I converted all the Ask for Text actions to Run AppleScript actions that did the same thing, and initially converted all but the last Run JavaScript actions to Run AppleScript action and everything worked.
I then converted the last remaining Run JavaScript action to Run AppleScript action and everything worked. I did this because of the differences in how each variable was being saved/returned. Thus by making all the variables the same type/class it worked.
In the fifth Get Value of Variable action, when running the edited workflow, its Results, with the list button selected, was, e.g.,:
{"Hey", "What's Up?", "1-3", "Full QA", "aren't"}

In the sixth Get Value of Variable action, when running the edited workflow, its Results, with the list button selected, was, e.g.,:
{"Hey", "What's Up?", "1-3", "Full QA", "aren't", "Thank you"}

As you can see in the example results what's returned is a plain list of text strings not mixed as in the output of the original workflow.
The end result was, e.g.,:

While I can not say for sure, nonetheless, it looks like there may be some sort of bug with the type/class count when stacking more than five Get Value of Variable actions and why it does not fail when all have been acquired, set and retrieved when done using the same type of actions.

Here is a link for the edited workflow: Send_QA_Mail_Test.zip

*

*SHA1: dfdec5414d0d5e22c46ad444b7bb77f19b442a45

A: I had encountered same problem when some "Get Value of Variable"s were set after "Run AppleScript".

After all, I adopt workaround that is set "Run Shell Script" imedeatelly after "Run AppleScript".
In "Run Shell Script" just execute "cat".


text:
Q: Content of element doesn't refresh after onBlur action I try to edit content of an select input when text entered to a textbox by using jQuery.
This is my TextBox
<input id="id_subsector_selector" type="text" maxlength="100" name="subsector_selector" onblur="onSubSectorSelectorChange(this);"/>
and this is my multiple selectbox
<select id="id_subsector" name="subsector" multiple="multiple">
<option value="14">Yazılımevi </option>
</select>
This is my javascript function(I know this is trivial)
function onSubSectorSelectorChange(item) {
    $('select#id_subsector').html("");
}

The question is when I enter a character to the textbox, althought onSubSectorSelectorChange function is triggered, selectbox content doesn't change until I click on somewhere on page or press tab button.
The problem may be the trigger action which is "onBlur" but I couldn't find a proper function.
I am waiting for any comment or solution!
Thanks

A: blur is triggered when the element loses focus. What you are after is the keyup event:
http://api.jquery.com/keyup/

A: If you want execute the method onSubSectorSelectorChange on keydown, you need use attribute onkeydown instead. The onblur will work only if you change focus.
Take a look about onkeydown, onkeypress and onkeyup attributes.

A: Get rid of the onblur attribute althogether, and late-bind in document.ready() event to the keyup event:
$(document).ready(function(){
    $("#id_subsector").keyup(function(){
        onSubSectorSelectorChange(this);
    });
});

Or even more concisely:
$(document).ready(function(){
    $("#id_subsector").keyup(function(){
        $(this).html("");
    });
});


text:
Q: One thread is always running without a chance for other threads Why the main thread is never executed? I thought that is I use Thread.sleep(int value) I give a chance to other threads to run, but this never happen.
    public static void main(String[] args) {
        final Sook o = new Sook();
        Thread t = new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(10000); // Specially set to give a chance to the main thread to run
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        t.run();

        System.out.println("<<<<<BACK TO MAIN >>>>>>"); // Never happens
    }

A: Do not call, t.run(), call t.start()
Just run will call the run method in the currently Thread.


text:
Q: How to group this dataframe in python? I have this problem:
import pandas as pd

stripline = "----------------------------"

rawData = {
    'order number': ['11xa', '11xa', '11xa', '21xb', '31xc'],
    'working area': ['LLA', 'LLE', 'LLS', 'MLA', 'MLE'],
    'time': [1, 6, 13, 35, 24]
}

df = pd.DataFrame(rawData)
print("original data:")
print(df.head())

print(stripline)

rawData2 = {
    'order number': ['11xa', '21xb', '31xc'],
    'working area': ['LLS', 'MLA', 'MLE'],
    'time': [20, 35, 24]
}
df2 = pd.DataFrame(rawData2)

print("expected result:")
print("group after order number, sum all times to that order and choose working field with the biggest time")
print(df2.head())

How can I manipulate my dataframe df to get the df2?
I want to sum up all values in the time column that correspond to an order number. I want to use the working field with the highest time and especially I want to keep the rest of the data. The new data frame has three orders, the old one five.

A: import pandas as pd

rawData = {
    'order_number': ['11xa', '11xa', '11xa', '21xb', '31xc'],
    'working_area': ['LLA', 'LLE', 'LLS', 'MLA', 'MLE'],
    'time': ['1', '6', '13', '35', '24']
    }

df = pd.DataFrame(rawData)
df['time'] = df['time'].apply(int)
df = df.groupby('order_number', as_index=False).apply(lambda g: g.assign(sum=g.time.sum()))
df.groupby('order_number', ascending=False).apply(lambda x: x.sort_values('time').head(1)).reset_index(drop=True)

gives you
  order_number working_area  time  sum
0         11xa          LLA     1   20
1         21xb          MLA    35   35
2         31xc          MLE    24   24

A: rawData = {
    'order number': ['11xa', '11xa', '11xa', '21xb', '31xc'],
    'working area': ['LLA', 'LLE', 'LLS', 'MLA', 'MLE'],
    'time': ['1', '6', '13', '35', '24']
}

dataframe = pd.DataFrame(rawData)
dataframe['time'] = dataframe['time'].astype(int)
dataframe.groupby(['order number']).sum().reset_index()

output
order number    time
0     11xa     20
1     21xb     35
2     31xc     24

A: Try like this , you can use agg to do this : (nb : small changes in the column names) :
rawData = {
    'order_number': ['11xa', '11xa', '11xa', '21xb', '31xc'],
    'working_area': ['LLA', 'LLE', 'LLS', 'MLA', 'MLE'],
    'time': ['1', '6', '13', '35', '24']
    }

df = pd.DataFrame(rawData)
df['time'] = df['time'].apply(int)
df = df.sort_values(['time'], ascending=True)

df = df.groupby(['order_number'], as_index=False).agg(dict(working_area='last', time='sum'))

Output :
   order_number  time working_area
0         11xa    20          LLS
1         21xb    35          MLA
2         31xc    24          MLE


text:
Q: Как работают крупные проекты, которые используют несколько серверов? Никогда не задумывался как работают проекты, которые используют несколько серверов.
Я нарисовал схемку (на ней все указано, но не знаю, верно ли). Если не верно, можете поправить или покидать статей на эту тему.


text:
Q: What will be the behavior of the index in these two scenarios in relation databases like mysql? Let's say I have a table students with the following fields

id,student_id,test_type,score

Consider these two queries

select * from students where student_id = x and score > y
  select * from students where student_id = x order by score

Let's say I have indexes on both student_id and score but not a composite index, what will be the indexes that will be used by the database? Will the query be able to use both of the indexes or whether at max one index can be used?
Let's say with the student_id index I am able to restrict the results in the query, will I be able to use the score index to sort or filtering?
or if databases chooses the score index to sort or filter first, will I be able to student_id index for student_id =x filtering?

A: MySQL's optimizer would like the composite INDEX(student_id, score) for both queries.
Without the composite index...  The optimizer almost never uses two indexes.  The optimizer would pick between INDEX(student_id) and INDEX(score).
But there is another wrinkle -- If this table is InnoDB, and if it has PRIMARY KEY(student_id), then INDEX(score) implicitly has student_id tacked on then end.  HenceINDEX(score)` would be perfect for the first query.
Given two indexes, the optimizer looks at cardinality and various other things to pick between them.
More on creating the best index.

A: Well it definitely depends on your data set and database. Imagine in the students table if I have 100 different id's but the same student_id. The student_id index would be considered bad and the *Teradata Query Optimizer would be smart enough to choose a better one like score or id. (If using Teradata DB, but most have built in smart features like this). A Composite Index certainly wouldn't be selected because WHY? I think in this tables case wouldn't help fetch at all. The best way to select a good index is to ask okay which column can provide me a solid unique value that is inexpensive (Integer) and can eliminate a good partition or chunk of data if selected. But yes student_id would be the best index in this case. Plus the query that ends with "and score > y" would be quicker. Where clause is always seen first so dataset will be much smaller.


text:
Q: How to make a number with commas as thousands separator in table, javascript I want to print an integer with a comma as a separator, for example 10,234,234
in the price column.
I have made the function, but I am a little confused how to make it in the table.  Below is my code

       Item
      Price

      @foreach (SHOP.ViewModels.ItemViewModel item in Model.Itemss)
      {

            @Html.DisplayFor(modelitem => item.itemName)
            @Html.DisplayFor(modelitem => item.itemPrice)

      }

             @Html.EditorFor(model => model.TotalPrice, new { htmlAttributes = new { @class = "form-control", @onchange = "validationCheck();", @readonly = "readonly" } })

A: You need to get all second td elements in the table and then update the content using the code.

       Item
      Price

      @foreach (SHOP.ViewModels.ItemViewModel item in Model.Itemss)
      {

            @Html.DisplayFor(modelitem => item.itemName)
            @Html.DisplayFor(modelitem => item.itemPrice)

      }

FYI : It's always better to do it from the backend side if possible. There may be some functions available in your backend framework/programming language.

UPDATE : In your updated code you are creating an input so get input element update it's value.

       Item
      Price

      @foreach (SHOP.ViewModels.ItemViewModel item in Model.Itemss)
      {

            @Html.DisplayFor(modelitem => item.itemName)
            @Html.DisplayFor(modelitem => item.itemPrice)

      }

             @Html.EditorFor(model => model.TotalPrice, new { htmlAttributes = new { @class = "form-control", @onchange = "validationCheck();", @readonly = "readonly" } })

A: You can use toLocaleString to display a number with comma separators
let num = 1000000
let display = num.toLocaleString('us-US')
console.log(display)   // 1,000,000

I suspect your code could work like this
@foreach (SHOP.ViewModels.ItemViewModel item in Model.Itemss)
  {

        @Html.DisplayFor(modelitem => item.itemName)
        @Html.DisplayFor(modelitem => item.itemPrice.toLocaleString('us-US'))

  }


text:
Q: Proof by induction regarding injections and part of the pigeonhole principle Prove the following implication by induction on $m$:
If there exists an injection $N_m \rightarrow N_n$, then $m \le n$.
$N_n$ and $N_m$ are sets with $n$ and $m$ elements, respectively.
I know how to do proofs by induction, I'm just struggling with the inductive step. So far I have the predicate P(n) = If there exists an injection $N_m \rightarrow N_n$, then $m \le n$.
I proved the base case "P(1) = If there exists an injection $N_1 \rightarrow N_n$, then $1 \le n$" sloppily by saying no element in $N_n$ could be assigned to more than one element of $N_1$ because there is only a single element in $N_1$. There must at least one element in $N_n$ in order for it to be a function, so $1 \le n$.
So I know the inductive hypothesis is P(k) = If there exists an injection $N_k \rightarrow N_n$, then $k \le n$. Now I need to prove P(k+1) = If there exists an injection $N_{k+1} \rightarrow N_n$, then $k+1 \le n$, but I'm clueless about how to do this step.

A: For any $f: N_m \rightarrow N_n$, if $m > n$ then by the Pigeonhole Principle (at least) two elements of $N_m$ must be sent to the same element of $N_n$. Then $f$ is not injective. Now take the contrapositive.
Factoid: (which I think is not well-known?) the Pigeonhole Principle is very similar to the Principle of Mathematical Induction. See, for example, this article. However, criticisms can be found here as well as in The complexity of the Pigeonhole Principle by M. Ajtai, in which PHP is shown to be (in some sense) stronger than PMI.

A: The statement is true for $m=1$: If there is a map $f:\{1\}\to N_n$ then necessarily $n\geq1$.
Assume that the statement is true for  $m\geq1$ and that we are given an injective map $f:\ [m+1]\to [n]$. We have to prove that $m+1\leq n$. We distinguish two cases:
(a) $\quad f(r)\ne n$ for all $r\in[m]$.
In this case restricting $f$ to $[m]$ provides an injective map $f':\ [m]\to[n-1]$. By the induction hypothesis it follows that $m\leq n-1$. Therefore we have $m+1\leq n$ in this case.
(b) $\quad f(r)=n$ for a unique $r\in[m]$.
In this case $f(m+1)<n$. Therefore the new function
$$f'(k):=\cases{f(k) &$k\in[m], \ k\ne r$\cr f(m+1) &$(k=r)$\cr}$$
is an injective function $f':\ [m]\to[n-1]$. By the induction hypothesis it again follows that $m\leq n-1$, or $m+1\leq n$.


text:
Q: Destination table becomes truncated at start of running Kettle script I have a kettle script that reads from Table A, parses the data then sends them to Table 1 and Table 2. From the whole kettle script, I disabled the branch that populates Table 2 and ran the script; from this, Table 1 is populated. After this I did the other way around to populate the other table (Table2). That is, I disabled the branch that populates Table 1. When the script was running, I noticed that Table1 is being truncated while Table2 is being populated. After the whole migration script has finished, both tables are populated.
I also noticed this 'Truncate Table' flag in the destination table. I just don't understand why the truncation is necessary given that I disabled the branch that runs it. Any explanations for this?

A: The truncation happens when the step is initialized. Regardless of the incoming hop being enabled or disabled, the truncation will always happen. Same happens in steps like Text file output, where a 0 byte file is created when the transformation starts.


text:
Q: Rails Tutorial - Errors with User.rb File I'm following the railstutorial.org chapter 7 - I'm trying to run the app but getting errors with the following code. The error suggests I need another "end" at the end of the file -- but I've tried this and it hasn't worked.
The error is:
/Users/woshea/rails/sample_app2/app/models/user.rb:58: syntax error, unexpected kEND, expecting $end

The code is here:
require 'digest'

class User < ActiveRecord::Base
  attr_accessor :password
    attr_accessible :name, :email, :password, :password_confirmation

  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :name,  :presence => true,
                    :length   => { :maximum => 50 }
   validates :email, :presence   => true,
             :format     => { :with => email_regex },
             :uniqueness => { :case_sensitive => false }
   validates :password, :presence     => true,
             :confirmation => true,
             :length       => { :within => 6..40 }

end

before_save :encrypt_password

def has_password?(submitted_password)
  encrypted_password == encrypt(submitted_password)
end

  private

     def encrypt_password
       self.salt = make_salt if new_record?
       self.encrypted_password = encrypt(password)
     end

     def encrypt(string)
       secure_hash("#{salt}--#{string}")
     end

     def make_salt
       secure_hash("#{Time.now.utc}--#{password}")
     end

     def secure_hash(string)
       Digest::SHA2.hexdigest(string)
     end

end
end
end

A: try this:
require 'digest'

class User < ActiveRecord::Base
  attr_accessor :password
    attr_accessible :name, :email, :password, :password_confirmation

  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :name,  :presence => true,
                    :length   => { :maximum => 50 }
   validates :email, :presence   => true,
             :format     => { :with => email_regex },
             :uniqueness => { :case_sensitive => false }
   validates :password, :presence     => true,
             :confirmation => true,
             :length       => { :within => 6..40 }

before_save :encrypt_password

def has_password?(submitted_password)
  encrypted_password == encrypt(submitted_password)
end

  private

     def encrypt_password
       self.salt = make_salt if new_record?
       self.encrypted_password = encrypt(password)
     end

     def encrypt(string)
       secure_hash("#{salt}--#{string}")
     end

     def make_salt
       secure_hash("#{Time.now.utc}--#{password}")
     end

     def secure_hash(string)
       Digest::SHA2.hexdigest(string)
     end

end