text:
Q: laravel jquery select2 multiselect - initialize selected elements Good morning everybody, I'm stuck while trying to set initial selected options (got through an ajax requests) to a jquery select2 (multi-select). If I use the control, multi selection works just fine. The problem arise when I have to edit a previously saved model, as none of the options I previously selected are shown.
This is my view:

has('pubblicazione_giuridica_id') ? 'has-error' : ''}}">
    {!! Form::label('pubblicazione_giuridica_id', 'Law Pubs', ['class' => 'col-sm-3 control-label']) !!}

        {!! Form::select('pubblicazione_giuridica_id[]', [$pubGiurList], null, ['class' => 'form-control', 'id'=>'select-pgiur', 'multiple'=>'multiple']) !!}
        {!! $errors->first('pubblicazione_giuridica_id', '
:message
') !!}

The javascript:
$('#select-pgiur').select2({
    ajax: {
        url: "{!! URL::to('/gare/proc-getpubgiur') !!}",
        dataType: 'json',
        delay: 150,
        data: function (params) {
            return { q: params.term, };
        },
        processResults: function (data, params) {
            return { results: data.items, };
        },
        cache: true
    },
    language: 'it',
    theme: "bootstrap",
    placeholder: "Choose an option."
});

The Controller:
public function edit($id, Request $request) {
    $procedure = $this->getProcedure($id, $request, true);
    if (!$procedure) {
        return redirect('gare/procedure')->with('alert-warning', 'Gara non trovata - Operazione non consentita');
    }
    return view('gare.procedures.edit', [ 'procedure'=>$procedure, 'opChoiceList'=>$this->getOpChoiceList(), 'pubGiurList'=>json_encode(GaraPubblicazioneGiuridica::GetPubByGaraId($procedure->id)) ]);
}

Model:
public static function GetPubByGaraId($id){
    //TODO: visualizzare le selected publications
    $procagg = GaraPubblicazioneGiuridica::where('gara_id','=',$id)->select('id')->get();
    if($procagg){
        $plucked = $procagg->pluck('nome');
        $toReturn = array();
        foreach($plucked as $key=>$value){
            $toReturn[$key]=$value;
        }
        return $toReturn;
    }
    return "";
}

Could you shed some light on this?
Thank you in advance.

A: You can create an ajax call on J-query Event and Bind the data through id.
$("#select-pgiur").val(data.items).trigger("change");
Maybe it helps you.....

A: If I understand your end-goal correctly, you want to update the Select2 multi-select by selecting options after the Select2 has been initialized using data received from an Ajax request.
If that's the case, you're looking for the .trigger('change') event.
I personally use VueJS and hand-crafted forms, but this should point you in the right direction:
$("#your_select2_id").val(selected_values_array).trigger("change");

The selected_values_array is a JS array that contains the values: <option value="1"></option> that you want selected. The .trigger() then updates the Select2 to show them.
Hope that helps!

A: When you make a dropdown selector you can specify the initially selected options:
Form::select(
   'pubblicazione_giuridica_id[]',
   [$pubGiurList],
   $opChoiceList,
  ['class' => 'form-control', 'id'=>'select-pgiur', 'multiple'=>'multiple']
)

However this means you need to pre-populate your AJAX select2 dropdown with the initially selected options.


text:
Q: Using Grails without an user interface I'm thinking about possible alternatives for our EJB based service layer and wondered if it would make sense to use just the service and database layer of Grails together with the Remoting Plugin or is this using a sledgehammer to crack a nut?
Speaking of the Remoting Plugin: is there a standard way of generating a JAR file, that contains the necessary classes to make a remote call to a Grails service from a non-Spring Java application?

A: Interesting idea.  I don't think it'd be overkill at all.  The nice thing is that your service would be very portable across protocols and deployment options (e.g. put a controller layer on top and it's instantly embedded).  This gives you the benefits of EJB's (persistence) + the ability to use Groovy and GORM.
FWIW, we're using Grails as our service tier; in come cases we use it embedded (as a plugin), in others we expose the services (via controllers) as JSON or SOAP; I see exposing as RMI as a variation of what we're doing (without the controller layer).

redpajama_set_name: RedPajamaStackExchange


text:
Q: suppressing output variables in matlab I am using a function with multiple outputs in Matlab, but am only interested in one of the outputs. I would like to suppress the other output variables (i.e. avoid them being returned and placed into memory). For example, with the max function:
[output1 output2] = max(matrixA, [], 1);
% output1 returns the maximum, which i'm not interested in
% output2 returns the index of the maximum, which i *am* interested in

Is there any way to call the function so that output1 is not returned? And if there is, does it offer any memory advantage over calculating as above but immediately calling clear output1 to remove output1 from the memory?
Thanks for your help.

A: Use the tilde:
[~, output2] = max(matrixA, [], 1);

I doubt there would be much memory advantage (apart from clerical stuff like allocating output variables, etc.)) since the function will run completely and allocate all that it needs to. This way, you just don't get the value, and the value of the first output variable in the scope of the max function will be garbage-collected.

A: Replace any output variables you don't want with a ~ character.
E.g.
[~,I] = max(matrix);

This pattern has an advantage over clear in that the MATLAB interpreter and just-in-time compiler can avoid the memory and CPU costs of calculating ignored variables.
Edit
Here is the documentation and a blog post by Loren Shure on this use of ~. I can't find any definite information about use of ignored variables for eliminating unnecessary computation.


text:
Q: Confusion about load word (lw) vs load address(la) and offsets in mips assembly? So I'm pretty new to assembly and I got so many questions. For example, if in the data segment I type this
.data

n:.word 4

And in the text segment
.text
lw $t0, n

Does $t0 now store the value 4 or the address of n?
Because I know that if n were an array and if I type lw $t0 4(n) $t0 stores the first VALUE of n(the content). And if I type lw $t0 n then $t0 stores the address.
Also I am wondering if I were to set an offset of 4 to register $0 like this:
lw $t0 4($0)

would $t0 just hold 0?

A: lw load a word from memory.
lw $t0, n reads from the address of the symbol n.
lw $t0, 4($t1) reads from the address generated as $t1 + 4.
lw $t0, 0x10000 reads from the address 0x10000.
Apart from the second, all are pseudo-instructions.
la load an address.
la $t0, n puts the address of the symbol n in $t0.
la $t0, 4($t1) put the address generated as $t1 + 4 in $0.
These are all pseudo-instructions.
li load an immediate.
li $t0, 10000 puts the immediate 10000 in $t0.
This is a pseudo instruction.

The central point is that MIPS has 16-bit immediates (constants) for I-type instructions, so the real form of li and lw don't permit to move a value greater than 0x10000 or access and address above 0x10000.
The assembler gets around it by generating two or more instructions.
la isn't needed in theory, li could be used to load the address of a symbol since the said address is an immediate in this context but a specific mnemonic was introduced instead.


text:
Q: Counting the number of times a session ID appears (MSSQL) I am trying to put together a realtime view of users on our ticketing site.
Currently, I have 2 sessions on the site (Session col).  My current query returns the following:
EVENTID     EVENT      Session    SessionOpened           SessionLength   NumberofTix
1619        BB King     11         2013-01-28 09:34:16.300   -2            2
1622        BB King     12         2013-01-28 09:36:55.073    0            1
1622        BB King     12         2013-01-28 09:36:55.077    0            3

However, it should look like this :
EVENTID     EVENT      Session    SessionOpened           SessionLength   NumberofTix
1619        BB King     11         2013-01-28 09:34:16.300   -2            2
1622        BB King     12         2013-01-28 09:36:55.073    0            4

Why is Session 12 returning 2 rows- 1 with 1 ticket and 1 with 3 tickets?
The query:
SELECT distinct set_eSRO_Event as EventID, shName as EventName, setSRO_UID as SRO_SessionID, setDateTime as SessionStarted,
DATEDIFF(mi, getDate(), setDateTime) as SessionTimer, Count(*) AS NumberofTickets FROM SessionTickets
INNER JOIN Shows on shCode = setShowCode
WHERE setStatus = 0
GROUP BY setsro_UID, shName, set_eSRO_Event, setDateTime

A: your result's columns and query's aliases are not coherent, so hard to say. I would imagine that setDateTime is different (= SessionStarted or SessionOpened). As you group by setDatetime, if they are different => two lines.
So add a MIN aggregate function to setDatetime (as in your "wanted" result), and remove setDatetime from GROUP BY
SELECT set_eSRO_Event as EventID,
shName as EventName,
setSRO_UID as SRO_SessionID,
MIN(setDateTime) as SessionStarted,
DATEDIFF(mi, getDate(), MIN(setDateTime)) as SessionTimer,
COUNT(*) AS NumberofTickets
FROM SessionTickets
INNER JOIN Shows on shCode = setShowCode
WHERE setStatus = 0
GROUP BY setsro_UID, shName, set_eSRO_Event

A: Without really knowing wich column belongs to wich table, and the version of SQL Server, you can try the following query:
SELECT  EventID,
        EventName,
        SRO_SessionID,
        MIN(SessionStarted) SessionStarted,
        SessionTimer,
        SUM(NumberofTickets) NumberofTickets
FROM (  SELECT  set_eSRO_Event as EventID,
                shName as EventName,
                setSRO_UID as SRO_SessionID,
                setDateTime as SessionStarted,
                DATEDIFF(mi, getDate(), setDateTime) as SessionTimer,
                Count(*) AS NumberofTickets
        FROM SessionTickets
        INNER JOIN Shows
            ON shCode = setShowCode
        WHERE setStatus = 0
        GROUP BY set_eSRO_Event, shName, setSRO_UID, setDateTime,
                 DATEDIFF(mi, getDate(), setDateTime)) A
GROUP BY EventID, EventName, SRO_SessionID, SessionTimer


text:
Q: Can string be passed as data in setting the http method in swift I am working on Xcode 7.2 and swift 2.0 and I'm converting a block of Objective-C code to swift . The Code in Objective-c is
  NSString *jsonstring = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
[requests setHTTPBody:[jsonstring dataUsingEncoding:NSUTF8StringEncoding]];

I am passing the urlData as a parameter while calling the function. this works fine in obj-c .. But when I convert this into swift 2.0 as
let jsonstring = String(data: urlData, encoding: NSUTF8StringEncoding)!
requests.HTTPBody = String(data: jsonstring, encoding: NSUTF8StringEncoding)

error is shown in this line as

"cannot convert value of type 'string' to expected argument type
  nsdata"

Can anyone help in telling me why is this error being thrown and what should I do to rectify the code ?

A: [jsonstring dataUsingEncoding:NSUTF8StringEncoding]]; is the method -[NSString dataUsingEncoding:].
String(data: jsonstring, encoding: NSUTF8StringEncoding) is the method -[NSString initWithData:encoding:].
This is not equivalent code. Try calling jsonstring.dataUsingEncoding(NSUTF8StringEncoding) instead.


text:
Q: Nhibernate session in Ninject RequestScope Just a quick question. If I have a binding like so:
Bind<ISession>().ToMethod(context => context.Kernel.Get<ISessionManager>().GetSession()).InRequestScope();

(Assuming that ISessionManager.GetSession() returns SessionFactory.OpenSession())
Do I need to explicitly close the session? or will it automatically dispose itself when Ninject deems it out of scope?

A: If ISession implements IDisposable Ninject will call it , And I think it does.
Latest Source code : http://nhibernate.svn.sourceforge.net/viewvc/nhibernate/trunk/nhibernate/src/NHibernate/ISession.cs?revision=5765&view=markup


text:
Q: Get the ID/Name of Html.TextBox in the jquery select event of kendo AutoComplete I am having a razor page where there is a Kendo AutoComplete control and on its change event I need to get two things:

*

*Id of that Kendo Autocomplete Control

*The nearest Text Box Id

because there will be cloning of these two controls.
Here is my Code:
function autocomplete_select(e) {
      var dataItem = this.dataItem(e.item.index());
      var txtbx = $(this).closest("input[type='text']");
      alert("Name==" + txtbx.attr('name'));
      alert("ID==" + txtbx.attr('id'));
      var tmp = $(this).closest("div.mf_form_field").find("input[type='text']").attr('id');
      alert(tmp);
      }

@(Html.Kendo().AutoComplete()
 .Name("ACDD")
 .BindTo((IEnumerable<String>)strActionCodes)
 .Events(e => e.Select("autocomplete_select")))

@Html.Label("Action Value")

@Html.TextBox("Value",null, new { style = "width : 105px"})

Here none of the alert returning the ID of the textbox and i am not able to get the Name/ID of the  kendo autocomplete.

A: The id of the autocomplete is retrieved like this:
function onChange(e){
    alert(this.element.attr('id'))
}

The closest (which in your case is not closest but next - check jQuery documentation for the difference between these two) to the textbox could be retrieved like this.
function onChange(e){
    alert(this.wrapper.next('input[type="text"]').attr('id'))
}


text:
Q: Deleting a file with similar names in Java I have like 2 files with almost same name like "myfile_1234.mp4" and "myfile_5678.mp4" in the same directory. One File, say, "myfile_1234.mp4" size is ZERO bytes where as the other file say "myfile_5678.mp4" has some size NOT EQUAL to ZERO (say 32kb). Now I want to delete the 1st File from the Directory but not the other File.
Can we have something like a loop temp pointer to the Files in the Directory and we would then check for Size of  file and delete it when its size is ZERO.
Can anyone help me here...?

A: This is a relatively straightforward exercise. Here are the things that you need to know to do understand what to do:

*

*A directory is represented by a File object. Create a File object for the directory that you want to list

*The listFiles() call produces an array of all files in the directory

*The length() method returns the size of the file

*The delete() method deletes the file

Your code will look like this:
// Reference the directory in which the files reside
File dir = new File("c:/my/test/directory");
// Go through the files in the directory in a loop
for ( File file : dir.listFiles()) {
    // Make sure that an entry is a file (it could be a directory)
    // and that its size is zero
    if (file.isFile() && file.length() == 0) {
        // If both conditions are true, delete the empty file
        file.delete();
    }
}

You can make additional conditions to check if a file has a particular name, extension, etc.

A: You can have a file (handle) created like
File myFileOne = new File(path);
File myFileTwo = new File(anotherPath);

Having such handles it is quite easy to check files size or names and delete the files as well. For more info on Java File see: http://docs.oracle.com/javase/6/docs/api/java/io/File.html#File


text:
Q: Example for spring MVC DeferredResult with long running task Can anyone tell me, how to do long running transactional task using spring DeferredResult ? went through a lot of tutorial available on net but neither documentation nor examples clear on non Rest based application, which doesn't need long polling but running the task at background and immediately returning the HTTP response and subsequent calls to the same controller method just return the result. With some assumption i have created like the following
private static final Map<String, DeferredResult<ModelAndView>> deferredResults = new ConcurrentHashMap<>();

@RequestMapping(value = "longRunning", method = RequestMethod.POST)
public DeferredResult<ModelAndView> longRunning(@ModelAttribute LongRunningJob longRunningJob) {
    String resultKey = longRunningJob.getKey();
    DeferredResult<ModelAndView> result = deferredResults.get(resultKey);
    if (result == null ) {
        deferredResults.put(resultKey, result = new DeferredResult<ModelAndView>());
        new Thread(runLongRunning(longRunningJob, result)).start();
    }
    result.onCompletion(() -> {
        deferredResults.remove(resultKey);});
    return result;
}

public Runnable runLongRunning((LongRunningJob newLongRunningJob, DeferredResult deferredResult) {
    return () -> {
        LongRunningJob returnJobValue = this.longRunningJobService.startLongRunningJob(newLongRunningJob); //startLongRunningJob is a transactional method
        ModelMap modelMap = new ModelMap();
        modelMap.put("returnJobValue", returnJobValue);
        modelMap.put("message", "Success");
        deferredResult.setResult(new ModelAndView("job-view", modelMap));
    };
}

Will it work or is there any other better way to handle it ? Will it be threadsafe is there any chances of getting into a race condition ?


text:
Q: Android Studio and Gradle: versionNameSuffix I'd like to append special suffixes to my output APK files based on the current buildType. I am trying to use the standard Gradle's versionNameSuffix command:
android {
    defaultConfig {
       ...
       versionNameSuffix "-XXX"
    }
    buildTypes {
        debug {
            versionNameSuffix "-YYY"
        }
        release {
            versionNameSuffix "-ZZZ"
        }
    }
}

For some reason none of these suffixes gets applied to the actual output file name. Does Android Studio ignore this command? Whatever I do the result is the same: <module_name>-debug.apk or <module_name>-release.apk.
Here's my config:
classpath 'com.android.tools.build:gradle:2.2.3'
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

A:
Does Android Studio ignore this command?

No, but versionNameSuffix does not affect the filename. It affects the versionName (BuildConfig.VERSION_NAME, the version name shown in Settings, etc.).
You can teach Gradle to embed versionName in the APK filename, though.


text:
Q: Problems changing the text color of a link via external css file I've been searching for a good hour but no one seems to have had the same problem.
I am trying to change the text color of a link to grey, it is appearing blue however. I specifically want to achieve this by setting a class property of the link - I don't want custom css in the aspx file, and I don't want to set the style property of the link. (For the record I have tried both of these ways and they work).
//Site.css
 .grey {
 color: grey;
 }

  .button-link2 {
 padding: 10px 15px;
 background: #EFEFEF;
 -webkit-border-radius: 4px;
 -moz-border-radius: 4px;
 border-radius: 4px;
 -webkit-transition-duration: 0.2s;
 -moz-transition-duration: 0.2s;
 -transition-duration: 0.2s;
 text-decoration: none;
 cursor: pointer;
}

And the link the way I would like it to work:
Cancel

Thanks in advance!

A: you would either need to apply the text color to the element outside of the link or add the a attribute.
a.grey,
.grey {
  ...
}

A: Make this as important. Use only if it's necessary
//Site.css
 .grey {
 color: grey !important;
 }

A: Just wanted to confirm that you have below piece:
a:link {color:#FF0000;}      /* unvisited link */
a:visited {color:#00FF00;}  /* visited link */
a:hover {color:#FF00FF;}  /* mouse over link */
a:active {color:#0000FF;}  /* selected link */

A: Is it the spelling mistake? Try "Gray" instead of "grey"

A: The problem is, you might have in the same Site.css other link settings that override yours. By default, there are such style properties defined for hyperlinks. Get rid of those, or use this:
#btnCancel.grey {
 color: grey;
 }

A: This type of problem is fairly easy to solve with a DOM inspection tool like Chrome Developer Tools. In Chrome, right-click on the element and select "Inspect element" and in the window that pops up you will be able to see all of the possible declarations that could be overrriding your .grey class's color declaration.
And be sure you know your CSS specificity rules really well.
do not use !important, if you can avoid it.

A: .grey
{
color:gray;
}

This will work.


text:
Q: Socialite Laravel. How to get custom parameters? I develop API endpoint for binding social network account to exists account in our system. As it is API I can't use sessions but I need identificate of user that know what user I need binding. In the Laravel documentation for Socialite functionality I see that I can use "with" method to send custom parameters but there not write how I can get these parameters in incoming request. How I can get these parameteres?
I would be grateful for any help. Thanks.
Method for generate social link with uid parameter:
public function redirectToProvider($provider)
{
    return Socialite::driver($provider)
        ->with([
            'uid' => "Auth::id()"
        ])
        ->stateless()
        ->redirect()
        ->getTargetUrl();
}

Callback method from social network:
 public function handleProviderCallback($provider)
{
    $user = Socialite::driver($provider)
        ->stateless()
        ->user();

    return $user;

}

A: Correct solution ->with ('state' => Auth :: id ())


text:
Q: What are the available options for full text search in Firebase? I started to construct an app on Android using Firebase where users can post items to a live feed (recipes).
Everything was going great until I realized that as the number of posts grew, users would need a way to filter through all of the recipes.
For example, if they wanted to find all chicken dishes, they need to be able to search for chicken and see all recipes containing the word chicken.
The problem is that, as far as I can tell, you can only query for exact strings with Firebase. e.g. You can search for all recipes precisely titled "Chicken Parmesan" but you can't do a general search for all recipes containing the word "chicken".
Is there any way around this, or am I better off going for a relational DB setup?


text:
Q: How to pass multiple lines into interpreter? I'm not sure how to phrase the question another way, but I upgraded from VS 13' to 15', and I'm no longer able to run multiple statements in the REPL window. I get 'SyntaxError: multiple statements found while compiling a single statement'. I know in 13' i was able to run multiple lines/statements with error. Any suggestions?

A: Sending it to the interactive works. Still new to VS and PTVS, so kind of a bonehead move.


text:
Q: Why is the escape of quotes lost in this regex substitution? Why is the escaping of double quotes are lost in this case?
$ cat foo.txt
This is a \"very good\" text worth AMOUNT dollars
$ cat full_story.txt
This is about money:
STORY

Testing it with the following:
VAR=$(cat foo.txt)
TOTAL=$(cat full_story.txt)
echo "$TOTAL" | perl -pe "s/STORY/$VAR/g"

Result:
This is about money:
This is a "very good" text worth AMOUNT dollars

The escape of double quotes got lost. I was expecting:
This is about money:
This is a \"very good\" text worth AMOUNT dollars

How can I preserve the escapes?

A: The problem is that perl parses backslash escapes in an explicit  replacement string (not a perl variable), and hence a \" is parsed into a". For example:
$ echo "A STORY" | perl -pe 's/STORY/\"Hello\"/'
A "Hello"

(Note that the Bash variable $VAR does not become a perl variable $VAR , but rather a constant string.) So you need to escape the backslashes like this in constant string:
$ echo "A STORY" | perl -pe 's/STORY/\\"Hello\\"/'
A \"Hello\"

You can work around the issue by transferring the Bash variable $VAR into a perl variable $VAR by using the -s switch to perl like this:
echo "$TOTAL" | perl -spe 's/STORY/$VAR/g' -- -VAR="$VAR"

Ouput:
This is about money:
This is a \"very good\" text worth AMOUNT dollars

Explanation:

*

*-s enables switch parsing for user defined switches on the perl command line. Any switch found there is removed from @ARGV and sets the corresponding variable in the Perl program.

A: Your code suffers from a code injection bug. Specifically, you're trying to generate Perl code from the shell, but failing at it.
You are passing the following to Perl:
s/STORY/This is a \"very good\" text worth AMOUNT dollars/g

You should be passing the following:
s/STORY/This is a \\"very good\\" text worth AMOUNT dollars/g

To properly generate Perl code, you'd need something like the following:
perl -pe's/STORY/'"$( printf %s "$VAR" | sed 's/\W/\\&/g' )"'/'

This passes the following to Perl (which is also fine):
s/STORY/This is a \\\"very good\\\" text worth AMOUNT dollars/g

It's far simpler to avoid generating Perl code in the first place, though. There are three primary ways of passing information to Perl without using STDIN or external storage.

*

*Arguments
perl -pe'BEGIN { $VAR = shift(@ARGV) } s/STORY/$VAR/g' -- "$VAR"

*Command-line options
In a full program, you'd use Getopt::Long, but perl -s will do fine here.
perl -spe's/STORY/$VAR/g' -- -VAR="$VAR"

*Environment variables
VAR="$VAR" perl -pe's/STORY/$ENV{VAR}/g'


text:
Q: Evaluate: $ \int_0^1 \int_y^1 e^{x^2 }dxdy$
Evaluate: $$ \int_0^1  \int_y^1 e^{x^2 }dxdy=?$$

MyTry :
$$\begin{align} \int_0^1  \big(\int_y^1 e^{x^2 }dx\big)dy=?\end{align}$$
Now what ?
$$I=\big(\int_y^1 e^{x^2 }dx\big)=?$$

A: You have to switch the bounds of integration
$$ \int_0^1  \int_y^1 e^{x^2 }dxdy$$
$$ =\int_0^1  \int_0^x e^{x^2 }dydx$$
$$ =\int_0^1   xe^{x^2 }dx$$
$$ =1/2e^{x^2 }|^1_0$$
$$=1/2(e-1)$$


text:
Q: Product of product of all subset of size k of a set? example given set={$1,2,3$} size={$2$}
then ($1,2),(2,3),(1,3$) so product of each is $2,6,3$ and the product is $2*6*3=36$ again.
so i was looking for a method to do ?

A: Let's assume the set we're dealing with is finite. Let $S = \{s_1, s_2, \cdots, s_n \}$, and fix the size we're considering as $k$.
There are $\frac{n!}{k! (n-k)!}$ total subsets of size $k$. Now each element of $S$ will be a member of some (but not all) of these subsets. In particular, if we force $s_j$ to be in subset, there are $k-1$ remaining members to pick from the remaining $n-1$ members of $S$. Thus, there are exactly $\frac{(n-1)!}{(k-1)!(n-k)!}$ subsets  of size $k$ containing $s_j$.
Since this holds for any $j$, and muliplication in commutative, we find the value you're l0oking for, $V$ is given by:
$$V = \prod_{j=1}^{n}s_j^r$$
where $r$ is given by:
$$r = \frac{(n-1)!}{(k-1)!(n-k)!}$$

Applying this to your example above, we have $n =3$ and $k=2$, which yields $r = 2$. Then we have:
$$\begin{align}
V &= 1^2 *2^2 *3^2 \\ &= 1*4*9 \\ &=36
\end{align}$$

A: Consider the $k-$sets of $\{a_1,\cdots,a_n \}$ each element will occur $\binom{n-1}{k-1}$ times in a given set, so the product of the products of the sets will be $\color{red}{\left(\prod_{i=1}^{n} a_i \right)^{\binom{n-1}{k-1}}}$.


text:
Q: Server Hardware Recomendation I'm ready to buy a few servers and I'm wondering what the best setup would be.
My site serves about 1M php pages day. And the database has about 4M rows that are constantly growing. (60% read, 40% write, 100qps)
I just need to know what exactly would be the best hardware for what I'm doing.
I use CentOS, MySQL 5, and lighttpd.
I have the money to invest on good hardware, at the moment im looking at:
http://www.newegg.com/Product/Product.aspx?Item=
N82E16816101260
N82E16819117185
N82E16820148259
N82E16822116059
(had to list them like this because i cant post 4 links)
Would this been a compatible setup? Mainly i want to stray away from renting a box's and collocate instead.

A: I would recommend spending the extra money and getting a system from one of the big guys (Dell, HP, IBM, etc).  When you buy a server from these guys you get a support contract.  That support contract gives you replacement parts within hours of the failure so that you don't have to wait for the new part to arrive.  Unless of course you want to be down while you wait for the new motherboard to ship out before the BIOS upgrade bricked the thing.
Also you get some assurances that the RAM, board, disk controllers, etc will all work together without any funky driver issues as the vendor will have taken care of this for you already.

A: You can do a lot on a 1 or 2 web servers with 1-4GB of RAM and minimal disk.  Spend your dollars on the MySQL box for now.  The more of your dataset that can be crammed on to RAM the happier MySQL will be.  MySQL doesn't utilize many cores well, so raw CPU speed (mhz) is more important than the number of CPUs/cores.
We can't give specific recommendations without considering your application (do you use memcache, or another cache system?  Why not? What are your redundancy needs?  How much of the app is static or semi static vs dynamic?)
If your app is straightforward, you might want to just consider cloud hosting it. Rackspace, Amazon and others offer affordable services that allow you to ramp up and down the amount of systems you have online.  This can be very cost effective, especially if your system load changes a lot (slashdot/digg effects) or you have limited information how how your app usage will grow over time.

A: I hate to say this, but you don't mention anything about what is probably the most important piece - is your application designed to scale to a farm of multiple servers? If it can't be split up well then you're going to hit a fairly hard cap on your capacity where you can go higher but you're climbing the expensive part of the cost/performance curve.
(posted as an answer because I lack the level to comment instead)

A: You'll probably enjoy a dual quad core, preferably Intel Harpertown processors since they are quite affordable, but Nehalem processors with HT will offer more processor threads.
RAM is important, maybe 12GB or more of RAM, to avoid hitting the disks too much with DB queries.
Buying several SA-SCSI drives and placing them in a RAID-10 will give you added speed and offer fault tolerance. You will need at least 4 for a proper RAID-10 setup.
Beyond this, you will also need to keep MySQL optimized as well as your queries optimized if they are not.

A: Thats only an average of 11.5 req/sec.  Which assuming normal traffic patterns will mean 25 - 30 req/sec peak on a normal afternoon.  Even if you assume 10x peaks that could run anywhere from a 512mb slicehost VM ($40/month) to an 8-core/64gb/6-disk-raid-10-w/bbwc ($12K up-front, plus colo/bandwidth/power ongoing per month).  It will vary widely by what your php scripts are doing and your db schema.
You mention your traffic in the present tense, presumably then your existing server is handling the workload but you're looking to improve performance?  If you are not currently swapping then its unlikely you'll need more memory on a new server, though you'll probably want some room for growth.
Just about the only no-brainier I can recommend without more info is that if you intend to keep this on your own hardware make sure its raid-10 on a controller with battery backed write cache.


text:
Q: JQuery Mobile Listview search types I have a problem with searching in JQuery Mobile listview control.
In listview default search like this:
Listview Items:
AAA
BBB
CCC
ABB
BAB
CBA
When I search "A" I will get the Result
Current Displaying Items:
AAA
ABB
BAB
CBA
But I want the Items:
AAA
ABB

A: Add a custom filter callback.
Try something like this (untested):
var filter = function( text, searchString ) {
    return text.toLowerCase().indexOf( searchString ) !== 0;
};

$('#myListView').listview( 'option', 'filterCallback', filter );

I wrote this on my phone so that's my excuse for everything wrong with this answer.


text:
Q: C# project Background image for home page does not cover full page I am doing a C# project using the ASP.NET Core Web App (Model-View-Controller). I create the HomeStyleSheet.css file to edit the home page. I add an image background but it does not cover full div. This is my code for the html:

             welcome to
             foodies

And this is the code for the CSS file:
.header {
    margin-top: 60px;
    margin-left: 0px;
    width: 100%;
    height: calc(130vh - 80px);
    background: url(../images/background.jpg);
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: aqua;
}

.content {
    text-align: center;
}

.heading {
    color: #ffffff;
    text-transform: capitalize;
    font-size: 80px;
    line-height: 60px;
    margin-bottom: 80px;
}

    .heading .small {
        display: block;
        font-size: 40px;
    }

    .heading .no-fill {
        font-style: italic;
        color: transparent;
        -webkit-text-stroke: 2px #fff;
    }

I have tried to set the margin-left and margin-right to 0 but it did not work.
How could I solve this problem?


text:
Q: Question related to event detection - computer vision Steps involved in Event detection.
I am very new to computer vision and I am starting to look into how event detection works. But it really confuses me. I am basically creating a dataset where I am extracting frames from videos and annotating frame images with person, car, animal Etc and I would like to do a event detection to find if there was a crash or not in the image.
My question is that while annotating how can I include the events details? I am using online video annotating tools which allows only to annotate an object in the frame.
Could someone please guide me on this ?
Also on what steps should I follow for event detection ?


text:
Q: Is it possible that there isn't a linear span which precisely spans a vector space? In the assignment I'm asked to decide whether given:
$S = \Bigg \{ \begin{bmatrix}a &b \\ c &d\end{bmatrix} \in M_2(\mathbb{R}) \; | \; ad = 0 \Bigg \},\mathbb{F} = \mathbb{R}$.
$S$ is a vector space.  I believe that addition and multiplication by scalar are defined point-wise.  I believe that this is a vector space, but the question also asks to construct a linear span of this space (provided it is a space).  And here I'm in doubt: any two matrices with $a$ or $d$ non-zero would create elements not in $S$, but if I leave out either $a$ or $d$, the span won't generate every possible matrix.  Is this an okay situation, or did I do something wrong?

A: Since we're considering $S \subset \Bbb M_2(\Bbb R)$, it is natural to assume that the operations on $S$ are inherited from $\Bbb M_2(\Bbb R)$. But $S$ as it is, is not a subspace of $\Bbb M_2(\Bbb R)$. We have that $$\begin{bmatrix} a_1 & b_1 \\ c_1 & d_1\end{bmatrix}+\begin{bmatrix} a_2 & b_2 \\ c_2 & d_2\end{bmatrix} = \begin{bmatrix} a_1+a_2 & b_1+b_2 \\ c_1+c_2 & d_1+d_2\end{bmatrix}$$
If $a_1=d_2 = 0$ but $a_2,d_1 \neq 0$, closure under addition fails. But $${\rm span} \ S = \bigcap_{S \subset W \leq V} W$$ is always a vector space (intersection of vector spaces is still one). Now, finding a basis for ${\rm span} \ S$ is another problem.

A: Theorem: every vector space has a basis (and any two bases of the vector space have the same cardinality).
This theorem is the cornerstone of linear algebra, and usually the case of finite-dimensional vector spaces is proven in a linear algebra class. (I should warn that the above isn't true in general unless you assume the axiom of choice.)
Your specific set is not a vector space: $\left( \begin{array}{ccc}
1 & 0\\
0 & 0 \end{array} \right) \in S$ and $\left( \begin{array}{ccc}
0 & 0\\
0 & 1 \end{array} \right)\in S$, but their sum, $\left( \begin{array}{ccc}
1 & 0\\
0 & 1 \end{array} \right) \not\in S$.


text:
Q: Shifting AC Signal for ADC I have AC signal that varies from 50mV (pk-pk) to 420mV (pk-pk). I am trying to use a PGA (programmable gain amplifier) to amplifiy the signal so that it can be sent to the ADC in an ATmega328P. The signal sent to the ADC needs to be within 0-3.3V. I can't add a DC shift centred around 1.65V before passing it through the PGA, as this will also amplify the DC shift, which puts the signal outside the ADC range. How can I go about shifting the signal and amplifiying it using a PGA which is supplied from a single supply?

A:
I can't add a DC shift centred around 1.65V before passing it through the PGA, as this will also amplify the DC shift

Yes you can, and you have to. The PGA you want to use, MCP6S91, can only operate on positive signals, centered around a positive DC reference voltage. It has a dedicated VREF pin for this exact purpose.
There is even an example in the datasheet for a 2.5 volt DC bias:


text:
Q: guardar array de inputs en laravel 8 //comienzo de codigo malo
$precio_ = $request->input('precio_');

$j = count($precio_);
for( $h=0; $h<$j; $h++ ) {
    $compras = new Compras;
    $compras->CompraprecioUnitario = $precio_[$h];
    $compras->save();
}

$cantidad_ = $request->input('cantidad_');

$c = count($cantidad_);
for( $i=0; $i<$c; $i++ ) {
    $save = new Compras;
    $save->cantidadComprada = $cantidad_[$i];
    $save->save();
}

//codigo bueno
foreach (session ('productos_add') as $key=>$Productos) {
    Compras::create([
        'productos_id'=>$Productos['codigo_producto']
    ]);
}

vista

    <input type="text" id="cantidad_{{$cont}}" name="cantidad_[]"  class="inputcantidad form-control" onchange="calculate(),validatecantidad(this)" placeholder="cantidad" required="" >

array:5 [▼
    "_method" => "PUT"
    "_token" => "TkjSIyx2C2L6Vi8cX0FqOGik1P9r0gkykN07d8f9"
    "proveedor" => "32232323"
    "cantidad_" => array:2 [▼
        0 => "2"
        1 => "2"
    ]
    "precio_" => array:2 [▼
        0 => "2"
        1 => "2
    ]
]

Estoy tratando de acceder al campo cantidad_ y precio_ en las 1eras lineas de código. Hice dos intentos de guardar el campo cantidad sin mucho éxito: en uno lo realice con metodo foreach y el otro un simple for y ninguno con exito.
Sale este error

Illuminate\Database\Grammar::parameterize(): Argument #1 ($values) must be of type array, string given, called in C:\xampp\htdocs\inventario_max-copia\vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\Grammar.php on line 886

este es mi ultima solucion la adjunto en foto
como logro ahora que me muestre todo en un insert solo muestra 1 de los 2 SQLSTATE[HY000]: General error: 1364 Field 'cantidadComprada' doesn't have a default value (SQL: insert into compras (productos_id) values (13), (12))

A: No he utilizado la forma que realizas tu, pero te recomiendo hacerlo de la siguiente manera.
En tu código veo que esto $compras->cantidadComprada => $cantidad_[$i], lo ingresas en un array cantidad no se porque, eso te puede estar provocando el error debido a que no se asigna correctamente el dato y a la hora de tener en tu BD ese campo como not null siempre te generará ese error.
foreach($cantidas as $ind=> $cant)
{
  $compras=new Compras();
  $compras->cantidadComprada => $cant;
  $compras->save();
}

A: Puedes enviar el contenido de una serie de inputs como un array,
por ejemplo tengo un listado de productos y cada uno tiene un input para indicar su stock. Es decir se genera un formulario con un número indeterminados de inputs de entrada para stock, uno por producto, algo así (en Blade):
<form action="{{ route('loquesea') }} method="POST">
    @method('PUT')
    @csrf

    @foreach ($products as $key => $product)

            {{ $product->name }}

            <siv class="form-group">
                id }}">
                <input name="stock[]"
                    type="number"
                    min="0"
                    step="1"
                    id="stock_for_product_{{ $product->id }}"
                    value="0">
            </siv>

    @endforeach

    <input type="submit" value="Enviar">
<form>

Aquí lo importante es como se nombra al input para introducir el stock de cada producto, como un array: stock[]
En tu controlador tienes un array con los stocks, uno por producto, su valor es 0 por defecto.
Puedes verlo así:
dump($request->stock);

Si usas validaciones en un form request, una regla que te valdría seria:
[
    stock => 'sometimes|array',
    stock.* => 'integer|min:0',
]

He puesto sometimes en la primera línea, por si en el formulario no hubiera ningún producto (tampoco llegaría stocks en la request en este caso).
La segunda línea permite validar el tipo de contenido de cada posición dentro del array.
También podrías usar un array asociativo, vinculando cada stock a la ID del producto:
<input name="stock[{{ $product->id }}][]"
    type="number"
    min="0"
    step="1"
    id="stock_for_product_{{ $product->id }}"
    value="0">

En este caso la validación podría ser:
[
    stock => 'sometimes|array',
    stock.* => 'integer|min:1|exists:products,id',
    stock.*.* => 'integer|min:0',
]

Se añadió una validación para las IDs de producto en este caso: valida que se usen IDs que se encuentran en la tabla "products".
En el controlador, lo mismo, para ver el dato:
dump($request->stock);

Si bien en el primer caso accederías al valor de stock para cada producto corriéndolos en el mismo orden en que se encuentran los productos que enviaste a la vista, en el segundo puedes usar directamente las IDs de los productos para tratar de obtener su stock.

Editado

Para guardar los datos del array en base de datos usar un bucle que recorra el mismo, p.e. un modelo Eloquent de nombre "Product" usando el segundo supuesto: usar un array asociativo, vinculando cada stock a la ID del producto (los productos ya existen, se va a proceder a una actualización, en la tabla products existe el campo "stock" para el tipo de dato esperado):
foreach ($request->stock as $productId => $stock) {
    if ($product = Product::find($productId)) {
        $product->stock = $stock;
        $product->save();
    }
}

A: Buen día,
Para guardar variables tipo array en una base de datos puedes utilizar el método insert() (Documentación)
En tu código primero deberías hacer la validación de los datos que contenga $precio_ (Voy a suponer que ya lo haces porque no se muestra en tu código)
Suponiendo que los datos de $precio_ ya están validados lo que puedes hacer es:
Tabla::insert($variable);

Explicación: $variable Puede ser un arreglo de arreglos (Los podemos llamar elementos) donde cada elemento tiene los datos de cada columna, en este caso puedes insertar directamente $variable, por ejemplo (Muestro la composición de $variable, tiene un arreglo de elementos):
$variable = [['columna_1' => 1,
             'columna_2' => 2,
             'columna_3' => 3,
             'columna_4' => 4,
            ],
            ['columna_1' => 5,
             'columna_2' => 6,
             'columna_3' => 7,
             'columna_4' => 8,
            ]];

Tabla::insert($variable);

La ventaja de hacer lo anterior es que en una sola línea de código puedes insertar muchos elementos (Por ejemplo, podrías utilizarlo en la parte donde pusiste // código bueno en lugar del foreach
Otra opción es escribir los valores de cada columna, por ejemplo
Tabla::insert([['nombreColumna1' => $variable1, 'nombreColumna2' => $variable2],
               ['nombreColumna1' => $variable1, 'nombreColumna2' => $variable2]]);

Explicación: Con esta opción escribes entrada por entrada, por lo que si quieres escribir más de una entrada tendrías que hacerlo de la forma que mostré  en el ejemplo anterior. Esto lo utilizas cuando quieres hacer entradas pero tu $variable no tiene los valores de todas las columnas
Recomendación: Asegúrate de que tu variable (En tu código sería $precio_) tenga todos los valores para cada columna de tu tabla (O podrías crear una nueva variable con todos los valores de cada columna para usar el ejemplo 1) De esta forma podrías utilizar el primer ejemplo Tabla::insert($variable); e ingresar todo tu arreglo en una sola línea de código
La ventaja de utilizar Tabla::insert($variable); sería que el número de interacciones que haces con tu tabla se reduce, por ejemplo, en el foreach que haces (Mostrado a continuación) cada ves que ejecutas create() haces una petición a tu base de datos, si son 10 elementos no habrá problema, pero si son 5000 ó 10000 entonces se va a tardar mucho en hacerlo
foreach (session ('productos_add') as $key=>$Productos) {
    Compras::create([
        'productos_id'=>$Productos['codigo_producto']
    ]);
}

Para concluir y aterrizando la explicación a tu código:
Te recomiendo que crees un arreglo que tenga la información para todas tus columnas (Suponiendo que $precio_ ya lo tiene)
Compras::insert($precio_);

Si quieres hacerlo línea por línea entonces podrías hacer algo así:
foreach($precio_ as $p){
    Compras::insert(['CompraprecioUnitario'=>$p]);
}

Existe otro método insertOrIgnore que funciona casi igual, la única diferencia es que ignora los errores que podría haber en las entradas de datos, por ejemplo si tuvieras valores repetidos y estas intentando escribir a una columna con valores únicos, ignoraría el duplicado y continuaría con los siguientes valores


text:
Q: Finding the Mean (Average) in C++ About the Program
The program is supposed to generate numbers from user input supplied (initial value and the maximum value) to generate a list of numbers ranging within those value. Once completed, the program needs to display the average between all of the numbers displayed.
My Code
#include <iostream>

int main(void)
{
    unsigned int INITIAL_VALUE;
    unsigned int MAX_VALUE;

    std::cout << "\n\n\nStarting value: ";
    std::cin >> INITIAL_VALUE;
    std::cout << "\nValue to count to: ";
    std::cin >> MAX_VALUE;

    std::cout << "\n";

    while(INITIAL_VALUE <= MAX_VALUE)
    {
        ++INITIAL_VALUE;
        std::cout << INITIAL_VALUE << ", ";
    }

    // Code to output the average goes here

    std::cin.get();
    std::cin.get();
}

I, of course, made an attempt to solve this, but I could not even wrap my head around an explanation. I know to find the mean (average) of numbers by simply adding up all of the numbers, then dividing by the amount of numbers; however, I can't think of a way to transfer such a simple equation into C++ syntax. A thorough explanation would be much appreciated, and thanks to everyone in advance.

A: #include <iostream>

int main(void)
{
    unsigned int INITIAL_VALUE;
    unsigned int MAX_VALUE;
    unsigned int sum  = 0;
    unsigned int count;
    double average;

    std::cout << "\n\n\nStarting value: ";
    std::cin >> INITIAL_VALUE;
    std::cout << "\nValue to count to: ";
    std::cin >> MAX_VALUE;

    std::cout << "\n";
    count = MAX_VALUE - INITIAL_VALUE + 1;

    while(INITIAL_VALUE <= MAX_VALUE)
    {
        sum += INITIAL_VALUE;
        ++INITIAL_VALUE;
        std::cout << INITIAL_VALUE << ", ";
    }

    // Code to output the average goes here
    average = 1.0 * sum / count;

    std::cin.get();
    std::cin.get();
}

A: What you are doing wrong is you are not keeping track of the sum of all the values. And then you can divide it by the number of values to get the average. So the while loop part should be like
double sum = 0.0;
int n = MAX_VALUE - INITIAL_VALUE + 1;
while(INITIAL_VALUE <= MAX_VALUE)
{
    sum += INITIAL_VALUE;
    ++INITIAL_VALUE;
    std::cout << INITIAL_VALUE << ", ";
}

double average = sum/n;


text:
Q: (TiledWorldMap) Error: Expected a value of type 'double?', but got one of type 'String' I am still pretty new to flame, flutter, and dart overall but I am trying to display a tiled world map using the Bonfire plugin which sits on top of flame but whenever I try to run the program it tells me that the value stored in 'TildWorldMap' is of type String and not a double which is correct because I am passing a json file ('tiled/firsttry.json') through the string. I am wondering if there is another way to store the string as a double or if it's just a syntax error that I am not picking up on?
import 'package:bonfire/bonfire.dart';
import 'package:flutter/material.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Flame.device.fullScreen();
  Flame.device.setLandscape();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {

  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return BonfireTiledWidget(
      map: TiledWorldMap('tiled/firsttry.json', forceTileSize: Size(16, 16)),
      lightingColorGame: Colors.black.withOpacity(0.5),
    joystick: Joystick(
      directional: JoystickDirectional(
        isFixed: false,
      )
    ),
      background: BackgroundColorGame(Colors.pinkAccent),
    );
  }
}

A: I figured it out by just using a URL instead of the JSON file.


text:
Q: Use Python to get state of combustion engine based on spark plug actuation Working to create a data acquisition system for a custom off-road vehicle. Using Raspberry Pi and a custom tachometer (tested and confirmed working) to measure RPM. Using interrupts in the following code to get RPM value.
def get_rpm():
    GPIO.wait_for_edge(17, GPIO.FALLING)
    start = time.time()
    GPIO.wait_for_edge(17, GPIO.FALLING)
    end = time.time()
    duration = end - start
    rpm = (1/duration)*60
    return rpm

This code only works if the engine is running and producing a spark. If there is no spark, the code sits waiting for that edge and does not proceed. When calling get_rpm(), if the code is waiting for an edge, this causes other processes to hang.
My intended workaround for this is to get the state of the engine in another process. I think it will work best in two parts.
Part 1, running (looped) in a separate thread:
GPIO.wait_for_edge(17, GPIO.RISING)
last = time.time

Part 2, running called as a function as needed:
def get_state():
    while time.time - last < .5:
        engine_state = true
    else:
        engine_state = false
    return engine_state

With Part 1 saving last to memory accessible to Part 2, Part 2 will determine whether or not the car is running based on the last time the spark plug sparked. Using engine_state as a comparator, the data acquisition system will get and store the RPM value from get_rpm() only when engine_state is true.
How can I implement Part 1 in such a way that I can use the last variable in Part 2? last will be changing very, very quickly. I don't want to store it to a text file on the Raspberry Pi's SD card every time last is updated. I want to store last in RAM.
Thanks so much!

A: This is just for inspiration. I don't have my Pis at hand so this is written blindly from memory.
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
# the line below is important. It'll fire on both rising and falling edges
# and it's non-blocking
GPIO.add_event_detect(17, GPIO.BOTH, callback=callback_func)

length_of_last_high = 0
length_of_last_low = 0

last_rise = 0
last_fall = 0
last_callback = 0

def callback_func(pin):
    # all of these global variables aren't needed
    # but I left them in for demo purposes
    global last_rise
    global last_fall
    global last_callback
    global length_of_last_high
    global length_of_last_low
    last_callback = time.time()
    if GPIO.input(17):
        print "Pin 17 is rising!"
        length_of_last_high = last_callback - last_rise
        last_rise = last_callback
    else:
        print "Pin 17 is falling!"
        length_of_last_low = last_callback - last_fall
        last_fall = last_callback

# last passed as parameter (the preferred solution if it works).
# You test it - I can't at the moment
def get_state(last=last_rise):
    engine_state = False
    if time.time() - last < .5:
        engine_state = True
    return engine_state

# last as global variable.
# This works too but global is bad practice if it can be avoided
# (namespace littering)
def get_state2():
    global last_rise
    engine_state = False
    if time.time() - last_rise < .5:
        engine_state = True
    return engine_state

def main():
    while True:
        print "Not blocking! This loop could sleep forever. It wouldn't affect the readings"
        time.sleep(1)
        print get_state()

"""
GPIO.cleanup()
"""


text:
Q: Angular, Node.js, MySQL image upload I want to send an image to MySQL blob feild using node.js and use Angular to display that blob as an image.
Any ideas how to do it?

A: It would be better if you upload image file on server and get its path and store that path in MySQL database.
for example if user wants to upload test.jpg
on server save it like : server/images/test.jpg
then insert saved path to MySQL
and on front-end retrieve image path and bind to src property of image tag.
saving blobs to database will result in slow response when you will fetch records.
you can see more details here: https://blog.jscrambler.com/implementing-file-upload-using-node-and-angular


text:
Q: Creating JSON Object Pojo for json String I have a scenario like this in which  need to be converted to object using Object mapper .Hence i create a proerty like below to capture OrderDispatchItemDTO.
@JsonProperty("OrderDispatchItemDTO")
    private OrderDispatchItemDTO orderDispatchItemsDTO;

{
  "Message": {

    "MessageData": {
      "OrderDispatchDTO": {
        "StartDateTime": "2017-05-19T02:45:00",
        "Details": {
          "OrderDispatchItemDTO": {
          more json properties
          }
        },
        "EndDateTime": "2017-05-19T05:45:00",
      }
    },
    "StatusID": 1,
  }
}

But if OrderDispatchItemDTO comes as list then my mapper fails as its not able to parse the json string
 @JsonProperty("OrderDispatchItemDTO")
        private List<OrderDispatchItemDTO> orderDispatchItemsDTO;

  {
          "Message": {

            "MessageData": {
              "OrderDispatchDTO": {
                "StartDateTime": "2017-05-19T02:45:00",
                "Details": [
                  "OrderDispatchItemDTO": {
                  more json properties
                  },
"OrderDispatchItemDTO": {
                  more json properties
                  }
                ],
                "EndDateTime": "2017-05-19T05:45:00",
              }
            },
            "StatusID": 1,
          }
        }

fix is          mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

A: You can use the @JsonAnySetter attribute and set your list dynamically. Here is an example. In my case one property can be either a number or an object, so here is how I solved it simply:
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
    try {
        if (name.equals("property") && value != null) {
            MyObject t = null;
            if (value instanceof Long) {
                t = new MyObject();
                t.setId((Long) value);
            } else if (value instanceof LinkedHashMap) {
                t = mapper.convertValue(value, MyObject.class);
            }
            //putting t anywhere i.e. setting property
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}


text:
Q: Null value in the controller after @PostMapping | Java I am trying to create a web application in Java using Spring.
The idea would be to call in @Get the model that displays the data entry form and then in @Post I would like to insert them in my persistence layer (SQL Server).
The problem is that I cannot make the object I pass in @Get be filled by the form, and therefore subsequently insert the data into the database. The attributes of the object I receive in @Post are all null and I can't understand why.
There is my controller:
package com.test.webapp.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.test.weapp.domain.Categorie;
import com.test.weapp.domain.File;
import com.test.weapp.domain.Regioni;
import com.test.webapp.repository.CategorieRepository;
import com.test.webapp.repository.FileRepository;
import com.test.webapp.repository.RegioniRepository;

@Controller
@RequestMapping("/")
public class IndexController
{
    @Autowired
    private CategorieRepository categorieRepository;

    @Autowired
    private RegioniRepository regioniRepository;

    @Autowired
    private FileRepository fileRepository;

    @GetMapping(value="/index")
    public String getWelcome(Model model)
    {
        File file = new File();

        model.addAttribute("regioni", getRegioni());
        model.addAttribute("categorie", getCategorie());
        model.addAttribute("Fileee", file);
        return "home";
    }

    @PostMapping(value="/index")
    public String GestInsFile (@ModelAttribute("Fileee") File file)
    {
            fileRepository.InsFile(file);
            return "home";
    }

    @ModelAttribute("regioni")
    public List<Regioni> getRegioni()
    {
        List<Regioni> regioni = regioniRepository.SelRegioni();

        return regioni;
    }

    @ModelAttribute("categorie")
    public List<Categorie> getCategorie()
    {
        List<Categorie> categorie = categorieRepository.SelCategorie();

        return categorie;
    }

}

Class File:
package com.test.weapp.domain;

import java.io.Serializable;
import java.util.Date;

import org.springframework.web.multipart.MultipartFile;

public class File implements Serializable {

    private static final long serialVersionUID = -316224596822077411L;

    private int id;
    private String titolo;
    private String regione;
    private String categoria;
    private String descrizione;
    private String note;
    private MultipartFile file;

    public File() {

    }

    public MultipartFile getFile() {
        return file;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitolo() {
        return titolo;
    }

    public void setTitolo(String titolo) {
        this.titolo = titolo;
    }

    public String getRegione() {
        return regione;
    }

    public void setRegione(String regione) {
        this.regione = regione;
    }

    public String getCategoria() {
        return categoria;
    }

    public void setCategoria(String categoria) {
        this.categoria = categoria;
    }

    public String getDescrizione() {
        return descrizione;
    }

    public void setDescrizione(String descrizione) {
        this.descrizione = descrizione;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

}

Class Categorie
package com.test.weapp.domain;

import java.io.Serializable;

public class Categorie implements Serializable
{

    private static final long serialVersionUID = 6904000811482985125L;

    private int id;
    private String categoria;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCategoria() {
        return categoria;
    }

    public void setCategoria(String categoria) {
        this.categoria = categoria;
    }

    public Categorie() {

    }

}

Class Regioni
package com.test.weapp.domain;

import java.io.Serializable;

public class Regioni implements Serializable
{

    private static final long serialVersionUID = 7083492150275199488L;

    private int id;
    private String regione;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getRegione() {
        return regione;
    }
    public void setRegione(String regione) {
        this.regione = regione;
    }
    public Regioni() {

    }

}

Class FileRepositoryImpl that inserts into the table
package com.test.webapp.repository;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.test.weapp.domain.File;

@Repository
public class FileRepositoryImpl implements FileRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<File> SelFileByFilter(String id) {
        return null;
    }

    @Override
    public void InsFile(File file) {
        String Sql = "insert into [dbo].[FILE] VALUES ('" + file.getTitolo() + "','" + file.getRegione() + "','"
                + file.getCategoria() + "','"  + file.getDescrizione() + "','" + file.getNote()
                + "');";

        jdbcTemplate.update(Sql);
    }

    @Override
    public void DelFile(String id) {

    }

}

And here is my JSP showing the Home.jsp compile form
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<!doctype html>

<meta charset="utf-8">
<meta name="viewport"
    content="width=device-width, initial-scale=1, shrink-to-fit=no">

<link href="<c:url value="/static/css/style.css" />" rel="stylesheet">

<title>Area Riservata</title>

Area Riservata

Bim Italia Srl

        <form:form action ="index" method="POST" modelAttribute="Fileee"
            enctype="multipart/form-data">

Informazioni File

                        File:
                        <form:input path="file" type="file" class="form:input-large" />

                        Titolo:
                        <form:input path="titolo" type="text" class="form-control" />

                        Regione:
                        <form:select path="regione" class="form-control">
                                <form:options items="${regioni}" itemValue="Id" itemLabel="Regione" />
                            </form:select>

                        Categoria:
                        <form:select path="categoria" class="form-control">
                                <form:options items="${categorie}" itemValue="Id" itemLabel="Categoria" />
                            </form:select>

                        Descrizione:
                        <form:textarea path="descrizione" rows="2" cols="33" autoResize="true" style="font-family: Helvetica Neue,Helvetica,Arial,sans-serif;" />

                        Note:
                        <form:textarea path="note" rows="2" cols="33" autoResize="true" style="font-family: Helvetica Neue,Helvetica,Arial,sans-serif;" />

        <input type="submit" id="btnAdd" />
                </form:form>

Here the data entered are all null!
Please help me understand why my form does not return the fields I filled in!
Thanks for the attention.

A: add File  in your getWelcome controller  @RequestBody annotation
   @GetMapping(value="/index")
    public String getWelcome(@RequestBody File file, Model model)
    {

        model.addAttribute("regioni", file.getRegioni());
        model.addAttribute("categorie", file.getCategorie());
        model.addAttribute("Fileee", file);
        return "home";
    }


text:
Q: How to aggregate based on one repeated value in a column I'm trying to aggregate data based on one particular field in my PL/SQL procedure. I have this table, let's call it MYTABLE:

And I want to obtain the following:

Values of column c have to appear only once,
values of column d have to be the same as the d value of the lines having b=1 and c=1111,
values of column e have to be populated with the minimum value of column e for the two equal line in c (min between 0 and -1 of 1111)
Thanks,
Ilaria

A: PL/SQL is not required for this.  You can do your aggregation in SQL.
After setting up the data:
CREATE TABLE MYTABLE (
  A NUMBER,
  B NUMBER,
  C NUMBER,
  D NUMBER,
  E NUMBER
);

INSERT INTO MYTABLE VALUES (111, 0, 1111, 11, 0);
INSERT INTO MYTABLE VALUES (222, 1, 2222, 22, 1);
INSERT INTO MYTABLE VALUES (222, 1, 1111, 22, 1);
INSERT INTO MYTABLE VALUES (222, 1, 3333, 22, 1);
COMMIT;

We can first make our only goal selecting DISTINCT values of C, and do so by GROUP BY C:
SQL> SELECT C
  2  FROM MYTABLE
  3  GROUP BY C;

2222
1111
3333

Then, to get the lowest value of E for each distinct value of C, we must apply an aggregate function to E, so there is only one value returned for each unique value of C:
SQL> SELECT C, MIN(E) AS E
  2  FROM MYTABLE
  3  GROUP BY C
  4  ORDER BY C ASC, E ASC;

1111  0
2222  1
3333  1

Please note this disagrees with the example table you provided, but should be in keeping with your described goal:

"values of column e have to be populated with the minimum value of
  column e for the two equal line in c"

Then to include D, we will again need an aggregate function (This will be the case for each column besides C, since a unique value needs to be returned for each non-C column.  In this case the value is not a simple MIN/MAX but has some dependency on the value of B as well.  In this case I would suggest KEEP in your aggregate function.  The below will work for the sample you've provided, but you may need to alter the conditions to work with your goals:
SQL> SELECT C,
  2    MIN(D) KEEP (DENSE_RANK LAST ORDER BY B ASC) AS D,
  3    MIN(E) AS E
  4  FROM MYTABLE
  5  GROUP BY C
  6  ORDER BY C ASC, D ASC, E ASC;

1111  22  0
2222  22  1
3333  22  1

Compare the above with this alternative, and one can see the value of B is being considered:
SQL> SELECT C,
  2    MIN(D) KEEP (DENSE_RANK LAST ORDER BY B DESC) AS D,
  3    MIN(E) AS E
  4  FROM MYTABLE
  5  GROUP BY C
  6  ORDER BY C ASC, D ASC, E ASC;

1111  11  0
2222  22  1
3333  22  1

Then, to finish the query, apply aggregate functions to A and B.  You didn't specify how you wanted to compress them, so I'm just using MIN as a placeholder that happens to work with your data.
SQL> SELECT
  2    MIN(A) AS A,
  3    MIN(B) AS B,
  4    C      AS C,
  5    MIN(D) KEEP (DENSE_RANK LAST ORDER BY B ASC) AS D,
  6    MIN(E) AS E
  7  FROM MYTABLE
  8  GROUP BY C
  9  ORDER BY C ASC, A ASC, B ASC, D ASC, E ASC;

111  0  1111  22  0
222  1  2222  22  1
222  1  3333  22  1

EDIT: for further discussion about FIRST/LAST:
Here's an example to illustrate KEEP and ranking.
There's a lot to explore with these, the documentation can be useful.
To explore what KEEP is doing, I'll switch to a general example with movies.  Suppose you had the following table.  It includes movie studios, movie titles they produce, along with their profit and how much people like them:
CREATE TABLE MOVIE(
  MOVIE_TITLE VARCHAR2(200) NOT NULL PRIMARY KEY,
  DISTRIBUTOR VARCHAR2(200) NOT NULL,
  MONEY_MADE  NUMBER(15,2) NOT NULL,
  REVIEW_SCORE NUMBER(3,0) NOT NULL
);
INSERT INTO MOVIE VALUES ('Avatar','Fox',2787965087,83);
INSERT INTO MOVIE VALUES ('Aliens','Fox',183000000,98);
--Not true moned-made, but just pretend
INSERT INTO MOVIE VALUES ('Prometheus','Fox',2787965087,72);
INSERT INTO MOVIE VALUES ('Terminator','Orion',78000000,100);
INSERT INTO MOVIE VALUES ('RoboCop','Orion',53000000,88);
COMMIT;

Both 'Fox' and 'Orion' in this example appear in the data multiple times.
If we want to, we can find the most profit on a single movie for each studio with standard aggregation:
SQL> SELECT DISTRIBUTOR, MAX(MONEY_MADE) FROM MOVIE
  2  GROUP BY DISTRIBUTOR;
DISTRIBUTOR  MAX(MONEY_MADE)
Orion        78000000
Fox          2787965087

But, that doesn't actually tell us which movie made the most money.  We could try to take MIN or MAX on the title, but that wouldn't help since the MAX movie maybe didn't make the most money; they are in different columns--they are independent.  So we instead can KEEP the movie that made the most money.  The "fact" that Prometheus and Avatar made the same amount of money matters here:
SELECT DISTRIBUTOR,
  MAX(MOVIE_TITLE) KEEP (DENSE_RANK LAST ORDER BY MONEY_MADE ASC) AS MOVIE_TITLE
FROM MOVIE
GROUP BY DISTRIBUTOR;

DISTRIBUTOR  MOVIE_TITLE
Fox          Prometheus
Orion        Terminator

This says: "For each Movie Studio, go get the movies that made the most money, and if there's a tie, just get the MAX (alphabetic) so I only have one row".
DENSE_RANK and FIRST/LAST is what gets us the highest-earning movie(s) per studio.  KEEP comes in and says "RANK the movies per studio by their MONEY_MADE, and only KEEP the LAST (most profitable) one(s)".  Since we have a tie between Avatar and Prometheus, the KEEP will return those two, then MAX helps resolve the tie (alphabetically).
If I switch to MIN, I'll get Avatar because it is alphabetically first:
SELECT DISTRIBUTOR,
  MIN(MOVIE_TITLE) KEEP (DENSE_RANK LAST ORDER BY MONEY_MADE ASC) AS MOVIE_TITLE
FROM MOVIE
GROUP BY DISTRIBUTOR;
DISTRIBUTOR  MOVIE_TITLE
Fox          Avatar
Orion        Terminator

If I KEEP the FIRST instead of the LAST, I'll get the lowest-money-made per studio:
SELECT DISTRIBUTOR,
  MIN(MOVIE_TITLE) KEEP (DENSE_RANK FIRST ORDER BY MONEY_MADE ASC) AS MOVIE_TITLE
FROM MOVIE
GROUP BY DISTRIBUTOR;
DISTRIBUTOR  MOVIE_TITLE
Fox          Aliens
Orion        RoboCop

In this way, KEEP and RANK let us compare across rows and have more control what the aggregation returns.
I hope this helps.


text:
Q: Where is encfs password stored How and where does encfs store the password for an encrypted directory?
I understand that encfs uses encfs6.xml to store the actual decryption key encoded using the password. I also understand that encfs6.xml is the only file required for decryption. I therefore assumed that the password hash should also be stored in the same file. However, I only see encodedKeyData and saltData in the file.
What I want to know is how does encfs make sure I have entered the correct password simply with the help of the information present in encfs6.xml

A: This Q&A how-do-decryption-algorithms-determine-whether-your-attempted-passphrase-is-correct suggest that decryption algorithms which needs to know if a passphrase is correct uses HMAC to validate the correctness of the passphrase.

Therefore, when it's important to be able to inform the user whether a
  decryption operation has succeeded in yielding the expected data,
  cryptography engineers use Message Authentication Codes.
  Hash-based MACs allow a candidate plaintext to be compared against an
  authenticated hash value. If the check passes, then we know that it is
  the correct plaintext and are then able to notify the user that the
  decryption function was successful as intended.

Some info about encfs design :

*

*There is volume key which is used for encrypting all file names and contents

*A user supplied password is used to decrypt a volume key

The password you provides is used in order to decrypt the volume key.

Technology

*

*Encfs uses algorithms from third-party libraries (OpenSSL is the default) to encrypt data and filenames.

*A user supplied password is used to decrypt a volume key, and the volume key is used for encrypting all file names and contents. This
  makes it possible to change the password without needing to re-encrypt
  all files.

According to this security audit

*

*EncFS uses the same key for encrypting data and computing MACs

*EncFS uses 64-bit MACs.

*EncFS uses Mac-then-Encrypt

*The purpose of MAC headers is to prevent an attacker with read/write
access to the ciphertext from being able to make changes without being
detected.  Unfortunately, this feature provides little security, since
it is controlled by an option in the .encfs6.xml configuration file

Answer to the question in comment, the MAC is being saved as part of each  encryped file.

A: Upon looking at encfs source it seems that the first 4 characters (bytes) of encodedKeyData is the hash used for HMAC validation.
https://github.com/vgough/encfs/blob/7cc6efa60ca7378ba2b95be1fe5804a97f29af10/encfs/SSL_Cipher.cpp#L530#L546
and
https://github.com/vgough/encfs/blob/7cc6efa60ca7378ba2b95be1fe5804a97f29af10/encfs/SSL_Cipher.cpp#L49


text:
Q: jScrollPane - How to get fixed width for track I am using jScrollPane on my website and everything works fine but I want to do the following: Currently the track has a width of 100% (it stretches as much as the content does) but I don't want to make it stretchable as the content, I want it to have a fixed width of for example 400px.
Is there any chance that can be done? I have tried changing it in style.css but doesn't seem to work :(
Thank you

A: http://jscrollpane.kelvinluck.com/settings.html
horizontalDragMinWidth = 400;
horizontalDragMaxWidth = 400;
i think this will do the trick


text:
Q: why Ubuntu command prompt is not prompting after executing the mail command? uuencode text.txt | mail -s "hai" "abc@gmail.com" < body.txt

after executing this command, terminal is blank. It is not prompting for next command. I have to press ctrl+z to return to terminal.
What could be the problem?

A: Well, you don't do it this way ;-) Nice try though!
You are using the pipe "|" to write the output of your uuencode command to the input channel (aka. stdin, standard input) of the mail command. You are also using the shell redirection "<" to write the file contents of body.txt to the input channel of you mail command.
This is ambiguous. I am not sure right now, what takes precedence, or how the shell handles the situation. You probably end up with one of the programs asking for input.
Better clarify for the shell, what to do, in what order. I.e. by writing:
(cat body.txt; uuencode text.txt) |mail -s "hai" "abc@gmail.com"

This executes cat (the file printer) and uuencode in one rush (in a subshell to be precise, due to the parenthesis) and pipes the common output to the mail program


text:
Q: sysmalloc: Assertion failure on ubuntu environment The C code below runs fine in my mac OS X environment, but if i try to run this code in a ubuntu environment, i get a malloc assert failure whenever i put in even number of inputs, such as "1 2", but odd input "1 2 3" works. the error is.
a.out: malloc.c:2372: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.
Aborted (core dumped)
I have no clue the difference between the OS X and ubuntu environment, so if anybody can point out what's wrong i'd appreciate it. I'm running Ubuntu 14.04.  It seems to crash within the y != NULL loop
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>

void free_argv(char **argv,int counter)
{
    int i = 0;
    for(i=0;i<counter;i++)
    {
        free(argv[i]);
    }

    free(argv);
}

int main()
{
    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    char **argv = NULL;
    int counter;
    int status;

    while ((read = getline(&line, &len, stdin)) != -1)
    {

        counter = 1;
        printf("$ ");
        char* x = strtok(line,"\n");

        int i = 0;

        while(x[i] != '\0')
        {
            if(x[i] == ' ')
            {
                counter++;
            }
            i++;
        }

        argv = malloc(sizeof(char*)*(counter+1));

        argv[counter+1] = NULL;

        i = 0;

        char* y = strtok(x," ");

        printf("user input:\n");
        while(y != NULL)
        {
            argv[i] = malloc(sizeof(char)*strlen(y));
            strncpy(argv[i],y,strlen(y));
            printf("      %s\n",argv[i]);
            y = strtok(NULL," ");
            i++;
        }
        free_argv(argv,counter);
    }
    return 0;
}

A: Consider using valgrind in such cases - it is very helpful! What it gave to me:
==6454== Invalid write of size 8
==6454==    at 0x4008CE: main (sysmalloc.c:49)
==6454==  Address 0x51e0128 is 0 bytes after a block of size 40 alloc'd
==6454==    at 0x4C2C27B: malloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==6454==    by 0x4008B1: main (sysmalloc.c:47)

sysmalloc.c:49 is argv[counter+1] = NULL; - this is line caused problem. Note that in C array indexes start with zero, so for array of length N+1 last index is N. So instead of writing last argv pointer, you wrote NULL to area used internally by sysmalloc and thus caused a fault.
Change this line to argv[counter] = NULL;
Also note comments about strcpy usage.

A: In addition to the argv[counter+1] problem referenced by myaut, these lines:
argv[i] = malloc(sizeof(char)*strlen(y));
strncpy(argv[i],y,strlen(y));
printf("      %s\n",argv[i]);

are printing a string which is not guaranteed to be null-terminated.
malloc(sizeof(char)*strlen(y));

does not allocate enough space for the null terminator (you would need strlen(y) + 1).  The strncpy will not overflow the buffer, but neither will it supply a terminator.  The printf() is printing a string which you have not terminated - if it prints the right thing, it is by happenstance that the argv[i] buffer is followed by a zero byte.
Also, I do not think you need the first strtok() call because getline() has done that work for you, and argv is a confusing name for your variable given that it is unlike its common usage as the command-line input.  Neither of those things are causing your crash, though.


text:
Q: Post to Twitter video with duration more than 30 seconds from iOS App? I have to upload video about 1 min duration to Twitter from my iOS app, but Twitter doesn't allow to upload videos more than 30 secs.
I know that before it was possible to use some 3rd party services like TwitVid, but now all of these services not working.
Is there any solution to upload or embed in Twitter posts videos more than 30 seconds duration?


text:
Q: I want my main to overlap my jumbotron in Bootstrap I'm trying to make my main container slightly overlap on top of my jumbotron, I have tried messing with "my,mb,py,pb" but it doesn't cause an overlap

Jumbotron H text

Text

            <?php
                if(isset($_SESSION) && isset($_SESSION['login'])){ ?>
                Welcome <?php echo $username; ?>

          Since <?php echo $created; ?>
                <?php }else{ ?>
                Please Sign in or Register
                <?php } ?>

I want the jumbotron to be the full horizontal width and the  content to be about halfway over the jumbotron on top, I just tried the position absolute on the jumbotron like someone suggested however it just caused the jumbotron to be squished

A: If you want that  overlaps
 slightly you could   add a negative margin-top to  main.

main.negative-margin {
  margin-top: -3rem;
}

/* the style form   */
html,
body {
  overflow-x: hidden; /* Prevent scroll on narrow devices */
}

body {
  padding-top: 56px;
}

@media (max-width: 767.98px) {
  .offcanvas-collapse {
    position: fixed;
    top: 56px; /* Height of navbar */
    bottom: 0;
    width: 100%;
    padding-right: 1rem;
    padding-left: 1rem;
    overflow-y: auto;
    background-color: var(--gray-dark);
    transition: -webkit-transform .3s ease-in-out;
    transition: transform .3s ease-in-out;
    transition: transform .3s ease-in-out, -webkit-transform .3s ease-in-out;
    -webkit-transform: translateX(100%);
    transform: translateX(100%);
  }
  .offcanvas-collapse.open {
    -webkit-transform: translateX(-1rem);
    transform: translateX(-1rem); /* Account for horizontal padding on navbar */
  }
}

.nav-scroller {
  position: relative;
  z-index: 2;
  height: 2.75rem;
  overflow-y: hidden;
}

.nav-scroller .nav {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: nowrap;
  flex-wrap: nowrap;
  padding-bottom: 1rem;
  margin-top: -1px;
  overflow-x: auto;
  color: rgba(255, 255, 255, .75);
  text-align: center;
  white-space: nowrap;
  -webkit-overflow-scrolling: touch;
}

.nav-underline .nav-link {
  padding-top: .75rem;
  padding-bottom: .75rem;
  font-size: .875rem;
  color: var(--secondary);
}

.nav-underline .nav-link:hover {
  color: var(--blue);
}

.nav-underline .active {
  font-weight: 500;
  color: var(--gray-dark);
}

.text-white-50 { color: rgba(255, 255, 255, .5); }

.bg-purple { background-color: var(--purple); }

.border-bottom { border-bottom: 1px solid #e5e5e5; }

.box-shadow { box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05); }

.lh-100 { line-height: 1; }
.lh-125 { line-height: 1.25; }
.lh-150 { line-height: 1.5; }
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

Jumbotron H text

Text

          Welcome

      Since  Please Sign in or Register

Servers

                        <input type="radio" name="options" checked>
                        Votes

                        <input type="radio" class="d-none d-sm-none" name="options">
                        PVP

                        <input type="radio" class="d-none" name="options">
                        PVE


text:
Q: Error al llamar al webservice SII (Suministro Inmediato de Información) de la AEAT Al hacer la llamada a un método del webservice de la AEAT me da el siguiente error:

The content type text/html of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <title>Agencia Tributaria - Se ha producido un error</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="https://www.agenciatributaria.gob.es/static_files/common/css/xzhtcs04.css" rel="stylesheet" type="text/css">
>

>

     '.

La llamada al ws la estoy haciendo así:
SuministroLRFacturasEmitidas FacturaEmitida = ObtenerObjetoEnvioFacturaEmitida();

siiSOAPClient wsSuministroFacturasEmitidas = new siiSOAPClient();

wsSuministroFacturasEmitidas.ClientCredentials.ClientCertificate.Certificate = certificadoObtenido;
wsSuministroFacturasEmitidas.ClientCredentials.UseIdentityConfiguration = true;
RespuestaLRFEmitidasType resultadoEnvioFactura = wsSuministroFacturasEmitidas.SuministroLRFacturasEmitidas(FacturaEmitida);

el objeto que le paso al webservice es este:
private static SuministroLRFacturasEmitidas ObtenerObjetoEnvioFacturaEmitida()
{
    //ObjetoGeneral Factura Emitida
    SuministroLRFacturasEmitidas FacturaEmitida = new SuministroLRFacturasEmitidas();

    //ObjetoCabecera Factura Emitida -> dentro lleva un objeto Titular
    CabeceraSii CabeceraFacutraEmitida = new CabeceraSii();
    //Objeto Titular
    PersonaFisicaJuridicaESType TitularFacturaEmitida = new PersonaFisicaJuridicaESType();
    //Facturas Emitidas
    List<LRfacturasEmitidasType> FacturasEmitidas = new List<LRfacturasEmitidasType>();
    //Periodo Impositivo
    RegistroSiiPeriodoImpositivo itemPeriodoImpositivo = new RegistroSiiPeriodoImpositivo();
    //Objeto Item para la factura
    LRfacturasEmitidasType ItemFactura = new LRfacturasEmitidasType();
    //Objeto IdFactura -> Contiene un objeto de tipo IDEmisora
    IDFacturaExpedidaType IdFactura = new IDFacturaExpedidaType();
    //Objeto IDEmisora
    IDFacturaExpedidaTypeIDEmisorFactura IDEmisora = new IDFacturaExpedidaTypeIDEmisorFactura();
    //Objeto Factura ExpedidaType
    FacturaExpedidaType FacturaExpedida = new FacturaExpedidaType();
    //Objeto FacturasAgrupadas
    IDFacturaARType[] FacturasAgrupadas = new IDFacturaARType[1];
    IDFacturaARType ElementoFacturasAgrupadas = new IDFacturaARType();

    //Objeto Facturas Rectificativas
    IDFacturaARType[] FacturasRectificativas = new IDFacturaARType[1];
    IDFacturaARType ElementoFacturasRectificativas = new IDFacturaARType();

    //ObjetoImporteRectificacion
    DesgloseRectificacionType ImporteRectificacion = new DesgloseRectificacionType();

    //Objeto DatosInmueble
    DatosInmuebleType[] DatosInmueble = new DatosInmuebleType[1];
    DatosInmuebleType ElementoDatosInmueble = new DatosInmuebleType();

    //Objeto Contraparte
    PersonaFisicaJuridicaType Contraparte = new PersonaFisicaJuridicaType();
    //Ojeto TipoDesglose
    FacturaExpedidaTypeTipoDesglose TipoDesglose = new FacturaExpedidaTypeTipoDesglose();

    CabeceraFacutraEmitida.IDVersionSii = VersionSiiType.Item06;
    CabeceraFacutraEmitida.TipoComunicacion = ClaveTipoComunicacionType.A0;
    CabeceraFacutraEmitida.Titular = TitularFacturaEmitida;

    //Titular de la cabecera de la factura
    TitularFacturaEmitida.NIF = "AAAA";
    TitularFacturaEmitida.NombreRazon = "prueba";
    TitularFacturaEmitida.NIFRepresentante = "RepresentanteXXXXX";

    FacturaEmitida.Cabecera = CabeceraFacutraEmitida; //Añadida cabecera de la factura

    itemPeriodoImpositivo.Periodo = TipoPeriodoType.Item01;
    itemPeriodoImpositivo.Ejercicio = "2015";
    ItemFactura.PeriodoImpositivo = itemPeriodoImpositivo;

    IDEmisora.NIF = "A84532501";
    IdFactura.NumSerieFacturaEmisor = "01";
    IdFactura.NumSerieFacturaEmisorResumenFin = "01";
    IdFactura.FechaExpedicionFacturaEmisor = "15-01-2015";
    IdFactura.IDEmisorFactura = IDEmisora;

    ItemFactura.IDFactura = IdFactura;

    FacturaExpedida.TipoFactura = ClaveTipoFacturaType.F1;
    FacturaExpedida.TipoRectificativa = ClaveTipoRectificativaType.I;
        FacturaExpedida.FechaOperacion = "15-01-2015";
    FacturaExpedida.ClaveRegimenEspecialOTrascendencia = IdOperacionesTrascendenciaTributariaType.Item01;
    FacturaExpedida.ImporteTotal = "26.70";
    FacturaExpedida.BaseImponibleACoste = "526";
    FacturaExpedida.DescripcionOperacion = "CompraXXXXXXX";
    FacturaExpedida.ImporteTransmisionSujetoAIVA = "Importe";
    FacturaExpedida.VariosDestinatarios = VariosDestinatariosType.N;
    FacturaExpedida.EmitidaPorTerceros = EmitidaPorTercerosType.N;
    FacturaExpedida.Cupon = CuponType.N;

    ElementoFacturasAgrupadas.NumSerieFacturaEmisor = "SERIE";
    ElementoFacturasAgrupadas.FechaExpedicionFacturaEmisor = "15-01-2015";
    FacturasAgrupadas[0] = ElementoFacturasAgrupadas;
    FacturaExpedida.FacturasAgrupadas = FacturasAgrupadas;

    ItemFactura.FacturaExpedida = FacturaExpedida;

    ElementoFacturasRectificativas.NumSerieFacturaEmisor = "SERIE";
    ElementoFacturasRectificativas.FechaExpedicionFacturaEmisor = "15-01-2015";
    FacturasRectificativas[0] = ElementoFacturasRectificativas;
    FacturaExpedida.FacturasRectificadas = FacturasRectificativas;

    ImporteRectificacion.BaseRectificada = "BASE";
    ImporteRectificacion.CuotaRecargoRectificado = "Cuota";
    ImporteRectificacion.CuotaRectificada = "Cuota";
    FacturaExpedida.ImporteRectificacion = ImporteRectificacion;

    ElementoDatosInmueble.SituacionInmueble = SituacionInmuebleType.Item1;
    ElementoDatosInmueble.ReferenciaCatastral = "Ref";

    DatosInmueble[0] = ElementoDatosInmueble;
    FacturaExpedida.DatosInmueble = DatosInmueble;

    Contraparte.NombreRazon = "EMPRESAYYYYYYYY";
    Contraparte.NIFRepresentante = "NIF";
    Contraparte.Item = "Item";
    FacturaExpedida.Contraparte = Contraparte;

    //((SuministroFactEmitidas.TipoSinDesgloseType)oSfe.RegistroLRFacturasEmitidas(0).FacturaExpedida.TipoDesglose.Item).Sujeta == new SuministroFactEmitidas.SujetaType()
    //TipoDesglose.Item = "";
    //TipoDesglose.Item
    //FacturaExpedida.TipoDesglose = TipoDesglose;

    //XmlSerializer serializer = new XmlSerializer(typeof(SuministroLRFacturasEmitidas));
    //using(TextWriter writer = new StreamWriter(@"C:\Xml.xml"))
    //{
    //    serializer.Serialize(writer, FacturaEmitida);
    //}

    return FacturaEmitida;
}

Y la configuración del app.config del webservice es esta
<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="siiBinding">
                <security mode="Transport">
                    <transport clientCredentialType="Certificate" />
                </security>
            </binding>
        </basicHttpBinding>
        <customBinding>
            <binding name="siiBinding">
                <textMessageEncoding messageVersion="Soap11" />
                <httpsTransport />
            </binding>
        </customBinding>
    </bindings>

    <client>
        <endpoint address="https://www7.aeat.es/wlpl/SSII-FACT/ws/fe/SiiFactFEV1SOAP"
            binding="basicHttpBinding" bindingConfiguration="siiBinding"
            contract="SuministroFactEmitidas.siiSOAP" name="SuministroFactEmitidasPruebas" />
    </client>

</system.serviceModel>

¿Alguien podría saber qué es lo que pasa?

A: El problema lo tienes en tu endpoint. Verás,

*

*Para Emitidas:
https://www7.aeat.es/wlpl/SSII-FACT/ws/fe/SiiFactFEV1SOAP

*Para Recibidas:
https://www7.aeat.es/wlpl/SSII-FACT/ws/fr/SiiFactFEV1SOAP

A mí me pasó lo mismo y casi me vuelvo loca y sólo tienes que cambiar fe por fr.

A: Solucioné el error que te daba al principio añadiendole el certificado.

The content type text/html of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were:

Ahora me da el siguiente error:

No se pudo establecer un canal seguro para SSL/TLS con la autoridad 'http://www7.aeat.es'

He leído por ahí como hacer que nos comuniquemos por SSL/TLS haciendo una "trampa". El código quedaría:
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
System.Net.ServicePointManager.Expect100Continue = false;

BasicHttpBinding binding = new BasicHttpBinding();
binding.Name = "siiBinding";
binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;

FacturasEmitidas.siiSOAPClient Servicio = new FacturasEmitidas.siiSOAPClient("SuministroFactEmitidasPruebas", new EndpointAddress("https://www7.aeat.es/wlpl/SSII-FACT/ws/fe/SiiFactFEV1SOAP"));
Servicio.Endpoint.Binding = binding;

Servicio.ClientCredentials.ClientCertificate.Certificate =
cFunciones.EncontrarCertificado(DatosEnvio.NombreCertificado);
                Servicio.ClientCredentials.UseIdentityConfiguration = true;

Servicio.SuministroLRFacturasEmitidas(GrupoFacturasAEAT.FacturasAltas.Facturas);

Hay que crearse una función para el tema del SSL/TLS:
public static bool ValidateServerCertificate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
   return true;
}

Ya he conseguido que me envíe sin errores. He añadido las siguientes dos líneas antes de hacer el envío:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

Esto obliga a establecer una conexión TLS. También he cambiado la forma en la que informaba del certificado, pues parece ser que a la hora de conectarse no pide las credenciales de forma correcta, así que la contraseña la incluyo en los parámetros para poder autenticar el certificado.
string certPath = @"D:\TMP\Certificado.pfx";
string certPass = "clave";
X509Certificate2 certifikat = new X509Certificate2(certPath, certPass, X509KeyStorageFlags.Exportable);

BasicHttpBinding binding = new BasicHttpBinding();
binding.Name = "siiBinding";
binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;

FacturasEmitidas.siiSOAPClient Servicio = new FacturasEmitidas.siiSOAPClient("SuministroFactEmitidasPruebas", new EndpointAddress("https://www7.aeat.es/wlpl/SSII-FACT/ws/fe/SiiFactFEV1SOAP"));
Servicio.Endpoint.Binding = binding;
Servicio.ClientCredentials.ClientCertificate.Certificate = certifikat;


text:
Q: VBA XML HTTP setrequest header in GET request based on previous getresponseheader (token) value For a product scraping project I need to pass a value in the header of a GET request with XMLHTTP in VBA. The value / token that needs to be passed is extracted from a previous XMLHTTP GET request (getReponseHeader) and stored in a variable in VBA.
When passing the value with setRequestHeader in a PUT request the correct value is passed on correctly (when checking with a getReponseHeader afterwards). But when sending the value in a GET request it doesn't work (a different token is extracted).
By connecting the correct store information with the active session (by sending the token in the header) the specific price for a product can be extracted that is linked to the specific store. For the sample product the price of 1,87 is the one i need. When no store is linked to the session the price of 1,97 is extracted. This is why i need to send the header information with correct x-jumbo-token in the following GET requests.
Here is what i need to do:

*

*Extract a token (x-jumbo-token) from a first XMLHTTP request

*Save/store this token in a VBA variable (and send it in header together with all the following requests).

*Send a PUT request with some store information in a JSON body and send the x-jumbo-token also as a request header (store information is connected now to the session).

*Send a GET request to another URL (together with the session token in the header) to extract the product information for the correct store.

Here is is the code i currently have.
Sub GetJumboPriceXML()

Dim XMLReq As New MSXML2.XMLHTTP60
Dim JumboPrice As Double
Dim SKU_tag As String, SKU_url As String
Dim Jumbo_token As String
Dim Body As String

'sample product (MARS 225gr) --> price 1,97 (when no store is selected), 1,87 when correct store is linked (store id 3065, complexNumber 33164)
SKU_tag = "153501PAK"
SKU_url = "http://mobileapi.jumbo.com/v2/products/" & SKU_tag

'get the x-jumbo-token value from the configuration page
XMLReq.Open "GET", "http://mobileapi.jumbo.com/v2/configuration", False
XMLReq.send
'store in variable
Jumbo_token = XMLReq.getResponseHeader("x-jumbo-token")
Debug.Print Jumbo_token

send JSON body with store info together with x-jumbo-token in header to select correct store
Body = "{""id"":""3065"", ""complexNumber"":""33164""}"
XMLReq.Open "PUT", "http://mobileapi.jumbo.com/v2/users/me/homestore", False
XMLReq.setRequestHeader "x-jumbo-token", Jumbo_token
XMLReq.send (Body)
'check on response value of x-jumbo-token (is equal to the token I sent in header), all seems fine until this point
Debug.Print XMLReq.getResponseHeader("x-jumbo-token")

'send final request to product page and extract the price info
XMLReq.Open "GET", SKU_url, False
XMLReq.setRequestHeader "x-jumbo-token", Jumbo_token
XMLReq.send

JumboPrice = Split(Split(XMLReq.responseText, "prices"":{""price"":{""currency"":""EUR"",""amount"":")(1), "}")(0) / 100

'debug print product price > 1,97 is displayed instead of 1,87 (when the correct store is connected to the session).
Debug.Print JumboPrice
'x-jumbo-token from RepsonseHeader is different vs. the one I sent as header with the request.
Debug.Print XMLReq.getResponseHeader("x-jumbo-token")

End Sub

Any suggestions how i could pass the correct token in the subsequent GET request and extract the same x-jumbo-token in the getResponseHeader of the final request, and extract the correct price of 1,87?