text:
Q: Cannot load Packages available in share\octave\packages but not listed in share\octave\octave_packages The short story:
In the directory ...\octave-4.2.1\share\octave\packages there were initially 45 package subdirectories (with .m and other files), for instance financial-0.5.0.
But I could not find a way to use them.
In more detail:
I have unzipped the portable (.zip) version of Octave 4.2.1 64 bit for Windows, at 8:00am (useful info for later), into C:\Users\user1\DOCUME~1\apps\OCTAVE~1.1 (originally C:\Users\user1\Documents\apps\octave-4.2.1).
I have then installed symbolic-2.6.0 (at 8:19am) with
>> pkg install symbolic-2.6.0

and this one is now available, e.g.,
>> pkg list
Package Name  | Version | Installation directory
--------------+---------+-----------------------
    symbolic  |   2.6.0 | C:\Users\user1\DOCUME~1\apps\OCTAVE~1.1\share\octave\packages\symbolic-2.6.0

As per official documentation,
>> pkg global_list
C:\Users\user1\DOCUME~1\apps\OCTAVE~1.1\share\octave\octave_packages

gives "the file in which to look for information on globally installed packages".
That file does not have any information on any of the 45 built-in packages. It only has info on symbolic.
I guess this is already enough for the packages not to be available.
Moreover, the first line of the file states # Created by Octave 4.2.1, ... 08:19:23 2017 GMT <unknown@unknown>, as if it did not exist prior to my installing symbolic.
Questions:
Q1: Is there any way to make the packages available?
I guess I could install each of them, but I also guess that is not the way the .zip provided is intended to be used.
Q2: Why would there be no octave_packages provided?

PS: Inspired by this old link, I checked if there was an octave_packages somewhere else in the tree... there is none.
PS2: Clarifications called for given a comment:
I did not do anything other than expanding the original zip file, and installing symbolic. The answers are then implied, but I make them explicit anyway.

Where did you install the rest? I did not do it; they were built into the .zip.

How did you try to install them? I did not.

Why are you not installing via forge? Because I already had the installer for symbolic downloaded.

Did you try setting a local_list in the same way as global_list (and as described in help pkg)? I did not set or try to set either local_list or global_list.

Have you tried creating an octave_packages file yourself? No. It was created automatically upon installing symbolic.

Did you set a pkg prefix before installing? No.

A: Do
pkg rebuild
From the documentation:

'rebuild'
      Rebuild the package database from the installed directories.
      This can be used in cases where the package database has been
      corrupted.

Once you do this, you should see all packages listed with the pkg list command and you can load them as necessary.
Having said that, I would encourage you to report this as a bug to the octave bug tracker (if it's not there already), since, I agree, this is unlikely to be the  desired first-run experience (it certainly isn't via the .exe installer). Someone must have forgotten to include a valid, pre-generated octave_packages file, which as you point out is missing from the zipfile.

A: This is detailed in the Wiki:

If you instead installed Octave from the .zip archive, you need to first rebuild the package list on your local machine. (The command above will produce a blank output and packages will be inaccessible before rebuilding.) Do this by typing the following command:
pkg rebuild

It has been this way since v4.01 according to an earlier mailing list discussion. According to the person making the primary Windows build,

the installer execute "pkg rebuild" in the windows console.
  For zip version, you need execute by yourself.

So this is a known issue with the 'portable' windows version. I cannot comment on whether there's a particular reason (size?) not to have the pkg rebuild done prior to zipping and releasing. There doesn't seem to be a good way to relay this issue/instruction to the user and it has created confusion before.
I could not find an associated bug, so one could be submitted to http://bugs.octave.org, it would at least formally track the issue even if there's no maintainer side interest in fixing it.
EDIT:  there is now a bug related to this issue:  Octave Bug #51632


text:
Q: Push notification in electron Is there any way to use firebase push notification in electron?I want to create a push notification for my electron app which is a chat app and whenever a new message comes I want to get that notification.But I did not get any good material online to implement it.How can I do it?

A: You can use Websocket.
Python Snippet for websocket
Client Side:
from ws4py.client.threadedclient import WebSocketClient
client_url = "ws://server_url + "/websocket/create
ws_client = WebsocketClient(client_url)
ws_client.connect()

Server Side: Assuming you have a server with server_url serving the api /websocket/create:
from ws4py.websocket import WebSocket

class ws_server(Websocket):
    WebSocket.__init__(self, *args, **kwargs)

class WebSocketHandler(object):

    @cherrypy.expose
    def create(self):
        # wsInstance is of type ws_server. Must set userName.
        wsInstance = cherrypy.request.ws_handler

And in the Server's config:
cherrypy.tree.mount(WebSocketHandler(), '/websocket',
                            config={
                                '/': {
                                    'tools.response_headers.on': True,
                                    'tools.sessions.locking': 'explicit',
                                    'tools.websocket.on': True,
                                    'tools.websocket.handler_cls': ws_server,
                                },
                            })

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sql blind Injection I have c# form based web application. When i am scanning the the application through Acunetix web scanner its giving me the a blind sql injection on a add module section. The report generated by the Acunteix is
POST (multipart) input ctl00$ContentPlaceHolder1$ddlRecommendoffer was set to -87
POST /

This ddlRecommendoffer is a drop down list and gets the values from database and when i am storing the form in the database i am getting the value of this drop down as
 ddlRecommendoffer.SelectedValue.ToString()

DDL Value  should ideally be an int(Id of the Row from the database)
i am using a store procedure with  parameters to insert it into database  which should stop Sql injection but then why is it showing me BLIND SQL INJECTION on this field..

A: A SQL injection is called blind when there is no direct feedback from the injection attempt, e.g., when the result of the SQL statement is not returned back to the user.
Your application may still be vulnerable although you're using a stored procedure if it builds the query with the parameters dynamically:
Create Procedure sp_EmployeeSelect
  @EmployeeName NVarchar(100)
AS
  Declare @SQLQuery AS NVarchar(4000)
  SET @SQLQuery = 'SELECT * FROM tblEmployees
    WHERE EmployeeName LIKE ''%' + @EmployeeName + '%'''
  EXECUTE sp_executesql @SQLQuery
GO

Here you can still inject SQL via EmployeeName as it's not properly formatted/escaped.
However, using the parameterized form would be secure:
Create Procedure sp_EmployeeSelect
  @EmployeeName NVarchar(100)
AS
  Declare @SQLQuery AS NVarchar(4000)
  Declare @ParamDefinition AS NVarchar(2000)
  SET @SQLQuery = 'SELECT * FROM tblEmployees
    WHERE EmployeeName LIKE ''%'' + @EmployeeName + ''%'''
  SET @ParamDefinition = '@EmployeeName NVarchar(100)'
  EXECUTE sp_executesql @SQLQuery, @ParamDefinition,
    @EmployeeName
GO


text:
Q: How can i initilaze BluetoothConnectionService on Fragment I want to try initilaze bluetoothservicejava on my fragment but i cant.
(My connection sucesfull before the this fragment).
On my fragment i added this
BluetoothConnectionService mBluetoothConnection;

and added this:
mBluetoothConnection = new BluetoothConnectionService(getActivity());
if(mBluetoothConnection!=null){
    Log.d(TAG,"initilazed mbluetoothconnection");
}

But i dont see any log my screen so i cant initilaze.


text:
Q: Web API Delete not working on IE 10 I am using Angular JS + CORS + Web API. I am able to make an HTTP request for GET, POST and PUT. However IE shows "DELETE" request always in pending state.
I tried to add traces on server side & it's responding correctly but somehow IE shows that request in pending state only.

This code works for all browsers excepts IE 10.it works on local & not on production.I'm using Azure to deploy API.

"The requested resource does not support http method 'DELETE'." my web api code is:
Config Code
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        EnableCorsAttribute CorsAttribute = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors();
        // Web API routes
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Controller Code
[EnableCors("*", "*", "*")]
[Authorize]
public IHttpActionResult Delete()
{
        if (string.IsNullOrEmpty(this.userName)) return BadRequest();
        if (string.IsNullOrEmpty(this.clientId)) return BadRequest();

        var result =  _repo.DeleteRefreshToken(this.userName, this.clientId, this.session);
        return new CustomErrorResult(this.Request, System.Net.HttpStatusCode.NoContent);
}


text:
Q: R: How to omit tested warning message from test report when testing for result AND warning I want to test in R if a function

*

*returns the correct value

*throws the correct warning during calculation

For that, I created a reproducible example.
There a two scripts, the first one (e.g. test-warning-and-result.R) works fine and without any errors:
library(testthat)

f <- function(x) {
  if (x < 0) {
    warning("*x* is already negative")
    return(x)
  }
  -x
}

test_that("warning and result", {
  x = f(-1)
  expect_that(x, equals(-1))
  expect_warning(f(-1), "already negative")
})

However, when I run the tests from an external script (e.g. run-test.R), it logically throws a warning at "x = f(-1)"
library(testthat)
test_dir(".")

Picture of test results
Since I know there will be a warning and am testing for it, I'm searching for a way to omit the warning within test_that() from the test report. Ideally, I would not have to run the function twice but in one test.
Any Ideas would be appreciated

A: Ok after having one night's sleep on it I found a simple sollution:
Don't store the functions result in a variable x. Nest the two tests into each other, with the expect_warning outside
Change from
test_that("warning and result", {
  x = f(-1)
  expect_that(x, equals(-1))
  expect_warning(f(-1), "already negative")
})

to
test_that("warning and result", {
  expect_warning(expect_that(f(-1), equals(-1)), "already negative")
})


text:
Q: Extract portions of a HTML table with Python I want to extract portions of a HTML page using Python.
For instance: take this page
http://www.wsdot.com/traffic/traveltimes/default.aspx?region=seattle&direction=all
Let's say I want to extract Distance, Current Travel Time and HOV Time for the route Bellevue-Bothell.
How can I do that in Python?

A: Beautiful Soup performs html escape which I believe is what you want. I've used some time ago and it worked just fine.
Take a look at the documentation Beautiful Soup Documentation


text:
Q: Windows и Linux в Qt Creator Работаю на Windows 10 в Qt Creator.
Можно ли в Qt Creator под Windows сделать приложение Qt Widgets под Linux?
Если да, то как?

A: Линусков слишком много и все они разные.
При написании программы следует придерживаться ряда правил, в частности, не выходить за пределы Qt и C++, не использовать платформенно-зависимые API.
А потом нужно взять ваши исходники, взять нужный вам дистр линукса и собраться на нем.


text:
Q: parcolumns: no footnotes are produced The footnote number appears in the printed text but I cannot see any footnote when using the parcolumns environment:
\documentclass{article}
\usepackage{parcolumns}
\usepackage[paperheight=9cm]{geometry}
\begin{document}
\begin{parcolumns}{2}
\colchunk[1]{
Foo
}
\colchunk[2]{
Bar\footnote{Baz}
}
\end{parcolumns}
\end{document}

Is there any workaround to solve this problem?

A: The parcolumns documentation (section 4) says:

Footnotes are not set in columns.

Here's a way to circumvent this. Note that it only works if you only have one footnote per \colchunk. Otherwise, you'll have to fiddle with counters; Reference different places to the same footnote might be a start. Also note that this solution here might not work with hyperref.
\documentclass{article}
\usepackage{parcolumns}
\usepackage[paperheight=9cm]{geometry}
\begin{document}
\begin{parcolumns}{2}
\colchunk[1]{
Foo\footnotemark
}\footnotetext{Baz the first}
\colchunk[2]{
Bar\footnotemark
}\footnotetext{Baz the second}
\end{parcolumns}
\end{document}


text:
Q: How to check if user is interacting with phone? Is possible to know if user is currently interacting with a phone (touching the screen), on ANY activity (including launcher) on android device?
I would like to check in my app if any interaction was made in the last few seconds.

A: To detect a touch anywhere on your app you can simply add a onTouchListener to the main, outermost layout of you app.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/myLayout">
 <!- Your other view->
</Relativelayout>

If suppose this is your Xml file then in the activity java file you can do:
 RelativeLayout l = (RelativeLayout) findViewById(R.id.mylayout);
 l.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        Log.d("screen","touched");
      //do stuff.

    }

 });

And if you want not just your app but anywhere and anytime to detect the touch no mater what app user is using. Then for that you have to create a service which will detect and keep recording all the touches. For more help check out this link
Detecting user activity in android


text:
Q: load posts from firebase i m working over application connected with fire base here which retrieves data from db 'm getting error unresolved reference dataSnapshot in Homefrag.kt file and to be very precise in
 //load posts from firebase
    fun LoadPostFromFireBase(){...}

clean project=>rebuild=>invalidate cache

fun LoadPostFromFireBase(){
    myRef.child("posts")
            .addValueEventListener(object : ValueEventListener {

                override fun onDataChange(p0: DataSnapshot  ) {

                    try {

                        listOfPost.clear()
                        listOfPost.add(Post("0","him","url"," ","add","addPost"))

                        var td= dataSnapshot!!.value as HashMap<String,Any>

                        for(key in td.keys){

                            var post= td[key] as HashMap<String,Any>

                            listOfPost.add(Post(key,
                                    post["postText"] as String,
                                    post["postImageURL"] as String
                                    ,post["postDate"] as String
                                    ,post["personName"] as String
                                    ,post["personID"] as String))

                        }

                        adapter!!.notifyDataSetChanged()
                    }catch (ex:Exception){}

                }

                override fun onCancelled(p0: DatabaseError) {

                }
            })
}

getting unresolved dataSnapshot!

A: You're looking for something that does not exist. Look at what the function onDataChange is giving you through its parameters.
I don't know Kotlin, but I'm pretty sure looking at your syntax that you're receiving "p0" inside the onDataChange, but you're looking for the object dataSnapshot.
You can fix it by replacing
var td= dataSnapshot!!.value as HashMap<String,Any>

with
var td= p0!!.value as HashMap<String,Any>


text:
Q: Python: How to mock a call that accepts a list argument and assert the first item of the list arg I'm using python mock and have a unit test where I need to ensure a function was called and the first element of this is a particular value. Consider this short example:
import unittest
from mock import patch, ANY

class foo():
    def something(self, a, b):
        print a,b

class footest(unittest.TestCase):
    def testany(self):
        f = foo()
        with patch.object(f, "something", autospec=True) as mock_something:
            f.something(1, [2,3,4])
            mock_something.assert_called_with(ANY, [2, ANY])

unittest.main()

Certainly this fails because I passed a three element list instead of a two element list. I can resolve this by going through mock_something.calls myself and pulling apart the arguments, but I'm wondering if any built in mock feature exists that would easily allow me to assert that the list can contain any number of ANYs?

A: You might be interested with mock.call_args
Link: https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.call_args
#!/usr/bin/env python

import unittest
from mock import patch, ANY

class foo():
    def something(self, a, b):
        print(a, b)

class footest(unittest.TestCase):
    def testany(self):
        f = foo()
        with patch.object(f, "something", autospec=True) as mock_something:
            f.something(1, [2,3,4])
            # mock_something.assert_called_with(ANY, [2, ANY])
            assert mock_something.call_count == 1

            received_args = mock_something.call_args.args
            target_arg = received_args[1]
            assert target_arg[0] == 2

            print("Result of mock_something.call_args", mock_something.call_args)
            print("Result of mock_something.call_args.args", mock_something.call_args.args)

unittest.main()

Output:
(venv) nponcian 2020_7Jul_14_StackOVerflowPytest$ ./script.py
Result of mock_something.call_args call(1, [2, 3, 4])
Result of mock_something.call_args.args (1, [2, 3, 4])
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK


text:
Q: JavaFX How to set max/min window size? Does setMinSize() work on containers such as GridPane, for example? I have found that in my program GridPane ignores min. size properties while resized manually.
Here is the FXML code:
<GridPane fx:id="gp" prefHeight="134.0" prefWidth="238.0" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxapplication12.SampleController">
  <columnConstraints>
    <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
    <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
  </columnConstraints>
  <rowConstraints>
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
  </rowConstraints>
</GridPane>

and the controller class
public class SampleController implements Initializable {

    @FXML
    private GridPane gp;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        gp.setMaxWidth(700);
        gp.setMinSize(200, 200);
    }
}

What's wrong here? Should there be some sort of a 'window' max/min size?

A: I am going to assume that by window, you mean a Stage (which subclasses Window).
The window size can vary from the root container size for the scene.  You can think of a window or stage as an independent viewport into the scene which can be sized larger or smaller than the min and max specifications of the scene root.
To set the minimum or maximum size of the Stage, set its minHeight and minWidth or maxHeight and maxWidth properties.
Answers to additional questions

Can the Stage be set to "fit whole display" size?

stage.setFullScreen(true)

But how to make the size as same as we make size by clicking on the title bar?

stage.setMaximized(true)


text:
Q: iPhone App failed to install Through the safari browser , I have added one of my org device UDID in the Developer account. Now I am trying to install one of custom application using iTunes to that device. But App failed to install.
I am able to see in the Developer account that , under the profiles , it is showing 0.
Why I am unable to install the app in the device.
The same scenario I tried with iPad , But It got installed. Can anyone tell me what could be the reason ??

A: What you need to do is sign the Application with an Adhoc_Distribution Profile and include your iPhone as well as any other devices you want to deploy your application on.
To create the profile, go to provisioning portal, select Provisioning from left, then choose distribution tab. From there select Adhoc_Distribution, select proper AppID and add the devices you want to deploy application upon.
Download the profile and follow these steps..
http://diaryofacodemonkey.ruprect.com/2011/03/18/ad-hoc-app-distribution-with-xcode-4/
Then use the iTunes to install the Application on required devices.


text:
Q: How to set chart series color for entire series (all points) I'm trying to loop through the entire series to color all points (bars) in the chart pictured below using VBA. This is what I have so far
Sub ChartColors()
    Dim sld As Slide
    Dim shp As Shape
    Dim cht As Chart
    Dim cats As Variant
    Dim j As Integer

    For Each sld In ActivePresentation.Slides
        For Each shp In sld.Shapes
            If shp.Type = msoChart Then
                cats = shp.Chart.Axes(xlCategory).CategoryNames

                For j = LBound(cats) To UBound(cats)
                    With shp.Chart.SeriesCollection(1).Points(j).Format.Fill.ForeColor
                        Select Case cats(j)
                            Case "Apple"
                                .RGB = RGB(192, 0, 0)
                            Case "Banana"
                                .RGB = RGB(0, 112, 192)
                            Case Else
                                .RGB = RGB(0, 176, 80)
                        End Select
                    End With
                Next j
            End If
        Next shp
    Next sld
End Sub

enter image description here

A: Try the following code...
Option Explicit

Sub ChartColors()
    Dim sld As Slide
    Dim shp As Shape
    Dim cht As Chart
    Dim sr As Series
    Dim pt As Point
    Dim cats As Variant
    Dim i As Integer
    Dim j As Integer

    For Each sld In ActivePresentation.Slides
        For Each shp In sld.Shapes
            If shp.Type = msoChart Then
                Set cht = shp.Chart
                With cht
                    For i = 1 To .SeriesCollection.Count
                        Set sr = .SeriesCollection(i)
                        For j = 1 To sr.Points.Count
                            cats = sr.XValues()(j)
                            Select Case cats
                                Case "Apple"
                                    sr.Points(j).Format.Fill.ForeColor.RGB = RGB(192, 0, 0)
                                Case "Banana"
                                    sr.Points(j).Format.Fill.ForeColor.RGB = RGB(0, 112, 192)
                                Case Else
                                    sr.Points(j).Format.Fill.ForeColor.RGB = RGB(0, 176, 80)
                            End Select
                        Next j
                    Next i
                End With
            End If
        Next shp
    Next sld
End Sub


text:
Q: Tab shortcut for custom JSX components in VSCode I've just made the switch from Atom to VSCode.
When I used Atom and I'm typing JSX in .js files, I could type anything and press tab and it would turn what I tabbed into a custom component. For example, asdf and then tab would give <asdf></asdf>.
Now I have VSCode along with Emmet but this only works some of the time. I've experimented with Emmet and everything works except for basic custom components
All the HTML tags work as expected. i.e div.blue & tab return

Nesting works asdf>jkl & tab return
<asdf>
    <jkl></jkl>
</asdf>

For some reason adding a colon triggers it. as:df & tab return <as:df></as:df> but asdf & tab does not return <asdf></asdf>. I just get my cursor tabbed forward.
I'm not sure whether Intellisense or Snippets are interfering in some way.
The relevant extensions I have installed are JavaScript and TypeScript Intellisense v0.0.7, Javascript Snippet Pack v0.1.5 and simple React Snippets 1.2.2.
And here are my settings:
{
    "editor.formatOnSave": true,
    "editor.tabSize": 2,
    "editor.wordWrap": "on",
    "prettier.singleQuote": true,
    "prettier.jsxBracketSameLine": true,
    "prettier.semi": false,
    "prettier.useTabs": true,
    "html.format.indentInnerHtml": true,
    "workbench.colorTheme": "Base16 Tomorrow Dark",
    "liveServer.settings.donotShowInfoMsg": true,
    "window.zoomLevel": 0.5,
    "editor.fontSize": 11,
    "emmet.includeLanguages": {
        "javascript": "javascriptreact"
    }
}

A: I've found the answer. In settings add "emmet.triggerExpansionOnTab": true and it will work the way I want it to. By default it was set to false


text:
Q: jersey: JSONJAXBContext (from jersey 1) replacement in jersey 2? I noticed that JSONJAXBContext (from Jersey 1) is gone in Jersey 2. So, what is the alternative way in Jersey 2 to marshal/unmarshal JAXB objects into JSON?
Thank you very much.

A: JBT
Your question is already answered in : Where did JSONConfiguration go in Jersey 2.5.x?
You have to use an ObjectMapperProvider :
https://github.com/jersey/jersey/blob/2.5.1/examples/json-jackson/src/main/java/org/glassfish/jersey/examples/jackson/MyObjectMapperProvider.java


text:
Q: What is another phrases for "My body is lean toward ..."? What is another concise phrases for

My body is lean toward the steering wheel to dodge the bullet

with the same meaning?
lean toward is the big part that need to revise.
It is difficult look up synonym phrases on all types of search engines.

A: For your phrase

leaned towards

you could also use

leaned against (using the steering wheel as support)
leaned forward (since the steering wheel is in front of you)


text:
Q: How to cast a model into its parent? I've made a class that, when you save a User, creates automatically the Person associated with the User like this:
class Person(models.Model):
    user = models.OneToOneField(User, blank=False, null=False,
                                on_delete=models.CASCADE)

@receiver(post_save, sender=User)
def my_post_save_user_handler(sender, instance, created, **kwargs):
    if created:  # a User = physical -> create the associated person:
        Person.objects.create(user=instance, is_physical=True)

Later I've made a Worker:
class Worker(Person):
    job = models.CharField(unique=True, max_length=200)

My problem is that I'd like to create a User associated with a Worker (= not a Person).
When I do this:
user = User.objects.create(username='test',)
Worker.objects.create(user=user)

I get this error:
django.db.utils.IntegrityError: duplicate key value violates unique constraint "app_person_user_id_key"
DETAIL:  Key (user_id)=(2230) already exists.

This is normal, because post_save is triggered when I create the User, and then a second time when I create the Worker.
You might answer "just remove the auto generation of the Person" but I want for security reasons to always have a Person associated with a User. So is there a way to do something like:
user = User.objects.create(username='test',)
w = Worker(user.person)
w.job = "the job"
w.save()

(I know that the previous code isn't working) or is there a way to "cast" a Person into a Worker?

A: Here's the solution:
p = Worker(person_ptr=user.person,
           date_creation=datetime.date.today(),
           date_last_modif=datetime.date.today(),
           job=job or _("(not precised)"))
p.__dict__.update(instance.__dict__)
p.save()

It works even though it's a bit hackish.


text:
Q: Prepopulate ModelMultipleChoiceField Django I am creating a website that allows users to follow stocks and see articles based on those stocks. Upon registration the user follows Stocks for the first time. After this I would like them to be able to view a page that shows all Stocks and which ones they follow. How can I prepopulate a ModelMultipleChoiceField?
models.py:
class Stock(models.Model):
    name = models.CharField(max_length = 50)
    ticker = models.CharField(max_length = 50)

    def __str__(self):
        return self.name

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    followed_stocks = models.ManyToManyField(Stock, blank=True)

    def __str__(self):
        return self.user.username

    @receiver(post_save, sender=User)
    def update_user_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)
        instance.profile.save()

views.py:
def test(request):
    if request.method == "POST":
        form = StockFollowForm(request.POST)
        if form.is_valid():
            request.user.profile.followed_stocks = list(form.cleaned_data.get('stocks_selected'))
            request.user.profile.save()
            return redirect('index')
    else:
        form = StockFollowForm() #how do I prepopulate this if there are already followed Stock objects
        return render(request, 'core/test.html',{'form': form})

template:

Register

        <form method = 'post'>
            {% csrf_token %}
            {{ form }}

                <button class="btn btn-primary" type = 'submit'>Follow/Unfollow Stocks</button>

        </form>

forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Stock
from django.forms import ModelMultipleChoiceField

class ProfileRegistrationForm(UserCreationForm):

    class Meta:
        model = User
        fields = ('username', 'password1', 'password2', 'email', 'first_name' ,'last_name')

class StockFollowForm(forms.Form):
    stocks = forms.ModelMultipleChoiceField(required =False,
                                           widget=forms.CheckboxSelectMultiple,
                                           queryset=Stock.objects.all())

A: Try specifying the initial value for the stocks field:
form = StockFollowForm(
    initial={'stocks': request.user.profile.followed_stocks.all()}
)

For more on this, check out the Django docs on providing initial values to a ModelForm


text:
Q: Can't find /dist directory in Netbeans 8 I'm trying to export a project as a .jar in NetBeans 8, and I realize it's supposed to save automatically. All the sources I've found point out that it should be located in <myProjectFolder>/dist,but that directory does not exist-- is there a setting I must toggle?

A: You have to first clean and build to generate one.
As you do programming work you will see the result of your work , but this doesn't go into the dist folder until you clean and build.

A: Right click your project name in the NetBeans and you will see many options
starting with new, Build, clean and Build. click the clean and build and it will
create a dist folder which has the war file and you can access the dist folder
in the files at the top (projects Files Services)


text:
Q: Core Data save not completing before next screen is displayed My iOS app has two screens that are showing a problem:
On the first screen, the user takes a photo. This photo is resized (using UIImage-ResizeMagick) to a thumbnail, 58 pixels high. So a pretty small image.
This image is then converted to NSData and saved to a core data record. I then save the context and display the next screen (actually, I pop back to the root controller.)
This second screen is supposed to display a list of the items already added and photographed. Unfortunately, most of the time (but not all of the time) it does not display the last item. The item is eventually saved in the database and will be displayed the next time the second screen is shown, but it seems like the core data save is not quick enough... the screen is displayed before the data is available to be pulled out of the database.
As I indicated above, sometimes the save is quick enough, and the item is displayed on the second screen immediately, so it does seem to be a timing issue.
What is the proper way to 'wait' for the database to be updated, before displaying the second screen?
UIImage *theImage = [info objectForKey:UIImagePickerControllerOriginalImage];

// RESIZE IT
UIImage *thumbNailImage = [theImage resizedImageByHeight:58];
theImage = nil;

// save image to tag
NSData *imageData = UIImagePNGRepresentation(thumbNailImage);
self.appDelegate.currentTag.photo_data = imageData;
[self.appDelegate saveContext];

// pop back to Home page
[self.navigationController popToRootViewControllerAnimated:NO];

A: Core data has two means of performing changes on a Context. [NSManagedObjectContext performBlock:] and [NSManagedObjectContext performBlockAndWait:].
If you really want a synchronous save, add another method to your appDelegate called saveContextAndWait. Then in this method you can perform exactly what you did in your save, just make sure you wrap the [NSManagedObjectContext save:] method in a performBlockAndWait:.
Happy coding


text:
Q: Visual studio 2015 debugging with older dlls I'm trying to debug the sample application from OpenCV under Windows 10 - Visual Studio 2015.
I have already configured Visual Studio according to the OpenCV wiki and I can compile the application and run it fine.
The issue I'm having is when I try to debug the application. I'm getting that the program can't be started because MSVCP120D.dll is missing. I have already installed the Visual C++ 2013 redistributables from Microsoft, however they don't come with the debugging dlls.
The issue probably stems from the fact that the OpenCV version I'm using (D:\opencv\opencv\build\x64\vc12) was compiled with 2013. Is there a way to get the debugger version of this dll? Or start the debugger without it? Or am I stuck having to recompile OpenCV with 2015?
Thanks.

A:
Or am I stuck having to recompile OpenCV with 2015?

You probably are since it is a really bad idea to mix different runtime dlls. In your case you're mixing your compiled program (MSVC 2015) with the OpenCV dlls (MSVC 2013).
You should do either of these:

*

*Compile your program with MVSC 2013, which I believe will require you to install MSVC 2013 on your machine

*Compile OpenCV using MSVC 2015.

Note: This is probably gonna be better with programs compiled with MSVC 2015 and later compilers because of the Universal CRT


text:
Q: Find a better way to renew AWS credentials I am using sts:assumeRole to connect to a s3 bucket of a different account.
Now, the job that I run takes a few days and along the way the credentials expire and I needed a way to renew them.
I have written the following code to handle expiry of the temporary credentials
This code is inside my downloadFile():
return new Promise((resolve, reject) => {
    function responseCallback(error, data) {
        if (error) {
            const errorMessage = `Fail to download file from s3://${config().s3.bucket}/${path}: ${error};`;
            reject(error);
        } else {
            Logger.info(`Successfully download file from s3://${config().s3.bucket}/${path}`);
            resolve(data.Body);
        }
    }
    const fn = this.s3Client.getObject({
        Bucket: config().s3.bucket,
        Key: path
    }, (error, data) => this.handleTokenExpiry(error, data, fn, responseCallback));
});

And this is the handleTokenExpiry()
handleTokenExpiry(error, data, fn, callback) {
    if (!error || error.code !== "ExpiredToken") return callback(error, data);

    Logger.info("Token expired, creating new token");
    this.s3Client = null; // null so that init() doesn't return existing s3Client
    return this.init().then(fn);
}

Here init() is the method which sets this.s3Client using sts:assumeRole
and then new AWS.S3()
This works fine but I am not sure if this a clean way to do it. The strange thing is when I test it in local it takes almost two minutes for responseCallback() to be called when token is expired. Though responseCallback() gets executed immediately while the token is active.

A: For tasks running less than 12h, here is the solution.
When using AssumeRole, you can specify DurationSeconds argument to specify the duration of the temporary credentials returned by STS.  This is 15 min minimum, up to 12h.
The role you are assuming needs to be modified to authorize the maximum duration too.  See https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session
In your case, with a job running for several days.  I would suggest to refactor the app to run in smaller batches, each running for a few hours each.
Another alternative would be to be proactive about token expiration.  If your code know the token duration and the time at which it acquired the token, I would suggest to call a method before calling a method that uses the token (such as S3's getObject).  That method you check if the token are soon to expire and proactively refresh them.  Pseudo code would be like
function refreshToken() {
   return new Promise( (resolve, reject) => {
      // XX depends how long is your S3 getObject call
      if (token_acquisition_time + token_duration <= now() + xx minutes)  {
         // refresh token
         sts.assumeRole(...).promise().then(resolve());
      } else {
         resolve();
      }
   });
}

...

refreshToken.then(s3.getObject(...));

A: The AWS SDK can handle refreshing the credentials for you. For example:
const credentials = new ChainableTemporaryCredentials({
  params: {
    RoleArn: "optional-role-arn",
    RoleSessionName: `required-parameter-${Date.now()}`
  }
})
const s3 = new AWS.S3({credentials})

Now AWS SDK will refresh the tokens behind the scenes without any action from caller of s3.
For more information, please see AWSK SDK Documentation. Refresh is limited to validity time of the credentials used.


text:
Q: Adding multiple rows to table with auto_increment column Im trying to insert Data into a table named team. The table holds 4 colums. selection_id(primary key), player_name, position, and fixture id.
The selection_id has a value of auto_increment. Im adding the player names and position to the table. However the problem is, for each value it extracts out of the arrays, $playnames and $positions, the selection_id updates. Like this:

This is not what I want. 5 names should be stored (thus storing the team selected) in the table before the selection_id updates. OR for each new row, where a new team selection is made, the selection_id must be the same.
Im not sure how to get around this problem. I thought about doing another query after the data has been inserted to overwrite the selection_id and making all the rows (in this case) equal to 117. But im sure this is not the most effecient way to do it.
If anyone can give me a couple of pointers it would be greatly appreciated.
Code follows:
if ( isset($_POST['submit']) ) {
    $player_ids = array_map('intval', $_REQUEST['players']);

    var_dump($player_ids);

    $query = 'SELECT `name`, `position`
        FROM `player_info`
        WHERE `player_id` IN (' . implode(',', $player_ids) . ')';

    $return_names = mysql_query($query) or die(mysql_error());

    while ( $row = mysql_fetch_assoc($return_names) ) {
        $selected[] = $row['name'];
        $position[] = $row['position'];
    }

            for ($i=0; sizeof($selected) > $i; $i++){
                 $sql = mysql_query("INSERT INTO `team`(`selection_id`,`player_position`,`player_name`) VALUES ('selection_id\"\"','$position[$i]','$selected[$i]')")
                 or die(mysql_error());
                 echo $selected[$i];
                 echo $position[$i];
                     echo'<br>';
   }
 var_dump($selected);
          }


text:
Q: AWS SES Suppression list issue Recently I got a delivery issue on SES, the configuration is good, and there is only one user not getting emails. I checked the email and the reason why is not getting the emails is this one:
Action: failed
Remote-MTA: dns; amazonses.com
Final-Recipient: rfc822; xxxx@mydomain.com
Diagnostic-Code: Amazon SES did not send the message to this address because it is on the suppression list for your account. For more information about removing addresses from the suppression list, see the Amazon SES Developer Guide at https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-email-suppression-list.html Status: 5.1.1

All good until here, the thing is when I checked the suppression list, the email address is not there.
What am I missing here? Any idea about where else to take a look?
Any help will be appreciate. Thanks!


text:
Q: How to load and run a whole external js file after DOM loaded using GWT I would like to load and run  an external js file after DOM loaded, the external js file like:
<script type="text/javascript" src="http://example.com/example.js"></script>

below is the onLoad hook:
 @Override
    protected void onLoad()
    {
        super.onLoad();
        //how to load and run the whole js file?
    }

Thanks

A: Have a look at ScriptInjector, and don't forget setWindow(TOP_WINDOW)


text:
Q: Access session user id from java in php code igneter I want to use my user id in my Java project. I get my user id through session in PHP and then access it in my Java project. But it shows nothing in my Java project.
I get my user id through api call in java and in PHP api function, used the following code:
$user_id = $this->session->userdata('user_id');

Normally this returns my user id when i call this funcion through api.
But in java when it calls the api, than it returns null.
user id  =

But if i hardcode the user id in PHP like this:
$user_id = "3";

Then java can get the user id through api call.  But do not want to use any hard code value in PHP. Any suggestions please.


text:
Q: Displaying item in python dictionary in HTML on new line I have a python dictionary which stores the HTML title and comments from the user. I want to display each comment on a new line. I'm wondering is there a way to do this through some sort of loop like a while or for? I am displaying it manually for now. I am using flask if that helps. Here is my code:
Python:
with open ("comments.txt", "r") as myfile:
            data=myfile.read()
display_information = {
            'title':'My title'
            'messages':data.split('*')
}
    return render_template('test.html', pageinfo=display_information)

HTML:
{{ pageinfo.messages[0] }}

{{ pageinfo.messages[1] }}

{{ pageinfo.messages[2] }}

Is there a fast way of displaying the messages on a new line?

A: Iterate pageinfo.messages:
{% for msg in pageinfo.messages %}
    {{ msg }}

{% endfor %}


text:
Q: ecma6 shortest for loop with if check what is the shortest way to achieve this for loop in ecmascript 6:
var data = {
        sales: [
            {
                name: "Jim Frost",
                region: "USA East",
                phone: "212-555-1212",
                email: "jfrost@acme-travel.com"
            },
            {
                name: "Jan Smith",
                region: "USA West",
                phone: "310-555-1212",
            }
        ]
};

here is my attempt to see if the key is equal to my manually set variable, then i change that key item's field, if not, i change it to something else.
var str = '0'; // could also be an integer
for (var key in data.sales) {
  key ===  str ? data.sales[key].region = 'StateChosen' : data.sales[key].region = 'stateEliminated';
}

what is the shortest way to achieve this using ecma6, object.keys, map, filter, every, etc methods?

A: Your example could be done just by doing:
data.sales.forEach(el => el.region = 'stateEliminated'); // Change every region to eliminated
data.sales[str].region = 'StateChosen'; // Change back the selected to StateChosen.

Note: I am assuming that str is a valid key in data.sales.

A: A for of loop with destructuring assignment and .entries() would help.
for (let [k, v] of data.sales.entries())
  v.region = k == str ? 'StateChosen' : 'stateEliminated';

var data = {
        sales: [
            {
                name: "Jim Frost",
                region: "USA East",
                phone: "212-555-1212",
                email: "jfrost@acme-travel.com"
            },
            {
                name: "Jan Smith",
                region: "USA West",
                phone: "310-555-1212",
            }
        ]
};
var str = '0';

for (var [k, v] of data.sales.entries())
  v.region = k == str ? 'StateChosen' : 'stateEliminated';

console.log(data);


text:
Q: dplyr adding a label to a group of columns in a table When creating an R markdown report in Rstudio, I would like to make my tables a little easier to understand.  I have looked into kable() and xtable(), but I have not found what I'm looking for (or perhaps haven't understood what I've found).  Here is a sample table that I might include:
library(dplyr)
library(tidyr)
library(knitr)

mtcars %>%
 group_by(gear,cyl) %>%
 summarize(count = n()) %>%
 spread(cyl,count) %>%
 kable()

Here is the (console) result:
| gear|  4|  6|  8|
|----:|--:|--:|--:|
|    3|  1|  2| 12|
|    4|  8|  4| NA|
|    5|  2|  1|  2|

In a report, I'd like to include the column name "Cyl" (or even better "Cylinder") above the 4/6/8.  Otherwise, in complex tables, it may not be clear what those values represent.
Specifically: How can I add a row to the start of this table that displays "Cylinder" above the final three columns?
Thanks for the help!

A: When using HTML as the output the htmlTable package provides column grouping:
library(dplyr)
library(tidyr)
library(htmlTable)

test <- mtcars %>%
 group_by(gear,cyl) %>%
 summarize(count = n()) %>%
 spread(cyl,count)

htmlTable(
    test[,-1], # data.frame
    cgroup = c("Cylinders"), # Column group labels
    n.cgroup = c(3), # Number of columns per group
    rnames = test[[1]], # Row labels
    rowlabel = "Gears" # Column header for row labels
)

For PDF output Hmisc::latex provides a similar syntax (which I unfortunately cannot test by lack of LaTeX on the machine I'm currently working on):
library(Hmisc)

latex(
    test[,-1], # data.frame
    cgroup = c("Cylinders"), # Column group labels
    n.cgroup = c(3), # Number of columns per group
    rowname = test[[1]], # Row labels
    rowlabel = "Gears" # Column header for row labels
)

If you want MS Word output you're in bad luck as far as I can see at this moment.

A: It's not specifically what I was looking for, but I settled for just changing each individual column name.  It's basic, but for anyone looking here in the future, my code now looks like this:
library(dplyr)
library(tidyr)
library(knitr)

test <- mtcars %>%
 group_by(gear,cyl) %>%
 summarize(count = n()) %>%
 spread(cyl,count)

colnames(test)[2:4] <- paste(c(4,6,8),"Cylinder",sep=" ")

test %>% kable()

The resulting table looks like this in the console:
| gear| 4 Cylinder| 6 Cylinder| 8 Cylinder|
|----:|----------:|----------:|----------:|
|    3|          1|          2|         12|
|    4|          8|          4|         NA|
|    5|          2|          1|          2|


text:
Q: Huawei HMS maps not working on Ionic Capacitor runtime I have followed this guide to add Huawei HMS maps to my IONIC capacitor runtime app.
https://github.com/HMS-Core/hms-cordova-plugin/tree/master/cordova-plugin-hms-map/example/ionic
This app has google-services.json and huawei agconnect-services.json.
In project build.gradle I'm using
[...]
classpath 'com.huawei.agconnect:agcp:1.5.2.300'

capacitor.build.gradle
dependencies {
    [...]
    implementation "com.huawei.hms:base:5.2.0.300"
    implementation "com.huawei.hms:maps:6.0.1.304"
}

Here are the npm libs
npm install @hmscore/cordova-plugin-hms-map@latest
npm install @ionic-native/core @hmscore/ionic-native-hms-map@latest

Set the appropriate sha2 figerprint in the Huawei developer console. App build.gradle.
    signingConfigs {
        config {
            storeFile file('huawei.jks')
            storePassword '*****'
            keyAlias 'mapshowcase'
            keyPassword '*****'
        }
    }

dependencies {
    [...]
    implementation 'com.huawei.agconnect:agconnect-core:1.5.2.300'
}

     async initMap() {
            const mapOptions = {
                mapType: MapType.MAP_TYPE_TERRAIN,
                cameraPosition: {
                    target: {lat: 40.7587658, lng: 30.3146964},
                    zoom: 2
                }
            };

            this.hmsMap.requestPermission();
            this.map = await this.hmsMap.getMap('map', mapOptions, {marginTop: 50});
            this.addListener();
            this.map.setMyLocationEnabled(true);
            this.map.getUiSettings().setMyLocationButtonEnabled(true);
            this.map.getProjection().getVisibleRegion().then(vr => console.log(JSON.stringify(vr)));
            this.map.getProjection().toScreenLocation({lat: 12, lng: 43}).then(point => console.log(JSON.stringify(point)));
            this.map.getProjection().fromScreenLocation({x: 300, y: 600}).then(latLng => console.log(JSON.stringify(latLng)));
        }

Testing on a Huawei Harmony OS phone, but geting this error.
E/HmsMapKit_ErrorTraceLogPusher_4: cache error trace log : ErrorTraceLogDTO{ scenario = ACCESS_SERVICE_ERROR', message='5 : Unknown Code - 5'}
    com.huawei.hms.maps.foundation.client.mac: * * *n*n*w* *o*e*-*5
        at com.huawei.hms.maps.foundation.client.mac$maa.b(Unknown Source:25)
        at com.huawei.hms.maps.foundation.client.mab.a(Unknown Source:20)
        at com.huawei.hms.maps.foundation.client.mab.c(Unknown Source:80)
        at com.huawei.hms.maps.foundation.client.mab.a(Unknown Source:88)
        at com.huawei.hms.maps.provider.client.tile.maa.a(Unknown Source:1)
        at com.huawei.hms.maps.provider.client.tile.maa.lambda$gI3f4RyIuh0G4Qoia5V0XosFnEE(Unknown Source:0)
        at com.huawei.hms.maps.provider.client.tile.-$$Lambda$maa$gI3f4RyIuh0G4Qoia5V0XosFnEE.call(Unknown Source:6)
        at com.huawei.hms.maps.foundation.client.mab$maa.a(Unknown Source:3)
        at com.huawei.hms.maps.provider.client.tile.maa.c(Unknown Source:23)
        at com.huawei.hms.maps.provider.client.tile.maa.a(Unknown Source:4)
        at com.huawei.hms.maps.provider.cache.mag.a(Unknown Source:63)
        at com.huawei.hms.maps.provider.cache.mag$mac.startUrlRequest(Unknown Source:2)
        at com.huawei.map.MapController.startUrlRequest(Unknown Source:28)

Fo far I have not found any solution or details about such error on internet. Any help is appreciated.
Update 1
Looks like the map is properly constructed:
I/Capacitor/Console: File: http://localhost/ - Line 6588 - Msg: Huawei map constructed with the div id map :: and the props 1

But the target map div stays in blank and when I tap on it I'm able to see the clicks being logged.
addListener() {
        const log = document.getElementById('log');
        this.map.on(MapEvent.ON_MAP_CLICK, (latLng) => {
            log.innerHTML = '
' + 'Map_Click:' + latLng.lat + '<-->' + latLng.lng + log.innerHTML;
        });
        this.map.on(MapEvent.ON_MAP_LONG_CLICK, (latLng) => {
            log.innerHTML = '
' + 'Map_Long_Click:' + latLng.lat + '<-->' + latLng.lng + log.innerHTML;
        });
}

Update 2
The issue is with the transparency of the parent div of the map div. The plugin does not set the background transparent to all its parent nodes automatically on map init.

A: The issue was solved by setting all map div's parent ion-content nodes'css value when map has to be shown and remove it when map page is destroyed.
global.scss
    --ion-background-color: var(--map-background, white);

    .background-transparent {
      --map-background: transparent !important;
    }

Map.page.ts
ionViewDidEnter(){
    document.body.classList.toggle('background-transparent', true);
}

ionViewWillLeave(){
    document.body.classList.toggle('background-transparent', false);
}

A: The provided log is not enough.
It is better to create ticket here: https://developer.huawei.com/consumer/en/support/feedback/#/
And put all the log file in the ticket.
Or you can search "HmsMap" and share the search result here.


text:
Q: How do I check whether a given directory is empty with Ansible? I am trying to implement a role that checks whether a given directory is empty before proceeding with the rest of the playbook.
I have tried this code but I am getting an error and I am not sure about the correct implementation.
- name: Check if d folder is empty before proceeding
  find:
   paths: c/d/
   patterns: "*.*"
   register: filesFound

- fail:
     msg: The d folder is not empty.
  when: filesFound.matched > 0

- debug:
    msg: "The d folder is empty. Proceeding."

This is the error that I am getting:
fatal FAILED! =>
{"changed": false,
"module_stderr": "Exception calling \"Create\" with \"1\" argument(s):
\"At line:4 char:21
def _ansiballz_main():
An expression was expected after '('.
At line:12 char:27
except (AttributeError, OSError):
Missing argument in parameter list.
At line:14 char:7
if scriptdir is not None:
Missing '(' after 'if' in if statement.
At line:21 char:7
if sys.version_info < (3,):
Missing '(' after 'if' in if statement.
At line:21 char:30
if sys.version_info < (3,):
Missing expression after ','.
At line:21 char:25
if sys.version_info < (3,):
The '<' operator is reserved for future use.
At line:23 char:32
MOD_DESC = ('.py', 'U', imp.PY_SOURCE)
Missing expression after ','.
At line:23 char:33
MOD_DESC = ('.py', 'U', imp.PY_SOURCE)                                 Unexpected token 'imp.PY_SOURCE' in expression or statement.
At line:23 char:32
MOD_DESC = ('.py', 'U', imp.PY_SOURCE)
Missing closing ')' in expression.
At line:23 char:46
MOD_DESC = ('.py', 'U', imp.PY_SOURCE)
Unexpected token ')' in expression or statement.
Not all parse errors were reported.  Correct the reported errors and try again.\"
At line:6 char:1
$exec_wrapper = [ScriptBlock]::Create($split_parts[0])
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo          : NotSpecified: (:) [], MethodInvocationException\r\n    + FullyQualifiedErrorId : ParseException\r\n \r\nThe expression after '&' in a pipeline element produced an object that was not valid. It must result in a command
name, a script block, or a CommandInfo object.
At line:7 char:2
&$exec_wrapper
~~~~~~~~~~~~~\
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : BadExpression
", "module_stdout": "", "msg": "MODULE FAILURE
See stdout/stderr for the exact error", "rc": 1}

A: You could use the shell module.
- name: Register contents of /a/b/c
  shell: ls -lA # Thank you Life5ign
  args:
    chdir: /a/b/c
  register: contents

- name: do stuff when not empty
  debug:
    msg: "There are elements inside!"
  when: contents["stdout_lines"] | length > 0 # Thank you Life5ign

A: You are on the right way, but as @HermanTheGermanHesse mentioned, there is an idention error, try this:
- name: Check if d folder is empty before proceeding
  find:
    paths: 'c/d/'
  register: filesFound

- fail:
     msg: 'The d folder is not empty.'
  when: filesFound.matched > 0

- debug:
    msg: 'The d folder is empty. Proceeding.'

A: Solution inspired by Jeremy Canfield which checks if a directory contains files:
- name: Check if d folder is empty before proceeding
  stat:
    path: c/d/*
  register: filesFound

- fail:
     msg: The d folder is not empty.
  when: filesFound.stat.exists == true

- debug:
    msg: The d folder is empty. Proceeding.
  when: filesFound.stat.exists == false


text:
Q: Facebook access token changes on every pageload is it correct that the Facebook API access token changes on every pageload?
I thought once a token was obtained, it would stay the same until expiry.
I am using the Facebook SDK for Javascript.
Facebook says that with this SDK, there is no need to manually manage access tokens. The SDK just does it.
But is it correct that the token changes on every pageload?
My code is this:

     test

A: I just tested this and you are right, the Token changes with every page refresh. I would not worry much about it though, when using one of the SDKs (JavaScript, PHP, ...) you most likely don´t need to think about the Access Tokens at all.
And even if you need them (for managing Pages, for example), you can just use the last one.
The "older" Tokens are still valid btw, they don´t get invalidated. But they will stop working after 2 hours anyway.
There is also a second parameter you can set to "true": https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/ (see "Roundtrips to Facebook's servers") - which may have explained the new Token, but you´re not using that either.

A: Facebook has recently changed its process of refreshing access token.
Try to use this if it works in you case:
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN

EDIT:
This will might help you as well. Link


text:
Q: Chef chef-validator.pem security Hi I am setting up a cluster of machines using chef at offsite locations.  If one of these machines was stolen, what damage can the attacker do to my chef-server or other nodes by having possession of chef-validator.pem ?  What other things can they access through chef?  Thanks!

A: The validator key is used to create new clients on the Chef Server.
Once the attacker gets hold of it, he can pretend he's a node in your infrastructure and have access to the same information any node has.
If you have sensitive information in an unencrypted data bag, for example, he'll have access to that.
Basically he'll be able to run any recipe from any cookbook, do searches (and have access to all your other nodes' attributes), read data bags, etc.
Keep that in mind when writing cookbooks and populating the other objects in the server. You could also somehow monitor the chef server for any suspicious client creation activity, and if you have any reason believe that the validator key has been stolen, revoke it and issue a new one.
It's probably a good idea to rotate the key periodically as well.

A: As of Chef 12.2.0 the validation key is no longer required:
https://blog.chef.io/2015/04/16/validatorless-bootstraps/
You can delete your validation key on your workstation and then knife will use your user credentials to create the node and client.
There's also some other nice features of this since whatever you supply for the run_list and environment is also applied to the node when it is created.  No more relying on the first-boot.json file to be read by the chef-client and the run having to complete before the node.save creates the node at the end of the bootstrapping process.

A: Basically, chef-client uses 2 mode authentication for to the server :-
1) organization validator.pem and
2) user.pem
Unless and until there is the correct combination of these 2 keys. chef-client wont be able to authenticate with the chef server.

A: They can even connect any node to the chef server with the stolen key via the following steps.

*

*Copying and pasting the validator key into /etc/chef folder on any machine

*Creating client.rb file with the following details
log_location     STDOUT
chef_server_url  "https://api.chef.io/organizations/ORGNAME"
validation_client_name 'ORGNAME-validator'
validation_key      '/etc/chef/validater.pem'

3: Run chef-client to connect to the chef server

A: This was one of the items discussed at a recent Foodfight episode on managing "secrets" in chef. Highly recommended watching:

*

*http://foodfightshow.org/2013/07/secret-chef.html
The knife bootstrap operation uploads this key when initializing new chef clients. Possession of this key enables the client to register itself against your chef server. That is actually its only function, once the client is up and running the validation key is no longer needed.
But it can be abused.... As @cbl has pointed out, if an unauthorized 3rd party gets access to this key they can create new clients that can see everything on your chef server that normal clients can see. It can theoretically be used to create a Denial of Service attack on your chef server, by flooding it with registration requests.
The foodfight panel recommend a simple solution. Enable the chef-client cookbook on all nodes. It contains a "delete_validation" recipe that will remove the validation key and reduce your risk exposure.


text:
Q: tlmgr does not recognize xzdec When trying tlmgr init-usertree, I get the following error:
/usr/bin/tlmgr: Initialization failed (in setup_unix_one):
/usr/bin/tlmgr: could not find a usable xzdec.
/usr/bin/tlmgr: Please install xzdec and try again.

So apparently, the program xzdec is not found. I downloaded, compiled and installed xzdec inside ~/.local, but tlmgr still complains. The command xzdec works though. How can I make tlmgr aware of this installation?
Unfortunately, this is my work PC, so I don't have root access, and cannot simply
sudo apt-install xzdec


text:
Q: Excel - Lookup value in multiple columns I have a datasheet with multiple columns that I want to search through - ending up with returning the top row value(s) in the found column(s). How to do this?
My idea would be to combine index with match, but I am rather lost for specific ideas...
January February March April May June
      1        2     3     4   5    6
      7        8     9    10  11   12
      2        7     1     8   4    5
      9       10    11    12   6    3

E.g. Search for: ID 3 - should return: March, June
Regards,
Nyborg

A: You need to add a VLOOKUP for each columns and after build the result
Following the Scheme:

A7 -> =IF(IFERROR(VLOOKUP($A$9;A1:A5;1;);"")="";"";A1)          and autocomplete
D9 -> =SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(CONCATENATE(A7;",";B7;",";C7;",";D7;",";E7;",";F7);",,";",");",,";",");",,";",")
D10 -> =IF(RIGHT(D9;1)=",";LEFT(D9;LEN(D9)-1);D9)

Formula for D9 & D10 it's only to have a good display of the results.
UPDATE Version:
Considering you agree to have the Row 7 ... You can simplyfy using the Result formula:
=INDEX(List;SMALL(IF(List<>"";COLUMN(List)-MIN(COLUMN(List))+1);1))&IFERROR(", " & INDEX(List;SMALL(IF(List<>"";COLUMN(List)-MIN(COLUMN(List))+1);2));"")&IFERROR(", " & INDEX(List;SMALL(IF(List<>"";COLUMN(List)-MIN(COLUMN(List))+1);3));"")

List it's the name Range of Row 7. The formula shall be apply with Ctrl+Shift+Enter.
This formula collect the first 3 value.
If you want more, add for each nth value you have:
&IFERROR(", " & INDEX(List;SMALL(IF(List<>"";COLUMN(List)-MIN(COLUMN(List))+1);3));"")

changing the last numer (in this case 3) and putting 4, 5, 6 ...
Obviusly if the result can be a lot, have few sense... Consider to use VBA !


text:
Q: Why some gradle tasks are inaccessible? gradlew tasks gives me these tasks (amongst others):
assemble - Assembles all variants of all applications and secondary packages.
assembleAndroidTest - Assembles all the Test applications.
assembleDebug - Assembles all Debug builds.
assembleRelease - Assembles all Release builds.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
clean - Deletes the build directory.
cleanBuildCache - Deletes the build cache directory.
compileDebugAndroidTestSources
compileDebugSources
compileDebugUnitTestSources
compileReleaseSources
compileReleaseUnitTestSources
mockableAndroidJar - Creates a version of android.jar that's suitable for unit tests.

I can add additional code to say, assemble, like this:
assemble {
    doFirst {
        println "hello"
    }
}

but can't do it with many others from this list, for example, trying to add to assembleDebug gives me this error:
Error:(65, 0) Could not find method assembleDebug() for arguments [build_6s1kvuwgpamstoh3d4xsg1ndv$_run_closure3@13494795] on project ':app' of type org.gradle.api.Project.

Why is that?

A: It's quite easy to explain. When you run gradle script it's evaluated in order of declaration. But - sometimes, and android project is a good example - you don't (and can't) know what tasks can be created because they're based on the content of project (files, variants, whatever). So, these tasks are being created no sooner than the whole project is evaluated. That's why you can't access them in build.gradle - because the project evaluation isn't finished yet.
Now, if you know that a task named assembleDebug will be created you can use [afterEvaluate]1 to configure the task after evaluation. At this time the whole project is evaluated and all the tasks are added/generated.
So:
project.afterEvaluate {
   assembleDebug {
      doFirst {
         println "hello"
      }
   }
}


text:
Q: How to programmatically select multiple sheets and copy to the same workbook at the same time in C# I'm looking for some advices.
I'm sorry, I don't know how to make it clarify in text, so, I will show you what I need to achieve via Excel instead.

*

*Select multiple sheet by Ctrl+Left click (To make Sheet1, Sheet2 active)

*Right click > Move or Copy... > select (move to end) > check "Creat a copy" > Ok

*Result

I would like to know 2 things

*

*How to select multiple sheets

*How to copy selected sheets to the same workbook in 1 shot

The reason why I want to copy both in 1 shot because I put formula in Sheet1 in cell A1 which is "=Sheet2!A1". If I copy it one by one the formula won't change but If I select both sheets and copy at the same time, the formula will change to "=Sheet2(2)!A1" automatically << This is what I intend to do.
Which excel interop command should I use to achieve this result ?

A: I think this is what you need:
            var MyApp = new Excel.Application();
            MyApp.Visible = false;
            var MyBook = MyApp.Workbooks.Open(path);

            Excel.Worksheet sheet = (Excel.Worksheet)MyBook.Sheets[1];
            sheet.Copy(MyBook.Sheets[MyBook.Sheets.Count]);

            sheet = (Excel.Worksheet)MyBook.Sheets[2];
            sheet.Copy(MyBook.Sheets[MyBook.Sheets.Count]);

            MyBook.Save();


text:
Q: How to debug a Snowflake stored procedure? I am using the Snowflake Cloud Database, please help me with a tool to debugging the procedures or functions.

A: The following Snowflake Javascript Stored Procedure is a template I use to get started on a new Stored Procedures.  It contains plenty of debugging tricks, such as:

*

*it has a "where am I?" variable which gives you a understanding of where in the code you are

*it gathers information in an array as the process moves along

*it returns that array to the standard output of the call command

*it has a "good start" of an exception block, who's contents also get pushed out to standard output on a call of the stored procedure, should it fail.

Something I've been meaning to add is to set a query tag in the code as well, that'd be helpful when reviewing query history, to easily identify the SQL commands that were used in the execution of the Stored Procedure.
This "ties into" the final "debugging trick" - you should always review the query history (actual queries your code executed) when developing stored procedures in a development or test environment, particularly when you are building dynamic SQL statements.  Reviewing your query history is a must-do and will show you exactly the commands run and the order of operations of them running.
Here's the code with the sample table it uses, I hope it helps...Rich
CREATE OR REPLACE TABLE test_scripts (
   load_seq  number,
   script    varchar(2000)
   );

INSERT INTO test_scripts values
   (1, 'SELECT current_timestamp();'),
   (2, 'SELECT current_warehouse();'),
   (3, 'SELECT COUNT(*) FROM snowflake.account_usage.tables;'),
   (4, 'SELECT current_date();'),
   (5, 'SELECT current_account();'),
   (6, 'SELECT COUNT(*) FROM snowflake.account_usage.tables;'),
   (7, 'SELECT ''RICH'';');

select * from test_scripts;

CREATE OR REPLACE PROCEDURE sp_test(p1 varchar, p2 varchar)
  RETURNS ARRAY
LANGUAGE javascript
EXECUTE AS caller
AS
$$
//note:  you can change the RETURN to VARCHAR if needed
//       but the array "looks nice"
try {
   var whereAmI = 1;
   var return_array = [];
   var counter = 0;

   var p1_str = "p1: " + P1
   var p2_str = "p2: " + P2
   var load_seq = P1;
   var continue_flag = P2;

   whereAmI = 2;
   return_array.push(p1_str)
   return_array.push(p2_str)

   whereAmI = 3;
   //which SQL do I want to run?
   if (continue_flag=="YES") {
       return_array.push("query 1")
       var sqlquery = "SELECT * FROM test_scripts WHERE load_seq >= " + load_seq + " order by 1, 2;";
       }
   else {
       return_array.push("query 2")
       var sqlquery = "SELECT * FROM test_scripts WHERE load_seq = " + load_seq + " order by 1, 2;";
       }

   whereAmI = 4;
   //begin the run of grabbing the commands
   var stmt = snowflake.createStatement( {sqlText: sqlquery} );
   var rs = stmt.execute();

   whereAmI = 5;
   // Loop through the results, processing one row at a time...
   while (rs.next())  {
       counter = counter + 1;
       var tmp_load_seq = rs.getColumnValue(1);
       var tmp_script = rs.getColumnValue(2);

       var tmp_rs = snowflake.execute({sqlText: tmp_script});
       tmp_rs.next();
       var tmp_col1 = tmp_rs.getColumnValue(1);
       return_array.push("tmp_col1: " + tmp_col1)

       }

   whereAmI = 6;
   return_array.push("end process - counter: " + counter)

   return return_array;
   }

catch (err) {
   return_array.push("error found")
   return_array.push(whereAmI)
   return_array.push(err)
   return return_array;
}

$$;

CALL sp_test(3, 'NO');

A: I do not believe there is any editor / debugger for stored procedures for Snowflake. Few options:

*

*You can break your code to smaller parts and try to troubleshoot

*Use a log table and insert into log table often, so you can look at the log table to find out what went wrong

A: unfortunately there isn't one environment to rule them all
1. write your SQL in a Worksheet or Editor
2. write your SPROC code in a JS enabled editor
3. merge them together in a Worksheet or Editor
4. Unit test in SPROCS as shown above by @Rich Murmane
I normally just write SPROCS in a Worksheet but it isnt optimal

A: Logging is your friend here, as there is no debugger. In general finding and using a debugger for db stored procedures is hard to pull off. Not impossible, just unlikely.
This is a decent alternative:
CREATE or replace PROCEDURE do_log(MSG STRING)
 RETURNS STRING
 LANGUAGE JAVASCRIPT
 EXECUTE AS CALLER
AS $$

 //see if we should log - checks for do_log = true session variable
 try{
    var foo = snowflake.createStatement( { sqlText: `select $do_log` } ).execute();
 } catch (ERROR){
    return; //swallow the error, variable not set so don't log
 }
 foo.next();
 if (foo.getColumnValue(1)==true){ //if the value is anything other than true, don't log
    try{
        snowflake.createStatement( { sqlText: `create temp table identifier ($log_table) if not exists (ts number, msg string)`} ).execute();
        snowflake.createStatement( { sqlText: `insert into identifier ($log_table) values (:1, :2)`, binds:[Date.now(), MSG] } ).execute();
    } catch (ERROR){
        throw ERROR;
    }
 }
 $$
;

Then in the stored procedure, you want to debug add a log function at the top:
function log(msg){
    snowflake.createStatement( { sqlText: `call do_log(:1)`, binds:[msg] } ).execute();
}

Then above the call to the stored procedure:
set do_log = true; --true to enable logging, false (or undefined) to disable
set log_table = 'my_log_table'; --The name of the temp table where log messages go

Then in the actual stored procedure you need to add some logging lines:
log('this is another log message');

Then call the stored procedure as you would normally. Then select from my_log_table.
Important note: this uses a temp table, so you won't be able to read from that logging table in a different Snowflake connection. This means if you're using the Worksheet editor you need to keep all this stuff on the same sheet.
"Borrowed" from: https://community.snowflake.com/s/article/Snowflake-Stored-Procedure-Logging


text:
Q: Why do "Community Wiki" Q & A not get awarded reputation? I stumbled across a question on SO while looking for answers and ended up adding my own answer to the list of suggested solutions. Soon after this I realized that this question was a community wiki before I had added my answer to it.
According to the community this was the best answer as it received most upvotes for the question but I received nothing for it. Why?
Questions:

*

*Why does making a question/answer a part of the community wiki mean
no one can earn points for contributing to it?

*What's the reason for the reputation being disassociated with the contributor?
I understand on a technical level that the posts sort of gets owned by the community user instead of me but that shouldn't mean I get nothing for contributing should it?
Edit:
I've read the post What are "Community Wiki" posts and I'm not concerned with what Community Wiki posts are. I'm concerned with the rep-denial aspect and the reasoning behind it.
That said Robert's answer addressed this.

A: Since Community Wiki is largely deprecated (The Future of Community Wiki), it's not worth going into all the nuances of how it was supposed to be used. But in the earliest days, it was designed for posts that were sooo collaborative, it would have been near-impossible to determine who deserved the credit — so we removed reputation awards from those works completely.
We no longer recommend the use of Community Wiki as a rep-denial mechanism (no longer allow might be more accurate). We still allow users to set their own answers to community wiki if they wish, but the concept of using Community Wiki to lower the reputation requirements to post was replace with the "suggested edit" feature.
From the blog post: Putting the Community back in Wiki:

That's where Community Wiki came in - it killed those friction points by eliminating rep generation from those posts and lowering the bar on who could edit them. Which made it much easier for people who wanted to create collaborative, ensemble works - true community owned and edited resources.
But, much like dynamite, this well-intentioned invention was quickly weaponized into an instrument of destruction. Our big mistake: thinking we could systematically detect when such collaboration was happening, and automatically convert those posts to Community Wiki. It sounded awesome - "we'll help you collaborate even more! When we see enough editors, we'll save you the trouble of making it community wiki yourself and do it for you…"
Yeah, we are dumb.


text:
Q: Create a bootable USB live stick that is still useable on Windows? I would like to format a USB stick (32 GB) in a way so I have:

*

*A working *nix live system (preferably Arch Linux), about 3-5 GB in size

*A 'data' partition that is seen by windows (preferably NTFS) that I can use like any regular USB drive and uses the remaining size of the stick.

*I want that NTFS partition to be mounted in the Arch Linux live system

I have so far read that the big data partition should be the first in order for Windows to easily work with it. However I think that conflicts with the stick being bootable. Is this still doable?
The stick is a Kingston DataTraveler DTSE9 which I keep on my key ring. The live system is meant as an emergency / recovery system.

A: If FAT32 is acceptable you'll be able to do this with UNetbootin.


text:
Q: Pear Excel Writer ENCODING I'm developing an automated Excel-Export with Pear Excel Writer:
http://pear.php.net/package/Spreadsheet_Excel_Writer/docs
I used $worksheet->setInputEncoding("ISO-8859-1") to set the encoding, because my PHP system gives back ISO-8859-1 if i use iconv();
But in the Excel file I have display errors with umlaut (in german).

***** PHP *****
require_once 'Spreadsheet/Excel/Writer.php';

$workbook = new Spreadsheet_Excel_Writer();
$workbook->send('data.xls');

$worksheet =& $workbook->addWorksheet('Data');
$worksheet->setInputEncoding("ISO-8859-1"); // !?!?!

// some $worksheet->write() and so on

$worksheet->write($row, 2, 'Priotität', $format_bold); // The problem is the word with 'ä'

***** PROBLEM *****
it looks like this in the excel sheet:
http://www.pic-upload.de/view-25183541/Unbenannt.png.html

A: Your PHP code is written in UTF-8, but you set the input encoding to iso-8859-1.
Set the input encoding to utf-8 to fix the issue.


text:
Q: Verify recursion formula I have the following problem
When calculating all the values of a binomial distribution, the work can usually be simplified by first calculating $b(0;n,θ)$and then using the recursion formula
$b(x+1;n,θ)=\frac{θ(n−x)}{(x+1)(1−θ)}·b(x;n,θ)$
Verify this formula and use it to calculate the values of the binomial distribution with $n=7$ and $θ=0.25$
I have no clue where to begin or how to prove this. I'm looking for some help or at least a nudge in the right direction
Update: I figured out how to prove it, and I got 0.3115 as the answer? I think this is correct. Thoughts?


text:
Q: How do I split my code into functions for better readability? I have written a code which translates morse to text and vice versa. However, I am having a hard time to make them into simpler functions. I will have to submit the code into a makefile for which I need to split my code into two source code files- morse.c and main.c- and one header file morse.h. There is no problem regarding the makefile but only that I need to split m code into functions and not use any global variables for better clarity.
Code: https://onlinegdb.com/BJiDmG2A-
Any advice or direction would be really appreciated.
Just now I tried make a small part into a function but it does not work
  if (input[0] == '.' || input[0] == '-')
  { void MorseToText (input);
      printf("%s", result);
  } //go for morse to text conversion

   void MorseToText (char input,char result)
{
    // Morse to Text translation part
     const char s[MATCH] = " ";
     char *section;
     int l;
     int check = 0;

    section = strtok (input, s);

    do
    {
        for (l = 0; l < DATA; l++)
        {

            if (!strcmp (section, table[l].morse))
            {
                check = check + 1;
                result = result + table[l].ascii; //printf ("%s", table[l].ascii);
            }
        }

        if (check == 0)
        {
            printf ("Invalid Morse code!\n");
            return 0;
        }
        section = strtok (NULL, s);
    }while (section != NULL);
    printf ("\n");

    return 0;
}

A: Well, it is better to start off writing the functions than to implement the functions after you have the code "done".
I would look for code that completes a single task over and over again (for example, having functions that do the conversion, then havinga function that displays the output.)
You might be interested in return values. This lets your function interact with other functions, without using global variables.


text:
Q: not enough storage space available to process this command I am using windows vista and IE7.
I was trying to upgrade to IE8 or update my IE7.
Either way i am getting the error message
not enough storage space available to process this command

This comes after i try to download ,run and execute the IE updates from the msn website.
Kindly help cant figure out wat the issue is.

A: *

*I assume your Windows is installed on C:\ (Windows Drive). If yes check if there is enough space on the drive. (1-2 GB will suffice.).

*How much RAM do you have. If its less than 1 GB, then increase it to min 1 GB (recommended atleast 2GB).

*How much is your Page File size? It must be atleast equal to your RAM size (not sure on that calculation). Also by default, the space for the page file is allocated on Windows Drive i.e C:\. So make sure there is enough space for the page file to auto grow if required.

*Make sure your temp folder is empty (recommended) or atleast has enough space for IE installer to extract & run. Try using CCleaner which will easily clean up temp for you. type %TEMP% in Run prompt to see your temp folder. Again temp folder is mostly present on Windows drive i.e. C:\.

*Just for the heck of it, do a "Run As Administrator" while launching the installer. (IE installer will be smart enough to do that, but still)


text:
Q: A google sheet api http request with "Service account key" auth and without google/apiclient Google docs contains only examples with google/apiclient php library. But the library contains 14888 php files. This is too much for just one google sheet api request with the "Service account key" auth that I need.
Is there an example with a native http google sheet api request for the "Service account key" auth somewhere?

A: I believe your goal as follows.

*

*You want to retrieve the access token from the service account without using googleapis for PHP.

*You want to use Sheets API with the retrieved access token.

In order to achieve your goal, the sample script is as follows.
Sample script:
Before you use this script, please set the variables of $private_key and $client_email using your values of service account. And also, as the sample script for using Sheets API, please set $spreadsheetId and $range. In this case, for example, please share your Google Spreadsheet on your Google Drive with the email of the service account. By this, your Spreadsheet can be seen by the service account. Please be careful this.
<?php

$private_key = "-----BEGIN PRIVATE KEY-----\n###-----END PRIVATE KEY-----\n"; // private_key of JSON file retrieved by creating Service Account
$client_email = "###"; // client_email of JSON file retrieved by creating Service Account
$scopes = ["https://www.googleapis.com/auth/spreadsheets.readonly"];  // This is a sample scope.

$url = "https://www.googleapis.com/oauth2/v4/token";
$header = array("alg" => "RS256", "typ" => "JWT");
$now = floor(time());
$claim = array(
    "iss" => $client_email,
    "sub" => $client_email,
    "scope" => implode(" ", $scopes),
    "aud" => $url,
    "exp" => (string)($now + 3600),
    "iat" => (string)$now,
);
$signature = base64_encode(json_encode($header, JSON_UNESCAPED_SLASHES)) . "." . base64_encode(json_encode($claim, JSON_UNESCAPED_SLASHES));
$b = "";
openssl_sign($signature, $b, $private_key, "SHA256");
$jwt = $signature . "." . base64_encode($b);
$curl_handle = curl_init();
curl_setopt_array($curl_handle, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => array(
        "assertion" => $jwt,
        "grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer"
    ),
]);
$res = curl_exec($curl_handle);
curl_close($curl_handle);
$obj = json_decode($res);
$accessToken = $obj -> {'access_token'};

print($accessToken . "\n");  // You can see the retrieved access token.

// The following script is for a sample for using the access token.
$spreadsheetId = '###';  // Please set the Spreadsheet ID.
$range = 'Sheet1';
$curl_test = curl_init();
curl_setopt($curl_test, CURLOPT_URL, 'https://sheets.googleapis.com/v4/spreadsheets/' . $spreadsheetId .'/values/'. $range);
curl_setopt($curl_test, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $accessToken));
curl_setopt($curl_test, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl_test);
print($response);

*

*When you run this script, the access token is retrieved from the service account, and as a sample, the values of "Sheet1" of $spreadsheetId are retrieved using Sheets API.

References:

*

*Using OAuth 2.0 for Server to Server Applications

*jwt.io

*Method: spreadsheets.values.get

A: Although this doesn't answer your question (this might be useful to others who might stumble on this 14888-file issue), please note that you can also reduce the number of classes by specifying which services to use in your composer.json file.
In your case you would need to use the following;
{
    "require": {
        "google/apiclient": "^2.7"
    },
    "scripts": {
        "post-update-cmd": "Google\\Task\\Composer::cleanup"
    },
    "extra": {
        "google/apiclient-services": [
            "Sheets"
        ]
    }
}

Refer to: https://packagist.org/packages/google/apiclient


text:
Q: How to save image taken by phone to local folder in Windows Phone 8.1 Is there a way I can get the image as Stream and then store it locally to upload it to server?
So far I found the code below which lets me load the image to an image view , but how do I create a stream from the image source to pass it to SaveToLocalFolderAsync method?
    private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
    {

        FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;

        if (args != null)
        {
            if (args.Files.Count == 0) return;
            view.Activated -= viewActivated;
            StorageFile storageFile = args.Files[0];
            var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
            var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
            await bitmapImage.SetSourceAsync(stream);
            var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
            imgCover.Source = bitmapImage;

            //save the image in local folder

            //SaveToLocalFolderAsync(stream, "Test.jpg");

        }
    }

  public async Task SaveToLocalFolderAsync(Stream file, string fileName)
    {
        StorageFolder localFolder = ApplicationData.Current.LocalFolder;
        StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
        using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
        {
            await file.CopyToAsync(outputStream);
        }
    }


text:
Q: Learning to process files. Trying to think of a method for maintaining file pointer position I am working on a program to store data from a text file within a structure. The goal is to perform the file processing completely within the function outside of the main. The function opens and closes the file, and when it is called by the main function it is to populate the particular structure array element is supposed to be performed upon. The test file I am using is just a text file containing 3 lines:
Gates M 60
Jobs M 55
Jane F 45
These should be populated into an array of structures when called by the function. However, when I call the function it only populates the same first line to all array elements, I believe because the file pointer resets everytime I call the function. How can I remedy this? My code is below!
#include <stdio.h>
struct Individual
{
    char LastName[30];
    char gender;
    unsigned int age;
};
int function(struct Individual *person)
{
    FILE *cfPtr;
    char holder[100];
    cfPtr = fopen("C:\\Users\\Nick\\Desktop\\myfile","r");
    fscanf(cfPtr, "%10s %c %3d", &person->LastName, &person->gender, &person->age);
    fclose(cfPtr);
}
int main(void)
{
    struct Individual person[3];
    function(&person[0]);
    function(&person[1]);
    printf("%s %c %d", person[0].LastName, person[0].gender, person[0].age);
    printf("%s %c %d", person[1].LastName, person[1].gender, person[1].age);
    return 0;
}

A: FILE already tracks position for you; you don't need to do it yourself. The problem is that you keep re-opening the file, which resets the location back to the beginning of the file each time.
Open it once, read multiple times, then close it. Make your function take a FILE * parameter.
#include <stdio.h>
struct Individual
{
    char LastName[30];
    char gender;
    unsigned int age;
};
int function(FILE *cfPtr, struct Individual *person)
{
    fscanf(cfPtr, "%10s %c %3d", &person->LastName, &person->gender, &person->age);
    // TODO: Check for failure
    // TODO: Return appropriate value
}
int main(void)
{
    struct Individual person[3];
    FILE *cfPtr;

    cfPtr = fopen("C:\\Users\\Nick\\Desktop\\myfile","r");
    // TODO: Check for failure

    function(cfPtr, &person[0]);
    function(cfPtr, &person[1]);

    fclose(cfPtr);

    printf("%s %c %d", person[0].LastName, person[0].gender, person[0].age);
    printf("%s %c %d", person[1].LastName, person[1].gender, person[1].age);
    return 0;
}


text:
Q: Jenkins use Parameterized Trigger Plugin to build other project with confirmation I have three project of my Jenkins, A, B and C. When I fill the parameter on A and build it, will send email to me to run B. B only have one choice parameter for confirmation, it must be confirm manually, if B choice parameter is true, C will use A parameter to run some script, if B choice parameter is false, no other action will do of three project and send email to me. How can I achieve this scenario?
This scenario look like:
If true:
A (input parameter when build) → B confirm manually (ture) → C (use A parameter to do something)
If false:
A (input parameter when build) → B confirm manually (false) → will send email to me and not build C
Thanks

A: First of all, I think there are several of ways :) I would do something like this:
If I understand you correctly, going from A to B is done manually, so you are not asking about that.
As for going from B to C.
You should have B job receive this boolean parameter. Then B should have something like that in its Jenkins file:

        if (params.MY_FLAG && params.MY_FLAG.toBoolean()){
                                        c_job = build(job: 'C-Job', propagate: true, wait: true)
        } else {
// Sending you an email .
}


text:
Q: Not able to run juju bootstrap : ERROR You are not allowed to start up this node Trying to install MaaS server with juju using 12.10 ubuntu. MaaS was well installed with separate dhcp/dns server. Created then:
 ~/.juju/environments.yaml with the following content:
juju: environments environments:   maas:
    type: maas
    maas-server: 'http://myMaaSIpAddress'
    maas-oauth: '${maas-api-key}'
    admin-secret: 'nothing'

then run ssh-keygen
After adding the Mac address of node01 in maas. I noticed that wake on lan works and the new node being booted and installed buuuuut..Once trying to create my juju env with:
juju bootstrap

it returns:
 590 INFO Bootstrapping environment 'maas' (origin: ppa type: maas)...
    005 ERROR Failed to launch machine /MAAS/api/1.0/nodes/node-0516f9b8-825d-11e2-90af-0050561dd02a/; attempting to release.
    Traceback (most recent call last):
      File "/usr/lib/python2.7/dist-packages/juju/providers/maas/launch.py", line 49, in start_machine
        instance_uri, series, cloud_init.render())
      File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 551, in _runCallbacks
        current.result = callback(current.result, *args, **kw)
      File "/usr/lib/python2.7/dist-packages/juju/providers/maas/maas.py", line 82, in _process_error
        raise ProviderError(error.response)
    ProviderError: You are not allowed to start up this node.
    133 ERROR You are not allowed to start up this node.

It seems as authentication process goes wrong. However the MAASKey was copied from the MAAS GUI once generated new one. The node is being changing its status to ready but could not bootstrap juju???? ANY IDEA???

A: Basically here tow fundamentals reasons for that error:

*

*The node is not ready when generating the ssh key.

*Zookeeper is not being runinng it s agent in the node so does not pass the ssh key even the node started form maas.
if you have other experiences with this. Please share !!!


text:
Q: Google App Engine low level api - saving a custom object as Blob? I have a custom object that I would like to save in the datastore(not the blobstore).
Something like
Entity.setProperty("myobj", custonObject)

I have a list of users within this customObject
public user class{
 String name;
 String age;
}

public user_s class{

 List<user> userList;

 public user_s(){
  userList = new ArrayList<user>();
 }
}

I would then like to save user_s.
I guess I need some serialization, if at all possible. I can see that there is a Blob class in the datastore, but how do you use it?
https://developers.google.com/appengine/docs/java/datastore/entities
Regards

A: I know your question specifically says "low level API" but you might want to consider using Objectify if you want to avoid having to make boilerplate serialization code everywhere.  Then you can simply use a @Serialized annotation on the list of custom objects you want to store.
I would call Objectify "middle-low level"--it gives you a high degree of control in that you can manipulate the Datastore exactly as you wish, without the abstraction/obstruction of JDO, but still lets you avoid a bunch of boilerplate.

A: Yes, there is a Blob class.
Serialization is simple:
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(obj);
    Blob blob = new Blob(baos.toByteArray());


text:
Q: Tabs in the ActionBar What i mean in my question is the following :

'Android new dialer app' :

How can i add these tabs to my ActionBar? And how do i style them?
Please don't suggest using libraries

A: Try to use PagerTitleStrip Provided by android as suggested in comments but to solve the problem try to:
add that to your manifest file
android:value="splitActionBarWhenNarrow" />

and disable the action bar icon and title with setDisplayShowHomeEnabled(false); and setDisplayShowTitleEnabled(false);
here is a link to get you start from android developers:


text:
Q: Generating PDF from Rails Backend I have a 'download' button on the frontend (vue.js) that's reaching the endpoint /reports in my app. In the reports_controller, I'm scoping the data that I need and then trying to create a new PDF report. In the report model, I'm using the renderanywhere and pdfkit gem to try to get a PDF with the data that I'm passing through.
I'm trying to follow the documentation/example on pdfkit but the PDF that I'm creating is not including the data that I want (I'm only getting the h3 title and nothing else), is my as_html method correct? Is there something I'm missing in the template (pdf.html.erb)?
Is there another gem/approach that I can try?
reports_controller.rb
  def index
    send_report_pdf
  end

  private

  def report_pdf
    report = Thing.find(10)
    Report.new(report)
  end

  def send_report_pdf
    send_file report_pdf.to_pdf
  end

report.rb
require 'render_anywhere'

class Report
  include RenderAnywhere

  def initialize(report)
    @report = report
  end

  def to_pdf
    kit = PDFKit.new(as_html, page_size: 'A4')
    kit.to_file("#{Rails.root}/tmp/report.pdf")
  end

  private

  def as_html
    render template: "reports/pdf.html.erb",
    layout: "application",
    locals: { report: @report }
  end
end

pdf.html.erb

Report Test

 <%= @report %>


text:
Q: Run another python script without a popup cmd prompt and not in a sequence Problem with os.system("script2.py 1") is that it pops up a black cmd prompt momenterally :/
Problems with exec("script2.py 1") is that it waits in sequence...
Any alternatives?

A: subprocess is where you should be looking specifically Popen.
i.e.:
p = subprocess.Popen(["script2.py", "1"])

or
p = subprocess.Popen(["python", "script2.py", "1"])

You have a lot of control over what goes on including hiding windows.


text:
Q: Mysql Distance from test point to a polygon I have stored some map zones to a table using Geometry type field.
So the inserts are like this:
INSERT INTO zones (zoneName, coords) VALUES ('name',
PolygonFromText('POLYGON((
41.11396418691335 1.2562662363052368,
41.11370552595821 1.2560248374938965,
41.11851079510035 1.2459397315979004,
41.11880984984478 1.2461864948272705,
41.11396418691335 1.2562662363052368))'));

Then I have the user position, and I need to know if he is inside some zone. This works well with this:
SELECT id
  FROM zones
 WHERE MBRContains(coords,GeomFromText('POINT(41.117783 1.260590)'))

But sometimes, user position is not perfect, so I think its better to know wich zone is closest to user position.
That is the part that I don't have any idea about... I found some queries to get distance between two points, but not a point and polygons.

A: The MBR series of functions (like MBRContains) are unsuitable for what you're trying to do; they only test bounding rectangle inclusion.
You may wish to jump forward to MySQL 5.6.1, and use the ST_ functions, like ST_Contains. These functions actually test the geometry.
The problem you're working on can be defined as an uncertainty in the position of your POINT when you go to compare it to your collection of boundary POLYGON items.
Try this: create a POLYGON from your point that is a square with the size of your uncertainty. You can think of this square as a "fuzzy" point. (You could also use an octagon or another closer approximation of a circle in place of a rectangle, but your querying speed will slow.)
Then use ST_Within to see if you have a unique polygon that entirely contains your fuzzy point.  If you get just one polygon, you're done.
If you get multiple polygons that entirely contain your fuzzy point, that means some of your boundary polygons overlap other ones.  You need to figure out what this means in your problem space. If your data is intended to be properly structured cartographic boundary data, it means you have a data mistake. (NOTE:  This is not unheard of :-)
If you get no polygons that entirely contain your fuzzy point, then your fuzzy point may  or may not overlap the boundary of at least one polygon. Use ST_Overlaps to find those polygons.
If you get just one, you're done -- your fuzzy point is near the boundary of just one polygon.
If you get none, you're done -- your fuzzy point is away from the boundaries of all your polygons.
If you get more than one hit, you have an ambiguity -- your fuzzy point is near the boundary of more than one polygon.
This is the hard case to sort out. You could reduce the size of the fuzzy point and try again. This MIGHT yield just one polygon result. But, you could deceive yourself into thinking that your points are more accurate than they are by doing this.
MySQL doesn't have the geometric operator Area(Intersection(Polygon, FuzzyPoint)). If it did you could choose the polygon with the biggest area of intersection with your fuzzy point, and that would be a good disambiguator. But it would still be as inaccurate as the position of your point.
Maybe your application should handle the category of result "too near the boundary of A, B, and C to be sure."