Q: How to optimize navigation and user-experience into a login form? I have developed an Universal app that uses a login form, that allowing users to connect or to create an account.
It is a simple page that looks like this:

This XAML code is also very simple:
    <ScrollViewer>
        <StackPanel>
            <TextBlock x:Uid="loginRegisterTextblockMessage"
                       Style="{StaticResource TitleTextBlockStyle}"
                       Text="Remplissez vos informations d'inscription" />
            <TextBox x:Uid="loginRegisterTextboxOrganizationURL"
                     Header="Organisation ou URL"
                     IsSpellCheckEnabled="False"
                     IsHitTestVisible="True"
                     IsTextPredictionEnabled="False"
                     Text="{Binding OrganizationURL, Mode=TwoWay}" />
            <TextBox x:Uid="loginRegisterTextboxLastName"
                     Header="Nom"
                     Text="{Binding LastName, Mode=TwoWay}" />
            <TextBox x:Uid="loginRegisterTextboxFirstName"
                     Header="Prénom"
                     Text="{Binding FirstName, Mode=TwoWay}" />
            <TextBox x:Uid="loginRegisterTextboxEmail"
                     Header="Email"
                     InputScope="EmailSmtpAddress"
                     Text="{Binding Email, Mode=TwoWay}"/>
            <PasswordBox x:Uid="loginRegisterPasswordboxPassword"
                         Header="Mot de passe"
                         Password="{Binding Password, Mode=TwoWay}" />
            <PasswordBox x:Uid="loginRegisterPasswordboxConfirmPassword"
                         Header="Confirmez le mot de passe"
                         Password="{Binding PasswordConfirmation, Mode=TwoWay}" />
            <CheckBox x:Uid="loginRegisterCheckboxTermsOfUse"
                      IsChecked="{Binding TermsOfUse, Mode=TwoWay}" >
                <TextBlock Style="{StaticResource BaseTextBlockStyle}">
                    <Run x:Uid="loginRegisterTextblockTermsOfUse1"
                         Text="J'accepte les " />
                    <Underline>
                        <Hyperlink x:Uid="loginRegisterHyperlinkTermsOfUse"
                                   NavigateUri="http://termsofuse.html" >
                            <Run x:Uid="loginRegisterTextblockTermsOfUse2"
                                 Text="conditions générales d'utilisation" />
                        </Hyperlink>
                    </Underline>
                </TextBlock>
            </CheckBox>
            <Button x:Uid="loginRegisterButtonRegister"
                    Content="S'inscrire"
                    Command="{Binding RegisterCommand}" />
        </StackPanel>
    </ScrollViewer>

But I meet a "problem" for navigating between each fields of this page:

=> The user must click outside of a TextBlock to hide the keyboard and select the next field: this is not very user-friendly
I took a look at a similar "system" form: the page used to create an account to access to the Windows Store.
The page looks very similar to my own page:

But it is there possible to activate the next field by clicking on its header:

The focus moved on the field and the keyboard is also automatically displayed:

If I click on the the next header "Nom d'utilisateur", I can see that the next field is now "Domaine", by moving automatically into the displayed content:

=> Is there an easy way to reproduce this comportment?  Is it based on the "Header" of the "TextBox", or by using seperated "TextBlock" to show the header?

A: I always looking for a good solution but I didn't find it.
I've added events in the XAML for the TextBox and PasswordBox on GetFocus and KeyDown.
In the Code-Behind, I can now manage the "Enter" Key, that gives the focus to the next TextBox:
        private void RegisterTextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        TextBox currentTextBox = (TextBox)sender;
        if (currentTextBox != null)
        {
            if (e.Key == Windows.System.VirtualKey.Enter)
            {
                FocusManager.TryMoveFocus(FocusNavigationDirection.Next);
            }
        }
    }

But I haven't yet managed the ScrollViewer autoscroll like I hope.
I tried to inspire me from this link, but to no avail:
Keyboard-Overlaps-Textbox
=> Is there really a way to reproduce the autoscroll that is used on the registration form for the Windows Store?


Q: How to get map values by index when inside each loop in JavaScript? I try to write tests in a clean way.
I iterate through the rows (each of which shows info about attached file) of the table on the page and verify if each attached file has correct size:
   it('attaches many documents', () => {
     const fileSizes = ['17.19 KB', '12.06 KB', '67.75 KB']
     cy.get('input[type="file"]').attachFile([excelFilePath, docxFilePath, pdfFilePath])

     cy.get('div.table-body>.table-row').each(($el, index) => {
       expect($el.find('.col-upload-size')).to.contain.text(fileSizes[index])
     })

   })

But earlier in the code I have this map defined:
const fileSizesMap = new Map([
    ["excelFileSize", "17.19 KB"],
    ["docxFileSize", "12.06 KB"],
    ["pdfFileSize", "67.75 KB"]
]);

Can I somehow get rid of fileSizes list inside of the test and make use of fileSizesMap instead?

A: I understand you want to replace fileSizes with the values from your fileSizesMap:
const fileSizes = Array.from(fileSizesMap.values())

A: You could try to return an iterable for values and do your assertions:
const fileSizesMap = new Map([
    ["excelFileSize", "17.19 KB"],
    ["docxFileSize", "12.06 KB"],
    ["pdfFileSize", "67.75 KB"]
]);

it('attaches many documents', () => {
    cy.get('input[type="file"]').attachFile([excelFilePath, docxFilePath, pdfFilePath])
    for (const value of fileSizesMap.values()) {
        cy.get('div.table-body>.table-row').then(() => {
            expect($el.find('.col-upload-size')).to.contain.text(value)
        })
    }
})


Q: Input 0 of layer time_distributed_30 is incompatible with the layer: expected ndim=5, found ndim=4. Full shape received: (None, None, None, None)
*

*I am trying for classification of MSTAR data set with 10 classes

*I have used the modal that contains DCNN and BILSTM with 15 time steps

My questions are:

*

*How to overcome the error

*How to get the good classification results.

My code is:
inputs=Input(shape=(15,60,60,3))
model = Sequential()
# 1st Convolutional Layer
model.add(TimeDistributed(Conv2D(filters=16 ,kernel_size=(5,5), padding='valid'),input_shape=(15,60,60,3)))
model.add(TimeDistributed(Activation('relu')))
# Batch Normalisation
model.add(TimeDistributed(BatchNormalization()))
# Pooling
model.add(TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid')))

# 2nd Convolutional Layer
model.add(TimeDistributed(Conv2D(filters=32, kernel_size=(5,5), padding='valid')))
model.add(TimeDistributed(Activation('relu')))
# Batch Normalisation
model.add(TimeDistributed(BatchNormalization()))
# Pooling
model.add(TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid')))

# 3rd Convolutional Layer
model.add(TimeDistributed(Conv2D(filters=64, kernel_size=(5,5), padding='valid')))
model.add(Activation('relu'))
# Batch Normalisation
model.add(TimeDistributed(BatchNormalization()))
# Pooling
model.add(TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid')))

# 4th Convolutional Layer
model.add(TimeDistributed(Conv2D(filters=128, kernel_size=(4,4), padding='valid')))
model.add(TimeDistributed(Activation('relu')))
# Batch Normalisation
model.add(TimeDistributed(BatchNormalization()))
model.add(TimeDistributed(Flatten()))
#add dropout
model.add(Dropout(0.0))
#bidirectional lstm
model.add(Bidirectional(LSTM(1024,activation='tanh',return_sequences=True)))
#2 nd bidirectional layer
model.add(Bidirectional(LSTM(1024,activation='tanh',return_sequences=False)))
# Output Layer
model.add(Dense(10))
model.add(Activation('softmax'))

# (4) Compile
model.compile(loss='categorical_crossentropy', optimizer='adam',\
 metrics=['accuracy'])
model.summary()


Q: How to call a UDF from a JSON file in Python? I'm working on a chatbot project which fetches "delivery status" information from a database. I've defined a function (lets call it db_info) which will connect to my DB and then get the results.
I have a .json file which has different intents like "Greeting", "Status Check", "Closing" etc. The way the application works is - whenever the user types in something, the text is classified into an intent. For ex: when the user types "Hi" the application recognizes it is from the intent "Greeting" and then gives out one of the responses I hard coded in the .json file.
However, for the "Status Check" intent I don't want the application to give out some hard coded response from .json file. Instead, I'd like it to call the db_info function when the intent "Status Check" is identified.
I'm aware that a function map (dictionary) can be created in .py file and then its value can be called in the json file. But I'm not sure how this is done exactly.
def db_info(): --> lives in .py file
   # connect to postgres and get some information

if intent == 'greetings':
   # pick random statement from "responses" of tag "greeting" from json file

if intent == 'status_check':
   # go to "responses" under tag "status_check" and run the func mentioned there
   def db_info():
       # instead of picking up a random statement from "response" this func needs to be called

My json file:
{"tag": "greetings",
 "pattern": ["Hi", "How are you", "Hey", "Hello", "Good Day"],
 "responses": ["Hello!", "Hey there", "Hi, how can I help you today?"]
},
{"tag": "status_check",
 "pattern": ["Where's my shipment", "Track my shipment"],
 "responses": ["GetDBInfo function"]
}

A: You can modify your json to match the following parsing process:

*

*find the intent the pattern matches

*get a response

*pass it as an argument to the function of that intent

This means that you will add a "function" field to the json and call it when you parse. All intents will simply have it as "print" (or whatever other default operation you're doing) and the "Status_Check" intent will have its own special function. Then, just map the names to actual function objects that you can call.
So the json can look like this:
[{"tag": "greetings",
  "pattern": ["Hi", "How are you", "Hey", "Hello", "Good Day"],
  "function": "print",
  "responses": ["Hello!", "Hey there", "Hi, how can I help you today?"]
 },
  {"tag": "status_check",
    "pattern": ["Where's my shipment", "Track my shipment"],
    "function": "GetDBInfo",
    "responses": [""]
  }]

And to parse it:
import json
import random

def db_info(useless_arg):
    print("from func")

func_mapping = {"print": print,
                "GetDBInfo": db_info}

with open("test.json") as file:
    intents = json.load(file)

text = input("input: ")

for intent in intents:
    if text in intent["pattern"]:
        function = intent["function"]
        arg = random.choice(intent["responses"])
        func_mapping[function](arg)

An example run:
input: Where's my shipment
from func

input: Hi
Hello!


Q: How to plot wide dataframe After training a model, I want to plot the accuracy, validation accuracy, etc. In Seaborn, this is what I tried to do:
df_model_history = pd.DataFrame(
    np.array([
        history.history['accuracy'],
        history.history['val_accuracy']
    ]).T,
    columns=['Accuracy', 'Validation Accuracy']
)

df_model_history.index.name = 'Epochs'

That creates a data frame that looks like this:

Epochs
Accuracy
Validation Accuracy

0
0.769296
0.766673

1
0.858553
0.894064

2
0.915641
0.901508

3
0.936782
0.892285

And when I want to plot, I do this:
sns.set(rc={'figure.figsize':(11.7,8.27)})

sns.lineplot(
    x='Epochs',
    y='Accuracy',
    data=df_model_history
)

However, this only plots a single variable in the figure, but I wanted both 'accuracy' and 'val_accuracy' in the same figure. Also, compared to Matplotlib, I have a lot more steps in Seaborn to plot the same output, so I was wondering if I'm doing it incorrectly.


Q: Interrupting DataAdapters? I have a circumstance where I'm popping up a dialog window containing a "Please Wait" message, running an SQL query, then replacing the "Please Wait" message with a DataGridView containing the collected results.
The code I'm using for this is basically:
    Dim X As New Data.SqlClient.SqlCommand
    X.CommandText = "SELECT some_data FROM someTable"
    Dim XAdapter As New System.Data.SqlClient.SqlDataAdapter(X)
    Dim XSet As New DataSet
    XAdapter.Fill(XSet, "MyTable")

    Me.someDataGridView.DataSource = XSet.Tables("MyTable").DefaultView

I would like to put the retrieval of this data into a background thread, so that the UI doesn't freeze up while I'm loading larger datasets, but, having done this, I'd also like to allow the user to cancel and close the dialog, if accessing the data takes longer than they want to wait.
At the moment, this Dialog window can take some arbitrary SQL string and display the results (using SQLDataAdapter) without any extra code.
How can I make this process interruptible, while also retaining the ease of access of the SQLDataAdapter?

A:
How can I make this process
  interruptible, while also retaining
  the ease of access of the
  SQLDataAdapter?

According to the documentation you should be able to call Close on the underlying SqlConnection instance. The documentation says this will terminate and rollback any pending transactions. Also, instead of using a SqlDataAdapter (which unfortunately does not have the async Fill methods) you could use SqlCommand.BeginExecuteReader and once that is done you can fill a DataTable by calling the overload of DataTable.Load that accepts an IDataReader. If you want to interrupt a pending a command just call Close.


Q: Android Video View turns black This seems to be a very common problem, but I couldn't search for it on SO.
I have a simple videoview and it play video from a mp4 file. It continously plays video and loop through the video.
Problem is when playing I went to settings and came back then video turns black.
This is my Code:
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_video);
    video = (VideoView) findViewById(R.id.video);
    // Load and start the movie
    Uri video1 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.videoplayback);
    video.setVideoURI(video1);
    video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.setLooping(true);
        }
    });
    video.start();

I don't want anything special in this, just a full screen of video playback which loops video till user tap back button.

A: try this
private int stopPosition;
   private VideoView splashVideoView;  <-- my Video view

in onCreate
 //video player

    if (savedInstanceState != null) {
            stopPosition = savedInstanceState.getInt("position");
        }

  @Override
    protected void onResume() {
        super.onResume();
        splashVideoView.seekTo(stopPosition);
        splashVideoView.start();
    }

// This gets called before onPause so pause video here.
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        stopPosition = splashVideoView.getCurrentPosition();
        splashVideoView.pause();
        outState.putInt("position", stopPosition);
    }

A: try this
  private int videoViewStopPosition ;

   @Override
    protected void OnPause(){
    super.onPause();
    videoViewStopPosition = vidView.getCurrentPosition();
    vidView.pause();
    }

  @Override
    protected void OnResume() {
     super.onResume();
     vidView.seekTo(videoViewStopPosition);
     vidView.start();

    }

A: I had the same issue. I found that the main reason for that was the use of FrameLayout as the parent layout. I changed it into RelativeLayout as parent layout of the VideoView and the problem get solved.

A: You need to create Video view in onResume() also. Try this:
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_video);

        setVideoBackground();
    }

    @Override
    protected void onResume() {
      super.onResume();

        setVideoBackground();
    }

   private void setVideoBackground(){
       video = (VideoView) findViewById(R.id.video);
       // Load and start the movie
       Uri video1 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.videoplayback);
       video.setVideoURI(video1);
       video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
       @Override
       public void onPrepared(MediaPlayer mp) {
       mp.setLooping(true);
    }
  });
       video.start();
}


Q: QList destructor behavior - Does call delete/free() on pointers in the list? I have a class SomeObjectList : public QList<SomeObject*>
I am creating pointers to SomeObject and sticking them in the list like so:
SomeObjectList MyClass::getSomeObjects()
{
    SomeObjectList list;

    for( int i=0; i<10; ++i )
    {
        list << new SomeObject();
    }

    return list;   // Crashes approximately here in QList::~QList
}

I'm getting a crash in the QList destructor, and it looks like free() may be being called.  I found the source code for the function (Qt 4.8.2) and it looks like this:
template <typename T>
Q_OUTOFLINE_TEMPLATE QList<T>::~QList()
{
    if (!d->ref.deref())
        free(d);
}

Does this mean that free() is being called on any pointers left in the list when the destructor is called?  I have used lists in other places without this problem.  Under what circumstances does the destructor call free()?

A: To elaborate: destroying a QList will destroy the elements of the list. If the elements are pointers, the pointers themselves are destroyed, not the pointees. You can use qDeleteAll to delete the pointees.
(That will use operator delete, which is the right choice if and only if you're using operator new; malloc will always require free and operator new[] will always require operator delete[]).
That having been said, returning a QList by value won't destroy it, as its refcount won't drop to 0. Getting a crash there means it's very likely that you have some memory corruption. Use valgrind or similar tools to debug that.


Q: Create thrift service We have a some mobile service, google maps based (mobile applications for iOS and Android). So, the server part is a Java application, which accepts connection from clients.
In one moment, without me, server was moved (relocated) to another one, and they not moved the Thrift service on the new server. Server works fine, but Android app works only via Apache Thrift. So, the Android developer provided to me the .thrift file.
Can I create service with this data? How? What do I need to read?
The part of .thrift file:
namespace cpp gb65.HelpMeService
namespace csharp gb65.HelpMeService
namespace java com.gb65.HelpMeService
namespace php com.gb65.HelpMeService

//Version
const i32       SERVICE_API_MAJOR_VERSION = 1;
const i32       SERVICE_API_MINOR_VERSION = 0;

enum Res
{
    SUCCESS                             = 0,
    EMAIL_AND_PASSWORD_NOT_FOUND        = 1,
    EMAIL_NOT_UNIQUE                    = 2,
    EMAIL_VALUE_WRONG                   = 3,
    CELLPHONE_NOT_UNIQUE                = 4,
    CELLPHONE_VALUE_WRONG               = 5,
    FIRST_NAME_VALUE_WRONG              = 6,
    LAST_NAME_VALUE_WRONG               = 7,
    PASSWORD_VALUE_WRONG                = 8,
    PHOTO_IS_TOO_LARGE                  = 9,
    SESSION_NOT_FOUND                   = 10,
    TASK_NOT_FOUND                      = 11,
    PHOTO_NOT_FOUND                     = 12,
    USER_NOT_FOUND                      = 13,
    OTHER                               = 14,
    MESSAGE_NOT_FOUND                   = 15,
    OFFER_NOT_FOUND                     = 16,
    ALREADY_FRIENDS                     = 17,
    FRIENDSHIP_OFFER_NOT_FOUND          = 18,
    _LAST                               = 19
}

If needed, I can provide all of the .thrift file code.

A: Like CORBA, Thrift has developped a neutral language.
As shown in this tutorial, you have to compile the .thrift file with
thrift -r --gen java YourFile.Thrift

After that you have to implement the client calls.


Q: ValueError: Metric 'cosine' not valid. Use sorted(sklearn.neighbors.VALID_METRICS['ball_tree']) I'm trying to use cosine metric with Ball_tree algorithm since my data is of high dimensions. e.g.
nbrs = NearestNeighbors(n_neighbors=2,algorithm='ball_tree',metric='cosine').fit(data_seed)

However i get the following error:
ValueError: Metric 'cosine' not valid. Use sorted(sklearn.neighbors.VALID_METRICS['ball_tree']) to get valid options. Metric can also be a callable function.

I don't understand why i cannot use cosine similarity with ball tree?

A: check valid matrics sklearn.neighbors.VALID_METRICS['ball_tree'])
and use instead of cosine


Q: Why the function strlen() returns different values for the same length of two char arrays? #include <stdio.h>
#include<string.h>

int main() {

    char a[50],b[50];// same sized arrays

    for(int j =0;j<50;j++){
        b[j]='b';a[j]='a';// initializing with the same number of elements
    }

    printf("the size of a is %ld,",strlen(a));
    printf("the size of B is %ld",strlen(b));

    return 0;
}

The output is
the size of a is 50,
the size of B is 54

But what i expect is the size of a is 50
the size of B is 50
what is the problem here?

A:
what is the problem here?

The problem is that you don't terminate your strings.
C requires strings to be null terminated:

The length of a C string is found by searching for the (first) NUL byte. This can be slow as it takes O(n) (linear time) with respect to the string length. It also means that a string cannot contain a NUL character (there is a NUL in memory, but it is after the last character, not "in" the string).

#include <stdio.h>
#include<string.h>

int main() {

    char a[50],b[50];// same sized arrays

    for(int j =0;j<50;j++){
        b[j]='b';a[j]='a';// initializing with the same number of elements
    }

    // Terminate strings
    a[49] = b[49] = 0;

    printf("the size of a is %ld,",strlen(a));
    printf("the size of B is %ld",strlen(b));

    return 0;
}

Gives the correct result.


Q: reuse a widget in GWT I have a label widget and im trying to add this widget to the multiple cells in the flex table but the widget is appearing only in the first cell. Is it possible to reuse a widget in gwt?? how?
Label l1=new Label("USER") ;
tweetFlexTable.setWidget(0,0,l1);
tweetFlexTable.setWidget(0,1,l1);

A: Every widget can only have one parent.
So you have to create as many widgets as you have cells, like this:
Label l1=new Label("USER") ;
tweetFlexTable.setWidget(0,0,l1);
Label l2=new Label("dunno") ;
tweetFlexTable.setWidget(0,1,l2);


Q: copy the same row from multiple sheets into one sheet in excel I need to copy the same row from multiple sheets into one row.
Example: I have an excel file with 5 sheets. I have to copy the 10th row (or the 15th row, or the 21th row) of every sheet in a 6th sheet, in the order of the sheets.
Thanks in advance.

A: This code will copy 7th row from all first 5 sheets into 6th sheet.
Sub row_copy()

For i = 1 To Worksheets.Count - 1

Sheets(i).Rows(7).Copy Sheets(6).Cells(i, 1)

Next i

End Sub

A: Here is a sample for 6 sheets and rows # 7:
Sub copyrow()
    Dim Nrow As Long, Nsheet As Long
    Dim i As Long

    Nrow = 7
    Nsheet = 6

    For i = 1 To Nsheet - 1
        Sheets(i).Cells(Nrow, 1).EntireRow.Copy Sheets(Nsheet).Cells(i, 1)
    Next i
End Sub

The row # 7 from the first 5 sheets will be copied into the 6th sheet.


Q: Using Reflection to get property from field I have these classes:
public class Foo
{
    public Bar bar;
}

public class Bar
{
    public List<int> Something { get; set; }
    public string Else { get; set; }
}

I have a lot of classes like Foo. They all contain exactly one field. This field, Bar in my example, will be a different type of object every time, it doesn't have to be of type Bar. Whatever object it is (Bar or otherwise), this field will always be an object that has two properties, Something and Else.
My challenge: given any object that's like Foo (with one Field that holds two properties), get the value of the two properties. Given this method:
public void DoStuff(object myObject)
{
    var asdf = myObject.GetType().GetFields().First();
}

I can get the FieldInfo for Bar. What I'm looking for is the values of Something and Else. The names of these properties never change. Whatever the type is of the Field, it will always have two properties named Something and Else that will be of the same type.
Sadly, my problem involves auto generated code, and there are no shared interfaces or base types I can easily use.

A: Using this code you can retrieve the PropertyInfos for the Something and for the Else property:
Foo myObject = new Foo { bar = new Bar() };

// the FieldInfo for Foo.bar
var barField = myObject.GetType().GetFields().First();

// the Bar instance, i.e. myObject.bar
var barValue = barField.GetValue(myObject);

var somethingProperty = barField.FieldType.GetProperty("Something", BindingFlags.Instance | BindingFlags.Public);
var elseProperty = barField.FieldType.GetProperty("Else", BindingFlags.Instance | BindingFlags.Public);

as PsiHamster noted, you can then use GetValue and SetValue to retrieve and set the values of somethingProperty and elseProperty like this:
// get the value
var somethingValue = somethingProperty.GetValue(barValue);

// set the value
somethingProperty.SetValue(barValue, new List<int>());

A: //Get Bar FieldInfo
var barFieldInfo = myObject.GetType().GetFields().First();

// Get all public instance properties info
var barProps = barFieldInfo.FieldType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

// Get Something and Else properties info
var smthPropInfo = barProps.First(prop => prop.Name == nameof(Bar.Something));
var elsePropInfo = barProps.First(prop => prop.Name == nameof(Bar.Else));

// Get values
var bar = barFieldInfo.GetValue(myObject);
var smth = smthPropInfo.GetValue(bar);
var else = elsePropInfo.GetValue(bar);


Q: Transform a function into something that lapply works on properly (lists) I'm trying to make a list with 10 elements, each element consisting of 5 * i items drawn from a uniform distribution, i being the ith entry, and I want to use lapply.
Currently I made this function:
z_list <- list()
z_list_generator <- function(n) {
  for(i in 1:n){
  a <- runif(5 * i)
  tmp <- list(a)
  mybiglist[[i]] <- tmp
  }
  mybiglist
}

This function does give the correct outcome when I just put z_list_generator(2), it prints a list with the first element consisting of 5 elements, the second of 10 elements.
What I want to achieve is that I do lapply(some number, z_list_generator) such that it generates this same list, and such that when I do length(lapply(some number, z_list_generator)), the outcome is 'some number'.

A: Do you mean something like this?
z_list_generator  <- function(k) lapply(1:k, function(i) runif(5 * i))

set.seed(2018)    # Fixed random seed for reproducibility
z_list_generator(2)
#[[1]]
#[1] 0.33615347 0.46372327 0.06058539 0.19743361 0.47431419
#
#[[2]]
# [1] 0.3010486 0.6067589 0.1300121 0.9586547 0.5468495 0.3956160 0.6645386
# [8] 0.9821123 0.6782154 0.8060278

length(z_list_generator(2))
#[1] 2

A: Your z_list_generator is strange.
1) You do not initialise mybiglist in your function code. It probably modifies some global variable.
2) You assign mybiglist elements with another list (of lenght 1), which first element contains a sample from a uniform distrubution. Better assign a, not tmp there.


Q: django-tables2: Adding columns/fields dynamically I want to add a new field when somebody checks an option in my web page ("Add column 'external id' ")
table = IssueTable(issue_list)
show_ext = request.GET.get('show_ext', 0)
if show_ext:
    table._meta.fields = table._meta.fields + ('external_id',)

I thought doing that it was the solution but I didn't succeed. The external_id is part of the model. table._meta.fields doesnt get updated and of course I cannot see the column in the table when this one is rendered.
class IssueTable(tables.Table):

    def render_id(self, value, record):
        if record.status.upper() in ['RESOLVED', 'INVALID']:
            return mark_safe('<s>#%s</s>' % (reverse('issues.views.view', args=(record.pk,)), record.pk))
        else:
            return mark_safe('#%s' % (reverse('issues.views.view', args=(record.pk,)), record.pk))

    def render_title(self, value, record):
        return mark_safe('%s' % (reverse('issues.views.view', args=(record.id,)), value))

    class Meta(object):
        model = Issue
        fields = ('id', 'title', 'product', 'type', 'priority', 'status', 'created')
        attrs = {'class': 'table table-bordered'}
        empty_text = _('No records found')

Any ideas?


Q: C#, I want to call a method with parameters like var test = new test1.test2.Method("parameter1","parameter2") I want to call a method in a fixed structure like below in C#:
var Test = new test1.test2.test3("parameter1","parameter2");

Is this possible in C#?
Here test1 and test2 can be classes and test3 is my method name and it will return string text.
I can manage if need to remove new keyword.
I am assuming it should something like this :-
Public class test1
{
   Public class test2
   {
     Public string test3("parameter1","parameter2")
     {
       //Do something
     }
   }
}

A: Yes, you can if test3 is public structure type nested inside public structure type test2 which is nested inside test1
struct test1{
    public struct test2{
        public struct test3{
            public test3(string p1,string p2) {/*do something*/}
            //some params
        }
        //some params
    //some params
}

Also test1 and test2 could be namespaces.


Q: How to delete all files with certain suffix before file extension I was just handed a directory with some 40,000+ images, and the directory includes three versions of every file, which makes it a bear to have to transfer between servers.
I'm looking for a way using bash (OSX Terminal) to find and remove (rm) all files, for example, with _web, or _thumb on the end of the filename, just before the .jpg (or .gif, or .png, or .bmp, etc.) extension.
So, to be clear, I have the following files:
1.jpg
1_web.jpg
1_thumb.jpg
2.gif
2_web.gif
2_thumb.gif
etc.

And I only want "1.jpg", "2.gif", etc. to remain.
I've been able to rename extensions in the past, but my command-line-fu is pretty weak, and I'm at my wits end trying to figure out something that's reusable (I'm going to need to do this a couple times, as I'm working on a continuous migration script for this project).
Edit: After a bit more work on this, I found a few odd limitations of rm and xargs that I had to work around. I basically adapted the accepted answer below and ended up with:
$ find . -name '*_thumb.*' -print0 | xargs -0 rm -f
$ find . -name '*_web.*' -print0 | xargs -0 rm -f

Now I'm down to about 10,000 files - quite a savings in terms of pushing files around on the web!

A: One (relatively robust) option is to run
find . -iregex ".*\(_web\|_thumb\)\.\(jpg\|png\|bmp\)" -delete

Assuming that you don't have anything other than image files in the directory, another (simpler) option is to run
 rm *_web.* *_thumb.*

Warning: this will also delete files that are named something like my_web.file.jpg, so if you want to play safe, you'll have to add all the extensions instead of relying on .*
If you know that your extensions are always going to be 3 characters long, you can use something like *_thumb.???

A: I don't have a MAC or a UNIX terminal in front of me, but I imagine something like the following might work
rm *_web.jpg
rm *_web.jpg
rm *_thumb.gif


Q: Update jquery scrollbar after ng-repeat render Scrollbar don't see height of div because scrollbar update apply before child elements render.
How i can watch what elements is compiled?
I used watch to see when object adding to array. It works fine, but tinyscrollab_update sees empty div, because ng-repeat no compiled yet.
$scope.$watch('comments', function(){
    angular.element('#comment-list').tinyscrollbar_update('relative');
});

A: I write it in directive.
app.directive('commentsDirective', function(){
   $scope.$watch('comments', function(){
      angular.element('#comment-list').tinyscrollbar_update('relative');
   });
})


Q: CasperJS click() doesn't load new html I'm trying to use CasperJS' click() to follow a link which generates a modal on the current screen. When I query the proper selector and click it in the browser console using document.querySelector().click() it works, but even when I casper.evaluate() this it doesn't work. I found someone who had a very similar problem, but his question remains unanswered, and I am experiencing almost identical problems. casperjs button click doesn't navigate to next page
the code I'm currently using is
this.waitForSelector('div.talk-sharing__tools a.rate-button', function() {
    this.then(function() {
        this.evaluate(function() {
            document.querySelector('a.rate-button').click();
});

the page I'm trying to scrape is http://www.ted.com/talks/uri_alon_why_truly_innovative_science_demands_a_leap_into_the_unknown

A: It is really impossible to do those navigation steps with the phantomjs engine. It seems that the QtWebkit fork of phantom (version 1.9.7) is not up to the task anymore. Although your code works fine as is with slimerjs. You can comfortably install slimerjs through npm:
npm install -g slimerjs

and run your script with
casperjs --engine=slimerjs script.js

I tried several things with phantomjs that did not work. I added casper.on listeners for remote.message and resource.error, but those didn't show any errors when running the script in phantom. logLevel: "debug" also didn't show anything.
First: Using a casperjs function.
casper.thenClick("div.talk-sharing__tools a.rate-button");

Second: Trying to explicitly show the modal for the button (specific to the page).
casper.then(function(){
    var name = this.evaluate(function(){
        var modal = document.querySelectorAll(".modal-wrapper > .modal")[0];
        modal.className += " modal--show";
        return modal.className;
    });
    this.echo("name: "+name); // null
});

casper.waitUntilVisible(".modal__head__title");

Third: Let jQuery do the work.
var casper = require('casper').create({
    remoteScripts: [ "http://code.jquery.com/jquery-1.11.1.min.js" ]
});

casper.waitForSelector(selector, function() {
    this.evaluate(function() {
        jQuery("a.rate-button").click();
    });
});

A: Encountered similar issue today. After executing this.click() on start page (which I verified that PhantomJS is executing - by hooking into resource.requested and resource.received events), current page remained on start page (and it should go to clicked link page).
Solution was to update to the latest PhantomJS (1.9.8 at this moment).
Please note that I had PhantomJS 1.9.7 when the above described problem occurred.


Q: Getting binary data directly off the windows clipboard I've been beating my head against the desk for about an hour now just trying to find some way of getting say... an array of bytes off the clipboard.  Instead, all I can seem to find is information on how to get plain text from the clipboard... that's not helpful at all.
I've tried following this: Java getting bytes of clipboard
I've also tried following this: http://mrbool.com/manipulating-clipboard-content-with-java/24758
Every time I run into the silly DataFlavor being "unsupported".  Surely there's just something simple that I'm missing here... I mean... how can it support plain text, images, and java objects, but NOT have the basic functionality that just has to be under the hood of all this?
Sorry if I sound sarcastic and pissed off here... Java seems to have that effect on me. :(

A: Awt Clipboard and MIME types
InsideClipboard shows that the content's MIME type is application/spark editor
You should be able to create a MIME type DataFlavor by using the constructor DataFlavor(String mimeType, String humanReadableFormat) in which case the class representation will be an InputStream from which you can extract bytes in a classic manner...
However, this clipboard implementation is very strict on the mime type definition and you cannot use spaces in the format id, which is too bad because your editor seems to put a space there :(
Possible solution, if you have access to JavaFX
JavaFX's clipboard management is more lenient and tolerates various "Format Names" (as InsideClipboard calls them) in the clipboard, not just no-space type/subtype mime formats like in awt.
For example, using LibreOffice Draw 4.2 and copying a Rectangle shape, awt only sees a application/x-java-rawimage format whereas JavaFX sees all the same formats as InsideClipboard :

[application/x-java-rawimage], [PNG], [Star Object Descriptor (XML)], [cf3], [Windows Bitmap], [GDIMetaFile], [cf17], [Star Embed Source (XML)], [Drawing Format]

You can then get the raw data from the JavaFX clipboard in a java.nio.ByteBuffer
//with awt
DataFlavor[] availableDataFlavors = Toolkit.getDefaultToolkit().getSystemClipboard().getAvailableDataFlavors();
System.out.println("Awt detected flavors : "+availableDataFlavors.length);
for (DataFlavor f : availableDataFlavors) {
    System.out.println(f);
}

//with JavaFX (called from JavaFX thread, eg start method in a javaFX Application
Set<DataFormat> contentTypes = Clipboard.getSystemClipboard().getContentTypes();
System.out.println("JavaFX detected flavors : " + contentTypes.size());
for (DataFormat s : contentTypes) {
        System.out.println(s);
}

//let's attempt to extract bytes from the clipboard containing data from the game editor
// (note : some types will be automatically mapped to Java classes, and unknown types to a ByteBuffer)
// another reproducable example is type "Drawing Format" with a Rectangle shape copied from LibreOffice Draw 4.2
DataFormat df = DataFormat.lookupMimeType("application/spark editor");
if (df != null) {
    Object content = Clipboard.getSystemClipboard().getContent(df);
    if (content instanceof ByteBuffer) {
        ByteBuffer buffer = (ByteBuffer) content;
        System.err.println(new String(buffer.array(), "UTF-8"));
    } else
        System.err.println(content);
}


Q: Migration from SherlockActionBar to ActionBar I just migrate to native actionBar, before, with ABS it was working great.
Now, I don't need anymore compatibility as I develop for API 16+
I changed all references, and now, my menu only shows in text, with physic button, it doesn't show up in action bar...
I don't know what am I missing...
Here is my code :
main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >

<item
    android:id="@+id/menu_sync"
    android:icon="@drawable/ic_action_update"
    android:orderInCategory="80"
    android:showAsAction="ifRoom"
    android:title="Sync"/>
<item
    android:id="@+id/more"
    android:icon="@drawable/ic_action_core_overflow"
    android:orderInCategory="90"
    android:showAsAction="always"
    android:title="See more options">
    <menu>
        <item
            android:id="@+id/menu_send_coords"
            android:icon="@drawable/ic_action_send_coords"
            android:orderInCategory="80"
            android:showAsAction="ifRoom"
            android:title="Send Coords"
            android:visible="true"/>
        <item
            android:id="@+id/menu_foto"
            android:icon="@drawable/ic_action_device_access_camera"
            android:orderInCategory="100"
            android:showAsAction="ifRoom"
            android:title="Foto"
            android:visible="true"/>
    </menu>
</item>

In my Activity :
public class DashBoard extends BaseActivity { //BaseActivity extends ActionBarActivity
...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}

I tried to change the menu xml to another one ( google example), but it did not work.
I made a search fro any reference to Sherlock* and replace all of them
In my manifest I have :
  <application
    ...
    android:theme="@style/Theme.AppCompat" >

In my style.xml I have :
     <style name="AppBaseTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <!-- nothing API level dependent yet -->
</style>

    <!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

I've followed each step of :
http://www.grokkingandroid.com/migrating-actionbarsherlock-actionbarcompat/
What are the common issues when migrating from ActionBarSherlock to ActionBarCompat?
ActionBarCompat menu item is not showing
I don't know what more can I do???
Any help would be appreciated !

A: I think you should change your style.xml and your Android Theme since you don't ne the Android appcompat libarary anymore.
styles.xml:
<style name="AppBaseTheme" parent="@style/Theme.Holo.Light.DarkActionBar">
<!-- nothing API level dependent yet -->
</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

AndroidManifest.xml:
    <application
        android:theme="@style/AppTheme"
    ...


Q: how can i add a timeout function to javascript?

$('.btn').click(function() {
  $(this).toggleClass('spinner');
});

and i want to add a timeout function to it i added it like this but it does not work, any ideas why?

$('.btn').click(function() {
  $(this).toggleClass('spinner');
   setTimeout(function() {
       $this.button('reset');
   }, 8000);

});


Q: Error installing mariadb-server mariadb-client on Chromebook I'm trying install wordpress locally on my chromebook following these instructions.
I successfully ran:
`
sudo apt update
sudo apt upgrade
sudo apt install nano

`
But then get an error when I try to run
`
sudo apt install mariadb-server mariadb-client -y

`
Here's the error from my terminal:
`
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 libdbi-perl : Depends: perlapi-5.32.0
E: Unable to correct problems, you have held broken packages.

`
I'm a complete newb at Linux and spend hours googling / trying solutions to no avail. Any help is appreciated.


Q: undefined method `stringify_keys' for "/users/sign_out":String (Devise gem) In my project i am using devise gem .And also using link_to_if url helper because when users not isn't signed in , it will provide  new_user_session_path and also when they signed in it will provide destroy_user_session_path. For this at first I tried this code:
  <%=
      link_to_if(current_user.nil?, "Sign in", new_user_session_path) do
        link_to(user_signed_in?, "Sign out", destroy_user_session_path, method: :delete )
      end
  %>

its says "wrong number of arguments (4 for 3)"
Then I tried this code:
  <%=
      link_to_if(current_user.nil?, "Sign in", new_user_session_path) do
        link_to(user_signed_in?, "Sign out", destroy_user_session_path)
      end
  %>

its says "undefined method `stringify_keys' for "/users/sign_out":String"
Please help me out of this.

A: You're using a condition in your link_to call, just remove the first argument like this :).
link_to("Sign out", destroy_user_session_path)


Q: localstorage not defined ionic 2 i'm trying to import "local storage" from 'ionic-angular' and it says me
"LocalStorage is not defined"..
in addtion I got this error

RangeError: Maximum call stack size exceeded
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:153:20)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)
  at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18)

first time I got these error on this morning. yesterday I worked fine with another ionic 2 project.
by the way, that's my code
   import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import {Storage,LocalStorage} from 'ionic-angular';

/*
  Generated class for the Admin page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  selector: 'page-admin',
  templateUrl: 'admin.html'
})
export class AdminPage {
  data: any;
  public local: Storage;
  public getsession:any;

  constructor(public navCtrl: NavController) {
    this.data={};
    this.data.title="";
    this.data.desc="";
    this.local=new Storage(LocalStorage);
    this.local.set('session','true');

    this.getsession=this.local.get('session');
    this.getsession.then((value)=>{
      let x=value;
      console.log(x);

    })

  }

  ionViewDidLoad() {

  }

}

A: The ionic storage has moved to '@ionic/storage'
as of rc.0
so
import { Storage } from '@ionic/storage';

You can't specify whether its localstorage/sql or anything. But it uses each in order until its able to use one.
Just create an instance and use it
new Storage().set("key","value");

A: Old Question... but it just came up in my Google Results:
import { Storage } from '@ionic/storage';

Current as of RC4


Q: HTTP Post by android always return result 0 i supposed to send http post to web service in the form
POST[messageTitle, messageContent, messageFrom]
it's like array with the name post
i searched around and some people said i should do :
nameValuePairs.add(new BasicNameValuePair("POST[]", messageTitle.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("POST[]", messageContent.getId()));
nameValuePairs.add(new BasicNameValuePair("POST[]", messageFrom.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Execute HTTP Post Request

        try {
            HttpResponse response = httpclient.execute(httppost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            } else {
                Log.e("JSON", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
    Log.d("Cat", stringBuilder.toString());
}

but it returned {"result":0}
and supposed to return {"result":"row"}


Q: How to change the existing html text in a D3 rect? How to change the existing html text in a D3 rect to something else on the click of a button. There is an image on the top right corner of a D3 rect. When I click on that image the text inside the rect has to change to another html text like This is new text . It would be great if anyone could help me figure out a way to do it.
<!DOCTYPE html>

https://jsfiddle.net/passionateCoder/prh2acot/
I am not able to add an image to the JSFiddle.

A: This should work.

img.on('click', function () {
        txt.text('this is new text')
        });

Or for innerHTML:
img.on('click', function () {
        txt.html('this is new text')
        });

Remember that you cannot use traditional HTML in SVG Texts. Read here:
https://developer.mozilla.org/en-US/docs/Web/SVG/Element/text


Q: How to run on the page typed js I'm currently working on a project which requires me to run by the user typed javascript in the form of a string.
I've tried adding an empty <script> tag to the html and appending the string (containing the users freshly typed (after the page was loaded) javascript) to this script tag but this doesn't work. (since the code inside the script tag will be run immediately after the page is loaded).
So I tried a different approach. I wrapped the js string inside of a function like so:
function runCode() { userString }
This is what the string I now append to the empty script tag looks like:
var code = "function runCode() { "+ userString +" }"
However this still doesn't work. The code (userString) shows up in the script tag according to the chrome dev tools, but trying to run the function causes the following error:
Uncaught ReferenceError: runCode is not defined
Does somebody know how this works? What is the proper way for me to do this?
Some background:
The project I'm working on is an online tool to draw using js. The goal here is to use the two.js library and link it to a modified textarea. (codemirror) Clicking the button will take your typed in code and use it to modify the two.js canvas on the other half of the screen.
This will make it easier to draw using the library, since you don't have to set up all the html, css and js files yourself, but instead you can focus on the code.
Note: The js you type into the textarea can by any valid js, so simple things as alerts, or even jQuery lines will work just fine.

A: Use eval() function.
However be aware that this is by design a HUGE hole of security.

A: You have to use eval(). Extract the user input from an onclick event and pass it into eval like so:
eval(userString)


Q: How do I get the real error message in HttpClient response.ReasonPhrase? My Setting
I have 2 WebApi projects with the following flow:

*

*User makes request to API 1

*API 1 makes request to API 2 on behalf of the user (using an HttpClient).

using (var client = new HttpClient())
{
    client.SetBearerToken(token);

    string endpoint = PbbSettings.Identity.Users.Delete.Replace("{userId}", userId);

    // Attempt deletion of the user
    using (var response = await client.DeleteAsync(endpoint))
    {
        // Throw exception if not succeeded
        EnsureSuccess(response);
    }
}

The Problem
So the flow of control and information works fine.
The problem is that when API 2 responds with an error, response.ReasonPhrase says "Bad Request" or "Internal Server Error", instead of the message I set in the exception.
Been spitting blood on this for a whole day now. Any insights?
More Info (TLDR)
For clarity, all my APIs have a global exception filter registered to handle errors:
public class RepositoryExceptionsHandlerAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        HandleException(context);

        base.OnException(context);
    }

    public override Task OnExceptionAsync(HttpActionExecutedContext context, CancellationToken cancellationToken)
    {
        HandleException(context);

        return base.OnExceptionAsync(context, cancellationToken);
    }

    /// <summary>
    /// Recognizes common repository exceptions and if necessary creates a response and updates the context.
    /// </summary>
    /// <param name="context">The context in which the exception was thrown.</param>
    private void HandleException(HttpActionExecutedContext context)
    {
        var response = CreateResponse(context.Request, context.Exception);

        if (response != null)
            context.Response = response;
    }

    /// <summary>
    /// Recognizes common repository exceptions and creates a corresponding error response.
    /// </summary>
    /// <param name="request">The request to which the response should be created.</param>
    /// <param name="ex">The exception to handle.</param>
    /// <returns>An error response containing the status code and exception data, or null if this is not a common exception.</returns>
    private HttpResponseMessage CreateResponse(HttpRequestMessage request, Exception ex)
    {
        string message = ex.Message;

        if (ex is KeyNotFoundException)        return request.CreateErrorResponse(HttpStatusCode.NotFound, message);
        if (ex is ArgumentException)           return request.CreateErrorResponse(HttpStatusCode.BadRequest, message);
        if (ex is InvalidOperationException)   return request.CreateErrorResponse(HttpStatusCode.BadRequest, message);
        if (ex is UnauthorizedAccessException) return request.CreateErrorResponse(HttpStatusCode.Unauthorized, message);
#if !DEBUG
        // For security reasons, when an exception is not handled the system should return a general error, not exposing the real error information
        // In development time, the programmer will need the details of the error, so this general message is disabled.
        request.CreateErrorResponse(HttpStatusCode.InternalServerError, Errors.InternalServerError);
#endif

        return null;
    }
}

This works fine between the user and API 1.
But when API 1 and API 2 do their thing, the response creation ignores the message I put in and sets the status as the reason.

A: The new CreateResponse() method:
    /// <summary>
    /// Recognizes common repository exceptions and creates a corresponding error response.
    /// </summary>
    /// <param name="request">The request to which the response should be created.</param>
    /// <param name="ex">The exception to handle.</param>
    /// <returns>An error response containing the status code and exception data, or null if this is not a common exception.</returns>
    private HttpResponseMessage CreateResponse(HttpRequestMessage request, Exception ex)
    {
        string message = ex.Message;

        HttpStatusCode code = 0;

        if      (ex is KeyNotFoundException)        code = HttpStatusCode.NotFound;
        else if (ex is ArgumentException)           code = HttpStatusCode.BadRequest;
        else if (ex is InvalidOperationException)   code = HttpStatusCode.BadRequest;
        else if (ex is UnauthorizedAccessException) code = HttpStatusCode.Unauthorized;
        else if (ex is HttpException)
        {
            // HttpExceptions are thrown when request between IdentityServer and the API server have failed.
            // IdentityServer has generated an error, the API server received it and now it needs to relay it back to the client.
            var httpException = (HttpException) ex;

            code = (HttpStatusCode) httpException.GetHttpCode();
            message = httpException.Message;
        }
        else
        {
            code = HttpStatusCode.InternalServerError;

            // For security reasons, when an exception is not handled the system should return a general error, not exposing the real error information
            // In development time, the programmer will need the details of the error, so this general message is disabled.
#if DEBUG
            message = ex.Message;
#else
            message = Errors.InternalServerError;
#endif
        }

        // For some reason the request.CreateErrorResponse() method ignores the message given to it and parses its own message.
        // The error response is constructed manually.
        return CreateErrorResponse(request, code, message);
    }

    private HttpResponseMessage CreateErrorResponse(HttpRequestMessage request, HttpStatusCode code, string message)
    {
        var content = new { Message = message };

        return new HttpResponseMessage(code)
        {
            ReasonPhrase = message,
            RequestMessage = request,
            Content = new ObjectContent(content.GetType(), content, new JsonMediaTypeFormatter())
        };
    }
}

Hope this just saved someone's day... ;)


Q: error: could not find or load main class First.class I have made program in java using netbeans. it is located in d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp. its name is First.java. it is running successfully and showing output in netbeans IDE. but when i m trying to run it through cmd its showing the above error.
PATH is set to c:\program files\java\jdk1.7.0_07\bin
classpath is set to .
i have also tried setting classpath to c:\program files\java\jdk1.7.0_07\bin but there was no change in the error..
javac First.java is running and CLASS file is getting created in the same folder where the program is.
please help me out.. i cannot debug it..

A: Most probably you are missing execution using package name.
You would be executing main class from src directory as :
D:\sudhanshu\documents\netbeansprojects\Firstapp\src> java firstapp.First

A: If your package is : somepackage,
And you have saved your .java file at: d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp
then in command prompt, go to the above directory and compile using: -
javac -d . First.java   // Don't use javac First.java

Then your class file will be created inside the folder somepackage inside the above path..
i.e. your class file will be at d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp\somepackage\First.class
Then you should go at the directory where your .java. file is saved, and run as: -
java First

From d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp directory..
If you want to run this class file from anywhere: -
Add d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp directory in your classpath..
Note: - You need to add the directory containing your package directory to classpath..

A: - If you are able to create a .class file then i think you have successfully installed your Java
Tip:
Always do a java -version on the command prompt, and if it returns with the version of JDK installed on your system, then you have successfully installed your Java.
- Now i will advice you to do this from the same directory where you class file is located to execute the file.
java First


Q: Character encoding for US Census Cartographic Boundary Files I'm trying to import the US Census cartographic boundary files (available here: http://www.census.gov/geo/www/cob/bdy_files.html ) into a GeoDjango application.  However, python is complaining about UnicodeDecodeErrors (for example, for the non-ascii characters in Puerto Rico).
The shapefile description file (*.dbf) doesn't specify what character encoding it uses; this is not defined by the spec for shapefiles.  What is the correct character encoding to use?

A: I was having the same issue with CBSA and Place data from 2010 Census full geometry shapes. These are not the clipped carto files.
IBM850 Did not work correctly for me. On a whim, I tried latin1 and it worked perfectly.

A: The US Census cartographic boundary files use the IBM850 character encoding.  Python code to properly encode these strings would be as follows:
unicode(featurestring.decode("IBM850"))


Q: Force Chromewebdriver to download text,jpg instead of opening in a new tab I have a need to download txt and jpg files that are basically links in a web page. I am using chrome webdriver to do the same. My code to set the chrome settings is as below:
 prefs = {
      :download => {:prompt_for_download => false,:default_directory => download_directory} ,
      :managed_default_content_settings => {:images => 2 },
      :webprefs =>  {:loads_images_automatically  => 'false' }
  }
  @browser = Watir::Browser.new :chrome , :prefs => prefs

When I click on these links, I the files opens in a new window instead of a download prompt. Is there a way to force chrome webdriver NOT to open these automatically?


Q: Ajax call fails in IE with requests from HTTPS to HTTP I'm making a trivial ajax CORS request from HTTPS to HTTP, and it's working fine on every browser, except IE. It's not even trying to make a request and fails immediately. There is no error messages in console.
This fails even without trying (there is no network traffic), then executed from secure site:
$.ajax({
    url:'http://foo.bar'
}).done(function() {
    alert('success');
}).fail(function() {
    alert('fail');
});

I'm using IE 10 in Standards Mode. Is there any way to make it work with HTTP? It's obvious it blocks unsecure request from secure site, but maybe it's possible to change this using browser settings?

A: Unfortunatelly there seems to be no solution for this.
Your best alternative option (for quick solution) is to implement HTTPS (directly or as a proxy for external HTTP-only service) using self-signed certificate and add it to exception list.


Q: Getting undefined when using "var" instead of "let" with Object.assign() var name = {
  nameValue: 'John'
};
console.log(name.nameValue);  // undefined
var surname = {
  surnameValue: 'Doe'
};
Object.assign(name, surname);
console.log(name.surnameValue); // undefined

I am getting undefined when using var but everything is working good with let and
I am running this code on jsbin.com

A: Global scope (i.e. window in this case) already has a property name. You'll need to either create a new scope by wrapping your code with a function. Or use block scoped variable declaration let

console.log(typeof name); // string

var name = {
  nameValue: 'John'
};
console.log(name.nameValue); // undefined
var surname = {
  surnameValue: 'Doe'
};
Object.assign(name, surname);
console.log(name.surnameValue); // undefined

function run() {
  var name = {
    nameValue: 'John'
  };
  console.log(name.nameValue); // John
  var surname = {
    surnameValue: 'Doe'
  };
  Object.assign(name, surname);
  console.log(name.surnameValue); // Doe
}

run();

A: Because 'name' is existed in window, you can use other name of variable
var name0 = {
  nameValue: 'John'
};
console.log(name0.nameValue);

A: (Window.)name is a specific value of the global window object that can be used (but pretty uncommon) for setting forms and hyperlinks targets.
The name property is not read only but is limited to the primitive type string. Therefore, any value that you assign to window.name will turn into a string.
This is essentially why you got undefined when used name.nameValue. name is not an object.
var name = { hello: "world!" };
console.log(name + ' - ' + name.hello); // "[object Object] - undefined"
var name = "Hello World!"
console.log(name); // "Hello World!";

A: You are setting the variable name in the global scope in window object. When you set the value of name in window object, its get method will call the toString method.
As specified in here
var name = {first:"Vignesh"};
console.log(name); //(1)
console.log(name.first); //(2)

(1) will give the value [object Object] as string instead of {first: "Vignesh"}.
(2) depicts that you are accessing an unassigned property of a string. i.e., [object Object].first which becomes undefined.
You have to declare the name object in some other scope like if...else block, function block to achieve what you need.


Q: No ads error from adcontrol I'm checking out ads in a Windows Phone app for the first time.
When I tried with the test settings, the test app showed up.
When I replace the info by the applicationID and AdUnitId from PubCenter,
nothing at all appeared (when debugging on a device).
I suscribed to the erroroccured event:
  private void AdControlInBorder_ErrorOccurred(object sender, Microsoft.Advertising.AdErrorEventArgs e)
    {
        MessageBox.Show(e.Error.Message.ToString());
    }

And I get: "No ad available". This is about a second after the app started up.
Extra info: I'm in Belgium, checked it with the phone plugged to pc, unplugged,
I'm on wifi and I have internet available.

A: AdDUplex is just for promote your app not for gain money :) In your case, you can't have ads in debug mode. Send your app in beta test and look if ads is available. Pub center have the best fill rate in wp8  platform. But you need to choice your app usage. If you app is a type like rss flow or news you need ads because you will have a lot of users connected for a long time and frequently. If you app is a productivity app, you will add in app purchase or send your app like a paid app or donation. Don't forget if you add ads, the possibility to remove.


Q: Infinispan file system store plus sql database I am trying to use infinispan to achieve the following:
-   n JVM instances in cluster
-   All data replicated between one node and the remaining nodes
-   Data to be backed up by the filesystem to that the node can recover from the local file store
-   I want some specific data to be persisted in the database (sql) asynchronously, but first to be written on the filesystem synchronously and once the transaction has been committed – then trigger the asynchronous persistence to the sql database
What is unclear from the documentation, it seems I will have to do everything myself – and infinispan just gives me jgroups clustering
It is unclear also how to remove data from the file store once the sql persistence successfully takes place – within an “atomic” transaction.
So data replication aside, I must be able to:

*

*Store data to the local cache (in-memory and file-system)

*Recover from the local cache (if the JVM crashes) and/or remote caches

*For some data, add to the cache, then FS, then asynchronously persist and remove from the FS

It seems that I can do all of this obviously, but Infinispan vs. me using jgroups and do it myself?

A: Infinispan allows you to chain cache stores together (by defining multiple stores within the persistence XML section), and each can be configured to either be synchronous or asynchronous (see here). However, transactional persistence stores are not supported (see here)


Q: Transforming OLTP Relational Database to Data Warehousing Model What are the common design approaches taken in loading data from a typical Entity-Relationship OLTP database model into a Kimball star schema Data Warehouse/Marts model?

*

*Do you use a staging area to perform the transformation and then load into the warehouse?

*How do you link data between the warehouse and the OLTP database?

*Where/How do you manage the transformation process - in the database as sprocs, dts/ssis packages, or SQL from application code?

A: Personally, I tend to work as follows:

*

*Design the data warehouse first. In particular, design the tables that are needed as part of the DW, ignoring any staging tables.

*Design the ETL, using SSIS, but sometimes with SSIS calling stored procedures in the involved databases.

*If any staging tables are required as part of the ETL, fine, but at the same time make sure they get cleaned up. A staging table used only as part of a single series of ETL steps should be truncated after those steps are completed, with or without success.

*I have the SSIS packages refer to the OLTP database at least to pull data into the staging tables. Depending on the situation, they may process the OLTP tables directly into the data warehouse. All such queries are performed WITH(NOLOCK).

*Document, Document, Document. Make it clear what inputs are used by each package, and where the output goes. Make sure to document the criteria by which the input are selected (last 24 hours? since last success? new identity values? all rows?)

This has worked well for me, though I admit I haven't done many of these projects, nor any really large ones.

A: I'm currently working on a small/mid size dataware house. We're adopting some of the concepts that Kimball puts forward, i.e. the star scheme with fact and dimension tables. We structure it so that facts only join to dimensions (not fact to fact or dimension to dimension - but this is our choice, not saying it's the way it should be done), so we flatten all dimension joins to the fact table.
We use SSIS to move the data from the production DB -> source DB -> staging DB -> reporting DB (we probably could have have used less DBs, but that's the way it's fallen).
SSIS is really nice as it's lets you structure your data flows very logically. We use a combination of SSIS components and stored procs, where one nice feature of SSIS is the ability to provide SQL commands as a transform between a source/destination data-flow. This means we can call stored procs on every row if we want, which can be useful (albeit a bit slower).
We're also using a new SQL Server 2008 feature called change data capture (CDC) which allows you to audit all changes on a table (you can specify which columns you want to look at in those tables), so we use that on the production DB to tell what has changed so we can move just those records across to the source DB for processing.

A: I agree with the highly rated answer but thought I'd add the following:

* Do you use a staging area to perform the transformation and then

load into the warehouse?

It depends on the type of transformation whether it will require staging. Staging offers benefits of breaking the ETL into more manageable chunks, but also provides a working area that allows manipulations to take place on the data without affecting the warehouse. It can help to have (at least) some dimension lookups in a staging area which store the keys from the OLTP system and the key of the latest dim record, to use as a lookup when loading your fact records.
The transformation happens in the ETL process itself, but it may or may not require some staging to help it along the way.

* How do you link data between the warehouse and the OLTP database?

It is useful to load the business keys (or actual primary keys if available) into the data warehouse as a reference back to the OLTP system. Also, auditing in the DW process should record the lineage of each bit of data by recording the load process that has loaded it.

* Where/How do you manage the transformation process - in the

database as sprocs, dts/ssis packages,
  or SQL from application code?

This would typically be in SSIS packages, but often it is more performant to transform in the source query. Unfortunately this makes the source query quite complicated to understand and therefore maintain, so if performance is not an issue then transforming in the SSIS code is best. When you do this, this is another reason for having a staging area as then you can make more joins in the source query between different tables.

A: John Saunders' process explanation is a good.
If you are looking to implement a Datawarehouse project in SQL Server you will find all the information you require for the delivering the entire project within the excellent text "The Microsoft Data Warehouse Toolkit".
Funilly enough, one of the authors is Ralph Kimball :-)

A: You may want to take a look at Data Vault Modeling. It claims solving some loner term issues like changing attributes.


Q: Using Custom Font - Failed to decode downloaded font in Oracle Apex I'm trying to use some customized font in my application.
So i tried downloading Pacifico and trying to use in my application. But getting Failed to decode downloaded font and the font is not loading
Below is my CSS .
@font-face {
  font-family: 'MyWebFont';
  src:  url('#WORKSPACE_IMAGES#Pacifico.ttf')  format('ttf');
}

body {
    font-family: 'MyWebFont', sans-serif;
    font-weight: 300;
    line-height: 25px;
    font-size: 14px;
}

This is not working. So i tried converting this to .woff as per suggestions found in web and tried below. Even this is failing. I'm using Chrome 74.0 version . How to solve this?
@font-face {
  font-family: 'MyWebFont';
  src: url('#WORKSPACE_IMAGES#Pacifico.ttf')  format('ttf'),
       url('#WORKSPACE_IMAGES#Pacifico.woff')  format('woff'),
       url('#WORKSPACE_IMAGES#Pacifico.woff2')  format('woff2');
}

body {
    font-family: 'MyWebFont', sans-serif;
    font-weight: 300;
    line-height: 25px;
    font-size: 14px;
}

A: Problem here is you need upload the font into /i/
@font-face {
      font-family: "Pacifico";
      src: url("http://localhost:8080/i/Pacifico.ttf");
    }

body {
    font-family: "Pacifico", serif;
    font-weight: 300 !important;
    line-height: 25px !important;
    font-size: 14px !important;
}

I don't know why Apex is not resolving the #WORKSPACE_IMAGES# but you can upload the font in the web server. In my case I'm using tomcat


Q: usort Date Assistance I am trying, unsuccessfully, to sort my list by one of my template fields ($fields[3]) which is a text input field with a date inside it. The problem is that because of the format of the date it will not sort correctly because I guess it is just comparing numbers.
I think I need to change the dateformat before sorting occurs but have so far failed to do this.
I am trying to use the usort function like so (field 3 is the one with the date in which is formatted like this dd/mm/yyyy),
if (!function_exists('do_sort')) {
    function do_sort($a, $b) {
        return $a->fields[3] > $b->fields[3];
    }}

$data = $params['data'];
usort($data, 'do_sort');
$smarty->assign('sorted', $data);

This sorts the data but as before, because I haven't changed anything, not in the correct order. Can anyone help me reformat the date prior to sorting?
Many thanks
Chris

A: Managed to do it. If anyone else is interested I used the following function:
   function date_compare($a, $b)
    {
        $t1 = strtotime($a->fields[3]);
        $t2 = strtotime($b->fields[3]);
        return $t1 - $t2;
    }
    $data = $params['data'];
    usort($data, 'date_compare');
    $smarty->assign('sorted', $data);

A: Try converting the strings to timestamps first:
function do_sort($a, $b) {
    $aval = strtotime($a);
    $bval = strtotime($b);
    if ($aval == $bval) {
        return 0;
    }
    return $aval < $bval ? -1 : 1;
}


Q: How to get and convert back user's birthdate to/from a NSTimeInterval? Suppose, my birthdate is (mon/day/year) 10-05-1932 (as NSDate), how to convert this to NSTimeInterval.
Again, how to convert back that NSTimeInterval to NSDate back?
I tried using different methods of NSDate but haven't succeed yet.
What I'm doing?
NSString *strdate = @"10-05-1932";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MM-dd-yyyy"];
NSDate *date = [df dateFromString:strdate];
NSLog(@"%.f", -[date timeIntervalSinceNow]);

This logs 2616605071 (as on 4th September 2015 at 16:21) – When I checked it with the site like this it gives me wrong date.

A: NSTimeInterval timeInterval = date.timeIntervalSinceReferenceDate;
NSDate *anotherDate = [NSDate dateWithTimeIntervalSinceReferenceDate: timeInterval];

Try the code below. date and anotherDate will be identical.
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:10];
[components setMonth:5];
[components setYear:1934];
NSDate *date = [calendar dateFromComponents:components];
NSLog(@"%@", date);
NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
NSDate *anotherDate = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
NSLog(@"%@", anotherDate);

UPDATE:
It's incorrect because you get timestamp (time interval) from that website which use UNIX timestamp. Also, it's incorrect because you use timeIntervalSinceNow which will likely change every time you call the method because it's relative to the current time. If you want the date/time interval that compatible with that website. Use:
NSTimeInterval timeInterval = date.timeIntervalSince1970;
NSDate *anotherDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];

You can copy the timeInterval from the code above (-1188000000) and paste it on the website and it will give you a correct date.
Internally, NSDate store time interval relative to reference date (Jan 1st, 2001). The website you mentioned is UNIX timestamp that relative to Jan 1st, 1970.

A: This is just worked!
NSString *strdate = @"10-05-1932";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MM-dd-yyyy"];
NSDate *date = [df dateFromString:strdate];
NSLog(@"%@",date);
NSTimeInterval interval = [date timeIntervalSince1970];
NSLog(@"%f", interval);
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:interval];
NSLog(@"%@",date2);

Thanks to @sikhapol


Q: How do I retrieve disk information in C#? I would like to access information on the logical drives on my computer using C#. How should I accomplish this? Thanks!

A: If you want to get information for single/specific drive at your local machine. You can do it as follow using DriveInfo class:
//C Drive Path, this is useful when you are about to find a Drive root from a Location Path.
string path = "C:\\Windows";

//Find its root directory i.e "C:\\"
string rootDir = Directory.GetDirectoryRoot(path);

//Get all information of Drive i.e C
DriveInfo driveInfo = new DriveInfo(rootDir); //you can pass Drive path here e.g   DriveInfo("C:\\")

long availableFreeSpace = driveInfo.AvailableFreeSpace;
string driveFormat = driveInfo.DriveFormat;
string name = driveInfo.Name;
long totalSize = driveInfo.TotalSize;

A: For most information, you can use the DriveInfo class.
using System;
using System.IO;

class Info {
    public static void Main() {
        DriveInfo[] drives = DriveInfo.GetDrives();
        foreach (DriveInfo drive in drives) {
            //There are more attributes you can use.
            //Check the MSDN link for a complete example.
            Console.WriteLine(drive.Name);
            if (drive.IsReady) Console.WriteLine(drive.TotalSize);
        }
    }
}

A: What about mounted volumes, where you have no drive letter?
foreach( ManagementObject volume in
             new ManagementObjectSearcher("Select * from Win32_Volume" ).Get())
{
  if( volume["FreeSpace"] != null )
  {
    Console.WriteLine("{0} = {1} out of {2}",
                  volume["Name"],
                  ulong.Parse(volume["FreeSpace"].ToString()).ToString("#,##0"),
                  ulong.Parse(volume["Capacity"].ToString()).ToString("#,##0"));
  }
}

A: Use System.IO.DriveInfo class
http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx

A: Check the DriveInfo Class and see if it contains all the info that you need.

A: In ASP .NET Core 3.1, if you want to get code that works both on windows and on linux, you can get your drives as follows:
var drives = DriveInfo
    .GetDrives()
    .Where(d => d.DriveType == DriveType.Fixed)
    .Where(d => d.IsReady)
    .ToArray();

If you don't apply both wheres, you are going to get many drives if you run the code in linux (e.g. "/dev", "/sys", "/etc/hosts", etc.).
This is specially useful when developing an app to work in a Linux Docker container.


Q: Nesting flexbox layout causes scrollable area to misbehave I've read various questions about scrolling within flexbox but I seem to have a slightly more complicated version of what I've seen.  I have an editor that uses flexbox and contains a toolbar with many components that is scrollable, and this works fine on its own.  However, on the live site it's wrapped in a parent which is display:flex (for reasons I won't go into but this editor isn't the only component on the page), and as soon as the editor is put within this flex parent its scrollable area becomes full width, pushing the whole page wider than it should be.
In this snippet, all the 'Thumb Example' elements are supposed to be scrollable within their parent .image-thumbs-container respecting the page's overall width:800px limit, but they lay out and push their parent wider than that.  But, if you turn off the display:flex of the .product-page element, the scrolling then works.  I built this simplified example of just the editor to demonstrate the problem, and it worked fine, took me a while to realise it was a parent element that was causing the error.
[Edit] This snippet may not work as expected within StackOverflow, please see this identical Pen: https://codepen.io/neekfenwick/pen/NWbpqZg

body {
    background-color: lightgrey;
}
.page-container {
    width: 800px;
    background-color: white;
}

.product-page {
    display: flex; /* Disable me to make scrolling work */
    flex-wrap: wrap;
}
.uploads-container {
    text-align: left;
    white-space: nowrap;
    padding: 5px;
    border: 1px solid black;
    display: flex;
    box-sizing: border-box;
}

.uploads-scroller {
    overflow-x: scroll;
    flex: 1 1 auto;
    overflow-y: hidden;
}
.image-thumbs-container {
    border: initial;
}
.image-thumb {
    display: inline-block;
    width: 100px;
    border: solid 2px grey;
    border-radius: 5px;
    margin-right: 2px;
    vertical-align: top;
}
<!DOCTYPE html>

    <link rel="stylesheet" href="mock.css">
    <title>Mockup</title>

Page contains other content required to layout by flexbox.

File Upload
Widget Goes
Here

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Some complicated workspace content goes here.

Page contains other content required to layout by flexbox.

So, please bear in mind I don't want to alter anything above the .editor div.  A lot of our site relies on the .product-page CSS.  I can consider it, but, is it possible to fix this scrolling problem by only modifying elements from the .editor div and down?

A: You can fix this one by just setting 100% width on .editor.
Since the parent already has flex-wrap: wrap, this should work out just fine for you. The content below the editor will just wrap to below it.

.editor { /* <-- add this */
  width: 100%;
}

body {
    background-color: lightgrey;
}
.page-container {
    width: 800px;
    background-color: white;
}

.product-page {
    display: flex; /* Disable me to make scrolling work */
    flex-wrap: wrap;
}
.uploads-container {
    text-align: left;
    white-space: nowrap;
    padding: 5px;
    border: 1px solid black;
    display: flex;
    box-sizing: border-box;
}

.uploads-scroller {
    overflow-x: scroll;
    flex: 1 1 auto;
    overflow-y: hidden;
}
.image-thumbs-container {
    border: initial;
}
.image-thumb {
    display: inline-block;
    width: 100px;
    border: solid 2px grey;
    border-radius: 5px;
    margin-right: 2px;
    vertical-align: top;
}
<!DOCTYPE html>

    <link rel="stylesheet" href="mock.css">
    <title>Mockup</title>

Page contains other content required to layout by flexbox.

File Upload
Widget Goes
Here

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Thumb
Example

Some complicated workspace content goes here.

Page contains other content required to layout by flexbox.

A: Add width: 100% to your .editor element.
Or, just in case you really needed to, add max-width: 800px to any of the following elements... .editor, .uploads-container, or .uploads-container


Q: How can I DRY out this Ruby Code How can I DRY out the following Ruby Code:
    x = 'a random string to be formated'
    x = x.split('^')[0] if x.include?('^')
    x = x.split('$')[0] if x.include?('$')
    x = x.split('*')[0] if x.include?('*')

I'm looking for the amazingly elegant ruby one liner but I'm having a hard time finding it.
It should probably be somewhat readable though.
Thanks

A: I think this might be what you're looking for

x.split(/\^|\$|\*/)

A: This works for me:
x = "a random string to be formatted"
['^', '$', '*'].each { |token|
  x = x.split(token)[0] if x.include?(token)
}

A: Based on the code you provided
x = 'a random string to be formated'

%w(^ $ *).each do |symbol|
  x = x.split(symbol)[0] if x.include?(symbol)
end

A: You're looking for this regex:
string.match(/^([^^$*]+)[$^*]?/).captures[0]

It returns all characters up the the first occasion of $, ^, or *, or the end of the string.


Q: Is there a magic method that gets called when I write **object_identifier? Consider the use of the double-star notation in python:
instance = NotDictionary(name="", description="")
print( **instance )

Is there any way I can control the resulting value of the expression
**instance

In python?
What methods or what parent must my object have, in order to be treated as a 'expandable' dict in this instance?
For instance, in the same way I can control addition between two objects by the add and radd methods?


Q: error when defining function inside another function in fortran For some use I need to define a function inside another function inside a fortran module.
A sample code for easy comprehension is
module func
implicit none
contains

real function f(x,y)
real x,y,g

real function g(r)
real r
g=r
end function g

f=x*g(y)
end function f
end module func

use func
implicit none

write(*,*) f(1.0,1.0)
end

This is giving lots of errors in gfortran like unexpected data declaration, expected end function f, not g....etc.
What is the correct way of defining a function inside another function in fortran?

A: You use an internal subprogram, see below. Note internal subprograms themselves can not contain internal subprograms.
ian@eris:~/work/stack$ cat contained.f90
Module func

  Implicit None

Contains

  Real Function f(x,y)

    ! Interface explicit so don't need to declare g
    Real x,y

    f=x*g(y)

  Contains

    Real Function g(r)
      Real r
      g=r
    End Function g

  End Function f

End Module func

Program testit

  Use func

  Implicit None

  Write(*,*) f(1.0,1.0)

End Program testit
ian@eris:~/work/stack$ gfortran-8 -std=f2008 -Wall -Wextra -fcheck=all -O -g contained.f90
ian@eris:~/work/stack$ ./a.out
   1.00000000
ian@eris:~/work/stack$


Q: connection oracle 11g with java 8 (eclipse) I can't import java.sql.*; because it said that this package is not accessible although I put ojdbc6 and also I tried ojdbc8 in the classpath but it isn't work;
[ I mention that I have oracle 11g and jdk 10 & eclipse 4 ]

A: How did you add your ojdbc driver ? A typical way is shown below:
First you need to right click your project and go for "Build Path" and go for "Configure build Path"

Then , in the "libraries" tab, click on the "Add External JARs" go to your ojdbc driver file to load it.

This is the typical way to load your ojdbc driver. Try first see whether it will help

A: If your IDE (Eclipse) gives error:
The package java.sql is not accessible

Or if compiling using javac gives error:
test\Test.java:3: error: package java.sql is not visible
import java.sql.*;
           ^
  (package java.sql is declared in module java.sql, but module Test does not read it)
1 error

Then it is because your Java 9+ project has a module-info.java file, i.e. your project is modular.
You need to add the following line to the module-info.java file:
    requires java.sql;


Q: UITableView Content Offset Increasing Unexpectedly I have a UITableView embedded in a navigation controller. When i segue from the TableView onto the next screen, i store the offset such that if i press the 'back' button, the offset on the original view remains the same, and it doesnt scroll up to the top.
var tableViewContentOffset = CGPointMake(0.0, 0.0)

override func viewWillAppear(animated: Bool) {
    super.viewDidAppear(animated)
    tableView.contentOffset = tableViewContentOffset
}

override func viewWillDisappear(animated: Bool) {
    super.viewDidDisappear(animated)
    tableViewContentOffset = tableView.contentOffset
}

This works perfectly when the view loads the first time, however each time i move onto the next screen and then return, the offset is increased by y(-64.0)
What is causing this?
First time loaded:

After Segueing and returning once:

A: You can set automaticallyAdjustScrollViewInsets to false.


Q: nginx not serving correct react build content I have a react app. When I build my app via the dev server (localhost: 3000), the app is served correctly with the correct styling etc.
However, when I serve via nginx (via docker) I get a completely different UI? Does anyone know why this may be?
I don't think it is a docker issue. I am using webpack if this is something that I may need to look at?
My nginx config:
server {
  listen    80 default_server;
  listen    [::]:80 default_server;

  root /usr/share/nginx/html;

  location = / {
    try_files $uri /index.html;
  }
}

Dockerfile:
FROM nginx:1.16-alpine
COPY nginx/default.conf /etc/nginx/conf.d/default.conf
COPY public/ /usr/share/nginx/html/

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]


Q: Azure Functions scaling and concurrency using Queue triggers and functionAppScaleLimit on the Consumption Plan I have an Azure Function app on the Linux Consumption Plan that has two queue triggers. Both queue triggers have the batchSize parameter set to 1 because they can both use about 500 MB of memory each and I don't want to exceed the 1.5GB memory limit, so they should only be allowed to pick up one message at a time.
If I want to allow both of these queue triggers to run concurrently, but don't want them to scale beyond that, is setting the functionAppScaleLimit to 2 enough to achieve that?
Edit: added new examples, thank you @Hury Shen for providing the framework for these examples
Please see @Hury Shen's answer below for more details. I've tested three queue trigger scenarios. All use the following legend:

QueueTrigger with no functionAppScaleLimit

QueueTrigger with functionAppScaleLimit set to 2

QueueTrigger with functionAppScaleLimit set to 1

For now, I think I'm going to stick with the last example, but in the future I think I can safely set my functionAppScaleLimit to 2 or 3 if I upgrade to the premium plan. I also am going to test two queue triggers that listen to different storage queues with a functionAppScaleLimit of 2, but I suspect the safest thing for me to do is to create separate Azure Function apps for each queue trigger in that scenario.
Edit 2: add examples for two queue triggers within one function app
Here are the results when using two queue triggers within one Azure Function that are listening on two different storage queues. This is the legend for both queue triggers:

Both queue triggers running concurrently with functionAppScaleLimit set to 2

Both queue triggers running concurrently with functionAppScaleLimit set to 1

In the example where two queue triggers are running concurrently with functionAppScaleLimit set to 2 it looks like the scale limit is not working. Can someone from Microsoft please explain? There is no warning in the official documentation (https://learn.microsoft.com/en-us/azure/azure-functions/functions-scale#limit-scale-out) that this setting is in preview mode, yet we can clearly see that the Azure Function is scaling out to 4 instances when the limit is set to 2. In the following example, it looks like the limit is being respected, but the functionality is not what I want and we still see the waiting that is present in @Hury Shen's answer.
Conclusion
To limit concurrency and control scaling in Azure Functions with queue triggers, you must limit your Azure Function to use one queue trigger per function app and use the batchSize and functionAppScaleLimit settings. You will encounter race conditions and waiting that may lead to timeouts if you use more than one queue trigger.

A: Yes, you just need to set functionAppScaleLimit to 2. But there are some mechanisms about consumption plan you need to know. I test it in my side with batchSize as 1 and set functionAppScaleLimit to 2(I set WEBSITE_MAX_DYNAMIC_APPLICATION_SCALE_OUT as 2 in "Application settings" of function app instead of set functionAppScaleLimit, they are same). And I test with the code below:
import logging
import azure.functions as func
import time

def main(msg: func.QueueMessage) -> None:
    logging.info('=========sleep start')
    time.sleep(30)
    logging.info('=========sleep end')
    logging.info('Python queue trigger function processed a queue item: %s',
                 msg.get_body().decode('utf-8'))

Then I add message to the queue, I sent 10 messages: 111, 222, 333, 444, 555, 666, 777, 888, 999, 000, I sent them one by one. The function was triggered success and after a few minutes, we can see the logs in "Monitor". Click one of the log in "Monitor", we can see the logs show as:

I use 4 red boxes on the right of the screenshot above, I named each of the four logs as "s1", "s2", "s3", "s4"(step 1-4). And summarize the logs in excel for your reference:

I make cells from "s2" to "s4" as yellow because this period of time refer to the execution time of the function task.
According the screenshot of excel, we can infer the following points:
1. The maximum number of instances can only be extended to 2 because we can find it doesn't exist more than two yellow cells in each line of the excel table. So the function can not scale beyond 2 instances as you mentioned in your question.
2. You want  to allow both of these queue triggers to run concurrently, it can be implemented. But the instances will be scale out by mechanism of consumption. In simple terms, when one function instance be triggered by one message and hasn't completed the task, and now another message come in, it can not ensure another instance be used. The second message might be waiting on the first instance. We can not control whether another instance is enabled or not.
===============================Update==============================
As I'm not so clear about your description, I'm not sure how many storage queues you want to listen to and how many function apps and QueueTrigger functions you created in your side. I summarize my test result as below for your reference:
1. For your question about would the Maximum Burst you described on the premium plan behave differently than this ? I think if we choose premium plan, the instances will also be scale out with same mechanism of consumption plan.
2. If you have two storage queues need to be listen to, of course we should create two QueueTrigger functions to listen to each storage queue.
3. If you just have one storage queue need to be listen to, I test with three cases(I set max scale instances as 2 in all of three cases):
A) Create one QueueTrigger function in one function app to listen to one storage queue. This is what I test in my original answer, the excel table shows us the instances will scale out by mechanism of consumption plan and we can not control it.
B) Create two QueueTrigger functions in one function app to listen to same storage queue. The result is almost same with case A, we can not control how many instances be used to deal with the messages.
C) Create two function apps and create a QueueTrigger function in each of function app to listen to same storage queue. The result also similar to case A and B, the difference is the max instances can be scaled to 4 because I created two function apps(both of them can scale to 2 instances).
So in a word, I think all of the three cases are similar. Although we choose case 3, create two function apps with one QueueTrigger function in each of them. We also can not make sure the second message be deal with immediately, it still may be processed to first instance and wait for frist instance complete deal with the first message.
So the answer for your current question in this post is setting the functionAppScaleLimit to 2 enough to achieve that? is: If you want both of instances be enabled to run concurrently, we can't make sure of it. If you just want two instances to deal with the messages, the answer is yes.


Q: Lambda referencing itself Suppose I have a global function pointer like so:
void (*Callback)(My_special_t*);

If I want to assign it a lambda I do so like so:
Callback = [](My_special_t* instance) {
   //Useful stuff
};

What I really would like to do is something like this:
Callback = [](My_special_t* instance) {
   //Useful stuff
   Callback = /* Somehow get the current lambda? */
};

So my question is this:
Is it possible to reference the a lambda object from inside of itself.....and if so how?

A: I know lambda is very cool feature and because its coolness it is overused.
Trying forcing lambda here is creating a problem.
Just define a function and problem is resolved.
void myNiceFunction(My_special_t *instance) {
    instance->doStuff();

    … … …

    if (instance->next) {
        myNiceFunction(instance->next);
    }
}

It is better since it is self documenting (if good name is provided) and it is testable (test can reach this function directly).

A: You can do it with std::function, like this:
#include <functional>
#include <iostream>

using std::cout;
using std::function;

struct My_special_t
{
};

int main()
{
  function<void(My_special_t*)> Callback;

  auto otherCallback = [](My_special_t* instance)
  {
    cout << "otherCallback " << static_cast<void*>(instance) << "\n";
  };

  Callback = [&Callback, &otherCallback](My_special_t* instance)
  {
    cout << "first callback " << static_cast<void*>(instance) << "\n";
    Callback = otherCallback;
  };

  My_special_t special;
  Callback(&special);
  Callback(&special);
}