text:
Q: Populate Listview from Google Books JSON I'm using Google Books API for searching books. But problem is that when I want my ListView to be populated with books, I get an error. This error is pointed onPostExecute, but I can't figured out what's the problem.
 kotlin.KotlinNullPointerException
    at com.example.claudiu.reader.Fragments.ISBNFragment$FetchBookTask.onPostExecute(ISBNFragment.kt:137)
    at com.example.claudiu.reader.Fragments.ISBNFragment$FetchBookTask.onPostExecute(ISBNFragment.kt:56)

Here is where I set my adapter :
 override fun onPostExecute(books: List<Book>?) {
        if (books != null) {
            adapter!!.clear()
            for (book in books) {
                adapter!!.add(book)
            }
        }
    }

And here is all code where I'm parsing the JSON:
  @Throws(JSONException::class)
    private fun getBookDataFromJson(booksJsonStr: String?): List<Book> {

        val books = ArrayList<Book>()

        val API_RESULT_ITEMS_ARRAY = "items"
        val API_VOLUME_INFO = "volumeInfo"
        val API_BOOK_TITLE = "title"
        val API_BOOK_IMAGE_LINKS = "imageLinks"
        val API_BOOK_SMALL_THUMBNAIL = "smallThumbnail"
        val API_BOOK_AUTHORS_ARRAY = "authors"

        val booksJson = JSONObject(booksJsonStr)
        val itemsArray = booksJson.getJSONArray(API_RESULT_ITEMS_ARRAY)

        for (i in 0 until itemsArray.length()) {

            val item = itemsArray.getJSONObject(i)
            val volumeInfo = item.getJSONObject(API_VOLUME_INFO)

            val bookTitle = volumeInfo.getString(API_BOOK_TITLE)

            val imageLinksSB = StringBuilder()
            if (!volumeInfo.isNull(API_BOOK_IMAGE_LINKS)) {
                val imageLinks = volumeInfo.getJSONObject(API_BOOK_IMAGE_LINKS)
                imageLinksSB.append(imageLinks.getString(API_BOOK_SMALL_THUMBNAIL))
            } else {
                imageLinksSB.append("-1")
            }
            val bookImageLink = imageLinksSB.toString()

            val authorsSB = StringBuilder()
            if (!volumeInfo.isNull(API_BOOK_AUTHORS_ARRAY)) {
                val authorsArray = volumeInfo.getJSONArray(API_BOOK_AUTHORS_ARRAY)
                for (k in 0 until authorsArray.length()) {
                    authorsSB.append(authorsArray.getString(k))
                    authorsSB.append(getString(R.string.comma))
                }
            } else {
                authorsSB.append(getString(R.string.unknown_error))
            }
            val bookAuthors = authorsSB.toString()

            books.add(Book(bookTitle, bookAuthors, bookImageLink))
        }

        Log.d(LOG_TAG, "BOOKS : $books")
        return books
    }

I couldn't find any thing to help me and I have no idea what should I do.

A: Your problem is the place where you declare your adapter, I had this problem because declaration of my adapter was in the wrong place.
You should move adapter declaration from onCreatView into onViewCreated and everything will work fine.
Hope it helps !


text:
Q: Directline with Polyfill ES5 in IE I am currently having an issue with the botchat framework from Microsoft.
In essence, they are saying that for the framework to work in I.E., all you have to do is change the script for their webchat-es5.js version. However, this still does not work at all in IE. I am using IE 11. All other browsers work fine, except IE.
Could someone please point me in the right direction so that I may have this ChatBot actually work in IE?
Here is the code I am using for all of this stuff:
Relevant HTML:

Relevant JavaScript:
 const styleOptions =
    {
        accent: '#0063B1',
        backgroundColor: 'White; border:2px solid #23447e; border-radius: 25px; padding-top:20px',
        cardEmphasisBackgroundColor: '#F0F0F0',
        paddingRegular: 10,
        paddingWide: 10 * 2,
        subtle: '#767676',
        bubbleBackground: '#CCCCCC',
        bubbleBorder: 'solid 1px #E6E6E6',
        bubbleBorderRadius: 10,
        bubbleFromUserBackground: '#0084ff',
        bubbleFromUserBorder: 'solid 1px #E6E6E6',
        bubbleFromUserBorderRadius: 10,
        bubbleFromUserTextColor: 'White',
        bubbleImageHeight: 100, //240,
        bubbleMaxWidth: 480, // screen width = 600px
        bubbleMinHeight: 40,
        bubbleMinWidth: 250, // min screen width = 300px, Edge requires 372px (https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/13621468/)
        bubbleTextColor: 'Black',
        // Send box
        hideSendBox: false,
        hideUploadButton: false,
        microphoneButtonColorOnDictate: '#F33',
        sendBoxBackground: 'White',
        sendBoxButtonColor: '#767676',
        sendBoxButtonColorOnDisabled: '#CCC',
        sendBoxButtonColorOnFocus: '#333',
        sendBoxButtonColorOnHover: '#333',
        sendBoxHeight: 40,
        sendBoxMaxHeight: 200,
        sendBoxTextColor: 'Black',
        sendBoxBorderBottom: '',
        sendBoxBorderLeft: '2px solid #23447e; border-radius: 25px',
        sendBoxBorderRight: '2px solid #23447e; border-radius: 25px',
        sendBoxBorderTop: '2px solid #23447e; border-radius: 25px',
        sendBoxPlaceholderColor: '#23447e',
        sendBoxTextWrap: false,
        typingAnimationBackgroundImage: 'https://support.signal.org/hc/article_attachments/360016877511/typing-animation-3x.gif',
        spinnerAnimationBackgroundImage: 'https://support.signal.org/hc/article_attachments/360016877511/typing-animation-3x.gif',
        avatarSize: 80,
        botAvatarImage: 'https://s3.gifyu.com/images/oie_3BXuLVEkv2Ad.gif',
        userAvatarImage: 'https://i.ibb.co/5xz4X4P/kissclipart-generic-person-icon-clipart-computer-icons-person-96a092499db1d0d3.png',
        botAvatarInitials: '',
        userAvatarInitials: ''
    };

const token = 'MY TOKEN SECRET IS HERE';

const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
    if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
        dispatch({
            type: 'WEB_CHAT/SEND_EVENT',
            payload: {
                name: 'webchat/join',
                value: { language: window.navigator.language }
            }
        });
    }
    return next(action);
});

window.WebChat.renderWebChat({
    directLine: window.WebChat.createDirectLine({ token }),
    styleOptions
}, document.getElementById("webchat"));

I've also tried their other version of rendering/creating the webchat :
window.fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { method: 'POST' })
.then(function (res) {
  return res.json();
})
.then(function (json) {
  const token = json.token;
  window.WebChat.renderWebChat({
    directLine: window.WebChat.createDirectLine({
      token: token
    })
  }, document.getElementById('webchat'));
  document.querySelector('#webchat > *').focus();
});

With this instantiated version, it still doesn't work in IE, and in other browsers, it loads the MockBot from GitHub instead of my own chatbot.

A: Arrow functions in IE11 are not supported, so you store middleware is causing the problem. Take a look at the code snippet below.
<!DOCTYPE html>

    <title>Web Chat: Full-featured bundle with ES5 polyfills</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

Hope this helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: use jquery to load different divs into popup div I have a popup div that I need to load a bunch of different divs with custom ids.
for example say we have recipepopup1 recipepopup2 and recipepopup3 each of which have a recipebutton1, recipebutton2 recipebutton3 respectively  and then we have another div to load the recipepopup1..recipepopup3 into called recipe_popup.
how can i have it so when i click button1 it will load div1 into popupdiv and if i click button2 it will load div2 into recipe_display etc.
right now I am using replaceWith() and i have found that it replaces the id of the recipe_pop div with recipepopup1 when i click button1 so when i click recipepopup2 it just loads the div outside of the recipe_popup div
one more thing to note is that each of the recipepopup should be able to be loaded infinitely many times - so when i close the popup and click a recipebutton that has already been clicked it will still popup the relevant div
thanks for any help :)
katie
here is my current code:
<script type="text/javascript">
$(document).ready(function(){
    $("#recipebutton1").click(function(){
        $('#create_form_span').css('display', 'none');
        $(".recipepopup").css('display','none');
        $("#recipe_display").replaceWith($('#recipepopup1').css('display','block'));
    });
    $("#recipebutton2").click(function(){
        $('#create_form_span').css('display', 'none');
        $(".recipepopup").css('display','none');
        $("#recipe_display").replaceWith($('#recipepopup2').css('display','block'));
    });
    $("#recipebutton3").click(function(){
        $('#create_form_span').css('display', 'none');
        $(".recipepopup").css('display','none');
        $("#recipe_display").replaceWith($('#recipepopup3').css('display','block'));
    });

});
</script>

A: I think you can use $("#recipe_display").html($('#recipepopup2').html())
Hope it helps.


text:
Q: postgresql sticking "enable_seqscan=False" in a UDF sensible? I have a query which is taking 40 seconds to execute over the 80ms that it should if postgres where to filter off the primary key rather than doing a sequential scan. I have to force postgres to filter off the index by setting the above flag.
Having to stick this into the UDF seems like quite a hack to me, I mean it's unreasonable IMO that the query planner is chosing a seq scan over a indexed filter. Most of my SQL experience is off SQL Server, and I haven't experienced it missplaning such basic optimizations.
Edit:
To anyone interested, the query exeuction time droped from 80ms to 27 ms with 9.2, holly molley.

A: enable_seqscan=true doesn't do what you think it will.  It only allows the planner to choose that.  It doesn't force it.
Note it should be on generally anyway.  Sequential scans are far less costly in PostgreSQL than in MySQL since they scan in physical order.  There are many times when they are the cheaper plan.

A: Do not set it globally, that would lead to terrible query plans. But there are sensible use cases for enable_seqscan=False. I quote the manual here:

It is impossible to suppress sequential scans entirely, but turning
this variable off discourages the planner from using one if there are
other methods available. The default is on.

So, if for some reason, the planner keeps picking a sequential scan where another type of scan would be faster, this could be your ugly fix - for this query only. If no other route is available, Postgres will still use a sequential scan.
Of course, in most cases you are just covering up the underlying problem - the planner should not be that wrong to begin with. You may want to start digging what's wrong in your setup. Is autovacuum on (default), so ANALYZE is run against your tables automatically? Try a manual
ANALYZE mytable

Or even:
VACUUM FULL ANALYZE

to begin with. Then read the chapter on Planner Cost Constants and search for key words like random_page_cost here or on SO ...
Your settings are probably way off. The packaged defaults are hardly any good for bigger databases.


text:
Q: How to create a shortcut to run a command and then exit? I was looking for something like this:
.bat or .exe file to run "ipconfig /renew" ONCE and then exit.
Im planning on making this an autorun cause windows wont identify the network on its own unless I run that command.
Cheers!

A: You did all the work for me. Create a text file entitled: iprenew.bat and put the following in it:

ipconfig /renew

That's it.


text:
Q: ckeditor4 codesnippet plugin - dialogue is not showing I installed the codesnippet plugin by copying the files in the plugins folder
I added codesnippet to the extra plugins line in include.php:
$ckeditor->config['extraPlugins'] = 'codesnippet,droplets,pagelink,shybutton,justify,colorbutton';

The plugin icon shows up in the editor, but when I click it the darkened background of the plugins dialogue appears only for a blink, than nothing happens.
As supposed in the ckeditor forum I even added the lines
<link rel="stylesheet" type="text/css" href="/modules/ckeditor/ckeditor/plugins/codesnippet/lib/highlight/styles/googlecode.css" />
<script src="/modules/ckeditor/ckeditor/ckeditor.js"></script>
<script src="/modules/ckeditor/ckeditor/plugins/codesnippet/lib/highlight/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

to the header of my theme and checked the paths, which are ok, but nothing helps.
Does anynone have an idea what could be missing?

A: Just found out the folder /dialogs/ in my plugins/codesnippet folder was missing. Now everything works fine.


text:
Q: Python dateutil.parser treating string ending with m as date from dateutil.parser import parse
parse('2m') - treating it as a datetime
I'm testing a few terms like 2w, 2y, 2m and some other date formats received in a string to check whether a given string has a date of any format.
Everything works fine except '2m'
It's treating it as 2 minutes past, I don't want to treat it as a date format.
Please can anyone help to resolve this issue


text:
Q: Can I debug an application which is running on other eclipse instance? I have two eclipse instances running.

*

*And in one I have the code base.

*And in other eclipse i am running the application.

So can I debug this application in the eclipse where I have code base?

A: I imagine your build produces a JAR file? if so, then you can run the JAR from the console and then plug the eclipse debugger.
Check this tutorial, that is clear and with screenshots

A: You should be able to launch a remote debug session
1/ Specify the following option when launching the app from the first eclipse
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000

2/ Launch a Remote Java App (Run > Debug> Debug Configurations... > Remote Java Application.)
 -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000

(if port 8000 is free) in order to debug the app from the "code base" eclipse.
See Remote Debugging with Eclipse.
You can specify the sources in the Remote Java App configuration by referencing your own code base.

A: Yes, you can attach the debugger to a remote JVM. See How to attach debugger to running process?


text:
Q: update function w/ multiple intervals (SWIFT) I'm a newbie to programming so please help. I'm trying to set up intervals to create various Sprite nodes throughout my game (using the update function). However, each Sprite node needs to spawn at different intervals. I have a bunch of "if" statements and it seems to be causing my frame rate to drop and cause the app to lag. Can someone please tell me how to fix this? If possible, please also explain to me why it does this so that I can better understand the coding process. Thank you!
var timeBetweenBirds: Int!
var timeBetweenBadBirds: Int!
var timeBetweenSubtractTimeBirds: Int!
var timeBetweenAddTimeBirds: Int!
var timeBetweenBonusBirds: Int!

var now : NSDate?
var nextTime : NSDate?
var badBirdNextTime: NSDate?
var subtractTimeBirdNextTime: NSDate?
var addTimeBirdNextTime: NSDate?
var bonusBirdNextTime: NSDate?

override func update(currentTime: CFTimeInterval) {

 timeBetweenBirds = Int(arc4random_uniform(3))
 timeBetweenBadBirds = Int(arc4random_uniform(3) + 2)
 timeBetweenSubtractTimeBirds = Int(arc4random_uniform(3) + 2)
 timeBetweenAddTimeBirds = Int(arc4random_uniform(1) + 5)
 timeBetweenBonusBirds = Int(arc4random_uniform(20) + 20)

now = NSDate()

  if now?.timeIntervalSince1970 > nextTime?.timeIntervalSince1970 {

        nextTime = now?.dateByAddingTimeInterval(NSTimeInterval(timeBetweenBirds))

        createBird()
    }

    if now?.timeIntervalSince1970 > badBirdNextTime?.timeIntervalSince1970 {

        badBirdNextTime = now?.dateByAddingTimeInterval(NSTimeInterval(timeBetweenBadBirds))

        createBadBird()

    }

    if now?.timeIntervalSince1970 > subtractTimeBirdNextTime?.timeIntervalSince1970 {

        subtractTimeBirdNextTime = now?.dateByAddingTimeInterval(NSTimeInterval(timeBetweenSubtractTimeBirds))

        createSubtractTimeBird()

    }

    if now?.timeIntervalSince1970 > addTimeBirdNextTime?.timeIntervalSince1970 {

        addTimeBirdNextTime = now?.dateByAddingTimeInterval(NSTimeInterval(timeBetweenAddTimeBirds))

        createAddTimeBird()

    }

    if now?.timeIntervalSince1970 > bonusBirdNextTime?.timeIntervalSince1970 {

        bonusBirdNextTime = now?.dateByAddingTimeInterval(NSTimeInterval(timeBetweenBonusBirds))

        createBonusBird()

    }

A: Maybe this is not the correct solution, but it'll simplify things at least.
A couple of things to consider.

*

*Right now you are generating a new timeBetweenBirds value in each update loop, but you're only using it if you end up in the if statement
override func update(currentTime: CFTimeInterval) {

    timeBetweenBirds = Int(arc4random_uniform(3)) //Created on each update loop
    ...
    now = NSDate()

    if now?.timeIntervalSince1970 > nextTime?.timeIntervalSince1970 {
        //Only used here
        nextTime = now?.dateByAddingTimeInterval(NSTimeInterval(timeBetweenBirds))
        createBird()
    }

So a place to start could be to  update the timeBetweenBirds value only when needed.

*As I see it, you don't need to create all these dates and compare between them.
Every time update is called, you get a currentTime property for free :-) This property could be used to check against a nextTime variable like so:
var nextTime: CFTimeInterval = 0
...
override func update(currentTime: CFTimeInterval) {
    if currentTime > nextTime {
        nextTime = currentTime + CFTimeInterval(arc4random_uniform(3))
        createBird()
    }
    //And so on with your other if statements
}

As I said, I don't know if this speeds things up, but it'll simplify your code, which is always good :-)

A: I always give each function that update calls its own timing variable so that it doesn't have to run so many blocks of code every 1/60th of a second.
Example:
var timeOfLastUpdateForUserMotion:CFTimeInterval = 0

func processUserMotionForUpdate(currentTime: CFTimeInterval){
    if (currentTime - timeOfLastUpdateForUserMotion > 0.1) {
        ...
        timeOfLastUpdateForUserMotion = currentTime
    }
}
override func update(currentTime: CFTimeInterval) {
    processUserMotionForUpdate(currentTime)
}

In this particular case I'm checking the accelerometer once every 3 frames.  In your case:
var timeOfLastUpdateForRandomVariable
var birdOneInterval:Double = 0
var birdTwoInterval:Double = 0

func updateRandomVariables(currentTime:CFTimeInterval){
    if (currentTime - timeOfLastUpdateForRandomVariable > 1.0){
        birdOneInterval = Int(arc4random_uniform(3)+1)
        birdTwoInterval = Int(arc4random_uniform(3) + 2)
        timeOfLastUpdateForRandomVariable = currentTime
    }
}
    override func update(currentTime: CFTimeInterval) {
        updateRandomVariables(currentTime)
    }

Make sure not to get the interval, birdOneInterval, for example, too close to zero, or you could get a machine gun effect of birds flying everywhere; happens to me occasionally.


text:
Q: Find repeated cell in 2D array java I have 3x3 matrix as:
 1 -1 0  0
 1  2 2  1
 1  1 1 -1
-1  0 3  6

I am trying to find the diagonal elements of the cell that has value = -1, and multiplying the diagonal cell ([i-1][j-1],[i-1][j+1],[i+1][j-1],[i+1][j+1]) values with 2. So far I have achieved this but it seems that the cell [1][2] i.e. second row third column,is diagonal to 2 cells, which are [0][1] and [2][3]. So, my resulting array which should look like this:
 1 -1 0  0
 2  2 4  1
 1  2 1 -1
-1  0 6  6

instead looks like this:
 1 -1 0  0
 2  2 8  1
 1  2 1 -1
-1  0 6  6

i.e. there is a value 8 instead of 4 in cell [1][2]. So how can I check if the cell has already visited once and multiplied by 2 so that it cannot be multiplied again. Here is the code that i tried:
for (int i = 0; i <= x; i++) {
        for (int j = 0; j <= y; j++) {
            if (resultArray[i][j] == -1) {
                if (isAdjacent(i - 1, j - 1, x, y))
                    resultArray[i - 1][j - 1] *= 2;
                if (isAdjacent(i - 1, j + 1, x, y))
                    resultArray[i - 1][j + 1] *= 2;
                if (isAdjacent(i + 1, j - 1, x, y))
                    resultArray[i + 1][j - 1] *= 2;
                if (isAdjacent(i + 1, j + 1, x, y))
                    resultArray[i + 1][j + 1] *= 2;
            }
        }
    }
return resultArray;

static boolean isAdjacent(int i, int j, int x, int y) {
    boolean flag = false;
    if (i >= 0 && i <= x && j >= 0 && j <= y) {
        flag = true;
    }
    return flag;

}

A: Make a two dimensional boolean array with true or false at the positions that are diagonal to the -1's and then update the matrix by multiplying all of the numbers at the true positions by two in your matrix. This way no values will be multiplied twice.
So you could initialize the boolean array:
boolean diagonalsArray[][] = new boolean[x][y];

and then instead of  multiplying the positions
resultArray[i + 1][j + 1] *= 2;

set those positions to true in your boolean array:
diagonalsArray[i + 1][j + 1] = true;

and between your for loop and return resultArray, do all the multiplying
for (int i = 0; i <= x; i++) {
        for (int j = 0; j <= y; j++) {
               if(diagonalsArray[i][j]){
                    resultArray[i][j] *= 2;
                 }
            }
    }


text:
Q: How to access data in a child react component from a parent react component I'm new to ReactJS.  I want to be able to set some properties of a React component and then be able to access it from a parent React component.  But I'm not entirely sure how to do this.  For example, consider the following two classes:
export default class SubWindow extends React.Component {

    click(event)
    {
        this.myCollection.push({name:'receiptNum',value:$(event.currentTarget).html()});
    }

    render()
    {
        return (

0

1

2

3

        );

    }

}

export default class MainWindow extends React.Component {

    click(event)
    {
        console.log(SubWindow.myCollection);
    }

    render()
    {
        const SubWindow = require('./SubWindow').default;
        return (
            <SubWindow />
            <button onClick={this.click}>Log subwindow array</button>
        );

    }

}

Basically, I want the SubWindow to have a property called myCollection which is just an array of JSON objects.  myCollection gets populated by each click on the list item.
Later, I want to be able to console.log(SubWindow.myCollection) when I press on a button in the parent window.  My question how do I access the SubWindow.myCollection from a parent react component?

A: I would recommend you to solve this problem by using callback. MainWindow is creating SubWindow, and you can give here a callback function as a property. For example:
<SubWindow onClick={this.onSubwindowClick} />

Now in your SubWindow class, just call this callback inside your click function:
click(event)
    {
        this.myCollection.push({name:'receiptNum',value:$(event.currentTarget).html()});
        this.props.onClick(/* data you want to pass to the parent */);
    }

Also you have to define onSubwindowClick in the class MainWindow. This function should receive any data you wish from child class - the data which you pass from child where I put comment /* data you want to pass to the parent */.
Also, don't forget to bind this to that onSubwindowClick function. This is usually done in constructor of the class, which I suggest you to create for each component.
You can find good example about "passing data to parent" on React's pages. You can take a look at the article Thinking in React, particularly section "Step 5: Add inverse data flow".

A: just pass a function to you child component, and the function is bind to the parent component's 'this', actually you just created a closure.
then in your parent component, the function's args are passed in your child component, meanwhile your parent component's scope has access to the args, so in the parent scope you can get access to the data in the child scope.


text:
Q: Select Multiple Columns join SQL Server I have an Employee table like this

And a second table for EmployeeComments with the EmployeeID as foreign key:

I would like to query the employees with their comments in the following format:
select Name, Comment
from Employee emp
left join EmployeeComments empC on empC.EmployeeID = emp.ID

I would like the results to be like:

I have already looked at Pivot, but it doesn't resolve my issue

A: Use window function:
select case when row_number() over(partition by emp.name order by empC.ID) = 1
            then Name
            else '' end as Name,
       Comment
from Employee emp
left join EmployeeComments empC On empC.EmployeeID = emp.ID

A: This might give you some kind of order in your result window at least
WITH cte AS(
    SELECT  emp.Name ,
            empC.Comment,
            RANK() OVER (ORDER BY emp.Name) NameOrder,
            ROW_NUMBER() OVER (PARTITION BY emp.Name ORDER BY empC.ID) RN
    FROM    Employee emp
            LEFT JOIN EmployeeComments empC ON empC.EmployeeID = emp.ID
)
SELECT
    Name = (CASE WHEN RN = 1 THEN Name ELSE '' END),
    Comment
FROM
    cte
ORDER BY
    NameOrder,
    RN

A: "use Cross Join:"

Query:

  select case t.cnt
  when  1 then
  coalesce(t.Name,' ')
  end as Name,t.comment
  from
  (
  select t1.Name,t2.comment,row_number()
  over(partition by t1.name order by t1.Name)
  as cnt
  from
  EmployeeComments t1
  cross join
  Employee t2
  where t1.ID=t2.Employeeid
  )t


text:
Q: firebase projects api getConfig Environment details

*

*OS: MacOS 10.13.1 (17B1003

*Python version: 3.6

*pip version: 10.0.1

*google-api-python-client version: 1.6.4 or 1.7.5

Steps to reproduce

I try to use this api https://firebase.google.com/docs/projects/api/reference/rest/
setup auth:
credentials = ServiceAccountCredentials.from_p12_keyfile(
            self.__service_account_email,
            self.__path_to_p12,
            scopes=['https://www.googleapis.com/auth/firebase'])
self.__service = build('firebase', 'v1beta1', credentials=credentials)

this methods are correctly works
self._service.projects().androidApps().list(parent=self.project).execute()
self._service.projects().iosApps().list(parent=self.project).execute()

but if I use getConfig
name = 'projects/{}/androidApps/{}/config'.format(self.project_id, app_id)
self._service.projects().androidApps().getConfig(name=name).execute()

I receive:
21:04:22 - oauth2client.client                 : INFO   Refreshing access_token
21:04:23 - googleapiclient.discovery           : INFO   URL being requested: GET https://firebase.googleapis.com/v1beta1/projects/PROJECT_ID/iosApps/IOS_APP_ID/config?alt=json
21:04:24 - googleapiclient.http                : WARNING Encountered 403 Forbidden with reason "forbidden"
21:04:24 - root                                : ERROR  <HttpError 403 when requesting https://firebase.googleapis.com/v1beta1/projects/PROJECT_ID/iosApps/IOS_APP/config?alt=json returned "gaia_mint_verify::NO_MATCHING_SCOPES: Incoming scopes [(111700 25302 57500 1907 1914 53300 8305 145900 40100 70002 75101 28301 30401 706 1921 32722 713 107005 744 63913 15100 720 34204 22211 63906 32708 45701 727 9506 65300 8333 44103 57012 57019 8340 95500 44700 1433 21400 48900 95802 120001 8319 29400 53100 71600 70701 8312 1454 29414 35201 4400 29421 44300 330 92301 48500 90201 2732 44602 57300 25351 50800 50161 2904 56401 57005 25200 88210 741 62522 734 56805 62515 5703 54101 107001 755 103405 103412 15606 32729 7501 62508 75301 50210 62501 46600 66800 724 8323 49307 20403 68900 22208 731 32704 5605 121300 94201 64700 57503 82100 8309 40700 71200 4369 63924 97400 34200 28901 745 56302 103900 738 11508 27700 4320 49500 4471 8344 1300 11501 4464 86500 100002 25305 43000 90700 33101 8337 710 57008 703 57015 717 4306 8330 1918 34604 56404 26801 101101 62512 62505 77900 29403 2901 1700 499 29410 1405 1412 89601 29417 94001 52601 44110 4383 41901 29424 2729 752 70501 34400 49300 44001 320 62526 9338 15020 92600 3800 5700 56801 5707 62519 103401 57110 25354 99900 50041 50192 24606 45202 8341 103408 15603 95801 742 47110 137301 98000 8334 62525 22700 77200 5602 62518 8313 10002 29408 9700 310 62511 70700 41200 63926 29415 90207 77000 29422 56300 111706 721 92300 106600 32730 63919 41302 728 79500 714 140500 25352 32400 41400 20400 63912 735 8348 63905 32716 25201 36800 57020 77400 2775 352 45702 131501 1416 107000 18100 27803 4482 119400 70001 64400 7502 75300 53101 63933 89101 57501 83802 9328 8306 4401 34605 123807 73302 9500 2733 11600 21401 2912 113300 57006 2905 57013 22100 50600 63909 76600 65700 11509 34401 28621 61500 50400 59200 25306 8345 103404 64808 91900 103411 15010 81000 8338 25355 3601 59611 42000 33000 725 20404 13507 32705 22820 17103 29404 15600 70402 24600 57202 746 732 95805 11558 739 29418 47120 44100 89600 753 5209 65001 43201 63923 11551 14803 50042 57002 82001 57009 80800 56405 70500 68200 1441 21900 57016 4324 54600 700 1455 8324 62504 2765 1701 8331 4412 64000 8317 43001 87300 1413 6800 4440 26900 72400 8303 83100 212 25102 24800 4433 2923 135900 34606 29423 140501 799 15021 52301 70506 31400 99000 2906 50022 25353 750 50043 80700 103400 2713 107003 743 62524 103407 57400 86101 27804 62517 56803 22104 103414 55300 49302 141600 49000 65400 62510 67802 22701 15604 17100 91200 4321 80904 1905 63925 32706 26501 27400 63918 1912 9501 63904 8307 20401 32713 23000 711 8300 68901 49204 9357 1926 101500 718 40400 110100 19000 8342 2934 8349 95804 14800 100011 25307 25300 4300 63932 42008 62521 350 62514 25356 13501 29412 62507 2759 4420 53800 29419 95200 90203 123500 50162 2938 26701 1421 62500 69000 42900 90800 111701 85803 11559 213 63908 9315 34402 2731 26901 32000 2724 111501 46401 22101 4406 15011 4483 103403 28116 715 8332 153800 90600 15601 722 17104 94800 43002 15903 729 99800 8318 8304 63915 736 50106 10000 57003 111104 45000 61404 25303 57010 1435 49200 57017 1442 83201 8346 1902 70401 701 62900 47100 8339 22800 1909 4469 9600 107002 25101 57011 28100 23001 57018 88200 2928 7500 5702 50044 64402 108800 3100 46901 4301 80903 2907 30400 2749 32500 27401 66400 41500 122000 36700 113302 2763 4424 45700 9354 57004 733 4364 62523 43200 42006 62516 8343 103406 32900 15900 95803 1200 44106 8336 747 24100 103413 21501 8322 22702 68700 111300 25301 22105 66600 62502 4371 10011 754 56804 54100 102500 740 56200 32707 24300 1460 25357 64809 47600 1906 719 63917 1920 65701 19050 32714 712 63903 34203 11700 29420 77300 726 63910 61501 9316 15700 4312 81100 1436 1443 57000 2795 1903 28103 57007 44000 45201 56403 4333 1910 400 128900 57014 709 5706 34603 33100 8315 62513 44200 48400 99901 133100 35200 351 45703 62506 4421 8308 1415 2911 52600 70000 63700 1422 30101 86701 1429 28900 79000 63907 4382 25304 11511 32710 99002 26800 103402 32717 56800 2728 91600 8347 62520 103409 59620 50300 716 33300 1478 730 723 4340 737 42901 9309 93700 90206 42002 63914)] have no matching scopes in acceptable scopes [73301 35600]. Are you using HTTPS? [go/gaiamintssl]">
Traceback (most recent call last):
...
    return self._service.projects().iosApps().getConfig(name=name).execute()
  File "/.../venv/lib/python3.6/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/.../venv/lib/python3.6/site-packages/googleapiclient/http.py", line 849, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://firebase.googleapis.com/v1beta1/projects/PROJEECT_ID/iosApps/APP_ID/config?alt=json returned "gaia_mint_verify::NO_MATCHING_SCOPES: Incoming scopes [(111700 25302 57500 1907 1914 53300 8305 145900 40100 70002 75101 28301 30401 706 1921 32722 713 107005 744 63913 15100 720 34204 22211 63906 32708 45701 727 9506 65300 8333 44103 57012 57019 8340 95500 44700 1433 21400 48900 95802 120001 8319 29400 53100 71600 70701 8312 1454 29414 35201 4400 29421 44300 330 92301 48500 90201 2732 44602 57300 25351 50800 50161 2904 56401 57005 25200 88210 741 62522 734 56805 62515 5703 54101 107001 755 103405 103412 15606 32729 7501 62508 75301 50210 62501 46600 66800 724 8323 49307 20403 68900 22208 731 32704 5605 121300 94201 64700 57503 82100 8309 40700 71200 4369 63924 97400 34200 28901 745 56302 103900 738 11508 27700 4320 49500 4471 8344 1300 11501 4464 86500 100002 25305 43000 90700 33101 8337 710 57008 703 57015 717 4306 8330 1918 34604 56404 26801 101101 62512 62505 77900 29403 2901 1700 499 29410 1405 1412 89601 29417 94001 52601 44110 4383 41901 29424 2729 752 70501 34400 49300 44001 320 62526 9338 15020 92600 3800 5700 56801 5707 62519 103401 57110 25354 99900 50041 50192 24606 45202 8341 103408 15603 95801 742 47110 137301 98000 8334 62525 22700 77200 5602 62518 8313 10002 29408 9700 310 62511 70700 41200 63926 29415 90207 77000 29422 56300 111706 721 92300 106600 32730 63919 41302 728 79500 714 140500 25352 32400 41400 20400 63912 735 8348 63905 32716 25201 36800 57020 77400 2775 352 45702 131501 1416 107000 18100 27803 4482 119400 70001 64400 7502 75300 53101 63933 89101 57501 83802 9328 8306 4401 34605 123807 73302 9500 2733 11600 21401 2912 113300 57006 2905 57013 22100 50600 63909 76600 65700 11509 34401 28621 61500 50400 59200 25306 8345 103404 64808 91900 103411 15010 81000 8338 25355 3601 59611 42000 33000 725 20404 13507 32705 22820 17103 29404 15600 70402 24600 57202 746 732 95805 11558 739 29418 47120 44100 89600 753 5209 65001 43201 63923 11551 14803 50042 57002 82001 57009 80800 56405 70500 68200 1441 21900 57016 4324 54600 700 1455 8324 62504 2765 1701 8331 4412 64000 8317 43001 87300 1413 6800 4440 26900 72400 8303 83100 212 25102 24800 4433 2923 135900 34606 29423 140501 799 15021 52301 70506 31400 99000 2906 50022 25353 750 50043 80700 103400 2713 107003 743 62524 103407 57400 86101 27804 62517 56803 22104 103414 55300 49302 141600 49000 65400 62510 67802 22701 15604 17100 91200 4321 80904 1905 63925 32706 26501 27400 63918 1912 9501 63904 8307 20401 32713 23000 711 8300 68901 49204 9357 1926 101500 718 40400 110100 19000 8342 2934 8349 95804 14800 100011 25307 25300 4300 63932 42008 62521 350 62514 25356 13501 29412 62507 2759 4420 53800 29419 95200 90203 123500 50162 2938 26701 1421 62500 69000 42900 90800 111701 85803 11559 213 63908 9315 34402 2731 26901 32000 2724 111501 46401 22101 4406 15011 4483 103403 28116 715 8332 153800 90600 15601 722 17104 94800 43002 15903 729 99800 8318 8304 63915 736 50106 10000 57003 111104 45000 61404 25303 57010 1435 49200 57017 1442 83201 8346 1902 70401 701 62900 47100 8339 22800 1909 4469 9600 107002 25101 57011 28100 23001 57018 88200 2928 7500 5702 50044 64402 108800 3100 46901 4301 80903 2907 30400 2749 32500 27401 66400 41500 122000 36700 113302 2763 4424 45700 9354 57004 733 4364 62523 43200 42006 62516 8343 103406 32900 15900 95803 1200 44106 8336 747 24100 103413 21501 8322 22702 68700 111300 25301 22105 66600 62502 4371 10011 754 56804 54100 102500 740 56200 32707 24300 1460 25357 64809 47600 1906 719 63917 1920 65701 19050 32714 712 63903 34203 11700 29420 77300 726 63910 61501 9316 15700 4312 81100 1436 1443 57000 2795 1903 28103 57007 44000 45201 56403 4333 1910 400 128900 57014 709 5706 34603 33100 8315 62513 44200 48400 99901 133100 35200 351 45703 62506 4421 8308 1415 2911 52600 70000 63700 1422 30101 86701 1429 28900 79000 63907 4382 25304 11511 32710 99002 26800 103402 32717 56800 2728 91600 8347 62520 103409 59620 50300 716 33300 1478 730 723 4340 737 42901 9309 93700 90206 42002 63914)] have no matching scopes in acceptable scopes [73301 35600]. Are you using HTTPS? [go/gaiamintssl]">

Please tell me, Where was I wrong?
or
Firebase v1beta1 is not stable?
Thanks!

A: I found new python sdk for it
https://github.com/firebase/firebase-admin-python
setup:
import firebase_admin
cred = firebase_admin.credentials.Certificate(self.__path_to_json)
self.__project = firebase_admin.initialize_app(cred)

get config:
from firebase_admin import project_management
app = project_management.android_app(app_id, self._project)
config = app.get_config()
with open('google-services.json', 'w+') as f:
    f.write(config)

it works!

A: At the time of writing, you can use the scope https://www.googleapis.com/auth/cloud-platform to get to the app config. There appears to be in an error in the documentation.


text:
Q: IndexError: list index out of range cuando se remueve item de array Tengo una función que lo que hace es remover un item de un array si este es igual a una palabra en especifico. Para ello el usuario ingresa una frase que luego es transformada en un array, la función itera sobre el array buscando la palabra (que puede estar en varias ocasiones).
Si la palabra solo esta una vez, todo funciona bien. Pero si la palabra está más de una vez en el array, da el error IndexError: list index out of range (Supongo que porque el array ha cambiado de tamaño)

fraze=input("frase: ")
palabras=fraze.split(" ")

def borrar(palabras):
    for i in range(len(palabras)):
        if (palabras[i] == "la"):
            palabras.remove(palabras[i])

De antemano muchas gracias, ha de ser alguna bobada, pero no tengo mucha experiencia programando y solo lo hago por hobby.


text:
Q: The symmetric group theory of natural numbers Sometimes it is not easy to formulate a correct question. Here is a better version of this  question (I still do not know if it is optimal, but it is better than the previous one).
We say that a set $X$ of natural numbers is symmetric group definable if there exists a first order formula $\theta$ in the group signature such that a symmetric group  $S_n$ satisfies  $\theta$ if and only if $n\in X$. Of course finite sets and sets with finite complements are symmetric group definable. It is not completely trivial to find any infinite set of natural numbers with infinite complement which is symmetric group definable. But it is not a difficult exercise to show that the set of numbers $n$ such that either $n$ or $n-1$ is prime is such a set.
Question. Is any of the following sets symmetric group definable?
1) the set of even numbers
2) the set of prime numbers
A more vague question Is there a characterization of the Boolean algebra of symmetric group definable sets?
Update Noam D. Elkies' answer below shows that the Boolean algebra contains many sets. Noah Schweber's answer of the previous question suggests looking at the computational complexity of $X$. Clearly, checking whether $n$ belongs to a symmetric group definable set $X$ takes time at most $(n!)^k$ where $k$ is the number of quantifiers in the corresponding formula $\theta$. So we have a couple of even better questions.
Question 1 Is the converse true, that is every set of numbers recognizable by deterministic a Turing machine in time $\le (n!)^k$ for some $k$ symmetric group definable? Here the size of a number $n$ is $n$ that is we consider the unary representation of natural numbers.
Question 2 Let us replace $S_n$ by, say, $SL_n(\mathbb{F}_2)$ and similarly define $SL_n(\mathbb{F}_2)$-definable sets of numbers. Will  the Boolean algebra of all $SL_n(\mathbb{F}_2)$-definable sets coincide with the Boolean algebra of all deterministic polynomial time decidable sets of natural numbers?
Question 3 Can the statements that "Primes are in P" be proved this way?

A: Almost the same first-order sentence that Noam used to define transpositions defines, in $SL_n(\mathbb F_2)$, a unipotent transvection (i.e. with a single $2\times 2$ Jordan block, and the rest $1 \times 1$).
The sentence is "$g$ has order $2$, and its product with any conjugate of itself has order at most $4$".
Indeed, if $g$ has order $2$ then $g$ is unipotent, with all Jordan blocks of size at most $2$. If it has one of size at most $2$ then $g$ times any conjugate of $g$ fixes a codimension two subspace, hence has order $1,2,3$, or $4$. On the other hand, if $g$ has $k$ Jordan blocks, we can view it as a unipotent matrix with a single Jordan block over $\mathbb F_{2^k}$, so using $$\begin{pmatrix} 1 & 1 \\ 0 & 1\end{pmatrix} \begin{pmatrix} 1 & 0 \\ x & 1 \end{pmatrix}=\begin{pmatrix} 1+x & 1 \\ x & 1\end{pmatrix} $$ we can produce any conjugacy class in $SL_2(\mathbb F_{2^k})$, and in particular an element of order $2^k+1>4$.
I suspect from appropriate finite configurations of transvections one can define the disjoint union of the set of nonzero vectors and the set of nonzero linear functions (it is not possible to separate these because of the inverse-transpose automorphism) but I wasn't able to make it work yet.

A: We can define the set $P$ of primes. That is, there is a 1st order sentence in the language of groups that holds in $S_n$ iff $n$ is prime.
Indeed, as already mentioned by Noam, we can recognize the set $O$ of odd numbers. Next, I show below that we can recognize the set $I$ of elements $k$ such that either $k$ or $k-1$ is prime. Since $P=\{2\}\cup (O\cap I)$, we can recognize $P$.
Let check that we can recognize $I$ by a single sentence. For a group $G$ and $c\in G$ say that $G$ (or $c$) satisfies $R(c)$ if $c\neq 1$ and every nontrivial element in the centralizer of $c$ has an abelian centralizer. As a 1st-order sentence:
$$R(c)\Leftrightarrow c\neq 1\wedge \forall x,y,z:(x\neq 1 \wedge\; [x,c]=[x,y]=[x,z]=1)\Rightarrow [y,z]=1.$$
Then, in a symmetric group $S_n$, an element $c$ satisfies $R(c)$ if and only if $c$ is a $p$-cycle with $p$ prime and $p\in\{n,n-1\}$.
Indeed, the sole condition that $c$ has an abelian centralizer implies that it's a disjoint product of cycles of pairwise distinct length.
Assuming $R(c)$, if two lengths $\ge 2$ occur, then $c$ has some nontrivial power with nonabelian centralizer and hence $R(c)$ fails. So either $c$ is a $k$-cycle with $k\in\{n,n-1\}$. Again if $k$ is non-prime then $c$ has some nontrivial power with nonabelian centralizer and hence $R(c)$ fails.
Conversely, for $p$ prime and $n\in\{p,p+1\}$, a $p$-cycle $c$ satisfies $R(c)$ in $S_n$ (its centralizer being reduced to the subgroup it generates).
So the sentence $\exists c:R(c)$ characterizes, among those symmetric groups $S_n$, those for which either $n$ or $n-1$ is prime. (This is a $\exists\forall$-sentence.)

Comment on Mark's approach. Instead of $R(c)$, he uses $Q(c)$, which says that $c\neq 1$ and that any two nontrivial elements in the centralizer of $c$ are conjugate. Namely
$$Q(c)\Leftrightarrow c\neq 1\wedge \forall x,y:(x,y\neq 1 \wedge\; [x,c]=[y,c]=1)\Rightarrow \exists z:zxz^{-1}=y.$$
In symmetric groups $S_n$, $Q(c)$ and $R(c)$ are equivalent: these are precisely $p$-cycles when $p$ is prime and belongs to $\{n,n-1\}$.
Still, let's benefit of this alternative approach.
A first remark is that they differ in more general groups, and even in the closely related setting of alternating groups. For instance, observe that in $\mathrm{Alt}_p$ or $\mathrm{Alt}_{p+1}$, a p-cycle $c$ satisfies $R(c)$ but not $Q(c)$. So if we're rather interested in alternating groups (a number of people study ultraproducts of finite simple groups) then only the formula $R$ gives something (actually it seems that $\mathrm{Alt}_n$ satisfies $\exists c:R(c)$ iff $\{n,n-1,n-2\}$ contains a prime).
We can also try to modify $Q$ and define more things for symmetric groups. For instance we can consider $Q'(c)$ to mean that $c\neq 1$ and the centralizer of $c$ meets at most two conjugacy classes of elements of order $\ge 3$.
$$Q'(c)\Leftrightarrow c\neq 1\wedge \forall x,y,z:(x^2,y^2,z^2\neq 1 \wedge\; [x,c]=[y,c]=[z,c]=1)\Rightarrow$$
$$\exists t:txt^{-1}=y \vee tyt^{-1}=z\vee tzt^{-1}=x.$$
If I'm correct, $Q'(c)$ characterizes in $S_n$ $p$-cycles with $p$ prime in $\{n,n-1,n-2\}$ (and a few more elements if $n\le 6$). So, that $S_n$ satisfies
$\exists c:Q'(c)$ characterizes those $n$ such that $\{n,n-1,n-2\}$ contains a prime.

A: It's possible to embed within the theory of the permutation group $S_n$ the theory of second-order arithmetic for numbers between $0$ and $n-1$. Using this we can construct propositions corresponding to any property of $n$ that can be determined by a Turing machine with resource bound that roughly corresponds to a maximum of $\sqrt {n}$ steps. With additional quantifiers we can add a finite amount of alternation to this complexity class and get a PH-like complexity class.
As Noam Elkies points out, for $n > 6$ simple transpositions are characterized by a first-order property. To be self-contained, I'll repeat his definition: $g$ is a simple transposition if $g^2 = 1$ and for any conjugate $g'$ of $g$, the order of $g g'$ is either $1$, $2$, or $3$.
Next, it is possible to encode a point in the underlying set acted on by the permutation group (that is, a point in $[n] = \{1, 2, \dots, n\}$) as pair of simple transpositions $(g_0, g_1)$ such that $g_0 g_1$ has order $3$, which represent the unique point which is transposed on both $g_0$ and $g_1$. The pairs $(g_0, g_1)$ and $(h_0, h_1)$ represent the same point if and only if for each $i \in \{0, 1\}$ and $j \in \{0, 1\}$ the product $g_i h_j$ is either the identity or order $3$. Next, given a permutation $g$ and a point $x$ encoded by $(h_0, h_1)$, the action of $g$ on $x$ is encoded by $(g^{-1} h_0 g, g^{-1} h_1 g)$. Seeing as we can quantify over all the points and compare points for equality, any two-sorted formula involving both permutations and points can be translated into an equivalent formula involving only permutations. Therefore I can freely incorporate points into my language for defining properties.
Permutations can also encode sets of points: Given a permutation $g$, define $Q (g)$ to be the set of all points not fixed by $g$. Then the sets $Q (g)$ for all $g \in S_n$ vary over all subsets of $[n]$ other than the ones with a single point. Then if $\phi (X)$ is a formula with a variable $X$ representing a subset of $X$, we can translate the quantifier $\forall X. \phi (X)$ into $\forall g \in S_n. \phi
45  (Q (g)) \land \forall x \in [n]. \phi (\{x\})$, where $\phi (Q (g))$ means we replace all instances of $y \in X$ with $g (y) \neq y$, and $\phi (\{x\})$ means we replace all instances of $y \in X$ with $x = y$. The formula $\exists X. \phi (X)$ is translated similarly. Therefore we can also add subsets of $[n]$ into our language.
I define that $g_0$ is cyclically contained in $g_1$ if for every point $x$ either $g_0 (x) = x$ or $g_0 (x) = g_1 (x)$. Equivalently, the cyclic decomposition of $g_0$ is a subset of the cyclic decomposition of $g_1$, not counting fixed points as cycles. Then a cycle can be defined as a permutation that is not the identity and such that every permutation cyclically contained in it is either equal to it or equal to the identity. A maximal cycle is a cycle without any fixed points.
For everything below, I will fix a maximal cycle $S$ and a point $O$. The lettering is intended to be suggestive of Peano arithmetic.
A permutation commutes with $S$ if and only if it is a power of $S$. I define the addition relation $x + y = z$ to mean that there exists a permutation $g$ which commutes with $S$ such that $g (O) = x$ and $g (y) = z$. I will denote by $x+y$ the unique point $z$ such that $x + y = z$.
I call a permutation $g$ linear if $g (x + y) = g (x) + g (y)$ for all $x$ and $y$. $x$ is call invertible if there is a linear permutation $g$ such that $g S (O) = x$. If $x$ is invertible I define the product $x \cdot y$ to be $g (y)$ for the unique such $g$. For an arbitrary $x$ I define $x \cdot y = z$ if there is a decomposition $x = x_0 + x_1$ or $x = x_0 + x_1 + x_2$ with $x_0, x_1, x_2$ all invertible and $z = x_0 \cdot y + x_1 \cdot y$ or $z = x_0 \cdot y + x_1 \cdot y + x_2 \cdot y$, respectively.
To define the order relation we can use subsets: I define $x < y$ if there is a subset $X \subseteq [n]$ such that

*

*$S (x) \in X$.

*If $a \in X$, then either $a = y$ or $S (a) \in X$.

*$O \notin X$.

Using all of the definition above as tools it should be possible to define whether some tuple of subsets $X_0, \dots, X_{r-1}$ denote a Turing machine computation. With a naive encoding of the computation as a concatenation of the state of the Turing machine at every time step, it is necessary that the computation terminate before the spacetime resource usage is greater than a fixed multiple of $n$, where the spacetime resource usage is defined as the sum of the space usage over each time step. With this it should be possible to define "$X_0$ encodes the binary representation of $x$" whenever $x$ less than the square root of $n$, by giving the input $x$ in unary. The binary representation of $n$ can be determined via a formula $n = x \cdot y + z$ where $y$ is a power of $2$ (definable as in Peano arithmetic) and $z < y$ and given the binary representations of $x$ and $z$. Verifying $n = x \cdot y + z$ comes down to the identity $x \cdot y + z = O$ plus the claim that $x \cdot y$ doesn't overflow. $n$ can also be split into three components to give more leeway for constant and logarithmic factors. Giving the binary representation of $n$ as input to a Turing machine allows defining all properties that checkable by a Turing machine with these resource bounds.
More sophisticated encoding schemes, making full use of the information encoded by a permutation rather than just thinking of it as a subset, should lead to a higher computational capacity. Using alternating quantifiers $\forall Y_0 \exists Y_1 \forall Y_2 \dots \exists Y_{s-1}$ and including $Y_0, \dots, Y_{s-1}$ as inputs to the computation, it should be possible to define all properties within a PH-like complexity class where the final verification step is restricted to computations with this spacetime resource bound or whatever resource cost the more sophisticated encoding takes.

A: Suppose $n>6$.  Then we give a "symmetric group definition" of the set
$\{2 | n \}$.  Since Mark Sapir already revealed in the comments
how to define "$n$ or $n-1$ is prime", this also gives definitions of
the set of primes (and of primes-plus-$1$).
First we give a first-order definition of simple transpositions.
(This would not be possible for $n=6$ because simple and triple transpositions
are equivalent under an outer automorphism of $S_6$.)  Namely: $g$ is a simple transposition iff
$g$ is of order $2$ and, for any conjugate $g'$ of $g$,
the product $gg'$ has order $1$, $2$, or $3$.
We can then define involutions without fixed points:
$g$ is such an involution iff for every simple tranposition $h$
the product $gh$ has order $2$ or $4$.  (If an involution $g$
does have a fixed point $x$ then there's a simple transposition $h$
that switches $x$ with a non-fixed point, and then $gh$ has order
$3$ or $6$ according as $g$ is a simple tranposition or not.)
Then $n$ is even iff $S_n$ has an involution without fixed points.


text:
Q: How to position text at the bottom of a triangle div? I have a following div:

div {
  width: 0px;
  height: 0px;
  border-left:  126px solid transparent;
  border-right:  126px solid transparent;
  border-bottom:  126px solid #D30000;
  position: relative;
  left: 55%;
  top: 40px;
  display: table-cell;
  text-align:center;
  vertical-align: bottom;
}

Triangle

The following align text on the triangle like this :
                    _Triangle_
                   /          \
                  /            \
                 /              \
                /                \
               /________________  \

What I am trying to accomplish is this :
                       /\
                      /  \
                     /    \
                    /      \
                   /        \
                  / Triangle \

How to I push the text to the bottom of a triangle div without having to wrap it in a tag? It is important for me to use position: relative; since absolute did not work. However, even if I remove position:relative; the text still doesn't go to the bottom of a div. It stays on top where the top angle of the triangle gets cut off and makes the shape look like a trapezoid.

A: You could use a pseudo element to make the triangle.

div {
  text-align: center;
  width: 126px;
  margin: 126px auto;
  position: relative;
  color: white;
}
div:after {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
  z-index: -1;
  border-left: 126px solid transparent;
  border-right: 126px solid transparent;
  border-bottom: 126px solid #D30000;
}

Triangle

A: You can do it with additional SPAN inside DIV and before pseudo class that is used for drawing triangle. I use SPAN to position text to the bottom of DIV.

div{
    width: 252px;
    height: 126px;
    position: absolute;
}
div>span{
    position: absolute;
    bottom: 0px;
    text-align: center;
    width: 100%;
}
div:before{
    content: '';
    position: absolute;
    bottom: 0px;
    border-width: 126px;
    border-style: solid;
    border-color: transparent transparent #D30000  transparent;
    display: block;
    z-index: -1;
}

Triangle

I tried it in chroma and IE.


text:
Q: Triggers in SQL Server There are two Table Table_Trigger and Table_Trigger1.I have created a trigger on Table_Trigger1. It works perfectly.Below is my Trigger script -
CREATE TRIGGER Test_Trigger
ON Table_Trigger1

INSTEAD OF INSERT

AS
SET NOCOUNT ON

INSERT INTO Table_Trigger1(FirstName)
SELECT FirstName from INSERTED I
WHERE I.firstName in (SELECT FirstName from Table_Trigger)

when my where condition is true, I get a message (1 row(s) affected) and value save in Table.But when my where condition is false, that time I also get a message (1 row(s) affected) and value not save in Table.
My question is - If where condition is false and value don't save in table so why I got a (1 row(s) affected) message. what is meaning of this message.
Thanks in advance.

A: In a nutshell, the "rows affected" for your original insert is ignorant of what's going on behind the scenes in your trigger. It passes one row through and considers that row "affected."
I tried to find some documentation to back this up. The closest I could come was the documentation on SqlCommand.ExecuteNonQuery, which states:

For UPDATE, INSERT, and DELETE
  statements, the return value is the
  number of rows affected by the
  command. When a trigger exists on a
  table being inserted or updated, the
  return value includes the number of
  rows affected by both the insert or
  update operation and the number of
  rows affected by the trigger or
  triggers.

Of course, the SET NOCOUNT ON in your trigger is suppressing the return of the number of rows affected within the trigger, so you're only seeing the result of the original insert statement.


text:
Q: ggplot2 log scale of y axis causing curved lines I'd like to graph some data as means of groups over time, with lines connecting the different mean time points for each group.
The code for this is:
line<-ggplot(dat, aes(Time, Cortisol.ngmL, shape=T))

line+
stat_summary(fun.y=mean, geom="point", size=4, aes(group=T))+
stat_summary(fun.y=mean, geom="line", aes(group=T), linetype="dashed", lwd=0.7)

But…I want the y axis logged (log10). And when I do this the lines connecting the groups across time become curved (code below)
line<-ggplot(dat, aes(Time, Cortisol.ngmL, shape=T))

line+
stat_summary(fun.y=mean, geom="point", size=4, aes(group=T))+
stat_summary(fun.y=mean, geom="line", aes(group=T), linetype="dashed", lwd=0.7)+
coord_trans(y="log10")

Does anyone know a way I can have a log scale and straight lines?

A: I use this function to connect points with straight lines in log scale:
log_line <- function(x, y, n = 1000) {
  l <- lapply(2:length(x),
              function(i, n) {
                xl <- seq(x[i - 1], x[i], (x[i] - x[i - 1]) / n)
                yl <- exp(log(y[i]) + (xl - x[i]) * (log(y[i]) - log(y[i - 1])) / (x[i] - x[i - 1]))
                return(data.frame(x = xl, y = yl))
              },
              n)

  return(do.call(rbind, l))
}

The arguments are the x and y coordinates of the points you want to connect with a straight line in log scale and the n number of points you want to predict between each pair of original points.
This function fits a straight line in log scale between each points, predicts n new points between the two original points and than converts them back to the original scale. The output is a data frame with the predicted values x and y coordinates.
It can be easily added to a ggplot:
v1 <- 1:10
v2 <- exp(-v1)

ggplot() +
  geom_point(aes(v1, v2)) +
  geom_line(aes(x, y), data = log_line(v1, v2)) +
  coord_trans(y = "log")


text:
Q: How do I validate that a Radio Button is selected upon a click event? I'm trying to help and I'm definitely out of my element on this assignment. I'm by no means a programmer but sometimes can manipulate pre-existing code.
I have a HTML web part form loaded on a SharePoint front end. The form has basic features to fill out, one of which is a Radio button feature.
I'm unsure of the proper html or better yet where to even place it (which function) or even if I can place it in a pre-existing function.
I've done quite a bit of googling around and have tried this method. I'm sure that the syntax maybe off and perhaps that's why it does nothing and I'm able to proceed when I "check-in" Upon click of that button "Check-in" is when I'd like the validation to check and see if a radio button is selected. By default there is no default selected (yes I know, but don't tell me why it's bad practice just doing my job).
if(document.form1.btn-group[0].checked == true) {
    alert("Please select On-Site or Remote Surveillance Type");
}

The pre-existing code is very lengthy and again I'm no developer so perhaps I placed the code in the wrong place. If anyone has the time to assist this would be greatly appreciated and I think it would be very beneficial.
function checkInSupplier(){
if (!onloadCheckin){
    //Save PRS/SRA data
    ia.loadScreen.displayCover(true, 'Verifing PRS/SRA Data');
    ia.loadScreen.changeProgress({load: true});
    updateTokenData();

    //Save parts data
    ia.loadScreen.displayCover(true, 'Verifing Part Data');
    ia.loadScreen.changeProgress({load: true});
    updatePartsData();

    //Save progression date data
    ia.loadScreen.displayCover(true, 'Verifing Progression Data Data');
    ia.loadScreen.changeProgress({load: true});
    updateProgressionDateData();

    //Save notes data
    ia.loadScreen.displayCover(true, 'Verifing Note Data');
    ia.loadScreen.changeProgress({load: true});
    updateNotesData();

    //Save mandatory contacts data
    ia.loadScreen.displayCover(true, 'Verifing Mandatory Contacts Data');
    ia.loadScreen.changeProgress({load: true});
    updateMandatoryContactData();

    //Save additional contacts data
    ia.loadScreen.displayCover(true, 'Verifing Additional Contacts Data');
    ia.loadScreen.changeProgress({load: true});
    updateAdditionalContactData();

if(document.form1.btn-group[0].checked == true) {
alert("Please select On-Site or Remote Surveillance Type");

}
    }


text:
Q: Json-Server DELETE without CASCADE? I am using json-server for mock REST API in an Angular project.   Works well for everything except DELETE wherein any and all of my json objects that contain more than one ID column are deleted anytime a DELETE request is made.
Let's say I have the following set of objects with related 'accountId' ID columns:
"accountfiles": [{
    id: 9001,
    accountId: 1001,
    filename: 'test.docx',
  },  {
    id: 9002,
    accountId: 1002,
    filename: 'test.txt',
  },  {
    id: 9003,
    accountId: 1001,
    filename: 'taxes.pdf',
  },  {
    id: 9004,
    accountId: 1003,
    filename: 'layout.ppt',
  },  {
    id: 9005,
    accountId: 1002,
    filename: 'Spreadsheet 5.xlsx',
  }
)];

And these are available at:
http://localhost:3000/accountfiles
And I delete this individual object:
http://localhost:3000/accountfiles/1001
The entire collection is deleted as well as all other collections that contain multiple ID columns.
Further, if I have an Account class:
"account": [
  {
    "id": 1001,
    "isInactive": false,
    "name": "HK Asset Group",
    "accountLogoUrl": "/assets/img/logos/logo2.png",
    "location": "Minneapolis MN 55434"
  }
]

And I delete the account id: 1001, the entire accountfiles collection is deleted as well.
I've tried using --no-cascade-delete startup flag to no avail (does not seem to be part of the current json-server build).
Is it not possible to host related data in json-server and do deletes effectively?
Thanks

A: A late answer but better late than never.
The issue is still relevent.
I managed to bypass such a behaviour by redirecting all deletes to a custom middleware.
To be upfront, dealing with complex aspects requires a middleware that could handle all of the compliancies related to your logic.

const SERVER = JSON_SERVER.create();
.
.
.
SERVER.delete('/api/entities/:id', (req, res) => dbUtils.deleteEntities(req, res));

and then in your deleteEntities() method just get a reference to your db and manage the records accordingly:

var ROUTER = JSON_SERVER.router('./db/db.json');
.
.
.
var paramID = req.params?.id;
var db = router.db;
var ents = db.get('entitieAs').valueOf(); // gets entitieAs collection

db.set('entitieAs', ents.filter(element=>element.id === paramID)).write(); // replace the target collection by the resulting collection after delete


text:
Q: VBScript can create text file but can't delete file (permission denied)? I create a .vbs file (that can: creat text file -> Open notepad.exe -> delete the file above) like this:
' Create a new file
Dim objFS, objFile
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.CreateTextFile("D:\Folder\Textfile.txt")
objFile.WriteLine ("sample text")

' Run a program and wait
WScript.CreateObject("WScript.Shell").Run "notepad.exe", 1, true

' Delete file
objFS.Deletefile("D:\Folder\Textfile.txt")

But when I run it, after close notepad window, it show error message:
Line: 10
Char: 1
Error: Permission denied
Code: 800A0046
Source: Microsoft VBScript runtime error

I don't know why this .vbs can't not delete the text file? Thank you for any help!

A: You have to close the file handle in the script before trying to delete it.
' Create a new file
Dim objFS, objFile
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.CreateTextFile("D:\Folder\Textfile.txt")

'write to the file
objFile.WriteLine ("sample text")

'close the file
objFile.close
set objFile = Nothing

' open the file in notepad, and wait
WScript.CreateObject("WScript.Shell").Run "notepad.exe D:\Folder\Textfile.txt", 1, true

' Delete file
objFS.Deletefile("D:\Folder\Textfile.txt")

set objFS = Nothing


text:
Q: Why Quartz 2.* does not cleanup indexes in Postgres database? I use Quartz 2.* in cluster mode. Quartz uses Postgres database for clustering feature. Database size grows as the Java application works. The only reason for this growing is that Quartz does not cleanup it's indexes on tables:
quartz.qrtz_triggers
quartz.qrtz_cron_triggers
quartz.qrtz_fired_triggers
quartz.qrtz_scheduler_state

One week of application working increases database by ~500 MiB. I have 5 microservices which use Quartz, so the whole database grows by 5*500 MiB each week.
Then I need to execute manually:
REINDEX TABLE quartz.qrtz_cron_triggers;
REINDEX TABLE quartz.qrtz_fired_triggers;
REINDEX TABLE quartz.qrtz_triggers;
REINDEX TABLE quartz.qrtz_scheduler_state;

And after it the database's size becomes adequate.
Is it normal?
How to configure Quartz/Postgres to cleanup it's stuff atomatically?

A: While not being that experienced with the quartz / postgres combination, this seems to be an index fragmentation problem.
I.e. index size grows and performance suffers while table rows are being updated or deleted repeatedly. This could be the case if your quartz jobs run in short intervals while creating a corresponding number of entries in your cluster database.
Reindexing the database tables (a common maintenance procedure) refreshes the index and potentially reduces the index size also.
I would propose to create a database job running the reindexing commands on a regular basis, from what i found this can be done using either the pg_cron or pgAdmin tool.
You will also find some useful queries regarding index size/usage and index bloat in the PostgreSQL Wiki:
https://wiki.postgresql.org/wiki/Index_Maintenance


text:
Q: Reading text file into two arrays C#(Edited) To clarify, I want all the odd lines of the text file read to an array called cPhone and all the even lines read to an array called cName.This is not reading from an array to two separate arrays, but from a text file and creating those arrays. I should have been more clear in the original question, so hopefully this makes a difference.
While it may appear that this question has been answered, I have searched for 3 nights now, across multiple sites and can't find something that helps me. And not just helps, but explains why it works (I want to learn, not just copy).
I want to read a text file into two arrays that I can use later. Shortened version of the list below:
0884006750
Blazing Fire
0350237000
Iron Engineering
0798726565
Custom Couture

I'd like to have all the phone numbers in one array and the business names in the other, but I am at a loss how to do this and think there has to be a simple answer. I've seen a LOT of answers about delimeters, and I understand that I could do this easily if they were on the same line separated by a comma or space, but I don't know that it can work with this file. I am new to programming, but I've tried the solutions I've found and nothing seems to work, either that or I don't understand what I've read.
This is what I'm trying to work with, but I'm getting an exception. I've tried changing the order and all.
string cCustomer = "customer.txt";
string[] cName = new string[0];
int[] cPhone = new int[0];

private void SplitArray()
{
    int counter = 0;
    string line;
    StreamReader fileSR = new StreamReader(cCustomer);
    line = fileSR.ReadLine();
    while (line != null)
    {
        cPhone[counter] = int.Parse(fileSR.ReadLine());
        cName[counter] = line;
        counter ++;
        line = fileSR.ReadLine();
    }
    fileSR.Close();

    for (int i = 0; i < counter; i++)
    {
        phoneComboBox.Items.Add(cPhone[i]);
    }

}

Chances are there is a lot wrong with this as I've never attempted this properly before, I've always had instructions to follow. Any help would be greatly appreciated.


text:
Q: Latex two column text figures bad positioning I have two figures each of which has two part a and b. However, their position in the page is not good and they are not in the center. This is my Latex code. How can I make them to be located more symmetric?
\documentclass{sig-alternate-05-2015}
\usepackage[backend=biber]{biblatex}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{csquotes}
\usepackage{amsmath}
\usepackage{subfig}

\begin{document}
 \begin{figure*}[tbh]
\centering
\subfloat[][]{
    \includegraphics[width=3.25in]
    {figures/gini.pdf}
  \label{fig:gini}
}%
\qquad
\subfloat[][]{\includegraphics[width=3.25in]
{figures/coverage.pdf}
\label{fig:coverage}
}%
\caption{Trade-off between nDCG and (a) gini and (b) catalog coverage for different $\lambda$.}%
\label{fig:hist}
\end{figure*}

\begin{figure*}[tbh]
\centering
\subfloat[][]{
    \includegraphics[width=3.25in]
    {figures/lo.pdf}
  \label{fig:lorenzCluster}
}%
\qquad
\subfloat[][]{\includegraphics[width=3.25in]
{figures/lo2.pdf}
\label{fig:lorenz}
}%
\caption{Lorenz curve for the (a) items recommended from each cluster and (b) total items recommended.}%
\label{fig:hist}
\end{figure*}
\end{document}

Here are figures:

A: Let convert my comments to an answer:

*

*test with demo options of graphicx package show, that you poroblem arise from white space around your images. To see this, add frame around images:

\fbox{\includegraphics[width=3.25in]{figures/coverage.pdf}}

*

*white space around images can be trimmed with includegraphics option trim:

\includegraphics[trim=<left> <bottom> <right> <top>, ...]{...}
or even beer to redraw diagrams for example with pgfplot. Since diagrams are relatively simple, the learning of pgfplots -- if you not familiar with it -- is not so difficult (well, bunch of comments above says opposite :( ) .
An example of redrawing, which can serve for all similar diagrams, is:

Code for above image is:
\documentclass[tikz,
               border=3mm
               ]{standalone}%
\usepackage{pgfplots}
\pgfplotsset{compat=1.14,
% common options for graphs
    width=0.45\linewidth,
    grid=both,
    minor grid style={very thin,gray!10},
    every axis label/.append style={font=\small\sffamily},
    scaled ticks=false,
    every tick label/.append style={font=\scriptsize\sffamily,
                                    /pgf/number format/precision=3,
                                    /pgf/number format/fixed},
            }
\usetikzlibrary{intersections, patterns}

\begin{document}
\begin{tikzpicture}
    \begin{axis}[
% specific options
minor tick num=4,
xlabel={Gini},
ylabel={nDCG@10},
xmin=70, xmax=85,
ymin=0.01, ymax=0.05,
                    ]
\addplot coordinates   { (72.5,0.025) (73.0,0.027) (73.5,0.027)
                         (75.0,0.018) (76.0,0.031) (79.0,0.039)
                         (82.0,0.041) (83.8,0.039) (84.2,0.047)
                        };
    \end{axis}
\end{tikzpicture}
\end{document}

Coordinates is estimated from your image and should be adjusted to correct values. To adopt to others image you need to change coordinates and in case of more curves in graph for each of them add addplot command with belonging coordinates.
If it is worth to learn `pgfplots? Depends. In comments are some thoughts (pros and cons) about this, also are some other proposition ... I only like to encourage to start learning. You newer know, when this will more than welcome at some of your future projects, articles etc. In first you can search for similar graphs here on site or look in package documentation and then accommodate closest example to your specifics ... and if you will stuck in drawing, ask here for help.


text:
Q: How do i add an additional property to each element in array, how do i then use that property to affect the style of the output How can i set a color to each object in array ?
For example i want to set  "Zen" (green) , "bless" (yellow).
$prices = array(
    " Zen " => $chk_prices['zen'],
    " Bless " => $chk_prices['bless'],
    " Credits " => $chk_prices['credit'],
    " Chaos " => $chk_prices['chaos'],
    " Creation " => $chk_prices['creation'],
    " Rena " => $chk_prices['rena'],
    " Stone " => $chk_prices['stone'],
    " Life " => $chk_prices['life'],
    " Soul " => $chk_prices['soul']);

Can someone help me with this.
Thanks.

A: looks like you need a multi dimensional array
$prices = array(
"Zen" => ["price" => $chk_prices['zen'], "color" => "green"],
and so on....
);
think of it like this
Zen is an array within an the $prices array (which now isn't the best name for it as it contains other properties not just prices)
$prices = array(
   "zen" => array(
        "price" => $chk_prices['zen'],
        "color" => "#7396FF"
    ),
    "Bless " => array(
        "price" => $chk_prices['bless'],
        "color" => "#7396FF>"
    )
)

to access the price of zen you would use $prices['zen']['price']
a better way to do this would be to use objects, but that's a whole other conversion.
i edited it again, because now i see you want to add styling.
you cant add styling to the output in this way. you need to echo some code using the values from the array.
for instance
echo 'zen price is '.$prices['zen']['price'].'';

[i haven't tested this code]


text:
Q: Spreadsheet Manipulation Tricks w/ Python's Pandas I'm giving myself a crash course in using python and pandas for data crunching.  I finally got sick of using spreadsheets and wanted something more flexible than R so I decided to give this a spin.  It's a really slick interface and I'm having a blast playing around with it.  However, in researching different tricks, I've been unable to find just a cheat sheet of basic spreadsheet functions, particularly with regard to adding formulas to new columns in dataframes that reference other columns.
I was wondering if someone might give me the recommended code to accomplish the 6 standard spreadsheet operations below, just so I can get a better idea of how it works.  If you'd like to see a full size rendering of the image just click here

If you'd like to see the spreadsheet for yourself, click here.
I'm already somewhat familiar with adding columns to dataframes, it's mainly the cross-referencing of specific cells that I'm struggling with.  Basically, I'm anticipating the answer loosely looking something like:
table['NewColumn']=(table['given_column']+magic-code-that-I-don't-know).astype(float-or-int-or-whatever)

If I would do well to use an additional library to accomplish any of these functions, feel free to suggest it.

A: In general, you want to be thinking about vectorized operations on columns instead of operations on specific cells.
So, for example, if you had a data column, and you wanted another column that was the same but with each value multiplied by 3, you could do this in two basic ways. The first is the "cell-by-cell" operation.
df['data_prime'] = df['data'].apply(lambda x: 3*x)

The second is the vectorized way:
df['data_prime'] = df['data'] * 3

So, column-by-column in your spreadsheet:
Count (you can add 1 to the right side if you want it to start at 1 instead of 0):
df['count'] = pandas.Series(range(len(df))

Running total:
df['running total'] = df['data'].cumsum()

Difference from a scalar (set the scalar to a particular value in your df if you want):
df['diff'] = scalar - df['data']

Moving average:
df['moving average'] = df['running total'] / df['count'].astype('float')

Basic formula from your spreadsheet:
I think you have enough to this on your own.
If statement:
df['new column'] = 0
mask = df['data column'] >= 3
df.loc[mask, 'new column'] = 1


text:
Q: how to directly pass value of a variable from 1st activty to 3rd activity using putextra? how to directly pass value of a variable from 1st activity to 3rd activity using putextra?
For example:
I have a variable A in the first screen (first activity) if I hit the button it will show the 2nd screen. The 2nd screen(2nd activity) has a button. If I click the button it will open the 3rd screen(3rd activity) and it will show the variable A in the textview of 3rd screen (3rd activity).
how can I pass the value of variable A from the first screen DIRECTLY to the third screen(third activity). (1st->3rd)
is it possible to directly pass the value ? or should I pass it in 2nd activity first before passing to 3rd activity (1st->2nd->3rd)

A: Actually its not possible to go from 1st activity to 3rd directly...
You must have to follow the activity stack..
So if you want the data to be passed from 1st to 3rd follow by
1st -> 2nd -> 3rd
with the use of intent suggested by @Lalit Poptani

A: You can pass any value between any two Activities you want. You just need to do two things:

*

*In your FirstActivity:
Intent intent = new Intent(context, ThirdActivity.class);
i.putExtra("value_key", value); //valus is a String
startActivity(intent);

*In your ThirdActivity's onCreate():
Bundle b = getIntent().getExtras();
String value = (String) b.getString("value_key");

A: You may keep them as static objects and retrieve as Myclass.myObject. But what you really want is impossible.

A: You can use a database, SharedPreferences, Application, Static Methods and more for share data between Activitys. Look here


text:
Q: Calling another function within Foundation's Reveal with React I haven't seen anything regarding my issue here: after opening up the modal, I have a button that when clicked, it calls another function but nothing happens. This is a slimmed down example with React:
_sayHi: function() {
 console.log("Hi");
}

_loop: function() {
 var foo = this.props.bar.map( function(a,b){
  return(

     <button className="small button success" data-open="exampleModal1">Open</button>

Are you sure

This action cannot be undone and it's final!

       <button className="close-button" data-close="" aria-label="Close modal" type="button">
          ×
       </button>

          <button className="small button success" onClick={this._sayHi}>Hi</button>
          <button className="small button alert" data-close="">Close</button>

  )
 }.bind(this));
  return(
{foo}
)
},

render: function() {
 return(
{this._loop()}
)
}

If I should move the function button outside the modal, the button works as it should. Do I need to do something special?
What I want: Open the modal (which works), then click a button to call a function (does nothing, nothing in console).
Edit:
I see why this is not working. Foundation's Reveal is not mounted inside the prop, it's outside so this is not being referred to my Component:

 // React component

 // Modal when closed

I guess foundation's modal is not ideal in this case?

A: buttons will try to submit by default maybe you could try the following
_sayHi: function(e) {
 e.preventDefault();
 console.log("Hi");
}

You should also wrap the return from your map function in a single div like so
_loop: function() {
  var foo = this.props.bar.map( function(a,b){
  return(

      <button className="small button success" data-open="exampleModal1">Open</button>

Are you sure

This action cannot be undone and it's final!

        <button className="close-button" data-close="" aria-label="Close modal" type="button">
          ×
        </button>

          <button className="small button success" onClick={this._sayHi}>Hi</button>
          <button className="small button alert" data-close="">Close</button>

  )}.bind(this));
  return(
{foo}
)
}


text:
Q: CSS relative and absolute, ignoring z-index I have a grid of li's all floated left with a fixed width/height. The problem is when I hover over the Latest Product in the centre, the div which is displayed in not positioned on top and sits under the next li's
EDIT/BREAKTHROUGH:
If I remove the z-index on the relative li this works in all browsers except IE7

A: Try changing the hovered LI's z-index to make it greater than it's siblings, like so in your productOver function:
function productOver(){
  var product_html = $(this).find(".product_html");
  // Generate HTML only on first hover.
  if(product_html.data("generated") != true){
    var tis = $(this);
    product_html.find(".name").html(tis.find("h2").html());
    product_html.find(".price").html(tis.find(".price").html());
    product_html.data("generated", true);
  }
  $(this).css('z-index','10'); //add this
  product_html.stop().fadeTo('fast', 1).show();
}

and of course set it back to it's default on productOut
function productOut(){
  $(this).css('z-index', '8'); //add this
  $(this).find(".product_html").stop().fadeTo('slow', 0, function() {
    $(this).hide();
  });
}

A: Put z-index: 1; to the bottom row LIs and higher z-inded to all the elements that appear on hover. That should get you started.


text:
Q: Is there a way to change the number of output ports in a component at run-time? In my application I will not know the number of output ports for the component until a user specifies a configuration file. I attempted to do this by leaving the number of output ports in the .scd.xml file at zero. When I select the configuration file through the IDE on the property change event I call releaseOutPorts() and delete any existing port objects.
In my example component I create N new output ports by creating new bulkio::OutFloatPort objects, and activate them in the same way the custom ports are activated in the USRP_UHD component by calling ossie::corba::RootPOA()->activate_object(port)
and calling registerOutPort. I receive no errors when I do this but I cannot see the ports show up in either the sandbox or the IDE. Is it a problem because no port information is supplied in the .scd.xml file? Can anyone shed some insight into how the ports are currently enumerated when a component is dragged into the chalkboard or loaded into the sandbox?

A: You are correct; the IDE uses the the scd.xml file to display the ports.  There isn't a way to programmatically obtain a list of all ports.


text:
Q: Change date format which going in mail but it showing an error I have tried Utilities.formatDate but it showing an error

Exception: The parameters (String,String,String) don't match the method signature for Utilities.formatDate.

function findCell() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("DELEGATION");
  var lr = sheet.getLastRow();
  var dataRange = sheet.getRange(5,1,lr-4,9).getValues();

  for (var i = 0; i < dataRange.length; i++) {
    for (var j = 0; j < dataRange[i].length; j++) {
      var taskAsignDate = dataRange[i][0];
      var taskId = dataRange[i][1];
      var doerName = dataRange[i][2];
      var taskName = dataRange[i][4];
      var dueDate = dataRange[i][5];
      var taskAsignBy = dataRange[i][6];
      var date = new Date;
      var status = dataRange[i][1];
      var htmlfile = HtmlService.createTemplateFromFile("email")
      htmlfile.taskAsignDate = Utilities.formatDate(taskAsignDate,"GMT","dd-mm-yy");
      htmlfile.taskId = taskId;
      htmlfile.doerName = doerName;
      htmlfile.taskName = taskName;
      htmlfile.dueDate = dueDate;
      htmlfile.taskAsignBy = taskAsignBy;
      htmlfile.status = status;
      var htmlforemail = htmlfile.evaluate().getContent();
      if (dataRange[i][j] == "Pending" && doerName == "Mr. Deepak Raj" && dueDate<=date) {
         Logger.log(dataRange[i],[j]);
         GmailApp.sendEmail("abc@abc.com","Test HTML","HTML FILE",{htmlBody:htmlforemail});
      }
    }
  }
}

A: The first parameter of Utilities.formatDate should be a Date object, but the value of taskAsignDate is a string.
You need to review your spreadsheet and verify that the values of first column from the source range (sheet.getRange(5,1,lr-4,9).getValues()) are all dates.
Related

*

*Google scripts - Formatting date from a form input


text:
Q: ESD diodes - on what lines? I'm just learning about the use of ESD diodes to protect your system.
Although I've read multiple cases on this being more a black box magic than true science, I'm still going to try.
On what 'signals' or 'traces' from my PCB would it be wise to place some diodes? I do not mean a specific PCB but more 'in general.' What's a rule of thumb? Incoming power lines? Only RX/TX pins or all I/O pins?
Also, I have an example as such which is for an isolated connector. Would it make sense to place such a ESD protection on here? Why? Why not? -> My mind says it is isolated so would be rather safe already.


text:
Q: Understanding Quantum Measurement in infinite dimensional systems I have been relearning quantum mechanics recently since I realized I got stuck in some misunderstanding of fundamentals when trying to solve certain problems. My question is actually simply the following:
What is the relationship between the measurement postulate, stated in terms of projection valued measures, and the eigenvectors of observables in the case of an infinite dimensional Hilbert space?
Now here is some context to maybe see where my confusion comes from:
Most QM textbooks advertise that observables are postulated to be self-adjoint operators because the spectral theorem assures you that their eigenvectors form a basis, which is connected to the measurement postulate via the idea that when you expand the state of the system in the eigenvectors of an observable, the coefficients of this expansion are the probability amplitudes for the measurement of said observable. I was stuck with the idea that somehow you can always use the eigenvectors of some observable to decompose any state. However, now I know that this is only true for finite dimensional Hilbert spaces.
On infinite dimensional Hilbert spaces, the eigenvectors of self-adjoint operators need not even be in the Hilbert space (for example, the momentum operator $\hat{p}:D(\hat{p})\rightarrow L^2(\mathbb{R})$, $\hat{p}=-i\partial_x$, which has a self-adjoint extention, has eigenvectors $\psi_p(x) = e^{ipx}$, which aren't square integrable functions. Even so, while they do not really form a basis in the Hilbert space, they still play an important role (related to Fourier transforms).
Now, measurement, formulated in a more rigorous manner, has to do with the actual spectral theorem, namely that for any self-adjoint operator there exists a projection-valued measure $P_A$
such that $A$ can be represented in terms of the Lebesgue-Stieltjes integral as
$$A = \int_\mathbb{R} \lambda dP_A(\lambda)$$
Now from my understanding so far, PVMs on finite dimensional spaces and the projectors described in QM texbooks as say $P_\psi = |\psi><\psi|$ in Dirac notation (which again is a notation enabled by working with bases given by the eigenvectors of observables) are actually two sides of the same coin so to say. But I cannot seem to wrap my head around (or find any resource on the internet) about the infinite dimensional case.
Here would be some of the questions I'm pondering regarding this:

*

*What is the connection between PVM and eigenvectors in the case of the momentum operator for example?

*Are eigenvectors of operators actually relevant in the infinite dimensional case in general? (or the momentum/position are some very special cases?)

*If the answer to 2 is affirmative, what happens to operators whose eigenvectors have discontinuities with infinite jumps? (one such an example I can think of is: $\hat{T}:D(T)\rightarrow \{f \in L^2(\left[0,2\pi\right])|f(0)=f(2\pi)\}$, $\hat{T} = i(cos^2 (\theta) - 1/2)\frac{d}{d \theta} + i\, sin(\theta) cos(\theta)$, for which there should be a self-adjoint extension, or rather some $D(T)$ for which it is self-adjoint - if I'm wrong scream at me, please. The primitive $\int \frac{sin(\theta)cos(\theta)}{cos^2(\theta)-1/2} d\theta$ diverges to $+\infty$ at the points $\theta_0\in\{\pi/4,\, 3\pi/4,\, 5\pi/4,\, 7\pi/4\}$ ).

*How would one treat the measurement of the operator described in 3.?


text:
Q: strings.h and wrapping this macro with a macro check of whether I infer from Google search results that strings.h (from here) is for UNIX systems. I would like to wrap the following line with a macro check of whether the host's operating system is Linux/UNIX. It would be much appreciated to hear suggestions about it. Thanks in advance.
#include <strings.h>

A: strings.h contains only a few functions, most of which are simply different names for functions that are in the standard library (such as bcmp() <--> memcmp()). If your code uses these functions, instead of throwing #ifdefs around why not just write your own set?
Then everyone gets to use them and be happily conditional-compilation free.
Here's a not-fully-tested set of functions in the public domain that you can use at your own risk:
#include <string.h>
#include <ctype.h>

int bcmp(const void * p1, const void * p2, size_t n)
{
    return memcmp( p1, p2, n);
}

void   bcopy(const void * src, void * dst, size_t n)
{
    memmove( dst, src, n);  /* note different order of args - yuck */
}

void   bzero(void * p, size_t n)
{
    memset( p, 0, n);
}

char   *index(const char * s, int c)
{
    return strchr( s, c);
}

char   *rindex(const char * s, int c)
{
    return strrchr( s, c);
}

int    strcasecmp(const char* s1, const char* s2)
{
    for (;;) {
        int c1 = tolower( *((unsigned char*) s1++));
        int c2 = tolower( *((unsigned char*) s2++));

        if ((c1 != c2) || (c1 == '\0')) {
            return( c1 - c2);
        }
    }
}

int    strncasecmp(const char* s1, const char* s2, size_t n)
{
    for (; n != 0; --n) {
        int c1 = tolower( *((unsigned char*) s1++));
        int c2 = tolower( *((unsigned char*) s2++));

        if ((c1 != c2) || (c1 == '\0')) {
            return( c1 - c2);
        }
    }

    return( 0);
}

int    ffs(int v)
{
    unsigned int x = v;
    int c = 1;

    /*
     * adapted from from
     *      http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightBinSearch
     *
     * a modified binary search algorithm to count 0 bits from
     *  the right (lsb).  This algorithm should work regardless
     *  of the size of ints on the platform.
     *
     */

    /* a couple special cases */
    if (x == 0) return 0;
    if (x & 1)  return 1;   /* probably pretty common */

    c = 1;
    while ((x & 0xffff) == 0) {
        x >>= 16;
        c +=  16;
    }
    if ((x & 0xff) == 0) {
        x >>= 8;
        c +=  8;
    }
    if ((x & 0x0f) == 0) {
        x >>= 4;
        c +=  4;
    }
    if ((x & 0x03) == 0) {
        x >>= 2;
        c +=  2;
    }

    c -= (x & 1);
    c += 1;     /* ffs() requires indexing bits from 1 */
                /*   ie., the lsb is bit 1, not bit 0  */
    return c;
}

A: One option would be:
#ifndef _WIN32
#include <strings.h>
#endif

Per MSDN, _WIN32 is "defined for applications for Win32 and Win64. Always defined."
A compiler or standard library for an operating system other than Windows is, of course, free to define _WIN32, but that would be... most unusual.


text:
Q: How to plot directed acyclic lattice graph in R I need to plot directed acyclic lattice graph of size m x n, similar as in this picture, but without edges on the contour and without vertexes on the corners:

Is this possible to do with graph.lattice function? If yes, how to set such vertexes' labels (i.e. (x,y) format, not just an  integer number) and remove mentioned edges and vertexes? Moreover, is it possible to plot graph in such position (as in a picture) without using tkplot function and rotating it then?

A: I am not exactly sure what you mean by 'without edges on the contour', but here are some points:

*

*Read ?igraph.plotting for the complete list of plotting parameters.

*If you don't want the frame on the vertices, set vertex.frame.color to the same value as vertex.color.

*Use layout.grid, see ?layout.grid.

*Use vertex.label to set the labels.

*If you want to omit some edges, then delete them, or set their width to zero or their color to background color.

*If you want to omit some vertices, then attach the coordinates calculated by layout.grid as vertex attributes, and then remove the vertices from the graph.

Something like this could work:
g <- graph.lattice( c(5,5) )
lay <- layout.grid(g)
V(g)$x <- lay[,1]
V(g)$y <- lay[,2]
V(g)$color <- V(g)$frame.color <- "darkolivegreen"
V(g)$label.color <- "lightgrey"
V(g)$label <- paste(V(g)$x+1, V(g)$y+1, sep=",")

To remove the edges, you can select them based on the coordinates of the vertices:
torem <- c(E(g)[ V(g)[x==0] %--% V(g)[x==0] ],
           E(g)[ V(g)[y==0] %--% V(g)[y==0] ],
           E(g)[ V(g)[x==4] %--% V(g)[x==4] ],
           E(g)[ V(g)[y==4] %--% V(g)[y==4] ])
g2 <- delete.edges(g, torem)

And then remove the vertices and plot:
g3 <- delete.vertices(g2, V(g2)[ x %in% c(0,4) & y %in% c(0,4) ])
plot(g3, layout=cbind(V(g3)$x, V(g3)$y))


text:
Q: Not able to load the third party dll in IIS hosted rest WCF service I have hosted a Rest WCF to my IIS 7. I tested the everything and it works fine except to importing the dll. My instance class code are following:
[OperationContract, WebInvoke(Method = "GET", UriTemplate = "/getname?name={name}&age={age}", ResponseFormat = WebMessageFormat.Json)]
    bool getname(string name, string age);

[OperationContract, WebInvoke(Method = "GET", UriTemplate = "/getcallfromdll?name={name}&age={age}", ResponseFormat = WebMessageFormat.Json)]
    bool getcallfromdll(string name, string age);

Whereas the definition of above methods are :
public string getname(string name, int len)
    {
        return "It's working";
    }
public string getcallfromdll(string name, int len)
    {
        return UnsafeNativeMethods.getvalue(name, len); //Unsafe.. is a internal structure
    }

internal static class UnsafeNativeMethods
    {
        const string _dllLocation = "school.dll";

        [DllImport(_dllLocation, CallingConvention = CallingConvention.Cdecl)]
        public static extern bool getvalue(string name, String len);
     }

When  tried to run localhost:8085/service.svc/getname?name=kajn&len=21: it returns "It's working", which is correct but whenever i tried to call localhost:8085/service.svc/getcallfromdll?name=kajn&len=21: It returns The server encountered an error processing the request. See server logs for more details.
I searched for it and somehow i got to know that it all happening due to service are not bale to find the DLL. To solve this i tried to put my dll in following places but it didn't help me:( :

*

*system32/inetsrv

*SysWOW64/inetsrv

*in bin folder

*i also put the same folder where the project exists.

But nothing works for me. Please suggest me a solution.
NOTE: there are no problem with the dll because i call the dll methods from a self hosted WCF application and it was working perfectly. At that time i put my dll into bin/debug folder.

A: I would guess that it could be related to the fact that IIS may copy binaries to shadow location and when it does that it may not realize the unmanaged dll may be required. Is your "school.dll" part of your WCF solution and is it added as an reference? Also does it depend on any other unmanaged dlls? Next time you get that error you can try to search your system to find all instances of your WCF dll, then if you find one in shadow location, take a look if your "school.dll" is there too.

A: Well, you should turn on WCF Tracing on the server and see what the actual error/exception is. But I would suspect some sort of permissions-related error... i.e. the DLL can be found, but the IIS worker process doesn't have the right permissions to read it or to execute methods in it. Just for debugging purposes, try setting the permission on the DLL such that it can be read/executed by "Everyone".


text:
Q: JAXB not generating XML as per the Annotations (JDK 1.7)     import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;

    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;

    public class JavaToXMLDemo {
      public static void main(String[] args) throws Exception {
    JAXBContext context = JAXBContext.newInstance(Employee.class);

    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Employee object = new Employee();
    object.setCode("CA");
    object.setName("Cath");
    object.setSalary(300);
    object.setProperties(new PropertiesMap());
    m.marshal(object, System.out);

  }
}

@XmlRootElement(name="Employee")
@XmlAccessorType(XmlAccessType.FIELD)
class Employee {
  private String code;

  @XmlElement(name = "Name")
  private String name;

  private int salary;

  @XmlElement(name = "Properties")
  protected PropertiesMap params;

  public String getCode() {
    return code;
  }

  public void setCode(String code) {
    this.code = code;
  }

  public PropertiesMap getProperties() {
      return params;
  }

  public void setProperties(PropertiesMap value) {
      this.params = value;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getSalary() {
    return salary;
  }

  public void setSalary(int population) {
    this.salary = population;
  }
}

  @XmlRootElement(name="Properties")
  class PropertiesMap<K,V> extends HashMap<K,V>
  {

  }

The above code generates the below XML with JDK 1.6
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee>
    CA
    <Name>Cath</Name>
    <salary>300</salary>
    <Properties/>
</Employee>

and this on JDK 1.7
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee>
    CA
    <Name>Cath</Name>
    <salary>300</salary>
    <params/>
</Employee>

Why does the Marshaller behave differently?

A: You should use @XmlElementWrapper instead of @XmlElement for your Properties map.
See http://blog.bdoughan.com/2013/03/jaxb-and-javautilmap.html use case #2.