problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
What are the truthy and falsy values in Perl 6? : <p>While it is always possible to use mixins or method overrides to modify the Bool coercions, <em>by default</em> what values are considered to be truthy and what values are considered to be falsy?</p>
<p>Note: this question was <a href="https://stackoverflow.com/questions/125265/how-does-perl-6-evaluate-truthiness">asked previously</a>, but unfortunately it is so old its content is completely out of date and useless is modern Perl 6.</p>
| 0debug
|
How to randomly select certain percentage of rows and create new columns in r : I have a species column containing 100 species names. I have to distribute the species into four columns randomly such that each column will take a specific percentage of species. lets say the first column takes 20%, the second 30%, the third 40% and the last 10%. The four columns will be four different environments ie. Restricted, Tidal flat, beach, estuary. Hence the column intake will be predefined but the selection will be random.
| 0debug
|
How to return an array of objects with a count of how many for each one : <p>How would I go about returning an object that returns the genres of Country, Rock, and Pop with and a count of how many songs are in each genre? The output would look something like:</p>
<p>Country: 4,
Rock: 2,
Pop: 1</p>
<pre><code>const music= [{
"title": "Cheats",
"year": 2018,
"cast": ["Jane Rhee", "Kacey Brown"],
"genres": ["Country"]
}, {
"title": "Road",
"year": 2018,
"cast": ["Jeff Bates", "Alan Walker", "Cindy Bates"],
"genres": ["Country"]
}, {
"title": "Trail Down",
"year": 2018,
"cast": ["Ken Clemont"],
"genres": ["Jazz"]
}, {
"title": "Way Down",
"year": 2018,
"cast": ["Denzel Harr", "Dan Smith", "Lee Kyle", "Nate Hill"],
"genres": ["Pop"]
}, {
"title": "Fountain",
"year": 2018,
"cast": ["Brad Smith", "Rosa King"],
"genres": ["Rock"]
}, {
"title": "Gold Bells",
"year": 2018,
"cast": ["Paisley John"],
"genres": ["Blues"]
}, {
"title": "Mountain Curve",
"year": 2018,
"cast": ["Michael Johnson"],
"genres": ["Country"]
}, {
"title": "Arabella",
"year": 2018,
"cast": [],
"genres": ["Rock"]
}, {
"title": "Curved",
"year": 2018,
"cast": ["Brett Shay"],
"genres": ["Country"]
}];
</code></pre>
<p>This is my code. I am getting all the genres and no counts.</p>
<pre><code>let songs = [];
for (var i = 0; i < music.length; i++) {
songs.push(music[i].genres);
}
console.log(songs);
</code></pre>
| 0debug
|
How to un-obfuscate JavaScript starting with const and a bunch of vars : <p>Hi i found this extension and would like to see the contents of the script itself to check what is actually does. I tried putting the script through all sort of javascript de/un-obfuscators and none worked.</p>
<p>Please tell me one that works or send me the de-obfuscated JS.</p>
<p><strong><a href="https://skidlamer.github.io/js/skid.js" rel="nofollow noreferrer">CODE HERE</a></strong></p>
| 0debug
|
static void vfio_add_kvm_msi_virq(VFIOMSIVector *vector, MSIMessage *msg,
bool msix)
{
int virq;
if ((msix && !VFIO_ALLOW_KVM_MSIX) ||
(!msix && !VFIO_ALLOW_KVM_MSI) || !msg) {
return;
}
if (event_notifier_init(&vector->kvm_interrupt, 0)) {
return;
}
virq = kvm_irqchip_add_msi_route(kvm_state, *msg);
if (virq < 0) {
event_notifier_cleanup(&vector->kvm_interrupt);
return;
}
if (kvm_irqchip_add_irqfd_notifier_gsi(kvm_state, &vector->kvm_interrupt,
NULL, virq) < 0) {
kvm_irqchip_release_virq(kvm_state, virq);
event_notifier_cleanup(&vector->kvm_interrupt);
return;
}
vector->virq = virq;
}
| 1threat
|
Javascript closure and return values : can someone please explain the code below? I'm confused about the role of
return f();
1) Does return f(); call the method 'f' and return the result? (i.e. the return of 'f')
2) Does return f(); return an object?
If I change return f(); to just f(); checkscope = undefined
var scope = "global scope"; // A global variable
function checkscope() {
var scope = "local scope"; // A local variable
function f() { return scope; } // Return the value in scope here
return f();
}
checkscope() // => "local scope"
| 0debug
|
How to replace part of text with html text : I want to replace matching keyword in text with same keyword but wrapped with `<span></span>`
example : This is the sample text to be searched
replaced text should be line
This is the <span class="match">sample</span>text to be searched
i am using following code but its not working
protected String getTitle(object title)
{
string sTitle = title.ToString();
Regex regex = null;
string pattern = @"(\b(?:" + _Keyword.ToString().Trim() + @")\b)(?![^<]*?>)";
regex = new Regex(pattern);
sTitle = regex.Replace(sTitle, "<span class='keyword-highlight'>" + _Keyword + "</span>");
return sTitle;
}
above code replace whole text with keyword not just the matching part
| 0debug
|
What is the usage of the pseudo class :not()? : <p>I saw this pseudo class <code>:not()</code> being used in a source code of a <strong>Youtube</strong> video page, searching in the <strong>MDN</strong> I saw <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:not" rel="nofollow noreferrer">this article</a> explaining the pseudo class, but I couldn't understand why (<em>and in which case</em>) someone would use that. </p>
| 0debug
|
CUDA kernel performance is bad using a for-loop : I have a 1D array in C-code that I would like to convert to a corresponding CUDA kernel that can execute with good performance on a GPU DEVICE. The architecture is Nvidia CUDA 10.x
I have tried the naive approach whereby the C-code is applied directly to a CUDA kernel and got correct results.
```CUDA
#include <cuda.h>
#include <cuComplex.h>
#include <stdio.h>
// DEVICE code:
__global__ void myKern(const int N, cuComplex *d_a, cuComplex *d_b){
// global thread ID
int i = blockIdx.x * blockDim.x + threadIdx.x;
// check range
if(i >= N) return;
// *****************************************************
// This appears to work, but is VERY bad performance
// - can this for-loop be removed or defined differently
// for better performance ?
for(; i < N; ++i){
d_b[0].x *= d_a[i].x;
d_b[0].y *= d_a[i].y;
}
// *****************************************************
}
// HOST code:
int main() {
cuComplex *h_a, h_b;
cuComplex *d_a, *d_b, chk;
const int N = 5;
h_b.x = 0.0f;
h_b.y = 0.0f;
// allocate HOST and DEVICE memory
h_a = (cuComplex*)malloc(N*sizeof(cuComplex));
cudaMalloc((void**)&d_a, N*sizeof(cuComplex));
cudaMalloc((void**)&d_b, sizeof(cuComplex));
// initialize input array
for(int i = 0; i < N; ++i){
h_a[i].x = (float)(i + 1);
h_a[i].y = 1.0f
}
// copy to DEVICE
cudaMemcpy(d_a, h_a, N*sizeof(cuComplex), cudaMemcpyHostToDevice);
cudaMemcpy(d_b, &h_b, sizeof(cuComplex), cudaMemcpyHostToDevice);
// call CUDA kernel
int tpb = 1024;
int nblocks = (N + tpb - 1) / tpb;
myKern<<<nblocks,tpb>>>(N, d_a, d_b);
// ******************************************
// PROBLEM: I would like to convert this
// for-loop to CUDA kernel that is optimized
// for performance
// ******************************************
for(int i = 0; i < N; ++i){
h_b.x *= h_a[i].x;
h_b.y *= h_a[i].y;
}
// ******************************************
// get results from DEVICE
cudaMemcpy(&chk, d_b, sizeof(cuComplex), cudaMemcpyDeviceToHost);
// compare HOST and DEVICE
printf("HOST: %0.4f, DEVICE: %0.4f\n", h_b.x, chk.x);
// free memory
free(h_a);
cudaFree(d_a); cudaFree(d_b);
```
The results from HOST and DEVICE appear same, but performance is degraded on DEVICE due to the for-loop inside the CUDA kernel. I don't get an error and would just like to create a CUDA kernel that will properly execute the for-loop in C HOST code that has good performance for the DEVICE.
| 0debug
|
Method validate does not exist - Laravel 5.4 : <p>I have a very weird problem. When I'm submitting the form, it throws an error with server-side validation.</p>
<p>Here is my simple controller:</p>
<pre><code>namespace App\Http\Controllers;
use Newsletter;
use Illuminate\Http\Request;
class SubscriptionController extends Controller
{
public function subscribe(Request $request)
{
$request->validate([
'email' => 'required|email',
]);
}
}
</code></pre>
<p>Submitting the form gives me:</p>
<blockquote>
<p>BadMethodCallException
Method validate does not exist.</p>
</blockquote>
<p>it should work according to:</p>
<p><a href="https://laravel.com/docs/5.4/validation" rel="noreferrer">https://laravel.com/docs/5.4/validation</a></p>
| 0debug
|
checkbox attibuted checked but the opposite checkbox that does not have the attribute checked is selected : my checkboxes are acting strangely or maybe I am missing something but cannot get my finger on it.
I have two checkboxes of the same name and the one with the attribute Checked="checked" is not showing as checked. Instead the other atttribute that does not contain the checked attribute shows as checked.
I am missing anything?
Below is my html:
<input checked="checked" id="EditLearnerReadOnly" name="EditLearner" type="radio" value="False"> ReadOnly
<input id="EditLearnerFullAccess" name="EditLearner" type="radio" value="True"> Full Access
The browser shows Full Access as the checked one.
[Screenshot here][1]
[1]: https://i.stack.imgur.com/7HpGE.jpg
| 0debug
|
static void imx_gpt_write(void *opaque, hwaddr offset, uint64_t value,
unsigned size)
{
IMXGPTState *s = IMX_GPT(opaque);
uint32_t oldreg;
uint32_t reg = offset >> 2;
DPRINTF("(%s, value = 0x%08x)\n", imx_gpt_reg_name(reg),
(uint32_t)value);
switch (reg) {
case 0:
oldreg = s->cr;
s->cr = value & ~0x7c14;
if (s->cr & GPT_CR_SWR) {
imx_gpt_reset(DEVICE(s));
} else {
imx_gpt_set_freq(s);
if ((oldreg ^ s->cr) & GPT_CR_EN) {
if (s->cr & GPT_CR_EN) {
if (s->cr & GPT_CR_ENMOD) {
s->next_timeout = TIMER_MAX;
ptimer_set_count(s->timer, TIMER_MAX);
imx_gpt_compute_next_timeout(s, false);
}
ptimer_run(s->timer, 1);
} else {
ptimer_stop(s->timer);
}
}
}
break;
case 1:
s->pr = value & 0xfff;
imx_gpt_set_freq(s);
break;
case 2:
s->sr &= ~(value & 0x3f);
imx_gpt_update_int(s);
break;
case 3:
s->ir = value & 0x3f;
imx_gpt_update_int(s);
imx_gpt_compute_next_timeout(s, false);
break;
case 4:
s->ocr1 = value;
if (!(s->cr & GPT_CR_FRR)) {
s->next_timeout = TIMER_MAX;
ptimer_set_limit(s->timer, TIMER_MAX, 1);
}
imx_gpt_compute_next_timeout(s, false);
break;
case 5:
s->ocr2 = value;
imx_gpt_compute_next_timeout(s, false);
break;
case 6:
s->ocr3 = value;
imx_gpt_compute_next_timeout(s, false);
break;
default:
IPRINTF("Bad offset %x\n", reg);
break;
}
}
| 1threat
|
opts_type_int(Visitor *v, int64_t *obj, const char *name, Error **errp)
{
OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);
const QemuOpt *opt;
const char *str;
long long val;
char *endptr;
if (ov->list_mode == LM_SIGNED_INTERVAL) {
*obj = ov->range_next.s;
return;
}
opt = lookup_scalar(ov, name, errp);
if (!opt) {
return;
}
str = opt->str ? opt->str : "";
assert(ov->list_mode == LM_NONE || ov->list_mode == LM_IN_PROGRESS);
errno = 0;
val = strtoll(str, &endptr, 0);
if (errno == 0 && endptr > str && INT64_MIN <= val && val <= INT64_MAX) {
if (*endptr == '\0') {
*obj = val;
processed(ov, name);
return;
}
if (*endptr == '-' && ov->list_mode == LM_IN_PROGRESS) {
long long val2;
str = endptr + 1;
val2 = strtoll(str, &endptr, 0);
if (errno == 0 && endptr > str && *endptr == '\0' &&
INT64_MIN <= val2 && val2 <= INT64_MAX && val <= val2) {
ov->range_next.s = val;
ov->range_limit.s = val2;
ov->list_mode = LM_SIGNED_INTERVAL;
*obj = ov->range_next.s;
return;
}
}
}
error_set(errp, QERR_INVALID_PARAMETER_VALUE, opt->name,
(ov->list_mode == LM_NONE) ? "an int64 value" :
"an int64 value or range");
}
| 1threat
|
How to control other view in different activity? : I have created the customAdapter of listview . when I click the button in the listview ,I want to control the Textview outside the listview from different layout. Notice ! There are not in the same java code.
here is i want to do:
viewHolder.plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TextView tx=(TextView) txt.findViewById(R.id.moneytext);
//find the textview outside listview (now In the same java code and xml)
totalmoney= (Integer.parseInt(tx.getText().toString()))+(Integer.parseInt(price[position]));
//get the textview integer and add to my present number
tx.setText(""+totalmoney);
//post on the textview
}
});
| 0debug
|
What's the difference between getElementById and getElementsByClassName : <p>I know maybe is not the right way of using the <code>getElementsByClassName</code>. For example the code below doesn't work as it is ¿why?, but when change <code>getElementsByClassName("demo")</code> for <code>getElementById("demo2")</code> does work</p>
<pre><code><!DOCTYPE html>
<html>
<body>
<p>Click the button.</p>
<button onclick="myFunction()">Try it</button>
<p class="demo" id="demo2">anything</p>
<script>
function myFunction() {
var str = "How are you doing today?";
var res = str.split(" ");
document.getElementsByNameClass("demo").innerHTML = res;
}
</script>
</body>
</html>
</code></pre>
| 0debug
|
static av_cold int vaapi_encode_h264_init_internal(AVCodecContext *avctx)
{
static const VAConfigAttrib default_config_attributes[] = {
{ .type = VAConfigAttribRTFormat,
.value = VA_RT_FORMAT_YUV420 },
{ .type = VAConfigAttribEncPackedHeaders,
.value = (VA_ENC_PACKED_HEADER_SEQUENCE |
VA_ENC_PACKED_HEADER_SLICE) },
};
VAAPIEncodeContext *ctx = avctx->priv_data;
VAAPIEncodeH264Context *priv = ctx->priv_data;
VAAPIEncodeH264Options *opt = ctx->codec_options;
int i, err;
switch (avctx->profile) {
case FF_PROFILE_H264_CONSTRAINED_BASELINE:
ctx->va_profile = VAProfileH264ConstrainedBaseline;
break;
case FF_PROFILE_H264_BASELINE:
ctx->va_profile = VAProfileH264Baseline;
break;
case FF_PROFILE_H264_MAIN:
ctx->va_profile = VAProfileH264Main;
break;
case FF_PROFILE_H264_EXTENDED:
av_log(avctx, AV_LOG_ERROR, "H.264 extended profile "
"is not supported.\n");
return AVERROR_PATCHWELCOME;
case FF_PROFILE_UNKNOWN:
case FF_PROFILE_H264_HIGH:
ctx->va_profile = VAProfileH264High;
break;
case FF_PROFILE_H264_HIGH_10:
case FF_PROFILE_H264_HIGH_10_INTRA:
av_log(avctx, AV_LOG_ERROR, "H.264 10-bit profiles "
"are not supported.\n");
return AVERROR_PATCHWELCOME;
case FF_PROFILE_H264_HIGH_422:
case FF_PROFILE_H264_HIGH_422_INTRA:
case FF_PROFILE_H264_HIGH_444:
case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
case FF_PROFILE_H264_HIGH_444_INTRA:
case FF_PROFILE_H264_CAVLC_444:
av_log(avctx, AV_LOG_ERROR, "H.264 non-4:2:0 profiles "
"are not supported.\n");
return AVERROR_PATCHWELCOME;
default:
av_log(avctx, AV_LOG_ERROR, "Unknown H.264 profile %d.\n",
avctx->profile);
return AVERROR(EINVAL);
}
if (opt->low_power) {
#if VA_CHECK_VERSION(0, 39, 1)
ctx->va_entrypoint = VAEntrypointEncSliceLP;
#else
av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
"supported with this VAAPI version.\n");
return AVERROR(EINVAL);
#endif
} else {
ctx->va_entrypoint = VAEntrypointEncSlice;
}
ctx->input_width = avctx->width;
ctx->input_height = avctx->height;
ctx->aligned_width = FFALIGN(ctx->input_width, 16);
ctx->aligned_height = FFALIGN(ctx->input_height, 16);
priv->mb_width = ctx->aligned_width / 16;
priv->mb_height = ctx->aligned_height / 16;
for (i = 0; i < FF_ARRAY_ELEMS(default_config_attributes); i++) {
ctx->config_attributes[ctx->nb_config_attributes++] =
default_config_attributes[i];
}
if (avctx->bit_rate > 0) {
ctx->va_rc_mode = VA_RC_CBR;
err = vaapi_encode_h264_init_constant_bitrate(avctx);
} else {
ctx->va_rc_mode = VA_RC_CQP;
err = vaapi_encode_h264_init_fixed_qp(avctx);
}
if (err < 0)
return err;
ctx->config_attributes[ctx->nb_config_attributes++] = (VAConfigAttrib) {
.type = VAConfigAttribRateControl,
.value = ctx->va_rc_mode,
};
if (opt->quality > 0) {
#if VA_CHECK_VERSION(0, 36, 0)
priv->quality_params.misc.type =
VAEncMiscParameterTypeQualityLevel;
priv->quality_params.quality.quality_level = opt->quality;
ctx->global_params[ctx->nb_global_params] =
&priv->quality_params.misc;
ctx->global_params_size[ctx->nb_global_params++] =
sizeof(priv->quality_params);
#else
av_log(avctx, AV_LOG_WARNING, "The encode quality option is not "
"supported with this VAAPI version.\n");
#endif
}
ctx->nb_recon_frames = 20;
return 0;
}
| 1threat
|
How many elements in string array : I want to find how many names in `names` array.I know `sizeof(names)/sizeof(names[0])` give the right answer. But the problem is i can't just decleare `char *names[];`. Because compiler gives me an error like this ***"Storage of names is unknown"***. To avoid this error, i must decleare like this `char *names[] = {"somename", "somename2"};`. But the thing is i cannot assign the strings right after decleration. I assign strings after some conditions and my problem is how many strings i have after that conditions.
| 0debug
|
Excel VBA - Providing cell address in formula as a variable : Is this doable? I'll edit in more details in 5 minutes, unable to initiate question form on a desktop so I'm posting from my phone and will edit on a computer.
| 0debug
|
int ff_h264_field_end(H264Context *h, H264SliceContext *sl, int in_setup)
{
AVCodecContext *const avctx = h->avctx;
int err = 0;
h->mb_y = 0;
if (!in_setup && !h->droppable)
ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
h->picture_structure == PICT_BOTTOM_FIELD);
if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
if (!h->droppable) {
err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
h->prev_poc_msb = h->poc_msb;
h->prev_poc_lsb = h->poc_lsb;
}
h->prev_frame_num_offset = h->frame_num_offset;
h->prev_frame_num = h->frame_num;
}
if (avctx->hwaccel) {
if (avctx->hwaccel->end_frame(avctx) < 0)
av_log(avctx, AV_LOG_ERROR,
"hardware accelerator failed to decode picture\n");
}
#if CONFIG_ERROR_RESILIENCE
if (!FIELD_PICTURE(h) && h->enable_er) {
h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr);
h264_set_erpic(&sl->er.last_pic,
sl->ref_count[0] ? sl->ref_list[0][0].parent : NULL);
h264_set_erpic(&sl->er.next_pic,
sl->ref_count[1] ? sl->ref_list[1][0].parent : NULL);
ff_er_frame_end(&sl->er);
}
#endif
emms_c();
h->current_slice = 0;
return err;
}
| 1threat
|
static inline void RENAME(bgr15ToY)(uint8_t *dst, uint8_t *src, int width)
{
int i;
for(i=0; i<width; i++)
{
int d= ((uint16_t*)src)[i];
int b= d&0x1F;
int g= (d>>5)&0x1F;
int r= (d>>10)&0x1F;
dst[i]= ((RY*r + GY*g + BY*b)>>(RGB2YUV_SHIFT-3)) + 16;
}
}
| 1threat
|
In a C# console app, how would I create 'images' for playing cards in a blackjack game? : <p>I'm working on a simple C# blackjack console application game for my school and I was given an example to look at. This example somehow draws a picture of the card in the console window and I can't figure out how to replicate this without specifying hundreds of Console.Write's for each of the 52 unique cards. </p>
<p><a href="https://i.stack.imgur.com/88P7U.png" rel="nofollow noreferrer">in game scene</a>
This is what it looks like when you're actually playing the game. Quite nice.</p>
<p><a href="https://i.stack.imgur.com/C3TBN.png" rel="nofollow noreferrer">shuffle and show deck</a>
There is also an option from the main menu to shuffle and display all 52 cards.</p>
<p>So what is this wizardry? Did they actually spend a TON of time hard-coding how every single unique card prints out? I sure hope not. This is what I'm trying to replicate and I'm at a loss for ideas besides hard-coding. Thanks for your help.</p>
| 0debug
|
Swift 3 sound play : <p>Ok I have looked into this and have tried many different ways to play a sound when a button is clicked.</p>
<p>How would I play a sound when a button is clicked in swift 3?
I have my sound in a folder named Sounds and the name is ClickSound.mp3</p>
| 0debug
|
error: lvalue required as left operand of assignment, I GOT THIS ERROR WHAT IS lvalue and rvalue and how to remove this error : I got this error in my code while compiling
here is the code
#include <iostream>
using namespace std;
int main()
{
int l,n,w,h;
cin>>l>>n;
while(n--){
cin>>w>>h;
if(w>l||h>l)
cout<<"CROP IT"<<endl;
if(w==l&&h==l&&w=h)
cout<<"ACCEPTED"<<endl;
if(w<l||h<l)
cout<<"UPLOAD ANOTHER"<<endl;
}
}
and the error
11:22: error: lvalue required as left operand of assignment
| 0debug
|
Data science/General Programming- How to make all combination of features ? : I am trying to generate all combination of features so that I can try all the combination to check which combination increased cross validation score. I am using this code which I used to do solve data structures problem.But it becomes highly inefficient if features >16 or so. Can you suggest something efficient ?
allcomb=[]
for i in range(pow(2,len(features))):
com=[]
for j in (range(len(features))):
if((i&(1<<j))==1):
com.append(features[j])
allcomb.append(com)
| 0debug
|
Dutuch flag for 4 colors : I went trough solution for 2 and 3 colors but I am unable to get it for 4 colors.
I am unable to do it for fo four colors.Please help.
Will it be rrbb????yyyggg
how will we swap the green flag.
I tried the solution but it is not working swapping ;last yellow with green
public class count123 {
// Java program to sort an array of 0, 1 and 2,3
static void sort0123(int a[], int arr_size)
{
int lo = 0;
int hi = arr_size - 1;
int mid = 0,temp=0;
int h2=arr_size - 1;
while (mid <= hi)
{
switch (a[mid])
{
case 0:
{
temp = a[lo];
a[lo] = a[mid];
a[mid] = temp;
lo++;
mid++;
break;
}
case 1:
mid++;
break;
case 2:
{
temp = a[mid];
a[mid] = a[hi];
a[hi] = temp;
hi--;
h2=hi;
break;
}
case 3:{
temp = a[mid];
a[mid] = a[h2];
a[h2] = temp;
// h2--;
//hi=h2;
break;
}
}
}
}
/* Utility function to print array arr[] */
static void printArray(int arr[], int arr_size)
{
int i;
for (i = 0; i < arr_size; i++)
System.out.print(arr[i]+" ");
System.out.println("");
}
/*Driver function to check for above functions*/
public static void main (String[] args)
{
int arr[] = {0, 1, 0,1,2,2,0,3,3,0,0,1};
int arr_size = arr.length;
sort0123(arr, arr_size);
System.out.println("Array after seggregation ");
printArray(arr, arr_size);
}
}
/*This code is contributed by Devesh Agrawal*/
| 0debug
|
int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
AVPacket *avpkt,
const AVFrame *frame,
int *got_packet_ptr)
{
AVFrame tmp;
AVFrame *padded_frame = NULL;
int ret;
AVPacket user_pkt = *avpkt;
int needs_realloc = !user_pkt.data;
*got_packet_ptr = 0;
if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
av_free_packet(avpkt);
av_init_packet(avpkt);
return 0;
}
if (frame && !frame->extended_data) {
if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
avctx->channels > AV_NUM_DATA_POINTERS) {
av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
"with more than %d channels, but extended_data is not set.\n",
AV_NUM_DATA_POINTERS);
return AVERROR(EINVAL);
}
av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
tmp = *frame;
tmp.extended_data = tmp.data;
frame = &tmp;
}
if (frame) {
if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
if (frame->nb_samples > avctx->frame_size) {
av_log(avctx, AV_LOG_ERROR, "more samples than frame size (avcodec_encode_audio2)\n");
return AVERROR(EINVAL);
}
} else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
if (frame->nb_samples < avctx->frame_size &&
!avctx->internal->last_audio_frame) {
ret = pad_last_frame(avctx, &padded_frame, frame);
if (ret < 0)
return ret;
frame = padded_frame;
avctx->internal->last_audio_frame = 1;
}
if (frame->nb_samples != avctx->frame_size) {
av_log(avctx, AV_LOG_ERROR, "nb_samples (%d) != frame_size (%d) (avcodec_encode_audio2)\n", frame->nb_samples, avctx->frame_size);
ret = AVERROR(EINVAL);
goto end;
}
}
}
ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
if (!ret) {
if (*got_packet_ptr) {
if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
if (avpkt->pts == AV_NOPTS_VALUE)
avpkt->pts = frame->pts;
if (!avpkt->duration)
avpkt->duration = ff_samples_to_time_base(avctx,
frame->nb_samples);
}
avpkt->dts = avpkt->pts;
} else {
avpkt->size = 0;
}
}
if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
needs_realloc = 0;
if (user_pkt.data) {
if (user_pkt.size >= avpkt->size) {
memcpy(user_pkt.data, avpkt->data, avpkt->size);
} else {
av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
avpkt->size = user_pkt.size;
ret = -1;
}
avpkt->buf = user_pkt.buf;
avpkt->data = user_pkt.data;
avpkt->destruct = user_pkt.destruct;
} else {
if (av_dup_packet(avpkt) < 0) {
ret = AVERROR(ENOMEM);
}
}
}
if (!ret) {
if (needs_realloc && avpkt->data) {
ret = av_buffer_realloc(&avpkt->buf, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
if (ret >= 0)
avpkt->data = avpkt->buf->data;
}
avctx->frame_number++;
}
if (ret < 0 || !*got_packet_ptr) {
av_free_packet(avpkt);
av_init_packet(avpkt);
goto end;
}
avpkt->flags |= AV_PKT_FLAG_KEY;
end:
av_frame_free(&padded_frame);
return ret;
}
| 1threat
|
Display full image without cut in ViewPager how to fix : i want to display full image without cut height/width on android.support.v4.view.ViewPager but when a set image in ImagePagerAdapter adapter image crop from both side in my image gallery how to fix pls help me i am new in android so pls help me how to display full image in viewer.
Pls help me i am new in android
| 0debug
|
How to calculate profit formula with multiple user input text in swift4 : So im traying to make a simple calculation formula , but I don't know how to add all the variables simultaneously.
I already tried this but is giving an error and is being supper inaccurate.
var fee :Int = Int(0.866)
var otherFee:Int = Int(0.30)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func calculateProfit(_ sender: Any) {
let sold = Int(soldTextField.text!)!
let paid = Int(paidTextField.text!)!
let shipping = Int(shippingTextField.text!)!
profitTotal.text = String(sold * fee - otherFee - paid - shipping )
}
}
I spect that when I hit the button it will multiply ,subtract, subtract simultaneous.
| 0debug
|
How to generate constructors in swagger codegen? : <p>The codegen did not generate any constructor.
I referred to petstore swagger file, used latest swagger codegen jar file.</p>
<p>But only default constructor was generated.</p>
<p>It is not generating constructor based on its fields.</p>
<p>How to enable it?</p>
| 0debug
|
static int v9fs_do_open2(V9fsState *s, V9fsCreateState *vs)
{
FsCred cred;
int flags;
cred_init(&cred);
cred.fc_uid = vs->fidp->uid;
cred.fc_mode = vs->perm & 0777;
flags = omode_to_uflags(vs->mode) | O_CREAT;
return s->ops->open2(&s->ctx, vs->fullname.data, flags, &cred);
}
| 1threat
|
uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length){
const uint8_t *end= buffer+length;
#if !CONFIG_SMALL
if(!ctx[256])
while(buffer<end-3){
crc ^= le2me_32(*(const uint32_t*)buffer); buffer+=4;
crc = ctx[3*256 + ( crc &0xFF)]
^ctx[2*256 + ((crc>>8 )&0xFF)]
^ctx[1*256 + ((crc>>16)&0xFF)]
^ctx[0*256 + ((crc>>24) )];
}
#endif
while(buffer<end)
crc = ctx[((uint8_t)crc) ^ *buffer++] ^ (crc >> 8);
return crc;
}
| 1threat
|
Android 3.3.0 update, ERROR: Cause: invalid type code: 68 : <p>After the new update of Android Studio (3.3.0) I'm getting error from Gradle sync saying "ERROR: Cause: invalid type code: 68". Even in project, that have been created before the update and hasn't changed at all.
I've tried to reinstall Android Studio, which hasn't helped either, so there has to be something incompatible with my project, but it doesn't say what and why.</p>
<p>App gradle:</p>
<pre><code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 28
defaultConfig {
applicationId "cz.cubeit.cubeit"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:design:28.0.0'
}
</code></pre>
<p>Project gradle:</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.3.11'
ext.anko_version='0.10.7'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
| 0debug
|
Finding the last row with data using vba : <p><strong>I am creating a program in which everytime it generates, the generated data will appear in a specific sheet and arranged in specific date order . It looks like this.</strong></p>
<p><a href="https://i.stack.imgur.com/1vUeq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1vUeq.png" alt="Generated data"></a></p>
<p>But when I generate again, the existing data will be replaced/covered by the new data generated. Looks like this.</p>
<p><a href="https://i.stack.imgur.com/KM55r.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KM55r.png" alt="enter image description here"></a></p>
<p>Now my idea is, before I am going to paste another data, I want to find out first what is the last used cell with value so that in the next generation of data, it wont be replaced/covered by the new one. Can someone help me with this. The output should look like this.</p>
<p><a href="https://i.stack.imgur.com/YLXnq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YLXnq.png" alt="enter image description here"></a></p>
<p>Any help everyone? Thanks! </p>
| 0debug
|
ld: library not found for -lFirebaseCore clang: error: linker command failed with exit code 1 (use -v to see invocation) : <p>I using <code>react-native-fcm</code> for remote push notification but it gives this error:</p>
<p>ld: library not found for -lFirebaseCore
clang: error: linker command failed with exit code 1 (use -v to see invocation)</p>
<p>Pod:</p>
<pre><code># Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
target 'SefrTaSad' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for SefrTaSad
pod 'Firebase'
pod 'Firebase/Messaging'
end
</code></pre>
<p>Podfile.lock:</p>
<pre><code>PODS:
- Firebase (5.5.0):
- Firebase/Core (= 5.5.0)
- Firebase/Core (5.5.0):
- Firebase/CoreOnly
- FirebaseAnalytics (= 5.1.0)
- Firebase/CoreOnly (5.5.0):
- FirebaseCore (= 5.1.0)
- Firebase/Messaging (5.5.0):
- Firebase/CoreOnly
- FirebaseMessaging (= 3.1.0)
- FirebaseAnalytics (5.1.0):
- FirebaseCore (~> 5.1)
- FirebaseInstanceID (~> 3.2)
- GoogleAppMeasurement (~> 5.1)
- GoogleUtilities/AppDelegateSwizzler (~> 5.2.0)
- GoogleUtilities/MethodSwizzler (~> 5.2.0)
- GoogleUtilities/Network (~> 5.2)
- "GoogleUtilities/NSData+zlib (~> 5.2)"
- nanopb (~> 0.3)
- FirebaseCore (5.1.0):
- GoogleUtilities/Logger (~> 5.2)
- FirebaseInstanceID (3.2.0):
- FirebaseCore (~> 5.1)
- GoogleUtilities/Environment (~> 5.2)
- FirebaseMessaging (3.1.0):
- FirebaseCore (~> 5.0)
- FirebaseInstanceID (~> 3.0)
- GoogleUtilities/Reachability (~> 5.2)
- Protobuf (~> 3.1)
- GoogleAppMeasurement (5.1.0):
- GoogleUtilities/AppDelegateSwizzler (~> 5.2.0)
- GoogleUtilities/MethodSwizzler (~> 5.2.0)
- GoogleUtilities/Network (~> 5.2)
- "GoogleUtilities/NSData+zlib (~> 5.2)"
- nanopb (~> 0.3)
- GoogleUtilities/AppDelegateSwizzler (5.2.2):
- GoogleUtilities/Environment
- GoogleUtilities/Logger
- GoogleUtilities/Network
- GoogleUtilities/Environment (5.2.2)
- GoogleUtilities/Logger (5.2.2):
- GoogleUtilities/Environment
- GoogleUtilities/MethodSwizzler (5.2.2):
- GoogleUtilities/Logger
- GoogleUtilities/Network (5.2.2):
- GoogleUtilities/Logger
- "GoogleUtilities/NSData+zlib"
- GoogleUtilities/Reachability
- "GoogleUtilities/NSData+zlib (5.2.2)"
- GoogleUtilities/Reachability (5.2.2):
- GoogleUtilities/Logger
- nanopb (0.3.8):
- nanopb/decode (= 0.3.8)
- nanopb/encode (= 0.3.8)
- nanopb/decode (0.3.8)
- nanopb/encode (0.3.8)
- Protobuf (3.6.1)
DEPENDENCIES:
- Firebase
- Firebase/Messaging
SPEC REPOS:
https://github.com/cocoapods/specs.git:
- Firebase
- FirebaseAnalytics
- FirebaseCore
- FirebaseInstanceID
- FirebaseMessaging
- GoogleAppMeasurement
- GoogleUtilities
- nanopb
- Protobuf
SPEC CHECKSUMS:
Firebase: 8c957f9cb3852b519180fb378801b7eeeba4d288
FirebaseAnalytics: d4a260c114aec0d765ab5b9c404ac63de1d29381
FirebaseCore: ee4b35cf8c8e781da296cc7c15125e4608bb954d
FirebaseInstanceID: 8cd2c6cfe7b9ab65ce7e248f6da7f26f6775b9be
FirebaseMessaging: f67b3719f520ee200da0e20ce577fe2bce0c01d0
GoogleAppMeasurement: e785bdb86d3d280abc778156cec323a975f11d1d
GoogleUtilities: 06b66f9567769a7958db20a92f0128b2843e49d5
nanopb: 5601e6bca2dbf1ed831b519092ec110f66982ca3
Protobuf: 1eb9700044745f00181c136ef21b8ff3ad5a0fd5
PODFILE CHECKSUM: 5128fcc348aba846d880d9bb9978b4bf02c0718d
COCOAPODS: 1.5.3
</code></pre>
<p>project build whit react-native
and I make appId, key and profile
the app successfully conected to firebase console but when I want to archive it whit xcode it gives this error:</p>
<p><a href="https://i.stack.imgur.com/QpNC4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QpNC4.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/bDxUo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bDxUo.png" alt="enter image description here"></a></p>
<p>how can I solve this error ?</p>
| 0debug
|
void qemu_system_reset_request(void)
{
if (no_reboot) {
shutdown_requested = 1;
} else {
reset_requested = 1;
}
cpu_stop_current();
qemu_notify_event();
}
| 1threat
|
What is the best method to seeding a Node / MongoDB application? : <p>So, I'm new to the MEAN stack, and I've hit a wall trying to seed MongoDB. I'm using Mongoose to communicate with the database, and there's a bunch of documentation suggesting I should be able to seed using populated JSON files.</p>
<p>What I've tried:</p>
<p><strong><a href="https://www.npmjs.com/package/node-mongo-seeds" rel="noreferrer">node-mongo-seed</a></strong>; Pretty straight forward, but consistently throws errors on the end of arrays. (Perhaps the missing bson module is at fault?)</p>
<pre><code>{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
Seeding files from directory /Users/Antwisted/code/wdi/MEAN/seeds
----------------------
Seeding collection locations
err = [SyntaxError: /Users/Antwisted/code/wdi/MEAN/seeds/locations.json: Unexpected token {]
</code></pre>
<p><strong><a href="https://www.npmjs.com/package/mongoose-seed" rel="noreferrer">mongoose-seed</a></strong>; Also pretty straight forward, basically puts the JSON objects into a variable before exporting to the database. Promising, but... more errors...</p>
<pre><code>Successfully initialized mongoose-seed
[ 'app/models/locationsModel.js' ]
Locations collection cleared
Error creating document [0] of Location model
Error: Location validation failed
Error creating document [1] of Location model
Error: Location validation failed
Error creating document [2] of Location model
Error: Location validation failed...
</code></pre>
<p>So, my thoughts were that it was probably a syntax error within the JSON structure, but playing around with that has not yielded any real solutions (or maybe I'm missing it?). Sample of my JSON:</p>
<pre><code>{
{
"header": "Dan's Place",
"rating": 3,
"address": "125 High Street, New York, 10001",
"cord1": -73.0812,
"cord2": 40.8732,
"attributes": ["Hot drinks", "Food", "Premium wifi"],
"hours": [
{
"days": "Monday - Friday",
"hours": "7:00am - 7:00pm",
"closed": false
},
{
"days": "Saturday",
"hours": "8:00am - 5:00pm",
"closed": false
},
{
"days": "Sunday",
"closed": true
}
],
"reviews": [
{
"rating": 4,
"id": ObjectId(),
"author": "Philly B.",
"timestamp": "new Date('Feb 3, 2016')",
"body": "It was fine, but coffee was a bit dull. Nice atmosphere."
},
{
"rating": 3,
"id": ObjectId(),
"author": "Tom B.",
"timestamp": "new Date('Feb 23, 2016')",
"body": "I asked for her number. She said no."
}
]
},
{
"header": "Jared's Jive",
"rating": 5,
"address": "747 Fly Court, New York, 10001",
"cord1": -73.0812,
"cord2": 40.8732,
"attributes": ["Live Music", "Rooftop Bar", "2 Floors"],
"hours": [
{
"days": "Monday - Friday",
"hours": "7:00am - 7:00pm",
"closed": false
},
{
"days": "Saturday",
"hours": "8:00am - 5:00pm",
"closed": false
},
{
"days": "Sunday",
"closed": true
}
],
"reviews": [
{
"rating": 5,
"id": ObjectId(),
"author": "Jacob G.",
"timestamp": "new Date('Feb 3, 2016')",
"body": "Whoa! The music here is wicked good. Definitely going again."
},
{
"rating": 4,
"id": ObjectId(),
"author": "Tom B.",
"timestamp": "new Date('Feb 23, 2016')",
"body": "I asked to play her a tune. She said no."
}
]
}
}
</code></pre>
<p>Additionally, I'm not entirely sure how to specify subdocuments within the JSON (assuming I can get the seeding process to work correctly in the first place).</p>
<p>Here's my model:</p>
<pre><code>var mongoose = require('mongoose');
var subHoursSchema = new mongoose.Schema({
days: {type: String, required: true},
opening: String,
closing: String,
closed: {type: Boolean, required: true}
});
var subReviewsSchema = new mongoose.Schema({
rating: {type: Number, required: true, min: 0, max: 5},
author: String,
timestamp: {type: Date, "default": Date.now},
body: String
});
var locationSchema = new mongoose.Schema({
name: {type: String, required: true},
address: String,
rating: {type: Number, "default": 0, min: 0, max: 5},
attributes: [String],
coordinates: {type: [Number], index: '2dsphere'},
openHours: [subHoursSchema],
reviews: [subReviewsSchema]
});
mongoose.model('Location', locationSchema);
</code></pre>
<p>Any insight on how to navigate these issues would be greatly appreciated. Thanks!</p>
| 0debug
|
Git clone: Redirect stderr to stdout but keep errors being written to stderr : <p><code>git clone</code> writes its output to <code>stderr</code> as documented <a href="https://www.kernel.org/pub/software/scm/git/docs/git-clone.html">here</a>. I can redirect this with the following command:</p>
<pre><code>git clone https://myrepo c:\repo 2>&1
</code></pre>
<p>But this will redirect all output, including errors, from <code>stderr</code>to <code>stdout</code>. Is there a way to redirect progress messages to <code>stdout</code> but have error messages still written to <code>stderr</code>. </p>
| 0debug
|
Save Login Data in NSUserDefaults : <p>How to save Login form data and after click on login it switch to logout page. and when we click logout it come back to login form.</p>
| 0debug
|
How Do We Generate a Base64-Encoded SHA256 Hash of SubjectPublicKeyInfo of an X.509 Certificate, for Android N Certificate Pinning? : <p>The documentation in the N Developer Preview for their network security configuration offers these instructions:</p>
<blockquote>
<p>Certificate pinning is done by providing a set of certificates by hash of the public key (SubjectPublicKeyInfo of the X.509 certificate). A certificate chain is then only valid if the certificate chain contains at least one of the pinned public keys. </p>
</blockquote>
<p>The XML that they show is broken (missing a closing tag), but otherwise suggests that the hash is SHA256 and encoded base64:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config>
<domain includeSubdomains="true">example.com</domain>
<pin-set expiration="2018-01-01">
<pin digest="SHA-256">7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=</pin>
<!-- backup pin -->
<pin digest="SHA-256">fwza0LRMXouZHRC8Ei+4PyuldPDcf3UKgO/04cDM1oE=</pin>
</domain-config>
</network-security-config>
</code></pre>
<p>How do we create such a hash?</p>
<p>I tried the approach in <a href="https://gist.github.com/woodrow/9130294" rel="noreferrer">this gist</a>, but <code>openssl x509 -inform der -pubkey -noout</code> is not liking my CRT file. I cannot readily determine if the problem is in the CRT file, the instructions, my version of <code>openssl</code>, or something else.</p>
<p>Does anyone have a known good recipe for creating this hash?</p>
| 0debug
|
def does_Contain_B(a,b,c):
if (a == b):
return True
if ((b - a) * c > 0 and (b - a) % c == 0):
return True
return False
| 0debug
|
New to Java - How do I properly check that user input is an Integer in this scenario? : I'm new to Java and I have an assignment in where I have to calculate a user-determined amount of Fibonacci numbers using a recursive function, then again with an iterative function, then compare the times it takes to do each. Anyways, I have it all done, except, I can't get my check for valid integer input to work (see reader() method. Please help! Thanks!
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
import java.util.Scanner;
import java.lang.System;
import java.util.concurrent.TimeUnit;
/*
Class: FibonacciNumbers
Description: This class will take an integer from the user representing how many Fibonacci numbers they want to be calculated
and printed. It will then calculate this using a recursive function, and output the Fibonacci sequence. It will
then calculate the time elapsed (in nanoseconds) to perform the calculations and outputs, and will output this
result. It will then repeat this entire process using an iterative function (for loop). This is mainly meant to
show the difference in time between recursive and iterative functions.
*/
public class Fibonacci_Numbers {
private static int n1 = 0, n2 = 1; // first two Fibonacci numbers (no need to calculate).
/*
Method: main
Description: The primary method of the program. This introduces the program and the recursive and iterative functions to the
user. For the recursive function, it calls the reader function to get the integer representing the number of
Fibonacci numbers to be printed/calculated, then passes it to the recursive function. It also calculates and outputs
the time elapsed (in nanoseconds) to complete the recursive function. Before it calls the iterative function, it
resets the previously defined variables representing the first two numbers of the Fibonacci sequence to their
original values after they were altered within the recursive function. After calling and the completion of the
iterative function, it then exits the program.
Usage: primary method in class FibonacciNumbers
Parameters: String args[]
Return Type: void
*/
public static void main(String args[]) {
System.out.println(); // blank line, for output formatting.
System.out.println("Welcome to the Fibonacci Sequence Recursion/Iteration Comparison Program!"); // welcome message.
System.out.println(); // blank line, for output formatting.
System.out.println("RECURSIVE FUNCTION:"); // introduce recursive function.
int n = reader(); // call reader function.
long startTime = System.nanoTime(); // get and store time at beginning of recursive function.
fibSeriesRec(n); // call recursive function.
long endTime = System.nanoTime(); // get and store time at end of recursive function.
long timeElapsed = endTime - startTime; // calculate total time elapsed during recursive function.
System.out.println(); // blank line, for output formatting.
System.out.println("Elapsed Time for Recursive Function: " + timeElapsed + " nanoseconds."); // print total time elapsed during recursive function.
System.out.println(); // blank line, for output formatting.
n1 = 0; // reset first number of Fibonacci sequence.
n2 = 1; // reset second number of Fibonacci sequence.
System.out.println("ITERATIVE FUNCTION:"); // introduce iterative function.
fibSeriesIte(); // call iterative function.
System.exit(0); // exit program.
}
/*
Method: reader
Description: Reads integer n from user to represent number of Fibonacci numbers to be calculated/printed, then returns n.
Usage: called in main and fibSeriesIte methods
Parameters: none
Return Type: integer
*/
private static int reader() {
Scanner scanner = new Scanner(System.in); // create new scanner object to scan user input.
System.out.println("How many Fibonacci numbers would you like to generate?: "); // prompt user to enter number.
int n = scanner.nextInt(); // read user-entered number and store as integer.
if (!scanner.hasNextInt() || n <= 0){ // if the user input is not an integer or is less than or equal to 0...
System.out.println("Invalid integer. Please try again."); // print error message.
reader(); // restart reader method.
}
return n; // return user-entered integer.
}
/*
Method: fibSeriesRec
Description: Takes user-inputted integer n from main method (from reader method) and calculates and prints the Fibonacci sequence of n
numbers recursively. At the end of the function (within the if statement), the method calls itself again (for each number).
Each time through the function, n decreases by 1, and it will only run through the if statement while n is greater than 0.
Therefore, it will go through the function the original, user-inputted value of n times.
Usage: called in main method as well as within itself, fibSeriesRec method (recursion)
Parameters: integer n (from main, from reader. number of Fibonacci numbers to be calculated/printed)
Return Type: void
*/
private static void fibSeriesRec(int n) {
if(n>0){ // if the number entered by user is greater than 0...
System.out.print(n1 + " "); // print next Fibonacci number in sequence.
int sum = n1 + n2; // calculate sum of previous two numbers in Fibonacci sequence.
n1 = n2; // set value of first number to second number (move first number that will be added in calculation of next number in sequence over).
n2 = sum; // set value of second number to the sum of previous two numbers (move second number that will be added in calculation of next number in sequence over).
fibSeriesRec(n-1); // call to restart recursive function and decrease n by 1.
}
}
/*
Method: fibSeriesIte
Description: Calls reader method to get a user-inputted integer to represent the amount of Fibonacci numbers to be printed in the
Fibonacci sequence. Will then use a for loop to iteratively calculate and output Fibonacci sequence. The time elapsed
during the for loop will be calculated and output as well.
Usage: called in main method
Parameters: none
Return Type: void
*/
private static void fibSeriesIte() {
int n = reader(); // call reader function.
long startTime = System.nanoTime(); // get and store time at start of iterative function.
for (int i = 1; i <= n; i++) { // for loop that will run n times (number of Fibonacci numbers desired by user).
System.out.print(n1 + " "); // print next Fibonacci number in sequence.
int sum = n1 + n2; // calculate sum of previous two numbers in Fibonacci sequence.
n1 = n2; // set value of first number to second number (move first number that will be added in calculation of next number in sequence over).
n2 = sum; // set value of second number to the sum of previous two numbers (move second number that will be added in calculation of next number in sequence over).
}
long endTime = System.nanoTime(); // get and store time at end of iterative function.
long timeElapsed = endTime - startTime; // calculate total time elapsed during iterative function.
System.out.println(); // blank line, for output formatting.
System.out.println("Elapsed Time for Iterative Function: " + timeElapsed + " nanoseconds."); // print total elapsed time during iterative function.
}
}
<!-- end snippet -->
| 0debug
|
static rwpipe *rwpipe_open( int argc, char *argv[] )
{
rwpipe *this = av_mallocz( sizeof( rwpipe ) );
if ( this != NULL )
{
int input[ 2 ];
int output[ 2 ];
pipe( input );
pipe( output );
this->pid = fork();
if ( this->pid == 0 )
{
#define COMMAND_SIZE 10240
char *command = av_mallocz( COMMAND_SIZE );
int i;
strcpy( command, "" );
for ( i = 0; i < argc; i ++ )
{
av_strlcat( command, argv[ i ], COMMAND_SIZE );
av_strlcat( command, " ", COMMAND_SIZE );
}
dup2( output[ 0 ], STDIN_FILENO );
dup2( input[ 1 ], STDOUT_FILENO );
close( input[ 0 ] );
close( input[ 1 ] );
close( output[ 0 ] );
close( output[ 1 ] );
execl("/bin/sh", "sh", "-c", command, (char*)NULL );
_exit( 255 );
}
else
{
close( input[ 1 ] );
close( output[ 0 ] );
this->reader = fdopen( input[ 0 ], "r" );
this->writer = fdopen( output[ 1 ], "w" );
}
}
return this;
}
| 1threat
|
#javascript if condition is getting executed even though the condition is false : javascript flow is entering `if condition` even if the condition is false.
The code is below:
console.log("RefRefRef: "+Ref.length);
if(false) {
console.log("slakdfjaskldjlk");
$
.ajax({
url : "OnlineForm",
data : {
"RefId" : Ref
},
success : function(response) {
});
}
Let me know if the question is not clear enough.
Thanks
| 0debug
|
Scan a folder for files : <p>I am tasked with creating an app to monitor a folder for files to be processed.</p>
<p>I was wondering if there is anything new an exciting that I can use or should I just spin up a good old windows service?</p>
| 0debug
|
Python : What is the purpose of a double comma in a if statement : I have this piece of python code below.
def m(list):
v = list[0]
for e in list:
if v < e: v = e
return v
values = [[3, 4, 5, 1], [33, 6, 1, 2]]
for row in values:
print(m(row), end = " ")
The result is 5, 33.
Can somebody explain me that following if statement `if v < e: v = e`?
| 0debug
|
Javascript function : I recently started learning Javascript.
I have an assignment for my class, and what I have to do is to click a button (a number 10 is written on the button), and there has to be "Result = 55". (here all numbers from 0 to 10 are added)
To change words by clicking buttons, I wrote code like this.
function myFunction(num) {var p = document.getElementById("mydata); for (var i = 0; i <= num; i++) {sum = sum + i; p.innerHTML = "Result = " + sum;} }
As I submit an assignment for school, I learned that I have to add "var sum = 0" above "var p = document.getElementById("mydata")". However, I do not understand what "var sum = 0" means.
As for looks already show when to begin and end calculating, I feel like it doesn't have to be there.
| 0debug
|
INLINE float64 packFloat64( flag zSign, int16 zExp, bits64 zSig )
{
return ( ( (bits64) zSign )<<63 ) + ( ( (bits64) zExp )<<52 ) + zSig;
}
| 1threat
|
How to find images in a specific folder which are not multiples of 2? : I've some folders with about 200 images and I'd like to highligh the images which are not multiples of 2.
Is there an efficient way of doing so?
Best Regards!
| 0debug
|
what is delay() in C? is it a system function? : in a book, I saw a piece of code.
[![command line aurguments][1]][1]
but when I ran this code it says
C:\Users\dipankar\Desktop\cla.cpp [Error] 'delay' was not declared in this scope
they used it without proper documentation. they only said that "delay() is used to delay the execution of the next line by few milliseconds"!!.
please help.
[1]: https://i.stack.imgur.com/WSOUm.png
| 0debug
|
Eclipse Maven project error when performing any maven operation (maven build, maven clean ...) : <p>Error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher</p>
| 0debug
|
static void mptsas_update_interrupt(MPTSASState *s)
{
PCIDevice *pci = (PCIDevice *) s;
uint32_t state = s->intr_status & ~(s->intr_mask | MPI_HIS_IOP_DOORBELL_STATUS);
if (s->msi_in_use && msi_enabled(pci)) {
if (state) {
trace_mptsas_irq_msi(s);
msi_notify(pci, 0);
}
}
trace_mptsas_irq_intx(s, !!state);
pci_set_irq(pci, !!state);
}
| 1threat
|
static void stream_complete(BlockJob *job, void *opaque)
{
StreamBlockJob *s = container_of(job, StreamBlockJob, common);
StreamCompleteData *data = opaque;
BlockDriverState *bs = blk_bs(job->blk);
BlockDriverState *base = s->base;
Error *local_err = NULL;
if (!block_job_is_cancelled(&s->common) && data->reached_end &&
data->ret == 0) {
const char *base_id = NULL, *base_fmt = NULL;
if (base) {
base_id = s->backing_file_str;
if (base->drv) {
base_fmt = base->drv->format_name;
}
}
data->ret = bdrv_change_backing_file(bs, base_id, base_fmt);
bdrv_set_backing_hd(bs, base, &local_err);
if (local_err) {
error_report_err(local_err);
data->ret = -EPERM;
goto out;
}
}
out:
if (s->bs_flags != bdrv_get_flags(bs)) {
blk_set_perm(job->blk, 0, BLK_PERM_ALL, &error_abort);
bdrv_reopen(bs, s->bs_flags, NULL);
}
g_free(s->backing_file_str);
block_job_completed(&s->common, data->ret);
g_free(data);
}
| 1threat
|
Recursive Fibonacci in Python : This is not my code. I can't understand
what line 3 is doing exactly, the logical operations.
cache = {}
def fiba(n):
cache[n] = cache.get(n, 0) or (n <= 1 and 1 or fiba(n-1) + fiba(n-2))
return cache[n]
n = 0
x = 0
while fiba(x) <= 4000000:
if not fiba(x) % 2: n = n + fiba(x)
x=x+1
print(n)
| 0debug
|
What kind of code is this? C or C++ : <p>I have written some code for my own practice purpose, but interesting thing happened. I was originally trying to write a C++ code, however I forgot include streamio library and using namespace std, then I just using printf() function all the way during my coding. </p>
<p>I think the most confusing part to me is I use .cpp extension and compile this program using VS 2015 compiler but I actually wrote in C style. Could someone tell me do I wrote a C or C++ code?</p>
<p>Here is the source code:</p>
<pre><code>#include "stdafx.h"
#include <stdlib.h>
typedef struct node
{
int data;
node *next;
}node;
node *create()
{
int i = 0;
// Each variable must be assign to some value in the function
node *head, *p, *q = NULL;
int x = 0;
head = (node *)malloc(sizeof(node));
while (1)
{
printf("Please input the data: ");
scanf_s("%d", &x);
if (x == 0)
break;
p = (node *)malloc(sizeof(node));
p->data = x;
if (++i == 1) {
head->next = p;
}
else
{
q->next = p;
}
q = p;
}
q->next = NULL;
return head;
}
void printList(node head)
{
node *tmp = &head;
int counter = 0;
printf("Print out the list: \n");
while (tmp->next != NULL) {
tmp = tmp->next;
counter++;
//surprise to me printf() is pretty advance...
printf("%d item in the list: %d\n",counter, tmp->data);
}
}
int main()
{
printList(*create());
return 0;
}
</code></pre>
| 0debug
|
static av_cold void decode_init_vlc(void){
static int done = 0;
if (!done) {
int i;
done = 1;
init_vlc(&chroma_dc_coeff_token_vlc, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 4*5,
&chroma_dc_coeff_token_len [0], 1, 1,
&chroma_dc_coeff_token_bits[0], 1, 1, 1);
for(i=0; i<4; i++){
init_vlc(&coeff_token_vlc[i], COEFF_TOKEN_VLC_BITS, 4*17,
&coeff_token_len [i][0], 1, 1,
&coeff_token_bits[i][0], 1, 1, 1);
}
for(i=0; i<3; i++){
init_vlc(&chroma_dc_total_zeros_vlc[i], CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 4,
&chroma_dc_total_zeros_len [i][0], 1, 1,
&chroma_dc_total_zeros_bits[i][0], 1, 1, 1);
}
for(i=0; i<15; i++){
init_vlc(&total_zeros_vlc[i], TOTAL_ZEROS_VLC_BITS, 16,
&total_zeros_len [i][0], 1, 1,
&total_zeros_bits[i][0], 1, 1, 1);
}
for(i=0; i<6; i++){
init_vlc(&run_vlc[i], RUN_VLC_BITS, 7,
&run_len [i][0], 1, 1,
&run_bits[i][0], 1, 1, 1);
}
init_vlc(&run7_vlc, RUN7_VLC_BITS, 16,
&run_len [6][0], 1, 1,
&run_bits[6][0], 1, 1, 1);
}
}
| 1threat
|
is "delete[]" necessary after a wchar_t array/ string? : As i was explaining in the title, is that necessary? or operative system just handle that? This is the first question. The second question is from the code i was developing, i had an error from debugging with the "delete" instruction, and i'm not able to know why. When should i use delete and when i shouldn't?
[1]: https://i.stack.imgur.com/PV0ke.png
[here you can see the code][1]
[2]: https://i.stack.imgur.com/s4Lnc.png
[here you can see the error from debugging vmstudio 2013][2]
| 0debug
|
What does std::cout << std::cin do? : <p>I am new to C++ and was messing around with some of the things that I've learnt.
So I tried the following code:</p>
<pre><code>#include <iostream>
int main() {
std::cout << std::cin;
}
</code></pre>
<p>So I expected the code to return an error, but instead got what I think is a memory address (0x6fccc408). Also, when running it multiple times, I got the same memory address, even after restarting cmd. What exactly does this memory address signify?</p>
| 0debug
|
My if/else is messing up. (New programmer.) : cout << "Get ready to enter in the total rainfall for year " << yearCount << ".\n";
for (months = 1; months <= 12; months ++)
cout << "Please enter the total rainfall for ";
if (months == 1)
cout << "January.\n";
else if (months == 2)
cout << "February.\n";
else if (months == 3)
cout << "March.\n";
ect
I'm trying to make it to where each if statement will cout a name of a month instead of a number. however it just continues to loop "Please enter the total rainfall for " 12 times.
| 0debug
|
static void qdict_array_split_test(void)
{
QDict *test_dict = qdict_new();
QDict *dict1, *dict2;
QList *test_list;
qdict_put(test_dict, "1.x", qint_from_int(0));
qdict_put(test_dict, "3.y", qint_from_int(1));
qdict_put(test_dict, "0.a", qint_from_int(42));
qdict_put(test_dict, "o.o", qint_from_int(7));
qdict_put(test_dict, "0.b", qint_from_int(23));
qdict_array_split(test_dict, &test_list);
dict1 = qobject_to_qdict(qlist_pop(test_list));
dict2 = qobject_to_qdict(qlist_pop(test_list));
g_assert(dict1);
g_assert(dict2);
g_assert(qlist_empty(test_list));
QDECREF(test_list);
g_assert(qdict_get_int(dict1, "a") == 42);
g_assert(qdict_get_int(dict1, "b") == 23);
g_assert(qdict_size(dict1) == 2);
QDECREF(dict1);
g_assert(qdict_get_int(dict2, "x") == 0);
g_assert(qdict_size(dict2) == 1);
QDECREF(dict2);
g_assert(qdict_get_int(test_dict, "3.y") == 1);
g_assert(qdict_get_int(test_dict, "o.o") == 7);
g_assert(qdict_size(test_dict) == 2);
QDECREF(test_dict);
}
| 1threat
|
How to set start page in dotnet core web api? : <p>I try to build a web application with dotnet core web api,but i do not know how to set index.html as start page which can be done with dotnet framework web api easily. And i tried to use <code>app.UseDefaultFiles();app.UseStaticFiles();</code> to solve this problem, however, it did not work.</p>
| 0debug
|
Submit form to fill up the last recent ID row [MySQL] : <p>Lets say I have this table:</p>
<pre><code>------------------
ID | Car |
------------------
25 | Honda |
.. | ... |
.. | ... |
.. | ... |
123 | Toyota |
------------------
</code></pre>
<p>How to start fill in at row 124 instead of filling up row 1 til row 24 first? Assuming the <code>ID</code> is auto-incremental value.</p>
<p>Actual problem: my form method post fill up row with <code>ID = 1</code> instead of <code>ID = 124</code></p>
| 0debug
|
BusState *qbus_create(BusType type, size_t size,
DeviceState *parent, const char *name)
{
BusState *bus;
bus = qemu_mallocz(size);
bus->type = type;
bus->parent = parent;
bus->name = qemu_strdup(name);
LIST_INIT(&bus->children);
if (parent) {
LIST_INSERT_HEAD(&parent->child_bus, bus, sibling);
}
return bus;
}
| 1threat
|
Ckeditor show block element html : I'm using Ckeditor 4.5 version. I want to config same this images.
Please help me
[Block html][1]
[1]: http://i.stack.imgur.com/ezjxL.png
| 0debug
|
void do_savevm(Monitor *mon, const QDict *qdict)
{
DriveInfo *dinfo;
BlockDriverState *bs, *bs1;
QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
int must_delete, ret;
QEMUFile *f;
int saved_vm_running;
uint32_t vm_state_size;
#ifdef _WIN32
struct _timeb tb;
#else
struct timeval tv;
#endif
const char *name = qdict_get_try_str(qdict, "name");
bs = get_bs_snapshots();
if (!bs) {
monitor_printf(mon, "No block device can accept snapshots\n");
return;
}
qemu_aio_flush();
saved_vm_running = vm_running;
vm_stop(0);
must_delete = 0;
if (name) {
ret = bdrv_snapshot_find(bs, old_sn, name);
if (ret >= 0) {
must_delete = 1;
}
}
memset(sn, 0, sizeof(*sn));
if (must_delete) {
pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
} else {
if (name)
pstrcpy(sn->name, sizeof(sn->name), name);
}
#ifdef _WIN32
_ftime(&tb);
sn->date_sec = tb.time;
sn->date_nsec = tb.millitm * 1000000;
#else
gettimeofday(&tv, NULL);
sn->date_sec = tv.tv_sec;
sn->date_nsec = tv.tv_usec * 1000;
#endif
sn->vm_clock_nsec = qemu_get_clock(vm_clock);
f = qemu_fopen_bdrv(bs, 1);
if (!f) {
monitor_printf(mon, "Could not open VM state file\n");
goto the_end;
}
ret = qemu_savevm_state(f);
vm_state_size = qemu_ftell(f);
qemu_fclose(f);
if (ret < 0) {
monitor_printf(mon, "Error %d while writing VM\n", ret);
goto the_end;
}
TAILQ_FOREACH(dinfo, &drives, next) {
bs1 = dinfo->bdrv;
if (bdrv_has_snapshot(bs1)) {
if (must_delete) {
ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
if (ret < 0) {
monitor_printf(mon,
"Error while deleting snapshot on '%s'\n",
bdrv_get_device_name(bs1));
}
}
sn->vm_state_size = (bs == bs1 ? vm_state_size : 0);
ret = bdrv_snapshot_create(bs1, sn);
if (ret < 0) {
monitor_printf(mon, "Error while creating snapshot on '%s'\n",
bdrv_get_device_name(bs1));
}
}
}
the_end:
if (saved_vm_running)
vm_start();
}
| 1threat
|
static void img_snapshot(int argc, char **argv)
{
BlockDriverState *bs;
QEMUSnapshotInfo sn;
char *filename, *snapshot_name = NULL;
int c, ret;
int action = 0;
qemu_timeval tv;
for(;;) {
c = getopt(argc, argv, "la:c:d:h");
if (c == -1)
break;
switch(c) {
case 'h':
help();
return;
case 'l':
if (action) {
help();
return;
}
action = SNAPSHOT_LIST;
break;
case 'a':
if (action) {
help();
return;
}
action = SNAPSHOT_APPLY;
snapshot_name = optarg;
break;
case 'c':
if (action) {
help();
return;
}
action = SNAPSHOT_CREATE;
snapshot_name = optarg;
break;
case 'd':
if (action) {
help();
return;
}
action = SNAPSHOT_DELETE;
snapshot_name = optarg;
break;
}
}
if (optind >= argc)
help();
filename = argv[optind++];
bs = bdrv_new("");
if (!bs)
error("Not enough memory");
if (bdrv_open2(bs, filename, 0, NULL) < 0) {
error("Could not open '%s'", filename);
}
switch(action) {
case SNAPSHOT_LIST:
dump_snapshots(bs);
break;
case SNAPSHOT_CREATE:
memset(&sn, 0, sizeof(sn));
pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
qemu_gettimeofday(&tv);
sn.date_sec = tv.tv_sec;
sn.date_nsec = tv.tv_usec * 1000;
ret = bdrv_snapshot_create(bs, &sn);
if (ret)
error("Could not create snapshot '%s': %d (%s)",
snapshot_name, ret, strerror(-ret));
break;
case SNAPSHOT_APPLY:
ret = bdrv_snapshot_goto(bs, snapshot_name);
if (ret)
error("Could not apply snapshot '%s': %d (%s)",
snapshot_name, ret, strerror(-ret));
break;
case SNAPSHOT_DELETE:
ret = bdrv_snapshot_delete(bs, snapshot_name);
if (ret)
error("Could not delete snapshot '%s': %d (%s)",
snapshot_name, ret, strerror(-ret));
break;
}
bdrv_delete(bs);
}
| 1threat
|
np.arange function returns weird value. I don't know why : <pre><code>import numpy as np
a=np.arange(1e-10,2e-10,1e-11)
print(len(a))
b=np.arange(0.1,0.2,0.01)
print(len(b))
</code></pre>
<p>Value of a is 11 and value of b is 10. Why is that? I've known that arange func is the interval including start but excluding stop. </p>
| 0debug
|
unsigned long get_checksum(ByteIOContext *s){
s->checksum= s->update_checksum(s->checksum, s->checksum_ptr, s->buf_ptr - s->checksum_ptr);
s->checksum_ptr= NULL;
return s->checksum;
}
| 1threat
|
how to solve bean exception in spring framework? :
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.Test;
public class Client
{
public static void main(String args[])
{
ApplicationContext ap=new ClassPathXmlApplicationContext("res/spring.xml");
Test t=(Test)ap.getBean("t");
t.printData();
}
}
———————————————————————————————————
package beans;
public class Test {
private String name;
private int age;
public Test(String name) {
this.name=name;
}
public Test(int age)
{
this.age=age;
}
public void printData()
{
System.out.println("age="+age);
System.out.println("name="+name);
}
}
———————————————————————————————————-
**Jun 28, 2016 4:01:06 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@138eb89: startup date [Tue Jun 28 16:01:06 IST 2016]; root of context hierarchy
Jun 28, 2016 4:01:06 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [res/spring.xml]
Jun 28, 2016 4:01:06 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@616ca2: defining beans [t]; root of factory hierarchy
Jun 28, 2016 4:01:06 PM org.springframework.beans.factory.support.DefaultListableBeanFactory destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@616ca2: defining beans [t]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 't' defined in class path resource [res/spring.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)**
———————————————————————————————————
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd
(http://www.springframework.org/dtd/spring-beans-2.0.dtd)">
<beans>
<bean id="t" class="beans.Test">
<constructor-arg value="vikram" type="java.Lang.String" index="0"/>
<constructor-arg value="123" type="int" index="1"/>
</bean>
</beans>
| 0debug
|
static void dump_video_param(AVCodecContext *avctx, QSVEncContext *q,
mfxExtBuffer **coding_opts)
{
mfxInfoMFX *info = &q->param.mfx;
mfxExtCodingOption *co = (mfxExtCodingOption*)coding_opts[0];
#if QSV_HAVE_CO2
mfxExtCodingOption2 *co2 = (mfxExtCodingOption2*)coding_opts[1];
#endif
#if QSV_HAVE_CO3
mfxExtCodingOption3 *co3 = (mfxExtCodingOption3*)coding_opts[2];
#endif
av_log(avctx, AV_LOG_VERBOSE, "profile: %s; level: %"PRIu16"\n",
print_profile(info->CodecProfile), info->CodecLevel);
av_log(avctx, AV_LOG_VERBOSE, "GopPicSize: %"PRIu16"; GopRefDist: %"PRIu16"; GopOptFlag: ",
info->GopPicSize, info->GopRefDist);
if (info->GopOptFlag & MFX_GOP_CLOSED)
av_log(avctx, AV_LOG_VERBOSE, "closed ");
if (info->GopOptFlag & MFX_GOP_STRICT)
av_log(avctx, AV_LOG_VERBOSE, "strict ");
av_log(avctx, AV_LOG_VERBOSE, "; IdrInterval: %"PRIu16"\n", info->IdrInterval);
av_log(avctx, AV_LOG_VERBOSE, "TargetUsage: %"PRIu16"; RateControlMethod: %s\n",
info->TargetUsage, print_ratecontrol(info->RateControlMethod));
if (info->RateControlMethod == MFX_RATECONTROL_CBR ||
info->RateControlMethod == MFX_RATECONTROL_VBR
#if QSV_HAVE_VCM
|| info->RateControlMethod == MFX_RATECONTROL_VCM
#endif
) {
av_log(avctx, AV_LOG_VERBOSE,
"InitialDelayInKB: %"PRIu16"; TargetKbps: %"PRIu16"; MaxKbps: %"PRIu16"\n",
info->InitialDelayInKB, info->TargetKbps, info->MaxKbps);
} else if (info->RateControlMethod == MFX_RATECONTROL_CQP) {
av_log(avctx, AV_LOG_VERBOSE, "QPI: %"PRIu16"; QPP: %"PRIu16"; QPB: %"PRIu16"\n",
info->QPI, info->QPP, info->QPB);
} else if (info->RateControlMethod == MFX_RATECONTROL_AVBR) {
av_log(avctx, AV_LOG_VERBOSE,
"TargetKbps: %"PRIu16"; Accuracy: %"PRIu16"; Convergence: %"PRIu16"\n",
info->TargetKbps, info->Accuracy, info->Convergence);
}
#if QSV_HAVE_LA
else if (info->RateControlMethod == MFX_RATECONTROL_LA
#if QSV_HAVE_LA_HRD
|| info->RateControlMethod == MFX_RATECONTROL_LA_HRD
#endif
) {
av_log(avctx, AV_LOG_VERBOSE,
"TargetKbps: %"PRIu16"; LookAheadDepth: %"PRIu16"\n",
info->TargetKbps, co2->LookAheadDepth);
}
#endif
#if QSV_HAVE_ICQ
else if (info->RateControlMethod == MFX_RATECONTROL_ICQ) {
av_log(avctx, AV_LOG_VERBOSE, "ICQQuality: %"PRIu16"\n", info->ICQQuality);
} else if (info->RateControlMethod == MFX_RATECONTROL_LA_ICQ) {
av_log(avctx, AV_LOG_VERBOSE, "ICQQuality: %"PRIu16"; LookAheadDepth: %"PRIu16"\n",
info->ICQQuality, co2->LookAheadDepth);
}
#endif
#if QSV_HAVE_QVBR
else if (info->RateControlMethod == MFX_RATECONTROL_QVBR) {
av_log(avctx, AV_LOG_VERBOSE, "QVBRQuality: %"PRIu16"\n",
co3->QVBRQuality);
}
#endif
av_log(avctx, AV_LOG_VERBOSE, "NumSlice: %"PRIu16"; NumRefFrame: %"PRIu16"\n",
info->NumSlice, info->NumRefFrame);
av_log(avctx, AV_LOG_VERBOSE, "RateDistortionOpt: %s\n",
print_threestate(co->RateDistortionOpt));
#if QSV_HAVE_CO2
av_log(avctx, AV_LOG_VERBOSE,
"RecoveryPointSEI: %s IntRefType: %"PRIu16"; IntRefCycleSize: %"PRIu16"; IntRefQPDelta: %"PRId16"\n",
print_threestate(co->RecoveryPointSEI), co2->IntRefType, co2->IntRefCycleSize, co2->IntRefQPDelta);
av_log(avctx, AV_LOG_VERBOSE, "MaxFrameSize: %"PRIu16"; ", co2->MaxFrameSize);
#if QSV_VERSION_ATLEAST(1, 9)
av_log(avctx, AV_LOG_VERBOSE, "MaxSliceSize: %"PRIu16"; ", co2->MaxSliceSize);
#endif
av_log(avctx, AV_LOG_VERBOSE, "\n");
av_log(avctx, AV_LOG_VERBOSE,
"BitrateLimit: %s; MBBRC: %s; ExtBRC: %s\n",
print_threestate(co2->BitrateLimit), print_threestate(co2->MBBRC),
print_threestate(co2->ExtBRC));
#if QSV_HAVE_TRELLIS
av_log(avctx, AV_LOG_VERBOSE, "Trellis: ");
if (co2->Trellis & MFX_TRELLIS_OFF) {
av_log(avctx, AV_LOG_VERBOSE, "off");
} else if (!co2->Trellis) {
av_log(avctx, AV_LOG_VERBOSE, "auto");
} else {
if (co2->Trellis & MFX_TRELLIS_I) av_log(avctx, AV_LOG_VERBOSE, "I");
if (co2->Trellis & MFX_TRELLIS_P) av_log(avctx, AV_LOG_VERBOSE, "P");
if (co2->Trellis & MFX_TRELLIS_B) av_log(avctx, AV_LOG_VERBOSE, "B");
}
av_log(avctx, AV_LOG_VERBOSE, "\n");
#endif
#if QSV_VERSION_ATLEAST(1, 8)
av_log(avctx, AV_LOG_VERBOSE,
"RepeatPPS: %s; NumMbPerSlice: %"PRIu16"; LookAheadDS: ",
print_threestate(co2->RepeatPPS), co2->NumMbPerSlice);
switch (co2->LookAheadDS) {
case MFX_LOOKAHEAD_DS_OFF: av_log(avctx, AV_LOG_VERBOSE, "off"); break;
case MFX_LOOKAHEAD_DS_2x: av_log(avctx, AV_LOG_VERBOSE, "2x"); break;
case MFX_LOOKAHEAD_DS_4x: av_log(avctx, AV_LOG_VERBOSE, "4x"); break;
default: av_log(avctx, AV_LOG_VERBOSE, "unknown"); break;
}
av_log(avctx, AV_LOG_VERBOSE, "\n");
av_log(avctx, AV_LOG_VERBOSE, "AdaptiveI: %s; AdaptiveB: %s; BRefType: ",
print_threestate(co2->AdaptiveI), print_threestate(co2->AdaptiveB));
switch (co2->BRefType) {
case MFX_B_REF_OFF: av_log(avctx, AV_LOG_VERBOSE, "off"); break;
case MFX_B_REF_PYRAMID: av_log(avctx, AV_LOG_VERBOSE, "pyramid"); break;
default: av_log(avctx, AV_LOG_VERBOSE, "auto"); break;
}
av_log(avctx, AV_LOG_VERBOSE, "\n");
#endif
#if QSV_VERSION_ATLEAST(1, 9)
av_log(avctx, AV_LOG_VERBOSE,
"MinQPI: %"PRIu8"; MaxQPI: %"PRIu8"; MinQPP: %"PRIu8"; MaxQPP: %"PRIu8"; MinQPB: %"PRIu8"; MaxQPB: %"PRIu8"\n",
co2->MinQPI, co2->MaxQPI, co2->MinQPP, co2->MaxQPP, co2->MinQPB, co2->MaxQPB);
#endif
#endif
if (avctx->codec_id == AV_CODEC_ID_H264) {
av_log(avctx, AV_LOG_VERBOSE, "Entropy coding: %s; MaxDecFrameBuffering: %"PRIu16"\n",
co->CAVLC == MFX_CODINGOPTION_ON ? "CAVLC" : "CABAC", co->MaxDecFrameBuffering);
av_log(avctx, AV_LOG_VERBOSE,
"NalHrdConformance: %s; SingleSeiNalUnit: %s; VuiVclHrdParameters: %s VuiNalHrdParameters: %s\n",
print_threestate(co->NalHrdConformance), print_threestate(co->SingleSeiNalUnit),
print_threestate(co->VuiVclHrdParameters), print_threestate(co->VuiNalHrdParameters));
}
}
| 1threat
|
Warning: function result variable of a managed type does not seem to initialized : I am unfortunately required to use pascal for university to create programs, the task I have requires me to create two routines one of which reads in data from a terminal and the other outputs data to the terminal, and another two routines which utilize an array to loop through these two routines to perform them multiple times. The issue I am having is that the terminal crashes after one run though of the ReadComputer function instead of looping multiple times. the compiler is also providing me the following warning: "Warning: function result variable of a managed type does not seem to initialized" although after extensive research and due to the fact that no one uses pascal I cannot find a solution. Any help is much appreciated! :)
I have provided a copy of my code here for reference:
program CompupterProgram;
uses TerminalUserInput;
type
Computer = Record
id: integer;
manafacturer: String;
year: integer;
warranty: integer;
end;
type Computers = Array of Computer;
function ReadComputer(): Computer;
begin
ReadComputer.id := ReadInteger('PLease Enter Computer Id:');
ReadComputer.manafacturer := ReadString('PLease Enter Computer Manafacturer:');
ReadComputer.year := ReadInteger('PLease Enter Computer Year:');
ReadComputer.warranty := ReadInteger('PLease Enter Computer Warranty:');
result := ReadComputer;
end;
procedure WriteComputer(c: Computer);
begin
WriteLn('Computer ID: ', c.id);
WriteLn('Computer Manafacturer ', c.manafacturer);
WriteLn('Computer Year ', c.year);
WriteLn('Computer Warranty ', c.warranty);
ReadLn();
end;
function ReadAllComputers(count: Integer): Computers;
var i: Integer;
begin
for i := 0 to count do
begin
ReadAllComputers[i] := ReadComputer();
end;
result := ReadAllComputers;
end;
procedure WriteAllComputers(computerArray: Computers);
var i: Integer;
begin
for i:= 0 to (length(computerArray)) do
begin
WriteComputer(computerArray[i]);
end;
end;
procedure Main();
var computers: Array of Computer;
index: Integer;
begin
computers := ReadAllComputers(3);
WriteAllComputers(computers);
end;
begin
Main();
end.
| 0debug
|
static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
Error **errp)
{
const char *buf;
int bdrv_flags = 0;
int on_read_error, on_write_error;
bool account_invalid, account_failed;
const char *stats_intervals;
BlockBackend *blk;
BlockDriverState *bs;
ThrottleConfig cfg;
int snapshot = 0;
Error *error = NULL;
QemuOpts *opts;
const char *id;
bool has_driver_specific_opts;
BlockdevDetectZeroesOptions detect_zeroes =
BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
const char *throttling_group = NULL;
id = qdict_get_try_str(bs_opts, "id");
opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
if (error) {
error_propagate(errp, error);
goto err_no_opts;
}
qemu_opts_absorb_qdict(opts, bs_opts, &error);
if (error) {
error_propagate(errp, error);
goto early_err;
}
if (id) {
qdict_del(bs_opts, "id");
}
has_driver_specific_opts = !!qdict_size(bs_opts);
snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
stats_intervals = qemu_opt_get(opts, "stats-intervals");
extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
&detect_zeroes, &error);
if (error) {
error_propagate(errp, error);
goto early_err;
}
if ((buf = qemu_opt_get(opts, "format")) != NULL) {
if (is_help_option(buf)) {
error_printf("Supported formats:");
bdrv_iterate_format(bdrv_format_print, NULL);
error_printf("\n");
goto early_err;
}
if (qdict_haskey(bs_opts, "driver")) {
error_setg(errp, "Cannot specify both 'driver' and 'format'");
goto early_err;
}
qdict_put(bs_opts, "driver", qstring_from_str(buf));
}
on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
on_write_error = parse_block_error_action(buf, 0, &error);
if (error) {
error_propagate(errp, error);
goto early_err;
}
}
on_read_error = BLOCKDEV_ON_ERROR_REPORT;
if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
on_read_error = parse_block_error_action(buf, 1, &error);
if (error) {
error_propagate(errp, error);
goto early_err;
}
}
if (snapshot) {
bdrv_flags &= ~BDRV_O_CACHE_MASK;
bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
}
if ((!file || !*file) && !has_driver_specific_opts) {
BlockBackendRootState *blk_rs;
blk = blk_new(qemu_opts_id(opts), errp);
if (!blk) {
goto early_err;
}
blk_rs = blk_get_root_state(blk);
blk_rs->open_flags = bdrv_flags;
blk_rs->read_only = !(bdrv_flags & BDRV_O_RDWR);
blk_rs->detect_zeroes = detect_zeroes;
if (throttle_enabled(&cfg)) {
if (!throttling_group) {
throttling_group = blk_name(blk);
}
blk_rs->throttle_group = g_strdup(throttling_group);
blk_rs->throttle_state = throttle_group_incref(throttling_group);
blk_rs->throttle_state->cfg = cfg;
}
QDECREF(bs_opts);
} else {
if (file && !*file) {
file = NULL;
}
blk = blk_new_open(qemu_opts_id(opts), file, NULL, bs_opts, bdrv_flags,
errp);
if (!blk) {
goto err_no_bs_opts;
}
bs = blk_bs(blk);
bs->detect_zeroes = detect_zeroes;
if (throttle_enabled(&cfg)) {
if (!throttling_group) {
throttling_group = blk_name(blk);
}
bdrv_io_limits_enable(bs, throttling_group);
bdrv_set_io_limits(bs, &cfg);
}
if (bdrv_key_required(bs)) {
autostart = 0;
}
block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
if (stats_intervals) {
char **intervals = g_strsplit(stats_intervals, ":", 0);
unsigned i;
if (*stats_intervals == '\0') {
error_setg(&error, "stats-intervals can't have an empty value");
}
for (i = 0; !error && intervals[i] != NULL; i++) {
unsigned long long val;
if (parse_uint_full(intervals[i], &val, 10) == 0 &&
val > 0 && val <= UINT_MAX) {
block_acct_add_interval(blk_get_stats(blk), val);
} else {
error_setg(&error, "Invalid interval length: '%s'",
intervals[i]);
}
}
g_strfreev(intervals);
if (error) {
error_propagate(errp, error);
blk_unref(blk);
blk = NULL;
goto err_no_bs_opts;
}
}
}
blk_set_on_error(blk, on_read_error, on_write_error);
err_no_bs_opts:
qemu_opts_del(opts);
return blk;
early_err:
qemu_opts_del(opts);
err_no_opts:
QDECREF(bs_opts);
return NULL;
}
| 1threat
|
static int decode_p_frame(FourXContext *f, const uint8_t *buf, int length){
int x, y;
const int width= f->avctx->width;
const int height= f->avctx->height;
uint16_t *src= (uint16_t*)f->last_picture.data[0];
uint16_t *dst= (uint16_t*)f->current_picture.data[0];
const int stride= f->current_picture.linesize[0]>>1;
unsigned int bitstream_size, bytestream_size, wordstream_size, extra;
if(f->version>1){
extra=20;
bitstream_size= AV_RL32(buf+8);
wordstream_size= AV_RL32(buf+12);
bytestream_size= AV_RL32(buf+16);
}else{
extra=0;
bitstream_size = AV_RL16(buf-4);
wordstream_size= AV_RL16(buf-2);
bytestream_size= FFMAX(length - bitstream_size - wordstream_size, 0);
}
if(bitstream_size+ bytestream_size+ wordstream_size + extra != length
|| bitstream_size > (1<<26)
|| bytestream_size > (1<<26)
|| wordstream_size > (1<<26)
){
av_log(f->avctx, AV_LOG_ERROR, "lengths %d %d %d %d\n", bitstream_size, bytestream_size, wordstream_size,
bitstream_size+ bytestream_size+ wordstream_size - length);
return -1;
}
av_fast_malloc(&f->bitstream_buffer, &f->bitstream_buffer_size, bitstream_size + FF_INPUT_BUFFER_PADDING_SIZE);
if (!f->bitstream_buffer)
return AVERROR(ENOMEM);
f->dsp.bswap_buf(f->bitstream_buffer, (const uint32_t*)(buf + extra), bitstream_size/4);
memset((uint8_t*)f->bitstream_buffer + bitstream_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
init_get_bits(&f->gb, f->bitstream_buffer, 8*bitstream_size);
f->wordstream= (const uint16_t*)(buf + extra + bitstream_size);
f->bytestream= buf + extra + bitstream_size + wordstream_size;
init_mv(f);
for(y=0; y<height; y+=8){
for(x=0; x<width; x+=8){
decode_p_block(f, dst + x, src + x, 3, 3, stride);
}
src += 8*stride;
dst += 8*stride;
}
if( bitstream_size != (get_bits_count(&f->gb)+31)/32*4
|| (((const char*)f->wordstream - (const char*)buf + 2)&~2) != extra + bitstream_size + wordstream_size
|| (((const char*)f->bytestream - (const char*)buf + 3)&~3) != extra + bitstream_size + wordstream_size + bytestream_size)
av_log(f->avctx, AV_LOG_ERROR, " %d %td %td bytes left\n",
bitstream_size - (get_bits_count(&f->gb)+31)/32*4,
-(((const char*)f->bytestream - (const char*)buf + 3)&~3) + (extra + bitstream_size + wordstream_size + bytestream_size),
-(((const char*)f->wordstream - (const char*)buf + 2)&~2) + (extra + bitstream_size + wordstream_size)
);
return 0;
}
| 1threat
|
PHP array sort using Bubble approach : <p>I have a array such as $arr = array(1,3,2,8,5,7,4,6,0);</p>
<p>How can i use bubble sorting method for custom sort ?</p>
<p>Thank you</p>
| 0debug
|
db.execute('SELECT * FROM products WHERE product_id = ' + product_input)
| 1threat
|
java static final in kotlin: Const 'val' initializer should be a constant value : <p>In Java, We can do this:</p>
<pre><code>public class TestA {
public static final boolean flag = true;
public static final String str = flag ? "A" : "B"; // ok
}
</code></pre>
<p>But cannot in Kotlin</p>
<pre><code> class TestA {
companion object {
const val flag = true
const val str = if (flag) "A" else "B" //err: Const 'val' initializer should be a constant value
val str2 = if (flag) "A" else "B" //ok, but not equals [public static final] in Java.
}
}
</code></pre>
<p>Tried <strong>@JvmStatic</strong> on non-const <strong>str2</strong>, but decompiled to java code, it's</p>
<pre><code>private static final String str2 = "A"
public static final String getStr2() {
return Companion.getStr2();
}
</code></pre>
<p>Problem: kotlin <strong>if-else</strong> equals <strong>?:</strong> in java,but cannnot use for <strong>const</strong> val. need solution for this.</p>
| 0debug
|
acces to switch statement parametre value from a global variable : am learning javascript by making a little project , I have little probleme of understanding well global variables ,
in that example when I put the variable = result ; from the randomvariable() function , on the switch parametre of test() function it doesn't work
function randomvariable () {
var myarray = new Array;
myarray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
randomvariable = Math.floor(Math.random() * 0);
result = (myarray[randomvariable]);
}
function test() {
switch (result) {
case 0:
alert("haahhaha");
break;
}
}
| 0debug
|
how to Increase the figure size of Dataframe.hist for pandas 0.11.0 : <p>I am trying to make histograms for all columns of a dataframe through pandas 0.11.0 but the figure size is very small and hence the histograms are coming even smaller. We have the figsize property in 0.19.0 but how can we achieve the same in 0.11.0.</p>
| 0debug
|
submit and do html form string in asp mvc controler side : i have html string like this in controller
i receive this from web service (not important)
string str ="<form name='jy'action='https://' method='POST'><input type=submit value='Pay'></form>";
i should send this to view and show to user and user should click on submit and ...
but i want do this form and submit it automatically in controller side .
i mean no need to show this to user then user click on submit
it useless
how can i do this?
| 0debug
|
How to use classes in C++? : <p>I can't see to find the problem in my code. Nor the solution on the internet. I can see that i can create the code in a different way but i need to know how to work with it written like this:</p>
<pre><code>class Triunghi{
int l1=0;//latura1
int l2=0;//latura2
int ba=0;//baza
int p=0;//perimetru
public:
Triunghi(){}
Triunghi(int a):l1(a){}
Triunghi(int a,int b):l1(a),l2(b){}
Triunghi(int a,int b,int c):l1(a),l2(b),ba(c){}
Triunghi(int a,int b,int c,char *msg):l1(a),l2(b),ba(c){
cout<<msg<<""<<l1<<l2<<ba<<endl;
}
Triunghi(Triunghi &A){
l1=A.l1;
l2=A.l2;
ba=A.ba;
}
~Triunghi(){
}
int Perimetru()
{
p=l1+l2+ba;
return (p);
}
};
</code></pre>
<p>It works fine there are no errors but i cant seem to give value to l1, l2 and ba, to use them in function 'Perimetru'.
This is how my main looks.</p>
<pre><code>int main()
{
Triunghi tri;
Triunghi(1,2,3);
tri.Perimetru();
return 0;
}
</code></pre>
<p>How to make it work?</p>
| 0debug
|
static void extend_solid_area(VncState *vs, int x, int y, int w, int h,
uint32_t color, int *x_ptr, int *y_ptr,
int *w_ptr, int *h_ptr)
{
int cx, cy;
for ( cy = *y_ptr - 1;
cy >= y && check_solid_tile(vs, *x_ptr, cy, *w_ptr, 1, &color, true);
cy-- );
*h_ptr += *y_ptr - (cy + 1);
*y_ptr = cy + 1;
for ( cy = *y_ptr + *h_ptr;
cy < y + h &&
check_solid_tile(vs, *x_ptr, cy, *w_ptr, 1, &color, true);
cy++ );
*h_ptr += cy - (*y_ptr + *h_ptr);
for ( cx = *x_ptr - 1;
cx >= x && check_solid_tile(vs, cx, *y_ptr, 1, *h_ptr, &color, true);
cx-- );
*w_ptr += *x_ptr - (cx + 1);
*x_ptr = cx + 1;
for ( cx = *x_ptr + *w_ptr;
cx < x + w &&
check_solid_tile(vs, cx, *y_ptr, 1, *h_ptr, &color, true);
cx++ );
*w_ptr += cx - (*x_ptr + *w_ptr);
}
| 1threat
|
Xcode 7.3 autocomplete is so frustrating : <p>There is a new autocomplete in Xcode. Probably might be useful because it checks not only beginning of names etc. But I found that very often it doesn't find a class name or a const name at all etc. I need to type in entire name by myself. Over all I found it makes my life harder and coding more time consuming. Is there a way to switch to the old way it used to work?</p>
| 0debug
|
Pytorch Chatbot Tutorial problem: How can I slove List Index Out of Range : I’m new to pytorch and have been following the many tutorials available.
But, When I did The CHATBOT TUTORIAL
(https://pytorch.org/tutorials/beginner/chatbot_tutorial.html?highlight=chatbot%20tutorial) is not work.
Like the figure below
[enter image description here][1]
[1]: https://i.stack.imgur.com/soEPi.jpg
What should I do and what is causing this?
| 0debug
|
How to implement drop down list in flutter? : <p>I have a list of locations that i want to implement as a dropdown list in Flutter. Im pretty new to the language. Here's what i have done.</p>
<pre><code>new DropdownButton(
value: _selectedLocation,
onChanged: (String newValue) {
setState(() {
_selectedLocation = newValue;
});
},
items: _locations.map((String location) {
return new DropdownMenuItem<String>(
child: new Text(location),
);
}).toList(),
</code></pre>
<p>This is my list of items:</p>
<pre><code>List<String> _locations = ['A', 'B', 'C', 'D'];
</code></pre>
<p>And I am getting the following error.</p>
<pre><code>Another exception was thrown: 'package:flutter/src/material/dropdown.dart': Failed assertion: line 468 pos 15: 'value == null || items.where((DropdownMenuItem<T> item) => item.value == value).length == 1': is not true.
</code></pre>
<p>I assume the value of <code>_selectedLocation</code> is getting null. But i am initialising it like so.</p>
<p><code>String _selectedLocation = 'Please choose a location';</code></p>
| 0debug
|
def dealnnoy_num(n, m):
if (m == 0 or n == 0) :
return 1
return dealnnoy_num(m - 1, n) + dealnnoy_num(m - 1, n - 1) + dealnnoy_num(m, n - 1)
| 0debug
|
wanting to print if list elements are armstrong number or not : n = int(input("" ""))
l = []
for i in range(n):
a = int(input())
l.append(a)
s=0
for i in l:
temp = i
while temp>0:
d = temp % 10
s += d**3
temp //= 10
if n == s:
print("yes")
else:
print("no")
I am trying to print yes if the number is Armstrong number if not no but the code give me only else part if part is not executing please help.
| 0debug
|
What's the difference between pg_table_size, pg_relation_size & pg_total_relation_size? (PostgreSQL) : <p>What's the difference between <code>pg_table_size()</code>, <code>pg_relation_size()</code> & <code>pg_total_relation_size()</code>?</p>
<p>I understand the basic differences explained <a href="https://www.postgresql.org/docs/current/static/functions-admin.html#FUNCTIONS-ADMIN-DBSIZE" rel="noreferrer">in the documentation</a>, but what does it imply in terms of how much space my table is actually using?</p>
| 0debug
|
void spapr_register_hypercall(target_ulong opcode, spapr_hcall_fn fn)
{
spapr_hcall_fn old_fn;
assert(opcode <= MAX_HCALL_OPCODE);
assert((opcode & 0x3) == 0);
old_fn = hypercall_table[opcode / 4];
assert(!old_fn || (fn == old_fn));
hypercall_table[opcode / 4] = fn;
}
| 1threat
|
Javascript password validation check if it hass small and capitals and special characters : Am trying to create a password vaidation by checking if it has small, capital letters and special characters but still fails to work
so i have
testPwd(val){
return Boolean(/^[a-zA-Z0-9]+$/.test(val));
}
Where am i going wrong as a test of
console.log(testPwd("123")
shows true
which is the valid regex, i want to make sure all scenarios are included (small, capital and special characters)
| 0debug
|
int qemu_thread_is_self(QemuThread *thread)
{
QemuThread *this_thread = TlsGetValue(qemu_thread_tls_index);
return this_thread->thread == thread->thread;
}
| 1threat
|
static void generate_new_codebooks(RoqContext *enc, RoqTempdata *tempData)
{
int i,j;
RoqCodebooks *codebooks = &tempData->codebooks;
int max = enc->width*enc->height/16;
uint8_t mb2[3*4];
roq_cell *results4 = av_malloc(sizeof(roq_cell)*MAX_CBS_4x4*4);
uint8_t *yuvClusters=av_malloc(sizeof(int)*max*6*4);
int *points = av_malloc(max*6*4*sizeof(int));
int bias;
create_clusters(enc->frame_to_enc, enc->width, enc->height, yuvClusters);
for (i=0; i<max*24; i++) {
bias = ((i%6)<4) ? 1 : CHROMA_BIAS;
points[i] = bias*yuvClusters[i];
}
generate_codebook(enc, tempData, points, max, results4, 4, MAX_CBS_4x4);
codebooks->numCB4 = MAX_CBS_4x4;
tempData->closest_cb2 = av_malloc(max*4*sizeof(int));
generate_codebook(enc, tempData, points, max*4, enc->cb2x2, 2, MAX_CBS_2x2);
codebooks->numCB2 = MAX_CBS_2x2;
for (i=0; i<codebooks->numCB2; i++)
unpack_roq_cell(enc->cb2x2 + i, codebooks->unpacked_cb2 + i*2*2*3);
for (i=0; i<codebooks->numCB4; i++) {
for (j=0; j<4; j++) {
unpack_roq_cell(&results4[4*i + j], mb2);
index_mb(mb2, codebooks->unpacked_cb2, codebooks->numCB2,
&enc->cb4x4[i].idx[j], 2);
}
unpack_roq_qcell(codebooks->unpacked_cb2, enc->cb4x4 + i,
codebooks->unpacked_cb4 + i*4*4*3);
enlarge_roq_mb4(codebooks->unpacked_cb4 + i*4*4*3,
codebooks->unpacked_cb4_enlarged + i*8*8*3);
}
av_free(yuvClusters);
av_free(points);
av_free(results4);
}
| 1threat
|
static void pc_cpu_unplug_request_cb(HotplugHandler *hotplug_dev,
DeviceState *dev, Error **errp)
{
int idx = -1;
HotplugHandlerClass *hhc;
Error *local_err = NULL;
X86CPU *cpu = X86_CPU(dev);
PCMachineState *pcms = PC_MACHINE(hotplug_dev);
pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, &idx);
assert(idx != -1);
if (idx == 0) {
error_setg(&local_err, "Boot CPU is unpluggable");
hhc = HOTPLUG_HANDLER_GET_CLASS(pcms->acpi_dev);
hhc->unplug_request(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err);
if (local_err) {
out:
error_propagate(errp, local_err);
| 1threat
|
static void qxl_send_events(PCIQXLDevice *d, uint32_t events)
{
uint32_t old_pending;
uint32_t le_events = cpu_to_le32(events);
trace_qxl_send_events(d->id, events);
assert(qemu_spice_display_is_running(&d->ssd));
old_pending = __sync_fetch_and_or(&d->ram->int_pending, le_events);
if ((old_pending & le_events) == le_events) {
return;
}
if (qemu_thread_is_self(&d->main)) {
qxl_update_irq(d);
} else {
if (write(d->pipe[1], d, 1) != 1) {
dprint(d, 1, "%s: write to pipe failed\n", __func__);
}
}
}
| 1threat
|
function on php file : I have this code that I got from here,
(function() {
var quotes = $(".quotes");
var quoteIndex = -1;
function showNextQuote() {
++quoteIndex;
quotes.eq(quoteIndex % quotes.length)
.fadeIn(2000)
.delay(2000)
.fadeOut(2000, showNextQuote);
}
showNextQuote();
})();
I wanna know how to put it in my index php file cause it's not working , knowing that I'm working on a joomla template and the class quote is on one of the modules ... thanks
| 0debug
|
How to call Kotlin suspending coroutine function from Java 7 : <p>I'm trying to call Kotlin function from Java 7. I'm using coroutines and this called function is suspending, for example:</p>
<pre><code>suspend fun suspendingFunction(): Boolean {
return async { longRunningFunction() }.await()
}
suspend fun longRunningFunction() : Boolean {
delay(400)
return true
}
</code></pre>
<p>I was using coroutines in version 0.25.3 and I could emulate simple Java callback style by passing <code>Continuation<U></code> instance as an argument to suspending function, e.g.</p>
<pre class="lang-java prettyprint-override"><code>CoroutinesKt.suspendingFunction(new Continuation<Boolean>() {
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE;
}
@Override
public void resume(Boolean value) {
doSomethingWithResult(value);
}
@Override
public void resumeWithException(@NotNull Throwable throwable) {
handleException(throwable);
}
});
</code></pre>
<p>However, after updating to fully stable 1.0.1 release, I think it's no longer possible. Let's say updated version of suspending function looks like that:</p>
<pre><code>suspend fun suspendingFunction(): Boolean {
return GlobalScope.async { longRunningFunction() }.await()
}
</code></pre>
<p><code>Continuation<U></code> now uses <code>Result</code> class, which seems to be unusable from Java (which makes sense as it is inline class). I was trying to use some subclass of <code>Continuation</code> from coroutines but they are all internal or private.</p>
<p>I know that usually it is <a href="https://stackoverflow.com/questions/52869672/call-kotlin-suspend-function-in-java-class">advised to transform coroutine to <code>CompletableFuture</code></a>, but I'm on Android, which means Java 7 only. Simple <code>Future</code> on the other hand is too dumb as I don't want to check periodically if function is finished - I just want to be called when it is finished. And I would really like to avoid adding new libraries or many additional classes/methods. </p>
<p><strong>Is there any simple way to call suspending function directly from Java 7?</strong> </p>
<p>As Kotlin tries to be very interoperable with Java I would imagine there would be some easy way to do that, but I'm yet to find it.</p>
| 0debug
|
How to remove brackets and the contents inside from a file using python : I have a large file which have contents like
ServiceProfile.SharediFCList[11] where the number increments.
my requirement is to remove the [number] contents from the file and save those to another file.
Please guide me in doing so
Regards
Vishnu
| 0debug
|
cursor.execute('SELECT * FROM users WHERE username = ' + user_input)
| 1threat
|
Replacing golang error codes with panic for all error handeling : We have medium size application written in go. From all the code lines about 60 percent goes to code error handling. Something like this:
if err != nil {
return err
}
After some time, writing this lines over and over again becomes tiresome and we are now thinking to replace all error codes with panics.
I know panics aren't meant to be used like that.
What can be potential pitfall and does anyone have experience with something similar ?
| 0debug
|
static int process_requests(int sock)
{
int flags;
int size = 0;
int retval = 0;
uint64_t offset;
ProxyHeader header;
int mode, uid, gid;
V9fsString name, value;
struct timespec spec[2];
V9fsString oldpath, path;
struct iovec in_iovec, out_iovec;
in_iovec.iov_base = g_malloc(PROXY_MAX_IO_SZ + PROXY_HDR_SZ);
in_iovec.iov_len = PROXY_MAX_IO_SZ + PROXY_HDR_SZ;
out_iovec.iov_base = g_malloc(PROXY_MAX_IO_SZ + PROXY_HDR_SZ);
out_iovec.iov_len = PROXY_MAX_IO_SZ + PROXY_HDR_SZ;
while (1) {
header.type = 0;
retval = read_request(sock, &in_iovec, &header);
if (retval < 0) {
goto err_out;
}
switch (header.type) {
case T_OPEN:
retval = do_open(&in_iovec);
break;
case T_CREATE:
retval = do_create(&in_iovec);
break;
case T_MKNOD:
case T_MKDIR:
case T_SYMLINK:
retval = do_create_others(header.type, &in_iovec);
break;
case T_LINK:
v9fs_string_init(&path);
v9fs_string_init(&oldpath);
retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ,
"ss", &oldpath, &path);
if (retval > 0) {
retval = link(oldpath.data, path.data);
if (retval < 0) {
retval = -errno;
}
}
v9fs_string_free(&oldpath);
v9fs_string_free(&path);
break;
case T_LSTAT:
case T_STATFS:
retval = do_stat(header.type, &in_iovec, &out_iovec);
break;
case T_READLINK:
retval = do_readlink(&in_iovec, &out_iovec);
break;
case T_CHMOD:
v9fs_string_init(&path);
retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ,
"sd", &path, &mode);
if (retval > 0) {
retval = chmod(path.data, mode);
if (retval < 0) {
retval = -errno;
}
}
v9fs_string_free(&path);
break;
case T_CHOWN:
v9fs_string_init(&path);
retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ, "sdd", &path,
&uid, &gid);
if (retval > 0) {
retval = lchown(path.data, uid, gid);
if (retval < 0) {
retval = -errno;
}
}
v9fs_string_free(&path);
break;
case T_TRUNCATE:
v9fs_string_init(&path);
retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ, "sq",
&path, &offset);
if (retval > 0) {
retval = truncate(path.data, offset);
if (retval < 0) {
retval = -errno;
}
}
v9fs_string_free(&path);
break;
case T_UTIME:
v9fs_string_init(&path);
retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ, "sqqqq", &path,
&spec[0].tv_sec, &spec[0].tv_nsec,
&spec[1].tv_sec, &spec[1].tv_nsec);
if (retval > 0) {
retval = qemu_utimens(path.data, spec);
if (retval < 0) {
retval = -errno;
}
}
v9fs_string_free(&path);
break;
case T_RENAME:
v9fs_string_init(&path);
v9fs_string_init(&oldpath);
retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ,
"ss", &oldpath, &path);
if (retval > 0) {
retval = rename(oldpath.data, path.data);
if (retval < 0) {
retval = -errno;
}
}
v9fs_string_free(&oldpath);
v9fs_string_free(&path);
break;
case T_REMOVE:
v9fs_string_init(&path);
retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ, "s", &path);
if (retval > 0) {
retval = remove(path.data);
if (retval < 0) {
retval = -errno;
}
}
v9fs_string_free(&path);
break;
case T_LGETXATTR:
case T_LLISTXATTR:
retval = do_getxattr(header.type, &in_iovec, &out_iovec);
break;
case T_LSETXATTR:
v9fs_string_init(&path);
v9fs_string_init(&name);
v9fs_string_init(&value);
retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ, "sssdd", &path,
&name, &value, &size, &flags);
if (retval > 0) {
retval = lsetxattr(path.data,
name.data, value.data, size, flags);
if (retval < 0) {
retval = -errno;
}
}
v9fs_string_free(&path);
v9fs_string_free(&name);
v9fs_string_free(&value);
break;
case T_LREMOVEXATTR:
v9fs_string_init(&path);
v9fs_string_init(&name);
retval = proxy_unmarshal(&in_iovec,
PROXY_HDR_SZ, "ss", &path, &name);
if (retval > 0) {
retval = lremovexattr(path.data, name.data);
if (retval < 0) {
retval = -errno;
}
}
v9fs_string_free(&path);
v9fs_string_free(&name);
break;
case T_GETVERSION:
retval = do_getversion(&in_iovec, &out_iovec);
break;
default:
goto err_out;
break;
}
if (process_reply(sock, header.type, &out_iovec, retval) < 0) {
goto err_out;
}
}
err_out:
g_free(in_iovec.iov_base);
g_free(out_iovec.iov_base);
return -1;
}
| 1threat
|
SwsFunc ff_yuv2rgb_get_func_ptr(SwsContext *c)
{
SwsFunc t = NULL;
#if (HAVE_MMX2 || HAVE_MMX) && CONFIG_GPL
t = ff_yuv2rgb_init_mmx(c);
#endif
#if HAVE_VIS
t = ff_yuv2rgb_init_vis(c);
#endif
#if CONFIG_MLIB
t = ff_yuv2rgb_init_mlib(c);
#endif
#if HAVE_ALTIVEC && CONFIG_GPL
if (c->flags & SWS_CPU_CAPS_ALTIVEC)
t = ff_yuv2rgb_init_altivec(c);
#endif
#if ARCH_BFIN
if (c->flags & SWS_CPU_CAPS_BFIN)
t = ff_yuv2rgb_get_func_ptr_bfin(c);
#endif
if (t)
return t;
av_log(c, AV_LOG_WARNING, "No accelerated colorspace conversion found.\n");
switch (c->dstFormat) {
case PIX_FMT_RGB48BE:
case PIX_FMT_RGB48LE: return yuv2rgb_c_48;
case PIX_FMT_ARGB:
case PIX_FMT_ABGR: if (CONFIG_SWSCALE_ALPHA && c->srcFormat == PIX_FMT_YUVA420P) return yuva2argb_c;
case PIX_FMT_RGBA:
case PIX_FMT_BGRA: return (CONFIG_SWSCALE_ALPHA && c->srcFormat == PIX_FMT_YUVA420P) ? yuva2rgba_c : yuv2rgb_c_32;
case PIX_FMT_RGB24: return yuv2rgb_c_24_rgb;
case PIX_FMT_BGR24: return yuv2rgb_c_24_bgr;
case PIX_FMT_RGB565:
case PIX_FMT_BGR565:
case PIX_FMT_RGB555:
case PIX_FMT_BGR555: return yuv2rgb_c_16;
case PIX_FMT_RGB8:
case PIX_FMT_BGR8: return yuv2rgb_c_8_ordered_dither;
case PIX_FMT_RGB4:
case PIX_FMT_BGR4: return yuv2rgb_c_4_ordered_dither;
case PIX_FMT_RGB4_BYTE:
case PIX_FMT_BGR4_BYTE: return yuv2rgb_c_4b_ordered_dither;
case PIX_FMT_MONOBLACK: return yuv2rgb_c_1_ordered_dither;
default:
assert(0);
}
return NULL;
}
| 1threat
|
HTML + CSS only - three equal columns (33%~) with equal heights : <p>I'm having a huge issue and I suppose it may be not "doable", but I thought it would do no harm to ask.</p>
<p>I need three equal columns, with equal heights, but I don't know their heights, so this must be dynamic.</p>
<p>To make it even harder, each of these columns has different background colour.</p>
<p>Ideally the content would be vertically aligned, but that's not necessary.</p>
| 0debug
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.