problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
Shared element transition in RecyclerView : <p>I am trying to use shared element transition on RecyclerView but it doesn't seem to work.</p>
<p>This is a part of my adapter in which I use <code>makeSceneTransitionAnimation()</code> :</p>
<pre><code>public void onBindViewHolder(final BookViewHolder holder, final int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, DetailsActivity.class);
ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation((Activity)context , holder.smallThumbnail, "thumbnailTransition");
context.startActivity(intent, optionsCompat.toBundle());
}
}
}
</code></pre>
| 0debug |
static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
VLC *table, int coeff_index,
int plane,
int eob_run)
{
int i, j = 0;
int token;
int zero_run = 0;
DCTELEM coeff = 0;
int bits_to_get;
int blocks_ended;
int coeff_i = 0;
int num_coeffs = s->num_coded_frags[plane][coeff_index];
int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
int *coded_fragment_list = s->coded_fragment_list[plane];
Vp3Fragment *all_fragments = s->all_fragments;
VLC_TYPE (*vlc_table)[2] = table->table;
if (num_coeffs < 0)
av_log(s->avctx, AV_LOG_ERROR, "Invalid number of coefficents at level %d\n", coeff_index);
if (eob_run > num_coeffs) {
coeff_i = blocks_ended = num_coeffs;
eob_run -= num_coeffs;
} else {
coeff_i = blocks_ended = eob_run;
eob_run = 0;
}
if (blocks_ended)
dct_tokens[j++] = blocks_ended << 2;
while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
token = get_vlc2(gb, vlc_table, 11, 3);
if (token <= 6) {
eob_run = eob_run_base[token];
if (eob_run_get_bits[token])
eob_run += get_bits(gb, eob_run_get_bits[token]);
if (eob_run > num_coeffs - coeff_i) {
dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
blocks_ended += num_coeffs - coeff_i;
eob_run -= num_coeffs - coeff_i;
coeff_i = num_coeffs;
} else {
dct_tokens[j++] = TOKEN_EOB(eob_run);
blocks_ended += eob_run;
coeff_i += eob_run;
eob_run = 0;
}
} else {
bits_to_get = coeff_get_bits[token];
if (bits_to_get)
bits_to_get = get_bits(gb, bits_to_get);
coeff = coeff_tables[token][bits_to_get];
zero_run = zero_run_base[token];
if (zero_run_get_bits[token])
zero_run += get_bits(gb, zero_run_get_bits[token]);
if (zero_run) {
dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
} else {
if (!coeff_index)
all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
dct_tokens[j++] = TOKEN_COEFF(coeff);
}
if (coeff_index + zero_run > 64) {
av_log(s->avctx, AV_LOG_DEBUG, "Invalid zero run of %d with"
" %d coeffs left\n", zero_run, 64-coeff_index);
zero_run = 64 - coeff_index;
}
for (i = coeff_index+1; i <= coeff_index+zero_run; i++)
s->num_coded_frags[plane][i]--;
coeff_i++;
}
}
if (blocks_ended > s->num_coded_frags[plane][coeff_index])
av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
if (blocks_ended)
for (i = coeff_index+1; i < 64; i++)
s->num_coded_frags[plane][i] -= blocks_ended;
if (plane < 2)
s->dct_tokens[plane+1][coeff_index] = dct_tokens + j;
else if (coeff_index < 63)
s->dct_tokens[0][coeff_index+1] = dct_tokens + j;
return eob_run;
}
| 1threat |
now() or date(y-m-d) doesn't work when trying to query using php and sql to a mysql database : I'm trying to check to see if one date (in my database) is larger (later) then the current date. I've looked on other questions for a solution but none of them seem to work.
$sql = "SELECT * FROM customer_details, rental_details WHERE customer_details.customer_ID = rental_details.customer_ID AND rental_details.date_return >= date('y-m-d')";
Ive also tried
$sql = "SELECT * FROM customer_details, rental_details WHERE customer_details.customer_ID = rental_details.customer_ID AND rental_details.date_return >= now()";
Ive tried every combination of parentheses and brackets with these two, nothing seems to work.
Any suggestions?
This is not a duplicate question, I've looked all over stack overflow. | 0debug |
What's the proper way to have various URL endpoints for dev and release in a Java application? : <p>I'm building a Java desktop application, using JavaFX, Gradle, javafx-gradle-plugin. This application connects to a server that I also build. When I compile a release version, running <code>gradle jfxNative</code>, I want it to talk to the production server; but otherwise, I want it to talk to localhost.</p>
<p>What's the proper Java/Gradle way of handling this? Some sort of compilation profile?</p>
| 0debug |
Fill an int array with an txt java : Hi i want to fill and array with values from a txt file but i got the error java.util.NoSuchElementException: No line found when running the program, this is my code.
private static void leeArchivo()
{
Scanner s = new Scanner(System.in);
//Size of the array
int size = Integer.parseInt(s.nextLine());
datos = new int[size];
while (s.hasNextLine()) {
for (int i = 0; i < size; i++) {
//fill array with values
datos[i] = Integer.parseInt(s.nextLine());
}
}
}
the txt would look like this, first element size of the array
4
75
62
32
55 | 0debug |
How to check that in which textfield cursor is present in java? : How we will find that the cursor is now in that text field?
I have two text fields in Java.I want to write text in text field but before writing text i want to check that which text field is selected.How can i check it please help me. | 0debug |
Why i keep getting BSOD & CSGO not responding when using my glow hack : Yeah you read that.
BSOD crash code : "MEMORY_MANAGEMENT"
at random time and if im lucky only my csgo is crash and i dont get BSOD.
Here is my code
void Glow::Run()
{
ReadInfo();
for (int i = 0; i < 200; i++) // current glowcount and max glowcount have been removed? thats why i just put 200
{
ReadEntity(i);
GlowEntitys(i);
}
}
void Glow::ReadInfo(){
ReadProcessMemory(fProcess.__HandleProcess, (PBYTE*)(fProcess.__dwordClient + O.m_dwLocalPlayer), &LocalPlayer, sizeof(int), NULL); // Gets LocalPlayer
ReadProcessMemory(fProcess.__HandleProcess, (PBYTE*)(fProcess.__dwordClient + O.m_dwGlowObject), &GlowObject, sizeof(int), NULL); // Gets GlowObject
ReadProcessMemory(fProcess.__HandleProcess, (PBYTE*)(LocalPlayer + O.m_iTeamNum), &LocalTeam, sizeof(int), NULL);} // Gets My team from LocalPlayer
void Glow::ReadEntity(int Entnum){ // Reads our Entity information
ReadProcessMemory(fProcess.__HandleProcess, (PBYTE*)(GlowObject + 0x38 * Entnum), &Entity, sizeof(int), NULL); // First Adress in Glowobject is the Pointer to the entity its glowing.
ReadProcessMemory(fProcess.__HandleProcess, (PBYTE*)(Entity + 0x8), &ClassID, sizeof(int), NULL); // Multilevel Pointer Reading ClassID
ReadProcessMemory(fProcess.__HandleProcess, (PBYTE*)(ClassID + 0x8), &ClassID, sizeof(int), NULL);
ReadProcessMemory(fProcess.__HandleProcess, (PBYTE*)(ClassID + 0x1), &ClassID, sizeof(int), NULL);
ReadProcessMemory(fProcess.__HandleProcess, (PBYTE*)(ClassID + 0x14), &ClassID, sizeof(int), NULL);
ReadProcessMemory(fProcess.__HandleProcess, (PBYTE*)(Entity + O.m_iTeamNum), &TeamNum, sizeof(int), NULL);// Getting the entitys Team Number
ReadProcessMemory(fProcess.__HandleProcess, (PBYTE*)(Entity + O.m_iHealth), &Health, sizeof(int), NULL); } // Getting the entitys Team Number
void Glow::GlowEntity(int Entnum){ // Glows our entity
if (Entity && LocalPlayer)
WriteProcessMemory(fProcess.__HandleProcess, (PBYTE*)(GlowObject + 0x38 * Entnum + 0x4), &EntGlow, sizeof(EntGlow), NULL);} // Writes a struct with WPM
Can someone fix this please? | 0debug |
How to plot a function $f:D\subset\mathbb{R^2}\to\mathbb{R}$? : I'm new to Matlab and I have a function $f(x,\,y)=\sqrt{x^2+y^2}$ and $D=\{(x,\,y)\in\mathbb{R^2}:1\leq{x^2+y^2}\}$. | 0debug |
uint64_t helper_fmadd(CPUPPCState *env, uint64_t arg1, uint64_t arg2,
uint64_t arg3)
{
CPU_DoubleU farg1, farg2, farg3;
farg1.ll = arg1;
farg2.ll = arg2;
farg3.ll = arg3;
if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
(float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {
farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXIMZ);
} else {
if (unlikely(float64_is_signaling_nan(farg1.d) ||
float64_is_signaling_nan(farg2.d) ||
float64_is_signaling_nan(farg3.d))) {
fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
}
float128 ft0_128, ft1_128;
ft0_128 = float64_to_float128(farg1.d, &env->fp_status);
ft1_128 = float64_to_float128(farg2.d, &env->fp_status);
ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);
if (unlikely(float128_is_infinity(ft0_128) &&
float64_is_infinity(farg3.d) &&
float128_is_neg(ft0_128) != float64_is_neg(farg3.d))) {
farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXISI);
} else {
ft1_128 = float64_to_float128(farg3.d, &env->fp_status);
ft0_128 = float128_add(ft0_128, ft1_128, &env->fp_status);
farg1.d = float128_to_float64(ft0_128, &env->fp_status);
}
}
return farg1.ll;
}
| 1threat |
APNs push notification with macOS Sierra : <p>I'm trying to send my phone a push notification using the simple PHP tool which connects to <code>ssl://gateway.push.apple.com:2195</code>, but the connection fails with the following errors:</p>
<pre><code>Warning: stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in <Users/.../file.php> on line 30
Warning: stream_socket_client(): Failed to enable crypto in <Users/.../file.php> on line 30
Warning: stream_socket_client(): unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Unknown error) in <Users/.../file.php> on line 30
Failed to connect: 0
</code></pre>
<p>This all started since I upgraded to the GM Seed of macOS Sierra.
What's new in macOS Sierra that affects SSL connections?
How do I resolve this?</p>
| 0debug |
C# Method overload resolution not selecting concrete generic override : <p>This complete C# program illustrates the issue:</p>
<pre><code>public abstract class Executor<T>
{
public abstract void Execute(T item);
}
class StringExecutor : Executor<string>
{
public void Execute(object item)
{
// why does this method call back into itself instead of binding
// to the more specific "string" overload.
this.Execute((string)item);
}
public override void Execute(string item) { }
}
class Program
{
static void Main(string[] args)
{
object item = "value";
new StringExecutor()
// stack overflow
.Execute(item);
}
}
</code></pre>
<p>I ran into a StackOverlowException that I traced back to this call pattern where I was trying to forward calls to a more specific overload. To my surprise, the invocation was not selecting the more specific overload however, but calling back into itself. It clearly has something to do with the base type being generic, but I don't understand why it wouldn't select the Execute(string) overload.</p>
<p>Does anyone have any insight into this?</p>
<p><em>The above code was simplified to show the pattern, the actual structure is a bit more complicated, but the issue is the same.</em></p>
| 0debug |
static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
BlockCompletionFunc *cb, void *opaque)
{
return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
cb, opaque, QEMU_AIO_WRITE);
}
| 1threat |
R: If function, if value in vector > 0, then replace with number : I try to performe the Cowles-Jones-Test in R.
Basically, I don't know how to write a script, in which I can check, if a value within my vector is bigger than zero or not (for every single value in this vector). If it's bigger than zero, it should replace this number with an one, if not, than a zero.
Couldn't find anything so far and would appreciate some help | 0debug |
scala replace if else with state pattern : here is my if statement code in scala:
def handle(): Unit = {
if (calculator.num == 0.0){
calculator.num = number
}
else{
calculator.num = calculator.num * 10 + number
}
}
How do I replace the if else with state pattern? | 0debug |
static void ini_print_object_header(const char *name)
{
int i;
PrintElement *el = octx.prefix + octx.level -1;
if (el->nb_elems)
avio_printf(probe_out, "\n");
avio_printf(probe_out, "[");
for (i = 1; i < octx.level; i++) {
el = octx.prefix + i;
avio_printf(probe_out, "%s.", el->name);
if (el->index >= 0)
avio_printf(probe_out, "%"PRId64".", el->index);
}
avio_printf(probe_out, "%s", name);
if (el && el->type == ARRAY)
avio_printf(probe_out, ".%"PRId64"", el->nb_elems);
avio_printf(probe_out, "]\n");
}
| 1threat |
custom inputAccessoryView as UIView from nib giving error: returned 0 width, assuming UIViewNoIntrinsicMetric : <p>I am using an inputAccessoryView which is loaded from a nib using the following UIView subclass:</p>
<pre><code>class CustomInputAccessoryView: UIView {
@IBOutlet var containerView: UIView!
@IBOutlet var contentView: UIView!
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var textView: UITextView!
override var intrinsicContentSize: CGSize {
return CGSize.zero
}
override init(frame: CGRect) {
super.init(frame: frame)
setupInputAccessoryView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupInputAccessoryView()
}
func setupInputAccessoryView() {
self.translatesAutoresizingMaskIntoConstraints = false
Bundle.main.loadNibNamed("CustomInputAccessoryView", owner: self, options: nil)
addSubview(containerView)
containerView.frame = self.bounds
}
}
</code></pre>
<p>I assign the view to the inputAccessoryView and set it up just by the following:</p>
<pre><code>var customInputAccessoryView = CustomInputAccessoryView()
</code></pre>
<p>The inputAccessoryView loads properly and displays correctly. The problem is when I press inside the textView of the inputAccessoryView and the keyboard displays, I get the following error:</p>
<pre><code><_UIKBCompatInputView: ...; frame = (0 0; 0 0); layer = <CALayer: ...>> returned 0 width, assuming UIViewNoIntrinsicMetric
</code></pre>
<p>I have two files, a .swift file which is the subclass of UIView displayed above and the nib file by the same name. In the file owner of the nib I select the sub class (CustomInputAccessoryView) and wire up the outlets.</p>
<p>I don't really know what is happening other than maybe the input accessory view automatically resizing to zero frame whenever the keyboard is displayed before going to the correct size. If so I'm assuming I need to change some AutoLayout priorities but what I have tried is not working. The only hard width constraints are the buttons which have fixed widths.</p>
<p>The inputAccessoryView width should always be the width of the window it is displayed in.</p>
| 0debug |
static int libx265_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
const AVFrame *pic, int *got_packet)
{
libx265Context *ctx = avctx->priv_data;
x265_picture x265pic;
x265_picture x265pic_out = { { 0 } };
x265_nal *nal;
uint8_t *dst;
int payload = 0;
int nnal;
int ret;
int i;
if (pic) {
for (i = 0; i < 3; i++) {
x265pic.planes[i] = pic->data[i];
x265pic.stride[i] = pic->linesize[i];
}
x265pic.pts = pic->pts;
}
ret = x265_encoder_encode(ctx->encoder, &nal, &nnal,
pic ? &x265pic : NULL, &x265pic_out);
if (ret < 0)
return AVERROR_UNKNOWN;
if (!nnal)
return 0;
for (i = 0; i < nnal; i++)
payload += nal[i].sizeBytes;
payload += ctx->header_size;
ret = ff_alloc_packet(pkt, payload);
if (ret < 0) {
av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
return ret;
}
dst = pkt->data;
if (ctx->header) {
memcpy(dst, ctx->header, ctx->header_size);
dst += ctx->header_size;
av_freep(&ctx->header);
ctx->header_size = 0;
}
for (i = 0; i < nnal; i++) {
memcpy(dst, nal[i].payload, nal[i].sizeBytes);
dst += nal[i].sizeBytes;
if (is_keyframe(nal[i].type))
pkt->flags |= AV_PKT_FLAG_KEY;
}
pkt->pts = x265pic_out.pts;
pkt->dts = x265pic_out.dts;
*got_packet = 1;
return 0;
} | 1threat |
static uint64_t unassigned_mem_read(void *opaque, target_phys_addr_t addr,
unsigned size)
{
#ifdef DEBUG_UNASSIGNED
printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);
#endif
#if defined(TARGET_ALPHA) || defined(TARGET_SPARC) || defined(TARGET_MICROBLAZE)
cpu_unassigned_access(cpu_single_env, addr, 0, 0, 0, size);
#endif
return 0;
}
| 1threat |
Convert character to date vector (!bY) in R : <p>I am trying to convert a character vector of dates (in the format: i.e. "Jan.1990") to a date vector (keeping a similar format: i.e. "Jan 1990" or "Jan.1990"). </p>
<pre><code>month_year <- ("Jan.1990", "Feb.1990", "Mar.1990", "Jan.1991", "Feb.1991", Mar. 1991")
</code></pre>
<p>I have tried using as.Date and various commands with the lubridate package but I either end up with an incorrect format or NAs. </p>
<p>I tried using as.Date:</p>
<pre><code>df$month_year <- as.Date(df$month_year,format = "%b%Y")
</code></pre>
<p>This resulted in NAs.</p>
<p>I tried lubridate::parse_date_time2</p>
<pre><code>parse_date_time2(tidy_labor$month_year, c("Jan.1990"), exact = TRUE, orders = "bY")
</code></pre>
<p>But the format came out as:</p>
<pre><code>unknown timezone 'Jan.1990'unknown timezone 'Jan.1990' [1] "1990-01-01 GMT" "1990-01-01 GMT" "1990-01-01 GMT" "1990-01-01 GMT" "1990-02-01 GMT" "1990-02-01 GMT" "1990-02-01 GMT"
</code></pre>
<p>Any help would be much appreciated.</p>
| 0debug |
syntax error, unexpected end-of-input : <pre><code> class PinsController < ApplicationController
before_action :set_pin, only: [:show, :edit, :update, :destroy]
def index
@pins = Pin.all
end
def show
end
def new
@pin = Pin.new
end
def edit
end
def create
@pin = Pin.new(pin_params)
respond_to do |format|
if @pin.save
redirect_to @pin, notice: 'Pin was successfully created.' }
else
render action: 'new'
end
end
def update
if @pin.update(pin_params)
redirect_to @pin, notice: 'Pin was successfully updated.'
else
render action: 'edit'
end
end
def destroy
@pin.destroy
redirect_to pins_url
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pin
@pin = Pin.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def pin_params
params.require(:pin).permit(:description)
end
end
</code></pre>
<p>I know I am missing OR need to add a couple of 'ends'. However, I am just not sure where. Thank you :) I would really appreciate someone helping me to see where I have gone wrong. I am fairly new to ruby on rails.</p>
| 0debug |
The datetimepicker doesnot properly filter datagridview data : Hey Guys I have faced the bug that cause the filter work improperly, that is, when I change the value in datetimepicker then datagridview gets empty. Please help!!!
The code that I use is
> private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
> {
> dataGridView1.DataSource = db.Expenses.Where(x => x.Period == dateTimePicker1.Value).ToList();
> } | 0debug |
how to copy an active excel sheet and save it into a new workbook using vbs script : Im trying to copy an excel sheet that includes formulas and paste it into a new excel workbook as values and retaining the format using vbs script.
Im currently doing it but instead of copying i'm saving it as a CSV. so is only saving the first page but it looses the format. | 0debug |
How to loop through properties of JavaScript Object : <p>I have an object such that, I want to make the Months false, on/before current month.</p>
<p>Before:</p>
<pre><code>var oObj = {
"isJan" : true,
"isFeb" : true,
"isMar" : true,
"isApr" : true,
"isMay" : true,
"isJun" : true,
"isJul" : true,
"isAug" : true,
"isSep" : true,
"isOct" : true,
"isNov" : true,
"isDec" : true
}
</code></pre>
<p>Today is 5-Apr, hence object should be:</p>
<pre><code> {
"isJan" : false,
"isFeb" : false,
"isMar" : false,
"isApr" : false,
"isMay" : true,
"isJun" : true,
"isJul" : true,
"isAug" : true,
"isSep" : true,
"isOct" : true,
"isNov" : true,
"isDec" : true
}
</code></pre>
| 0debug |
Physical Pixels vs CSS Pixels vs Device Independent Pixels vs Density Independent Pixels vs PPI : <p>I am learning web development and I am having a hard time determining what is equivalent in all of this. </p>
<p>I know hardware pixels and physical pixels are the smallest unit, and that density independent pixels map to actual hardware pixels via a device pixel ratio and they are used to make the viewing experience more consistent. Does this mean that the device independent pixels I'm seeing are the same thing?</p>
<p>Further, I read that the browser reports viewport width in CSS pixels, are these and DIPs the same thing? </p>
<p>I know that Pixels per inch are literal, they are the number of pixels in an inch, but how do they relate to DIPs? A totally separate measurement? When should I use that instead? </p>
<p>I hope this is an appropriate question, I am having issues mentally linking all of these concepts into one usable map, and didn't find any other question where they are all addressed at once. </p>
| 0debug |
static int expand_zero_clusters_in_l1(BlockDriverState *bs, uint64_t *l1_table,
int l1_size, int64_t *visited_l1_entries,
int64_t l1_entries,
BlockDriverAmendStatusCB *status_cb)
{
BDRVQcowState *s = bs->opaque;
bool is_active_l1 = (l1_table == s->l1_table);
uint64_t *l2_table = NULL;
int ret;
int i, j;
if (!is_active_l1) {
l2_table = qemu_try_blockalign(bs->file, s->cluster_size);
if (l2_table == NULL) {
return -ENOMEM;
}
}
for (i = 0; i < l1_size; i++) {
uint64_t l2_offset = l1_table[i] & L1E_OFFSET_MASK;
bool l2_dirty = false;
uint64_t l2_refcount;
if (!l2_offset) {
(*visited_l1_entries)++;
if (status_cb) {
status_cb(bs, *visited_l1_entries, l1_entries);
}
continue;
}
if (offset_into_cluster(s, l2_offset)) {
qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#"
PRIx64 " unaligned (L1 index: %#x)",
l2_offset, i);
ret = -EIO;
goto fail;
}
if (is_active_l1) {
ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset,
(void **)&l2_table);
} else {
ret = bdrv_read(bs->file, l2_offset / BDRV_SECTOR_SIZE,
(void *)l2_table, s->cluster_sectors);
}
if (ret < 0) {
goto fail;
}
ret = qcow2_get_refcount(bs, l2_offset >> s->cluster_bits,
&l2_refcount);
if (ret < 0) {
goto fail;
}
for (j = 0; j < s->l2_size; j++) {
uint64_t l2_entry = be64_to_cpu(l2_table[j]);
int64_t offset = l2_entry & L2E_OFFSET_MASK;
int cluster_type = qcow2_get_cluster_type(l2_entry);
bool preallocated = offset != 0;
if (cluster_type != QCOW2_CLUSTER_ZERO) {
continue;
}
if (!preallocated) {
if (!bs->backing_hd) {
l2_table[j] = 0;
l2_dirty = true;
continue;
}
offset = qcow2_alloc_clusters(bs, s->cluster_size);
if (offset < 0) {
ret = offset;
goto fail;
}
if (l2_refcount > 1) {
ret = qcow2_update_cluster_refcount(bs,
offset >> s->cluster_bits,
refcount_diff(1, l2_refcount), false,
QCOW2_DISCARD_OTHER);
if (ret < 0) {
qcow2_free_clusters(bs, offset, s->cluster_size,
QCOW2_DISCARD_OTHER);
goto fail;
}
}
}
if (offset_into_cluster(s, offset)) {
qcow2_signal_corruption(bs, true, -1, -1, "Data cluster offset "
"%#" PRIx64 " unaligned (L2 offset: %#"
PRIx64 ", L2 index: %#x)", offset,
l2_offset, j);
if (!preallocated) {
qcow2_free_clusters(bs, offset, s->cluster_size,
QCOW2_DISCARD_ALWAYS);
}
ret = -EIO;
goto fail;
}
ret = qcow2_pre_write_overlap_check(bs, 0, offset, s->cluster_size);
if (ret < 0) {
if (!preallocated) {
qcow2_free_clusters(bs, offset, s->cluster_size,
QCOW2_DISCARD_ALWAYS);
}
goto fail;
}
ret = bdrv_write_zeroes(bs->file, offset / BDRV_SECTOR_SIZE,
s->cluster_sectors, 0);
if (ret < 0) {
if (!preallocated) {
qcow2_free_clusters(bs, offset, s->cluster_size,
QCOW2_DISCARD_ALWAYS);
}
goto fail;
}
if (l2_refcount == 1) {
l2_table[j] = cpu_to_be64(offset | QCOW_OFLAG_COPIED);
} else {
l2_table[j] = cpu_to_be64(offset);
}
l2_dirty = true;
}
if (is_active_l1) {
if (l2_dirty) {
qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
qcow2_cache_depends_on_flush(s->l2_table_cache);
}
ret = qcow2_cache_put(bs, s->l2_table_cache, (void **)&l2_table);
if (ret < 0) {
l2_table = NULL;
goto fail;
}
} else {
if (l2_dirty) {
ret = qcow2_pre_write_overlap_check(bs,
QCOW2_OL_INACTIVE_L2 | QCOW2_OL_ACTIVE_L2, l2_offset,
s->cluster_size);
if (ret < 0) {
goto fail;
}
ret = bdrv_write(bs->file, l2_offset / BDRV_SECTOR_SIZE,
(void *)l2_table, s->cluster_sectors);
if (ret < 0) {
goto fail;
}
}
}
(*visited_l1_entries)++;
if (status_cb) {
status_cb(bs, *visited_l1_entries, l1_entries);
}
}
ret = 0;
fail:
if (l2_table) {
if (!is_active_l1) {
qemu_vfree(l2_table);
} else {
if (ret < 0) {
qcow2_cache_put(bs, s->l2_table_cache, (void **)&l2_table);
} else {
ret = qcow2_cache_put(bs, s->l2_table_cache,
(void **)&l2_table);
}
}
}
return ret;
}
| 1threat |
What is the best way to implement roles and permission in Express REST Api : <p>I need kind of expert opinion to implement Roles and Permission in Express js. I'm planning to develop Restful Api using Express js but didn't get sufficient information to implement Roles and Permission although there are tons of option are available for authentication and authorization. </p>
| 0debug |
static int gif_read_packet(AVFormatContext * s1,
AVPacket * pkt)
{
GifState *s = s1->priv_data;
int ret;
ret = gif_parse_next_image(s);
if (ret < 0)
return ret;
if (av_new_packet(pkt, s->screen_width * s->screen_height * 3)) {
return AVERROR(EIO);
}
pkt->stream_index = 0;
memcpy(pkt->data, s->image_buf, s->screen_width * s->screen_height * 3);
return 0;
}
| 1threat |
I need to ask again. this time with more details : This is a Firebird database.
First Table
Contacts
Company_ID - job_title
Second Table
Client_id - Co_name
In contacts, I want to the job_title field to contain the co_name.
client_id and company_id are the same.
Co_name correspond to company_id as well as client_id.
this:
UPDATE Contacts
SET Contacts.Job_title = Clients.co_name
where company_id in
(select client_id from clients
JOIN Contacts c ON Client_id=company_id
where record_status='A')
gives me an error as cannot find (clients.co_name)
this other option:
UPDATE Contacts
JOIN Clients ON Clients.Client_id = Contacts.Client_id
SET Contacts.Job_title = Clients.Client_name
gives me an error on JOIN
Any other ideas please?
Thank you all | 0debug |
db.execute('SELECT * FROM products WHERE product_id = ' + product_input) | 1threat |
static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
{
int i, x;
if (s->buf_end - s->buf < 1)
return AVERROR(EINVAL);
x = bytestream_get_byte(&s->buf);
q->nguardbits = x >> 5;
q->quantsty = x & 0x1f;
if (q->quantsty == JPEG2000_QSTY_NONE) {
n -= 3;
if (s->buf_end - s->buf < n || 32*3 < n)
return AVERROR(EINVAL);
for (i = 0; i < n; i++)
q->expn[i] = bytestream_get_byte(&s->buf) >> 3;
} else if (q->quantsty == JPEG2000_QSTY_SI) {
if (s->buf_end - s->buf < 2)
return AVERROR(EINVAL);
x = bytestream_get_be16(&s->buf);
q->expn[0] = x >> 11;
q->mant[0] = x & 0x7ff;
for (i = 1; i < 32 * 3; i++) {
int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
q->expn[i] = curexpn;
q->mant[i] = q->mant[0];
}
} else {
n = (n - 3) >> 1;
if (s->buf_end - s->buf < 2 * n || 32*3 < n)
return AVERROR(EINVAL);
for (i = 0; i < n; i++) {
x = bytestream_get_be16(&s->buf);
q->expn[i] = x >> 11;
q->mant[i] = x & 0x7ff;
}
}
return 0;
}
| 1threat |
How would I find the user-agent from the http requests which were made to my website : <p>So a bit of a two part question </p>
<ol>
<li><p>When users make requests to our website where is the information from our http request header stored </p></li>
<li><p>Can you access the user-agent from this (for example googlebot)[Would this be done with a serverside language like ruby/php?]</p></li>
</ol>
| 0debug |
sorecvfrom(struct socket *so)
{
struct sockaddr_storage addr;
socklen_t addrlen = sizeof(struct sockaddr_storage);
DEBUG_CALL("sorecvfrom");
DEBUG_ARG("so = %p", so);
if (so->so_type == IPPROTO_ICMP) {
char buff[256];
int len;
len = recvfrom(so->s, buff, 256, 0,
(struct sockaddr *)&addr, &addrlen);
if(len == -1 || len == 0) {
u_char code=ICMP_UNREACH_PORT;
if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;
else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;
DEBUG_MISC((dfd," udp icmp rx errno = %d-%s\n",
errno,strerror(errno)));
icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));
} else {
icmp_reflect(so->so_m);
so->so_m = NULL;
}
udp_detach(so);
} else {
struct mbuf *m;
int len;
#ifdef _WIN32
unsigned long n;
#else
int n;
#endif
m = m_get(so->slirp);
if (!m) {
return;
}
m->m_data += IF_MAXLINKHDR;
len = M_FREEROOM(m);
ioctlsocket(so->s, FIONREAD, &n);
if (n > len) {
n = (m->m_data - m->m_dat) + m->m_len + n + 1;
m_inc(m, n);
len = M_FREEROOM(m);
}
m->m_len = recvfrom(so->s, m->m_data, len, 0,
(struct sockaddr *)&addr, &addrlen);
DEBUG_MISC((dfd, " did recvfrom %d, errno = %d-%s\n",
m->m_len, errno,strerror(errno)));
if(m->m_len<0) {
u_char code=ICMP_UNREACH_PORT;
if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;
else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;
DEBUG_MISC((dfd," rx error, tx icmp ICMP_UNREACH:%i\n", code));
icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));
m_free(m);
} else {
if (so->so_expire) {
if (so->so_fport == htons(53))
so->so_expire = curtime + SO_EXPIREFAST;
else
so->so_expire = curtime + SO_EXPIRE;
}
switch (so->so_ffamily) {
case AF_INET:
udp_output(so, m, (struct sockaddr_in *) &addr);
break;
default:
break;
}
}
}
}
| 1threat |
Primefaces ^ bar encode : java.lang.NullPointerException
at org.primefaces.component.chart.ChartRenderer.encodeScript(ChartRenderer.java:95)
at org.primefaces.component.chart.ChartRenderer.encodeEnd(ChartRenderer.java:68)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:312) | 0debug |
How to get average of column values in laravel : <p>Lets say I have this column</p>
<pre><code>star
----
1
3
3
1
2
5
3
</code></pre>
<p>It has seven rows and there are integer values! I want to have it added and divided by the rows there are.</p>
<p>How do I do it in laravel. I can do it in plain php but I want to learn it in laravel.</p>
| 0debug |
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
{
if (d->term_got_escape) {
d->term_got_escape = 0;
if (ch == term_escape_char)
goto send_char;
switch(ch) {
case '?':
case 'h':
mux_print_help(chr);
break;
case 'x':
{
const char *term = "QEMU: Terminated\n\r";
qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
exit(0);
break;
}
case 's':
blk_commit_all();
break;
case 'b':
qemu_chr_be_event(chr, CHR_EVENT_BREAK);
break;
case 'c':
mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
d->focus++;
if (d->focus >= d->mux_cnt)
d->focus = 0;
mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
break;
case 't':
d->timestamps = !d->timestamps;
d->timestamps_start = -1;
d->linestart = 0;
break;
}
} else if (ch == term_escape_char) {
d->term_got_escape = 1;
} else {
send_char:
return 1;
}
return 0;
}
| 1threat |
connection.query('SELECT * FROM users WHERE username = ' + input_string) | 1threat |
I keep getting errors for my restaurant code? (python) : So basically idk I just feel like my code is not really getting anywhere. I have trouble with the list and stuff, and I need this for school. My teacher doesn't really teach, and this is what they 'taught' us so far about list arrays, but I don't really understand it. Also, I keep getting this error of:
TypeError: append() takes exactly 2 arguments (1 given) on line 31
So basically? Just fix my entire code.
So my menu is alright, the printing turns out ok. I took out my whole menu here and just pasted where my problem occurs. Here's the part that actually works though:
```
print "[Welcome to Python Cafe!]"
print ('\n')
print "1) Menu and Order"
print "2) Exit"
choice=input("What would you like to do? ")
print ('\n')
if choice == "1":
print "-T H E M E N U-"
print " DRINKS "
print "1. Coffee: $2.50"
print "2. Hot Cocoa: $2.30"
print "3. Tea: $1.50"
print " FOOD "
print "4. Bagel: $1.50"
print "5. Donut: $1.00"
print "6. Muffin: $1.50"
```
The main problem is in the while statements and if statements, and how it
doesn't print my order in the end. I already tried changing like for example: if order == "coffee": to instead if order == "1": so I could make it easier so user doesn't have to type out the whole word? And also I tried taking out the tot=tot+... just to see. I have no idea, my teacher just told us to do that, but I don't think this format is quite right.
```
if choice == "1":
print ('\n')
food=[]
order=0
while order != "done":
order=input("What's your order? ")
if order == "coffee":
list.append("coffee")
tot=tot+2.50
else:
if order == "hot cocoa":
list.append("hotcocoa")
tot=tot+2.30
if order == "tea":
list.append("tea")
tot=tot+1.50
if order == "bagel":
list.append("bagel")
tot=tot+1.50
if order == "donut":
list.append("donut")
tot=tot+1.00
if order == "muffin":
list.append("muffin")
tot=tot+1.50
print ('\n')
print "Here's your final order:"
for item in food:
print(order)
```
And when the append() error doesn't appear, and the code actually 'works' when I change it back, it just ends there after 'done' and doesn't print anything after. I'm sorry if this seems really confusing, I just think this whole code is a mess.
pls send help. | 0debug |
Regex "is not a constant" error in Golang : <p>I'm trying to write a regex in Golang to verify that a string only has alphanumerics, periods, and underscores. However, I'm running into an error that I haven't seen before and have been unsuccessful at Googling.</p>
<p>Here's the regex:</p>
<pre><code>pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)
</code></pre>
<p>Here is the error:</p>
<pre><code>const initializer regexp.MustCompile("^[A-Za-z0-9_\\.]+") is not a constant
</code></pre>
<p>What does "not a constant" mean and how do I fix this?<br>
Thanks.</p>
| 0debug |
WebView vs Chrome Custom Tab : <p>I am building an app where in a Detail Activity I have to show a web page.
I was going to use WebView, but then I saw Chrome Custom Tab.</p>
<p>What do you guys think it's better to implement and why?</p>
| 0debug |
static int decode_frame_mp3on4(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
AVFrame *frame = data;
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
MP3On4DecodeContext *s = avctx->priv_data;
MPADecodeContext *m;
int fsize, len = buf_size, out_size = 0;
uint32_t header;
OUT_INT **out_samples;
OUT_INT *outptr[2];
int fr, ch, ret;
frame->nb_samples = MPA_FRAME_SIZE;
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
return ret;
}
out_samples = (OUT_INT **)frame->extended_data;
if (buf_size < HEADER_SIZE)
return AVERROR_INVALIDDATA;
avctx->bit_rate = 0;
ch = 0;
for (fr = 0; fr < s->frames; fr++) {
fsize = AV_RB16(buf) >> 4;
fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
m = s->mp3decctx[fr];
assert(m != NULL);
if (fsize < HEADER_SIZE) {
av_log(avctx, AV_LOG_ERROR, "Frame size smaller than header size\n");
return AVERROR_INVALIDDATA;
}
header = (AV_RB32(buf) & 0x000fffff) | s->syncword;
if (ff_mpa_check_header(header) < 0)
break;
avpriv_mpegaudio_decode_header((MPADecodeHeader *)m, header);
if (ch + m->nb_channels > avctx->channels ||
s->coff[fr] + m->nb_channels > avctx->channels) {
av_log(avctx, AV_LOG_ERROR, "frame channel count exceeds codec "
"channel count\n");
return AVERROR_INVALIDDATA;
}
ch += m->nb_channels;
outptr[0] = out_samples[s->coff[fr]];
if (m->nb_channels > 1)
outptr[1] = out_samples[s->coff[fr] + 1];
if ((ret = mp_decode_frame(m, outptr, buf, fsize)) < 0)
return ret;
out_size += ret;
buf += fsize;
len -= fsize;
avctx->bit_rate += m->bit_rate;
}
avctx->sample_rate = s->mp3decctx[0]->sample_rate;
frame->nb_samples = out_size / (avctx->channels * sizeof(OUT_INT));
*got_frame_ptr = 1;
return buf_size;
}
| 1threat |
What list functions are true functions in python? : <p>By 'true function' I mean a function that cannot be recreated with ordinary python logic. For example the append function could simply be done by creating a list one larger (through lens if you dont define that as a function) than that of the original, and then transfering the contents plus that one from a user input.</p>
| 0debug |
How update a SwiftUI List without animation : <p>I want to update a SwiftUI List without any insert animation.
My <code>List</code> is getting its data from an <code>@EnvironmentObject</code>
I already tried to wrap the <code>List</code> itself and the <code>PassthroughSubject.send()</code> in a <code>withAnimation(.empty)</code> block but this does not help.</p>
<p>A very very dirty workaround is to call <code>UIView.setAnimationsEnabled(false)</code> (yes, UIKit has impact on SwiftUI), but there must be a SwiftUI-like way to set custom insert animations.</p>
| 0debug |
How to customize data took from web into excel : How to customize data taken from web into excel
Example Data taken from Web getting displayed as below when paste into excel/word:
1
John
Florida
2
Harish
Los Angeles
3
Kiran
Newyork
4
Gautam
Washington
The expected tabular format as:
Sl.No Name City
1 John Florida
2 Harish Los Angeles
3 Kiran NewYork
4 Gautam Washington
I tried with Text to columns or delimited etc but not getting as expected output. | 0debug |
static uint32_t vbe_ioport_read_index(void *opaque, uint32_t addr)
{
VGACommonState *s = opaque;
uint32_t val;
val = s->vbe_index;
return val;
}
| 1threat |
How to halt form submission until user agreement is accepted? : On many websites I saw such approach:
You fill a registration form.
And press submit button.
Then you see a modal with user agreement (or smth similiar), which you have to accept to continue.
Browsing through SO and google search I've found nothing looking like a solution and hardly like a clue... I would appreciate your help! | 0debug |
How to get the text of the selected option using vuejs? : <p>I want to get the text of a selected option input and display it somewhere else. I know how to do it using jQuery but I want to know how can we do it using Vuejs.</p>
<p>Here is how we do in jQuery. I mean the text of Selected Option not the value.</p>
<pre><code>var mytext = $("#customerName option:selected").text();
</code></pre>
<p>Here is my HTML</p>
<pre><code> <select name="customerName" id="">
<option value="1">Jan</option>
<option value="2">Doe</option>
<option value="3">Khan</option>
</select>
{{customerName}}
</code></pre>
<p>Now how can I display the selected option under it. like Jan, Doe, Khan ?</p>
| 0debug |
How to avoid memory leak : Question on memory leak. Probably a basic one.
C++ Pseudo code:
map map_a;
for ( 1 to 10 ) {
element = 5;
vector<int> *ptr = map_a[element];
if (!ptr) {
ptr = new vector<int>;
map[element] = ptr;
}
ptr->push_back(i);
}
How to free up the memory we are allocation using new? | 0debug |
Java HasgMap gives wrong values for the given key : I am using a Map<Integer,Map<String,List<Employee>>>. After populating the map , if i immediately retrieve some values with key(String). The returned List<Employee> is correct. After some iteration the values are changing.
After first time populating data into the map, i have not used map.put anywhere. Only i am using map.get() | 0debug |
target_ulong HELPER(mfspr)(CPUOpenRISCState *env,
target_ulong rd, target_ulong ra, uint32_t offset)
{
#ifndef CONFIG_USER_ONLY
int spr = (ra | offset);
int idx;
OpenRISCCPU *cpu = openrisc_env_get_cpu(env);
switch (spr) {
case TO_SPR(0, 0):
return env->vr & SPR_VR;
case TO_SPR(0, 1):
return env->upr;
case TO_SPR(0, 2):
return env->cpucfgr;
case TO_SPR(0, 3):
return env->dmmucfgr;
case TO_SPR(0, 4):
return env->immucfgr;
case TO_SPR(0, 16):
return env->npc;
case TO_SPR(0, 17):
return env->sr;
case TO_SPR(0, 18):
return env->ppc;
case TO_SPR(0, 32):
return env->epcr;
case TO_SPR(0, 48):
return env->eear;
case TO_SPR(0, 64):
return env->esr;
case TO_SPR(1, 512) ... TO_SPR(1, 639):
idx = spr - TO_SPR(1, 512);
return env->tlb->dtlb[0][idx].mr;
case TO_SPR(1, 640) ... TO_SPR(1, 767):
idx = spr - TO_SPR(1, 640);
return env->tlb->dtlb[0][idx].tr;
case TO_SPR(1, 768) ... TO_SPR(1, 895):
case TO_SPR(1, 896) ... TO_SPR(1, 1023):
case TO_SPR(1, 1024) ... TO_SPR(1, 1151):
case TO_SPR(1, 1152) ... TO_SPR(1, 1279):
case TO_SPR(1, 1280) ... TO_SPR(1, 1407):
case TO_SPR(1, 1408) ... TO_SPR(1, 1535):
break;
case TO_SPR(2, 512) ... TO_SPR(2, 639):
idx = spr - TO_SPR(2, 512);
return env->tlb->itlb[0][idx].mr;
case TO_SPR(2, 640) ... TO_SPR(2, 767):
idx = spr - TO_SPR(2, 640);
return env->tlb->itlb[0][idx].tr;
case TO_SPR(2, 768) ... TO_SPR(2, 895):
case TO_SPR(2, 896) ... TO_SPR(2, 1023):
case TO_SPR(2, 1024) ... TO_SPR(2, 1151):
case TO_SPR(2, 1152) ... TO_SPR(2, 1279):
case TO_SPR(2, 1280) ... TO_SPR(2, 1407):
case TO_SPR(2, 1408) ... TO_SPR(2, 1535):
break;
case TO_SPR(9, 0):
return env->picmr;
case TO_SPR(9, 2):
return env->picsr;
case TO_SPR(10, 0):
return env->ttmr;
case TO_SPR(10, 1):
cpu_openrisc_count_update(cpu);
return env->ttcr;
default:
break;
}
#endif
return rd;
}
| 1threat |
create typeface from font resource id : <p>I have tried using <code>Typeface.createFromAsset(getAssets(),"font/myfont.ttf"));</code></p>
<p>I know font directory should be in assets but in my case, I have an existing font resource directory so I thought asset manager will read from font resource directory but I was wrong. I am creating Typeface to set custom font for collapsingToolbarLayout.</p>
<p>I found <a href="https://stackoverflow.com/questions/30765287/change-font-of-the-floating-label-edittext-and-textinputlayout/30767869#30767869">this answer</a> but it requires me to keep font in assets</p>
| 0debug |
Merging row data based in common Ids in angularjs : I have a JSON data, Data =[{"Id":1,"Name":"Test","Datacol1":"1","Datacol2":0,"Datacol3":0},{"Id":2,"Name":"Test123","Datacol1":"1","Datacol2":2,"Datacol3":0},{"Id":1,"Name":"Test","Datacol1":"0","Datacol2":1,"Datacol3":0},
{"Id":1,"Name":"Test","Datacol1":"0","Datacol2":0,"Datacol3":2}]
I want to merge the data and put it in single row data based on Id some thing like this Output = [{"Id":1,"Name":"Test","Datacol1":"1","Datacol2":1,"Datacol3":2},{"Id":2,"Name":"Test123","Datacol1":"1","Datacol2":2,"Datacol3":0}]
can some one please help me in acheiving this using angularjs. | 0debug |
Facebook graph user picture won't show on mobile devices : <p>I use the url <code>https://graph.facebook.com/{app_user_id}/picture?width=120&height=120</code> to show the user picture on my app, but since this morning, it has stopped working on mobile devices.</p>
<p>Now, the same url redirects to <code>https://lookaside.facebook.com/platform/profilepic/?asid={app_user_id}&height=120&width=120</code>. This url works on desktop web, but on mobile it redirects again to <code>https://m.facebook.com/platform/profilepic/?asid={app_user_id}&height=120&width=120</code> and the mobile web refuses to output the image. If I try to load it in the address bar, it is downloaded instead of showed.</p>
<p>I have searched for any change on the Facebook graph api about this but didn't find anything. Any hint to solve this? Thanks.</p>
| 0debug |
static int nbd_send_negotiate(NBDClient *client)
{
int csock = client->sock;
char buf[8 + 8 + 8 + 128];
int rc;
const int myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA);
socket_set_block(csock);
rc = -EINVAL;
TRACE("Beginning negotiation.");
memcpy(buf, "NBDMAGIC", 8);
if (client->exp) {
assert ((client->exp->nbdflags & ~65535) == 0);
cpu_to_be64w((uint64_t*)(buf + 8), NBD_CLIENT_MAGIC);
cpu_to_be64w((uint64_t*)(buf + 16), client->exp->size);
cpu_to_be16w((uint16_t*)(buf + 26), client->exp->nbdflags | myflags);
} else {
cpu_to_be64w((uint64_t*)(buf + 8), NBD_OPTS_MAGIC);
}
memset(buf + 28, 0, 124);
if (client->exp) {
if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
LOG("write failed");
goto fail;
}
} else {
if (write_sync(csock, buf, 18) != 18) {
LOG("write failed");
goto fail;
}
rc = nbd_receive_options(client);
if (rc < 0) {
LOG("option negotiation failed");
goto fail;
}
assert ((client->exp->nbdflags & ~65535) == 0);
cpu_to_be64w((uint64_t*)(buf + 18), client->exp->size);
cpu_to_be16w((uint16_t*)(buf + 26), client->exp->nbdflags | myflags);
if (write_sync(csock, buf + 18, sizeof(buf) - 18) != sizeof(buf) - 18) {
LOG("write failed");
goto fail;
}
}
TRACE("Negotiation succeeded.");
rc = 0;
fail:
socket_set_nonblock(csock);
return rc;
}
| 1threat |
int qcow2_read_snapshots(BlockDriverState *bs)
{
BDRVQcowState *s = bs->opaque;
QCowSnapshotHeader h;
QCowSnapshotExtraData extra;
QCowSnapshot *sn;
int i, id_str_size, name_size;
int64_t offset;
uint32_t extra_data_size;
int ret;
if (!s->nb_snapshots) {
s->snapshots = NULL;
s->snapshots_size = 0;
return 0;
}
offset = s->snapshots_offset;
s->snapshots = g_malloc0(s->nb_snapshots * sizeof(QCowSnapshot));
for(i = 0; i < s->nb_snapshots; i++) {
offset = align_offset(offset, 8);
ret = bdrv_pread(bs->file, offset, &h, sizeof(h));
if (ret < 0) {
goto fail;
}
offset += sizeof(h);
sn = s->snapshots + i;
sn->l1_table_offset = be64_to_cpu(h.l1_table_offset);
sn->l1_size = be32_to_cpu(h.l1_size);
sn->vm_state_size = be32_to_cpu(h.vm_state_size);
sn->date_sec = be32_to_cpu(h.date_sec);
sn->date_nsec = be32_to_cpu(h.date_nsec);
sn->vm_clock_nsec = be64_to_cpu(h.vm_clock_nsec);
extra_data_size = be32_to_cpu(h.extra_data_size);
id_str_size = be16_to_cpu(h.id_str_size);
name_size = be16_to_cpu(h.name_size);
ret = bdrv_pread(bs->file, offset, &extra,
MIN(sizeof(extra), extra_data_size));
if (ret < 0) {
goto fail;
}
offset += extra_data_size;
if (extra_data_size >= 8) {
sn->vm_state_size = be64_to_cpu(extra.vm_state_size_large);
}
if (extra_data_size >= 16) {
sn->disk_size = be64_to_cpu(extra.disk_size);
} else {
sn->disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
}
sn->id_str = g_malloc(id_str_size + 1);
ret = bdrv_pread(bs->file, offset, sn->id_str, id_str_size);
if (ret < 0) {
goto fail;
}
offset += id_str_size;
sn->id_str[id_str_size] = '\0';
sn->name = g_malloc(name_size + 1);
ret = bdrv_pread(bs->file, offset, sn->name, name_size);
if (ret < 0) {
goto fail;
}
offset += name_size;
sn->name[name_size] = '\0';
if (offset - s->snapshots_offset > QCOW_MAX_SNAPSHOTS_SIZE) {
ret = -EFBIG;
goto fail;
}
}
assert(offset - s->snapshots_offset <= INT_MAX);
s->snapshots_size = offset - s->snapshots_offset;
return 0;
fail:
qcow2_free_snapshots(bs);
return ret;
}
| 1threat |
C++, What is the difference for this code with and without the parentheses? : What is the purpose of the parentheses in the following piece of code? What would be happening if the parentheses were not there?
void foo(int * xPtr){
(*xPtr)++;
}
| 0debug |
Remove CV type qualifiers from libclang's CXType : <p>I use libclang to parse source file and get reference to some type as <code>CXType</code>, say it is "<code>const std::__1::basic_string<char></code>" (as reported by <code>clang_getTypeSpelling</code>). How can I get reference to same type but without const qualifier?</p>
| 0debug |
Change text color while typing in angular : <p>I am working on a Note Taking application, Requirement is when user types the text, It should in Red color, If he wants the rest of the text to be in black color while typing that also has to be achieved</p>
| 0debug |
How to include webpack plugins when using Laravel Mix? : <p>How should I include webpack plugins if I use WebPack AND Laravel Mix? I am confused which file I add the plugin code into.</p>
<p>My below attempt doesn't seem to be running my plugin. The plugin should be compressing the js, css files but its not.</p>
<p><code>webpack.config.js</code>:</p>
<pre><code> require('./node_modules/laravel-mix/src/index');
require(Mix.paths.mix());
// My plugin is here
const CompressionPlugin = require('compression-webpack-plugin');
Mix.dispatch('init', Mix);
let WebpackConfig = require('./node_modules/laravel-mix/src/builder/WebpackConfig');
module.exports = new WebpackConfig({
plugins: [
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.css$|\.html$|\.svg$/,
threshold: 10240,
minRatio: 0.8
})
],
}).build();
</code></pre>
<p><code>webpack.mix.js</code>:</p>
<pre><code> let mix = require('laravel-mix');
mix.setPublicPath('dist')
.js('src/app.js', 'scripts/')
.extract([
'jquery',
'axios',
'babel-polyfill',
'lodash',
'tether',
'vue',
'bootstrap-vue',
'vuex',
'vuex-localstorage',
])
.sass('src/styles/app.scss', 'styles/')
.copyDirectory('src/assets', 'dist/assets')
.options({
processCssUrls: false,
uglify: true
})
.version();
</code></pre>
<p>My NPM command is: </p>
<blockquote>
<p>node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=webpack.config.js</p>
</blockquote>
| 0debug |
static int vhost_verify_ring_part_mapping(void *part,
uint64_t part_addr,
uint64_t part_size,
uint64_t start_addr,
uint64_t size)
{
hwaddr l;
void *p;
int r = 0;
if (!ranges_overlap(start_addr, size, part_addr, part_size)) {
return 0;
}
l = part_size;
p = cpu_physical_memory_map(part_addr, &l, 1);
if (!p || l != part_size) {
r = -ENOMEM;
}
if (p != part) {
r = -EBUSY;
}
cpu_physical_memory_unmap(p, l, 0, 0);
return r;
}
| 1threat |
Regarding java's try/catch syntax; are these blocks equivalent? : <p>In the following block:</p>
<pre><code> try (final InputStream fis = new BufferedInputStream(Files.newInputStream(f.toPath()));
final ArchiveInputStream ais = factory.createArchiveInputStream(fn, fis)) {
System.out.println("Created " + ais.toString());
ArchiveEntry ae;
while ((ae = ais.getNextEntry()) != null) {
System.out.println(ae.getName());
}
}
</code></pre>
<p>is this equivalent to the following block:</p>
<pre><code>try {
final InputStream fis = new BufferedInputStream(Files.newInputS...;
} catch {
System.out.println("Created " + ais.toString());...
}
</code></pre>
<p>I stumbled across this syntax for try/catch in an apache common's library, and I'm not really sure how to take it. If I'm not correct in the only assumption that I can think of here, can anybody help me understand it or point me to a reference that explains this syntax? I've googled and searched aplenty on here and haven't been able to find anything applicable, though admittedly my search-fu is not the best.</p>
<p>Thanks in advance!</p>
| 0debug |
Is there any way to get s3 uri from aws web console? : <p>I want to download <em>a directory</em> from my s3.<br>
When I need <em>a file</em>, the s3 management console (aws web console) allows me to download it, but when <em>a directory</em>, I have to use aws-cli, like:</p>
<pre><code>$ aws s3 cp s3://mybucket/mydirectory/ . --recursive
</code></pre>
<p>My question is: Is there any way to get the s3 uri (<code>s3://mybucket/mydirectory/</code>) from s3 management console?<br>
It's URL is available, but it is slightly different from s3 URI required by aws-cli. I could not find any menu to get the uri.</p>
<p>Thank you in advance! </p>
| 0debug |
Binary Search Tree? Algorithm : <p>Does anyone know how to make an algorithm that transforms a binary search tree into an AVL tree, and yes transform it and not make another tree (so it will only be done using rotations) and not with the DSW technique... and in C. The tricky part here is that there is lots of cases since a binary search tree can be unbalanced in various ways and there being 4 types of rotations.</p>
| 0debug |
Error in Code Why does using float instead of int give me different results when all of my inputs are integers? : void main( )
{ int no=123;
while(no)
{ no/=10;
printf(“%d”, no%10);
}
}
1) 2 2) 210 3) 21 4) 213 | 0debug |
static inline void pit_load_count(PITChannelState *s, int val)
{
if (val == 0)
val = 0x10000;
s->count_load_time = cpu_get_ticks();
s->count_last_edge_check_time = s->count_load_time;
s->count = val;
if (s == &pit_channels[0] && val <= pit_min_timer_count) {
fprintf(stderr,
"\nWARNING: qemu: on your system, accurate timer emulation is impossible if its frequency is more than %d Hz. If using a 2.5.xx Linux kernel, you must patch asm/param.h to change HZ from 1000 to 100.\n\n",
PIT_FREQ / pit_min_timer_count);
}
}
| 1threat |
Select all elements except specific element with className by using plain Javascript : <p>I am implementing a simple website which has a toggle sidebar. I want to make the sidebar be hidden when I clicked somewhere on the page except the sidebar. So I think that I should get all elements on the page except a element that has sidebar class. Is there any way to do like that with plain javascript? JQuery has :not() select for this, but I'm trying to not using JQuery... :( </p>
| 0debug |
static void gen_mipsdsp_add_cmp_pick(DisasContext *ctx,
uint32_t op1, uint32_t op2,
int ret, int v1, int v2, int check_ret)
{
const char *opn = "mipsdsp add compare pick";
TCGv_i32 t0;
TCGv t1;
TCGv v1_t;
TCGv v2_t;
if ((ret == 0) && (check_ret == 1)) {
MIPS_DEBUG("NOP");
return;
}
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new();
v1_t = tcg_temp_new();
v2_t = tcg_temp_new();
gen_load_gpr(v1_t, v1);
gen_load_gpr(v2_t, v2);
switch (op1) {
case OPC_APPEND_DSP:
switch (op2) {
case OPC_APPEND:
tcg_gen_movi_i32(t0, v2);
gen_helper_append(cpu_gpr[ret], cpu_gpr[ret], v1_t, t0);
break;
case OPC_PREPEND:
tcg_gen_movi_i32(t0, v2);
gen_helper_prepend(cpu_gpr[ret], v1_t, cpu_gpr[ret], t0);
break;
case OPC_BALIGN:
tcg_gen_movi_i32(t0, v2);
gen_helper_balign(cpu_gpr[ret], v1_t, cpu_gpr[ret], t0);
break;
default:
MIPS_INVAL("MASK APPEND");
generate_exception(ctx, EXCP_RI);
break;
}
break;
case OPC_CMPU_EQ_QB_DSP:
switch (op2) {
case OPC_CMPU_EQ_QB:
check_dsp(ctx);
gen_helper_cmpu_eq_qb(v1_t, v2_t, cpu_env);
break;
case OPC_CMPU_LT_QB:
check_dsp(ctx);
gen_helper_cmpu_lt_qb(v1_t, v2_t, cpu_env);
break;
case OPC_CMPU_LE_QB:
check_dsp(ctx);
gen_helper_cmpu_le_qb(v1_t, v2_t, cpu_env);
break;
case OPC_CMPGU_EQ_QB:
check_dsp(ctx);
gen_helper_cmpgu_eq_qb(cpu_gpr[ret], v1_t, v2_t);
break;
case OPC_CMPGU_LT_QB:
check_dsp(ctx);
gen_helper_cmpgu_lt_qb(cpu_gpr[ret], v1_t, v2_t);
break;
case OPC_CMPGU_LE_QB:
check_dsp(ctx);
gen_helper_cmpgu_le_qb(cpu_gpr[ret], v1_t, v2_t);
break;
case OPC_CMPGDU_EQ_QB:
check_dspr2(ctx);
gen_helper_cmpgu_eq_qb(t1, v1_t, v2_t);
tcg_gen_mov_tl(cpu_gpr[ret], t1);
tcg_gen_andi_tl(cpu_dspctrl, cpu_dspctrl, 0xF0FFFFFF);
tcg_gen_shli_tl(t1, t1, 24);
tcg_gen_or_tl(cpu_dspctrl, cpu_dspctrl, t1);
break;
case OPC_CMPGDU_LT_QB:
check_dspr2(ctx);
gen_helper_cmpgu_lt_qb(t1, v1_t, v2_t);
tcg_gen_mov_tl(cpu_gpr[ret], t1);
tcg_gen_andi_tl(cpu_dspctrl, cpu_dspctrl, 0xF0FFFFFF);
tcg_gen_shli_tl(t1, t1, 24);
tcg_gen_or_tl(cpu_dspctrl, cpu_dspctrl, t1);
break;
case OPC_CMPGDU_LE_QB:
check_dspr2(ctx);
gen_helper_cmpgu_le_qb(t1, v1_t, v2_t);
tcg_gen_mov_tl(cpu_gpr[ret], t1);
tcg_gen_andi_tl(cpu_dspctrl, cpu_dspctrl, 0xF0FFFFFF);
tcg_gen_shli_tl(t1, t1, 24);
tcg_gen_or_tl(cpu_dspctrl, cpu_dspctrl, t1);
break;
case OPC_CMP_EQ_PH:
check_dsp(ctx);
gen_helper_cmp_eq_ph(v1_t, v2_t, cpu_env);
break;
case OPC_CMP_LT_PH:
check_dsp(ctx);
gen_helper_cmp_lt_ph(v1_t, v2_t, cpu_env);
break;
case OPC_CMP_LE_PH:
check_dsp(ctx);
gen_helper_cmp_le_ph(v1_t, v2_t, cpu_env);
break;
case OPC_PICK_QB:
check_dsp(ctx);
gen_helper_pick_qb(cpu_gpr[ret], v1_t, v2_t, cpu_env);
break;
case OPC_PICK_PH:
check_dsp(ctx);
gen_helper_pick_ph(cpu_gpr[ret], v1_t, v2_t, cpu_env);
break;
case OPC_PACKRL_PH:
check_dsp(ctx);
gen_helper_packrl_ph(cpu_gpr[ret], v1_t, v2_t);
break;
}
break;
#ifdef TARGET_MIPS64
case OPC_CMPU_EQ_OB_DSP:
switch (op2) {
case OPC_CMP_EQ_PW:
check_dsp(ctx);
gen_helper_cmp_eq_pw(v1_t, v2_t, cpu_env);
break;
case OPC_CMP_LT_PW:
check_dsp(ctx);
gen_helper_cmp_lt_pw(v1_t, v2_t, cpu_env);
break;
case OPC_CMP_LE_PW:
check_dsp(ctx);
gen_helper_cmp_le_pw(v1_t, v2_t, cpu_env);
break;
case OPC_CMP_EQ_QH:
check_dsp(ctx);
gen_helper_cmp_eq_qh(v1_t, v2_t, cpu_env);
break;
case OPC_CMP_LT_QH:
check_dsp(ctx);
gen_helper_cmp_lt_qh(v1_t, v2_t, cpu_env);
break;
case OPC_CMP_LE_QH:
check_dsp(ctx);
gen_helper_cmp_le_qh(v1_t, v2_t, cpu_env);
break;
case OPC_CMPGDU_EQ_OB:
check_dspr2(ctx);
gen_helper_cmpgdu_eq_ob(cpu_gpr[ret], v1_t, v2_t, cpu_env);
break;
case OPC_CMPGDU_LT_OB:
check_dspr2(ctx);
gen_helper_cmpgdu_lt_ob(cpu_gpr[ret], v1_t, v2_t, cpu_env);
break;
case OPC_CMPGDU_LE_OB:
check_dspr2(ctx);
gen_helper_cmpgdu_le_ob(cpu_gpr[ret], v1_t, v2_t, cpu_env);
break;
case OPC_CMPGU_EQ_OB:
check_dsp(ctx);
gen_helper_cmpgu_eq_ob(cpu_gpr[ret], v1_t, v2_t);
break;
case OPC_CMPGU_LT_OB:
check_dsp(ctx);
gen_helper_cmpgu_lt_ob(cpu_gpr[ret], v1_t, v2_t);
break;
case OPC_CMPGU_LE_OB:
check_dsp(ctx);
gen_helper_cmpgu_le_ob(cpu_gpr[ret], v1_t, v2_t);
break;
case OPC_CMPU_EQ_OB:
check_dsp(ctx);
gen_helper_cmpu_eq_ob(v1_t, v2_t, cpu_env);
break;
case OPC_CMPU_LT_OB:
check_dsp(ctx);
gen_helper_cmpu_lt_ob(v1_t, v2_t, cpu_env);
break;
case OPC_CMPU_LE_OB:
check_dsp(ctx);
gen_helper_cmpu_le_ob(v1_t, v2_t, cpu_env);
break;
case OPC_PACKRL_PW:
check_dsp(ctx);
gen_helper_packrl_pw(cpu_gpr[ret], v1_t, v2_t);
break;
case OPC_PICK_OB:
check_dsp(ctx);
gen_helper_pick_ob(cpu_gpr[ret], v1_t, v2_t, cpu_env);
break;
case OPC_PICK_PW:
check_dsp(ctx);
gen_helper_pick_pw(cpu_gpr[ret], v1_t, v2_t, cpu_env);
break;
case OPC_PICK_QH:
check_dsp(ctx);
gen_helper_pick_qh(cpu_gpr[ret], v1_t, v2_t, cpu_env);
break;
}
break;
case OPC_DAPPEND_DSP:
switch (op2) {
case OPC_DAPPEND:
tcg_gen_movi_i32(t0, v2);
gen_helper_dappend(cpu_gpr[ret], v1_t, cpu_gpr[ret], t0);
break;
case OPC_PREPENDD:
tcg_gen_movi_i32(t0, v2);
gen_helper_prependd(cpu_gpr[ret], v1_t, cpu_gpr[ret], t0);
break;
case OPC_PREPENDW:
tcg_gen_movi_i32(t0, v2);
gen_helper_prependw(cpu_gpr[ret], v1_t, cpu_gpr[ret], t0);
break;
case OPC_DBALIGN:
tcg_gen_movi_i32(t0, v2);
gen_helper_dbalign(cpu_gpr[ret], v1_t, cpu_gpr[ret], t0);
break;
default:
MIPS_INVAL("MASK DAPPEND");
generate_exception(ctx, EXCP_RI);
break;
}
break;
#endif
}
tcg_temp_free_i32(t0);
tcg_temp_free(t1);
tcg_temp_free(v1_t);
tcg_temp_free(v2_t);
(void)opn;
MIPS_DEBUG("%s", opn);
}
| 1threat |
conda environment to AWS Lambda : <p>I would like to set up a Python function I've written on AWS Lambda, a function that depends on a bunch of Python libraries I have already collected in a <a href="http://conda.pydata.org/docs/using/envs.html" rel="noreferrer">conda environment</a>.</p>
<p>To set this up on Lambda, I'm supposed to zip this environment up, but the <a href="http://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html" rel="noreferrer">Lambda docs</a> only give instructions for how to do this using pip/VirtualEnv. Does anyone have experience with this?</p>
| 0debug |
Decimal Format neglecting decimal 0 : <p>Hi I am trying to convert a decimal format.</p>
<pre><code>final DecimalFormat myFormatter = new DecimalFormat("###,###.##");
String total = "USD"+ myFormatter.format(78.0)
</code></pre>
<p>I need to get the out put as <strong>USD 78.00</strong></p>
<p>but I am getting the result as <strong>USD 78</strong></p>
<p>can any one suggest me how to resolve this.</p>
| 0debug |
static int hevc_parse_slice_header(AVCodecParserContext *s, H2645NAL *nal,
AVCodecContext *avctx)
{
HEVCParserContext *ctx = s->priv_data;
GetBitContext *gb = &nal->gb;
HEVCPPS *pps;
HEVCSPS *sps;
unsigned int pps_id;
get_bits1(gb);
if (IS_IRAP_NAL(nal))
get_bits1(gb);
pps_id = get_ue_golomb_long(gb);
if (pps_id >= HEVC_MAX_PPS_COUNT || !ctx->ps.pps_list[pps_id]) {
av_log(avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", pps_id);
return AVERROR_INVALIDDATA;
}
pps = (HEVCPPS*)ctx->ps.pps_list[pps_id]->data;
sps = (HEVCSPS*)ctx->ps.sps_list[pps->sps_id]->data;
s->coded_width = sps->width;
s->coded_height = sps->height;
s->width = sps->output_width;
s->height = sps->output_height;
s->format = sps->pix_fmt;
avctx->profile = sps->ptl.general_ptl.profile_idc;
avctx->level = sps->ptl.general_ptl.level_idc;
return 0;
}
| 1threat |
i used this code to make my calorie counting app and keep getting errors : its my first question here sorry if miss any details, im new to swift coding language but have used C++ and other languages but i keep getting the does not conform error on the line mainly shows up on the datasource `class CaloriesInputViewController: UIViewController, UIPickerViewDelegate , UITextFieldDelegate, UIPickerViewDataSource`,
also further down where ever it says `UIAlertControllerStyle` i keep getting a "Extra argument 'message' in call"
thank you in advance
import UIKit
import Parse
class CaloriesInputViewController: UIViewController, UIPickerViewDelegate , UITextFieldDelegate, UIPickerViewDataSource{
//Properties for food input detail
@IBOutlet weak var foodName: UITextField!
@IBOutlet weak var caloriesAmount: UITextField!
@IBOutlet weak var pickerView: UIPickerView!
var mealType: String = ""
var pickerDataSource = ["Breakfast", "Lunch", "Dinner", "Snacks"];
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = true
self.pickerView.dataSource = self
self.pickerView.delegate = self
initializeTextFields()
}
//Function to initialize text fields to only except numerical values
func initializeTextFields() {
caloriesAmount.delegate = self
caloriesAmount.keyboardType = UIKeyboardType.numberPad
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerDataSource.count;
}
private func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return pickerDataSource[row]
}
private func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
if(row == 0)//Breakfast
{
mealType = "Breakfast"
}
else if(row == 1)//Lunch
{
mealType = "Lunch"
}
else if(row == 2)//Dinner
{
mealType = "Dinner"
}
else//Snacks
{
mealType = "Snacks"
}
}
//Function to food details
@IBAction func addCalories(sender: AnyObject) {
if(foodName.text!.isEmpty || (caloriesAmount.text!.isEmpty) || mealType.isEmpty){
//Output an Alert
var alert = UIAlertControllerStyle(title: "Data Required", message: "Please enter all required information", delegate: self, cancelButtonTitle: "OK")
alert.show()
}
else{
//Create a foodLog object in Parse
var foodLog = PFObject(className: "foodLog")
//Put user food detail into foodLog
foodLog["foodName"] = foodName.text
foodLog["caloriesCount"] = caloriesAmount.text
foodLog["mealType"] = mealType
foodLog["user"] = PFUser.current()!
//Save data
foodLog.saveInBackground()
//Output an alert informing a user that the password or username did not meet the requirements
var alert = UIAlertControllerStyle(title: "Recorded", message: "Your calories were recorded", delegate: self, cancelButtonTitle: "OK")
alert.show()
//Redirect a user to a log view controller
self.navigationController?.popViewController(animated: true)
}
}
}
| 0debug |
best backend framework to use with React frontend : <p>i have to developed a web app intregated also with Android Phone.
I have choosen to use react js with redux for the frontend and native android for mobile app. I need to develop a backend that publish some restfull api and if possible push notification management. The backend should be connected data stores ( i need a framework compatible with mongo db and mysql). I need an high level of performance. The solutions that meet these reqs that i found on the web are:
sails
loopback
laravel
hibernate</p>
<p>What is the best solution that met these reqs and if is compatible with react ?
i need a production solution
Thanks</p>
| 0debug |
how to pass data from angular material dialog to parent component? : <p>I'm using angular 6 and I have a button which opens a dialog. in my dialog, I have a form that gets user's data and then I have two buttons to submit and cancel. I tried to show my form's data in the console but it returns undefined! whats the problem? here is part of codes:</p>
<p><strong>main.component.ts:</strong></p>
<pre><code>import { Work } from '../../../../classes/work_shift';
import { DialogContentComponent} from './dialog-content/dialog-content.component';
export class WorkShiftsComponent implements OnInit {
shifts: Work[];
name: string;
start: string;
end: string;
constructor(public dialog: MatDialog, private shiftService: WorkShiftsService) { }
ngOnInit() {
}
openDialog() {
const dialogRef = this.dialog.open(DialogContentComponent, {
width: '640px',
disableClose: true,
data: {name: this.name, start: this.start, end: this.end}
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
console.log(result);//returns undefined
});
}
}
</code></pre>
<p><strong>dialogContent.component.html:</strong></p>
<pre><code> <mat-dialog-content>
<form class="example-form">
<div fxLayout="column" fxLayoutAlign="space-around" class="form">
<div class="input">
<mat-form-field class="input4">
<input matInput placeholder="Shift name">
</mat-form-field>
</div>
<div>
<mat-form-field class="input input2">
<input matInput placeholder="Start" atp-time-picker>
</mat-form-field>
<mat-form-field class="input input2">
<input matInput placeholder="End" atp-time-picker >
</mat-form-field>
</div>
<br/>
</div>
</form>
</mat-dialog-content>
<mat-dialog-actions>
<button class="mat-button" mat-button (click)="onClose()">Cancel</button>
<button class="mat-button" mat-button [mat-dialog-close]="data" cdkFocusInitial color="primary">Create</button>
</mat-dialog-actions>
</code></pre>
| 0debug |
String to Unicode showing error: name 'unicode' is not defined : <p>I have to code a program that translates a string into a UNICODE equivalent. Please tell me how to fix: </p>
<pre><code>inp = input ("\nPLEASE ENTER A CHARACTER OR STRING: ")
display = [c for c in inp]
uni = [unicode(c) for c in inp]
print ("\nTHE CHARACTER(S)", display, "ARE REPRESENTED IN UNICODE AS", uni, ".")
</code></pre>
| 0debug |
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
{
LIST_REMOVE (e, entries);
qemu_free (e);
}
| 1threat |
How can I compare login data with my SQLite DB in android app..? : I,ve made a simple login app with an SQLite DB. Now I want to compare my login data(username,password) with my DB to proceed, for this what should I do in my loginactivity code. Both login and registration activities are shown.
\\This is Registration Activity with SQLite DB "DB"
package com.example.shahxad.myapp;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Handler;
public class RegistrationActivity extends AppCompatActivity {
public SQLiteDatabase DB;
public EditText username, email, phone, password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
DB = openOrCreateDatabase("DB", MODE_PRIVATE, null);
DB.execSQL("create table if not exists users(REC_ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME varchar(20),EMAIL VARCHAR(20),PHONE integer(10),PASSWORD VARCHAR(20))");
username = (EditText)findViewById(R.id.username);
email = (EditText)findViewById(R.id.email);
phone = (EditText)findViewById(R.id.phone);
password = (EditText)findViewById(R.id.password);
Button reg = (Button) findViewById(R.id.reg);
reg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String sql = "insert into users(REC_ID,NAME,EMAIL,PHONE,PASSWORD) values(NULL,'" + username.getText().toString() + "','" + email.getText().toString() + "','" + phone.getText().toString() + "','" + password.getText().toString() + "')";
DB.execSQL(sql);
Cursor cursor = DB.rawQuery("select * from users", null);
cursor.moveToLast();
String result = cursor.getString(0).toString() + cursor.getString(1).toString() + cursor.getString(2).toString() + cursor.getString(3).toString();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegistrationActivity.this, RegSplash.class);
startActivity(intent);
}
});
}
}
\\This is Login Activity (these are two different activities)
package com.example.shahxad.myapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class LoginActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, AppActivity.class);
startActivity(intent);
}
});
}
}
| 0debug |
void OPPROTO op_decq_ECX(void)
{
ECX--;
}
| 1threat |
Not able to run this php code? : <?PHP
$connection = mysqli_connect("localhost", "akdnaklnd", "lfnlfns","faknfns");
$game = $_POST['game'];
$post_rating = $_POST['rating'];
$find_data = mysqli_query( "SELECT * FROM rates WHERE game='$game'");
while($row = mysqli_fetch_assoc($find_data)){
$id=$row['id'];
$current_rating = $row['rating'];
$current_hits=$row['hits'];
}
$new_hits = $current_hits + 1;
$update_hits= mysqli_query("UPDATE rates SET hits = '$new_hits' WHERE id='$id'");
$pre_rating= $current_rating + $post_rating;
$new_rating = $pre_rating / $new_hits;
$update_rating = mysqli_query("UPDATE rates SET rating ='$new_rating' WHERE id='$id'");
header("location : average.php");
?>
Discription I am trying to insert rating in database and calling average of that given rating from data base
| 0debug |
Split Function working in c# : static void Main(string[] args)
{
string Var = ",A,,,B,,C";
string[] members = Var.Split(',');
foreach (string member in members)
{
Console.WriteLine(member);
}
Console.WriteLine(members.Length);
Console.ReadLine();
}
The output of the following code is
A
B
C
7
the 7 is length of the array , but my question is that when i passed ',' in parameters of split function so why it takes initial ',' as a space . and why it takes 2 out of 3 ',' as space after A . and why it takes 1 out of 2 ',' as space after B ? | 0debug |
How to make a pop-up alert when user did not enter email : <p>I need jquery script, to show pop up, when user did not enter email to the field after being at site 1 min. And redirect to another page if he enter his email. I have the pop up itself. Thank you for your help! </p>
| 0debug |
How to Access Variable's Memory Address In Java? : <p>I wrote this code and want to see memory location of 2 objects that i create from one class and make instance of one specific variable.</p>
<pre><code>public class StaticFields {
int a = 12;
int b = 235;
public static void main(String[] args) {
StaticFields obj = new StaticFields();
int a = obj.a;
StaticFields obj2 = new StaticFields();
int c = obj2.a;
System.out.println(System.identityHashCode(a));
System.out.println(System.identityHashCode(c));
}
}
</code></pre>
<p>why the "identityHashCode" of "a" and "c" is the same ?</p>
<p>Thanks.</p>
| 0debug |
Unable to find repository on Update-Module : <p>I'm using Windows 10 and Powershell 5.1</p>
<p>Get-PSRepository has result :</p>
<blockquote>
<p>PSGallery Untrusted <a href="https://www.powershellgallery.com/api/v2" rel="noreferrer">https://www.powershellgallery.com/api/v2</a></p>
</blockquote>
<p>whereas Update-Module returns error</p>
<blockquote>
<p>PackageManagement\Install-Package : Unable to find repository '<a href="https://www.powershellgallery.com/api/v2/" rel="noreferrer">https://www.powershellgallery.com/api/v2/</a>'. Use
Get-PSRepository to see all available repositories.
At C:\Program Files\WindowsPowerShell\Modules\powershellget\2.0.1\PSModule.psm1:13000 char:20
+ ... $sid = PackageManagement\Install-Package @PSBoundParameters
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Microsoft.Power....InstallPackage:InstallPackage) [Install-Package], Ex
ception
+ FullyQualifiedErrorId : SourceNotFound,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage</p>
</blockquote>
<p>Any idea of how to fix it?</p>
| 0debug |
static void vfio_calxeda_xgmac_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
VFIOCalxedaXgmacDeviceClass *vcxc =
VFIO_CALXEDA_XGMAC_DEVICE_CLASS(klass);
vcxc->parent_realize = dc->realize;
dc->realize = calxeda_xgmac_realize;
dc->desc = "VFIO Calxeda XGMAC";
dc->vmsd = &vfio_platform_calxeda_xgmac_vmstate;
} | 1threat |
static ObjectClass *alpha_cpu_class_by_name(const char *cpu_model)
{
ObjectClass *oc = NULL;
char *typename;
int i;
if (cpu_model == NULL) {
return NULL;
}
oc = object_class_by_name(cpu_model);
if (oc != NULL && object_class_dynamic_cast(oc, TYPE_ALPHA_CPU) != NULL &&
!object_class_is_abstract(oc)) {
return oc;
}
for (i = 0; i < ARRAY_SIZE(alpha_cpu_aliases); i++) {
if (strcmp(cpu_model, alpha_cpu_aliases[i].alias) == 0) {
oc = object_class_by_name(alpha_cpu_aliases[i].typename);
assert(oc != NULL && !object_class_is_abstract(oc));
return oc;
}
}
typename = g_strdup_printf("%s-" TYPE_ALPHA_CPU, cpu_model);
oc = object_class_by_name(typename);
g_free(typename);
if (oc != NULL && object_class_is_abstract(oc)) {
oc = NULL;
}
return oc;
}
| 1threat |
UnsafeRawPointer assumingMemoryBound vs. bindMemory : <p>Can anyone explain what is difference between <code>UnsafeRawPointer.assumimgMemoryBound(to:)</code> and <code>UnsafeRawPointer.bindMemory(to:capacity:)</code>?</p>
<p>A practical example of compile or run time difference would be more then welcome.</p>
<p><a href="https://swift.org/migration-guide-swift3/se-0107-migrate.html#common-use-cases" rel="noreferrer">Swift Doc</a> says about <code>bindMemory(to:capacity:)</code>: </p>
<blockquote>
<p>This API allows a region of memory to hold unrelated types at different points in the program. Binding uninitialized memory to a type prepares the memory to store values of that type. Binding memory that is already initialized reinterprets the in-memory values as the new type. If the old values are either nontrivial (require destruction) or if they are ever read from memory before being overwritten, then the new type must be mutually layout compatible with the old type.</p>
</blockquote>
<p>What does it mean <em>Binding uninitialized memory to a type prepares the memory to store values of that type</em>? It's allocated bytes, right? So what's different after <code>bindMemory(to:capacity:)</code> completes?</p>
| 0debug |
static int cpu_gdb_write_register(CPUState *env, uint8_t *mem_buf, int n)
{
uint32_t tmp;
if (n < CPU_NB_REGS) {
env->regs[gpr_map[n]] = ldtul_p(mem_buf);
return sizeof(target_ulong);
} else if (n >= IDX_FP_REGS && n < IDX_FP_REGS + 8) {
#ifdef USE_X86LDOUBLE
memcpy(&env->fpregs[n - IDX_FP_REGS], mem_buf, 10);
#endif
return 10;
} else if (n >= IDX_XMM_REGS && n < IDX_XMM_REGS + CPU_NB_REGS) {
n -= IDX_XMM_REGS;
env->xmm_regs[n].XMM_Q(0) = ldq_p(mem_buf);
env->xmm_regs[n].XMM_Q(1) = ldq_p(mem_buf + 8);
return 16;
} else {
switch (n) {
case IDX_IP_REG:
env->eip = ldtul_p(mem_buf);
return sizeof(target_ulong);
case IDX_FLAGS_REG:
env->eflags = ldl_p(mem_buf);
return 4;
#if defined(CONFIG_USER_ONLY)
#define LOAD_SEG(index, sreg)\
tmp = ldl_p(mem_buf);\
if (tmp != env->segs[sreg].selector)\
cpu_x86_load_seg(env, sreg, tmp);\
return 4
#else
#define LOAD_SEG(index, sreg) return 4
#endif
case IDX_SEG_REGS: LOAD_SEG(10, R_CS);
case IDX_SEG_REGS + 1: LOAD_SEG(11, R_SS);
case IDX_SEG_REGS + 2: LOAD_SEG(12, R_DS);
case IDX_SEG_REGS + 3: LOAD_SEG(13, R_ES);
case IDX_SEG_REGS + 4: LOAD_SEG(14, R_FS);
case IDX_SEG_REGS + 5: LOAD_SEG(15, R_GS);
case IDX_FP_REGS + 8:
env->fpuc = ldl_p(mem_buf);
return 4;
case IDX_FP_REGS + 9:
tmp = ldl_p(mem_buf);
env->fpstt = (tmp >> 11) & 7;
env->fpus = tmp & ~0x3800;
return 4;
case IDX_FP_REGS + 10: return 4;
case IDX_FP_REGS + 11: return 4;
case IDX_FP_REGS + 12: return 4;
case IDX_FP_REGS + 13: return 4;
case IDX_FP_REGS + 14: return 4;
case IDX_FP_REGS + 15: return 4;
case IDX_MXCSR_REG:
env->mxcsr = ldl_p(mem_buf);
return 4;
}
}
return 0;
}
| 1threat |
void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
void *opaque)
{
BlockDriver *drv;
int count = 0;
int i;
const char **formats = NULL;
QLIST_FOREACH(drv, &bdrv_drivers, list) {
if (drv->format_name) {
bool found = false;
int i = count;
while (formats && i && !found) {
found = !strcmp(formats[--i], drv->format_name);
}
if (!found) {
formats = g_renew(const char *, formats, count + 1);
formats[count++] = drv->format_name;
}
}
}
qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
for (i = 0; i < count; i++) {
it(opaque, formats[i]);
}
g_free(formats);
}
| 1threat |
static int check_recording_time(OutputStream *ost)
{
OutputFile *of = output_files[ost->file_index];
if (of->recording_time != INT64_MAX &&
av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
AV_TIME_BASE_Q) >= 0) {
ost->is_past_recording_time = 1;
return 0;
}
return 1;
}
| 1threat |
Capturing high collinearity in statsmodel : I was trying to solve a problem that asked me to assess whether the digital advertising campaign is successful in driving volume sales.
Because we only have limited impression data, I have filled 0 in impression for those that are nan.
The data is on a weekly basis and it looks like this:
[![enter image description here][1]][1]
Then I did a scatterplot for impression and volume:
[![enter image description here][2]][2]
However when I try to regression using impression as x and volume as y in statsmodel it gives me collearity warning but I 'm only using impression as x variables. The code I'm using is the following:
[![enter image description here][3]][3]
And it gives me the following result:
[![enter image description here][4]][4]
[![enter image description here][5]][5]
Could anyone help me to figure out?? I'm really confused since I only have one x, there shouldn't be any collearity.
[1]: https://i.stack.imgur.com/vEU1y.png
[2]: https://i.stack.imgur.com/S3IE1.png
[3]: https://i.stack.imgur.com/B9xiO.png
[4]: https://i.stack.imgur.com/h3E1b.png
[5]: https://i.stack.imgur.com/X5bKD.png | 0debug |
How can I create method for passing values from Activity to other components : <p>I need the <code>chapterId</code> and <code>lessonId</code> value in <code>Tablayout</code> fragments .</p>
<p>one of the solution to send data from activity to fragment is sending value with public method in activity and create a new instance in fragment and give the value in fragments .</p>
<p>I have This activity where i get bundle in that .</p>
<pre><code> public class DetailActivity extends AppCompatActivity {
private String chapterId;
private String lessonId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
getBundle();
}
private void getBundle() {
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
chapterId = bundle.getString("CHAPTERID");
lessonId = bundle.getString("LESSONID");
}
}
======== Method for sending data to other Activities and Fragments=====
public String getId(){
}
}
</code></pre>
<p>Now my question is how can i write this method . Thanks</p>
| 0debug |
React hook useEffect dependency array : <p>I trying to wrap my head around the new hooks api of react. Specifically, I'm trying to construct the classic use case that once was the following: </p>
<pre><code>componentDidUpdate(prevProps) {
if (prevProps.foo !== this.props.foo) {
// animate dom elements here...
this.animateSomething(this.ref, this.props.onAnimationComplete);
}
}
</code></pre>
<p>Now, I tried to build the same with a function component and <code>useEffect</code>, but can't figure out how to do it. This is what I tried:</p>
<pre><code>useEffect(() => {
animateSomething(ref, props.onAnimationComplete);
}, [props.foo]);
</code></pre>
<p>This way, the effect is only called when props.foo changes. And that does work – BUT! It appears to be an anti-pattern since the <code>eslint-plugin-react-hooks</code> marks this as an error. All dependencies that are used inside the effect should be declared in the dependencies array. So that means I would have to do the following:</p>
<pre><code>useEffect(() => {
animateSomething(ref, props.onAnimationComplete);
}, [props.foo, ref, props.onAnimationComplete]);
</code></pre>
<p>That does not lead to the linting error BUT it totally defeats the purpose of <em>only</em> calling the effect when <code>props.foo</code> changes. I don't WANT it to be called when the other props or the ref change.</p>
<p>Now, I read something about using <code>useCallback</code> to wrap this. I tried it but didn't get any further.</p>
<p>Can somebody help?</p>
| 0debug |
Understanding Flutter Render Engine : <p>The docs <a href="https://flutter.io/docs/get-started/flutter-for/android-devs#how-do-i-update-listviews-dynamically" rel="noreferrer">here</a> about how to update a <code>ListView</code> say:</p>
<blockquote>
<p>In Flutter, if you were to update the list of widgets inside a
setState(), you would quickly see that your data did not change
visually. This is because when setState() is called, the Flutter
rendering engine looks at the widget tree to see if anything has
changed. When it gets to your ListView, it performs a == check, and
determines that the two ListViews are the same. Nothing has changed,
so no update is required.</p>
<p>For a simple way to update your ListView, create a new List inside of
setState(), and copy the data from the old list to the new list.</p>
</blockquote>
<p>I don't get how the Render Engine determines if there are any changes in the Widget Tree in this case.</p>
<p>AFAICS, we care calling <code>setState</code>, which marks the <code>State</code> object as dirty and asks it to rebuild. Once it rebuilds there will be a new <code>ListView</code>, won't it? So how come the <code>==</code> check says it's the same object? </p>
<p>Also, the new <code>List</code> will be internal to the <code>State</code> object, does the Flutter engine compare all the objects inside the <code>State</code> object? I thought it only compared the <code>Widget</code> tree. </p>
<p>So, basically I don't understand how the Render Engine decides what it's going to update and what's going to ignore, since I can't see how creating a new <code>List</code> sends any information to the Render Engine, as the docs says the Render Engine just looks for a new <code>ListView</code>... And AFAIK a new <code>List</code> won't create a new <code>ListView</code>. </p>
| 0debug |
more syntax in Java : <p><a href="https://i.stack.imgur.com/8C5VE.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Hey everyone, i'm just beginning to learn Java. I encounter a java program and see the keyword 'more'. Can anyone explain what 'more' does in this situation</p>
| 0debug |
Laravel Mail to Log : <p>I have my Laravel Mail driver setup as to print to my log file:</p>
<pre><code>'driver' => env('MAIL_DRIVER', 'log'),
</code></pre>
<p>When I send mail, however, I am receiving a swiftmail authentication error:</p>
<blockquote>
<p>Expected response code 250 but got code '530' with message '530 5.7.1
Authentication required'</p>
<pre><code>vendor\\swiftmailer\\swiftmailer\\lib\\classes\\Swift\\Transport\\AbstractSmtpTransport.php
</code></pre>
<p>line 383\">AbstractSmtpTransport.php line 383 </p>
<pre><code>530 5.7.1 Authentication required
</code></pre>
</blockquote>
<p>Is there another setting I need to set somewhere? Why is it trying to use swiftmailer?</p>
| 0debug |
static av_cold int decoder_init(AVCodecContext * avctx)
{
G729Context* ctx = avctx->priv_data;
int i,k;
if (avctx->channels != 1) {
av_log(avctx, AV_LOG_ERROR, "Only mono sound is supported (requested channels: %d).\n", avctx->channels);
return AVERROR(EINVAL);
}
avctx->sample_fmt = AV_SAMPLE_FMT_S16;
avctx->frame_size = SUBFRAME_SIZE << 1;
ctx->gain_coeff = 16384;
for (k = 0; k < MA_NP + 1; k++) {
ctx->past_quantizer_outputs[k] = ctx->past_quantizer_output_buf[k];
for (i = 1; i < 11; i++)
ctx->past_quantizer_outputs[k][i - 1] = (18717 * i) >> 3;
}
ctx->lsp[0] = ctx->lsp_buf[0];
ctx->lsp[1] = ctx->lsp_buf[1];
memcpy(ctx->lsp[0], lsp_init, 10 * sizeof(int16_t));
ctx->exc = &ctx->exc_base[PITCH_DELAY_MAX+INTERPOL_LEN];
ctx->rand_value = 21845;
for(i=0; i<4; i++)
ctx->quant_energy[i] = -14336;
avctx->dsp_mask= ~AV_CPU_FLAG_FORCE;
dsputil_init(&ctx->dsp, avctx);
return 0;
}
| 1threat |
window.location.href = 'http://attack.com?user=' + user_input; | 1threat |
Unable to define Math Expression for Cloudwatch Alarm in a Cloudformation Template : <p><a href="https://aws.amazon.com/about-aws/whats-new/2018/11/amazon-cloudwatch-launches-ability-to-add-alarms-on-metric-math-expressions/" rel="noreferrer">Recently</a> AWS announced that Cloudwatch alarms can use Math Expressions on metrics. I decided to create an alarm that compares the SUM of 2 single metrics with a given threshold. This means that according to <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/using-metric-math.html#metric-math-syntax" rel="noreferrer">AWS documentation</a> my expression should be SUM([m1,m2]), where m1 and m2 are 2 single metrics.
I also decided to implement this idea using a cloudformation template (in yaml). Here's the Cloudwatch alarm definition:</p>
<pre><code>BillingAlarmExpression:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmActions:
- !Ref BillingAlertTopic
AlarmDescription: String
ComparisonOperator: GreaterThanOrEqualToThreshold
EvaluationPeriods: 1
Metrics:
- Id: m1
MetricStat:
Metric:
Dimensions:
- Name: ServiceName
Value: AmazonEC2
- Name: Currency
Value: USD
MetricName: EstimatedCharges
Namespace: AWS/Billing
Period: 86400
Stat: Maximum
ReturnData: False
- Id: m2
MetricStat:
Metric:
Dimensions:
- Name: ServiceName
Value: AmazonCloudwatch
- Name: Currency
Value: USD
MetricName: EstimatedCharges
Namespace: AWS/Billing
Period: 86400
Stat: Maximum
ReturnData: False
- Id: Expr1
Expression: SUM([m1,m2])
Label: Yeap
Threshold: 100
TreatMissingData: ignore
</code></pre>
<p>The single metrics , m1 and m2 , have to do with the billing cost of EC2 and Cloudwatch service. What I want to check is if the charging cost for these 2 services has crossed the threshold of 100$. (Note that since the billing costs are exclusively stored in the N.Virginia region, I tried to deploy the above template in N.Virginia).
During the deployment of this template Cloudformation responds with the following error:</p>
<pre><code>"Invalid metrics list (Service: AmazonCloudWatch; Status Code: 400; Error Code: ValidationError; Request ID: c0748047-0378-11e9-ac36-5b1829988d18)"
</code></pre>
<p>When Cloudformation says "metrics list" it refers to the definition of m1,m2, Expr1. What is even more strange is that when I use the above metrics-list definition from aws cli the charging data return successfully:</p>
<pre><code>aws cloudwatch get-metric-data --metric-data-queries file://./metric-data.json --start-time 2018-12-03T03:00:00Z --end-time 2018-12-10T04:30:00Z
</code></pre>
<p>,where metric-data.json is the above metrics-list.</p>
<p>For creating my template I used the following guides:
<a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html" rel="noreferrer">https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html</a>
and
<a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricData.html" rel="noreferrer">https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricData.html</a></p>
<p>Do you have any idea why Cloudformation returns this error? Thanks!</p>
| 0debug |
static int mpegps_read_header(AVFormatContext *s)
{
MpegDemuxContext *m = s->priv_data;
char buffer[7];
int64_t last_pos = avio_tell(s->pb);
m->header_state = 0xff;
s->ctx_flags |= AVFMTCTX_NOHEADER;
avio_get_str(s->pb, 6, buffer, sizeof(buffer));
if (!memcmp("IMKH", buffer, 4)) {
m->imkh_cctv = 1;
} else if (!memcmp("Sofdec", buffer, 6)) {
m->sofdec = 1;
} else
avio_seek(s->pb, last_pos, SEEK_SET);
return 0;
}
| 1threat |
print_execve(const struct syscallname *name,
abi_long arg1, abi_long arg2, abi_long arg3,
abi_long arg4, abi_long arg5, abi_long arg6)
{
abi_ulong arg_ptr_addr;
char *s;
if (!(s = lock_user_string(arg1)))
return;
gemu_log("%s(\"%s\",{", name->name, s);
unlock_user(s, arg1, 0);
for (arg_ptr_addr = arg2; ; arg_ptr_addr += sizeof(abi_ulong)) {
abi_ulong *arg_ptr, arg_addr, s_addr;
arg_ptr = lock_user(VERIFY_READ, arg_ptr_addr, sizeof(abi_ulong), 1);
if (!arg_ptr)
return;
arg_addr = tswapl(*arg_ptr);
unlock_user(arg_ptr, arg_ptr_addr, 0);
if (!arg_addr)
break;
if ((s = lock_user_string(arg_addr))) {
gemu_log("\"%s\",", s);
unlock_user(s, s_addr, 0);
}
}
gemu_log("NULL})");
}
| 1threat |
static int decode_type1(GetByteContext *gb, PutByteContext *pb)
{
unsigned opcode, len;
int high = 0;
int i, pos;
while (bytestream2_get_bytes_left(gb) > 0) {
GetByteContext gbc;
while (bytestream2_get_bytes_left(gb) > 0) {
while (bytestream2_get_bytes_left(gb) > 0) {
opcode = bytestream2_get_byte(gb);
high = opcode >= 0x20;
if (high)
break;
if (opcode)
break;
opcode = bytestream2_get_byte(gb);
if (opcode < 0xF8) {
opcode = opcode + 32;
break;
}
i = opcode - 0xF8;
if (i) {
len = 256;
do {
len *= 2;
--i;
} while (i);
} else {
len = 280;
}
do {
bytestream2_put_le32(pb, bytestream2_get_le32(gb));
bytestream2_put_le32(pb, bytestream2_get_le32(gb));
len -= 8;
} while (len && bytestream2_get_bytes_left(gb) > 0);
}
if (!high) {
do {
bytestream2_put_byte(pb, bytestream2_get_byte(gb));
--opcode;
} while (opcode && bytestream2_get_bytes_left(gb) > 0);
while (bytestream2_get_bytes_left(gb) > 0) {
GetByteContext gbc;
opcode = bytestream2_get_byte(gb);
if (opcode >= 0x20)
break;
bytestream2_init(&gbc, pb->buffer_start, pb->buffer_end - pb->buffer_start);
pos = -(opcode | 32 * bytestream2_get_byte(gb)) - 1;
bytestream2_seek(&gbc, bytestream2_tell_p(pb) + pos, SEEK_SET);
bytestream2_put_byte(pb, bytestream2_get_byte(&gbc));
bytestream2_put_byte(pb, bytestream2_get_byte(&gbc));
bytestream2_put_byte(pb, bytestream2_get_byte(&gbc));
bytestream2_put_byte(pb, bytestream2_get_byte(gb));
}
}
high = 0;
if (opcode < 0x40)
break;
bytestream2_init(&gbc, pb->buffer_start, pb->buffer_end - pb->buffer_start);
pos = (-((opcode & 0x1F) | 32 * bytestream2_get_byte(gb)) - 1);
bytestream2_seek(&gbc, bytestream2_tell_p(pb) + pos, SEEK_SET);
bytestream2_put_byte(pb, bytestream2_get_byte(&gbc));
bytestream2_put_byte(pb, bytestream2_get_byte(&gbc));
len = (opcode >> 5) - 1;
do {
bytestream2_put_byte(pb, bytestream2_get_byte(&gbc));
--len;
} while (len && bytestream2_get_bytes_left(&gbc) > 0);
}
len = opcode & 0x1F;
if (!len) {
if (!bytestream2_peek_byte(gb)) {
do {
bytestream2_skip(gb, 1);
len += 255;
} while (!bytestream2_peek_byte(gb) && bytestream2_get_bytes_left(gb) > 0);
}
len += bytestream2_get_byte(gb) + 31;
}
pos = -bytestream2_get_byte(gb);
bytestream2_init(&gbc, pb->buffer_start, pb->buffer_end - pb->buffer_start);
bytestream2_seek(&gbc, bytestream2_tell_p(pb) + pos - (bytestream2_get_byte(gb) << 8), SEEK_SET);
if (bytestream2_tell_p(pb) == bytestream2_tell(&gbc))
break;
if (len < 5 || bytestream2_tell_p(pb) - bytestream2_tell(&gbc) < 4) {
bytestream2_put_byte(pb, bytestream2_get_byte(&gbc));
bytestream2_put_byte(pb, bytestream2_get_byte(&gbc));
bytestream2_put_byte(pb, bytestream2_get_byte(&gbc));
do {
bytestream2_put_byte(pb, bytestream2_get_byte(&gbc));
--len;
} while (len && bytestream2_get_bytes_left(&gbc) > 0);
} else {
bytestream2_put_le32(pb, bytestream2_get_le32(&gbc));
len--;
do {
bytestream2_put_byte(pb, bytestream2_get_byte(&gbc));
len--;
} while (len && bytestream2_get_bytes_left(&gbc) > 0);
}
}
return 0;
}
| 1threat |
Python quest urgent : Write a program that uses a while loop
Process input that uses a sentinel value to indicate the end of input
Write a program that reads a series of numbers from standard input and prints out the sum of those values. A sentinel value of -999 will indicate the end of the input values. Do not include the sentinel value in the sum.
Can anyone help me with this?
This is what i have tried
`user_input = 1
while user_input = -999:
user_input = int(input())`
| 0debug |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.