text:
Q: Android Studio Button Error: Attempt to invoke virtual method on a null object reference I believe I have correctly instantiated my button, but when I try to set the onClickListener, I get an error.
val button = findViewById<Button>(R.id.plant_based_diets)
    button.setOnClickListener {
        setCurrentFragment(thirdFragment)
    }

The error is on line 2, it reads: Unable to start activity ComponentInfo{com.example.dietcentral/com.example.dietcentral.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference.
Also here is the xml for the button
<Button
    android:id="@+id/plant_based_diets"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:text="@string/plant_based_diets"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintBottom_toTopOf="@+id/guideline5"
    app:layout_constraintTop_toTopOf="@+id/guideline4"
    tools:layout_editor_absoluteX="114dp" />

How do I properly use the onclicklistener, I cannot find the solution elsewhere.

A: I think the problem has something to do with the way you instantiate your button, but I'm not sure. This code should work;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button val = (Button) findViewById(R.id.plant_based_diets);
    val.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });

}


text:
Q: Sidepanel with Qt I'd like to implement a sidepanel in my Qt window. I search something like the one that is used in the Visual Studio (see below).

Important notes:

*

*The widgets don't have to be moveable

*resizing should be possible

*each widget should be clearly separated from the other layout

Does anyone have an idea how I could build such a sidepanel? (Maybe there even exists a library)
Or does anyone know a project which uses Qt and some kind of sidepanel?

A: One option would be to use QDockWidgets. That's the type of thing they are intended for inside a QMainWindow.
You can put toolbars, QTreeViews and QTableViews (or related) widgets inside your dock widget to simulate the screenshot you posted.
For an example usage: Dock Widgets Example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I add text to an existing text file in python? Hey i'm a super beginner, and hope i could get some help with my issue.
prompt='> '
fin1=raw_input(prompt)
fin2=raw_input(prompt)

o1=open(fin1, 'r+')
o2=open(fin2, 'r+')

r1=o1.read()

o2.write(r1)

o1.close()
o2.close()

o3=open(fin2)
print o3.read()

o3.close()

What I'm trying to do is make the text in file 'fin1' copied into 'fin2', the problem is that when the program is done running the text file 'fin2' becomes an exact copy of 'fin1', deleting everything there was inside of fin2 before the program was run. Is there a way i can add text to the fin2 file while retaining all the text inside of it?
Sorry if this is a dumb question, i have just started out and was confused.
And Thanks in advance:)


text:
Q: .htaccess is there a more efficient way of doing this? I have URLs in this format
site.com/brochure/12/subcat/subcat/maincat
The only important part of the string to my application is the number directly after brochure
There can sometimes be many subcat false directories so I've had to use many rules like these to make it work
RewriteRule ^brochure/([^/]+)/([^/]+)/([^/]+)/?$ brochure.php?cat_path=$1
RewriteRule ^brochure/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ brochure.php?cat_path=$1
RewriteRule ^brochure/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ brochure.php?cat_path=$1
etc etc - sometimes up to five different rules to allow for the different directory structures.
I'm guessing this can be done in a single rule, anyone kind enough to share their ideas?
Thanks

A: Since you don't care about any part of the string after your initial ([^/]+), why not just use something like:
RewriteRule ^brochure/([^/]+).*$ brochure.php?cat_path=$1

This will match and group your 12, then quietly match and discard the remainder of the string (.*$).


text:
Q: How to transform each YUV_420_888 frame to RGB efficiently (e.g., using renderscript yuv2rgb.rs) in Android camera2? I am building a image processing program using Android camera2. Since the image format of each captured frame is YUV_420_888, I need to transform it to RGB efficiently for image processing. I googled and read a lot (especially the following two links), and finally found that renderscript may be the solution. However, I don't know how to use the yuv2rgb script in my code.
http://werner-dittmann.blogspot.jp/2016/03/using-android-renderscript-to-convert.html
Convert android.media.Image (YUV_420_888) to Bitmap
Currently, I use the TextureView surface to show the preview, and use ImageReader to capture each YUV_420_888 frame in onImageAvailable function.
   protected void createCameraPreview() {
    try {
        SurfaceTexture texture = textureView.getSurfaceTexture();
        assert texture != null;
        texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
        Surface surface = new Surface(texture);
        Surface mImageSurface = mImageReader.getSurface();
        captureRequestBuilder =    cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        captureRequestBuilder.addTarget(surface)
        List surfaces = new ArrayList<>();
        surfaces.add(surface);
        surfaces.add(mImageSurface);
        captureRequestBuilder.addTarget(mImageSurface);
     cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);

        cameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback(){
                    @Override
                    public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                        //The camera is already closed
                        if (null == cameraDevice) {
                            return;
                        }
                        // When the session is ready, we start displaying the preview.
                        cameraCaptureSessions = cameraCaptureSession;
                        updatePreview();
                    }
                    @Override
                    public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                        Toast.makeText(MainActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
                    }
                }, null);
        } catch (CameraAccessException e) {
             e.printStackTrace();
        }
}

  private final ImageReader.OnImageAvailableListener mOnImageAvailableListener  = new ImageReader.OnImageAvailableListener() {
    @Override
    public void onImageAvailable(ImageReader reader) {
        Image img = null;
        img = reader.acquireNextImage(); // we got YUV_420_888 frame here
        // transform to RGB format here?
        // image processing
    }
};

How to update my codes to achieve the goal (e.g., using the yuv2rgb.rs)? Thanks.

A: The camera2 sample application HdrViewfinder, which uses RenderScript to do some image processing, may be helpful for how to connect up the camera and RenderScript: https://github.com/googlesamples/android-HdrViewfinder
It doesn't do YUV->RGB conversion, IIRC, and I think yuv2rgb.rs may be intended for a different YUV colorspace than what the camera produces (due to backwards-compatibility concerns - it existed before camera2).  But it gets you to the point where you can write your own RS script to apply to camera data.


text:
Q: Navigate to a page after a GET request in express? I'm fairly new to express and was wondering how to navigate to a page as a result of a GET request? I'm building my page from a template, and the following works if I manually input the '/id' url:
const express = require('express');
const template = require('./template.js');

const app = express();
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send(template({
    body: "Home",
    title: "Home Title"
  }))
});

app.get('/id', (req, res) => {
  console.log("received get request for id");
  res.send(template({
    body: "id",
    title: "ID"
  }));
});

const server = app.listen(port);
console.log("listening...");

But if I send a GET request from the client, it gets received and nothing happens. Any tips or help would be appreciated! Thank you!


text:
Q: How to monitor system resource usage without showing process list I want to monitor system resources usage, the htop works very well, but I don't care processes now, is it possible to hide process list parts? Or, is there any other tool can do that?

A: I am not aware of a way to not show the processes in htop, but if you go with a similar alternative like btop or bpytop you can turn off the showing of the processes by pressing 4 on the keyboard.
Examples:
BTOP:  To install btop it is sudo snap install btop.  Then to run it just btop from a terminal window.
btop with processes:

btop without processes:

BPYTOP: To install bpytop it is pip3 install bpytop.  Then to run it just bpytop from a terminal window.
bpytop with processes:

bpytop without processes:

Hope this helps!


text:
Q: tar error: Unexpected EOF in archive I am trying to extract large tar folders, using the tar command
tar -xvif v1-2-val.tar.gz

but I get the error
gzip: stdin: invalid compressed data--format violated
tar: Unexpected EOF in archive
tar: Unexpected EOF in archive
tar: Error is not recoverable: exiting now

the output of file v1-2-val.tar.gz
v1-2_val.tar.gz: gzip compressed data, last modified: Thu May  9 13:21:59 2019, from Unix, original size modulo 2^32 2301755392 gzip compressed data, unknown method, ASCII, has CRC, encrypted, from FAT filesystem (MS-DOS, OS/2, NT), original size modulo 2^32 2301755392

I am able to get 10 or so uncompressed videos before it stops and shows the error, I want to skip any corrupted files and continue the process. I have searched the error, and tried different tar flags and re-downloading the folders, but nothing works, so I want to mention that the tar folders are the validation and testing set of ActivityNet, in case someone had an experience downloading the dataset.


text:
Q: What is the purpose of the AmplifyDataStore DynamoDB table? Context
When using AWS Amplify JS, and specifically the DataStore part of the SDK, the models that you specify in your schema.graphql each get an associated DynamoDB table:
schema.graphql
type Blog @model {
  id: ID!
  name: String!
  posts: [Post] @connection(name: "BlogPosts")
}
type Post @model {
  id: ID!
  title: String!
  blog: Blog @connection(name: "BlogPosts")
  comments: [Comment] @connection(name: "PostComments")
}
type Comment @model {
  id: ID!
  content: String
  post: Post @connection(name: "PostComments")
}

This corresponds to 4 DynamoDB tables that get created in AWS

*

*Blog-somerandomstring-dev — (makes sense)

*Post-somerandomstring-dev — (makes sense)

*Comment-somerandomstring-dev — (makes sense)

*AmplifyDataStore-somerandomstring-dev — (where does this table come from?)

Question
Given the above, what is the explanation behind, and/or function of this extra table (AmplifyDataStore-somerandomstring-dev)?

A: Answer
This extra table, not created by any particular @model in your Amplify Graphql schema is called the Delta Sync Table and its purpose to help with Conflict Detection and Sync
This may not mean much, but the rest of the doc explains how Amplify/AppSync go about conflict resolution for your data.


text:
Q: Mandatory Jenkins parameter I would like to know how to make a parameter mandatory in Jenkins, so the "Build" button is unavailable until someone fills it.
[$class: 'hudson.model.StringParameterDefinition', defaultValue: 'master', description: 'Description', name: 'repositoryTag'],

I have this, and I was wondering if there is something I could do such as adding "required: True" for example.


text:
Q: Index re/organize/Rebuild Report using Ola Is there any way we can generate report after running IndexOptimize - USER_DATABASES jobs.
I need a report which tells me which indexes have been rebuild/re-organised.
    Select * from commandlog

I had a look in the above table, but I am unable to identify which indexes has this actually performed rebuild/re-organize. Even though there is a command logged in the table, there are always few tables which didn't get rebuild/reorganized for different reasons like pagecounts etc..
Does anyone had any requirement like this. Can anyone share any script with me please.

A: You can find answer for this question at Ola Hallengren website itself. He has put lot of effort to make DBA's life easier and provided lot of parameters in order to customize and run the script as per user's requirement.
SELECT DatabaseName,
       SchemaName,
       ObjectName,
       CASE WHEN ObjectType = 'U' THEN 'USER_TABLE' WHEN ObjectType = 'V' THEN 'VIEW' END AS ObjectType,
       IndexName,
       CASE WHEN IndexType = 1 THEN 'CLUSTERED' WHEN IndexType = 2 THEN 'NONCLUSTERED' WHEN IndexType = 3 THEN 'XML' WHEN IndexType = 4 THEN 'SPATIAL' END AS IndexType,
       PartitionNumber,
       ExtendedInfo.value('(ExtendedInfo/PageCount)[1]','int') AS [PageCount],
       ExtendedInfo.value('(ExtendedInfo/Fragmentation)[1]','float') AS Fragmentation,
       CommandType,
       Command,
       StartTime,
       EndTime,
       CASE WHEN DATEDIFF(ss,StartTime, EndTime)/(24*3600) > 0 THEN CAST(DATEDIFF(ss,StartTime, EndTime)/(24*3600) AS nvarchar) + '.' ELSE '' END + RIGHT(CONVERT(nvarchar,EndTime - StartTime,121),12) AS Duration,
       ErrorNumber,
       ErrorMessage
FROM dbo.CommandLog
WHERE CommandType = 'ALTER_INDEX'
ORDER BY StartTime ASC


text:
Q: When designing a hash/indexed system, is a timestamp a good base for unique IDs? I find myself currently working on several projects which include user entries in a database which need to be uniquely identified. (Some examples are a userscript manager and a list of my apps.)
Is using a timestamp a good way or starting point to manage these entries and ensure they are unique?

A: I would probably concatenate timestamp and something else, like a user_id or the text of the entry, and throw in some random characters if you can, then hash the whole thing.
Something like SELECT MD5(CONCAT(entry_time, NOW())) would probably do the trick, and it's nice and simple.

A: In short, no.
Timestamps aren't inherently unique, due to various causes, including:

*

*Multiple threading (including threads on multiple hosts); and

*Timestamp granularity - that is, the clock itself - run up a pair of test programs, one which sends messages and one which "processes" them with their timestamp, and you'll see that you get many entries with the same timestamp, because on many platforms, the system clock doesn't change millisecond every millisecond. Worse, you can't depend on this behavior: it's dependent on platform and speed.

So, as colinmark noted in a comment, use a uuid if you need a unique identifier.

A: There are two reasons not to do this:

*

*there's no guarantee that timestamps are unique. It's entirely possible that two users interacting with the system will share a timestamp; even if this is unlikely, it's possible so you have to code around it.

*your unique identifier should be meaningless. A timestamp is sorta kinda meaningless, but it's possible someone would ask you to update the timestamp to deal with timezone issues, or daylight savings, or "I meant to post that yesterday"; in that case, you can't guarantee you'd break the uniqueness requirement.

Also, MySQL already includes a guaranteed way of assigning unique identifiers (auto increment integers), and UUIDs are widely considered to be the best way of doing this cross-platform. I'd go with the majority on this one...


text:
Q: How to package Tcl libraries in my own program? In my c++ program, I used Tcl library and linked libtcl8.5.so, but the target hosts don't have tcl8.5, so I copied the libtcl8.5.so and  tcl8.5 dir which contains init.tcl there, and set the environmet variable TCLLIBPATH to path/to/copied/tcl8.5, but when my program call Tcl_Init, it failed and said "package not known".
It seems the copied tcl8.5/ cannot be init correctly.
How can I solve this problem?

A: If you change the location of the script library directory (tcl8.5/ in your case), you need to tell the shared library part of Tcl where it is. You do this using the TCL_LIBRARY environment variable, which if set should contain the absolute path that is the location of that directory (technically, the directory that contains init.tcl).
In a normal installation of Tcl, the correct location of that directory is baked directly into the shared library, but when you move things round (or when you are running Tcl's make test) the environment variable allows you to override.
You might wish to look into alternate packaging mechanisms; there have already been a few questions in the tcl tag on this matter (but the usual favorite — a starkit — is probably not suitable for your case given the fact that the program is mainly C++).


text:
Q: In Service Fabric, does SetupEntryPoint execute on all nodes? In a Service Fabric cluster of 10 nodes, I deploy my application which have an InstanceCount set to 1.
If I specify the SetupEntryPoint element so a certain startup script will be executed before my service starts, will it execute only in the 1 node that currently hosts my application? Or will automatically execute on all of the 10 possible cluster nodes (that is, after the app was deployed to those nodes).
In other words, I want my script to execute on all of the cluster's nodes, not only in the node that currently runs my app.
Is it possible? (using SetupEntryPoint?).

A: The SetupEntryPoint script is only executed before the service is created. Therefore, it is not necessarily executed on all nodes. In other words, if you create a single instance, it is only run once on this particular node. If the service is moved to another node, it is run again on the new node.
If you need to run scripts on all nodes, maybe a custom script extension for the VMSS is an option. This is not specific to Service Fabric. It can be integrated using an ARM template.


text:
Q: How to display TextBlock while a string is downloaded from server My app for Windows Phone has a string downloaded from server. I'm trying displaying a textBlock while the download is in execution. However, my code doesn't works.
The textBlock is not displayed. Why? Is there another way for this?
 WebClient webClient1 = new WebClient();
 webClient1.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
 webClient1.DownloadStringCompleted += webClient_DownloadStringCompleted1;
 webClient1.DownloadStringAsync(new Uri(string.Format(url + insCodComanda.Text + "&random=" + ran.Next().ToString(), UriKind.RelativeOrAbsolute)));

 public void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
  {

     testete.Visibility = Visibility.Visible;

  }

void webClient_DownloadStringCompleted1(object sender, DownloadStringCompletedEventArgs e)
    {
      testete.Visibility = Visibility.Collapsed;
    }

A: If you want to manipulate UI element like that you need to use Dispatcher
this.Dispatcher.BeginInvoke(new Action(() => testete.Visibility = Visibility.Visible));


text:
Q: jquery creating variable and using it to for load - laravel I am a newbie in jQuery, obviously I don't really understand some basics, although I have read some tutorials.
I Have two buttons:
News 1

News 2

 - - -

I want to use them to load content of a div with id="dashcontent"
My Route looks like this:
Route::get('newcontent/latest_events/{mode}', 'ReportsController@newcontent_partials');

My controller method is this:
public function newcontent_partials($mode)
{

    if($mode == 'importance') {

    $rnd = rand(4, 5);  // just for testing purpose

    $top5events = Event1::
            ->orderBy('id', 'desc')
            ->take($rnd)
            ->get();

    $test_type = 'ajax OK - OLDEST';
    }
    else {

    $rnd = rand(5, 6);

    $top5events = Event1::
            ->orderBy('id', 'asc')
            ->take($rnd)
            ->get();

    $test_type = 'ajax OK - NEWEST';

    }

return View::make('partials._event_minibox', compact('test_type','top5events','rnd'));
}

My script looks like this:
This works just as expected:
function getbyText() {
$("#dashcontent").toggleClass( "col_12" );  // just to see that the script is working
$('#dashcontent').load('newcontent/latest_events/newest');
}

This works only if load target is delivered as plain text:
function getbyVar() {
$('#test_output').text($('#test2').attr("displaymode"));  // printing the value of attr
var linkcode = $('#demo3').attr("displaymode"); // creating the variable
$('#dashcontent').load(linkcode);  // THIS WILL NOT LOAD
$('#test_output').text(linkcode); // surprisingly, this one works!!!
}

if in the above code getbyVar function I use
$('#dashcontent').load('newcontent/latest_events/newest');

then the thing is working as expected

Please help me to solve these two problems:

*

*Make the loading div content work with the variable  displaymode.
Note: it can be a different solution than the one I am trying to implement.

*Make the function work extract the attr("displaymode") of the element which is clicked.
not from an element with specified ID.
 I have tried this:
var linkcode = $(this).attr("displaymode");

but contrary to examlpes I have found on-line, in case of my code doesn't work.
Any help appreciated. Thx

A: Update:
I don't see any id "demo3" in your markup code:
$('#demo3').attr("displaymode"); // creating the variable

I guess you want to use the "displaymode" attribute of clicked anchor, so for this you can pass this as an argument:
onclick="getbyText(this)"
onclick="getbyVar(this)"

then in your functions:
function getbyText(elem) {
    // use elem as a clicked elem.
}

function getbyVar(elem) { // elem is clicked element
    $(elem).attr("displaymode"); // get the attr of clicked elem
}

Or more unobtrusive way:
$('a[id^="test"]').on('click', function(e){
    if(this.id === "test1"){
       // code for test1
    }else if(this.id === "test2"){
       // code for test2
    }
});

even you can use switch cases here.


text:
Q: Python program Returning "None" as output import random

nums1 = [1,2,3]
nums2 = [random.shuffle(nums1)]
print nums2

how can I get nums2 as a list ?

A: random.shuffle() returns None. So, you are getting a list with element None.
random.shuffle() shuffles a list in place. So print nums1.
However, if you want to have a new shuffled list, first do:
nums2 = nums1[:]

That will make a new copy of nums1
Then do:
random.shuffle(nums2)
print nums2


text:
Q: ngClick with window.location.href lands redirect twice My mobile first application needs clickable table rows for navigation, which it solves through
<tr ng-repeat="foo in bar" ng-click="go_to(foo.id)" >

The go_to() function is defined in the controller scope like:
 $scope.go_to = function (in_id) {
    var url = "#details/" + in_id;
    window.location.href = url;
 };

And the #details is routed through ngRoute:
.when('/details/:id', {
            templateUrl : 'foo.html',
            controller  : 'fooController'
        })

The table-row calls the go_to function fine, but it lands the #details/x page twice in the history, where the first hit is a constant redirect to the next, so the back button is rendered useless.
IE: Say we have two pages; Main and Sub, where Main has the ng-click(go_to) functionality. Before clicking the ng-click the browser history looks like this [Main]. After clicking it, it looks like [Main, Sub, Sub]. Hitting back, no matter the amount of times, will still land you on Sub.
Is there any coherent explanation why the application behaves this way? Alternative solutions to it all are also very welcome

A: Since you are in an Angular application, changing pages with use of window.location.href is not the right way to do things, since it will effectively cause the whole page to reload and therefore your whole Angular application to be reloaded. What you have is a single-page application and you should treat it as such, ie. you should avoid reloading the page unless you absolutely have to.
The recommended way to do what you want is therefore to use the $location service to change the page displayed to the user. Something like
$scope.go_to = function (in_id) {
    var url = "#details/" + in_tg_id;
    $location.url(url);
 };

The $route service watches $location.url() (according to its documentation) and therefore a change in $location.url() will cause the correct route to be displayed to the user.

A: You should use the $location service like this ....
 $scope.go_to = function (in_id) {
    var url = "/details/" + in_id;
    $location.path(url);
 };

Also fix your syntax.

A: I also have same problem in my webapp the only difference is I am using ngNewRouter and defining components in configuration. For me when I click on the table row the browser(IE11) get stuck for atleast 6-7 seconds when I do window.location.href=#/newpath or $window.location.href=#/newpath from the javascript.


text:
Q: In Swift, what's the cleanest way to get the last two items in an Array? Is there a cleaner way to get the last two items of an array in Swift? In general, I try to avoid this approach since it's so easy to be off-by-one with the indexes. (Using Swift 1.2 for this example.)
// Swift -- slices are kind of a hassle?
let oneArray = ["uno"]
let twoArray = ["uno", "dos"]
let threeArray = ["uno", "dos", "tres"]

func getLastTwo(array: [String]) -> [String] {
    if array.count <= 1 {
        return array
    } else {
        let slice: ArraySlice<String> = array[array.endIndex-2..<array.endIndex]
        var lastTwo: Array<String> = Array(slice)
        return lastTwo
    }
}

getLastTwo(oneArray)   // ["uno"]
getLastTwo(twoArray)   // ["uno", "dos"]
getLastTwo(threeArray) // ["dos", "tres"]

I was hoping for something closer to Python's convenience.
## Python -- very convenient slices
myList = ["uno", "dos", "tres"]
print myList[-2:] # ["dos", "tres"]

A: With Swift 5, according to your needs, you may choose one of the following patterns in order to get a new array from the last two elements of an array.

#1. Using Array's suffix(_:)
With Swift, objects that conform to Collection protocol have a suffix(_:) method. Array's suffix(_:) has the following declaration:
func suffix(_ maxLength: Int) -> ArraySlice<Element>

Returns a subsequence, up to the given maximum length, containing the final elements of the collection.

Usage:
let array = [1, 2, 3, 4]
let arraySlice = array.suffix(2)
let newArray = Array(arraySlice)
print(newArray) // prints: [3, 4]

#2. Using Array's subscript(_:)
As an alternative to suffix(_:) method, you may use Array's subscript(_:) subscript:
let array = [1, 2, 3, 4]
let range = array.index(array.endIndex, offsetBy: -2) ..< array.endIndex
//let range = array.index(array.endIndex, offsetBy: -2)... // also works
let arraySlice = array[range]
let newArray = Array(arraySlice)
print(newArray) // prints: [3, 4]

A: In Swift 2, you can extend CollectionType. Here's an example (borrowing from Rob Napier's answer):
extension CollectionType {
    func last(count:Int) -> [Self.Generator.Element] {
        let selfCount = self.count as! Int
        if selfCount <= count - 1 {
            return Array(self)
        } else {
            return Array(self.reverse()[0...count - 1].reverse())
        }
    }
}

You can use it on any CollectionType. Here's Array:
let array = ["uno", "dos", "tres"]
print(array.last(2)) // [dos, tres]

Here's CharacterView:
let string = "looking"
print(string.characters.last(4)) // [k, i, n, g]

(Note that my example returns an Array in all cases, not the original collection type.)

A:
myList[-2:]

Yes, I have an enhancement request filed asking for negative index notation, and I suggest you file one too.
However, you shouldn't make this harder on yourself than you have to. The built-in global suffix function does exactly what you're after:
let oneArray = ["uno"]
let twoArray = ["uno", "dos"]
let threeArray = ["uno", "dos", "tres"]

let arr1 = suffix(oneArray,2) // ["uno"]
let arr2 = suffix(twoArray,2) // ["uno", "dos"]
let arr3 = suffix(threeArray,2) // ["dos", "tres"]

The result is a slice, but you can coerce it to an Array if you need to.

A: More generic answer ...
let a1 = [1,2,3,4,5]
let a2 = ["1","2","3","4","5"]

func getLast<T>(array: [T], count: Int) -> [T] {
  if count >= array.count {
    return array
  }
  let first = array.count - count
  return Array(array[first..<first+count])
}

getLast(a1, count: 2) // [4, 5]
getLast(a2, count: 3) // ["3", "4", "5"]

A:
the last two items of an array in Swift

EDIT: first checks that myArray.count >= 2
let myArray2:Array? = myArray.count >= 2 ? [myArray[myArray.count-2], myArray[myArray.count-1]] : nil

Here it is wrapped in a function which takes the array and either returns an array containing the last two or else returns nil if the passed array does not contain at least two items.
func getLastTwo(myArray:[String]) -> [String]? {
        return myArray.count >= 2 ? [myArray[myArray.count-2], myArray[myArray.count-1]] : nil
    }

A: I doubt it's going to make you that much happier, but the math is certainly simpler:
func getLastTwo(array: [String]) -> [String] {
    if array.count <= 1 {
        return array
    } else {
        return array.reverse()[0...1].reverse()
    }
}

Note that reverse() is lazy, so this isn't particularly expensive.

A: let items = [0, 2, 5, 3, 7, 6, 9, 10]
let count = items.count
let last2 = items[count - 2 ..< count] // [9, 10]

A: in swift 5 you can use suffix for get objects from the last and use prefix for get objects from the first, here is an example:
let exampleArray = ["first text", "second text", "third text"]

let arr1 = exampleArray.suffix(2) // ["second text", "third text"]
let arr2 = exampleArray.prefix(2) // ["first text", "second text"]

The result is a slice, but you can coerce it to an Array if you need to.

A: Swift4 solution:
let oneArray = ["uno"]
let twoArray = ["uno", "dos"]
let threeArray = ["uno", "dos", "tres"]

let arr1 = threeArray.suffix(from: threeArray.count-2) // ["dos", "tres"]

Other examples to clarify the functionality of Swift's built in function func suffix(from start: Int) -> ArraySlice<Element> are...
let arr2 = oneArray.suffix(from: 0) // ["uno"]
let arr3 = twoArray.suffix(from: 0) // ["uno", "dos"]
let arr4 = twoArray.suffix(from: 1) // ["dos"]
let arr5 = threeArray.suffix(from: 1) // ["dos", "tres"]
let arr6 = threeArray.suffix(from: 2) // ["tres"]


text:
Q: How can I extract the unique variables in one column conditional to a variable in another and make a new data frame with the output? I would like to extract the number of camera trap nights (CTN) (one column in df) per camera trap station (another column in DF) so I can work out relative abundance indices for each cameras station. For example Station 1 has had 5 triggers/events (of the same species) and has had 30 CTN. It is listed in my database 5 times (has 5 rows). I want to extract the unique CTN for Station 1 and subsequently all the other Stations in the DF.
Data frame:
EventID  CameraStation  CTN
001      Station 1      30
002      Station 1      30
003      Station 1      30
004      Station 1      30
005      Station 2      29
006      Station 2      29
007      Station 2      29
008      Station 2      29
009      Station 2      29
010      Station 3      31
011      Station 3      31

I have tried to use 'unique' and 'with' but do not get the result I want.
with(unique(rai.PS[c("CameraStation", "CTN")]), table(CameraStation))

I expect to get the following results;
CameraStation    CTN

Station 1        30
Station 2        29
Station 3        31

I.e. Station 1 is only listed once with the outcome of CTN and in a new data frame.
But instead I get;
CameraStation
Station 1
1
Station 2
1
Station 3
1

I am assuming it is giving me the unique station once without the CTN as the criteria.


text:
Q: Not able to click button on website using Selenium I am unable to programmatically click the hidden button below:

    <input type="button" value="Get Results" tabindex="9" id="submitMe" onclick="submitData();" style="display:none" ;="">

I tried the following in Python:
sub_driver=webdriver.Chrome("C:\Program Files\chromedriver.exe")
sub_driver.find_element_by_id("get").click()
sub_driver.find_element_by_xpath("//input[@id=\"submitMe\"]")
sub_driver.execute_script("javascript:submitData();")
sub_driver.find_element_by_class_name('getdata-button').click()
my_var=sub_driver.find_element_by_xpath("//input[@type='button'][@id='submitMe']").click
sub_driver.execute_script("arguments[0].click();",my_var)

But the code is either hanging or not finding the element.


text:
Q: Can for-loops counter be const declaration in ES2015? First, let can be used on loop counter declaration. This is also described in MDN.
for(let i = 0; i < 2; ++i) {
  setTimeout(function(){
    document.write(i + "
");
  }, 0);
}

result:
0
1

Since let is used, a value of i can be changed in inside of for block.
for(let i = 0; i < 2; ++i) {
  setTimeout(function(){
    document.write(i + "
");
  }, 0);
  i = 123; // I want to block this assignment!!
}

So I considered using const instead of let.
for(const i = 0; i < 2; ++i) { // throws Assignment to constant variable
  setTimeout(function(){
    document.write(i + "
");
  }, 0);
  i = 123; // not here...
}

However, this code throws Assignment to constant variable. (in Chrome 53.0.2773.0).
I expected this loops twice like first let example, but make counter i writable in internal for-loop iteration only.
I think this is allowed because ECMA-262 §13.7.4.7 seems to mention this situation as If isConst is true, ..., but I cannot find this usage (or implementation status) in MDN and other sites. Kangax's table contains tests for let bindings, but not for const bindings.

A: I tested it (in Firefox) and the const binding works according to spec:

let i = 0;
for (const len = 3; i < len; i++) {
  console.log(i);
}

// From https://kangax.github.io/compat-table/es6/#test-const
for (const baz = 0; false;) {}

// Yay, a const counter! ...uh
for (const counter = {i: 0}; counter.i < 3; counter.i++) {
  console.log(counter.i);
}

It is probably not particularly useful though...
Why does it work?
The standard says:
  5. For each element dn of boundNames do
    a. If isConst is true, then
      i.  Perform loopEnv.CreateImmutableBinding(dn, true).

...where boundNames refers to the const binding. As you can see, the standard allows const 'loop counters', but doesn't say that you will be able to re-assign (increment) them later on (which, in fact, does not work).


text:
Q: Security (aka Permissions) and Lucene - How ? Should it be done? First some background to my question.

*

*Individual entities can have read Permissions.

*If a user fails a read permission check they cant see that instance.

The probelm relates to introducing Lucene and performing a search which simply returns a list of matching entity instances. My code would then need to filter entities one by one. This approach is extremely inefficient as the situation exists that a user may only be able to see a small minority and checking many to return a few is less than ideal.
What approaches or how would developers solve this problem - keeping in mind that indexing and searches are performed using Lucene ?
EDIT
Definitions

*

*A User may belong to many Groups.

*A Role may have many Groups - these can change.

*A Permission has a Role - (indirection).

*X can have a read Permission.

*It is possible for the definition of a Role to change at any time.

Indexing

*

*Adding the set of Groups (expanding a Permmission) at index time may result in the definition becoming out of sync when the list of member groups for a Role change.

*I am hoping to avoid having to reindex X whenever the definition of a Permission/Role changes.

Security Check

*

*To pass a Permission check a User must belong to a group that is within the set of groups belong to the Role for a given Permission.

A: It depends on the number of different security groups that are relevant in your context and how the security applies to your indexed data.
We had a similar issue which we solved the following way: When indexing we added the allowed groups to the document and when searching we added a boolean query with the groups the user was a member of. That performed well in our scenario.

A: It depends on your security model. If permissions are simple - say you have three classes of documents - It is probably best to build a separate Lucene index per class, and merge the results when a user can see more than one class.
The Solr security Wiki suggests something similar to HakonB's suggestion - adding user's credentials to the query and searching by them.
See also this discussion in the Lucene user group.
Another strategy will be to wrap the Lucene search with a separate security class that does additional filtering out of Lucene. It may be faster if you can do this using a database for the permissions.
Edit:
I see you have a rather complex permission system. Your basic design choice is whether to implement it inside Lucene or outside Lucene. My advice is to use Lucene as a search engine (its primary strength) and use another system/application for security. If you choose to use Lucene for security anyway, I suggest you learn Lucene Filters well, and use a bitset filter in order to filter a query's results. It does have the problems you listed of having to keep the permissions updated.

A: As Yuval mentioned, it might be worth having the permission mechanism independent of the lucene index.
One way to do it is to implement your own Collector, that will filter out the results that the user should not have access to.

A: What I would suggest is having two kind of documents:
1) Real_documents with a field called: "DocumentID"
2) A security document with fields: "Role" "Groups" "Users" "PermisionId" "DocumentsIds"
then a pseudo-code could be:
   Field[] docIds =searcher.search("Users", "currentUser").getFields("DocumentIds");
   TermsFilter filter = new TermFilter();

   foreach(field:docIDs){
       filter.add(new Term(field.field(),field.text());
   }
   searcher.search(query.getWeight(searcher), filter, numberOfDocuments);

Being that Lucene is very fast on searching two searches are really easy to make. In this way you also have a better tf-idf per user.


text:
Q: Saving a QGraphicsScene to Svg changes scaling I need to save the items from my QGraphicsScene to an svg, and be able to load that svg back on the scene.
I can do it...
But each time the canvas is saved to svg, upon load the items are somewhat bigger (and repeatedly saving and loading the same svg causes it to grow).
I can't find the cause.
I am attaching a sample code - and the result.

test1.pro

QT       += gui svg
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets core
TARGET = test1
TEMPLATE = app
SOURCES += \
    svggenerator.cpp

svggenerator.cpp

#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsEllipseItem>
#include <QGraphicsSvgItem>
#include <QSvgGenerator>
#include <QSvgRenderer>
#include <QFile>
#include <QByteArray>
#include <QMessageBox>

void saveSceneToSvg(QGraphicsScene* s, const QString &filename) {
    QRectF newSceneRect;
    QGraphicsScene *tempScene = new QGraphicsScene(s->sceneRect());
    tempScene->setBackgroundBrush(QBrush(Qt::transparent));
    tempScene->setItemIndexMethod(QGraphicsScene::BspTreeIndex);
    foreach(QGraphicsItem* item, s->items()) {
        newSceneRect |= item->mapToScene(item->boundingRect()).boundingRect();
        tempScene->addItem(item);
    }
    tempScene->setSceneRect(newSceneRect);
    tempScene->clearSelection();
    QSize sceneSize = newSceneRect.size().toSize();

    QSvgGenerator generator;
    generator.setFileName(filename);
    generator.setSize(sceneSize);
    generator.setViewBox(QRect(0, 0, sceneSize.width(), sceneSize.height()));
    generator.setDescription(QObject::tr("My canvas exported to Svg"));
    generator.setTitle(filename);
    QPainter painter;
    painter.begin(&generator);
    tempScene->render(&painter);
    painter.end();

    tempScene->clear();
    delete tempScene;
}

void loadSvg(QGraphicsScene* s, const QString &filename, const QPointF& p) {
    QGraphicsSvgItem* item = new QGraphicsSvgItem();
    QFile file(filename);
    file.open(QFile::ReadOnly);
    QByteArray contents = file.readAll();
    item->setSharedRenderer(new QSvgRenderer(contents));
    file.close();
    item->setPos(p);
    s->addItem(item);
}

void processScene(QGraphicsScene* s) {
    QGraphicsEllipseItem* eli = new QGraphicsEllipseItem();
    eli->setRect(QRectF(0, 0, 100, 100));
    eli->setPen(Qt::NoPen);
    eli->setBrush(Qt::red);
    eli->setPos(100, 300);
    s->addItem(eli);

    QGraphicsEllipseItem* eli1 = new QGraphicsEllipseItem();
    eli1->setRect(QRectF(0, 0, 100, 100));
    eli1->setPen(Qt::NoPen);
    eli1->setBrush(Qt::yellow);
    eli1->setPos(150, 300);
    s->addItem(eli1);

    QMessageBox::information(NULL, "hi", "click");

    saveSceneToSvg(s, "abcd.svg");
    loadSvg(s, "abcd.svg", QPointF(100,300));

    QMessageBox::information(NULL, "hi", "click");

    saveSceneToSvg(s, "abcd1.svg"); // saved with a dif name so I can see
    loadSvg(s, "abcd1.svg", QPointF(100,300));

    QMessageBox::information(NULL, "hi", "click");

    saveSceneToSvg(s, "abcd2.svg");
    loadSvg(s, "abcd2.svg", QPointF(100,300));

    // .... each time i call them they grow larger
}

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    QGraphicsScene s;
    s.setSceneRect(50, 0, 1000, 800);
    QGraphicsView view(&s);
    view.show();
    processScene(&s);
    return app.exec();
}

Result:

Looking at the svgs themselves, I can see that the svgs increase in size by approx 1.25... I can't explain, and can't be sure this will be true for other examples. (it seems to)
What is causing this growth ? How can I stop it ?
(Also I notice the ordering is different ... I just noticed and that is a different problem... But since in my "real" code I also have z order I don't care.)
Saving I think is fine - the resulting svg has size and view box of expected size.
Loading other svgs is fine - saving an svg from outside source creates an svg similar in size.
It seems the problem is when I am loading an svg created by the svg generator that it increases in size.
(If I could be sure it is always the case I could try scaling it down on load, but the ratio is not exactly 1.25 each time, close though... and I don't know how to tell the difference between an outside svg and a generated one).

A: It looks like a bug of SvgGenerator. The size which you provide to SVG generator is used only to form the header of svg. The actual size of .svg file differs from one written in the header. The only workaround I found is simple 25 percent decrease of size on save similar to:
int width = qCeil(qreal(sceneSize.width()/1.25));
int height = qCeil(qreal(sceneSize.height()/1.25));

generator.setSize(QSize(width, height));
generator.setViewBox(QRect(0, 0, width, height));


text:
Q: Need help displaying Itembox values Im brand new to visual basic and im having a hard time displaying the itembox values to my label display. Any Ideas?

Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'fill the list box with values
    lstNames.Items.Add("Smith, Joe")
    lstNames.Items.Add("Jones, Mary")
    lstNames.Items.Add("Adkari, Joel")
    lstNames.Items.Add("Lin, Sue")
    lstNames.Items.Add("Li, Vicky")
    lstNames.SelectedIndex = 0
End Sub

Private Sub MainForm_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick
    Select Case (lstNames.SelectedIndex)
        Case 0
            lblDisplay.Text = "3388"
        Case 1
            lblDisplay.Text = "3356"
        Case 2
            lblDisplay.Text = "2487"
        Case 3
            lblDisplay.Text = "1111"
        Case 4
            lblDisplay.Text = "2222"
    End Select
End Sub

A: I'd try moving your code from the MainForm.MouseClick event to lstNames.ItemSelected
Double clicking on the lstNames control in the design view should create this event for you by default.


text:
Q: Unable to repopulate a queue in python 3 The code is getting exited when I run the following code
    import mysql.connector
    import mysql.connector.pooling as x
    import time
    from threading import Thread
    from queue import Queue

    dbconfig = {
      "database": "mydb",
      "user":     "root",
      "password": "rootpass",
      "host":"127.0.0.1"
    }

    cnxpool =x.MySQLConnectionPool(pool_name = "mypool",pool_size = 2,**dbconfig)
    q = Queue(maxsize=20)

    threads = []
    limit = 0
    fetch_size = 20
    flag = True

    def populate():
        cnx = cnxpool.get_connection()
        cursor = cnx.cursor()
        global flag,fetch_size,limit
        while flag:
            cursor.execute("SELECT mycol from mytab limit " + str(limit)+","+ str(fetch_size))
            rows = cursor.fetchall()
            for row in rows:
                print("Putting "+ str(row[0]))
                q.put(row[0])
            if cursor.rowcount < 20 :
                for i in range(4):
                    q.put(None)
                flag = False
            limit = limit + 20
        cursor.close()
        cnx.close()

    def consume():
        while True:
            item = q.get()
            if item is None:
                q.task_done()
                break
            time.sleep(1)
            print(item)
            q.task_done()

    for i in range(4):
        t = Thread(target=consume)
        t.start()
        threads.append(t)

    y = Thread(target=populate)
    y.start()

    q.join()
    y.join()

    for t in threads:
        t.join()

    print("Completed")

Code is getting completed in jupyter notebook
But when I try to repopulate the queue even after removing the variable it hangs.
        import mysql.connector
        import mysql.connector.pooling as x
        import time
        from threading import Thread
        from queue import Queue

        dbconfig = {
          "database": "mydb",
          "user":     "root",
          "password": "rootpass",
          "host":"127.0.0.1"
        }

        cnxpool =x.MySQLConnectionPool(pool_name = "mypool",pool_size = 2,**dbconfig)
        q = Queue(maxsize=20)

        threads = []
        limit = 0
        fetch_size = 20
        flag = True

        def populate():
            cnx = cnxpool.get_connection()
            cursor = cnx.cursor()
            global flag,fetch_size,limit
            while flag:
                cursor.execute("SELECT mycol from mytab limit " + str(limit)+","+ str(fetch_size))
                rows = cursor.fetchall()
                for row in rows:
                    print("Putting "+ str(row[0]))
                    q.put(row[0])
                if cursor.rowcount < 20 :
                    for i in range(4):
                        q.put(None)
                    flag = False
                limit = limit + 20
            cursor.close()
            cnx.close()

        def consume():
            while True:
                item = q.get()
                if item is None:
                    q.task_done()
                    break
                time.sleep(1)
                print(item)
                q.task_done()

        for i in range(4):
            t = Thread(target=consume)
            t.start()
            threads.append(t)

        y = Thread(target=populate)
        y.start()

        q.join()
        y.join()

        for t in threads:
            t.join()

        print("Completed")

        del q

        q = Queue(maxsize=20)

        for i in range(4):
            t = Thread(target=consume)
            t.start()
            threads.append(t)

        y = Thread(target=populate)
        y.start()

        q.join()
        y.join()

        for t in threads:
            t.join()

        print("Completed")

It hangs for ever.  Even creating a new queue doesn't help.  Where am I going wrong.  Kindly guide me.
Thanks in advance.
I am using Python 3.


text:
Q: image_tag not displaying image in aws beanstalk production mode I have an image tag to display my avatar.  The tag works in development mode but not in the production mode when i deploy it to aws beanstalk. The place where I view the avatar picture shows up as "img 0645" Its almost as if the image gets saved but is displaying the img name in a way or id. The image itself isn't showing up!! How do i make the image show up??? Thanks!!!
Im using
Postgres, puma, aws beanstalk, ruby on rails

Not sure if this helps but I used Find to lookup anything in the log with avatar in the search and came up with these.
"GET /system/users/avatars/000/000/001/thumb/IMG_0645.JPG?1465126426 HTTP/1.1" 404 1564
"GET /system/users/avatars/000/000/001/medium/IMG_0645.JPG?1465126426 HTTP/1.1" 404 1564

Production.rb
Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both threaded web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Enable Rack::Cache to put a simple HTTP cache in front of your application
  # Add `rack-cache` to your Gemfile before enabling this.
  # For large-scale production use, consider using a caching reverse proxy like
  # NGINX, varnish or squid.
  # config.action_dispatch.rack_cache = true

  # Disable serving static files from the `/public` folder by default since
  # Apache or NGINX already handles this.
  config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = false

  # Asset digests allow you to set far-future HTTP expiration dates on all assets,
  # yet still be able to expire them through the digest params.
  config.assets.digest = true

  # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb

  # Specifies the header that your server uses for sending files.
  # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  # config.force_ssl = true

  # Use the lowest log level to ensure availability of diagnostic information
  # when problems arise.
  config.log_level = :debug

  # Prepend all log lines with the following tags.
  # config.log_tags = [ :subdomain, :uuid ]

  # Use a different logger for distributed setups.
  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)

  # Use a different cache store in production.
  # config.cache_store = :mem_cache_store

  # Enable serving of images, stylesheets, and JavaScripts from an asset server.
  # config.action_controller.asset_host = 'http://assets.example.com'

  # Ignore bad email addresses and do not raise email delivery errors.
  # Set this to true and configure the email server for immediate delivery to raise delivery errors.
  # config.action_mailer.raise_delivery_errors = false

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation cannot be found).
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners.
  config.active_support.deprecation = :notify

  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = ::Logger::Formatter.new

  # Do not dump schema after migrations.
  config.active_record.dump_schema_after_migration = false

#allow pictures
  config.serve_static_assets = false

#for rails devise
  Rails.application.routes.default_url_options[:host] = 'http://essayfriends-env.ss8bhfhxct.us-west-2.elasticbeanstalk.com'
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default :charset => "utf-8"

end

A: Try adding this to your config/environments/production.rb
config.serve_static_assets = false


text:
Q: Language picking don't display on Safari Version 14.1.2 browser In the app I work on every browser language picker shpws as it should be.
on the top of the screen it's rendering possibility to choose language of the app.
[![enter image description here][1]][1]
but once it's tested on Safari it does not display
[![enter image description here][2]][2]
Do You have any idea how to fix it ?
I cannot figure it out, didn't face something like that before
This is how it's build:
import React, { FC } from 'react';

import {
    ContainerSignInStyled,
    WrapperSignInStyled,
    LangHeader,
    StyledFlagButton,
    Footer,
    StyledPlFlag,
    StyledGbFlag,
    StyledPaper,
} from './styles';

import { LanguageEnum } from '@nevomo/utilities';

interface IProps {
    changeLanguage: (lang: LanguageEnum) => void;
    currentPath?: string;
}

export const ViewContainer: FC<IProps> = ({ changeLanguage, children }) => {
    return (
        <WrapperSignInStyled>
            <ContainerSignInStyled>
                <LangHeader>
                    <StyledFlagButton
                        onClick={() => changeLanguage(LanguageEnum.polish)}
                    >
                        <StyledPlFlag />
                    </StyledFlagButton>
                    <StyledFlagButton
                        onClick={() => changeLanguage(LanguageEnum.english)}
                    >
                        <StyledGbFlag />
                    </StyledFlagButton>
                </LangHeader>
                <StyledPaper>{children}</StyledPaper>
                <Footer>Footer Nevomo 2021</Footer>
            </ContainerSignInStyled>
        </WrapperSignInStyled>
    );
};

import { Container } from '@material-ui/core';
import styled from 'styled-components';
import { PlFlag, GbFlag } from '@nevomo/shared';
import { Paper } from '@material-ui/core';

export const WrapperSignInStyled = styled.div`
    background: url('/assets/Login_bckg.jpg');
    background-size: cover;
`;
export const ContainerSignInStyled = styled(Container)`
    display: flex;
    flex-direction: column;
    justify-items: stretch;
    min-height: 100vh;
    justify-content: space-between;
    align-items: center;
`;

export const LangHeader = styled.nav`
    display: flex;
    align-self: flex-end;
    margin-top: 2rem;
    margin-bottom: 2rem;
`;

export const StyledFlagButton = styled.button`
    outline: none;
    width: 4.4rem;
    border: 0.2rem solid transparent;
    margin-left: 1rem;
    position: relative;
    background: transparent;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    &:focus-visible {
        outline: 0;
        border: 0.2rem solid black;
        box-sizing: border-box;
    }
`;

export const Footer = styled.footer`
    margin-top: 2rem;
    margin-bottom: 2rem;
`;

export const StyledPlFlag = styled(PlFlag)`
    border-radius: 50%;
`;
export const StyledGbFlag = styled(GbFlag)`
    border-radius: 50%;
`;
export const StyledPaper = styled(Paper)`
    ${(props) => props.theme.breakpoints.up('xs')} {
        padding: 3rem;
        width: 38.8rem;
    }
    width: 100%;
    padding: 2rem;
    -webkit-box-shadow: 0px 6px 6px rgba(0, 0, 0, 0.35);
    box-shadow: 0px 6px 6px rgba(0, 0, 0, 0.35);
    z-index: 2;
`;

A: The problem could be in the management of the flexbox, I remember having compatibility issues a while ago.
What minimum version of safari do you intend to support?
If you are targeting < 9, be sure to specify vendor prefixes before some properties and properties values, i.e.:
.foo {
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -webkit-flex-direction: row;
  flex-direction: row;
}

you can use these links as a reference the check the support, know bugs and workaround to make flexbox cross-browser compatible:

*

*https://caniuse.com/flexbox

*https://github.com/philipwalton/flexbugs (which is also valid for Safari >= 9)

In any case, check with the safari devtools that the elements have the correct dimensions and positions, starting from the parents towards the children. If you have flexbox problems, going in this order can help.


text:
Q: How to enable indentation on Emacs in web-mode? I'm currently using GNU Emacs 24.3.1 with web-mode enabled. Everything works just fine but Tab key doesn't work like the way it used to. Indentation feature of web-mode also doesn't work perfectly. How can I configure my Emacs to enable Tab key work it just like before?

A: I am the author of web-mode.
Could give examples of indentation issues ?
Moreover "Tab key doesn't work like the way it used to" does not mean anything. Could you elaborate ?


text:
Q: Using proportion as the aggregate function in Data.Table's dcast When creating a pivot table using data.table, I am using the dcast function:
dcast(my_data, var1 ~ var2, length)

This gives a table with rows as var1 lables and column as var2 labels and value as count of cells common to particular row and column.
But instead of length I want to calculate the proportion and put it as the value, i.e. {count of cells common to particular row and column} divided by {count of all cells in the column i.e. a particular level of var2}
I have searched and couldn't able to implement it.
Any help would be appreciated.

A: There is a relatively simple solution, but it requires a second step after the dcast().
First, this is the data I am working on:
library(data.table)

set.seed(666)
my_data <- data.table(var1 = sample(letters[1:3], 10, TRUE),
                      var2 = sample(letters[4:6], 10, TRUE))

    var1 var2
 1:    c    f
 2:    a    d
 3:    c    d
 4:    a    d
 5:    b    d
 6:    c    f
 7:    c    d
 8:    b    f
 9:    a    e
10:    a    e

After the dcast
my_data_dcast <- dcast(my_data, var1 ~ var2, length)

the data looks like this:
   var1 d e f
1:    a 2 2 0
2:    b 1 0 1
3:    c 2 0 2

You can then simply go through all columns and divide each element in a column by the sum of all values in a column.
Select the columns to transform:
cols <- unique(my_data$var2)

Go through columns using lapply() on the subset of columns specified in .SDcols and override the values of all cols:
my_data_dcast[, (cols) := (lapply(.SD, function(col) col / sum(col))),
              .SDcols = cols]

The final result is this:
   var1   d e         f
1:    a 0.4 1 0.0000000
2:    b 0.2 0 0.3333333
3:    c 0.4 0 0.6666667

A: We can use Reduce with + if we need a row wise proportion
dcast(my_data, var1~ var2, length)[, .SD/Reduce(`+`, .SD), var1]
#   var1         A         B         C    D
#1:    a 0.3750000 0.0000000 0.3750000 0.25
#2:    b 0.6000000 0.2000000 0.2000000 0.00
#3:    c 0.2857143 0.1428571 0.5714286 0.00

If we need column wise
dcast(my_data, var1~ var2, length)[, .SD, var1][,
        (2:5) := Map(`/`, .SD, colSums(.SD)), .SDcols = -1][]
#   var1     A   B     C D
#1:    a 0.375 0.0 0.375 1
#2:    b 0.375 0.5 0.125 0
#3:    c 0.250 0.5 0.500 0

This would be more compact with base R
prop.table(table(my_data), 1)
prop.table(table(my_data), 2)

data
set.seed(24)
my_data <- data.table(var1 = sample(letters[1:3], 20, replace = TRUE),
           var2 = sample(LETTERS[1:4], 20, replace = TRUE))


text:
Q: Doctrine cant connect to database Im running a Symfony 5.3.2 application with Doctrine-bundle 2.4.2
I have a MariaDB 10.4.4 running also in a Docker-Container.
In my Controller Im trying to use:
 $doctrine = $this->getDoctrine();
 $repo = $doctrine ->getRepository('TestBundle:User');

But I just got the error
An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused
I have no Idea what Im missing. Do I need a special configuration in my database?
My Dockerfile:
FROM composer:latest AS composer
FROM php:7.4.20-apache

COPY --chown=33:33 . /srv/test
COPY .docker/vhost.conf /etc/apache2/sites-available/000-default.conf
COPY .docker/php.ini /usr/local/lib/
COPY .docker/php.ini /usr/local/lib/php
COPY .docker/php.ini /usr/local/etc/php

WORKDIR /srv/test

ENV COMPOSER_ALLOW_SUPERUSER 1

COPY --from=composer /usr/bin/composer /usr/bin/composer

RUN chown -R www-data:www-data /srv/test

RUN apt-get update && apt-get install -y \
        libfreetype6-dev \
        libjpeg62-turbo-dev \
        libpng-dev \
        libzip-dev \
                zip \
    && docker-php-ext-configure gd \
    && docker-php-ext-install -j$(nproc) gd \
    && docker-php-ext-install pdo_mysql \
    && docker-php-ext-install mysqli \
    && docker-php-ext-install zip \
    && docker-php-source delete \
    && useradd -rm -d /home/test-s /bin/bash -g root -G sudo -u 503 test \
    && pecl install xdebug \
    && apt install nano \
    && docker-php-ext-enable xdebug
RUN a2enmod rewrite
RUN service apache2 restart
RUN composer install

My Docker-Compose
version: '3.8'
services:
  app:
    build:
      context: .
      dockerfile: .docker/Dockerfile
    image: test-docker
    ports:
      - 8080:80
    links:
      - mysql
    volumes:
      - .:/srv/test
    environment:
      PHP_IDE_CONFIG: 'serverName=localhost'
      XDEBUG_SESSION: 'PHPSTORM'
      XDEBUG_MODE: 'debug'
  mysql:
    image: mariadb:10.4.4
    container_name: test_mysql
    volumes:
      - .docker/mysql/init:/docker-entrypoint-initdb.d
    restart: always
    ports:
      - 13306:3306
    environment:
      MYSQL_ROOT_PASSWORD: password

Config.yml
#If used in an dockerized development environment just remove the comment infront of the line containing
# "parameters_docker.yml" and comment out the line above.
imports:
    - { resource: parameters_docker.yml }

# Put parameters here that don't need to change on each machine where the app is deployed
# http://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    # a hack - should be configurable under jms_serializer, but the property_naming.id
    # doesn't seem to be taken into account at all.
    jms_serializer.camel_case_naming_strategy.class: JMS\Serializer\Naming\IdenticalPropertyNamingStrategy
    locale: en

framework:
    #esi:             ~
    translator:      { fallbacks: ["%locale%"] }
    secret:          "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection: ~
    validation:      { enable_annotations: true }
    #serializer:      { enable_annotations: true }
    templating:
        engines: ['php', 'twig']
    default_locale:  "%locale%"
    trusted_hosts:   ~
    trusted_proxies: ~
    session:
        # http://symfony.com/doc/current/reference/configuration/framework.html#handler-id
        handler_id:  session.handler.native_file
        save_path:   "%kernel.root_dir%/../var/sessions/%kernel.environment%"
    fragments:       ~
    http_method_override: true
    assets: ~

# Doctrine Configuration
doctrine:
    dbal:
        default_connection: return
        connections:
            default:
                schema_filter: ~^(?!view_)~
            user:
                driver:   pdo_mysql
                host:     "%database_host%"
                port:     "%database_port%"
                dbname:   "%database_name%"
                user:     "%database_user%"
                password: "%database_password%"
                charset:  UTF8
          # if using pdo_sqlite as your database driver:
          #   1. add the path in parameters.yml
          #     e.g. database_path: "%kernel.root_dir%/data/data.db3"
          #   2. Uncomment database_path in parameters.yml.dist
          #   3. Uncomment next line:
          #     path:     "%database_path%"
    orm:
        auto_generate_proxy_classes: "%kernel.debug%"
        default_entity_manager: return
        entity_managers:
            user:
                naming_strategy: doctrine.orm.naming_strategy.underscore
                connection: return
                mappings:
                    TestBundle:
                        type:     "annotation"
                        dir:      "Entity/User"
                        prefix:   "TestBundle\\Entity\\User"

parameters_docker.yml
    database_host:     127.0.0.1
    database_port:     3306
    database_name:     symfony_rest
    database_user:     root
    database_password: password


text:
Q: Why do tuples in a list comprehension need parentheses? It is well known that tuples are not defined by parentheses, but commas. Quote from documentation:

A tuple consists of a number of values separated by commas

Therefore:
myVar1 = 'a', 'b', 'c'
type(myVar1)
# Result:
<type 'tuple'>

Another striking example is this:
myVar2 = ('a')
type(myVar2)
# Result:
<type 'str'>

myVar3 = ('a',)
type(myVar3)
# Result:
<type 'tuple'>

Even the single-element tuple needs a comma, and parentheses are always used just to avoid confusion. My question is: Why can't we omit parentheses of arrays in a list comprehension? For example:
myList1 = ['a', 'b']
myList2 = ['c', 'd']

print([(v1,v2) for v1 in myList1 for v2 in myList2])
# Works, result:
[('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')]

print([v1,v2 for v1 in myList1 for v2 in myList2])
# Does not work, result:
SyntaxError: invalid syntax

Isn't the second list comprehension just syntactic sugar for the following loop, which does work?
myTuples = []
for v1 in myList1:
    for v2 in myList2:
        myTuple = v1,v2
        myTuples.append(myTuple)
print myTuples
# Result:
[('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')]

A: As I felt "because the grammar forbids it" to be a little too snarky, I came up with a reason.
It begins parsing the expression as a list/set/tuple and is expecting a , and instead encounters a for token.
For example:
$ python3.6 test.py
  File "test.py", line 1
    [a, b for a, b in c]
            ^
SyntaxError: invalid syntax

tokenizes as follows:
$ python3.6 -m tokenize test.py
0,0-0,0:            ENCODING       'utf-8'
1,0-1,1:            OP             '['
1,1-1,2:            NAME           'a'
1,2-1,3:            OP             ','
1,4-1,5:            NAME           'b'
1,6-1,9:            NAME           'for'
1,10-1,11:          NAME           'a'
1,11-1,12:          OP             ','
1,13-1,14:          NAME           'b'
1,15-1,17:          NAME           'in'
1,18-1,19:          NAME           'c'
1,19-1,20:          OP             ']'
1,20-1,21:          NEWLINE        '\n'
2,0-2,0:            ENDMARKER      ''

A: Python's grammar is LL(1), meaning that it only looks ahead one symbol when parsing.
[(v1, v2) for v1 in myList1 for v2 in myList2]

Here, the parser sees something like this.
[ # An opening bracket; must be some kind of list
[( # Okay, so a list containing some value in parentheses
[(v1
[(v1,
[(v1, v2
[(v1, v2)
[(v1, v2) for # Alright, list comprehension

However, without the parentheses, it has to make a decision earlier on.
[v1, v2 for v1 in myList1 for v2 in myList2]

[ # List-ish thing
[v1 # List containing a value; alright
[v1, # List containing at least two values
[v1, v2 # Here's the second value
[v1, v2 for # Wait, what?

A parser which backtracks tends to be notoriously slow, so LL(1) parsers do not backtrack. Thus, the ambiguous syntax is forbidden.

A: There was no parser issue that motivated this restriction. Contrary to Silvio Mayolo's answer, an LL(1) parser could have parsed the no-parentheses syntax just fine. The parentheses were optional in early versions of the original list comprehension patch; they were only made mandatory to make the meaning clearer.
Quoting Guido van Rossum back in 2000, in a response to someone worried that [x, y for ...] would cause parser issues,

Don't worry.  Greg Ewing had no problem expressing this in Python's
  own grammar, which is about as restricted as parsers come.  (It's
  LL(1), which is equivalent to pure recursive descent with one
  lookahead token, i.e. no backtracking.)
Here's Greg's grammar:
atom: ... | '[' [testlist [list_iter]] ']' | ...
  list_iter: list_for | list_if
  list_for: 'for' exprlist 'in' testlist [list_iter]
  list_if: 'if' test [list_iter]

Note that before, the list syntax was '[' [testlist] ']'.  Let me
  explain it in different terms:
The parser parses a series comma-separated expressions.  Previously,
  it was expecting ']' as the sole possible token following this.
  After the change, 'for' is another possible following token.  This
  is no problem at all for any parser that knows how to parse matching
  parentheses!
If you'd rather not support [x, y for ...] because it's ambiguous
  (to the human reader, not to the parser!), we can change the grammar
  to something like:
'[' test [',' testlist | list_iter] ']'

(Note that | binds less than concatenation, and [...] means an
  optional part.)

Also see the next response in the thread, where Greg Ewing runs
>>> seq = [1,2,3,4,5]
>>> [x, x*2 for x in seq]
[(1, 2), (2, 4), (3, 6), (4, 8), (5, 10)]

on an early version of the list comprehension patch, and it works just fine.


text:
Q: iOS: Tabbar - load default state of tab I need some idea or starting point to the following question:
I have an app which starts with an TabBarView - in some Tabs there are different Views / ViewControllers which are connected by seques.
If the active Tab is changed, i want the (now) open Tab to load the "Start"-View/ViewController of this Tab, not the View/ViewController which was last active on this Tab.
How can i do that?

A: I suggest you look at using the UITabBarDelegate method: tabBarController:didSelectViewController:
combined with the UINavigationController method: popToRootViewControllerAnimated:
So when the user selects a tab, you can ensure that the navigation begins from the root controller.
EDIT IN RESPONSE TO COMMENT:
It's not an ideal situation, but you can reference the UITabBarController in the app delegate. E.g.:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Get reference to Tab Bar Controller as the root view
    UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;

    // Set Delegate
    tabBarController.delegate = self;

    return YES;
}

You can then implement the UITabBarDelegate method similar to:
-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    // Pop to root if the selected controller is a navigation controller.
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        [((UINavigationController *)viewController) popToRootViewControllerAnimated:NO];
    }
}

I haven't tested this though!


text:
Q: Merging repositories override commits I have been trying to merge 3 subversion repositories together yesterday, and I am running into strange issues I cannot understand. I hope some of you can bring some additional insights.
In the subversion server, I first copied the major repository I want to use as a basis for the future:
$ cp main new

This creates a new repository, that I can checkout normally.
Then, I created subfolders in this repository :
$  svn mkdir svn+ssh://me@svn.website.se/spacemetric/svn/new/public --message "Added the public folder to merge video repository."

I dumped the content from my other repository into a file, which I then loaded into the newly created subfolder :
$ svnadmin dump public >  /disk/nas-files/website/shared/me/svnstuff/public_last.dump
$  svnadmin load . --parent-dir public < /disk/nasfiles/website/shared/me/svnstuff/public_last.dump

Now, I have a new repository that contains the content of both my main and public repository.
The next I wanted to do is to move the content of new/public/trunk into new/trunk, in order to be able to remove the public folder afterwards. That would allow me to work with only one repository in the future.
For this, I used tortoise, and selected all the folder in trunk and right-click dragged them into the new/trunk and selected "Move to"...
Everything seemed fine. . . for a while.
Then I realized that the last two weeks of commits in new have been overriden by really old commits of the public.
I do not understand why this could have happened, since I clearly performed a move operation.
Could someone bring me some insight on this?
Thanks


text:
Q: subscript out of range c++ vector erase when i try to erase an element from the vector i get an error subscript out of range vector
std::vector users; in my .hh
void    Server::read_client(int socket)
{
int     ret;
int     size;
char    buff[255];
std::string data = "Hello, world!";

size = 255;
ret = recv(socket, buff, size, 0);
if (ret == 0 || ret == SOCKET_ERROR)
{
    std::cout << "Client [" << socket << "] disconnected." << std::endl;

    for (int i = 0; i < this->users.size();)
    {
        if (this->users[i]->getId() == socket)
        {
            std::vector<User *>::iterator iter;
            /*for (iter = this->users.begin(); iter != this->users.end();)
            {
                if ((*iter)->getId() == socket)
                {
                    delete *iter;
                    closesocket(socket);
                    this->users.erase(iter); // crash here
                    return;
                }
                else
                    iter++;
            }*/
            closesocket(socket);
            delete this->users[i];
            this->users.erase(this->users.begin() + i); // crash here
            return;
        }
        else
            i++;
    }
    return;
}
}

i don't know why it crashes ... even if i do users.erase(users.begin()); it doesn't work and i get the same error

A: There is no need to write so much code since STL already gives you everything you need.
First you can use a std::vector<std::unique_ptr<User>> and forget about delete this->users[i]. Then you can use std::find_if to do the dirty job:
std::vector<std::unique_ptr<User>> users;

int socket = ...;
auto it = std::find_if(users.begin(), users.end(), [socket](const std::unique_ptr<User>& user) { return user->getId() == socket; });
users.erase(it);


text:
Q: How to post nested models in EmberJS with WebAPIAdapter from same view Our team has recently adopted EmberJS as our front-end framework! Our application is an ASP.NET MVC 4 application with WebAPI controllers interacting with EmberJS. It's almost magic the way it works and we really love it! However, we have a situation that we have simply not been able to resolve. We've spent way too much time on it and I'm hoping that someone on StackOverflow might be able to help us.
The application is very simple. A user is able to create an article and reference many sources from where they got the information from. Our models are setup like this:
// ARTICLES MODEL
App.Article = DS.Model.extend({
  status: DS.attr("string"),
  title: DS.attr("string"),
  body: DS.attr("string"),
  sources: DS.hasMany("App.Source"),

  didCreate: function () {
    var sources = this.get('sources');
    var id = this.get('id'); // <-- this is always null (?)
    debugger;
    sources.forEach(function (source) {
      source.set('articleId', id);
    });
  },
});

// SOURCE MODEL
App.Source = DS.Model.extend({
  name: DS.attr("string"),
  url: DS.attr("string"),
  article: DS.belongsTo("App.Article")
});

// ARTICLES.NEW CONTROLLER
App.ArticlesNewController = Ember.ObjectController.extend({
  // ... removed for brevity
  addSource: function(){
    var self = this;
    var source = App.Source.createRecord({
      articleId: self.get('id')
    });
    self.get('model.sources').addObject(source);
  },
  /* we also tried this, but it sends sources individually as well
  addSource: function() {
    this.get('model.sources').createRecord();
  },
  */
});

We are able to get everything working just fine. However, when creating articles things break down since the user is able to enter all the properties of the article as well as add multiple sources before commiting everything to the server. The problem is that when we post the data to the server, all of the models try to rush to the server as fast as they can and the Source objects don't have their articleId properties set yet. I tried getting around this by trapping the didCreate hook on DS.Model (notice code above)... This isn't work either.
Update: July 2nd
On the WebAPIAdapter, I tried setting the embedded property to always for the App.Article.sources:
DS.WebAPIAdapter.map('App.Article', {
  sources: { embedded: 'always' }
});

This still does not fix the problem. Each source is still hitting the server just as fast as the parent article. How do I prevent the source objects from being posted to the server for a particular transaction (ie. the 'New Article' transaction)?
Perhaps we are overthinking this and there is a "one config setting" flag that we are missing somewhere. We would appreciate any help on this!
Thanks in advance,
Luc
P.S. Note that I tried creating a fiddle for this: proof. However, it took me +3 hours to get where I got (I'm not a professional JSFiddler) and I clearly have more work that needed done. I resorted to explaining the problem verbally instead with code snippets. :)

A: I guess you need to tell the Adapter that your Source model is embedded. This way the Article and the Source model will be treated as one in terms of creating/deleting etc.
Try to define it like this:
DS.RESTAdapter.map('App.Article', {
  sources: { embedded: 'always' }
};

For the embedded property there are to possible values, load & always:
load: with load the child records are embedded when loading, but should be saved as standalone records. In order for this to work, the child records must have a proper id.
always: with always the child records are embedded when loading, and are saved embedded in the same record.
Hope it helps.

A: I had a similar problem. Before you assign the id, you'll need to wait for transaction to complete. You have to wait until the next run loop:
didCreate: function () {
    Ember.run.next(this, function () {
        var sources = this.get('sources'),
            id = this.get('id');

        sources.forEach(function (source) {
           source.set('articleId', id);
        });
    }
}


text:
Q: Iterating JSON in a django template I have a json coming from a view in below format in a variable(AllUsers) :
{
  "msg": "data found.",
  "user": [
    {
      "fname": "aaa",
      "lname": "aaa",
      "add": "add1",
      "city": "city1",
    },
    {
      "fname": "aaa2",
      "lname": "aaa2",
      "add": "add2",
      "city": "city2",
    }
  ],
  "data_status": "active",
  "error": false
}

I need to iterate through this JSON in my template and print in below format.So ideally my loop should run 2 times in this case.
name : aaa
name : aaa2

I tried :
{% for myusers in AllUsers %}
       name : {{ user.fname}}
{% end for%}

AND
{%with myusers=AllUsers.user%}
{% for user in myusers %}
name : {{ user.fname}}
{% endfor %}
{% endwith %}

But both of them are not working as loops are not iterating even once.In one of SO threads i read ....You shouldn't "convert it to JSON".... but this is not in my hand...i just get the JSON.
Views looks like this :
def somefucn(request):
    data = {
        "msg": "data found.",
        "AllUsers": AllUser                    ## This is where the above JSON resides
        "data_status": "active",
        "error": false
    }
    return TemplateResponse(request, 'path/to/Template.html', data)

Where am i going wrong in the iteration? Please help..

A: the solution was much easier than I thought:
Let's say you have some JSON like POST request with schema like:
"success": true,
  "users": [
    {
      "userId": "76735142",
      "username": "user11_01",
      "email": "test11@test.com",
      "isTest": false,
      "create_at": "2016-01-29T15:41:16.901Z",
      "isBlocked": false
    }

(All values in the scheme above were given as example)
And you know that to get this response correctly you need next variables in your post body:
{
"id": "",
"pass_code": "",
"search_for": "",
}

Next you need to send POST request with needed values to the API server:
First you need to install necessary components (from your virtualenv):
pip install requests[security]

[security] flag is needed in order to successful response from HTTPS
VIEWS.PY
import requests
from django.shortcuts import render_to_response

def get_user(request):
    args = {}
    args.update(csrf(request))
    post_data = {'id': '1234', 'pass_code': 'pass', 'search_for': '123456'}
    response = requests.post('https://example.com/api/', data=post_data)
    args['contents'] = response.json()
    return render_to_response('your_templae.html', args)

YOUR_TEMPLATE.HTML

<title>testing JSON response</title>

{% for user in contents.users %}
    {{ user.userId}}

    {{ user.username}}

{% empty %}
    Nothing found
{% endfor %}

That's it! Have a nice work!
If you mess around you can event fetch headers of this request ;-)

A: You can use template filter to load json in the template.
Create a file mytags.py as <your-app>/templatetags/mytags.py
The content of mytags.py as:
import json

from django import template

register = template.Library()

@register.filter
def loadjson(data):
    return json.loads(data)

Then in your django .htm/.html template load the tags. eg:
{% load mytags %}

{% for foo in YourJsonData|loadjson %}
    {{ foo.something }}
{% endfor %}

Hope this helps.
For more info about advanced templating see: http://www.djangobook.com/en/2.0/chapter09.html#extending-the-template-system


text:
Q: Excel Addin : Workbook refresh with data mode , Error : The cartridge directory could not be found I had a 2013 32-bit excel (Professional edition) and I am developing an addin. In  this addin I refresh a excel workbook. This workbook has a Data Model. My OS was recently upgraded from Windows 8 to Windows 10.
When I was refreshing the workbook through code, it throws me an error :
"We couldn't get data from the Data Model."
The cartridge directory could not be found.  Use the Windows Installer to repair the application.  Exception of type 'Microsoft.Office.PowerPivot.BackEnd.StorageException' was thrown."
I saw this  link in MSDN forums and tried to install 32 bit of those Hotifixes mentioned in the link, but it said "The hotfix was already installed".
I thought that may be something got corrupt while upgrade from Windows 8 to Windows 10. So I uninstalled 32-bit of office and restarted machine. Then I installed the Office 64-bit Professional version.
I then again tried to install the 64 bit version of the hotfixes but again got message "There is no software to apply this hotfix".I tried to run the add in code again but it again threw the same error again. My 64-bit machine is a click and run version of office (I checked in registry based on a article).
I do not think for my new 64 bit office, no updates are applied. I am not sure what is causing the error. Please advise.
My question are:

*

*Any suggestion what could be happening

*In Click and Run version of office 2013 , how do I update (All updates available) that ? I do not see any way I can update.

*Is this issue resolved in any SP or CU.

*Any way to resolve this?
I am currently stuck with this. Note : It works when manually refreshing. Just throws error when doing this through C# code.

*

*Girija


text:
Q: Decomposing Lagrangian into CM and relative parts with presence of uniform gravitational field Most problems concerning two-body motion (using Lagrangian methods) often only consider the motion of two particles subject to no external forces. However, the Lagrangian should be decomposable into the center of mass (CM) and relative parts even if our closed system (momentum of the CM is constant) of two interacting masses is producing an attractive gravitational field.
The Lagrangian that describes the two-body system with no attractive gravitational field is
$${\cal L}=\frac{1}{2}M\dot{\vec{R}}^2 +\left(\frac{1}{2}\mu\dot{\vec{r}}^2-U(r)\right)={\cal L}_{\rm CM}+{\cal L}_{\rm rel}$$
If we then considered an attractive gravitational field, how would this change the above Lagrangian?
My thought process is that the CM term will not change, since the gravitational field is attractive w.r.t the two masses, thereby implying that only the terms containing r will be affected by the field.
The gravitational field between masses 1 and 2 is simply described as conservative and central: $\vec{g}$.
How would I rewrite the Lagrangian with this g-field now in play?

A: It's not clear to me from your question if you are interested in the gravitational force that two particles exert on each other, or on the gravitational force the two particles experienced if they move in an external field. The way you handle these two cases is different, so below I outline how you can handle both.
If you are interested in the gravitational force that the two particles exert on each other, then you simply add a gravitational term in the potential
\begin{equation}
U(r) = U_{\rm non-gravity}(r) + U_{\rm gravity}(r)
\end{equation}
where
\begin{equation}
U_{\rm gravity}(r) = -\frac{G m_1 m_2}{r}
\end{equation}
The potential only appears in the relative term of the Lagrangian.
If you are interested in the particles moving in an external field, then...

*

*...if the external field is a constant in magnitude and direction, one strategy is to take advantage of the equivalence principle to cancel this force. Move into a freely falling frame that is accelerating with the same magnitude and opposite direction as the gravitational acceleration, and the gravitational force will be canceled by the fictitious force from being in a non-inertial reference frame.

*...if the external field is not constant (or if you just don't like using the equivalence principle), then you can write the Lagrangian in terms of the coordinates of the two particles $x_1$ and $x_2$ (without going to the center of mass and relative coordinates) as
\begin{equation}
\mathcal{L} = \frac{1}{2} m_1 \dot{x}_1^2 + \frac{1}{2} m_2 \dot{x}_2^2 - U(|\vec{x}_1 - \vec{x}_2|) - U_{\rm g, ext}(\vec{x}_1, \vec{x}_2)
\end{equation}
where $U_{\rm g, ext}(\vec{x}_1, \vec{x}_2)$ describes the potential energy due to the location of the point masses in the external gravitational field. For example, if you had a mass $M$ placed at a position $\vec{R}$, then the external potential energy would be
\begin{equation}
U_{\rm g, ext}(\vec{x}_1, \vec{x}_2) = - \frac{G M m_1}{|\vec{R}-\vec{r}_1|} - \frac{G M m_2}{|\vec{R}-\vec{r}_2|}
\end{equation}
As another example, you could consider the two particles in a uniform gravitational field where the magnitude of the gravitational acceleration is $g$, in which case
\begin{equation}
U_{\rm g, ext}(\vec{x}_1, \vec{x}_2) = m_1 g h_1 + m_2 g h_2
\end{equation}
where $h_1$ is the height of particle 1 (aka the displacement from particle 1 to wherever your surface of zero potential is), and $h_2$ is the height of particle 2.
Regardless of the specific form of $U_{\rm g, ext}$, since the external gravitational potential breaks translation invariance, momentum is not conserved, so the split into center of mass and relative coordinates may not be a useful thing to do in this case.

A: two-body motion
first you transfer the absolute coordinates $~r_1~,r_2~$ to the relative coordinate $~r~$ and the center of mass   coordinate $~R_c~$
I use this two equations
$$R_c=\frac{m_1\,r_1+m_2\,r_2}{m_1+m_2}\\
r=r_1-r_2$$
the solution for  $~r_1~,r_2~$ is:
$$r_1=\frac{R_c+r\,m_2}{m_1+m_2}\\
r_2=\frac{R_c-r\,m_1}{m_1+m_2}$$
from here you obtain the kinetic energy and the potential energy
$$T=\frac{m_1}{2}\dot r_1^2+\frac{m_2}{2}\dot r_2^2=
\frac 12 M\,\dot R_c^2+\frac 12 \frac{m_1\,m_2}{m_1+m_2}\dot r^2$$
$$U(r)=-\frac{m_1\,m_2\,G}{r}$$
the potential energy in case of the gravitation vector  $~\vec g~$
is:
$$U=-m_1\,g\,r_1-m_2\,g\,r_2=-M\,g\,R_c$$
EOM's
$$\ddot R_c=-g\\
\ddot r =0\quad \Rightarrow\\
\ddot r_1=-g\\
\ddot r_2=-g$$


text:
Q: Spring OAuth2+OIDC user logged in and pressed back button in browser I develop an application-Client and Authorization server on Spring Boot.
When user logged in in authorization server, redirected to client app and then press button back, he cames to login page of authorization server again, again logged in and after redirect the error appears. While debugging I saw, that after second redirect to client app session has no attribute AuthorizationRequest (exception org.springframework.security.oauth2.core.OAuth2AuthenticationException: [authorization_request_not_found] was just caught in filters and I didn't see it in logs).
May be someone run into same situation or know best way to handle such situations?
The result I expect is no exception for this flow, or after perss back user stay in client app as logged in user and not goes to authorization again.


text:
Q: How important is the global.json and src folder? In VS 2015, when you create a new MVC 6.0 application using this approach:
File-->New-->Project-->ASP.NET Web Application-->ASP.NET 5 Preview Templates

You end up have the following file structure on disk:

*

*artifacts

*src

*MyProject.sln

*global.json

Instead if I decide to create a blank solution first like so:
 File-->New-->Project-->Other Project Types-->Visual Studio Solutions-->Blank Solution

And start adding a new ASP.NET Web Application project to this solution; you end up having a file structure that doesn't have a global.json file and no src folder.
According to the documentation, the global.json file is used to configure the solution as a whole. It includes just two sections, projects and sdk by default.
The projects property designates which folders contain source code for the solution. By default the project structure places source files in a src folder, allowing build artifacts to be placed in a sibling folder, making it easier to exclude such things from source control.
The sdk property specifies the version of the DNX (.Net Execution Environment) that Visual Studio will use when opening the solution. It's set here, rather than in project.json, to avoid scenarios where different projects within a solution are targeting different versions of the SDK.
Question 1)
As mentioned above, if I choose to first create a Blank Solution, I won't be having a global.json file.
Is not having a global.json file impact the application's behavior in any shape or form? For example when I deploy or the interaction with the build artifacts?
Question 2)
If it does have an impact, then should I manually be creating this global.json file?
Question 3)
As of this writing, is there a recommended approach for creating a multi-layered application in ASP.NET 5?
Should I first create the MVC project and start adding Class Libraries to the project?
Or
Should I first start by creating a Blank Solution and start adding the Class Libraries and the Web Application to the solution (knowing I won't have global.json file nor a src folder)?

A: The src, test, etc. folders allow you to group projects by type. This helps keep the solution maintainable when there are a large number of projects. Here is an example of various project types that have been proposed.
Per the ASP.NET Core Engineering Guidelines: "By default project-to-project references must be sibling folders. Using a global.json file allows a solution to specify non-standard locations to locate references."
To sum it up, if have lots of projects, you can group them by type into folders and use global.json to allow projects in one group to reference those in another.

A: 1) Yes, for me I also had this issue and started with blank solution. Then my projects had issues referencing each others.
2) For me it did not work without global.json. You also need to make sure the solution file points correctly to everything, like the global.json.
The projects did not build and did not find each others for me otherwise.
3) To get everything working I created a mvc core project first to get the global.json file. Then I renamed the scr folder to applicationname.web. Make sure to alter the solution file accordingly so it does not point wrong. Also you should update the project.json file.
This way, all thou I wanted a blank solution like you, I created a default project and then altered it to how I wanted it, that worked for me.
I will build my current app using Onion Architeture as a guideline. I see no issue doing this with core. This also means that I will build the IoC in a different project (probably named infrastructure.IoC) so that my web project does not contain references to projects containing implementations of interfaces that the web should not know about.
Also, if you still have problems, I actually got local build and reference problems because I had resharper and I turned that off, then the reference problems between projects went away and I could build successfully.

A: As you've noted, this seems to be the new way of creating solutions when targeting ASP.NET 5. The global.json file specifies some solution-level settings. In particular, it defines the DNX runtime settings.
I've seen two approaches to the src / test folder structure. If you look at what the MVC team is doing, they incorporate the src / test folders into the repository root. Many projects on, e.g., Github have a src directory in the root. So as long as you're OK with your global.json and solution files in the root of your project, it seems to align well with existing practices.
If you look at what the .NET team is doing with the .NET 5 Core Framework, you'll see a similar pattern, albeit without the global.json file. Many of their libraries have src and tests subdirectories.
I am going to try to pattern my projects after what the MVC team is doing for the time being, until I have a better understanding of .NET 5, DNX, and the rest. It does impose a certain structure on your projects, but then so did VS 2013 and .NET 4.5.


text:
Q: How to use Hibernate ORM 5.5.x.Final with Jakarta 9 on wildfly-preview-25.0.0.Final Have been running Hibernate OGM (using MongoDB) for a number of years. Currently using WildFly 25.0.0.Final:
/wildfly-25.0.0.Final/modules/org/hibernate/ogm/internal/parboiled/5.4/asm-util-6.0.jar
/wildfly-25.0.0.Final/modules/org/hibernate/ogm/internal/parboiled/5.4/parboiled-core-1.3.1.jar
/wildfly-25.0.0.Final/modules/org/hibernate/ogm/internal/parboiled/5.4/asm-analysis-6.0.jar
/wildfly-25.0.0.Final/modules/org/hibernate/ogm/internal/parboiled/5.4/parboiled-core-1.1.8.jar
/wildfly-25.0.0.Final/modules/org/hibernate/ogm/internal/parboiled/5.4/parboiled-java-1.1.8.jar
/wildfly-25.0.0.Final/modules/org/hibernate/ogm/internal/parboiled/5.4/asm-6.0.jar
/wildfly-25.0.0.Final/modules/org/hibernate/ogm/internal/parboiled/5.4/asm-tree-6.0.jar
/wildfly-25.0.0.Final/modules/org/hibernate/ogm/mongodb/5.4/hibernate-ogm-mongodb-5.4.1.Final.jar
/wildfly-25.0.0.Final/modules/org/hibernate/ogm/mongodb/5.4/mongo-java-driver-3.12.10.jar
/wildfly-25.0.0.Final/modules/org/hibernate/ogm/jipijapa/5.4.1.Final/hibernate-ogm-jipijapa-5.4.1.Final.jar
/wildfly-25.0.0.Final/modules/org/hibernate/ogm/5.4/hibernate-ogm-core-5.4.1.Final.jar
/wildfly-25.0.0.Final/modules/org/hibernate/hql/1.5.0.Final/hibernate-hql-lucene-1.5.0.Final.jar
/wildfly-25.0.0.Final/modules/org/hibernate//hql/1.5.0.Final/antlr-runtime-3.5.2.jar
/wildfly-25.0.0.Final/modules/org/hibernate/hql/1.5.0.Final/antlr-runtime-3.4.jar
/wildfly-25.0.0.Final/modules/org/hibernate/hql/1.5.0.Final/hibernate-hql-parser-1.5.0.Final.jar

I want to migrate to Jakarta 9 using: wildfly-preview-25.0.0.Final.
I get this now:
Caused by: jakarta.persistence.PersistenceException: WFLYJPA0057: PersistenceProvider 'org.hibernate.ogm.jpa.HibernateOgmPersistence' not found

Looked at: https://in.relation.to/2021/06/02/hibernate-orm-550-final-release/ and downloaded:

hibernate-release-5.5.8.Final.zip

persistence.xml is:
<persistence-unit name="goStopHandleMongoDBPersistenceUnit" transaction-type="JTA">

        <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>

        <properties>
            <!-- <property name="jboss.as.jpa.providerModule" value="org.hibernate:5.2"/> -->
            <property name="jboss.as.jpa.providerModule" value="org.hibernate:5.5"/>

            <!-- <property name="wildfly.jpa.hibernate.search.module" value="org.hibernate.search.orm:5.8"/> -->
            <property name="wildfly.jpa.hibernate.search.module" value="org.hibernate.search.orm:5.10"/>

            <!-- <property name="hibernate.transaction.jta.platform" value="JBossTS"/> -->
            <!-- <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAS"/> -->
            <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform"/>
            <property name="hibernate.ogm.datastore.provider" value="org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider"/>
            <property name="hibernate.ogm.datastore.grid_dialect" value="org.hibernate.ogm.datastore.mongodb.MongoDBDialect"/>
            <property name="hibernate.ogm.datastore.database" value="goStopHandleDB"/>

            <property name="hibernate.ogm.datastore.host" value="127.0.0.1:27017"/>
        </properties>
</persistence-unit>

I can't located where I can found the Jars for
Hibernate ORM 5.5.8.Final & deploy on:
modules/org/hibernate etc.

A: Hibernate OGM is not going to work with ORM 5.5 (the latest version requires ORM 5.3).
Also, there hasn't been any progress on Hibernate OGM for a while and there are no future plans for it.