text:
Q: How does the module pattern know how to call the constructor here? What is the connection between the outer var Message and the inner var Message?
The Call
new Message ( element ).display( server_response_text.slice( 6 ) );

Object
var Message = ( function ()
{
    var messages =
    {
        name:         'Please enter a valid name',
        email:        'Please enter a valid email',
        email_s:      'Please enter a valid email.',
        pass:         'Please enter passoword, 6-40 characters',
        url:          'Please enter a valid url',
        title:        'Please enter a valid title',
        tweet:        'Please enter a valid tweet',
        empty:        'Please complete all fields',
        same:         'Please make emails equal',
        taken:        'Sorry, that email is taken',
        validate:     'Please contact support to reset your password',
    };
    var Message = function (element)
    {
        this.element = element;
    };
    Message.prototype.display = function( type )
    {
        this.element.innerHTML = messages[ type ];
        new Effects().fade( this.element, 'down', 4000 );
    };
    return Message;
} () );

My entire library is using the module pattern like this
    var NS = ( function ( window, undefined )
    {
    /*
    all code here including Message
    */
    } )( window );

A: These variable references are equal, despite of the same name.
Inside the anonymous function, Message is a locally declared constructor.
A reference to this constructor is returned at the end of the function.
Test for identity:
window.Message = ( function () {
    ...
    // Defer call
    setTimeout(function() {
        alert('Identity? ' + Message === window.Message);
    }, 100);
    return Message;
} () );

Picture:

*

*The green Message object (constructor) is defined within the red block (function).

*At the end of this function, the created green Message object is returned.

*Right after the creation of the function, it is invoked using (). The return value (the green box) is passed to the orange Message variable.

*Now, the orange Message variable points to the green Message object/constructor. To clarify: The green and orange Message variables refer to the same object.

*An instance of this constructor is created using the new operator.

A: The outer Message gets set to the result of an immediate function call (the "( function ()...").  The return value of the immediate function is the inner Message, which is also set to a function (just after "var messages" close scope, the "var Message = function(element)" function.).
When you call new Message outside of this code, it will call into the "var Message = function(element)" function to construct the object.
The reason to use this form is so that "messages" is kept in a closure -- essentially, it's private data.  Here's a commented version:
var Message = ( function ()     // Immediate function call
{
    // This is going to be private data - it's in a closure via the immediate function call
    var messages =
    {
        name:         'Please enter a valid name',
        email:        'Please enter a valid email',
        email_s:      'Please enter a valid email.',
        pass:         'Please enter passoword, 6-40 characters',
        url:          'Please enter a valid url',
        title:        'Please enter a valid title',
        tweet:        'Please enter a valid tweet',
        empty:        'Please complete all fields',
        same:         'Please make emails equal',
        taken:        'Sorry, that email is taken',
        validate:     'Please contact support to reset your password',
    };

    // This will be returned as the actual value of outer Message
    var Message = function (element)
    {
        this.element = element;
    };

    // This adds to the prototype so it will be found in all instances of Message objects
    Message.prototype.display = function( type )
    {
        this.element.innerHTML = messages[ type ];
        new Effects().fade( this.element, 'down', 4000 );
    };

    // This is the return value of the immediate function call and becomes outer Message
    return Message;
} () );

A: There is no relationship1 to the variable names at all.
It is just the name used inside. It might as well be fuubar:
var fuubar = function (element)
{
    this.element = element;
};
fuubar.prototype.display = function( type )
{
    this.element.innerHTML = messages[ type ];
    new Effects().fade( this.element, 'down', 4000 );
};
return fuubar; // the Object is returned, the Variable (Name) is not

It makes sense that the outer name is Message, because that is how it is "known" to others. 1The inner name was likely chosen for consistency, but otherwise does not affect semantics.
Constructors are just function-objects [designed to be] invoked with the new operator. Variables can name objects. In this case note that it is the function-object that is returned. Thus the function-object is known by the name Message (e.g. "is assigned to Message") outside. However, a variable is not an object.
Thus new X() evaluates the expression X, which must evaluate to a function-object, and then uses it as a constructor. (A constructor is just a normal function that expects to be used with new: it may perform initialization and establish a [[prototype]]). The name X is not important except insofar as it must evaluate to a function-object. Consider this equivalent form to show: new (X)(). The expression (X) is evaluated first.
So, let's break down the code:
var Message = (function () {
   // This function is invoked immediately, due to the
   // parenthesis immediately after the FunctionExpression.
   // As noted above the name Message used inside is not important.
   // What *IS* important is that a Constructor, which is just
   // a function-object (which is just an object) is returned.
   // This returned object will be assigned to (the outer)
   // Message variable. That is, it is "named by Message"
   // after the assignment occurs.
})()

// At this point Message will evaluate to a function-object
// (a Constructor in particular).
Message instanceof Function // -> true

// And we can use it to create new messages:
var messageA = new Message("a")
var messageB = new Message("b")

Happy coding.


text:
Q: Jasper Report con JRBeanCollectionDataSource error ClassNotFoundException Estoy intentado ejecutar un Jasper Report dentro de una Aplicación Java con JSF.
Al invocar la creación del Jasper Report con un DataSource, que es una colleción de JavaBeans (JRBeanCollectionDataSource), me da un error al ejecutar:
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);

El dataSource se crea con:
Collection<SlaReportItem> slaItems =  new ArrayList<SlaReportItem>(reports.get(0).getItems());
final JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(slaItems);

El error es:

Caused by: java.lang.ClassNotFoundException: org.primefaces.model.ScheduleModel
       at >java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[?:1.8.0_221]
       at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[?:1.8.0_221]
       at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[?:1.8.0_221]
       at java.lang.Class.forName0(Native Method) ~[?:1.8.0_221]
       at java.lang.Class.forName(Class.java:348) ~[?:1.8.0_221]
       at >net.sf.jasperreports.engine.util.JRClassLoader.loadClassForRealName

Da la impresión que al crear el Report no encuentra las clases que configurar el DataSource.
Si alguien tiene ha tenido que pelear con algo parecido, agradecería su ayuda.

A: El problema finalmente era que la versión del jasper reports del JasperStudio era diferente de la versión que utilizaba en la aplicación.
En la applicación tenía la 6.12 y en el JasperStudio la 6.17.
Al utilizar el subreport compilado, daba la excepción de ClassNotFound.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery Uncaught TypeError with offset().left My code, visually anyway, works fine, but I keep getting "Uncaught TypeError: Cannot Read property 'left' of undefined" in my console.  I have no clue what might be causing it.
Specifically, the error is showing up on the following: line:
var left = $(this).siblings('li.active').offset().left - ($(this).parents('.hoverBar').offset().left + 20);**

The whole function for context:
 $('.hoverBar li').hover(function(){

        var left = $(this).offset().left - ($(this).parents('.hoverBar').offset().left + 20);
        var width = $(this).width() + "px";
        var sictranslate = "translate("+left+"px, 0px)";

        $(this).parent('ul').next('div.floatr').css({
            "width": width,
            "-ms-transform" : sictranslate,
            "-webkit-transform": sictranslate,
            "-moz-transform": sictranslate,
            "transform": sictranslate
        });

    },

    function(){

        var left = $(this).siblings('li.active').offset().left - ($(this).parents('.hoverBar').offset().left + 20);**
        var width = $(this).siblings('li.active').width() + "px";

        var sictranslate = "translate("+left+"px, 0px)";

        $(this).parent('ul').next('div.floatr').css({
            "width": width,
            "-ms-transform" : sictranslate,
            "-webkit-transform": sictranslate,
            "-moz-transform": sictranslate,
            "transform": sictranslate

        });

    }).click(function(){

        $(this).siblings('li').removeClass('active');

        $(this).addClass('active');

        return false;

    });

And some relevant HTML:

About

Mission

Board Members

Staff

Members

Task Forces

Events

Description

Registration with Outlook ICS

Online Payment

Email auto-reminders

Multiple registrants allowed

A: This is when a selector has no elements, offset returns undefined. Just wrap your code into
var $siblings = $(this).siblings('li.active');
if ($siblings.length) {
    var left = $siblings.offset().left
             - ($(this).parents('.hoverBar').offset().left + 20);
    var width = $siblings.width() + "px";

    //...
}

This way your selector is cached into the variable $siblings and doesn't run twice or more.

A: I copied your code to a jsFiddle:
http://jsfiddle.net/mswieboda/F4fnf/ and on line 16 you needed to add .parents('.hoverBar').find('li.active') like this:
var left = $(this).parents('.hoverBar').find('li.active').offset().left -
    ($(this).parents('.hoverBar').offset().left + 20);

This is because the hovered element $(this): .hoverBar > ul > li > ul > li > a was not a sibling of .hoverBar > ul > li.active you were trying to navigate to in the DOM.
This fixed the JS error you were receiving with trying .offset() on undefined since that jQuery element didn't exist.


text:
Q: I am having problems in displaying images in django project I am trying to display an uploaded image on my Django website, but it seems I am unable to display it. Can anyone tell me what I am doing wrong?
in settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

image is stored in
project/core/media/images/image_name.jpg

And the url i am getting after opening image in new tab is:
http://127.0.0.1:8000/media/images/Bill_JcVkQAX.jpg

DEBUG is true (if that helps somehow)
Any help will be greatly appreciated.
settings.py
in urls.py and image link
Edit: in models.py:
class Bill(models.Model):

username = models.CharField(max_length=250, default = 0)
Shop_name = models.CharField(max_length=250, default=0)
Date = models.DateTimeField(auto_now_add=True)
Shop_address = models.CharField(max_length=250, default=0)
Telephone_no = models.CharField(max_length=250, default=0)
Total_items = models.IntegerField(default=0)
Bill_amount = models.IntegerField(default=0)
Bill_picture = models.ImageField(upload_to='images/')


text:
Q: Cannot deserialize nested JSON using Retrofit (Android) I have JSON wrapped by "_embedded" tag like below:
{
  "_embedded" : {
    "events" : [ { ... }]}

I'm using retrofit with interface:
public interface IEventRest {
    @GET("/events/search/findByPlaceId")
    Observable<List<Event>> getEventList(@Query("placeId")String placeId);
}

And this is my REST class:
public class EventRest implements IEventRest {
Gson gson = new GsonBuilder()
        .registerTypeAdapter(Event[].class, new MyDeserializer())
        .create();

private Retrofit getRetrofitClient() {
    final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    final OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

    return new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(gson))
            .baseUrl(UrlUtils.URL)
            .client(client)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
}

@Override
public Observable<List<Event>> getEventList(String placeId) {
    final IEventRest placeRest = getRetrofitClient().create(IEventRest.class);

    return placeRest.getEventList(placeId)
            .subscribeOn(Schedulers.io())
            .observeOn(Schedulers.newThread());
}

private class MyDeserializer implements JsonDeserializer<List<Event>> {
    @Override
    public List<Event> deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
            throws JsonParseException {
        JsonElement content = je.getAsJsonObject().get("_embedded");

        Type collectionType = new TypeToken<Collection<Event>>(){}.getType();
        return new Gson().fromJson(content, collectionType);

    }
}
}

But calling placeRest.getEventList(placeId) throws exception:
java.lang.IllegalStateException: Exception thrown on Scheduler.Worker thread. Add `onError` handling.
  at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:57)
  at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
  at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:269)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
  at java.lang.Thread.run(Thread.java:818)
Caused by: rx.exceptions.OnErrorNotImplementedException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
  at rx.internal.util.InternalObservableUtils$ErrorNotImplementedAction.call(InternalObservableUtils.java:386)
  at rx.internal.util.InternalObservableUtils$ErrorNotImplementedAction.call(InternalObservableUtils.java:383)
  at rx.internal.util.ActionSubscriber.onError(ActionSubscriber.java:44)
  at rx.observers.SafeSubscriber._onError(SafeSubscriber.java:152)
  at rx.observers.SafeSubscriber.onError(SafeSubscriber.java:115)
  at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.checkTerminated(OperatorObserveOn.java:276)
  at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:219)
  at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
  at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
  at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:269)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
  at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
  at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:351)
  at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:80)
  at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
  at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
  at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
  at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:117)
  at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:211)
  at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
  at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$RequestArbiter.request(RxJavaCallAdapterFactory.java:171)
  at rx.internal.operators.OperatorSubscribeOn$1$1$1.request(OperatorSubscribeOn.java:80)
  at rx.Subscriber.setProducer(Subscriber.java:211)
  at rx.internal.operators.OperatorSubscribeOn$1$1.setProducer(OperatorSubscribeOn.java:76)
  at rx.Subscriber.setProducer(Subscriber.java:205)
  at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call(RxJavaCallAdapterFactory.java:152)
  at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call(RxJavaCallAdapterFactory.java:138)
  at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
  at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
  at rx.Observable.unsafeSubscribe(Observable.java:9860)
  at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
  at rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:221)

Could you help me to find out what is wrong? Thank you in advance.

A:
I have JSON wrapped by "_embedded" tag

And that is exactly the problem. Gson doesn't know that your data is wrapped, it only cares that at the string that it sees, it is an object.
Pulling the preview, from here... We get a total of three objects
Event.java
(This wasn't generated because you left out what the JSON looks like)
Embedded.java
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Embedded {

    @SerializedName("events")
    @Expose
    private List<Event> events = new ArrayList<Event>();

    public Embedded() {
    }

    public Embedded(List<Event> events) {
        this.events = events;
    }

    public List<Event> getEvents() {
        return events;
    }

    public void setEvents(List<Event> events) {
        this.events = events;
    }

}

Response.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Response {

    @SerializedName("_embedded")
    @Expose
    private Embedded embedded;

    public Response() {
    }

    public Response(Embedded embedded) {
        this.embedded = embedded;
    }

    public Embedded getEmbedded() {
        return embedded;
    }

    public void setEmbedded(Embedded embedded) {
        this.embedded = embedded;
    }

}

And, so now, Retrofit cares about a Call<Response>, which you can then call .getEmbedded().getEvents()

Or, you could mess around with MyDeserializer more, since that seems to be the issue with the existing code.


text:
Q: How to handle duplicates on other sites? Simple example: better way to import java script files and css files using CDN or from local machine
The exact duplicate is on programmers.se: Referencing external javascript vs. hosting my own copy
However, SO won't allow me to flag the other as a duplicate because it's on another site. I don't want to close as off-topic; should be on programmers.se, because it might lead the asker to post his question on programmers.se or a mod to move the question over there.
Adding a comment + closing as off-topic is the best thing I can think of, but it feels "incomplete".
Thoughts?

A: The comment you've already left pointing to the Programmers version is enough.
The Stack Overflow version of the question is not off topic for Stack Overflow, closing it just because a very similar question exists on another site wouldn't make much sense. The sites overlap a bit in expertise, some questions are perfectly on topic on both. However, there's a very good duplicate of it right here on Stack Overflow, so it won't really stay open for long.
If the question was completely off topic on Stack Overflow, flagging for moderation attention and asking for it to be migrated would have been appropriate. Assuming the moderators agreed with your flag, your comment would have quickly pointed us to the duplicate once the question reached our shores.

A: My best quess is that you should flag the question with it needs ♦ moderator attention and the in the other section you could provide the link of the duplicate question so the moderator can look at it. You should also leave a comment on the question linking to the programmers.se question and telling him that such questions belong on that site.

A: I feel that the current solution of "just put a link in the comments" is wrong for two reasons.
Firstly anyone digging through to answer old questions will stumble upon it as an unanswered question and may start working on a solution. Yes I know we should all read the comments but the fact of the matter when you look up the question it states "0 answers" which is false.
Secondly, and this is the more important case, when users are seeking answers and perform a search they too will see "0 answers". This makes the site less user friendly. Its bad enough that people tend to answer questions in the comments section, do we really need to force people to do it now?
Why wouldn't you allow from cross site answers when you already allow for duplicates. When something is flagged duplicate its not instantly deleted. Its flagged, a note is put on it stating its a duplicate an users can see see it and navigate to a solution. The current "solution" feels more like a work around for the fact that the site has a bug (sites can't communicate with each other), rather than being an actual solution. If more sites are going to be added with specific scope (see how there is vi.se and emacs.se and yet there are tons of so.se posts that already answered their questions), this really should be resolved much better. Otherwise you're going to have lots of duplicate effort or lots of questions with no answers.


text:
Q: hpux: strange dsf thing Running setboot
setboot
Primary bootpath : 0/1/1/0.0.0 (No dsf found)
HA Alternate bootpath : 0/0/2/0.0.0x0.0x0 (/dev/rdisk/disk3)
Alternate bootpath : 0/1/2/1 (LAN Interface)

My system boot fine,i don't understand why setboot doesn't see the dsf.
I tried
insf -e 0/1/1/0.0.0`

Nothing change.
Why?

A: That hardware path is not complete, probably the path to the disk is:
    0/1/1/0.0.0x0.0x0

Try this:
    ioscan -kfnN -H 0/1/1/0.0.0

You will get a line for the disk ending with "LUN path for diskX", like 0/1/1/0.0.0x0.0x0
Then, execute:
    # setboot -p 0/1/1/0.0.0x0.0x0

And your setboot output should be ok.
The system boots because that is the only disk it finds under that hardware path.


text:
Q: SQL nvarchar considerations What's your strategy for determining nvarchar column sizes say for a address field? Do you always use nvarchar(max) or a fixed maximum size?
There is nothing worse than data integration breaking due to too small columns.
What are possible implications of using nvarchar(max) vs. a fixed maximum varchar size? I understand there is something about indices getting too large but what about query performance? Is there anything else to consider?

A: One row or field per address line, perhaps 100 long.
In ye olden days, people had to write on an envelope. No need for War and Peace epic addresses
And how would you break out post code, country, town etc if it was one field.
Or lookups as Astander mentioned too.
Anyway, don't use max: there are some overhead because it's a BLOB datatype.


text:
Q: Extracting floating-point significand and exponent in NumPy I would like to be able to extract the significand and exponent of floating-point numbers in NumPy. Getting the exponent as an integer is fine and ok for the significand. Getting the significand as a bitfield would be even more convienient.
I am aware that Python floats have a hex method; however, I wish to use numpy.float32, numpy arrays, and ufuncs. I am also aware of the numpy view method that allows me to see the float as an integer and thus as a binary string:
>>> import numpy as np

>>> b = bin(np.float32(1.23456789).view(np.int32))
'0b111111100111100000011001010010'

>>> b[-23:] # extract last 23 bits of IEEE 754 binary32 float, is significand
'00111100000011001010010'

Extracting the exponent and sign in this way is not convenient, as leading 0s are dropped by bin. (I could left-pad to 32 bits with 0s though…)
In any case, because bin is not a ufunc, this is not convenient and I would have to iterate over the array.
Isn't there any more convenient approach to doing what I want?

A: GPhilio's comment triggered a more thorough search on SO which resulted in the following solution, based on an answer to "extracting mantissa and exponent from double in c#":
import numpy as np

def decompose(x: np.float32):
    """decomposes a float32 into negative, exponent, and significand"""
    negative = x < 0
    n = np.abs(x).view(np.int32) # discard sign (MSB now 0),
                                 # view bit string as int32
    exponent = (n >> 23) - 127 # drop significand, correct exponent offset
                               # 23 and 127 are specific to float32
    significand = n & np.int32(2**23 - 1) # second factor provides mask
                                          # to extract significand
    return (negative, exponent, significand)

This approach with bit-level operations of integers is actually more convenient that going to the actual bitstring itself.


text:
Q: React Native User Input Data Into API Link I need to make it so the user can fill out the form with the sport they want to find from Google Places API  on the filters page click submit and have the form they just filled out replace the text in the api link to filter the results. After some research im pretty sure you use +this.state.variable+  in the API Link and in the form you use value={this.state.variable}
My Fetch Request on the Results Page
fetchData() {
   fetch('https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=GooglePlacesAPIKey&radius=5000&keyword=+this.state.variable+&location=+this.state.geolocation+')
   .then((response) => response.json())
   .then((responseData) => {
       this.setState({
           dataSource: this.state.dataSource.cloneWithRows(responseData.results),
           isLoading: false
       });

   })
   .done();
 }

Filters Page
render(){
  return (
  <View style={styles.container}>
   <View style={styles.loginContainer}>

   <TextInput
    style={styles.searchInput}
    value={this.state.variable}
    onChange={this.handleChange.bind(this)}/>

   <TouchableHighlight
      style={styles.button}
      onPress={this.goToSpotlight.bind(this)}>
      <Text style={styles.buttonText}> Search </Text>
    </TouchableHighlight>
   </View>
  </View>

A: fetchData() {
   fetch('https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=GooglePlacesAPIKey&radius=5000&keyword=+this.state.variable+&location=+this.state.geolocation+')
   .then((response) => response.json())
   .then((responseData) => {
       this.setState({
           dataSource: this.state.dataSource.cloneWithRows(responseData.results),
           isLoading: false
       });

   })
   .done();
 }

You have an error in your query. It should be done by this way:
var query = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=GooglePlacesAPIKey&radius=5000&keyword=${this.state.variable}&location=${this.state.geolocation}`;


text:
Q: ASP.NET Development Server Restart EVERY Time If I make a change in my ASP.NET project using VS2008 or VS2010, I must stop the ASP.NET development server and restart it (usually by "View in Browser") to see the change reflected.
I'm having the exact same problem as this guy:
ASP.net development server needs restart every time
Except for me, his solution doesn't work: adding/changing the registry value at HKLM\Software\Microsoft\ASP.NET\FCNMode to 0 or 2 does nothing that I can see.
Now the crazy part -- I just upgraded to VS2010 assuming all of my problems would be solved.  I migrated my project to .NET 4.0 and did my "View in Browser" only for the exact same behavior to occur!  4.0 runs a completely different version of WebDev.WebServer, I thought for sure this would solve my issue!  Nope.
THEN I read about IIS Developer Express, just being released with WebMatrix, and I find how to get my website to load (command prompt) only for, you guessed it, the same issue to happen.  I have to kill the server and restart for my changes to be seen.
And the changes I'm talking about don't have to be code updates, they could be a simple HTML modification.  The server isn't recognizing the change and thus isn't serving me the new page.  CSS or JS files can be updated and seen without restart.
I'm just looking for some ideas as to what could be the problem.  Thoughts, please!?
Workstation:  Win7 64-bit, VS2008 and VS2010.

A: So the answer was with the FCNMode, but on Windows 7 64-bit the registry location is different, HKLM/Software/Wow6432Node/Microsoft/ASP.Net
I changed the FCNMode setting from 1 to 2 and without rebooting loaded everything up just fine.
Thanks to Brian over at the ASP.NET Forums for the solution!
http://forums.asp.net/p/1516728/4017980.aspx#4017980

A: I generally avoid using Cassini and configure my projects to use IIS 7 instead.  Any reason why you can't use IIS directly?


text:
Q: Collapse a div using jquery I have 2 divs side by side divA and divB. I have a maximize button on top of divB.
When I click on button on divB, the divB should occupy the space of divA and become bigger, divA should be collapsed.
While clicking once again , it should be restored to normal size.
How to get this functionality using jquery?

A: The answer is to use jQuery's toggle() or animate() function. Viraj Nalawade gave you a good example of how to use slideToggle and collapse one div.
I give you here another example that include two divs, side by side: jsfiddle or see snippet below:

var original_width=$("#divA").width();
var max_width=original_width*18/10;
var min_width=original_width*2/10;
var div_status = {};
$("button").click(function () {
    var parent = $(this).parent();
    var sibling = $(parent).siblings();
    var parent_id = $(parent).attr("id");
    var sibling_id = $(sibling).attr("id");

    if (div_status[parent_id]) {
        div_status[parent_id] = false;
    } else {
        div_status[parent_id] = true;
        div_status[sibling_id] = false;
    }

    if (div_status[parent_id]) {
        $(parent).animate({
            width: max_width+"px"
        });
        $(sibling).animate({
            width: min_width+"px"
        });
    } else {
        $(parent).animate({
            width: original_width+"px"
        });
        $(sibling).animate({
            width: original_width+"px"
        });
    }
});
#container {
    width:500px;
    float:left;
}
div.mobile {
    float:left;
    width:50%;
    height:200px;
}
#divA {
    background-color:red;
}
#divB {
    background-color:green;
}

        <button>divA</button>

        <button>divB</button>


text:
Q: Hacer una API POST en .NET Estoy tratando de hacer una API de tipo POST en .NET. Pero cuando lo pruebo en POSTMAN, no me regresa ningun codigo de respuesta, soy nuevo en .NET y c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace firstangular.Controllers

{
    [ApiController]

    // Api

    public class UsersController : ControllerBase
    {
        private Person[] people = new Person[] {
           new Person { id=1, Name="Ana", age=24 },
           new Person { id=2, Name="Joseph", age=20 }
        };

[HttpGet("users")]

    public ActionResult<Person> GetAll()
    {
        return Ok(
            this.people
        );
    }

[HttpPost("add_user")]

    public IActionResult AddClient(Person data)
    {
        for (int x = 0; x < this.people.GetLength(0); x++) {
            this.people[x] = data;
        }
        return Ok()
    }

}

Ahora que me doy cuenta con los GET no funcionan en POSTMAN, pero en el navegador si puedo ver los datos normales

En el navegador, las APIS GET me las muestras sin ningun problema, el problema es que postman no me agarra con esas APIS

A: el GET posiblemente no funcione en postman porque la uri termina con un slash y en el navegador no.
Respecto al POST, en la firma del método. Puntualmente en el parámetro Person no indicas que este valor viaja en el body de la petición.
public IActionResult AddClient([frombody]Person data)


text:
Q: Optional where clause using ISNULL I have stored procedures take multiple parameters (up to 7 or 8 in some cases) to be used to filter down the result set.  These parameters are optional (default NULL).  All non-NULL values passed in are to be used in the filter (i.e. it's boolean and instead of boolean or).
These queries usual end up looking like this...
SELECT *
FROM [MyTable]
WHERE (@Param1 IS NULL OR (@Param1 IS NOT NULL AND [Field1] = @Param1))
      AND (@Param2 IS NULL OR (@Param2 IS NOT NULL AND [Field2] = @Param2))
      AND (@Param3 ...

I'm aware that this is very inefficient, but due to the number of parameters it just isn't possible split them into individual queries.
So instead I tried doing the following...
SELECT *
FROM [MyTable]
WHERE [Field1] = ISNULL(@Param1, [Field1])
      AND [Field2] = ISNULL(@Param2, [Field2])
      AND [Field3] ...

However, the problem occurs when a field contains NULL and therefore the = operator simply doesn't work.
Is there a simple and efficient way of doing this so I can have a single query, using multiple "filter" parameters?  I'd prefer not to use dynamic SQL if at all possible.

A: Well, you could simplify your initial SQL down to this, since you've already tested for NULL in each clause.
SELECT *
FROM [MyTable]
WHERE (@Param1 IS NULL OR [Field1] = @Param1)
      AND (@Param2 IS NULL OR [Field2] = @Param2)
      AND (@Param3 ...

This isn't necessarily inefficient.  You would probably be wise to check for parameter sniffing issues if you routinely pass in parameter combinations that lead to wildly different execution plans.

A: An alternative to using "is null" is to do this comparison:
where coalesce(Field1, @Param1, '') = coalesce(@Param1, Field1, '') . . .

If one of Field1 or @Param1 have values, then the two COALESCEs return that value.  Only if both are NULL do you get to the third arguemnt.
It so happens that you can convert '' to any type, so that is also covered.  However, the use of the function tends to preclude the user of indexes.


text:
Q: upgrade from spring-security-saml2-core to Spring Security SAML2 service provider We are using spring-security-saml2-core for SSO Okta Integration for the web application.
GitHub:  https://github.com/spring-projects/spring-security-saml
This project is in maintenance mode and will each End-of-Life on 6 October 2021. Please use Spring Security's SAML support instead.
I need to upgrade SAML library to Spring Security SAML2 service provider
https://docs.spring.io/spring-security/site/docs/current/reference/html5/#servlet-saml2login
There are a few questions:
what is the SAMLEntryPoint equivalent class or option in the New library (SAML2 service provider)?
What is the process to initiate the SSO Flow from SP?


text:
Q: MySql trigger to replace text everybody!
I have a trigger to replace text BEFORE INSERT to table, i have a text in which need change one word
SET NEW.shipping_method = CASE WHEN NEW.shipping_method LIKE 'weight' THEN 'Svars' ELSE
NEW.shipping_method END

But this command change all text who contain word weight to svars.
Thanks
P.S. I read a documentation on sql but can't  find the correct definition

A: If you need to replace a word in text, then use replace():
SET NEW.shipping_method = REPLACE(NEW.shipping_method, 'weight', 'Svars')


text:
Q: ecto failing to create table in postgresql I am using Phoenix framework and following along in book programming phoenix.
The project was created using mix. The relevant config for the database user and password were updated as necessary.
The following commands are entered and the model defined
A model of users - this follows the example in the book:
defmodule Rumbl.User do

    use Rumbl.Web, :model
    schema "users" do
        field :name, :string
        field :username, :string
        field :password, :string, virtual: true
        field :password_hash, :string
        timestamps
    end
end

The steps of:

*

*mix ecto.create

*mix ecto.gen.migration create_user
Generates a xxxx_create_user.exs file

*mix ecto.migrate
Produces the update to schema_migrations but does not create the user table in PostgreSQL.
Curious as to what I might be doing wrong here.

A: After you run mix ecto.gen.migration create_user command, you will get a migration file doing nothing to the database.
You need to create the table yourself in the generated migration file:
  def change do
    create table(:users) do
      add :name, :string
      add :username, :string
      add :password_hash, :string

      timestamps()
    end
  end

After that, running mix ecto.migration should modify your database schema as you wish.


text:
Q: Outlook VBA oItem_ReplyAll stops triggering after an email draft is cancelled I am using the following code to input the name of an attachment in the text of the email I am replying to.
I use two near-identical scripts to handle Reply and Reply all. When I boot outlook they work fine, but sometime later they will fail. I can reproduce the failure by replying to an email and then cancelling the send.
If I send the email then the script works perfectly ad infinitum until I exit an email window instead of pressing send.
What is it about cancelling a send that causes the script to stop being called?
Option Explicit
Private WithEvents oExpl As Explorer
Private WithEvents oItem As MailItem
Private bDiscardEvents, Cancel As Boolean
Private strAtt, FinalMsg As String
Private oAtt As Attachment
Private oResponse As MailItem

' Reply All
Private Sub oItem_ReplyAll(ByVal Response As Object, Cancel As Boolean)

Dim FinalMsg As String
Dim olInspector As Outlook.Inspector
Dim olDocument As Word.Document
Dim olSelection As Word.Selection

If bDiscardEvents = True Or oItem.Attachments.Count = 0 Then
       Exit Sub
End If

Cancel = True
bDiscardEvents = True
strAtt = ""

Call GoodExtensions 'Detect extensions to be included and put them into strAtt

If strAtt = "" Then Exit Sub 'quit if there are no attachments
FinalMsg = "Attached" & ": " & strAtt

    Set oResponse = oItem.ReplyAll
    oResponse.Display
    If oResponse.BodyFormat = olFormatPlain Then oResponse.BodyFormat = olFormatHTML 'prevent plaintext emails causing problems

    Set olInspector = Application.ActiveInspector()
    Set olDocument = olInspector.WordEditor
    Set olSelection = olDocument.Application.Selection

 'Find the beginning of the email being replied to
With ActiveInspector.WordEditor.Application
    .Selection.WholeStory
    .Selection.Find.ClearFormatting
    With .Selection.Find
        .Text = "Subject:"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .Execute
    End With

    Dim SubjectFont As String 'capture formatting details from the "From:" text to allow blending
    Dim SubjectSize As Integer
    SubjectFont = .Selection.Font.Name
    SubjectSize = .Selection.Font.Size

    .Selection.MoveDown Unit:=wdLine, Count:=1, Extend:=wdMove
    .Selection.HomeKey Unit:=wdLine
    .Selection.EndKey Unit:=wdLine, Extend:=wdExtend
    If InStr(.Selection.Text, "mportance") <> 0 Then
    .Selection.MoveDown Unit:=wdLine, Count:=1, Extend:=wdMove
    End If

End With

'Insert the message and format it to blend in
olSelection.InsertBefore FinalMsg
olSelection.Font.Name = SubjectFont
olSelection.Font.Size = SubjectSize
olSelection.Font.Color = wdColorBlack
olSelection.EndKey Unit:=wdLine
olSelection.TypeParagraph

'Embolden the word "Attached:" to ensure formatting compatibilty
With ActiveInspector.WordEditor.Application
    .Selection.WholeStory
    .Selection.Find.ClearFormatting
    With .Selection.Find
        .Text = "Attached:"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .MatchCase = True
        .Execute
    End With

.Selection.Font.Bold = True
End With

bDiscardEvents = False
Set oItem = Nothing

End Sub

A: The problem is the use of the boolean bDiscardEvents - in particular its use in the test
If bDiscardEvents = True Or oItem.Attachments.Count = 0 Then
       Exit Sub
End If

Its use here leads to the subroutine always exiting prematurely if it is called after an exit from the routine before setting it false e.g. after If strAtt = "" Then Exit Sub has triggered.  The boolean is not required and can be removed.
The diagnosis is that this boolean has been used in some of Diane Poremsky's macros (www.slipstick.com/), which I'm sure your code inherits from. However here its not required. She herself replied on being queried about its use in a similar function to yours says

"In this version of the macro, it looks like its not doing anything...
in the original macro, it was used much like cancel. When the macro
was edited for this example, it wasn't removed. :("

A: It looks like setting the oItem to nothing at the end was what was causing problems. I can no longer replicate the problem with this line removed. My code is below.
' Reply All
Private Sub oItem_ReplyAll(ByVal Response As Object, Cancel As Boolean)

Dim FinalMsg As String
Dim olInspector As Outlook.Inspector
Dim olDocument As Word.Document
Dim olSelection As Word.Selection

If bDiscardEvents Or oItem.Attachments.Count = 0 Then
       Exit Sub
End If

Cancel = True
bDiscardEvents = True
strAtt = ""

Call GoodExtensions 'Detect extensions to be included and put them into strAtt

If strAtt = "" Then Exit Sub 'quit if there are no attachments
FinalMsg = "Attached" & ": " & strAtt

    Set oResponse = oItem.ReplyAll
    oResponse.Display
    If oResponse.BodyFormat = olFormatPlain Then oResponse.BodyFormat = olFormatHTML 'prevent plaintext emails causing problems

    Set olInspector = Application.ActiveInspector()
    Set olDocument = olInspector.WordEditor
    Set olSelection = olDocument.Application.Selection

 'Find the beginning of the email being replied to
With ActiveInspector.WordEditor.Application
    .Selection.WholeStory
    .Selection.Find.ClearFormatting
    With .Selection.Find
        .Text = "Subject:"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .Execute
    End With
    'capture formatting details from the "From:" text to allow blending
    Dim SubjectFont As String
    Dim SubjectSize As Integer
    Dim SubjectBold As Boolean
    SubjectFont = .Selection.Font.Name
    SubjectSize = .Selection.Font.Size
    SubjectBold = .Selection.Font.Bold

    .Selection.MoveDown Unit:=wdLine, Count:=1, Extend:=wdMove
    .Selection.HomeKey Unit:=wdLine
    .Selection.EndKey Unit:=wdLine, Extend:=wdExtend
    If InStr(.Selection.Text, "mportance") <> 0 Then
    .Selection.MoveDown Unit:=wdLine, Count:=1, Extend:=wdMove
    End If

End With

'Insert the message and format it to blend in
olSelection.InsertBefore FinalMsg
olSelection.Font.Name = SubjectFont
olSelection.Font.Size = SubjectSize
olSelection.Font.Color = wdColorBlack
olSelection.EndKey Unit:=wdLine
olSelection.TypeParagraph

'Embolden the word "Attached:" if necessary to ensure formatting compatibility
With ActiveInspector.WordEditor.Application
    .Selection.WholeStory
    .Selection.Find.ClearFormatting
    With .Selection.Find
        .Text = "Attached:"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .MatchCase = True
        .Execute
    End With

.Selection.Font.Bold = SubjectBold
End With

bDiscardEvents = False
'Set oItem = Nothing
Exit Sub

End Sub

A: It turns out I was still having the problem but the code now appears to work perfectly since removing the bdiscardevents criteria - I never diagnosed what this was even supposed to do.
I have pasted my entire ThisOutlookSession because it is only used for attachment detection and is intertwined in a way I am not confident to unravel. I would welcome any feedback.
Option Explicit
Private WithEvents oExpl As Explorer
Private WithEvents oItem As MailItem
Private bDiscardEvents, Cancel As Boolean
Private strAtt, FinalMsg As String
Private oAtt As Attachment
Private oResponse As MailItem

 Private Sub Application_Startup()
   Set oExpl = Application.ActiveExplorer
   bDiscardEvents = False
End Sub

Private Sub oExpl_SelectionChange()
   On Error Resume Next
   Set oItem = oExpl.Selection.item(1)
End Sub

' Reply
Private Sub oItem_Reply(ByVal Response As Object, Cancel As Boolean)
'''''''''''''''''''''''''''''''''''''''''''
' This adds the name of any attachments   '
' in an email to the reply of said email. '
'''''''''''''''''''''''''''''''''''''''''''

'Dim finalmsg As String
Dim olInspector As Outlook.Inspector
Dim olDocument As Word.Document
Dim olSelection As Word.Selection

If oItem.Attachments.Count = 0 Then
       Exit Sub
End If

Cancel = True
bDiscardEvents = True

Call GoodExtensions

If strAtt = "" Then Exit Sub
FinalMsg = "Attached" & ": " & strAtt

Set oResponse = oItem.Reply
oResponse.Display
If oResponse.BodyFormat = olFormatPlain Then oResponse.BodyFormat = olFormatHTML 'prevent plaintext emails causing problems

Call insertAttachmentList

bDiscardEvents = False
'Set oItem = Nothing

End Sub
' Reply All
Private Sub oItem_ReplyAll(ByVal Response As Object, Cancel As Boolean)
'''''''''''''''''''''''''''''''''''''''''''
' This adds the name of any attachments   '
' in an email to the reply of said email. '
'''''''''''''''''''''''''''''''''''''''''''

Dim olInspector As Outlook.Inspector
Dim olDocument As Word.Document
Dim olSelection As Word.Selection

If oItem.Attachments.Count = 0 then Exit Sub

Cancel = True
bDiscardEvents = True

Call GoodExtensions 'Detect extensions to be included and put them into strAtt

If strAtt = "" Then Exit Sub 'quit if there are no attachments
FinalMsg = "Attached" & ": " & strAtt

    Set oResponse = oItem.ReplyAll
    oResponse.Display
    If oResponse.BodyFormat = olFormatPlain Then oResponse.BodyFormat = olFormatHTML 'prevent plaintext emails causing problems

Call insertAttachmentList

bDiscardEvents = False
'Set oItem = Nothing
Exit Sub

End Sub
Sub insertAttachmentList()

 'Find the beginning of the email being replied to
With ActiveInspector.WordEditor.Application
    .Selection.WholeStory
    .Selection.Find.ClearFormatting
    With .Selection.Find
        .Text = "Subject:"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .Execute
    End With
    If Not InStr(.Selection.Text, "ubject") <> 0 Then
        msg = MsgBox("Subject line not found. Abort", vbCritical)
        Exit Sub
    End If
    'capture formatting details from the "From:" text to allow blending
    Dim SubjectFont As String
    Dim SubjectSize As Integer
    Dim SubjectBold As Boolean
    SubjectFont = .Selection.Font.Name
    SubjectSize = .Selection.Font.Size
    SubjectBold = .Selection.Font.Bold

    .Selection.MoveDown Unit:=wdLine, Count:=1, Extend:=wdMove
    .Selection.HomeKey Unit:=wdLine
    .Selection.EndKey Unit:=wdLine, Extend:=wdExtend
    If InStr(.Selection.Text, "mportance") <> 0 Then
    .Selection.MoveDown Unit:=wdLine, Count:=1, Extend:=wdMove
    End If

End With

'Insert the message and format it to blend in
With Application.ActiveInspector.WordEditor.Application.Selection
    .InsertBefore FinalMsg
    .Font.Name = SubjectFont
    .Font.Size = SubjectSize
    .Font.Color = wdColorBlack
    .EndKey Unit:=wdLine
    .TypeParagraph
End With

'Embolden the word "Attached:" if necessary to ensure formatting compatibility
With ActiveInspector.WordEditor.Application
    .Selection.WholeStory
    .Selection.Find.ClearFormatting
    With .Selection.Find
        .Text = "Attached:"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .MatchCase = True
        .Execute
    End With

.Selection.Font.Bold = SubjectBold
End With
MsgBox "Attachment text added"
End Sub

Sub GoodExtensions()
Dim AttachName As String
FinalMsg = ""
strAtt = ""
For Each oAtt In oItem.Attachments
AttachName = LCase(oAtt.FileName)
    If InStr(LCase(AttachName), "pdf") <> 0 Or InStr(LCase(AttachName), "xls") <> 0 Or InStr(LCase(AttachName), "doc") <> 0 _
            Or InStr(LCase(AttachName), "ppt") <> 0 Or InStr(LCase(AttachName), "msg") <> 0 Or InStr(LCase(AttachName), "mac") <> 0 _
            Or InStr(LCase(AttachName), "arc") <> 0 Or InStr(LCase(AttachName), "prj") <> 0 Or InStr(LCase(AttachName), "rsl") <> 0 _
            Or InStr(LCase(AttachName), "results") <> 0 Or InStr(LCase(AttachName), "screenshot") <> 0 Or InStr(LCase(AttachName), "vtc") <> 0 _
            Or InStr(LCase(AttachName), "BLANK_PARAMETER") <> 0 Or InStr(LCase(AttachName), "BLANK_PARAMETER") <> 0 Or InStr(LCase(AttachName), "BLANK_PARAMETER") <> 0 _
            Or oAtt.Size > 95200 Then
            strAtt = strAtt & "<" & oAtt.FileName & ">, "
    End If
Next oAtt

End Sub
'This sub inserts the name of any meaningful attachments just after the signature
Private Sub Application_ItemSend(ByVal item As Object, Cancel As Boolean)
Dim oAtt As Attachment
Dim strAtt, DateMark, ShortTime, FinalMsg, AttachName, TriggerText  As String
Dim olInspector, oInspector As Inspector
Dim olDocument, olSelection As Object
Dim NewMail As MailItem
Dim AttchCount, i As Integer
strAtt = ""
FinalMsg = ""
'Stop
TriggerText = "Company Registration 1702660" 'This must be the last line of your signature or other place you want to insert the attachment text. It needs to be present in every email.

If TypeOf item Is MailItem Then Set NewMail = item
If item.Class = olMeetingRequest Then Exit Sub

With NewMail
    AttchCount = .Attachments.Count

    If AttchCount > 0 Then
        For i = 1 To AttchCount
        AttachName = .Attachments.item(i).DisplayName
            If InStr(LCase(AttachName), "pdf") <> 0 Or InStr(LCase(AttachName), "xls") <> 0 Or InStr(LCase(AttachName), "doc") <> 0 _
            Or InStr(LCase(AttachName), "ppt") <> 0 Or InStr(LCase(AttachName), "msg") <> 0 Or InStr(LCase(AttachName), "mac") <> 0 _
            Or InStr(LCase(AttachName), "arc") <> 0 Or InStr(LCase(AttachName), "prj") <> 0 Or InStr(LCase(AttachName), "rsl") <> 0 _
            Or InStr(LCase(AttachName), "results") <> 0 Or InStr(LCase(AttachName), "screenshot") <> 0 Or InStr(LCase(AttachName), "BLANK_PARAMETER") <> 0 _
            Or .Attachments.item(i).Size > 95200 Then
                strAtt = strAtt & "[" & AttachName & "] " & "
"
            End If
        Next i
    End If
End With

' this section is an alternative method of getting attachment names
'For Each oAtt In Item.Attachments
'    If InStr(oAtt.FileName, "xls") <> 0 Or InStr(oAtt.FileName, "doc") <> 0 Or InStr(oAtt.FileName, "pdf") <> 0 Or InStr(oAtt.FileName, "ppt") <> 0 Or InStr(oAtt.FileName, "msg") <> 0 Or oAtt.Size > 95200 Then
'    strAtt = strAtt & "<<" & oAtt.FileName & ">> " & vbNewLine
'End If
'Next
'Set olInspector = Application.ActiveInspector()
'Set olDocument = olInspector.WordEditor
'Set olSelection = olDocument.Application.Selection

DateMark = "" '" (dated " & Date & ")" 'Not necessary when sub works well
If strAtt = "" Then 'Reduce risk of erroneous entries.
    FinalMsg = ""
    'Exit Sub
Else
    FinalMsg = "

" & "Files attached to this email" & DateMark & ":
" & vbNewLine & strAtt
End If

Dim inputArea, SearchTerm As String
Dim SignatureLine, FromLine, EndOfEmail As Integer

If Not item.BodyFormat = 2 Then item.BodyFormat = 2 'force use of html
item.HTMLBody = Replace(item.HTMLBody, TriggerText & ".", TriggerText & FinalMsg)
If Not FinalMsg = "" Then MsgBox Replace(FinalMsg, "
", vbNewLine)
'Stop
Exit Sub


text:
Q: try-catch for logging purposes? According to this answer: https://stackoverflow.com/a/1722991/680026
you should only use try-catch if you really do something there besides logging:

Don't catch an exception if you're only going to log the exception and
throw it up the stack. It serves no meaning and clutters code.

But what about logging information that are not available at the higher level?
eg:
private void AddSomethingToTable(string tablename, string fieldname) {
  try {
    InsertFieldToTable(tablename, fieldname);
  } catch (Exception ex) {
    log.ErrorFormat("Could not insert field '{0}' into table '{1}'", fieldname, tablename);
    throw;
  }
}

private void main() {
  try {
    AddSomethingToTable("users","firstname");
    AddSomethingToTable("users","lastname");
    AddSomethingToTable("users","age");
  } catch (Exception ex) {
    MessageToUser("Sorry. Saving did not work.",ex);
  }
}

As you can see: In my (completely made up) example I log the information about the field that did cause the error. This could be some good information to start finding the error.
So even though I only logged the error, this information could be crucial and be lost outside that method.
Is this a valid use of try-catch here or are there other suggested ways to log that? (I don't think that just always logging this info (regardless if an error occurred or not) would be a valid solution)

A: I think you answered your own question with

But what about logging information that are not available at a higher instance

and

this information could be crucial and be lost outside that method

I dislike hard and fast "always do X and never Y", because there are times where it is necessary to go against so-called "best practice" in order to do what is best for your application.
If logging the information is necessary to fix the issue, and you lose this information if you don't log it immediately, then log the information.

A: There is nothing wrong in what you are trying to do. The idea of the other question/answer was that it is better to log the error at the place where you really handle it. In .NET every exception contains a stack trace. This means that upper layer can report location in the code that has generated this error. Doing that in one place instead of many is way more meaningful. This was their idea.

A: From your linked quesion:

The basic rule of thumb for catching exceptions is to catch exceptions if and only if you have a meaningful way of handling them.

I put emphasis on "The basic rule of thumb" as it's not a law. It's a best practice. i.e. follow it until you have a good motivation to not do so.
If you catch exceptions to include information you probably should throw a new meaningful exception with more context information. something like:
try
{
    //kldfsdölsdöls
}
catch (Exception ex)
{
    throw new MoreDetailedException("Text with context data", ex);
}

That way you'll get all context information for each stack level collected into the same exception (since you included the inner exception in it). Thus the log entry in the top level will contain ALL information in the same line.

A:
But what about logging information that are not available at a higher
  instance?

You can pass those information back to caller while re-throwing the exception
private void AddSomethingToTable(string tablename, string fieldname) {
  try {
    InsertFieldToTable(tablename, fieldname);
  } catch (Exception ex) {
    string str = string.Format("Could not insert field '{0}' into table '{1}'", fieldname, tablename);
    throw new Exception(str, ex);
  }

}

A: We use the Try Catch block in a similar way you have suggested and it works well for us.
We have implemented ELMAH https://code.google.com/p/elmah/ which is great for logging untrapped errors. With a line of code in the Try Catch block you can also write trapped exceptions into the log.
Catch ex As Exception
            Elmah.ErrorSignal.FromCurrentContext.Raise(ex)
            Return False
 End Try

The error is handled (the relevant function returned false) and user doesn't get the Yellow Screen of Death, and we can look up full details of any errors in the log.


text:
Q: Creating a mock API for third party library in statically typed language? I have an application in VB/C# .NET which needs to interact with a third party API, but I would like to interface it out so I can use a mock API for testing purposes. Here are example API calls I would use in code:
RelayClient.AuthenticateUser(username, password, request, sessionID)
RelayClient.GetUserInfo(sessionID)

A few problems I am facing:

*

*RelayClient is NonInheritable/Static.

*RelayClient doesn't implement any interfaces.

*The API client library is closed source.

Is there any standard way of dealing with this situation?

A: If you don't want to roll your own abstraction, have a look at TypeMock Isolator- it uses profiler hooks to do runtime class-level mocking of pretty much anything, whether you own it or not. It actually does a runtime substitution of the type implementation and intercepts all the calls (eg, you don't need to subclass the type- as far as the CLR is concerned, you ARE the type).
It's commercial, but they do have a free trial. Depending on how big the thing you need to mock is, the $799 can be well worth the time abstracting/wrapping the entire API surface if it's not interface-based.

A: The way to do this would be to make your code work against 'middle-man' non-static classes, which internally use the static classes from your 3rd party API. You then mock out these 'middle-man' classes for your unit tests.
Something like... (untested code)
// your consuming class
public class MyClass
{
    private readonly RelayClientManager manager;

    public MyClass(RelayClientManager manager)
    {
        this.manager = manager;
    }

    public UserInfo GetUserInfo(int sessionID)
    {
        return manager.GetUserInfo(sessionID);
    }
}

// 'middle-man' class
public class RelayClientManager
{
    public UserInfo GetUserInfo(int sessionID)
    {
        return RelayClient.GetUserInfo(sessionID);
    }
}

// unit test (using xUnit.net and Moq)
[Fact]
public static void GetsUserInfo()
{
    // arrange
    var expected = new UserInfo();
    var manager = new Mock<RelayClientManager>();
    manager.Setup(x => x.GetUserInfo(0)).Returns(expected);
    var target = new MyClass(manager);

    // act
    var actual = target.GetUserInfo(0);

    // assert
    Assert.Equal(expected, actual);
}


text:
Q: RenderAction errors with No route in table only from certain pages, works on others I am using @{ Html.RenderAction("SectionNavigation", "Section"); } from within a layoutpage. When I got to any page loaded from my HomeController the action breaks with the error No route in the route table matches the supplied values. but if I go to any page loaded from my SectionController it loads fine. My understanding of the RenderAction is that the first string is the Action to render and the second string is the controller name. What could be going wrong? Also, I am using Attribute Routing.

A: I have spent the last hour experimenting with trying to get this to work and finally figured it out. This is broken because I have a RoutePrefix assigned to the SectionController where this action lives. If I comment out the prefix everything works fine. I ended up moving it to a base controller that they all inherit from, which also has other general actions in it. Once it was moved and I updated the RenderAction to @{ Html.RenderAction("SectionNavigation", "Base"); } everything is working fine.


text:
Q: django and ajax dropdown based on selected dropdown I am trying to do a dropdown menu based on the selected dropdown and filter these results.
Here what I  did so far:
project_dropdown_options.html:
<option value="">---------</option>
{% for sw in result %}
<option value="{{ sw.pk }}">{{ sw.pk  }}</option>
{% endfor %}

view.py: (I checked the result I am getting values.)
def projects_dropdown(request):
    id = request.GET.get('id')
    print(id)
    result = list(SWTypes.objects.filter(proje=int(id)).values('swtype'))
    return render(request, 'project_dropdown_options.html', {'result': result})

url.py
path('ajax/projects-sw/', views.projects_dropdown, name='ajax_projects_dropdown'),

Ajax script:

html page where the dropdown is:
<select name="projects">
 {% for instance in projects%}
 <option value={{ instance.id }}>{{ instance.project_title }}</option>
 {% endfor %}

    <form method="post" id="personForm" projects-drop-url="{% url 'ajax_projects_dropdown' %}" novalidate>
    {% csrf_token %}
    <select name="sw" id="sw">
    <option value="">Switch Type</option>

  </form>

I think I have error either with Ajax script or the html part where the dropdown menu is.Any idea where I am doing which error ? I am getting no error and I am getting no values at the second dropdowsn menu which is called "sw" and I am getting values of the first dropdown.

A: You are using values method in your QuerySet and only sending swtype field value in context while rendering project_dropdown_options.html
Either remove the values method
result = SWTypes.objects.filter(proje=int(id))

Or add pk as well to values
result = SWTypes.objects.filter(proje=int(id)).values('pk', 'swtype')

Also, you don't have to convert QuerySet to list, you can loop over Queryset as well in the template

<option value="">---------</option>
{% for sw in result %}
   <option value="{{ sw.pk }}">{{ sw.swtype }}</option>
{% endfor %}

UPDATE
Change your parent HTML as well, replace name attribute of select tag with id, as you have attached JQuery change event on id i.e $("#projects").change

   <select id="projects">
    {% for instance in projects%}
      <option value={{ instance.id }}>{{ instance.project_title }}</option>
    {% endfor %}
   </select>

    <form method="post" id="personForm" projects-drop-url="{% url 'ajax_projects_dropdown' %}" novalidate>
      {% csrf_token %}
      <select name="sw" id="sw">
         <option value="">Switch Type</option>
      </select>
    </form>

UPDATE 2
Change your ajax call, remove data property and append id to URL itself as a query parameter, and use document on event
$(document).on('change', 'select#projects', function () {
  var url = $("#personForm").attr("projects-drop-url");
  var id = $(this).val();

  console.log("urls and project_id", url, id);

  $.ajax({
     type: "GET",
     url: url + "?id="+ id,
     success: function (data) {
        $("#sw").html(data);
     }
  });

});


text:
Q: How Can I obtain HAC standard errors for my VAR model? I've seen similar questions to this but the solutions don't seem to apply to my situation.
Anyway, my data looks like this. All variables are I(0) after first differencing.
   diff.data.gdpg. diff.data.narrowmg. diff.data.inf. diff.data.stir. diff.data.xrusd.
1     -0.51271298           -1.823265     -1.6304108      -1.0116667       -1.1520946
2     -0.04111672            2.799135     -0.3754515      -0.8033333       -3.8242471
3     -1.27394110            1.171467     -1.0167953      -0.7600000       -0.3483001
4     -1.23568342            3.327228     -0.6832069      -0.9600000       -1.1126535
5      2.92195504            4.291975      0.8145149      -0.7100000        0.4041784
6      1.79054994            2.522487      0.9598156       0.6266667        0.3260302

( I know that it is technically not advised to first difference when using VAR but I'm not concerned with forecasting here. I just want to get an idea of the relationships across these variables).
Anyway, I use the vars package and run my VAR. I save the lmobject I would like to get the standard errors of to another variable.
varmodel <- VAR(newdata, p = 4, type = "const")
lmobject <- varmodel$varresult$diff.data.stir.

Finally, I use call vcovHAC on the object.
vcovHAC(lmobject)

which gives me the following error
Error in bread. %*% meat. : non-conformable arguments

Does anyone have any solutions?

A: I might be too late, but I will answer this anyway in case anybody else searches for the same problem. I guess your problem here was having a varest object after estimating your model with the VAR() function. For vcovHAC() no varest object is okay. While for vcovHC it is. If you want to get your HAC covariance matrix you should estimate your VAR Model with dynlm() for example. The lm object is okay for vcovHAC.


text:
Q: Testing a linux kernel in qemu I have just built the 3.13.3 kernel from kernel.org on my ubuntu 12.04 computer. I ran the make menuconfig command and then I did make which built the kernel and the modules. I want to run the kernel in the qemu emulator (qemu-system-x86_64) so I can start testing and building on top of it. Curently I am getting it to run with qemu-system-x86_64 -kernel bzImage however it is not booting properly. What changes should I make in order to make the kernel boot properly?

A: You need to have a bootable disk first of all. Have you tried booting without -kernel and specifying the disk to boot from ?
If and only if that works, then think about using -kernel as an optimization
to test out new kernels
Making a bootable disk can be a challenge unless you take the easy route and use dd to make a large empty file e.g.
sudo dd if=/dev/zero of=$OUTPUT_DISK bs=4096 count=524288

then boot qemu with the linux iso you downloaded and also tell it to use this disk (-hda) and let the installer set the disk up for you
If making a bootable disk by hand, I've done this a couple of times - not easy, but the following steps may help you. You need to format the disk, create partitions, install grub and then boot
Personally I would take the easy route and install to disk via linux installer
#!/bin/sh
#
# Change these settings
#
INPUT_ISO=mydownloadedlinux.iso
OUTPUT_DISK=mydisk
KERNEL_IMAGE_NAME=linux-kernel
QEMU=qemu-system-x86_64

#
# Stuff you should not need to change
#
TMP_BOOTDISK=/tmp/disk.$$
ISO_MOUNT_DIR=/mnt/iso

#
# Choose DOS or Linux disks
#
PARTITION_TYPE=ext2
MKFS_TYPE=ext2

#
# Mount the ISO
#
sudo mkdir -p $ISO_MOUNT_DIR
sudo umount $ISO_MOUNT_DIR 2>/dev/null
sudo mount -o loop -t iso9660 $INPUT_ISO $ISO_MOUNT_DIR

#
# Make a new disk
#
sudo dd if=/dev/zero of=$OUTPUT_DISK bs=4096 count=524288
LOOP=`sudo losetup -f --show $OUTPUT_DISK`
LOOPDEV=`echo $LOOP | sed 's/.*loop/loop/g'`
echo "Loopback device $LOOP, ($LOOPDEV)"

#
# Make two partitions on the disk
#
sudo parted -s $LOOP mktable msdos \
              mkpart primary $PARTITION_TYPE 32K 50% \
              mkpart primary $PARTITION_TYPE 50% 95%

#
# Make one bootable
#
sudo parted -s $LOOP set 1 boot on
sudo kpartx -l $LOOP
sudo kpartx -a $LOOP

#
# Make the filesystems
#
sudo mkfs.$MKFS_TYPE /dev/mapper/${LOOPDEV}p1
sudo mkfs.$MKFS_TYPE /dev/mapper/${LOOPDEV}p2

#
# List what we made
#
sudo kpartx -l -v $LOOP

#
# Mount this temporary disk so we can install grub on it
#
sudo mkdir -p $TMP_BOOTDISK
sudo mount /dev/mapper/${LOOPDEV}p1 $TMP_BOOTDISK
sudo grub-install --boot-directory=/$TMP_BOOTDISK $LOOP

#
# Make grub boot config
#
cat >/tmp/grub.cfg <<%%
serial
#terminal_input --append serial_com0
#terminal_output --append serial_com0
configfile /mybootfile
%%

cat >/tmp/mybootfile <<%%
set timeout=5
set default=0
menuentry 'mylinux' {
    insmod ext2
    set root='(hd0,1)'
    linux /$KERNEL_IMAGE_NAME bigphysarea=28000
    initrd /rootfs.img.gz
}
%%

#
# Just copy all the files off of the ISO into the mounted temp disk
# This would be the tricky part as you need enough so linux can boot
#
sudo cp -r $ISO_MOUNT_DIR/* $TMP_BOOTDISK

#
# But use our grub files we made above
#
sudo cp /tmp/grub.cfg $TMP_BOOTDISK/grub/grub.cfg
sudo cp /tmp/mybootfile $TMP_BOOTDISK/mybootfile

#
# Show all the files on the temp disk and then unmuont it
#
find $TMP_BOOTDISK
sudo umount $TMP_BOOTDISK
sudo losetup -d $LOOP

#
# Convert the temp disk from raw to vmdk format
#
sudo qemu-img convert $OUTPUT_DISK -O vmdk $OUTPUT_DISK.vmdk

#
# Boot the vmdk
#
sudo $QEMU -boot d -m 4096 \
    -enable-kvm \
    -drive file=$OUTPUT_DISK.vmdk,if=virtio,media=disk \
    -serial telnet:localhost:4444,nowait,server,telnet \
    -net nic,model=e1000,vlan=0 -net user \


text:
Q: Wrap text when column name is too long? I have this script that sends an email:
USE msdb
EXEC sp_send_dbmail
@profile_name = 'Mail list',
@recipients = 'bob.jones@company.com',
@subject = 'query results',
@body = 'Result from SELECT appended below.',
@execute_query_database = 'DB',
@query = 'exec usp_DisplayData'

The issue is that many of the columns (or their alias) are incredibly long, so the query result in the email will look something like this:
SDMI POS Sales Name SDMI POS Purchases
------------------- ------------------
1              Joe  3

Without html, is there a way that that I can wrap the text in the columns so it will look something like this in the email?
SDMI  POS Name SDMI POS
Sales          Purchases
--------- ---- ---------
1         Joe  3

usp_DisplayData is a simple query, looks something like this:
Create procedure usp_usp_DisplayData
as
select
cast(sales as varchar(16))  as 'SDMI POS Sales',
Name,
cast(purch as varchar(16))  as 'SDMI POS Purchases',
from Sales

A: You will have no luck, if you try to insert line-breaks into your column aliases. Plain text will always return to the first character after a line-break. This will not be aware of columns...
If possible (depending on the target system of your eMail), you should use HTML to format a table.
In your last comment you ask about the function of the linked answer.
dbo.CreateHTMLTable() takes one parameter of type XML as input (some more if you take the version with class names) and returns one single XML (which is XHTML actually).
The trick is, that the following returns one single, scalar XML
SELECT
(
   SELECT * FROM SomeWhere FOR XML RAW,TYPE
) AS TheXmlResult;

The inner SELECT returns as XML, this is wrapped in paranthesis, thus it will be a single column in the outer select. (For details, e.g. about ELEMENTS XSINIL, read the background of the linked answer).
The call is easy (be aware of the doubled paranthesis):
SELECT dbo.CreateHTMLTable((***your select here*** FOR XML RAW,ELEMENTS XSINIL))

That's it... The return value is the full xhtml-table.
sp_send_dbmail has got a parameter to specify the format as html. I think this is
@body_format = 'HTML'

Btw: Wrong usage of a Stored Procedure
Your stored procedure is the wrong tool for this (hammering a nail with a beer bottle works, but...)
Create procedure usp_usp_DisplayData
as
select
[...]

SPs are created to do something. Your SP does nothing else then reading. This is much better packed into a VIEW or, if there are parameters, into an inline table valued function...
You can put this SELECT directly into the statement calling the function above
DECLARE @body XML=
(
SELECT dbo.CreateHTMLTable
 (
  (
  select cast(sales as varchar(16)) as 'SDMI POS Sales'
        ,Name
        ,cast(purch as varchar(16))  as 'SDMI POS Purchases'
  from Sales
  FOR XML RAW,ELEMENTS XSINIL
  )
 )
);


text:
Q: Confusion regarding instances I thought I had a decent enough grasp on methods and classes from the BNR book and now that I've reached the end of the chapter on them it notes (under 'Sending bad messages')

What would happen if you sent the date class method to an NSDate
  instance or the timeIntervalSince1970 instance method to the NSDate
  class?

I'm so god damn confused now, I thought NSDate was a class? Why the hell is it referred to as an instance here? Aren't instances just variables found in a class/object? And what the hell are instance methods?

A: Instance methods are methods that can be invoked on an instance of a class and are defined with the '-' character :
- (void)instanceMethod;

A class method is a method which does not require an instance of the class and can be invoked on the class itself (defined with '+') :
+ (void)classMethod;

The question you are asked is what happens if you call an instance method on a class and vice versa (class method on an instance of a class) :
[NSDate timeIntervalSince1970]; // Instance method (timeIntervalSince1970) called on the class itself (NSDate)

NSDate *dateInstance = [NSDate date]; // NSDate instance defined as dateInstance;
[dateInstance date]; // class method (date) called on an instance of NSDate

EDIT :
Regarding your Cars example in the comments. If Car is a class and you want to create an instance of this class named volvo :
Car *volvo = [[Car alloc] init];

Regarding class variables, if you have a static declaration of a variable in the implementation file then yes it will be shared with all the instances (i.e. change it in one instance and it will be reflected in all other instances).
If it is declared as a member instance (i.e. non-static and declared in your class) then it will be unique per class instance.


text:
Q: How to execute different error messages depending on where a query failed in a transaction in pg-promise? how can I execute varying error messages depending on where a query failed, triggering a rollback, in my transaction?
I'll be using the sample code from the documentation:
db.tx(t => {
    // creating a sequence of transaction queries:
    const q1 = t.none(query);
    const q2 = t.one(query);
    const q3 = t.one(query);

    // returning a promise that determines a successful transaction:
    return t.batch([q1, q2, q3]); // all of the queries are to be resolved;
})
    .then(data => {
        // success, COMMIT was executed
    })
    .catch(error => {
        // failure, ROLLBACK was executed
    });

Preferred output is the following:

*

*if the transaction failed in q1:

res.json({error: true, message:"q1 failed"})

*

*if the transaction failed in q2:

res.json({error: true, message:"q2 failed"})

*

*if the transaction failed in q3:

res.json({error: true, message:"q2 failed"}), etc.

What I'm thinking is using a Switch statement to determine what error message to execute, although I don't have an idea on how to know what query failed in the transaction.
Thank you for your help!
P.S. I recently migrated from node-pg to pg-promise (which is why I'm a bit new with the API) due to having a hard time with transactions as recommended in my previous posts, and yeah, pg-promise made a lot of things easier the 1 day worth of refactoring code is worth it.

A: Since you are using method batch, you get BatchError thrown when the method fails, which has useful property data, among others:
.catch(err => {
    // find index of the first failed query:
    const errIdx = err.data.findIndex(e => !e.success);

    // do what you want here, based on the index;
});

Note that inside such error handler, err.data[errIdx].result is the same as err.first, representing the first error that occurred.


text:
Q: How to compare database query results with a string using Bean Shell Assertion in JMeter I am new to JMeter.
In my Test Plan I am using

*

*JDBC Connection Configuration to connect SQL database.

*JDBC Request to run the select query. And I used Variable Names field to store the FK_SiteId from the database response as shows below.

*I used Debug Sampler to print the FK_SiteId in the results. Please find the Debug result.

*I am using BeanShell Assertion to compare the Actual FK_SiteId with Expected FK_SiteId as shown below.

Please find the error message below.
2019-03-04 12:25:45,549 INFO o.a.j.e.StandardJMeterEngine: Running the test! 2019-03-04 12:25:45,549 INFO o.a.j.s.SampleEvent: List of sample_variables: [] 2019-03-04 12:25:45,549 INFO o.a.j.g.u.JMeterMenuBar: setRunning(true, *local*)
2019-03-04 12:25:45,661 INFO o.a.j.e.StandardJMeterEngine: Starting ThreadGroup: 1 : SQL Database Connection 2019-03-04 12:25:45,661 INFO o.a.j.e.StandardJMeterEngine: Starting 1 threads for group SQL Database Connection.
2019-03-04 12:25:45,661 INFO o.a.j.e.StandardJMeterEngine: Thread will continue on error
2019-03-04 12:25:45,661 INFO o.a.j.t.ThreadGroup: Starting thread group... number=1 threads=1 ramp-up=1 perThread=1000.0 delayedStart=false
2019-03-04 12:25:45,677 INFO o.a.j.t.ThreadGroup: Started thread group number 1
2019-03-04 12:25:45,677 INFO o.a.j.e.StandardJMeterEngine: All thread groups have been started
2019-03-04 12:25:45,677 INFO o.a.j.t.JMeterThread: Thread started: SQL Database Connection 1-1
2019-03-04 12:25:50,564 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``String ActialResult = vars.get(${FK_SiteId}); String ExpectedResult = "14001";   . . . '' : Typed variable declaration : Attempt to access property on undefined variable or class name
2019-03-04 12:25:50,564 WARN o.a.j.a.BeanShellAssertion: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval   Sourced file: inline evaluation of: ``String ActialResult = vars.get(${FK_SiteId}); String ExpectedResult = "14001";   . . . '' : Typed variable declaration : Attempt to access property on undefined variable or class name
2019-03-04 12:25:50,564 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``String ActialResult = vars.get(${FK_SiteId}); String ExpectedResult = "14001";   . . . '' : Typed variable declaration : Attempt to access property on undefined variable or class name
2019-03-04 12:25:50,564 WARN o.a.j.a.BeanShellAssertion: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval   Sourced file: inline evaluation of: ``String ActialResult = vars.get(${FK_SiteId}); String ExpectedResult
= "14001";   . . . '' : Typed variable declaration : Attempt to access property on undefined variable or class name
2019-03-04 12:25:50,564 INFO o.a.j.t.JMeterThread: Thread is done: SQL Database Connection 1-1
2019-03-04 12:25:50,564 INFO o.a.j.t.JMeterThread: Thread finished: SQL Database Connection 1-1
2019-03-04 12:25:50,564 INFO o.a.j.e.StandardJMeterEngine: Notifying test listeners of end of test
2019-03-04 12:25:50,564 INFO o.a.j.g.u.JMeterMenuBar: setRunning(false, *local*)

Can anyone tell me where I am going wrong

A: Your variable was saved as FK_SiteId_1. You can access this variable by
vars.get("FK_SiteId_1")  or directly ${FK_SiteId_1}
Use log.info(... to check the variable value
I prefer to use vars.get solution.


text:
Q: Saving data into database using create function laravel I am having trouble saving this into database. When I submit my data into database it will only show name_of_bear and all the many relationship stuff(type_of_fish) but not the type_of_bear
Can someone explain to me why it can't work and also maybe give me an example on how it should be done. Thank you
Controller: (this works)
public function submit(Request $request)
{
    $fishType= $request->input('type_of_fish');
    $Name = $request->input('Name');
    $bearType = $request->input('bearType');

    $bear = Bear::create(['Name' => $request->input('name_of_bear')]);
    $bear->fishs()->create(['type_of_fish' => json_encode($fishType)]);

    return ('thank you');

}

But if I were to do this:
Controller : (doesn't work)
public function submit(Request $request)
{
    $fishType= $request->input('type_of_fish');
    $Name = $request->input('Name');
    $bearType = $request->input('bearType');

    $bear = Bear::create(['Name' => $Name]);
    $bear = Bear::create(['bearType' => $bearType]); --> doesn't  work if add in this
    $bear->fishs()->create(['type_of_fish' => json_encode($fishType)]);

    return ('thank you');

}

or this:
Controller: (doesn't work)
public function submit(Request $request)
{
    $fishType= $request->input('type_of_fish');
    $Name = $request->input('Name');
    $bearType = $request->input('bearType');

    $bear = Bear::create(['Name' => $Name], ['bearType' => $bearType]); --> doesn't work
    $bear->fishs()->create(['type_of_fish' => json_encode($fishType)]);

    return ('thank you');

}

A: You can add it like this
$bear = Bear::create(['Name' => $Name , 'bearType' => $bearType]);

full code:
public function submit(Request $request)
{
    $fishType= $request->input('type_of_fish');
    $Name = $request->input('Name');
    $bearType = $request->input('bearType');

    $bear = Bear::create(['Name' => $Name , 'bearType' => $bearType]);
    return ('thank you');
} // removed extra }

For further information you can read documentation

A: You can just use:
$bear = Bear::create(['Name' => $Name, 'bearType' => $bearType]);
For more info, visit this link.

A: You can insert data like this:
public function submit(Request $request)
{
    $data = array();
    $data['type_of_fish']= $request->type_of_fish;
    $data['Name'] = $request->Name;
    $data['bearType'] = $request->bearType;

    $bear = Bear::create($data);

    return ('thank you');

}

For more information read Documentation

A: I would do it like this, assuming that post array keys matches column names.
$bear = Bear::create($request->all()->except(['_token', 'type_of_fish']));


text:
Q: Dependency issues with actionpack upgrading rails from 4 to 5 Trying to upgrade rails to 5.0.0 and continue to receive the below error(first of quite a few).  I deleted my lock file, and tried adding gem('actionpack', '=5.0.0') to my gemfile and ran bundle install. It seems like 5.0.0 would meeet all the requirements below? I tried gem('actionpack', '~>5.0.0') as well and it just added actionpack (~> 5.0.0) to the output with the same error.
Bundler could not find compatible versions for gem "actionpack":
  In Gemfile:
    active_model_serializers was resolved to 0.10.12, which depends on
      actionpack (< 6.2, >= 4.1)

    haml-rails was resolved to 1.0.0, which depends on
      actionpack (>= 4.0.1)

    lograge was resolved to 0.11.2, which depends on
      actionpack (>= 4)

    rails (= 5.0.0) was resolved to 5.0.0, which depends on
      actionpack (= 5.0.0)

    rspec-rails was resolved to 4.1.2, which depends on
      actionpack (>= 4.2)

Edit2: Results with gem('rails', '= 5.0.7.2') and removing actionpack from Gemfile.  Ran docker-compose run web bundle update rails
  In Gemfile:
    active_model_serializers was resolved to 0.10.7, which depends on
      actionpack (< 6, >= 4.1)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      formtastic (~> 3.1) was resolved to 3.1.5, which depends on
        actionpack (>= 3.2.13)

    haml-rails was resolved to 1.0.0, which depends on
      actionpack (>= 4.0.1)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      inherited_resources (~> 1.7) was resolved to 1.9.0, which depends on
        has_scope (~> 0.6) was resolved to 0.7.2, which depends on
          actionpack (>= 4.1)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      inherited_resources (~> 1.7) was resolved to 1.9.0, which depends on
        actionpack (< 5.3, >= 4.2)

    lograge was resolved to 0.10.0, which depends on
      actionpack (>= 4)

    rails (= 5.0.7.2) was resolved to 5.0.7.2, which depends on
      actionpack (= 5.0.7.2)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      ransack (~> 1.3) was resolved to 1.8.9, which depends on
        actionpack (<= 5.1.1, >= 3.0)

    devise was resolved to 4.5.0, which depends on
      responders was resolved to 2.4.0, which depends on
        actionpack (< 5.3, >= 4.2.0)

    rspec-rails was resolved to 3.8.0, which depends on
      actionpack (>= 3.0)

Edit 3: Showing full output
Bundler could not find compatible versions for gem "actionpack":
  In Gemfile:
    active_model_serializers was resolved to 0.10.7, which depends on
      actionpack (< 6, >= 4.1)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      formtastic (~> 3.1) was resolved to 3.1.5, which depends on
        actionpack (>= 3.2.13)

    haml-rails was resolved to 1.0.0, which depends on
      actionpack (>= 4.0.1)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      inherited_resources (~> 1.7) was resolved to 1.9.0, which depends on
        has_scope (~> 0.6) was resolved to 0.7.2, which depends on
          actionpack (>= 4.1)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      inherited_resources (~> 1.7) was resolved to 1.9.0, which depends on
        actionpack (< 5.3, >= 4.2)

    lograge was resolved to 0.10.0, which depends on
      actionpack (>= 4)

    rails (= 5.0.7.2) was resolved to 5.0.7.2, which depends on
      actionpack (= 5.0.7.2)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      ransack (~> 1.3) was resolved to 1.8.9, which depends on
        actionpack (<= 5.1.1, >= 3.0)

    devise was resolved to 4.5.0, which depends on
      responders was resolved to 2.4.0, which depends on
        actionpack (< 5.3, >= 4.2.0)

    rspec-rails was resolved to 3.8.0, which depends on
      actionpack (>= 3.0)

Bundler could not find compatible versions for gem "activerecord":
  In Gemfile:
    acts_as_paranoid was resolved to 0.6.0, which depends on
      activerecord (< 6.0, >= 4.2)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      kaminari (< 2.0, >= 0.15) was resolved to 1.1.1, which depends on
        kaminari-activerecord (= 1.1.1) was resolved to 1.1.1, which depends on
          activerecord

    rails (= 5.0.7.2) was resolved to 5.0.7.2, which depends on
      activerecord (= 5.0.7.2)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      ransack (~> 1.3) was resolved to 1.8.9, which depends on
        activerecord (<= 5.1.1, >= 3.0)

Bundler could not find compatible versions for gem "activesupport":
  In Gemfile:
    acts_as_paranoid was resolved to 0.6.0, which depends on
      activesupport (< 6.0, >= 4.2)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      arbre (>= 1.1.1) was resolved to 1.1.1, which depends on
        activesupport (>= 3.0.0)

    haml-rails was resolved to 1.0.0, which depends on
      activesupport (>= 4.0.1)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      inherited_resources (~> 1.7) was resolved to 1.9.0, which depends on
        has_scope (~> 0.6) was resolved to 0.7.2, which depends on
          activesupport (>= 4.1)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      kaminari (< 2.0, >= 0.15) was resolved to 1.1.1, which depends on
        activesupport (>= 4.1.0)

    lograge was resolved to 0.10.0, which depends on
      activesupport (>= 4)

    paperclip (>= 5.0) was resolved to 6.1.0, which depends on
      activesupport (>= 4.2.0)

    rails (= 5.0.7.2) was resolved to 5.0.7.2, which depends on
      activesupport (= 5.0.7.2)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      ransack (~> 1.3) was resolved to 1.8.9, which depends on
        activesupport (<= 5.1.1, >= 3.0)

    rspec-rails was resolved to 3.8.0, which depends on
      activesupport (>= 3.0)

    slack-ruby-client was resolved to 0.13.0, which depends on
      activesupport

    spring was resolved to 2.0.2, which depends on
      activesupport (>= 4.2)

Bundler could not find compatible versions for gem "nokogiri":
  In Gemfile:
    cucumber-rails was resolved to 1.6.0, which depends on
      nokogiri (~> 1.8)

    haml-rails was resolved to 1.0.0, which depends on
      html2haml (>= 1.0.1) was resolved to 2.2.0, which depends on
        nokogiri (>= 1.6.0)

    paperclip (>= 5.0) was resolved to 6.1.0, which depends on
      mimemagic (~> 0.3.0) was resolved to 0.3.9, which depends on
        nokogiri (~> 1)

    roadie-rails was resolved to 1.3.0, which depends on
      roadie (~> 3.1) was resolved to 3.4.0, which depends on
        nokogiri (~> 1.5)

    ruby-saml (= 1.8.0) was resolved to 1.8.0, which depends on
      nokogiri (>= 1.5.10)

    twilio-ruby was resolved to 5.13.0, which depends on
      nokogiri (< 2.0, >= 1.6)

Bundler could not find compatible versions for gem "rails":
  In Gemfile:
    rails (= 5.0.7.2)

    rails_same_site_cookie was resolved to 0.1.4, which depends on
      rails (>= 4.1)

Bundler could not find compatible versions for gem "railties":
  In Gemfile:
    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      railties (< 5.2, >= 4.2)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      coffee-rails was resolved to 4.2.2, which depends on
        railties (>= 4.0.0)

    devise was resolved to 4.5.0, which depends on
      railties (< 6.0, >= 4.1.0)

    factory_bot_rails was resolved to 4.11.1, which depends on
      railties (>= 3.0.0)

    haml-rails was resolved to 1.0.0, which depends on
      railties (>= 4.0.1)

    lograge was resolved to 0.10.0, which depends on
      railties (>= 4)

    roadie-rails was resolved to 1.3.0, which depends on
      railties (< 5.3, >= 3.0)

    dotenv-rails was resolved to 2.5.0, which depends on
      railties (< 6.0, >= 3.2)

    quiet_assets was resolved to 1.1.0, which depends on
      railties (< 5.0, >= 3.1)

    xipio was resolved to 1.0.2, which depends on
      railties (>= 3)

    cucumber-rails was resolved to 1.6.0, which depends on
      railties (< 6, >= 4)

    rspec-rails was resolved to 3.8.0, which depends on
      railties (>= 3.0)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      inherited_resources (~> 1.7) was resolved to 1.9.0, which depends on
        railties (< 5.3, >= 4.2)

    activeadmin (= 1.2.1) was resolved to 1.2.1, which depends on
      jquery-rails (>= 4.2.0) was resolved to 4.3.3, which depends on
        railties (>= 4.2.0)

    devise was resolved to 4.5.0, which depends on
      responders was resolved to 2.4.0, which depends on
        railties (< 5.3, >= 4.2.0)

    rails (= 5.0.7.2) was resolved to 5.0.7.2, which depends on
      railties (= 5.0.7.2)

Bundler could not find compatible versions for gem "ruby":
  In Gemfile:
    ruby (~> 2.4.3.0)

    cucumber-rails was resolved to 1.6.0, which depends on
      nokogiri (~> 1.8) was resolved to 1.11.3, which depends on
        ruby (>= 2.5.0)

I think I need to update ruby, so my docker image as well.


text:
Q: Using Form in Django - get() missing 1 required positional argument: 'header' currently working in Django and trying to do a simple tutorial on forms, but I am receiving an error when the form is submitted.
Here is my urls.py:
from .views import*
urlpatterns = [
url(r'^name/', get_name, name='TheName'),
url(r'^name/present/', present, name='Present'),
]

Here are the views:
def get_name(request):
   if request.method == 'POST':
    form = NameForm(request.POST)
    if form.is_valid():
        return HttpResponseRedirect
   else:
    form = NameForm()

   return render(request, 'home/name.html', {'form': form})

def present(request):
   return render(request, 'home/present.html')

Here is the form:
class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

Here is name.html:
<form action="present/" method="post">
   {% csrf_token %}
   {{ form }}
   <input type="submit" value="Submit" />
</form>

Here is my present.html:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>{{ your_name }}</title>
</head>
<body>

</body>
</html>

After submit is clicked, and error message with the traceback:
Environment:

Request Method: POST
Request URL: http://localhost:8000/name/present/

Django Version: 1.11.4
Python Version: 3.6.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File   "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41.             response = get_response(request)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/deprecation.py" in __call__
142.             response = self.process_response(request, response)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/middleware/clickjacking.py" in process_response
32.         if response.get('X-Frame-Options') is not None:

Exception Type: TypeError at /name/present/
Exception Value: get() missing 1 required positional argument: 'header'

Any help would be appreciated!

A: You need to tell where to redirect after successful form submission. You are only doing return HttpResponseRedirect which is not valid, instead it should be:
return HttpResponseRedirect(the_path_to_redirect_to)

Please read documentation about HttpResponseRedirect.


text:
Q: How do I track only the last value for a user in Google Analytics? Here's the scenario:

*

*Clients come into my product and enter their employment income.

*They can adjust that income any time through the edit mode.

*If a client entered $50K during onboarding, then changed it to $100K later, I only want GA to "keep" the $100K value. When a pull a report to find out what the average value of employment income is for users of my site, I only want the $100K reflected for that client, not the average of $75K.
How can I do this in GA? In Mixpanel, for instance, there are certain types of "people properties" available for this scenario.
Thank you all in advance!
This product is for Angular JS...

A: In Google Analytics you would use a session scopes custom variable. "Session scope" means exactly what you want, only the last value per session is kept.
You need to create the dimension in the property settings and select the proper scope (you have a choice between hit scope, user scope and session scope - you want the latter) and then "set" in your tracking code. Since dimensions are transmitted with an interaction hit you need to set them before the pageview (or event tracking) call. You address the dimensions not with the name, but with the numeric index of their creation.
ga('create', 'UA-XXXX-Y', 'auto');
ga('set', 'dimension1', '<value>');
ga('send', 'pageview');

You can then access the dimension by the name you gave in the interface either by setting them as secondary dimension in a custom report, or using it in a custom report.
This retains the value for a user via a session. You can also choose a user scoped custom dimension which will only keep the last value for a user with multiple sessions. But user scope relies on cookies (unless you use the "user id" feature where you set an unique key per user from the serverside), so it might not always work for you.


text:
Q: What SynthConstants are supported by Component? The SynthConstants API says, "Constants used by Synth. Not all Components support all states." I have a question: What states in SynthConstants are respectively supported by each different Component? I think this is important for do a custom look and feel using Synth.

A: SELECTED and PRESSED can be used with buttons, such as JButtons or other sub classes of AbstractButton, and not passive components like JLabel. The others are valid for pretty much all components.


text:
Q: AdView missing required XML attribute adSize ,strange Hello in my app i'm using "Admob" banner when i running the aplication on my device i see the Advertisement and it's works but in the xml file  is see the banner with a message like "AdView missing required XML attribute 'adSize'"  . but when it's running it's look like it working fine.  Why is that? And is it important to treat it? or just ignore it?
(i searched about my question on the web but i think my problem is a little different)
Xml:
 <com.google.android.gms.ads.AdView
android:id="@+id/ad"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:layout_marginTop="300dp"
ads:adSize="BANNER"
ads:adUnitId="XXXXXXXXXXXXXXXXXXXXXXXX"
 />

manifest:
<activity android:name="com.google.android.gms.ads.AdActivity"
  android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />

MainActivity:
public void adMob(){
     adView = (AdView)v.findViewById(R.id.ad);
    AdRequest adRequest = new AdRequest.Builder()
        .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        .addTestDevice("TEST_DEVICE_ID")
        .build();
    adView.loadAd(adRequest);
}


text:
Q: Bulk delete discord.js I've been building my discord bot and have run into some trouble!
my bulk delete works but only for the cmd that you type any more than that I get this error
(node:146828) DeprecationWarning: Collection#find: pass a function instead
    (node:146828) UnhandledPromiseRejectionWarning: ReferenceError: args is not defined
        at purge (C:\Users\nevbw\Desktop\games\FBIBot\bot.js:29:13)
        at Client.<anonymous> (C:\Users\nevbw\Desktop\games\FBIBot\bot.js:46:2)
        at Client.emit (events.js:224:7)
        at MessageCreateHandler.handle

client.on('message', message => {
        if (message.content === 'L!delete') {
        async function purge() {
            message.delete();
                if (!message.member.roles.find("name", "LOLI POLICE")) {
                message.channel.send('You need the \`LOLI POLICE\` role to use this command.');
                return;}
               if (isNaN(args[0])) {
               message.channel.send('Please use a number as your arguments. \n Usage: ' + `L!` + 'purge
               <amount>');
            return;
            }
            const fetched = await message.channel.fetchMessages({limit: args[0]})
            console.log(fetched.size + ' messages found, deleting...');
            // Deleting the messages
            message.channel.bulkDelete(fetched)
                .catch(error => message.channel.send(`Error: ${error}`));
         it into the channel.
        }
        purge(); // Make sure this is inside the if(msg.startsWith)
        }
         });

A: The error is caused by the way you're using find(), you need to pass a function into it
if (!message.member.roles.find((role) => role.name === "LOLI POLICE"))