Q: Dynamically resize UICollectionViewCell in non-scrolling UICollectionView I have a small, single row horizontal layout UICollectionView at the top of the screen. It can contain up to a maximum of 6 items. The problem is that I want all 6 items visible without scrolling (this collection view is also going to be used in a Today extension which doesn't allow scrolling). What I want to do is reduce the cell-size and inter-item spacing a little bit to allow all 6 cells to fit.
Basically I'm trying to avoid this:

I've been playing with this for a while but I'm not sure how to approach it. I created a method that's fired every time an item is added or removed from the collection view, just before [self.collectionview reloadData] is called.
-(void)setupCollectionViewLayout{

     UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.buttonBarCollectionView.collectionViewLayout;

        //Figure out if cells are wider than screen
    CGFloat screenwidth = self.view.frame.size.width;

    CGFloat sectionInsetLeft = 10;
    CGFloat sectionInsetRight = 10;
    CGFloat minItemSpacing = flowLayout.minimumInteritemSpacing;
    CGSize  itemsize = CGSizeMake(58,58);
    CGFloat itemsizeWidth = itemsize.width;
    CGFloat totalWidth = sectionInsetLeft + sectionInsetRight +
                        (itemsizeWidth * _armedRemindersArray.count) +
                        (minItemSpacing * (_armedRemindersArray.count -2));

    CGFloat reductionAmount = itemsizeWidth;
    if (totalWidth > screenwidth) {

        while (totalWidth > screenwidth) {
            totalWidth = totalWidth - 1;
             reductionAmount = reductionAmount - 1;
        }

        CGSize newCellSize = CGSizeMake(reductionAmount, reductionAmount);
        flowLayout.itemSize = newCellSize;

    }

    else flowLayout.itemSize = itemsize;

}

This is the result.

Not exactly what I was expecting. Not only did it squash everything to the left and also added a second line, but I also seem to have a cell-reuse issue. Truthfully I would just use static-cells if it was even an option, but unfortunately it seems like it's not possible.
What should I be doing? Subclassing UICollectionViewFlowLayout? Won't that basically do the same thing I'm doing here with the built-in flow layout?
EDIT:
Kujey's answer is definitely closer to what I need. I still have a cell-reuse issue though.

A: Xcode provides an object designed for your need. It's called UICollectionViewFlowLayout and all you need to do is subclass it and place your cells the way you want. The function prepareForLayout is call every time the collection view needs to update the layout.
The piece of code you need is below :
#import "CustomLayout.h"

#define MainCell @"MainCell"

@interface CustomLayout ()

@property (nonatomic, strong) NSMutableDictionary *layoutInfo;

@end

@implementation CustomLayout

-(NSMutableDictionary *) layoutInfo
{
    if (!_layoutInfo) {
        _layoutInfo = [NSMutableDictionary dictionary];
    }

    return _layoutInfo;
}

-(void) prepareLayout
{
    NSMutableDictionary *cellLayoutInfo = [NSMutableDictionary dictionary];

    NSIndexPath *indexPath;

    CGFloat itemWidth;
    CGFloat itemSpacing;

    CGFloat widthWithoutSpacing = [self collectionViewContentSize].width / ([self.collectionView numberOfItemsInSection:0]);

    if (widthWithoutSpacing > [self collectionViewContentSize].height) {
        itemWidth = [self collectionViewContentSize].height;
        itemSpacing = ([self collectionViewContentSize].width - itemWidth*[self.collectionView numberOfItemsInSection:0])/
        ([self.collectionView numberOfItemsInSection:0]+1);
    }
    else {
        itemWidth = widthWithoutSpacing;
        itemSpacing = 0;
    }

    CGFloat xPosition = itemSpacing;

    for (NSInteger section = 0; section < [self.collectionView numberOfSections]; section++) {

        for (NSInteger index = 0 ; index < [self.collectionView numberOfItemsInSection:section] ; index++) {

            indexPath = [NSIndexPath indexPathForItem:index inSection:section];
            UICollectionViewLayoutAttributes *itemAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];

            CGRect currentFrame=itemAttributes.frame;

            currentFrame.origin.x = xPosition;
            currentFrame.size.width = itemWidth;
            currentFrame.size.height = itemWidth;

            itemAttributes.frame=currentFrame;
            cellLayoutInfo[indexPath] = itemAttributes;

            xPosition += itemWidth + itemSpacing;
        }
    }

    self.layoutInfo[MainCell] = cellLayoutInfo;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *allAttributes = [NSMutableArray arrayWithCapacity:self.layoutInfo.count];

    [self.layoutInfo enumerateKeysAndObjectsUsingBlock:^(NSString *elementIdentifier, NSDictionary *elementsInfo, BOOL *stop) {
        [elementsInfo enumerateKeysAndObjectsUsingBlock:^(NSIndexPath *indexPath, UICollectionViewLayoutAttributes *attributes, BOOL *innerStop) {
            if (CGRectIntersectsRect(rect, attributes.frame)) {
                [allAttributes addObject:attributes];
            }
        }];
    }];

    return allAttributes;
}

-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return self.layoutInfo[MainCell][indexPath];
}

-(CGSize) collectionViewContentSize
{
    return self.collectionView.frame.size;
}

@end

You can also change the y origin of your cells if you need to center them vertically.

A: try with this code. I get the width and use _armedRemindersArray (i guess you use this array for the items).
-(void)setupCollectionViewLayout{
         UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.buttonBarCollectionView.collectionViewLayout;

         //Figure out if cells are wider than screen
         CGFloat screenwidth = self.view.frame.size.width;
         CGFloat width = screenwidth - ((sectionInsetLeft + sectionInsetRight) *_armedRemindersArray.count  + minItemSpacing * (_armedRemindersArray.count -2));
         CGSize  itemsize = CGSizeMake(width,width);
         flowLayout.itemSize = itemsize;
}

A: I don't know why you're setting the itemsize first, and then reducing it. I think you should do it the other way around:
-(void)setupCollectionViewLayout{

     UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.buttonBarCollectionView.collectionViewLayout;

    CGFloat sectionInsetLeft = 10;
    CGFloat sectionInsetRight = 10;
    CGFloat minItemSpacing = flowLayout.minimumInteritemSpacing;

    // Find the appropriate item width (<= 58)
    CGFloat screenwidth = self.view.frame.size.width;
    CGFloat itemsizeWidth = (screenwidth - sectionInsetLeft - sectionInsetRight - (minItemSpacing * (_armedRemindersArray.count -2))) / _armedRemindersArray.count
    itemsizeWidth = itemsizeWidth > 58 ? 58 : itemsizeWidth;

    flowLayout.itemSize = CGSizeMake(itemsizeWidth, itemsizeWidth);
}

Does this work? If not, could you please include more of your code?


Q: Openshift new-app from image creates service with incorrect ports I am using openshift oc new-app to create a app from a image.
However oc new-app is creating the associated openshift service incorrectly with only one tcp port, not the two ports than the application uses.
Is there any simple way to force openshift new-app to correctly create the service with the two correct ports when building from a image rather than incorrectly with only one port ?
Alternatively is there a command line way to add the extra port to the service created that can be scripted (I know about oc edit) ..
(Disclaimer.. I am new to openshift and have lots to learn)


Q: How can I get rid of the parentheses in the dataframe column?(Python) I have dataframe like this

I want to remove the parentheses in the Movie_Name column.
Here is a few example
df_Movie["Movie Name"].str.findall(r'\([^()]*\)').sum()

['(500)',
 '(Eksiteu)',
 '(Mumbai Diaries)',
 '(Geukhanjikeob)',
 '(Erkekler Ne İster?)',
 '(The Witch)',
 '(Ji Hun)']

And then ı tried this solution.
import re
df_Movie["Movie Name"] = df_Movie["Movie Name"].str.replace(r'\([^()]*\)', ' ', regex = True)

Here is the output of the solution for one example.
df_Movie.iloc[394, :]
Movie Name      Days of Summer
Year                      2009
IMDB                       7.7
Name: 394, dtype: object

In this case, the values between the parentheses are completely lost. I don't want that.
I want output like this : (500) Days of Summer --> 500 Days of Summer
How can ı solve this ?

A: You can remove all parentheses from a dataframe column using
df_Movie["Movie Name"] = df_Movie["Movie Name"].str.replace(r'[()]+', '', regex=True)

The [()]+ regex pattern matches one or more ( or ) chars.
See the regex demo.


Q: pyspark - how to handle unicode from hive I am trying read a hive table in pyspark
from pyspark.sql import SQLContext
from pyspark import HiveContext
hivec = HiveContext(sc) sqlc = SQLContext(sc)
t = hivec.sql("select * from database.table").collect()

data = sqlc.createDataFrame(t)
data.registerTempTable("masterTable")
sqlc.sql("select * from masterTable").show()

I get the below error

UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in
  position 8871: ordinal not in range(128)

What I have tried:
I figured out the record that was falling over, when I "select * from    " in hive for the same record, there is no error reported nor can I    see any unicode
 - t = hivec.sql("select * from database.table").collect() there are    no errors reported in t variable itself
   '>>>t
   prints out all the rows

As soon as t  gets converted to DataFrame the issue pops up
I tried encoding and decoding, combination between 'utf-8' and    'ascii' mainly as I couldn't tell if the field was a unicode or a ascii visually as hive select nor printing the list was showing anything visible or throwing errors.
data.select(*(c.encode("ascii","ignore") if not isinstance(c,unicode) else c for c in data.columns )).show(10)

Throws the same error. Any suggestions how to get around this?


Q: Role based logo and UI in wss 3.0 I have to show user based logo and UI in wss 3.0. How can i do this? Can I customize master page or theme for users? Is there inbuilt option for this? It would be better if I could do this without programming.
Suppose I have 3 users and I would like to show their logo on login. they have their own logo.

A: This type of customisation will be very difficult to do without any programming.
I believe that this can be done however, with a custom masterpage in SharePoint Designer 2007, but there needs to be someway of identify the role of the current user. Once that role has been identified, by whatever method, then you can apply custom CSS files to apply different branding for the different users.
Are you able to be any more specific in your requirement? How do users differ, how do you tell SharePoint what user belongs to what role?

A: It's probably not something you will use for this specific solution, but you might want to check out Audiences
With an Audience, you can create a 'group' of people (picked by some common parameter). In several webparts you can set which Audience should see the webpart. Don't know if the picture webpart allows such things, but you might find this interesting.
http://office.microsoft.com/en-us/sharepoint-server-help/target-content-to-specific-audiences-HA010169053.aspx


Q: The removeChild(); is removing two inputs? I just need to remove 1 input I'm new to javascript, and currently, I need an individual delete function. I decided to use variable.removeChild() but it's deleting 2 inputs
document.addEventListener('DOMContentLoaded', () => {

  document.getElementById("delete").addEventListener("click", function deletes(){

    var parent = document.getElementById("list");

    var child = parent.getElementsByTagName("li")[0];

    console.log(child);

    parent.removeChild(child); //deletes a pair of my li inputs

  });

});

Here is how my HTML code looks like

LIST

Items:

test

        <form id="insert">
            <input type="text" id="itemInput" placeholder="Item" name="item">
            <input type="submit" id="add" value="Add">

        </form>
        <input type="submit" id="search" value="Search"> //search doesn't do anything yet
        <input type="submit" id="delete" value="Delete first item">  //Here is where it begins

Here is my other function. I also use addEventListener() perhaps is that the problem?
This code allows me to add list items dynamically to how the user wishes
document.addEventListener('DOMContentLoaded', () => {
//calls function once #insert has submit a form/hit the input
document.querySelector('#insert').onsubmit = () => {

    //create variable
    if(document.querySelectorAll('li').length >= 10){
        return false;
    };

    //get the value of the input
    let name = document.querySelector('#itemInput').value;
    //stores value in the h3 tag

    //create element of 'li'
    const li = document.createElement('li');
    //add the contents to the value of 'name'
    li.innerHTML = name;

    //now append the element to the #list section
    document.querySelector('#list').append(li);

    //gets the length of all the list items (li) and stored it in counter
    counter = document.querySelectorAll('li').length;
    //change the h2 tag with the updated list items
    document.querySelector('h2').innerHTML = `Items: ${counter}`;

    //prevents the form from submitting (good for debugging!!!)
    return false;
};

});

A: Get the list with document.querySelector('#list') and the first li by adding .querySelectorAll('li')[0], then find inputs inside.

document.addEventListener('DOMContentLoaded', () => {
    document.querySelector('#delete').addEventListener("click", function deletes(){
        let li = document.querySelector('#list').querySelectorAll('li')[0];
        let inputs = li.querySelectorAll('input');
        // Is there any input in li?
        if(inputs.length > 0) {
            // Delete only the first one
            inputs[0].remove();
            // If you want to keep other inputs, just disable the button
            this.disabled = true;
        }
    });
});

     <input type="text" value="input1">
     <input type="text" value="input2">

<button id="delete">Delete</button>

querySelector() and querySelectorAll() lets you find items by id, classname, tagname, attributes, etc. Just like jQuery does. Reference: https://developer.mozilla.org/en/docs/Web/API/Document/querySelector


Q: Eliminar elementos de un combobox cargado x BD luego de comparación con otra BD VB .NET Tengo un listado de procesos productivos, y tengo un producto que sigue una serie de esos procesos asignados. Cuando cargo el formulario, lleno un combobox con los procesos, pero al seleccionar el producto que ya tiene procesos debería eliminar los procesos que ya paso y sólo mostrarme los que faltan completar o los que estan vigentes.
Se me ocurre cargar los procesos en el combo, todos y despues recorrer y obtener los procesos terminados y despues recorrer nuevamente el combobox y remover items con:
ComboBox1.Items.RemoveAt(codigoProceso)

Ahora bien, cómo tendría que hacer esa operación ?

A: Los procesos se deberían cargar en demanda según el producto seleccionado y no de manera completa tal como lo vienes haciendo al cargar el formulario. En consecuencia, deberías poblar/enlazar el desplegable de procesos en el controlador del evento 'SelectionChangeCommitted' que se produce tras seleccionar un elemento del desplegable de productos, algo como:
Private Sub cbxProduct_SelectionChangeCommitted(sender As Object, e ...

    cbxProcess.DisplayMember = "Process"
    cbxProcess.ValueMember = "Id"
    cbxProcess.DataSource = GetProcesses(CInt(CType(sender, ComboBox).SelectedValue))

End Sub

Finalmente, para recuperar los procesos pendientes -para el producto seleccionado- debes discriminar los que ya se encuentren asociados -entiendo en una tabla de unión, intermedia-, por ejemplo:
SELECT id, Process FROM Process p
WHERE NOT EXISTS (SELECT 1 FROM Process_Product WHERE ProductId = @ProductId);
GO


Q: Select select form options using links and asmselect I have integrated jquery-asmselect  and would like to be able to also select the options using other links on the page.  To visualize what I'm trying to do, you can view the page here
Here is the jquery code I'm using for asmselect:
$(document).ready(function() {
    $("#CategoryID").asmSelect({
        addItemTarget: 'bottom',
        animate: true,
        highlight: false,
        sortable: false
    }).after($("select all neighborhoods").click(function() {
        $("#CategoryID").children().attr("selected", "selected").end().change();
        return false;
    }));
    $("#search_SubCategoryID").asmSelect({
        addItemTarget: 'bottom',
        animate: true,
        highlight: false,
        sortable: false
    }).after($("select all cuisines").click(function() {
        $("#search_SubCategoryID").children().attr("selected", "selected").end().change();
        return false;
    }));
});

A: First of all, you'll need to identify in wich neighborhood you are clicking. Adding a rel (like in the options) might work:
...

    East Village/LES

...

Then, add this script:
$(".search-map a").click(function(event) {
    event.preventDefault();
    var hood = $(this).attr('rel');
    var $option = $('option[rel=' + hood + ']');

    $option.change();
    return false;
});

Based on this asmselect example. You just need to get the correspondig option depending on the clicked link, and then call the change(); trigger on it.
EDITED:
The above code failed big time :P Here's the new version (With a working fiddle):
$(".search-map a").click(function() {

    var $city = $(this).html();
    var $rel = $(this).attr('rel');
    var disabled = $('#asmSelect0 option[rel=' + $rel + ']:first').attr('disabled');

    if (typeof disabled !== 'undefined' && disabled !== false) {
        return false;
    }

    var $option = $('<option></option>').text($city).attr({'selected': true, 'rel': $rel});

    $('#asmSelect0').append($option).change();
    $('#asmSelect0 option[rel=' + $rel + ']:first').remove();

    return false;
});

I had to do something I don't really like, but I couldn't find any other way of doing this without conflicting with the plugin. Anyway, it's not that bad. Basically I get the name of the neighborhood, the rel to identify the option, generate a new <option>, change(); it, and delete the old option tag. The plugin didn't like trying to change the tag itself without creating a new one... I had to add the if (...) thing because when adding a neighborhood (disabling it on the select), and clicking again on the same neighborhood, it enabled it on the select (And we don't want that, since it's already selected). With that condition, if we click on a link whose neighborhood is disabled, we'll do nothing and the option will remain the same.
Sorry if my explanation sucks, It took me a while to get the problem, I had to build everything up again, and I felt like having a lack of english xD Hope it works!


Q: IFilterProvider Injection without a Service Locator My goal: To inject an IFilterProvider in the case where one is provided by DI, but to fallback to the global FilterProviders.Providers.GetFilters() method by default.
There are a lot of resources on the Internet (including an "official" Microsoft one) that demonstrate how to inject the IFilterProvider interface into a class. However, all of them use the service locator anti-pattern (per Mark Seeman) to do so. Here is a list of the ones I found:

*

*http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvcdependencyinjection_topic4.aspx

*http://merbla.blogspot.com/2011/02/ifilterprovider-using-autofac-for-mvc-3.html

*http://thecodinghumanist.com/blog/archives/2011/1/27/structuremap-action-filters-and-dependency-injection-in-asp-net-mvc-3

*IFilterProvider and separation of concerns
So what's wrong with these methods? They all inject a DI container into the target class instead of the other way around. If you see something in your class like container.Resolve(), then you are not yielding control of the lifetime of objects to the DI container, which is what inversion of control is really about.
In addition, the problem with trying to create a fallback to the global FilterProviders.Providers instance is that although it has the same signature as the IFilterProvider interface, it does not actually implement this interface. So how can the global static member be injected as a logical default and still allow the use of DI to override it?

A: Create an wrapper class based on IFilterProvider that returns the global FilterProviders.Providers.GetFilters() result, like this:
public class FilterProvider
    : IFilterProvider
{
    #region IFilterProvider Members

    public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        return FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor);
    }

    #endregion
}

Then, adjust the constructor in your classes that require the dependency.
public class MyBusinessClass
    : IMyBusinessClass
{
    public MyBusinessClass(
        IFilterProvider filterProvider
        )
    {
        if (filterProvider == null)
            throw new ArgumentNullException("filterProvider");
        this.filterProvider = filterProvider;
    }
    protected readonly IFilterProvider filterProvider;

    public IEnumerable<AuthorizeAttribute> GetAuthorizeAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        var filters = filterProvider.GetFilters(controllerContext, actionDescriptor);

        return filters
                .Where(f => typeof(AuthorizeAttribute).IsAssignableFrom(f.Instance.GetType()))
                .Select(f => f.Instance as AuthorizeAttribute);
    }
}

Next, configure your DI container to use FilterProvider concrete type as the default.
container.Configure(x => x
    .For<IFilterProvider>()
    .Use<FilterProvider>()
);

If you need to override the default and provide your own IFilterProvider, now it is just a matter of creating a new concrete type based on IFilterProvider and swapping what is registered in the DI container.
//container.Configure(x => x
//    .For<IFilterProvider>()
//    .Use<FilterProvider>()
//);

container.Configure(x => x
    .For<IFilterProvider>()
    .Use<NewFilterProvider>()
);

Most importantly, there is no service locator anywhere in this pattern.


Q: How to read checkbox value in Angular I am trying to get the value of checkbox - i.e true or false. But this is only returning me Object Object.
<mat-cell *matCellDef="let row">
   <mat-checkbox [checked]="row.isDisabled" (change)="UpdateValue($event,row)">
   </mat-checkbox>
</mat-cell>

In my TS, I have this:
UpdateValue(event:any, myStock: stock) {
  alert(event);
  ...
}

Does anyone know how I can get the value as true or false?

A: Simply use:
UpdateValue(event:any,myStock: stock) {
   // ...
   console.log(event.checked);
}

Here's a working stackblitz for the same.

A: Just use ngModel
<mat-cell *matCellDef="let row"> <mat-checkbox
   [checked]="row.isDisabled"
   [(ngmModel)]="checkValue"
   (change)="UpdateValue($event,row)"></mat-checkbox> </mat-
    cell>

UpdateValue(event:any,myStock: stock) {
     alert(this.checkValue);
 }


Q: Is it possible to parse a remote file with ajax/javascript prototype I want to solve this puzzle but the file resides on remote server. How can I parse this file because I keep getting this error.
XMLHttpRequest cannot load http://www.weebly.com/weebly/publicBackend.php. Origin http://mysite.com is not allowed by Access-Control-Allow-Origin.
Refused to get unsafe header "X-JSON"
Code Below
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Untitled Document</title>
        <script type="text/javascript" src="prototype.js"></script>
        <!-- Puzzle starts here -->
<script type='text/javascript'>

  // Note: there may be some unfinished code here, that needs finishing...

  // You should probably try to get this function working...
  function solvePuzzle() {

        new Ajax.Request('http://www.weebly.com/weebly/publicBackend.php', {
          parameters:{
            pos: 'solvepuzzle'
          },
          onSuccess:handlerSolvePuzzle,
          onFailure:function() { alert('Transmission error. Please try again.'); }
        });

  }

  function handlerSolvePuzzle(t) {

        var responseText = t.responseText;
        responseText = responseText.replace(/\n/, "");

        if (responseText.match(/!!$/)) {

          alert("Oops: "+responseText);

        } else {

          // Still need to decode the response

          // Once the response is decoded, we can fire off the alert
          // giving the user further instructions
          //alert(responseText);
          //alert('To complete the challenge, '+t.responseText);

        }

  }

</script>
    </head>
    <body>

<input type="button" onclick="solvePuzzle()" value="hello"/>
    </body>
</html>

A: Chrome and Firefox's developer tools allow you to modify JS on the fly.
If you're on Chrome, open up the console by going to the menu View->Developer->JavaScript Console. Copy the js from the page source. Alter it. Then paste altered javascript function(s) into the console. Hit enter. Then start typing 'solvePuzzle();' Hit enter. You'll see the response come back.
For Firefox, you'll need to download Firebug plugin.

A: You cannot do this from JavaScript due to the same origin policy: https://developer.mozilla.org/en/Same_origin_policy_for_JavaScript.  If this weebly site supports some sort of JSON API, you could use JSONP: http://en.wikipedia.org/wiki/JSONP.  Other than that, you're probably better off interacting with this site via the server side due to security restrictions on the client side.

A: Consider installing a HTTP tunnel on your "mysite.com" so that the browser does not have to access "weebly.com" directly.


Q: Updated command to start blank project with ionic2 and angular2? Trying to create blank project with ionic2 not ionic1 or ionic3 using the below command in terminal
ionic start SqliteDemo blank --type ionic2

Error comes as below:
✔ Creating directory ./SqliteDemo - done!
✖ Looking up starter - failed!
[ERROR] Unable to find starter template for blank

        If this is not a typo, please make sure it is a valid starter template
        within the starters repo: https://github.com/ionic-team/starters

what i have tried ?
ionic start SQliteDemo blank --v2

not worked
all above commands just create Folder for the given name and nothing is inside.
Actually Trying:
I need to work with sqlite storage/ with any android native api's, as first attempt i try to do a sample project based on sqlite so that i can add android platform to this project and open with Android-Studio and check whether the .db file is created and working or not using Android-Monitor. If any references for this question will be very much appreciated.


Q: Java code is running select and update query for every data I am writing a Java code in Spring JPA which can add or update a data when saveData function is called. what I am trying to do is that if data is new it gets added as a new record in the database or else it will be updated.
public void saveData(List<StudentTable> studentTableList){

    List< StudentTable > data= new ArrayList<>();

    for(StudentTable dt: studentTableList){
        if(dt.getStudentId() ==null) {
            data.add(dt);

        }else{
            studentRepository.findById(dt.getStudentId()).map(
                    student->{
                        student.setFirstName(dt.getFirstName());
                        student.setLastName(dt.getLastName ());
                        student.setPhone(dt.getPhone());
                        student.setAddress(dt.getAddress());

                        return data.add(student);
                    });
        }
        studentRepository.saveAll(data);
        data.clear();
    }
}

While this code is working fine I see performance issues as my entries grow. I see that update and select queries are run for each row of the table which is slowing down the performance.
I want to know if there is any way to run queries only for those rows which are updated or added on a single post request or to improve the performance?

A: What about 2 blocks of code for each case?
Student student = studentRepository.findById(dt.getStudentId());
if(student == null){
  Student newStudent = new Student();
  //add data
  newStudent.save();
} else {
  student.setFirstName(dt.getFirstName());
  student.setLastName(dt.getLastName ());
  student.setPhone(dt.getPhone());
  student.setAddress(dt.getAddress());
  student.update();
}

A: You can follow what @fladdimir mentioned. Or, here is my suggestion[will not provide any code, leaving up to you]:

*

*filter objects which are old ones[contains id as I can see from your code]  and news ones in two separate lists

*List all ids

*use id <--> object as keyValue in a map

*Query all the objects with idList you got using IN clause

*Now, set value as you are doing in your 2nd code block from the map, add them in a list

*merge this list with new objectList

*save them altogether with saveAll(your_merged_list)

I am not saying this is the optimized way, but at least you can reduce load on your db.


Q: How to get a list from WebApi controller using jquery ajax I have this controller that returns correct results when I call it from a browser.
public async Task<IHttpActionResult> Get(string Id)
{
    if (Id == null)
        return BadRequest();

    try
    {
        var items = await obj.GetItems(Id);
        return Ok(items.ToList());
    }
    catch (Exception e)
    {
        return Content(HttpStatusCode.BadRequest, e.Message);
    }
}

In my view, I have this jquery.
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        data: {
            Id: "5AE158",
        },
        success: function (data) {
            alert('success');
        },
        error: function (x) {
            alert("error");
        }
    });

When I trigger the function from the UI, I hit a breakpoint in the Controller and I see that it returns correct results, but in the view control flows to the error handler.
I experimented with many combinations of dataType, type and function signatures but I'm not able to get a success return value.
Any help is appreciated.

A: Thanks to all that responded for the clues that helped me solve this. I looked in the console and saw the error message "No 'Access-Control-Allow-Origin' header is present on the requested resource".
What wasn't clear in my question was that the url I was trying to reach was on a different server and I was encountering this problem.
Thanks for the help.


Q: find out the number of multiples of K among the given N numbers
You are given N numbers. Now you have Q queries. For each query you
will be given an integer K
Input Format The first line consists of number N. Next N line contains N numbers. Next line contains number of queries Q. Next Q
lines contains Integer K for each query
Output Format Output Q lines the answer for every query.
Constraints 1 <= N <= 10^5; 1 <= numbers <= 10^5; 1 <= Q <= 10^5; 1 <= K <= 10^5
Sample Input
4
5
8
10
8
1
2

Sample Output
3

My code, getting one failed test case which uses 78000 inputs:
ans = []
def countSieve(arr, n):
    MAX=max(arr)
    global ans
    ans = [0]*(MAX + 1)
    cnt = [0]*(MAX + 1)
    for i in range(n):
        cnt[arr[i]] += 1
    for i in range(1, MAX+1):
        for j in range(i, MAX+1, i):
            ans[i] += cnt[j]

def countMultiples(k):
    return(ans[k])

n=int(input())
a=[]
count=0
for i in range(n):
    j=int(input())
    a.append(j)
countSieve(a,n)
q=int(input())
k=[]
for i in range(q):
    c=int(input())
    k.append(c)
i=0
for i in k:
    print(countMultiples(i))

A: The problem is that you create an array of size MAX(a) with a the list of your n numbers. This is inefficient if MAX(a) = 10^5 for example.
You should find another way to check if a number A is multiple of number B, for example A%B == 0 (use of modulo).
Try to remove countSieve and changed countMultiples.

def countMultiples(query, numbers):
    count = 0
    for i in numbers:
        if i%query == 0:
            count += 1
    return count

n=int(input())
numbers = []
for i in range(n):
    j=int(input())
    numbers.append(j)
q=int(input())
queries = []
for i in range(q):
    c=int(input())
    queries.append(c)
for i in queries:
    print(countMultiples(i, numbers))

EDIT :
Here is an optimization. First I search for numbers divisors, for each divisor I increment a counter in a dict d, then for a query q I print d[q], which is the exact amount of multiples present in the n numbers.
The method to search divisors of a number n : I make a loop until the square root of n, then for each divisor i, I also add r = n//i.
I also use a dict divs to store divisors for each number n, in order not to re-calculate them if I already found them.
Try this (it succeeded the problem https://hack.codingblocks.com/app/dcb/938) :

import math
d = {}
divs = {}

for _ in range(int(input())):
    num = int(input())
    if num in divs:
        for e in divs[num]:
            d[e] = d.get(e, 0) + 1
    else:
        div_list = []
        for i in range(1, math.floor(math.sqrt(num)) + 1):
            if not num % i:
                div_list.append(i)
                d[i] = d.get(i, 0) + 1
            r = num // i
            if (not num % r and r != i):
                div_list.append(r)
                d[r] = d.get(r, 0) + 1
        divs[num] = div_list

for i in range(int(input())):
    q = int(input())
    print(d.get(q, 0))

A: Alternatively, you could try counting how often each number appears and then checking the counts for each multiple of k up to the largest of the N numbers.
import collections

n = int(input())
nums = [int(input()) for _ in range(n)]
counts = collections.Counter(nums)
m = max(nums)

q = int(input())
for _ in range(q):
    k = int(input())
    x = sum(counts[i] for i in range(k, m+1, k))
    print(x)

At first sign, this does not look much different than the other approaches, and I think this even still has O(N*Q) in theory, but for large values of Q this should give quite a boost.
Let's say Q = 100,000. For all K > 10 (i.e. all except 10 values for K) you will only have to check at most 10,000 multiples (since m <= 100,000). For all K > 10,000 (i.e. 90% of possible values) you only have to check at most 10 multiples, and for 50% of Ks only K itself!
I other words, unless there's an error in my logic, in the worst case of N = Q = 100,000, you only have about 1,1 million check instead of 10,000,000,000.
>>> N = Q = 100000
>>> sum(N//k for k in range(1,Q+1))
1166750

(This assumes that all K are different, but if not, you can cache the results in a dict and then will only need a single check for the duplicates, too.)

On closer inspection, this approach is in fact pretty similar to what your sieve does, just a bit more compact and computing the values for each k as needed instead of all at once.

I did some timing analysis using random inputs using gen_input(n, q, max_k). First, all the algorithms seem to produce the same results. For small-ish input sizes, there is no dramatic difference in speed (except for naive modulo), and your original sieve is indeed the fastest. For larger inputs (maximal values), yours is still the fastest (even by a larger margin), and the divisors approach is considerably slower.
>>> n, q = gen_input(10000, 1000, 1000)
>>> modulo(n, q) == mine(n, q) == sieve(n, q) == modulo(n, q)
True

>>> %timeit modulo(n, q)
1 loop, best of 3: 694 ms per loop
>>> %timeit mine(n, q)
10 loops, best of 3: 160 ms per loop
>>> %timeit sieve(n, q)
10 loops, best of 3: 112 ms per loop
>>> %timeit divisors(n, q)
1 loop, best of 3: 180 ms per loop

>>> n, q = gen_input(100000, 100000, 100000)
>>> %timeit mine(n, q)
1 loop, best of 3: 313 ms per loop
>>> %timeit sieve(n, q)
10 loops, best of 3: 131 ms per loop
>>> %timeit divisors(n, q)
1 loop, best of 3: 1.36 s per loop

Not sure why you are getting timeouts for yours and mine algorithm while @phoenixo's divisors allegedly works (did not try it, though)...


Q: Bootstrap 3 is unable to unmark the justified dropdown button group for the inactive options With Bootstrap 3.3.7, I am trying to have a justified navigation dropdown button group, to mark correctly, after selection. I am having the problem of both menu options being marked, in the dropdown button, when one after another options being selected. Are there anyways to have the dropdown menu to mark only the option being selected, while being a justified group dropdown navigation button? Thank you!
sample code

        Left
        Middle

             Dropdown

drop 1

drop 2

please select 1 of the options in the dropdown

please try the dropdown on the right

please try select drop 2 also, then both are marked under the dropdown

please try select drop 1 also, then both are marked under the dropdown

A: Instead of using button groups I'd recommend using the Nav component instead styled with the pills modifier class. It's not the same but very close and the Tab panels are built to work with the pills styling.
It will solve the problem you have now with the active class remaining on the dropdown options.

Home

Profile

      Dropdown

Messages

Settings

home

profile

messages

settings

https://codepen.io/partypete25/pen/Moooaq?editors=1100

A: I tailored @partypete25 answers, to my needs. Thanks again @partypete25!
sample code

Left

Middle

                 Dropdown

drop 1

drop 2

please select 1 of the options in the dropdown

please try the dropdown on the right

please try select drop 2 also, then both are marked under the dropdown

please try select drop 1 also, then both are marked under the dropdown


Q: Sort array by name with array key I have an array like this, how can I sort by "name"
Array (
    [0] => Array (
        [id] => 1
        [name] => status_category_confide
    )
    [1] => Array (
        [id] => 2
        [name] => status_category_love
    )
    [2] => Array (
        [id] => 3
        [name] => status_category_household
    )
    [3] => Array (
        [id] => 4
        [name] => status_category_family
    )
    [4] => Array (
        [id] => 5
        [name] => status_category_friends
    )
    [5] => Array (
        [id] => 6
        [name] => status_category_colleague
    )
    [6] => Array (
        [id] => 7
        [name] => status_category_work
    )
    [7] => Array (
        [id] => 8
        [name] => status_category_ambition
    )
)

I've tried using the "sort" function but it doesn't work
$get_status_mood=mysqli_query($con, "select id, name from category");
while ($gsm=mysqli_fetch_array($get_status_mood)) {
    //array_push($status_category, constant($gsm['name']));
    $status_category[] = array(
        "id"=>$gsm['id'],
        "name"=>$gsm['name']
    );
}

sort($status_category);
for ($i=0; $i<count($status_category); $i++) {
    echo"<option value='".$status_category[$i]['id']."'>".$status_category[$i]['name']."</option>";
}

I want to display the results in the order of the name

A: Try the SQL order by option
$get_status_mood=mysqli_query($con, "select id, name from category order by name asc");

A: You can sort it using array_column and array_multisort functions.
$keys = array_column($array, 'name');

array_multisort($keys, SORT_ASC, $array);

A: You can try it with usort this sort an array by values using a user-defined comparison function
   function cmp($a, $b)
{
  return strcmp($a["name"], $b["name"]);
}
usort($vc_array, "cmp");

A: $a = array();
$a[] = array('id' => 1, 'name' => 'status_category_confide');
$a[] = array('id' => 2, 'name' => 'status_category_love');
$a[] = array('id' => 3, 'name' => 'status_category_household');

function cmp($x, $y) {
    if (strcmp($x['name'], $y['name']) == 0) {
        return 0;
    }
    return (strcmp($x['name'], $y['name']) < 0) ? -1 : 1;
}
usort($a, "cmp");

print_r($a);


Q: updating query parameters in SQL Data Source I have following code that updates the value of query parameters of a SQL Data Source after going through some conditions.
SqlDataSource sdm = new SqlDataSource("<our connection string>", "SELECT  [Message Id] ,[To] ,[From] ,[Reply To] ,[Subject] ,[Message] ,[Date added] FROM [database].[dbo].[User Messages] where ([to]=@sid or [from]=@sid) and ([to]=@qid or [from]=@qid)  and [reply to]=@rid");

string user = Session["USERID"].ToString();
string to = Request["to"].ToString();
string from = Request["from"].ToString();
sdm.UpdateParameters["rid"].DefaultValue = Request["replyid"].ToString();
sdm.UpdateParameters["sid"].DefaultValue = user;
if (user == to)
  sdm.UpdateParameters["qid"].DefaultValue=from;
else
  sdm.UpdateParameters["qid"].DefaultValue= to;

sdm.Update();
sdm.DataBind();
Repeater1.DataSource = sdm;
Repeater1.DataBind();

Its showing NullReferenceException at sdm.UpdateParameters["rid"].DefaultValue = Request["replyid"].ToString();
rid is already set in query string as ?rid=a

A: You'll want to use the Request.QueryString collection to get your rid parameter out:
sdm.UpdateParameters["rid"].DefaultValue = Request.QueryString["rid"];

Using an indexer with Request will get you values out of the QueryString, Form, Cookies or ServerVariables collections, using Request.QueryString directly makes your intentions that little bit clearer.

A: Shouldn't the query string be ?replyid=a instead of ?rid=a?.
It seems that Request["replyid"] returns null, and then ToString() throws the exception.


Q: How to display Date to Ext Js Column with Json response stackoverflow forum member I need some help from you.
I am getting the server response for the startDate in json format as
"startDate":1328466599000
I want to display it to my ExtJs column. But I am not able to display it.
My column in which i am displaying StartDate is
[Ext.Date.format(values.StartDate, "c")]
and my TaskModel is
Ext.define("TaskModel", {
        extend : "Gnt.model.Task",

        // Some custom field definitions
        fields : [
            { name: 'Id', type: 'int', useNull : true, mapping: 'id'},
            { name: 'StartDate', type: 'date', mapping: 'startDate'},
            { name: 'EndDate', type: 'date', mapping: 'endDate', dateFormat: 'MS'},
            { name: 'Priority', defaultValue : 1, mapping: 'priority', dateFormat: 'MS' },
            { name: 'Duration', mapping: 'duration'},
             { name: 'PercentDone', mapping: 'percentDone'},
             { name: 'DurationUnit', mapping: 'durationUnit'},
             { name: 'parentId', mapping: 'parentId', type: 'int'},
             { name: 'Name', mapping: 'taskName'},
             { name: 'index', mapping: 'taskindex'},
             { name: 'depth', mapping: 'depth'},
        ]
    });

I am not able to view my startDate I am receiving as response to my Column.
Does anyone have any idea as to what is causing this error? If anyone has a solution to this problem please help me.

A: Could it be that you have defined the dateformat on the priority column, not startdate column?

A: I did a blog post here: http://peterkellner.net/2011/08/24/getting-extjs-4-date-format-to-behave-properly-in-grid-panel-with-asp-net-mvc3/
sorry for digging up something from a while back but I was just searching for the same thing and ran into my blog post first (before this item)


Q: jQuery two column (one dimensional) array? I have a simple one dimensional array but I want to split the long list into two columns using jQuery. How can I achieve this?
var articles = ['article10','article9','article8','article7','article6','article5','article4','article3', 'article2', 'article1'];
for ( var articCounter = articles.length; articCounter > 0; articCounter--) {
    document.write(' ' + articles[articCounter-1] + '
');
} // end for

I don't want to have to create two different arrays for two different float divs....
I've googled this many times but many other methods deal with multidimensional arrays.
Thank you very much for the help in advance.
EDIT: Right now it's just one long list like so:
Article1
Article2
Article3
....
But I would like to achieve this:

A: This will split your array into 2 arrays:
var articles = ["article1", "article2", "article3", "article4", "article5", "article6", "article7", "article8", "article9", "article10"];
var separatorIndex = articles.length & 0x1 ? (articles.length+1)/2 : articles.length/2;

var firstChunk = articles.slice(0,separatorIndex);
//["article1", "article2", "article3", "article4", "article5"]
var secondChunk = articles.slice(separatorIndex,articles.length);
//["article6", "article7", "article8", "article9", "article10"]

Then you can use them where and/or how you want.
Explanation
The 2nd line finds an anchor index (alias -> middle index of division),by which array should be divided into 2 chunks. The array can have odd and even lengths,and those 2 situations must be distinguished. As it is impossible to divide odd-length array into 2 equal parts, it must be divided in such way, that 1st chunk will have 1 element more or less,than 2nd chunk.Here, I have implemented first case,that is, 1st chunk will have 1 element more,than 2nd one. Here are the examples of different situations:
total length | 1st (length) | 2st (length) | separatorIndex
    10            0-4 (5)        5-9 (5)          5
    11            0-5 (6)       6-10 (5)          6
    12            0-5 (6)       0-11 (6)          6

In table, number-number syntax shows accordingly start and end indexes in array. The division is done by .slice() function.


Q: Delete unpersisted record I wonder what's the procedure to delete a non persisted record.
I have a domain that has many redirections
I start to create a redirection with
domain = @modelFor('domain')
redirection = @store.createRecord('redirection')
domain.get('redirections').pushObject(redirection)

is this correct ? And how to delete the redirection object if my user click on cancel button ?
I've tried this but that does not work.
redirection = @get('model')
redirection.rollback()
redirection.unloadRecord()

I'm using ember and ember-data both in canary version.
Thanks.

A: You should be able to do
redirection = @get('model')
@store.deleteRecord(redirection)


Q: IPython change input cell syntax highlighting logic for entire session You can use extensions or display helpers in IPython to make whatever syntax highlighting you'd like on output cells.
For some special cell magics, like %%javascript you can also see the input cell itself is rendered with that language's natural syntax highlighting.
How can you cause every input cell to be displayed with some chosen, non-Python syntax highlighting (regardless of any magics used on a cell, regardless of whether the cell embodies Python code, some other language).
In my case I am working with a custom-made cell magic for a proprietary language. The %%javascript syntax highlighting works well for this language, but if I have my own %%proprietarylang magic function, I obviously can't use %%javascript to help me with how the cell is displayed.
Is there a setting I can enable when I launch the notebook, or some property of the ipython object itself that can be programmatically set inside of my magic function, which will cause the same display logic to happen as if it was %%javascript.
I know that general-purpose on-the-fly syntax highlighting is not supported by the notebook currently. I'm asking specifically about how to make use of pre-existing syntax highlighting effects, such as that of %%javascript.
I've seen some documentation referring to IPython.config.cell_magic_highlight but this does not seem to exist anymore. Is there a standard replacement for it?

A: To replace IPython.config.cell_magic_highlight, you can use something like
import IPython
js = "IPython.CodeCell.config_defaults.highlight_modes['magic_fortran'] = {'reg':[/^%%fortran/]};"
IPython.core.display.display_javascript(js, raw=True)

so cells which begin with %%fortran will be syntax-highlighted like FORTRAN. (However, they will still be evaluated as python if you do only this.)

A: For recent IPython version, the selected answer no longer works. The 'config_default' property was renamed options_default (Ipython 6.0.0).
The following works:
import IPython
js = "IPython.CodeCell.options_default.highlight_modes['magic_fortran'] = {'reg':[/^%%fortran/]};"
IPython.core.display.display_javascript(js, raw=True)


Q: How to output vertical bar format in textfile I am trying to save my contents in the textfile in this format
|Name|Description|

|QY|Hello|

But for now mine is returning me as this output:
|2014 1Q    2014 2Q 2014 3Q 2014 4Q|

|96,368.3   96,808.3    97,382  99,530.5|

Code:
def write_to_txt(header,data):
    with open('test.txt','a+') as f:
        f.write("|{}|\n".format('\t'.join(str(field)
                          for field in header))) # write header
        f.write("|{}|\n".format('\t'.join(str(field)
                          for field in data))) # write items

Any idea how to change my code so that I would have the ideal output?

A: This is happenning because you are joining the fields inside data iterable using \t , use | in the join as well for your requirement. Example -
def write_to_txt(header,data):
    with open('test.txt','a+') as f:
        f.write("|{}|\n".format('|'.join(str(field)
                          for field in header))) # write header
        f.write("|{}|\n".format('|'.join(str(field)
                          for field in data)))


Q: Why does adding a new element to an array list replace all the previous elements with the new one? I have a method in my class TextPlan, which calls all my rules in another class RSTRule and adds all rules to an array list. For this method I have used import java.lang.reflect.InvocationTargetException andimport java.lang.reflect.Method.
But it adds to the array list incorrectly. For example, the result ofadd(RSTRule)` in each call of RST methods are as follows:
 call 1: RSTRules.add(RSTRule)=R1
 call 2: RSTRules.add(RSTRule)=R2,R2
 call 3: RSTRules.add(RSTRule)=R3,R3,R3
 call 4: RSTRules.add(RSTRule)=R4,R4,R4

That means that every time I add a new element, it removes the previous elements from the array list, but repeats the new element.
Here is my code:
public class TextPlan extends ArrayList<Object>  {

  RSTRules rstRules=new RSTRules();

  public RSTRules produceAllRSTRules(RSTRules rstRules) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    RSTRule rstRule=new RSTRule();
        Method[] methods =rstRule.getClass().getMethods();
        for (Method method : methods) {
             if (method.getName().startsWith("generate")) {
            rstRule=(RSTRule)method.invoke(rstRule);
            rstRules.add(rstRule) ;
               }
         }
          return rstRules;
   }
}

hier one of my methodes in "RSTRule", which i call all of them in "TextPlan" to produce an instance of all Rules;
public class RSTRule{
    protected String ruleName;
    protected DiscourseRelation discourseRelation;
    protected String ruleNucleus;
    protected String ruleSatellite;
    protected String condition;
    int heuristic;

    public RSTRule generateBothAppearBothCosts_Join(){
            this.discourseRelation=DiscourseRelation.Join;
            this.ruleNucleus="BothProductAppear_Elaboration";
            this.ruleSatellite="BothProductCost_Elaboration";
            this.ruleName="BothProductAppearAndBothProductCost_Join";
            this.condition=null;
            this.heuristic=9;
            return this;
        }
}

A: You're not adding four new RSTRule instances to the list, you're adding the same RSTRule instance four times and modifying it each time through. Since it's the same instance stored four times, the modifications show up in every position of the list.


Q: chosen-select not working bootstrap 3 modal? I cannot fix a chosen-select from a modal which i am following here http://jsfiddle.net/koenpunt/W6dZV/,  I cannot apply it  to my code, please see this image
I have a chosen select on its page, but not on modal, I want to apply it on my modal,
this is my code on button:

Bootstrap starter template

Use this document as a way to quickly start any new project.
 All you get is this text and a mostly barebones HTML document.

  Launch demo modal

anyway, I am still applying the codes on the fiddle to mide.
the modal:

          ×
          Modal title

        United States
        United Kingdom
        Afghanistan
        Aland Islands
        Albania
        Algeria
        American Samoa
        Andorra
        Angola
        ....

          Close
          Save changes

and for the script.

As you can see, I have chosen select at the background, but i cannot apply it on modal.


Q: Getting an error on my do while loop in the doAgain method Getting an error on my do while loop in my doAgain method. Not sure why. Trying to use another Boolean method to check for mistakes in the user input :
import java.util.Scanner;
import java.util.Random;

public class Lottery {
    public static void main(String[] args) {
        do {
            int digits = getDigits();
            System.out.println(createNumber(digits));
        } while (doAgain() != false);
    }

    public static int getDigits() {
        Scanner kb = new Scanner(System.in);
        System.out.println("How many digits do you want the num to be?");
        int digits = kb.nextInt();
        return digits;
    }

    public static String createNumber(int digits) {
        Random r = new Random();
        StringBuilder sb = new StringBuilder(digits);
        for (int i = 0; i < digits; i++)
            sb.append((char) ('0' + r.nextInt(10)));
        return sb.toString();
    }

    public static boolean doAgain() {
        do {
            Scanner kb = new Scanner(System.in);
            String answer;
            System.out.println("Do you want to do this again? Enter yes to continue or no to quit");
            answer = kb.nextLine();
            if (answer.equals("yes"))
                return true;
            else
                return false;
        } while (incorrect(answer) != false);
    }

    public static boolean incorrect(String answer) {
        if (!answer.equals("yes") || !answer.equals("no"))
            return true;
        else
            return false;
    }
}

A: You should declare String answer=""; inside doAgain function. Otherwise you will get cannot find symbol error in this line
while (incorrect(answer) != false);

Modify doAgain function to this
 public static boolean doAgain() {
        String answer="";
        do {
            Scanner kb = new Scanner(System.in);
//            String answer;  // remove this
            System.out.println("Do you want to do this again? Enter yes to continue or no to quit");
            answer = kb.nextLine();
            if (answer.equals("yes")) {
                return true;
            } else {
                return false;
            }
        } while (incorrect(answer) != false);
    }

A: Here a some mistakes you made:

*

*!answer.equals("yes") || !answer.equals("no") always returns true.

*answer in } while (incorrect(answer) != false); is out of scope. You need to declare String answer = ""; before the do-while loop.

*The loop never repeats, because of you if else which always returns in the loop.
The fixed code can be:
public static boolean doAgain() {
    Scanner kb = new Scanner(System.in);
    String answer = "";
    do {
        System.out.println("Do you want to do this again? Enter yes to continue or no to quit");
        answer = kb.nextLine();
    } while (incorrect(answer)); // Better not use double negative

    if (answer.equals("yes"))
        return true;
    else
       return false;
}

public static boolean incorrect(String answer) {
    if (answer.equals("yes") || answer.equals("no"))
        return false; // answer is correct
    else
        return true; // answer is incorrect
}


Q: What is 1.1.1.1? Why does it work for traceoute but not ping? Today while trying out with networks I took traceroute of 1.1.1.1 and found my gateway address. Whereas I pinged 1.1.1.1 it results with packet loss.  I googled about 1.1.1.1 and can't find any relevant results.
The following were my questions:
What is 1.1.1.1? As per my understanding, Default Gateway is used when the host doesn't have any route information for a particular packet. So it will ask the default gateway. Since while tracerouteing is it my default gateway?
i tried to send ack packets using nmap and the result was :

Why does 1.1.1.1 respond to traceroute but not respond to ping?

A: What is 1.1.1.1?
1.1.1.1 is a public, assigned IP address; which is why you can traceroute to it. It was assigned to APNIC in 2010 (with the rest of the 1.0.0.0/8 block), and pretty useless as many folks treat it as a placeholder.
See Shane Madden's answer over at Server Fault for more info, including the article about traffic linked there.

A: 1.1.1.1 is used as the default address of the DHCP server on CISCO routers.
However, on the public internet, 1.1.1.1 now belongs to Cloudflare DNS service.
Whois record:
inetnum:        1.1.1.0 - 1.1.1.255
netname:        APNIC-LABS
descr:          APNIC and Cloudflare DNS Resolver project
descr:          Routed globally by AS13335/Cloudflare
descr:          Research prefix for APNIC Labs
country:        AU
org:            ORG-ARAD1-AP
admin-c:        AR302-AP
tech-c:         AR302-AP
mnt-by:         APNIC-HM
mnt-routes:     MAINT-AU-APNIC-GM85-AP
mnt-irt:        IRT-APNICRANDNET-AU
status:         ASSIGNED PORTABLE
remarks:        ---------------
remarks:        All Cloudflare abuse reporting can be done via
remarks:        resolver-abuse@cloudflare.com
remarks:        ---------------
last-modified:  2018-03-30T01:51:28Z
source:         APNIC

A: As stated by Daniel B in his answer, the 1.1.1.1 address is currently assigned to APNIC labs (as it was when the question has been asked). However, until January 2010, the 1.0.0.0/8 network block, of which 1.1.1.1 is part, was unassigned and therefore (ab)used for local use in several cases.
Although the network block has been now assigned to APNIC (and addresses starting with 1. are now definitely in use), several old pieces of equipment persist in using 1.1.1.1 for local purposes, and perhaps in consequence of this, a small block of 256 IP addresses (1.1.1.0 to 1.1.1.255) has been reserved for research purposes by APNIC labs.
No route for the 1.1.1.0/24 prefix containing 1.1.1.1 has ever been announced on BGP (see https://stat.ripe.net/1.1.1.1#tabId=at-a-glance for details, in particular 1.1.1.1 was never globally visible as exact match in BGP by any of the RIS peers since beginning of 2004. No less-specific covering prefixes.), which means that the address has never been used for a publicly-facing service. This of course does not mean that this will never happen.
The fact that you can have a traceroute to 1.1.1.1 that responds with the gateway address can come from two sources:

*

*The gateway figures out that the address can't be routed because there is no route announcement for it, and therefore answers with an ICMP "unreachable" message -- however your traceroute should in this case display a specific marking (e.g. !H). I would say that this explanation is not very probable, because your gatweay will probably only forward packets to the next router.

*The 1.1.1.1 address is still used locally by some equipment (see below).

Among unofficial uses of the 1.1.1.1 address, or of an address block containing it:

*

*Some equipment from several manufacturers (including Cisco and ZyXel) is still using the 1.1.1.1 address for local purposes (for example, login portals for public WiFi connections, local management networks, etc.). You can perhaps see what the equipment is by going to https://1.1.1.1/ with your browser. Also check the address of your DHCP or DNS server to see if one of those is 1.1.1.1.

*Fastweb, an Italian ISP (but probably other providers too), was in the past assigning IPs in the 1.0.0.0/8 network to their customers, but since that network range became public, they switched to a more classic private IP range (10.0.0.0/8).

UPDATE (April 11th 2018) — As per Bob's comment to another message, there is now a public DNS service on 1.1.1.1. See also https://1.1.1.1/ for more information about what this is. So this address is now definitely off-limits for private use! (as it should always have been).
$ ping 1.1.1.1
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
64 bytes from 1.1.1.1: icmp_req=1 ttl=57 time=4.67 ms
64 bytes from 1.1.1.1: icmp_req=2 ttl=57 time=4.20 ms
64 bytes from 1.1.1.1: icmp_req=3 ttl=57 time=4.19 ms
64 bytes from 1.1.1.1: icmp_req=4 ttl=57 time=4.17 ms
^C
--- 1.1.1.1 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3030ms
rtt min/avg/max/mdev = 4.179/4.313/4.677/0.210 ms

A: 1.1.1.1 is contained in APNIC-LABS (1.1.1.0/24), a research network of APNIC Labs. It is reachable (with ping and the like) only when a test is performed. That doesn’t mean, however, that there’s no route to it. It’s a regular IP address, after all.
Traceroute is very different from ping. Only in the last step will it actually contact the destination (1.1.1.1 in your case).

Traceroute, by default, sends a sequence of User Datagram Protocol (UDP) packets addressed to a destination host; ICMP Echo Request or TCP SYN packets can also be used. The time-to-live (TTL) value, also known as hop limit, is used in determining the intermediate routers being traversed towards the destination. Routers decrement TTL values of packets by one when routing and discard packets whose TTL value has reached zero, returning the ICMP error message ICMP Time Exceeded.

I don’t exactly understand your default gateway trouble, though. Any IP traffic leaving a host is directed at the next hop as indicated by the routing table. If there’s a fallback entry, the so-called default gateway, traffic not matching any other rule is directed there.
@bertieb Raises a good point, though: Some ISP-side data compression proxies also use this address illegally.

A: As of 2019, 1.1.1.1 is a public DNS-Resolver, which according to its provider, Cloudflaire, is:

a fast and private way to browse the Internet. It is a public DNS resolver, but unlike most DNS resolvers, 1.1.1.1 is not
  selling user data to advertisers. The implementation of 1.1.1.1 makes
  it the fastest resolver out there.

The result for nmap -sA 1.1.1.1 is as follows:
Starting Nmap 7.60 ( https://nmap.org ) at 2019-05-08 12:13 CEST
Nmap scan report for one.one.one.one (1.1.1.1)
Host is up (0.054s latency).
Not shown: 997 filtered ports
PORT    STATE      SERVICE
53/tcp  unfiltered domain
80/tcp  unfiltered http
443/tcp unfiltered https


Q: Validation of IP address in Scala I want to validate the IP address in scala. I have implemented the method but I am seeing some errors.
Can anyone look into it and suggest if they have better solution. I am not trying to implement functionally.
 def validIPAddress(IP: String): String = {

       var isValidIP = true
       if(IP.contains(":")) {
            var numbers= IP.split(":")   //create an array
            if (numbers.length!=8) return "Neither"
            for (n <- numbers) {
                if(n.length = 0 or n.length > 4) return "Neither"
                else {
                    for (m <- n) {
                        if(!m in "0123456789abcdefABCDEF") return "Neither"
                    }
                }
            }
            return "IPv6"
       }
       else if(IP.contains(".") {     //192.168.1.1
              nums = IP.split(".")
              if(nums.length!=4) isValidIP = false  //Array.length
              else {
                for (a <- nums) {
                  println(a)
                  try {
                    var intA = a.toInt
                    if(intA <=0 || IntA > 255) {
                      isValid = false
                    }

                  } catch (NumberFormatException e)  {
                    case e: Exception => None
                  }
                }

                if(isValid == true) {
                  println("Valid IP")
                } else {
                  println("Invalid IP")
                }

              }
       } return "IPv4"

       else {
         return "neither"
       }

       }

A: You might not intend to implement funcationaly but there is no need for imperative code in your example at all and returns and vars cause some serious issues when it comes to reading the intend of the code.
I would rewrite the code to something like this
sealed trait IP extends Product with Serializable
object IP {
  final case class V4(a: Int, b: Int, c: Int, d: Int) extends IP
  final case class V6(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int, g: Int, h: Int) extends IP
}

val ipV4 = """(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})""".r
val ipV6 = """([0-9a-fA-F]+):""".r

def validIPAddress(ip: String): Either[String, IP] = {
  def parseV4(s: String) = {
    val i = Integer.parseInt(s)
    if (0 <= i && i <= 255) Right(i) else Left(s"$i is not a valid IPv4 number")
  }
  def parseV6(s: String) = Integer.parseInt(s, 16)

  ip match {
    case ipV4(a, b, c, d) =>
      for {
        a1 <- parseV4(a)
        b1 <- parseV4(b)
        c1 <- parseV4(c)
        d1 <- parseV4(d)
      } yield IP.V4(a1, b1, c1, d1)
    case ipV6(a, b, c, d, e, f, g, h) =>
      // technically speaking this isn't exhausting all possible IPv6 addresses...
      // as this regexp would ignore e.g. ::1 or ::
      Right(IP.V6(parseV6(a), parseV6(b), parseV6(c), parseV6(d), parseV6(e), parseV6(f), parseV6(g), parseV6(h)))
    case _ =>
      Left(s"$ip is neither V4 nor V6 format")
  }
}

to make it easier to follow and debug errors, though as I checked this implementation is NOT really conforming to what IPv6 does, as some tuning around regexp usage would be necessary. As a matter of the fact, I would prefer to avoid rolling my own solution altogether if I couldn't afford some time for writing down like 15-20 test cases.
So, unless there is a reason to implement your own validator I would delegate that task to some library which already tested handling corner cases.
If you have to, however, do the following things:

*

*don't use return - in Scala it does something different than what you think it does

*don't use vars unless you're optimizing - the way you use them have nothing to do with optimization (isValid is never used, so why override it? and other vars are never modified)

*don't use string for everything because that is asking for trouble on its own (e.g. "neither" and "Neither" - should the caller use .equalsIgnoreCase on your code to check results?)

*start with tests written basing on specification. While I translated your code it fails valid IPv6 addresses. If I skipped the requirement that Iv6 is fixed size, it  would be even shorter to:

sealed trait IP extends Product with Serializable
object IP {
  final case class V4(a: Int, b: Int, c: Int, d: Int) extends IP
  final case class V6(values: List[Int]) extends IP
}

val ipV4 = """(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})""".r
val ipV6 = """([0-9a-fA-F]*)((:[0-9a-fA-F]*){2,})""".r

def validIPAddress(ip: String): Either[String, IP] = {
  def parseV4(s: String) = {
    val i = Integer.parseInt(s)
    if (0 <= i && i <= 255) Right(i) else Left(s"$i is not a valid IPv4 number")
  }
  def parseV6(s: String) = if (s.isEmpty) 0 else Integer.parseInt(s, 16)

  ip match {
    case ipV4(a, b, c, d) =>
      for {
        a1 <- parseV4(a)
        b1 <- parseV4(b)
        c1 <- parseV4(c)
        d1 <- parseV4(d)
      } yield IP.V4(a1, b1, c1, d1)
    case ipV6(head, tail, _) =>
      val segments = head +: tail.substring(1).split(':')
      Right(IP.V6(segments.map(parseV6).toList))
    case _ =>
      Left(s"$ip is neither V4 nor V6 format")
  }
}

which handled more correct cases but is still far from ready. So if you can - avoid doing it yourself and use a library.


Q: How to upload video file on parse in android? I am trying to upload video file on parse. For uploading the video I am using following code:
    File inputFile = new File(uri.toString());
    FileInputStream fis = new FileInputStream(inputFile);
    ByteArrayOutputStream bos= new ByteArrayOutputStream();
    byte[] buf = new byte[(int)inputFile.length()];

        for (int readNum; (readNum=fis.read(buf)) != -1;){
            bos.write(buf,0,readNum);
        }
        byte[] bytes = bos.toByteArray();
    ParseFile file = new ParseFile("testVideo1.mp4", bytes);
    ParseObject parseObject = new ParseObject("chat1");
    parseObject.saveInBackground();

But inputfile the File object not converted to FileInputStream.

A: thanks for the this, helped me get started with uploading a video to parse, I figure out your issue, you just didn't put the parse file in your parseobject. basically you never sent the video
File inputFile = new File(uri.toString());
FileInputStream fis = new FileInputStream(inputFile);
ByteArrayOutputStream bos= new ByteArrayOutputStream();
byte[] buf = new byte[(int)inputFile.length()];

    for (int readNum; (readNum=fis.read(buf)) != -1;){
        bos.write(buf,0,readNum);
    }
    byte[] bytes = bos.toByteArray();
ParseFile file = new ParseFile("testVideo1.mp4", bytes);
ParseObject parseObject = new ParseObject("chat1");
//addition
parseObject.put("video",file);
//it should work with this
parseObject.saveInBackground();


Q: How to use string keys in (fluent) NHibernate I am working with brownfield database that uses strings as primary keys.
Using Fluent NHibernate with Sqlite (in-memory provider for unit testing) and SQL Server 2005.
I have the following entity:
public class Entity
{
    public virtual DateTime TimeStamp { get; set; }

    public virtual string Name { get; set; }
}

With this mapping:
public class EntityMap : ClassMap<Entity>
{
    public EntityMap()
    {
        Map(_ => _.TimeStamp);
        Id(_ => _.Name).CustomType("AnsiString");
    }
}

However it does not work saying NHibernate.TypeMismatchException : Provided id of the wrong type. Expected: System.Int32, got System.String
How make this work? Also, is there any good documentation about fluent nhibernate available?
Thanks in advance.

A: If you are using strings as your primary keys you'll probably have to do something like this:
public class EntityMap : ClassMap<Entity>
{
    public EntityMap()
    {
        Id(x => x.Name).GeneratedBy.Assigned();
        Map(x => x.TimeStamp);
    }
}

From the nhibernate documentation:

5.1.4.7. Assigned Identifiers
If you want the application to assign identifiers (as opposed to
  having NHibernate generate them), you may use the assigned generator.
  This special generator will use the identifier value already assigned
  to the object's identifier property. Be very careful when using this
  feature to assign keys with business meaning (almost always a terrible
  design decision).
Due to its inherent nature, entities that use this generator cannot be
  saved via the ISession's SaveOrUpdate() method. Instead you have to
  explicitly specify to NHibernate if the object should be saved or
  updated by calling either the Save() or Update() method of the
  ISession.

Also here is a related article. It is a bit dated but still applies to your situation:
http://groups.google.com/group/fluent-nhibernate/browse_thread/thread/6c9620b7c5bb7ca8


Q: Adding custom function to handle additional column/ data while resampleBarFeed in PyAlgoTrade I am resampling custom columns with pyalogtrade.
Say I have an extra column called EX other than the default columns (open, close, high, low, etc). This is initialized and passed around in the bar.BasicBar() function as {'extraCol1' : 1.09 }.
By default, when the data is resampled, the EX is 0 in the resampled data. How/ where do we change, or override this default behaviour of pyalogtrade.
Example:
Say if we have three 1-minute OHLCV EX bars as follows (toy example)
       Cols: [O H L C V EX]
1-min bar#1: [1 1 1 1 1 1]
1-min bar#2: [2 2 2 2 2 2]
1-min bar#3: [3 3 3 3 3 3]

While resampling it for 3-minute, we get a bar like this:
       Cols: [O H L C V EX]
3-min bar#1: [1 3 1 3 3 *0*]

Suppose we want custom handling of the EX column, say:
resampled EX = 3rd minute - 1st minute = 3 - 2 = 1 (instead of the 0)
How does one achieve that?


Q: Hide parent div if :empty Trying to hide a parent div if a sibling is empty when document is ready. Doesn't seem to work for me:

$('.pp-post-content-location:empty').parent().hide();

  Location

A: First of All You Haven't included Document .ready in your Script
Here's The Code Try this
$(document).ready(function(){
var text=$('.pp-post-content-location').text(); //text Is Jquery Function which gets the content inside a element

if(text==""){
$('.pp-post-content-location').parent().hide();
}
});

Then Just a Simple If Condition to check That is there any Content In Specified Element If it has not Any content then it will hide the PARENT element


Q: CSS Selector for last-of-type/last-child but different parents? Would like to access item 6 only through css

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

A: EDIT
I think that it is duplicate. Select :last-child with especific class name (with only css)
So you need which div you want to point. In this case, this is second div so we specified:
div:nth-child(2)

And then we just select last li as below:
li:last-child

So finaly we got:
div:nth-child(2) li:last-child{
  background-color: red;
}

EDIT
With jQuery:
$('li').last().css('background', 'red');

Just to let you know, your html structure is incorrect as you should set li right after ul or ol

$('li').last().css('background', 'red');

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6


Q: ST_AsRaster, draw polygon in a corner I want to draw a simple polygon in a corner (i.e. not in a center) of the raster.
The following draws a shape across the whole PNG, but I imagined the line will be off the center, near the (200, 200) corner.
select st_aspng(
    ST_AsRaster(
        ST_Buffer(
            ST_GeomFromText('LINESTRING(150 200,200 200)'), 10),
        200,200,
        ARRAY['8BUI', '8BUI', '8BUI'], ARRAY[0,100,0], ARRAY[0,0,0]
        )
   );

The result is:

What did I miss?


Q: jsp failed to embed applet from jar, class-file not found I try to embed an applet into my Applet.jsp via jsp:plugin.
When I call the jsp through tomcat, the applet throws a "ClassNotFoundException".
So far I figured out, that the jar-file could be found and even downloaded, when I entered the classpath into url. In my tomcat-logs I see, that the test.jar is found, but not the MyClass.class in it.
My project-structure:
webapp
- applets
  - test.jar
- WEB-INF
  - templates
    - Applet.jsp
  - web.xml

The jar file only contains MyClass.class.
Applet.jsp
<jsp:plugin type="applet" /webapp/applets/test.jar" code="MyClass.class" width="300" height="300"></jsp:plugin>

Tomcat log
"POST /webapp/servlet/applet HTTP/1.1" 200
"GET /webapp/applets/test.jar/MyClass.class HTTP/1.1" 404

I also tried
Applet.jsp
<jsp:plugin type="applet" archive="/webapp/applets/test.jar" code="MyClass" width="300" height="300"></jsp:plugin>

and several variations, but no luck.
Tomcat log
"POST /webapp/servlet/applet HTTP/1.1" 200
"GET /webapp/applets/test.jar HTTP/1.1" 200
"GET /webapp/servlet/MyClass.class HTTP/1.1" 404

Versions are java 1.7, tomcat 7
Why isn't MyClass.class found in the test.jar?
EDIT
I figured out, that is has to do with the jsp or so.
My html with embeded applet-jar works, the jsp still fails.
html
<html>
<head>
  <title>Time</title>
</head>
<body>
  <object codetype="application/java-vm" width="300" height="300" archive="test.jar" classid="java:MyClass.class"></object>
</body>
</html>

Has anybody some ideas about why jsp won't cooperate?
And at least I would love to use jsp:plugin


Q: Socket Program to demonstrate Link layer communication in a network without using ip address As we all know that within a network, communication is by the MAC address and not by the ip address. So I always used to think that whether we can write a socket program in server-client paradigm which are only using MAC address for communication but not ip address i.e. the struct sock_in should be left unfilled, and within a lan they should be able to communicate.

A: Raw sockets, as given by the example above (by Carl) can work to give you access for L3 header. However, note that on more up-to-date Windows (XP SP3, Vista and 7) raw sockets are greatly restricted by the socket layer, making it difficult to send arbitrary data of your choosing.
You can also use special libraries that allow for a much more raw access to the Ethernet adapter. WinPcap (for Windows) or libpcap (for Linux) will allow you to manipulate the entire packet data, including the Ethernet header, and indeed send any other L2 protocol you wish.


Q: Magento properly reindex everything I have searched for a while, followed this answer even looked at the shell indexer script, and I came with this. Basically, I have
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL));
$processes->walk('save');

// Importing data here...

Mage::getModel('catalog/product_image')->clearCache();

// rebuild everything!!!
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('reindexEverything');
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME));
$processes->walk('save');

But I still get this screen in my backend

...How to "update" the indexes?
** UPDATE **
Problem solved!
To properly index everything, just call everything!
// rebuild everything!!!
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME));
$processes->walk('save');

$processes->walk('reindexAll');
$processes->walk('reindexEverything');

A: If you run indexer.php from cli, using the following parameters, do the alerts become resolved:
indexer.php reindex all
If so, is executing indexer.php with those params as part of your script an option?
Edit: also, in Mage_Index_Model_Process take a look at reindexEverything() method.
indexer.php has an example of its usage.

A: I just encountered this issue in CE v1.9.0.1. My admin module was getting all processes as a collection and looping through each one calling reindexEverything(). I based the code on the adminhtml process controller which was working fine, but my code wasn't working at all.
I finally figured out the issue was that I had previously set the reindex mode to manual (to speed up my product import routine) as follows:
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL));

// run product import

$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
foreach($processes as $p)
{
    if($p->getIndexer()->isVisible())
    {
        $p->reindexEverything();
        //echo $p->getIndexer()->getName() . ' reindexed
';
    }
}

$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME));

SOLUTION: set mode back to MODE_REAL_TIME before reindexing everything:
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL));

// run product import

$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME));

$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
foreach($processes as $p)
{
    if($p->getIndexer()->isVisible())
    {
        $p->reindexEverything();
        //echo $p->getIndexer()->getName() . ' reindexed
';
    }
}

Note: these are snips from a few different methods hence the repeated assignment of $processes etc..
It seemed reindexEverything() wasn't doing anything when the processes index mode was set to MODE_MANUAL. Setting mode back to MODE_REAL_TIME and then calling reindexEverything worked fine.
I hope this helps someone as I had a few frustrated hours figuring this one out!
Thanks


Q: How to pre-populate a form from a web app on a different server I have Web Application A on Server A that links to Web Application B on Server B. I'm linking to a form that I want to pre-populate with data from Web Application A. So:
Web App A --Links to form and sends data for pre-population--> Web App B
Since they're on seperate servers I importunately can't just plop something into Session, so I'm going to have to be a little more creative. I'm considering a few different options and I'm looking for the simplest of those solutions. Any suggestions?
Here's a few options I'm considering:

*

*Pass the form data in the link via query string parameters. This seems simple enough, is the legit to do? Or is it a security concern? I'd be passing about 8 parameters, the most sensitive being e-mail address and address. This would all be over SSL.

*Similarly, I could pass the data as POST parameters.

*Web App A writes a cookie, Web App B reads the data from the cookie. (This seems like more of a security concern than passing as GET or POST parameters)

*I could share an object via JNDI to use for prepopulation. Then I guess I could pass a unique ID on the query string which Web App B could use to pick up the object. This seems like it might be "overkill" and I'm not sure how this would work.

*I could store the data in a database against a unique ID, pass the unique ID on the query string, then pick it up in Web App B from that same database. Again, this might be "overkill".

Any thoughts? Or is there a better solution that I don't have listed?

A: In my opinion the GET params are the simplest way to do it, and I don't think there are important security implications.

A: You should assume anything that web app A puts in the redirect can be read/stolen/modified/spoofed before it gets to web app B (unless you are using SSL on both app A and B). If this isn't a problem then putting the params on the redirect URL should do you fine.
A secure way would be for app A to generate a unique ID (non guessable and short lived) and to store the info against this ID. The ID is passed with the request to app B. Server B then accesses the data from server A using the ID in a private secure way, for example be calling a web service on server A that is not publically accessible.


Q: How to query recursive MongoDB Document [File System of files and folders] I am developing an application that uses MongoDB (typegoose) to store file system-like (recursive) documents composed of files and folders. However, I do not know how to query such a schema. For querying, I am provided the following.

*

*users _id

*the array of folder names in order ex. ['root', 'nestedFolder1', 'nestedFolder2', 'etc...']

*_id of the last folder chosen

The schema is as follows

import { Types } from "mongoose";
interface File {
    _id: Types.ObjectId;
    fileName: string;
    isDir: false;
    content: string;
    title: string;
    description: string;
}

interface FileSystem {
    _id: Types.ObjectId;
    folderName: string;
    isDir: true;
    files: File[] | [];
    folders: FileSystem[] | [];
}

interface Project {
    _id: Types.ObjectId;
    projectName: string;
    fileSystem: FileSystem;
}
interface User {
    _id: Types.ObjectId;
    projects: Project[];
}

Update:
Here's a replit for reference
https://replit.com/@alphacoma18/mongodb-recursive-schema#server.ts

A: 1- Most trivial query, get all FileSystem Documents:
const fileSystems = await FileSystem.find({
    // Empty Object means no condition thus give me all your data
});

2- Using the $eq operator to match documents with a certain value
const fileSystems = await FileSystem.find({

        isDir: true,
        folderName: { $eq: 'root' }
    });

3- Using the $in operator to match a specific field with an array of possible values.
const fileSystems = await FileSystem.find({
    isDir: true,
    folderName: { $in: ['root', 'nestedFolder1', 'nestedFolder2'] }
});

4- Using the $and operator to specify multiple conditions
const fileSystems = await FileSystem.find({
    $and: [
        { isDir: true },
        { folderName: { $in: ['root', 'nestedFolder1', 'nestedFolder2'] } }
    ]
});

5- Retrieve all documents that are directories and are not empty.
const fileSystems = await FileSystem.find({
    isDir: true,
    $or: [
        { files: { $exists: true, $ne: [] } },
        { folders: { $exists: true, $ne: [] } }
    ]
});

6- All directories that have a folder name that starts with the letter 'n'
const fileSystems = await FileSystem.find({
    isDir: true,
    folderName: { $regex: '^n' }
});

Now the tougher queries:
1- count the total number of documents
const count = await FileSystem.aggregate([
    { $count: 'total' }
]);

2- count the total number of documents that are directories
const count = await FileSystem.aggregate([
    { $match: { isDir: true } },
    { $count: 'total' }
]);

3- Get 'foldername' and 'filename; of all documents that are files.
const fileSystems = await FileSystem.aggregate([
    { $match: { isDir: false } },
    { $project: { folderName: 1, fileName: 1 } }
]);

4-  Retrieve the total number of files (isDir: false) in each directory (isDir: true)
const fileCounts = await FileSystem.aggregate([
    { $match: { isDir: true } },
    {
        $project: {
            folderName: 1,
            fileCount: {
                $size: {
                    $filter: {
                        input: '$files',
                        as: 'file',
                        cond: { $eq: ['$$file.isDir', false] }
                    }
                }
            }
        }
    }
]);

5- Recursive structure querying:
The FileSystem interface is recursive, because it has both an array of files and an array of folders, which are both of type File[] and FileSystem[].
To query this recursive schema, you can use the $lookup operator in an aggregate pipeline, to make a left join between FileSystem and itself, based on some criteria.
//Retrieve All Documents from FileSystem and their child documents
const fileSystems = await FileSystem.aggregate([
    {
        $lookup: {
            from: 'FileSystem',
            localField: '_id',
            foreignField: 'parentId',
            as: 'children'
        }
    }
]);

//Use the match operator in the pipeline to filter the results:
const fileSystems = await FileSystem.aggregate([
    {
        $lookup: {
            from: 'FileSystem',
            localField: '_id',
            foreignField: 'parentId',
            as: 'children'
        }
    },
    { $match: { isDir: true } }
]);


Q: VS2008 and ClearCase : opening solution requests a checkout for no reason I have a little issue that's causing my automated builds to fall over.
When we open a solution recently converted from VS2005 to VS2008 VS through ClearCase requests that we checkout the solution file.
If we allow it then it makes no changes anyway and by default ClearCase doesn't like checkins without changes.  So we undo the checkout - and from then on VS is happy, it was able to write the .suo file.
If we un-read protect the solution file, start up VS2008 it creates the .suo file ok, if we then un-hijack the .sln file (no changes anyway so VS2008 doesn't notice) and fire up VS2008 again it's fine - doesn't ask for a checkout.
In my build script I delete all view private files from the view and then do an update with forced un-hijack of controlled files.  And then we build the deployment projects (and thus all dependencies), and as the .suo file is being deleted it falls into the checkout .sln file behaviour every time.
And on the build server there isn't anybody around to see the dialog asking for a checkout, the build hangs.
I could change (aka bodge) the build script to not delete the .suo file, but I would rather not do this.
edit:  clarification - the .suo file is NOT checked into ClearClase - it is a view private file that is being created by VS2008, however to create this file it wants to check out the .sln file for not real reason.
Further Edit:
I have found the solution to this - I've disabled the integration as per my follow up post on this thread.

A: Okay, I found the solution to the problem and it was quite simple in reality.
I disabled the Visual Studio ClearCase integration on the build server.
VS is being used as we need to build deployment projects and so we call devenv to do this for us.  However we are only using it as a build engine, there is never a need for the build engine to know how to modify the source items as they will all have just come from ClearCase.  The only items we allow the build server to modify are the assembly file version number attributes in the AssemblyInfo files, but we do that in the NAnt and not in Visual Studio.
So, disable the functionality and problem goes away.  Probably not the solution for everybody but on a build server it was the way forward.

A: This troubleshooting item, got me to this fix pack which has solved the issue in our development environment. We're still using VS2005, but I would expect that it's the same issue as what was going wrong in VS2008.

A: This seems to be normal for VS2008, it checks out the .sln file when opening a solution. I dont like it either.
Your problem however is the fact that the .suo file is also checked in. This file should not be placed under source control. It is like the proj.user files. I suspect suo stands for Solution User Options.

A: You could:

*

*update your script in order to hijack the sln file in your snapshot view just after your "cleartool update -force -overwrite".

*or, to avoid the sln to be checked-out, you could try and keep the .suo file checked-in,

If the above suggestion works, then here is a couple of reason why one would want to keep this file under version control:

*

*Since the .suo file is disposable (VS2008 just creates a new one if it does not exist), having under source control might been seen as a way to avoid that creation (hence avoiding the ClearCase plugin detecting it and trying to "add to source control" it or checking it out).

*Another advantage to having .suo file under version control (but not updated through any further checkout/checkin) is when you are comparing your checked out project with another checked out version of the same project downloaded elsewhere: that file will always be identical, as opposed to systematically different (since if is a binary file, and any new version of a binary file would register itself as different)


Q: I can't connect to the webserver I have a WordPress instance running locally on my mac with XAMPP.
It's working fine but when I want to install something I have to login with my ftp username and password.
I've tried to use my username and password which I use to logon to WordPress. Also I used my tried my database credentials. I really have no idea which other logon credentials I should have.

A: FTP credentials do not refer to your login details, it refers to credentials for File Transfer Protocol, it is given to you when you purchase a web hosting service or setup one yourself on your machine.
An alternative to this would be to download the plugin or theme you want and paste it to your /{website folder}/wp-content/themes or /{website folder}/wp-content/plugins

A: Try to

*

*Right click to htdocs folder, choose Get info

*Click the lock icon, type your MacOS account password to unlock below options.

*Allow everyone Read & Write permission, the click the cog icon and choose Apply to enclosed items..., this should apply all r+w permission to sub-folders.

*Done


Q: Trouble connecting to laravel api with jwt while hosting on 000webhost i am trying to host a project on 000webhost free tier and i am stuck on this problem. I have searched everywhere i could and still no solution. The project is a laravel 5.7 api using jwt for authentication and works fine on localhost. i uploaded everything on 000webhost without a problem and set up the database with this.
I know it is up and working to a certain degree as i can access the index.php and it shows up.(It is just a page showing 'hello' on it).
My problem is when i try to make a call to the '/api/showAuthUser' endpoint using postman I get this error.
Argument 3 passed to Lcobucci\JWT\Signer\Hmac::doVerify() must be an instance of Lcobucci\JWT\Signer\Key, null given, called in /storage/ssd1/450/8968450/vendor/lcobucci/jwt/src/Signer/BaseSigner.php on line 42

When i try to make a call to '/api/login' using postman i get this error.
Argument 2 passed to Lcobucci\JWT\Signer\Hmac::createHash() must be an instance of Lcobucci\JWT\Signer\Key, null given, called in /storage/ssd1/450/8968450/vendor/lcobucci/jwt/src/Signer/BaseSigner.php on line 34

I am sure I have the database connected correctly and I have the jwt secret in the .env file. I have tried every solution I could find online with no joy. The only one i have not tried was running php artisan jwt:secret as I can not run commands in 000webhost or I just don't know how to do this.
Sorry if this is not enough information but I am new to api's and this is my last hope. Thank you.

A: You have a jwt.php file in your config folder (config/jwt.php). In there please replace the JWT_SECRET with your generated jwt secret key on your .env file
In jwt.php file
'secret' => env('JWT_SECRET', 'PLACE YOUR JWT KEY HERE'),

Hope this will solve your problem


Q: How to create a link without .lnk extension? If I have a file named "C\Test\mypic.jpg", can I create a shortcut with path "C\Test2\mypic.jpg"? Windows always seems to add a ".lnk" suffix, which is unwanted in my case.

A: Link in this case can mean several things but we can unpack all the possible scenarios:

*

*A shortcut (.lnk file). These files must have the .lnk extension because the file extension is how Windows decides which handler to invoke when you double-click/execute the file. If you create a shortcut to a jpg file the real name can be link.jpg.lnk but the user will see the name as link.jpg in Explorer because .lnk is a special extension that is hidden.

*A symbolic link (symlink). These are links on the filesystem level and can have any extension. mklink "c:\mylink.jpg" "c:\file.jpg"

*A hardlink. This is another name for the same file (alias), it does not create a shortcut. mklink /H "c:\anothername.jpg" "c:\file.jpg"


Q: How to convert this Oracle query into HSQL query I am trying to convert this Oracle query into HSQL, but i have difficulties.
select a.t_user_id, listagg(et.event_type_name,', ') within group (order by a.t_user_id )
from t_agency a inner join t_agency_event_type aet on a.t_user_id = aet.agency_id
                inner join t_event_type et on aet.t_event_type_id=et.id
group by a.t_user_id;

Can anybody help me? Thanks in advance!
ADDED:
My HSQL query is like this:
Query queryEventTypes = em.createQuery("select agency, GROUP_CONCAT(et.eventTypeName SEPARATOR ', ') as  eventTypeName " +
                        "from TAgency agency join agency.tAgencyEventTypes eat " +
                        "join eat.tEventType et " +
                        "group by hiredAgency.tUserId, hiredAgency.address, hiredAgency.city, hiredAgency.information, "
                        + "hiredAgency.website");

But it gives me the error:
unexpected token: SEPARATOR near line 1, column 46 [select agency, GROUP_CONCAT(et.eventTypeName SEPARATOR ', ')
                    as  eventTypeName from bg.fmi.master.thesis.model.TAgency agency join agency.tAgencyEventTypes eat join eat.tEventType et
                    group by hiredAgency.tUserId, hiredAgency.address, hiredAgency.city, hiredAgency.information, hiredAgency.website]

A: Try the GROUP_CONCAT function supported by HSQLDB version 2.3.x and later. The HSQLDB syntax is different and documented here.
http://hsqldb.org/doc/2.0/guide/dataaccess-chapt.html#dac_aggregate_funcs
The example given in the Guide shows how you specify the grouping and ordering of the results;
SELECT LASTNAME, GROUP_CONCAT(DISTINCT FIRSTNAME ORDER BY FIRSTNAME DESC SEPARATOR ' * ') FROM Customer  GROUP BY LASTNAME


Q: Why does my then() never get invoked whenever I add a stream to my stream controller? I have a bloc which has a stream controller and in the constructor of the bloc I add the stream to the controller. I wait until the stream is added and then I add a listener to it. But the then() never get's invoked. I'm sure that GeoLocator() code works because I had it in a stateful widget before and that worked like a charm but I decided to move the business logic to a bloc.
import 'dart:async';

import 'package:geolocator/geolocator.dart';

class LocationBloc {
  final Geolocator _geolocator = Geolocator();
  final LocationOptions _locationOptions = LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10);
  StreamController<Position> _positionStreamController = StreamController<Position>();
  double _speed = 0;

  double get speed => _speed;

  LocationBloc() {
    print('it gets here');
    final Stream<Position> positionStream = _geolocator.getPositionStream(_locationOptions);
    print('and here');
    _positionStreamController.addStream(positionStream).then((value) {
      print('it never gets here');
      print(value);
      _positionStreamController.stream.listen((Position position) {
        this._speed = position == null ? 0 : position.speed;
      });
    });
  }

  void dispose() {
    print('dispose location stream');
    _positionStreamController.close();
    _speed = 0;
  }
}

When I dispose of he bloc provider when the widget get's disposed and call the dispose in the bloc it throws the following error
Bad state: Cannot add event while adding a stream

The stateless widget
class DigitalSpeedMeter extends StatelessWidget {

  static Widget create(BuildContext context) {
    return Provider(
      create: (_) => LocationBloc(),
      child: DigitalSpeedMeter(),
      dispose: (BuildContext context, LocationBloc bloc) => bloc.dispose(),
    );
  }

A: I ended up using this
import 'dart:async';

import 'package:geolocator/geolocator.dart';

class LocationBloc {
  final Geolocator _geolocator = Geolocator();
  final LocationOptions _locationOptions = LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10);
  StreamController<double> _streamController = StreamController<double>();
  Stream<double> get stream => _streamController.stream;

  LocationBloc() {
    _streamController.addStream(_geolocator.getPositionStream(_locationOptions).map((position) => position.speed ?? 0.0));
  }

  void dispose() {
    _streamController.close();
  }
}

With a stream builder widget.