problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
Each then() should return a value or throw when using Promises : <p>I have a few async methods that I need to wait for completion before I return from the request. I'm using Promises, but I keep getting the error:</p>
<pre><code>Each then() should return a value or throw // promise/always-return
</code></pre>
<p>Why is this happpening? This is my code:</p>
<pre><code>router.get('/account', function(req, res) {
var id = req.user.uid
var myProfile = {}
var profilePromise = new Promise(function(resolve, reject) {
var userRef = firebase.db.collection('users').doc(id)
userRef.get()
.then(doc => { // Error occurs on this line
if (doc.exists) {
var profile = doc.data()
profile.id = doc.id
myProfile = profile
resolve()
} else {
reject(Error("Profile doesn't exist"))
}
})
.catch(error => {
reject(error)
})
})
// More promises further on, which I wait for
})
</code></pre>
| 0debug
|
My video does'nt fit its place : In my HTML code, I have put a video like this :
<video id="video1" controls preload>
<source src="media/interview.mp4" type="video/mp4">
</video>
And the CSS part is :
#video1
{
width:100%;
height: 100%;
}
But, when I play it, it does'nt fit its place, and I have a result like this :
[![Application][1]][1]
Where is the origin of the problem ? How to solve this ?
[1]: https://i.stack.imgur.com/Xyhdm.png
| 0debug
|
How to do flow type annotations for React hooks (useState, etc.)? : <p>How should we be using Flow type annotations with react hooks, such as <code>useState</code>? I've tried searching for some examples of how they should be implemented, but can't find anything. </p>
<p>I tried this:</p>
<pre class="lang-js prettyprint-override"><code>const [allResultsVisible, setAllResultsVisible]: [ boolean, (boolean) => void, ] = useState(false);
</code></pre>
<p>Which doesn't throw any flow related errors, but I'm not sure if this is correct or the best way to annotate the hook. If my attempt isn't correct or the best way, what should I do instead?</p>
| 0debug
|
generation of postscript and merging using fop and java : how to generate PS file using fop and java, i want to merge multiple PS file into a single PS file using java.
I have tried to generate PS file using fop but i am getting font embedded like some hex code such as:
currentfile eexec
743F8413F3636CA85A9FFEFB50B4BB27302A5A63F932884E18BF5153AD36053037D1C6CD04294AF6
A35612DB9108AC8514CB5C4A8469971B75A09F9E662068B0685490EA8C73F2DE2FBBCF85D15AB938
5E529DAB15A40D408002E88D0C107F711BC66BF0F2E92FDDC6B188F91EEB6B86050D5032E6ABCB11
E343C6D795217B5973972E99A9420651ACF3B8FD4CAD1DA4B00642AD077A5B86240F89F2BC011009
CB2CF173FF68E9A88F0018F187D5E036FE8D904F211842FF01AA7CAADDEB9E5A534FA3F90BDB8F6F
FE24F7AC6E7BD0A74CF29EBBA568F06579E7B94525361F129F4F81EE9D544CFEFB99016F6E9A016E
B88F88C24726C9A599025E44462A175261626CE6EBAFB69756CC45D96FA04CF97B4A02B39C9F19C2
877B8CE3851E452934959B271BE3E0B169FC27C16FD23870F5BD117BADD10D56110795B27E4C18B8
FC1D4F2E23D69F032AD8BD2BA0DD229DF0F7531E572FA98036D5B425C4014559DEBFE1A4E7751D76
9A35ED5B80952DCA3908E603FC74D8EAFDCEC4F7485178235EDD900910F0DAFA48A518EBFF47CAE5
DEDDE9F4CD4D7C145E4B251BCBAFE60D78443E0644A37FB449E0FC66563DF4C8A55D73D939F86D1F
1D034B251E7F0EA3F68A549B809EF2C2A2DEAE6BD87BA1911799C6D56B59EA08B6BB183DB097481B
6A3DBEDCAC24C85DD2E082C79227338E9231AD1DF384DB40D108413FFE0DA0192ABE57D70170871C
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
cleartomark
Thanks for help in advance.
| 0debug
|
Why isn't this function displaying cookie? : I have set the cookie using **document.cookie** but I can't read it. I read on w3schools that you can read it by document.cookie, but it's not working. Maybe I've misunderstood this thing, or maybe I'm trying something wrong, I don't know. What's wrong in following code?
Here's my code:
<body>
<button onclick="one()">Set</button>
<button onclick="two()">Read</button>
<script>
function one()
{
document.cookie="user=Vikas; expires=Sun, 18 Dec 2016 12:00:00 UTC";
var r= document.cookie;
return r;
}
function two()
{
var h = one();
var i= h.split(";");
var j= i[0];
alert(j);
}
</script>
</body>
| 0debug
|
static void gen_op_iwmmxt_setpsr_nz(void)
{
TCGv tmp = new_tmp();
gen_helper_iwmmxt_setpsr_nz(tmp, cpu_M0);
store_cpu_field(tmp, iwmmxt.cregs[ARM_IWMMXT_wCASF]);
}
| 1threat
|
Calling sequential on parallel stream makes all previous operations sequential : <p>I've got a significant set of data, and want to call slow, but clean method and than call fast method with side effects on result of the first one. I'm not interested in intermediate results, so i would like not to collect them.</p>
<p>Obvious solution is to create parallel stream, make slow call , make stream sequential again, and make fast call. The problem is, ALL code executing in single thread, there is no actual parallelism.</p>
<p>Example code:</p>
<pre><code>@Test
public void testParallelStream() throws ExecutionException, InterruptedException
{
ForkJoinPool forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors() * 2);
Set<String> threads = forkJoinPool.submit(()-> new Random().ints(100).boxed()
.parallel()
.map(this::slowOperation)
.sequential()
.map(Function.identity())//some fast operation, but must be in single thread
.collect(Collectors.toSet())
).get();
System.out.println(threads);
Assert.assertEquals(Runtime.getRuntime().availableProcessors() * 2, threads.size());
}
private String slowOperation(int value)
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return Thread.currentThread().getName();
}
</code></pre>
<p>If I remove <code>sequential</code>, code executing as expected, but, obviously, non-parallel operation would be call in multiple threads.</p>
<p>Could you recommend some references about such behavior, or maybe some way to avoid temporary collections?</p>
| 0debug
|
Airflow: how to delete a DAG? : <p>I have started the Airflow webserver and scheduled some dags. I can see the dags on web GUI.</p>
<p>How can I delete a particular DAG from being run and shown in web GUI? Is there an Airflow CLI command to do that?</p>
<p>I looked around but could not find an answer for a simple way of deleting a DAG once it has been loaded and scheduled.</p>
| 0debug
|
I want to make a parking fee program by using visual stidio : int min1, min2, won;
printf("parking minutes(분)? ");
scanf("%d", &min1);
min2 = (min1 - 30) % 10;
if (min1 <= 39)
won = 2000;
else
{
if (min2 = 0)
won = 2000 + 1000 * (min1 - 30) % 10;
else
won = 2000 + 1000 * (min1 - min2 - 20) % 10;
}
printf("parking fee: %d", won);
The conditions of this program
1.until 30min, 2000won
2. after 30min, 1000won per 10min
3.max 25000won per a day
4.parking minutes cant be over than 24 hours
I thought that '%' means remainder so i write like that but when i input 52, the results say 5200! I want to make result to be 5000. And i want to know what to do for condition 3&4. What can i do? Should i use 'for' and 'sum'?
| 0debug
|
What will be the value of i and j after the following code is executed? : <p>Why is the value of i = 11 and j = 10 after running the code ? </p>
<pre><code> #include<iostream>
int main()
{
//Put your code here
int i = 10;
int j = i++;
std::cout << i << "\n";
std::cout << j << "\n";
return 0;
}
</code></pre>
| 0debug
|
CONNECTIVITY_CHANGE deprecated in target of Android N : <p>I am getting warning of deprecated declaration of Broadcast Receiver.</p>
<pre><code><!-- NETWORK RECEIVER... -->
<receiver android:name=".utils.NetworkUtils" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</code></pre>
<p><strong>WARNING:</strong></p>
<blockquote>
<p>Declaring a broadcastreceiver for android.net.conn.CONNECTIVITY_CHANGE
is deprecated for apps targeting N and higher. In general, apps should
not rely on this broadcast and instead use JobScheduler or
GCMNetworkManager.</p>
</blockquote>
<p>Is there any other way to use it without deprecated methods?</p>
| 0debug
|
av_cold int ff_fft_init(FFTContext *s, int nbits, int inverse)
{
int i, j, n;
if (nbits < 2 || nbits > 16)
goto fail;
s->nbits = nbits;
n = 1 << nbits;
s->revtab = av_malloc(n * sizeof(uint16_t));
if (!s->revtab)
goto fail;
s->tmp_buf = av_malloc(n * sizeof(FFTComplex));
if (!s->tmp_buf)
goto fail;
s->inverse = inverse;
s->fft_permute = ff_fft_permute_c;
s->fft_calc = ff_fft_calc_c;
#if CONFIG_MDCT
s->imdct_calc = ff_imdct_calc_c;
s->imdct_half = ff_imdct_half_c;
s->mdct_calc = ff_mdct_calc_c;
#endif
if (ARCH_ARM) ff_fft_init_arm(s);
if (HAVE_ALTIVEC) ff_fft_init_altivec(s);
if (HAVE_MMX) ff_fft_init_mmx(s);
for(j=4; j<=nbits; j++) {
ff_init_ff_cos_tabs(j);
}
for(i=0; i<n; i++)
s->revtab[-split_radix_permutation(i, n, s->inverse) & (n-1)] = i;
return 0;
fail:
av_freep(&s->revtab);
av_freep(&s->tmp_buf);
return -1;
}
| 1threat
|
void HELPER(ucf64_cmpd)(float64 a, float64 b, uint32_t c, CPUUniCore32State *env)
{
int flag;
flag = float64_compare_quiet(a, b, &env->ucf64.fp_status);
env->CF = 0;
switch (c & 0x7) {
case 0:
break;
case 1:
if (flag == 2) {
env->CF = 1;
}
break;
case 2:
if (flag == 0) {
env->CF = 1;
}
break;
case 3:
if ((flag == 0) || (flag == 2)) {
env->CF = 1;
}
break;
case 4:
if (flag == -1) {
env->CF = 1;
}
break;
case 5:
if ((flag == -1) || (flag == 2)) {
env->CF = 1;
}
break;
case 6:
if ((flag == -1) || (flag == 0)) {
env->CF = 1;
}
break;
case 7:
if (flag != 1) {
env->CF = 1;
}
break;
}
env->ucf64.xregs[UC32_UCF64_FPSCR] = (env->CF << 29)
| (env->ucf64.xregs[UC32_UCF64_FPSCR] & 0x0fffffff);
}
| 1threat
|
unit test cases for converters in wpf : <p>I have defined a converter in my project. I want to begin with writing unit test case for that converter.</p>
<p>Code for converter is:</p>
<pre><code> public class BirdEyeViewColumnWidthConverter : IValueConverter
{
public int BirdEyeModeWidth { get; set; }
public int DefaultWidth { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
if ((bool) value)
{
return BirdEyeModeWidth;
}
}
return DefaultWidth;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
</code></pre>
<p>How do I start with this? </p>
| 0debug
|
how to fix error of "Cannot assign to property: 'setBarTintGradientColors' is a method" : <p><a href="https://i.stack.imgur.com/iFjgs.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I trying to set Navigationbar gradient colors using CRGradientNavigationBar library. </p>
| 0debug
|
sum in excel until value met and show column header : <p>Hi and thank you in advance.</p>
<p>I want to sum up columns I2 to U2 but when the amount of the sum reaches 15, I want cell Y2 to display the column header, that are held in I1 to U1.</p>
<p><a href="https://i.stack.imgur.com/zpVND.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zpVND.png" alt="enter image description here"></a></p>
| 0debug
|
int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
{
BlockDriverState *bs;
int ret;
bs = bdrv_new("");
if (!bs)
return -ENOMEM;
ret = bdrv_open2(bs, filename, flags | BDRV_O_FILE, NULL);
if (ret < 0) {
bdrv_delete(bs);
return ret;
}
*pbs = bs;
return 0;
}
| 1threat
|
How to call function entity framework : I am trying to call function called connectUser that takes 2 arguments, name and password and returns id (number)
The problem is that it does not work and i am getting "NotSupportedException"
int userID;
[EdmFunction("Model.Store", "connectUser")]
public static int connectUser(String loginName, String loginPass)
{
throw new NotSupportedException("Direct calls are not supported.");
}
private void btnSignIn_Click(object sender, EventArgs e)
{
userID = (Int32)connectUser(loginName.Text, loginPass.Text);
}
any idea what is going on? I tried several tutorials and basing on them it should work while for me it ignores [EdmFunction("Model.Store", "connectUser")]
| 0debug
|
static void raw_invalidate_cache(BlockDriverState *bs, Error **errp)
{
BDRVRawState *s = bs->opaque;
int ret;
assert(!(bdrv_get_flags(bs) & BDRV_O_INACTIVE));
ret = raw_handle_perm_lock(bs, RAW_PL_PREPARE, s->perm, s->shared_perm,
errp);
if (ret) {
return;
}
raw_handle_perm_lock(bs, RAW_PL_COMMIT, s->perm, s->shared_perm, NULL);
}
| 1threat
|
Calling a method from a constructor in python : <p>The initial question I had was whether or not a method could be called from a Python constructor. The answer <a href="https://stackoverflow.com/questions/12646326/calling-a-class-function-inside-of-init">here</a> suggests that it can, but this surprised me some as, based on my reading, python cannot use something that hasn't been previously defined in the code. Looking at the answers in the linked thread, it seems like they are using a method in the constructor that is defined later in the text. How is this possible in python?</p>
<p>Thanks.</p>
| 0debug
|
static inline void *alloc_code_gen_buffer(void)
{
int flags = MAP_PRIVATE | MAP_ANONYMOUS;
uintptr_t start = 0;
size_t size = tcg_ctx.code_gen_buffer_size;
void *buf;
# if defined(__PIE__) || defined(__PIC__)
# elif defined(__x86_64__) && defined(MAP_32BIT)
flags |= MAP_32BIT;
if (size > 800u * 1024 * 1024) {
tcg_ctx.code_gen_buffer_size = size = 800u * 1024 * 1024;
}
# elif defined(__sparc__)
start = 0x40000000ul;
# elif defined(__s390x__)
start = 0x90000000ul;
# elif defined(__mips__)
# if _MIPS_SIM == _ABI64
start = 0x128000000ul;
# else
start = 0x08000000ul;
# endif
# endif
buf = mmap((void *)start, size + qemu_real_host_page_size,
PROT_NONE, flags, -1, 0);
if (buf == MAP_FAILED) {
return NULL;
}
#ifdef __mips__
if (cross_256mb(buf, size)) {
size_t size2;
void *buf2 = mmap(NULL, size + qemu_real_host_page_size,
PROT_NONE, flags, -1, 0);
switch (buf2 != MAP_FAILED) {
case 1:
if (!cross_256mb(buf2, size)) {
munmap(buf, size);
break;
}
munmap(buf2, size);
default:
buf2 = split_cross_256mb(buf, size);
size2 = tcg_ctx.code_gen_buffer_size;
if (buf == buf2) {
munmap(buf + size2 + qemu_real_host_page_size, size - size2);
} else {
munmap(buf, size - size2);
}
size = size2;
break;
}
buf = buf2;
}
#endif
mprotect(buf, size, PROT_WRITE | PROT_READ | PROT_EXEC);
qemu_madvise(buf, size, QEMU_MADV_HUGEPAGE);
return buf;
}
| 1threat
|
Location of MySQL configuration file (ie: my.cnf) not specified : <p>Location of MySQL configuration file (ie: my.cnf) not specified<a href="https://i.stack.imgur.com/cwmtI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cwmtI.png" alt="enter image description here"></a></p>
<p>How can I fixed this thing?
I been trying to reinstall mysqlserver 5.5 / 5.7 and workbench countless of time. But I still not able to fix this issue.</p>
| 0debug
|
static void gen_srq(DisasContext *ctx)
{
int l1 = gen_new_label();
TCGv t0 = tcg_temp_new();
TCGv t1 = tcg_temp_new();
tcg_gen_andi_tl(t1, cpu_gpr[rB(ctx->opcode)], 0x1F);
tcg_gen_shr_tl(t0, cpu_gpr[rS(ctx->opcode)], t1);
tcg_gen_subfi_tl(t1, 32, t1);
tcg_gen_shl_tl(t1, cpu_gpr[rS(ctx->opcode)], t1);
tcg_gen_or_tl(t1, t0, t1);
gen_store_spr(SPR_MQ, t1);
tcg_gen_andi_tl(t1, cpu_gpr[rB(ctx->opcode)], 0x20);
tcg_gen_mov_tl(cpu_gpr[rA(ctx->opcode)], t0);
tcg_gen_brcondi_tl(TCG_COND_EQ, t0, 0, l1);
tcg_gen_movi_tl(cpu_gpr[rA(ctx->opcode)], 0);
gen_set_label(l1);
tcg_temp_free(t0);
tcg_temp_free(t1);
if (unlikely(Rc(ctx->opcode) != 0))
gen_set_Rc0(ctx, cpu_gpr[rA(ctx->opcode)]);
}
| 1threat
|
static inline void gen_check_tlb_flush(DisasContext *ctx) { }
| 1threat
|
static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
{
AVStream *st = c->fc->streams[c->fc->nb_streams-1];
MOVStreamContext *sc = st->priv_data;
unsigned int i, entries;
get_byte(pb);
get_be24(pb);
entries = get_be32(pb);
dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
return -1;
sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
if (!sc->ctts_data)
return AVERROR(ENOMEM);
sc->ctts_count = entries;
for(i=0; i<entries; i++) {
int count =get_be32(pb);
int duration =get_be32(pb);
sc->ctts_data[i].count = count;
sc->ctts_data[i].duration= duration;
}
return 0;
}
| 1threat
|
static int hls_slice_data_wpp(HEVCContext *s, const HEVCNAL *nal)
{
const uint8_t *data = nal->data;
int length = nal->size;
HEVCLocalContext *lc = s->HEVClc;
int *ret = av_malloc_array(s->sh.num_entry_point_offsets + 1, sizeof(int));
int *arg = av_malloc_array(s->sh.num_entry_point_offsets + 1, sizeof(int));
int64_t offset;
int startheader, cmpt = 0;
int i, j, res = 0;
if (!ret || !arg) {
av_free(ret);
av_free(arg);
return AVERROR(ENOMEM);
}
if (s->sh.slice_ctb_addr_rs + s->sh.num_entry_point_offsets * s->ps.sps->ctb_width >= s->ps.sps->ctb_width * s->ps.sps->ctb_height) {
av_log(s->avctx, AV_LOG_ERROR, "WPP ctb addresses are wrong (%d %d %d %d)\n",
s->sh.slice_ctb_addr_rs, s->sh.num_entry_point_offsets,
s->ps.sps->ctb_width, s->ps.sps->ctb_height
);
res = AVERROR_INVALIDDATA;
goto error;
}
ff_alloc_entries(s->avctx, s->sh.num_entry_point_offsets + 1);
if (!s->sList[1]) {
for (i = 1; i < s->threads_number; i++) {
s->sList[i] = av_malloc(sizeof(HEVCContext));
memcpy(s->sList[i], s, sizeof(HEVCContext));
s->HEVClcList[i] = av_mallocz(sizeof(HEVCLocalContext));
s->sList[i]->HEVClc = s->HEVClcList[i];
}
}
offset = (lc->gb.index >> 3);
for (j = 0, cmpt = 0, startheader = offset + s->sh.entry_point_offset[0]; j < nal->skipped_bytes; j++) {
if (nal->skipped_bytes_pos[j] >= offset && nal->skipped_bytes_pos[j] < startheader) {
startheader--;
cmpt++;
}
}
for (i = 1; i < s->sh.num_entry_point_offsets; i++) {
offset += (s->sh.entry_point_offset[i - 1] - cmpt);
for (j = 0, cmpt = 0, startheader = offset
+ s->sh.entry_point_offset[i]; j < nal->skipped_bytes; j++) {
if (nal->skipped_bytes_pos[j] >= offset && nal->skipped_bytes_pos[j] < startheader) {
startheader--;
cmpt++;
}
}
s->sh.size[i - 1] = s->sh.entry_point_offset[i] - cmpt;
s->sh.offset[i - 1] = offset;
}
if (s->sh.num_entry_point_offsets != 0) {
offset += s->sh.entry_point_offset[s->sh.num_entry_point_offsets - 1] - cmpt;
if (length < offset) {
av_log(s->avctx, AV_LOG_ERROR, "entry_point_offset table is corrupted\n");
res = AVERROR_INVALIDDATA;
goto error;
}
s->sh.size[s->sh.num_entry_point_offsets - 1] = length - offset;
s->sh.offset[s->sh.num_entry_point_offsets - 1] = offset;
}
s->data = data;
for (i = 1; i < s->threads_number; i++) {
s->sList[i]->HEVClc->first_qp_group = 1;
s->sList[i]->HEVClc->qp_y = s->sList[0]->HEVClc->qp_y;
memcpy(s->sList[i], s, sizeof(HEVCContext));
s->sList[i]->HEVClc = s->HEVClcList[i];
}
avpriv_atomic_int_set(&s->wpp_err, 0);
ff_reset_entries(s->avctx);
for (i = 0; i <= s->sh.num_entry_point_offsets; i++) {
arg[i] = i;
ret[i] = 0;
}
if (s->ps.pps->entropy_coding_sync_enabled_flag)
s->avctx->execute2(s->avctx, hls_decode_entry_wpp, arg, ret, s->sh.num_entry_point_offsets + 1);
for (i = 0; i <= s->sh.num_entry_point_offsets; i++)
res += ret[i];
error:
av_free(ret);
av_free(arg);
return res;
}
| 1threat
|
Out of stack space (Error 28) VBA : <p>I am trying to convert an old Fortran program with a lot of nested goto statements to VBA but I am getting error mentioned in the title. The way I am converting is each statement, I made it a function and instead of <strong>goto</strong> then i call the function or statement, but apparently that's not a proper way of doing it. What else can I do? Thanks in advance. </p>
| 0debug
|
How to use SED command to get below output in desc? : My input is "INTC_KEY,ABC1|OBJID,ABC2".
And I want to send the output to the file like
DDS.INTC_KEY = REPL.OBJID AND DDS.ABC1 = REPL.ABC2
Thanks,
Eshan
| 0debug
|
def volume_cuboid(l,w,h):
volume=l*w*h
return volume
| 0debug
|
How do I create a 2d array with different starting values in the first row? : <p>I need help learning how to make a 2d array with different starting values in the first row, based on whatever the row is above it I then need it to double.
Like this:</p>
<p>Week pop 1 pop 2 pop 3 pop 4 pop 5</p>
<p>0 10 100 500 1000 5000</p>
<p>1 20 200 1000 2000 10000</p>
<p>and to go 9 weeks</p>
| 0debug
|
Match list of incrementing integers using regex : <p>Is it possible to match a list of comma-separated decimal integers, where the integers in the list always increment by one?</p>
<p>These should match:</p>
<pre><code>0,1,2,3
8,9,10,11
1999,2000,2001
99,100,101
</code></pre>
<p>These should not match (in their entirety - the last two have matching subsequences):</p>
<pre><code>42
3,2,1
1,2,4
10,11,13
</code></pre>
| 0debug
|
JSX props should not use .bind() : <p>How to fix this error when I have the binding this way: previously binding in constructor solved but this is bit complex for me:</p>
<pre><code> {this.onClick.bind(this, 'someString')}>
and
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
</code></pre>
| 0debug
|
How to assign $_GET value via 'a href' : <p>This is what I've done so far, but the $_GET['c_id'] is not assigned (URL looks like this <code>http://localhost/srs_stuff.php?c_id=</code>
Results are surely stored in $r variable since c_name is normally displayed as clickable link with the name I want.</p>
<pre><code>foreach ($results as $r) {
echo "<a href='srs_stuff.php?c_id='" . $r['c_id'] . ">" . $r['c_name'] . "</a></br>";
}
</code></pre>
<p>Even better solution would be, that the c_id would be set in SESSION variable, before redirection to new page. Is this possible?</p>
| 0debug
|
How to have ruby pick randomly from an array : <p>Im pretty new to programming and I'm trying to make a basic rock paper scissors program.</p>
<p>I've already made this program using 1 = rock, 2 = paper, 3 = scissors. but now I want to try doing it with actual words instead of numbers. How can I make ruby choose randomly from my array, mine?</p>
<p>Thanks!</p>
<pre><code>mine = ["Rock", "Paper", "Scissors"]
mine.sample(1 + rand(mine.count))
puts 'Write your choice, Rock, Paper, or Scissors'
yours = gets.chomp.to_s
if yours == "Rock"
puts 'Your choice is Rock'
elsif yours == "Paper"
puts 'Your choice is Paper'
else yours == "Scissors"
puts 'Your choice is Scissors'
end
puts "--------------------------"
if mine == "Rock"
puts 'Computer: My choice is Rock'
elsif mine == "Paper"
puts 'Computer: My choice is Paper'
else mine == "Scissors"
puts 'Computer: My choice is Scissors'
end
print 'Computer: My choice was: '
print mine
puts
if mine == "Rock" && yours == "Paper"
puts "==========="
puts "Paper Wins!"
puts "==========="
elsif mine == "Paper" && yours == "Rock"
puts "==========="
puts "Paper Wins!"
puts "==========="
elsif mine == "Paper" && yours == "Scissors"
puts "=============="
puts "Scissors Wins!"
puts "=============="
elsif mine == "Scissors" && yours == "Paper"
puts "=============="
puts "Scissors Wins!"
puts "=============="
elsif mine == "Scissors" && yours == "Rock"
puts "=========="
puts "Rock Wins!"
puts "=========="
elsif mine == "Rock" && yours == "Scissors"
puts "=============="
puts "Rock Wins!"
puts "=============="
else
puts "======================"
puts "It's a tie! TRY AGAIN!"
puts "======================"
end
</code></pre>
| 0debug
|
return the int result of sql query to php echo? : A little help would be lifesaving. I have an sql query that works in phpMyAdmin and gives me the result i need.
When i build this query into a php statement i cant seem to access the result (an integer)
I literally need to echo the value, so i need to output for exanmple " your number is" result.
here is my query:
$sqlstatement = "SELECT (SELECT `embark` FROM info ORDER BY `index_no` DESC LIMIT 1)-(SELECT `embark` FROM info ORDER BY `index_no` ASC LIMIT 1)";
$sql_result = mysqli_query($connection, $sqlstatement) or die
(" Couldn't execute the SQL calculate disembark statement********");
If anyone can help i would really appreciate it
Scott
| 0debug
|
static bool e1000_mit_state_needed(void *opaque)
{
E1000State *s = opaque;
return s->compat_flags & E1000_FLAG_MIT;
}
| 1threat
|
How can i print a alert message inside ajax other than using alert function : <p>How can i print a alert message inside ajax other than using alert function.</p>
<pre><code>if (x.readyState == 4 && x.status == 200)
{
var msg=x.responseText.trim();
if(msg=="Thank you for booking and Have a nice Journey!!!")
{
alert("Successfully submitted");
window.location="home.html";
}
}
</code></pre>
| 0debug
|
static int handle_primary_tcp_pkt(NetFilterState *nf,
Connection *conn,
Packet *pkt)
{
struct tcphdr *tcp_pkt;
tcp_pkt = (struct tcphdr *)pkt->transport_header;
if (trace_event_get_state_backends(TRACE_COLO_FILTER_REWRITER_DEBUG)) {
trace_colo_filter_rewriter_pkt_info(__func__,
inet_ntoa(pkt->ip->ip_src), inet_ntoa(pkt->ip->ip_dst),
ntohl(tcp_pkt->th_seq), ntohl(tcp_pkt->th_ack),
tcp_pkt->th_flags);
trace_colo_filter_rewriter_conn_offset(conn->offset);
}
if (((tcp_pkt->th_flags & (TH_ACK | TH_SYN)) == TH_SYN)) {
conn->syn_flag = 1;
}
if (((tcp_pkt->th_flags & (TH_ACK | TH_SYN)) == TH_ACK)) {
if (conn->syn_flag) {
conn->offset -= (ntohl(tcp_pkt->th_ack) - 1);
conn->syn_flag = 0;
}
if (conn->offset) {
tcp_pkt->th_ack = htonl(ntohl(tcp_pkt->th_ack) + conn->offset);
net_checksum_calculate((uint8_t *)pkt->data, pkt->size);
}
}
return 0;
}
| 1threat
|
Optional Chaining Operator in Typescript : <p>In javascript, Optional Chaining Operator is supported by the <a href="https://www.npmjs.com/package/babel-plugin-transform-optional-chaining" rel="noreferrer">babel plugin</a>. </p>
<p>But I can't find how to do this in Typescript. Any idea?</p>
| 0debug
|
Web API Controller method executes to end. No HTTP response. Hang : I am looking for an approach to debugging this scenario. I have verified in Fiddler that there is no HTTP response at all. To be clear, as I understand it a controller method should not simply hang, there is no exception. I have verified the lack of response in Fiddler. The method returns a valid object, verified by stepping through the code to the final return statement. If you are one of the previous down voters, I ask you to explain yourself since this is a valid question; please *think* before downvoting. - not a rookie
| 0debug
|
What does this regex do in terms of password validation? : <p>I inherited a project and have no idea what this does:</p>
<pre><code>/\d/.test(password)
</code></pre>
<p>Any ideas?</p>
| 0debug
|
Need to insert a worksheet into the body of an email but NOT send it. : I have a worksheet ("WC Referral Notice") that I need to put into the body of an email, but NOT send it immediately since I need to browse and attach several documents to the email before it is sent. I found macros to send it in the body of the email but it's sent as soon as you click. And I've also found macros to attach the workbook as an attachment. Neither of those are exactly what I'm looking for.
| 0debug
|
Python efficiency optimization : PROBLEM: given a list consisting of 1 to 50 integers in the range of -1000 to 1000, calculate the maximum product of one or any number of integers within the list given.
My Approach:
import itertools
def answer(xs):
cur = 1
dal = []
for i in range(len(xs), 0, -1):
for j in itertools.combinations(xs, i):
for x in j:
cur *= x
dal.append(cur)
cur = 1
dal.sort(reverse=True)
return str(dal[0])
Results/What I want to achieve: The results timed out. I want to optimize the structure of the procedure to be as efficient as possible and will need your help. Thanks in advance.
| 0debug
|
how do i find the sum of elements in an array in Java script? : <p>I have to find the sum of the elements inside an array. The array has 5 elements. Please help, im just learning java script and this simple question has been bugging me!</p>
| 0debug
|
does not contain a definition for " " and no extension method accepting a first argument : <pre><code>i am having trouble with my set and gets in my test class. it says it does not
</code></pre>
<p>contain a definition for ______ and no extension method accepting a first argument. i have read similar problems but i can not fix these errors. how can i fix this? Specifically it says my Car class does not contain a definition </p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Homework1
{
class Car
{
private string color;
private int numOfWheels;
private int startingPoint;
private int mileage;
private int currentSpeed;
public Car()
{
color = "";
NumOfWheels = 4;
StartingPoint = 100000;
CurrentSpeed = 0;
Mileage = 0;
}
public Car(string color, int numOfWheels, int startingPoint, int currentSpeed, int mileage)
{
Color = color;
NumOfWheels = numOfWheels;
StartingPoint = startingPoint;
CurrentSpeed = currentSpeed;
Mileage = mileage;
}
public virtual string Color
{
get
{
return color;
}
set
{
color = value;
}
}
public virtual int NumOfWheels
{
get
{
return numOfWheels;
}
set
{
numOfWheels = value;
}
}
public virtual int StartingPoint
{
get
{
return startingPoint;
}
set
{
startingPoint = value;
}
}
public virtual int CurrentSpeed
{
get
{
return currentSpeed;
}
set
{
currentSpeed = value;
}
}
public virtual int Mileage
{
get
{
return mileage;
}
set
{
mileage = value;
}
}
public override string ToString()
{
return (" color " + color + " numOfWheels" + numOfWheels + "startingPoint " + startingPoint + "mileage" + mileage + "current speed" + currentSpeed);
}
}
}
********************************************************************************
///this is the test program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Homework1
{
class CarTest
{
static void Main(string[] args)
{
Car myCar = new Car();
Console.WriteLine("*****************************");
Console.WriteLine("* *");
Console.WriteLine("* WELCOME TO CAR MANAGER *");
Console.WriteLine("* By <<my Name>> *");
Console.WriteLine("* *");
Console.WriteLine("*****************************");
Console.WriteLine("\nEnter the number of wheels of a car");
int numOfWheels = Console.Read();
myCar.setNumOfWheels(numOfWheels);
Console.WriteLine("Enter the color of the car");
String color = Console.ReadLine();
Console.WriteLine("Current mileage will be set to zero");
Console.WriteLine("The current starting point will be set to 100000");
Console.Write("The current status of your car \n{0:D} Wheels, \n{1}, \n{2:D} Miles and \nCAR POINT = {3:D}", myCar.getNumOfWheels,
myCar.getColor, myCar.getMileage, myCar.getStartingPoint);
Console.WriteLine("\nEnter the owner's name");
String name = Console.ReadLine();
Console.WriteLine("Enter the miles the car ran in this week");
int milesThisWeek = Console.ReadLine();
myCar.setMileage(Mileage);
Console.WriteLine("This car is owned by n{1}", name);
Console.WriteLine("===>The current status of your car:");
Console.WriteLine("Wheels: " + myCar.getWheels());
Console.WriteLine("Color: " + myCar.getColor());
Console.WriteLine("Current Mileage: " + myCar.getMileage());
Console.WriteLine("Starting Point: " + myCar.getStartingPoint());
Console.WriteLine("************ Thank you for using CAR MANAGER *************");
Console.WriteLine("----------------------------------------------------------");
Console.WriteLine("----------------------------------------------------------");
Console.WriteLine("Press ENTER to close console…….");
}
}
}
</code></pre>
| 0debug
|
My instance is not updating in my while loop : <p>I want to recalculate the hash by changing the nonce by 1. but the instance of self.hash is not changing. </p>
<p>I am not that experienced and do not know how to fix these types of issues</p>
<pre><code>import hashlib
class Block:
def __init__(self, timestamp, transaction, previousHash = ''):
self.timestamp = timestamp
self.transaction = transaction
self.nonce = 0
self.previousHash = previousHash
self.hash = self.calculateHash()
def mineBlock(self):
checkIfTrue = str(self.hash).startswith('0')
while checkIfTrue != True:
self.nonce += 1
self.hash = self.calculateHash()
print(self.hash)
print("block mined")
def calculateHash(self):
h = hashlib.sha256((str(self.timestamp) + str(self.transaction) + str(self.previousHash) + str(self.nonce)).encode('utf-8'))
return h.hexdigest()
</code></pre>
| 0debug
|
How to implement push notification for iOS 10[Objective C]? : <p>Can anyone help me with implementing push notification for iOS 10 as i have implemented following code but still getting problem in it:</p>
<pre><code>#define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
if(SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(@"10.0"))
{
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
if(!error){
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
}];
}
else {
// Code for old versions
}
</code></pre>
<p>I am getting error suggesting that </p>
<blockquote>
<p>Unknown receiver UIUserNotificationCenter</p>
</blockquote>
<p>Thank you in advance!</p>
| 0debug
|
About Initializing Pointers in C++ : <p>I've been reading C++ Primer 5th edition. It mentions that </p>
<blockquote>
<p>It is illegal to assign an int variable to a pointer, even if the variable’s value happens to be 0.</p>
</blockquote>
<p>I give it a try, and find the following result:</p>
<pre><code>int *u = 0; // success
int *w = 123; // fail
/* compile error:
ptr_test.cc:9:12: error: invalid conversion from 'int' to 'int*' [-fpermissive]
int *w = 123;
*/
int zero = 0;
int *v = zero; // fail
/* compile error
ptr_test.cc:9:12: error: invalid conversion from 'int' to 'int*' [-fpermissive]
int *w = zero;
*/
</code></pre>
<p>Can someone help me explain the exact rule of pointer initialization?
Why assigning to a int pointer to 0 is fine, but 123 is not ok, though they are both integer? Why does 123 result in a to "*int" cast, while 0 does not?</p>
<p>BTW, I'm using g++ (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0.</p>
| 0debug
|
I dont know why there is an Object Variable or With-blockvariable missing? : Please help I dont know why ther is an Objekt variable or With-bock varaible missing [In the Picture is the Problem (in German) and the Code ][1]
I have all ready googled if I could find anything in the Internet but I didn't
[1]: https://i.stack.imgur.com/QovY7.png
| 0debug
|
SQL:How return regularity N rows in Oracle? : I want to return follow result:
num random month char
1 33 Jan a
2 76 Feb b
3 784 Mar c
4 53 Apr d
5 34 May e
Now [I only know how return num and random row][1].
SELECT LEVEL num, dbms_random.RANDOM random
FROM DUAL
CONNECT BY LEVEL <= 5
[1]: http://stackoverflow.com/questions/1973676/sql-query-to-return-n-rows-from-dual
| 0debug
|
How can I clear a model created with Keras and Tensorflow(as backend)? : <p>I have a problem when training a neural net with Keras in Jupyter Notebook. I created a sequential model with several hidden layers. After training the model and saving the results, I want to delete this model and create a new model in the same session, as I have a <code>for</code> loop that checks the results for different parameters. But as I understand the errors I get, when changing the parameters, when I loop over, I am just adding layers to the model (even though I initialise it again with <code>network = Sequential()</code> inside the loop). So my question is, how can I completely clear the previous model or how can I initialise a completely new model in the same session?</p>
| 0debug
|
gradle external class required by plugin on runtime : Gents,
I'm creating custom gradle plugin for internal company use. It will add few tasks to project and behaviour of one task can be customized by plugin users. Idea is to have plugin property that will contain external class name. This class must implement appropriate interface to be correctly used. Plugin's task will instantiate objects for this class and use it during execution.
Reasons for that - there are several reasonably different patterns used by different teams in company. So set of these "external classes" will be created and published. Each team can choose which one to use for their build configuration. Or even can create a new one if there are reasons for that. So I want this thing to be configurable on a build level.
I'm failing to setup this kind of dependency in build.gradle script. Let me show you code on whicn I'm trying to reproduce and solve issue:
buildscript{
repositories {
mavenCentral()
maven{
url "http://our-internal-nexus/repository/maven-releases/"
}
dependencies{
classpath 'my.company:myplugin:0.1'
classpath 'my.other.company:extClass:0.1'
}
}
}
apply plugin: 'my.company.myplugin'
MyInput{
managerClass = "ExtClass"
}
myplugin - artifact of my plugin, and extclass - external class that should be instantiated by plugin's task.
When I try to execute plugins task: *gradle hellotask* I receive error: java.lang.ClassNotFoundException: ExtClass
I put a code to hellotask class definition to show me the classpath. The only thing it shows is C:/work/Projects/development/gradle-4.0.1/lib/gradle-launcher-4.0.1.jar. So for me it looks like no path to extClass jar provided by gradle to plugin in runtime so it can't find it.
Appreciate any help how to make it work. Below you can find source code of plugin and extClass if this may help.
**MyPlugin**
MyPlugin.java
package my.company;
import org.gradle.api.*;
//Plugin definition
public class MyPlugin implements Plugin<Project>{
@Override
public void apply(Project project){
project.getExtensions().create("MyInput", MyPluginExtension.class);
HelloTask helloTask = project.getTasks().create("helloTask", HelloTask.class);
}
}
HelloTask.java
package my.company;
import java.net.URL;
import java.net.URLClassLoader;
import org.gradle.api.*;
import org.gradle.api.tasks.*;
//Plugin task
public class HelloTask extends DefaultTask {
@TaskAction
public void action() {
//Print classpath
ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();
for(int i=0; i< urls.length; i++) {
System.out.println(urls[i].getFile());
}
//Try to instantiate class
try {
MyPluginExtension extension = getProject().getExtensions().findByType(MyPluginExtension.class);
Object instance = Class.forName(extension.getManagerClass()).newInstance();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
throw new GradleException("Class not found");
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new GradleException("IllegalAccessException");
} catch (InstantiationException e) {
e.printStackTrace();
throw new GradleException("InstantiationException");
}
}
}
MyPluginExtension.java
package my.company;
public class MyPluginExtension {
private String managerClass = null;
public String getManagerClass(){return this.managerClass;}
public void setManagerClass(String managerClass){ this.managerClass = managerClass;}
}
**extClass**
extClass.java
package my.other.company;
public class ExtClass {
public void ExtClass(){
System.out.println("Show me how it works!");
}
}
| 0debug
|
static void calculate_code_lengths(uint8_t *lengths, uint32_t *counts)
{
uint32_t nr_nodes, nr_heap, node1, node2;
int i, j;
int32_t k;
uint32_t weights[512];
uint32_t heap[512];
int32_t parents[512];
for (i = 0; i < 256; i++)
weights[i + 1] = (counts[i] ? counts[i] : 1) << 8;
nr_nodes = 256;
nr_heap = 0;
heap[0] = 0;
weights[0] = 0;
parents[0] = -2;
for (i = 1; i <= 256; i++) {
parents[i] = -1;
heap[++nr_heap] = i;
up_heap(nr_heap, heap, weights);
}
while (nr_heap > 1) {
node1 = heap[1];
heap[1] = heap[nr_heap--];
down_heap(nr_heap, heap, weights);
node2 = heap[1];
heap[1] = heap[nr_heap--];
down_heap(nr_heap, heap, weights);
nr_nodes++;
parents[node1] = parents[node2] = nr_nodes;
weights[nr_nodes] = add_weights(weights[node1], weights[node2]);
parents[nr_nodes] = -1;
heap[++nr_heap] = nr_nodes;
up_heap(nr_heap, heap, weights);
}
for (i = 1; i <= 256; i++) {
j = 0;
k = i;
while (parents[k] >= 0) {
k = parents[k];
j++;
}
lengths[i - 1] = j;
}
}
| 1threat
|
Aligning text in input text field little further away to the right : <p><a href="https://i.stack.imgur.com/SYzGF.jpg" rel="nofollow noreferrer">enter image description here</a></p>
<p>How can I align my placeholder text toward the right side? Please help!</p>
| 0debug
|
How to run sql multi line queries in php? : <p>I want to run the following sql code in php and store the result in a variable:</p>
<pre><code>declare @d1 datetime, @d2 datetime
select @d1 = '9/9/2011', @d2 = '9/18/2011'
select datediff(dd, @d1, @d2) - (datediff(wk, @d1, @d2) * 2) -
case when datepart(dw, @d1) = 1 then 1 else 0 end +
case when datepart(dw, @d2) = 1 then 1 else 0 end
</code></pre>
<p>Any help would be appreciated. Thanks!</p>
| 0debug
|
Calendar get date and check difference two date : <p>I used the <code>Calendar.getInstance().get(Calendar.DATE)</code> to get current date. <br> So the output is today (2018/05/14).
I change the device time to <code>2018/06/17</code>. So I use the <code>Calendar</code> get the date. I got the <code>17</code>.<br>
My question is I want to get <code>05/15</code> <code>05/16</code> .... <code>06/01</code> ... <code>0616</code> these two days. I need to know all the difference days.<br>
So I don't know which function can do this.</p>
| 0debug
|
static void coroutine_fn qed_co_pwrite_zeroes_cb(void *opaque, int ret)
{
QEDWriteZeroesCB *cb = opaque;
cb->done = true;
cb->ret = ret;
if (cb->co) {
qemu_coroutine_enter(cb->co, NULL);
}
}
| 1threat
|
is it possible to check in html that internet is connected? : <p>I am creating a webview. My apps displaying my folder link when internet connection is off.</p>
<p>Is it possible to check in html that internet is connected/not connected and displayed manual messages ? i want to hidden error in mobile browser like as.</p>
<pre><code>The webpage at http://www.example.com could not be loaded as :
net:: ERR_NAME_NOT_RESOLVED
</code></pre>
| 0debug
|
Change the browser's Date/time value using chrome extension : <p>I'm looking for a way to change the value returned from javascript's <code>new Date()</code> function.<br>
In general - I'm looking for a way to write an extension that will give the user the ability to set his timezone (or diff from the time of his system's clock) without changing time/timezone on his computer.</p>
<p>I checked the <a href="https://developer.chrome.com/extensions/api_index" rel="noreferrer">chrome extension api</a> but found nothing there. Will appreciate it if someone can point me at the right direction.</p>
| 0debug
|
How can I let something happen a certain percentage of the time? (Javascript) : <p>I'm a noob at javascript, sorry if this is a dumb question.
I want something to happen a certain % of the time.</p>
<p>So if a user clicks a button, x% of the time situation A will happen (Let's call this succes) and the other times situation B will happen.</p>
<p>The thing is, that the more user succeeds, the more % chance the user should have of succeeding the next time.</p>
<p>Any ideas?</p>
| 0debug
|
static always_inline void gen_op_arith_compute_ca(DisasContext *ctx, TCGv arg1, TCGv arg2, int sub)
{
int l1 = gen_new_label();
#if defined(TARGET_PPC64)
if (!(ctx->sf_mode)) {
TCGv t0, t1;
t0 = tcg_temp_new(TCG_TYPE_TL);
t1 = tcg_temp_new(TCG_TYPE_TL);
tcg_gen_ext32u_tl(t0, arg1);
tcg_gen_ext32u_tl(t1, arg2);
if (sub) {
tcg_gen_brcond_tl(TCG_COND_GTU, t0, t1, l1);
} else {
tcg_gen_brcond_tl(TCG_COND_GEU, t0, t1, l1);
}
} else
#endif
if (sub) {
tcg_gen_brcond_tl(TCG_COND_GTU, arg1, arg2, l1);
} else {
tcg_gen_brcond_tl(TCG_COND_GEU, arg1, arg2, l1);
}
tcg_gen_ori_tl(cpu_xer, cpu_xer, 1 << XER_CA);
gen_set_label(l1);
}
| 1threat
|
static int SocketAddress_to_str(char *dest, int max_len,
const char *prefix, SocketAddress *addr,
bool is_listen, bool is_telnet)
{
switch (addr->type) {
case SOCKET_ADDRESS_KIND_INET:
return snprintf(dest, max_len, "%s%s:%s:%s%s", prefix,
is_telnet ? "telnet" : "tcp", addr->u.inet->host,
addr->u.inet->port, is_listen ? ",server" : "");
break;
case SOCKET_ADDRESS_KIND_UNIX:
return snprintf(dest, max_len, "%sunix:%s%s", prefix,
addr->u.q_unix->path, is_listen ? ",server" : "");
break;
case SOCKET_ADDRESS_KIND_FD:
return snprintf(dest, max_len, "%sfd:%s%s", prefix, addr->u.fd->str,
is_listen ? ",server" : "");
break;
default:
abort();
}
}
| 1threat
|
How can I allow all classes within a project access to a form? : I am currently desigining a project with a windows form. I am also creating classes that I want to interact with this form. Instead of passing through the form to each object I create, is there a way to allow any class to interact with the form. This is mainly for debugging purposes, I only want access to the textboxes. At the moment I have to do this:
Dim x as new MyClass(Me)
where the me refers to the form I instantiate MyClass in. This means I need to assign a variable the form in the Sub New of the MyClass (creating a new instance of the form is not helpful).
Within the class I access other classes. If there was a way to interact with my form without the need to constantly pass it forward, it would be great.
Thanks.
| 0debug
|
const ppc_def_t *kvmppc_host_cpu_def(void)
{
uint32_t host_pvr = mfpvr();
const ppc_def_t *base_spec;
ppc_def_t *spec;
uint32_t vmx = kvmppc_get_vmx();
uint32_t dfp = kvmppc_get_dfp();
base_spec = ppc_find_by_pvr(host_pvr);
spec = g_malloc0(sizeof(*spec));
memcpy(spec, base_spec, sizeof(*spec));
alter_insns(&spec->insns_flags, PPC_ALTIVEC, vmx > 0);
alter_insns(&spec->insns_flags2, PPC2_VSX, vmx > 1);
alter_insns(&spec->insns_flags2, PPC2_DFP, dfp);
return spec;
}
| 1threat
|
how to print function-returned values in python : I have the following function:
import pandas as pd
def foo():
d1 = {'data1': ['A', 'B', 'C']}
d2 = {'data2': [20, 30, 40]}
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)
return df1, df2
df1, df2 = foo()
I am trying to get the following:
Results for df1:
data1
A
B
C
Results for df2:
data2
20
30
40
I tried some code below but didn't get me what I want (shows index, datatype and not very well aligned):
c = {'results for df1': df1,
'results for df2': df2
}
for a, b in c.items():
print(a, b)
| 0debug
|
aws cli: ERROR:root:code for hash md5 was not found : <p>When trying to run the AWS CLI, I am getting this error:</p>
<pre><code>aws
ERROR:root:code for hash md5 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type md5
ERROR:root:code for hash sha1 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha1
ERROR:root:code for hash sha224 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha224
ERROR:root:code for hash sha256 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha256
ERROR:root:code for hash sha384 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha384
ERROR:root:code for hash sha512 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha512
Traceback (most recent call last):
File "/usr/local/bin/aws", line 19, in <module>
import awscli.clidriver
File "/usr/local/lib/python2.7/site-packages/awscli/clidriver.py", line 17, in <module>
import botocore.session
File "/usr/local/lib/python2.7/site-packages/botocore/session.py", line 29, in <module>
import botocore.configloader
File "/usr/local/lib/python2.7/site-packages/botocore/configloader.py", line 19, in <module>
from botocore.compat import six
File "/usr/local/lib/python2.7/site-packages/botocore/compat.py", line 25, in <module>
from botocore.exceptions import MD5UnavailableError
File "/usr/local/lib/python2.7/site-packages/botocore/exceptions.py", line 15, in <module>
from botocore.vendored import requests
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/__init__.py", line 58, in <module>
from . import utils
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/utils.py", line 26, in <module>
from .compat import parse_http_list as _parse_list_header
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/compat.py", line 7, in <module>
from .packages import chardet
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/packages/__init__.py", line 3, in <module>
from . import urllib3
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/packages/urllib3/__init__.py", line 10, in <module>
from .connectionpool import (
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/packages/urllib3/connectionpool.py", line 31, in <module>
from .connection import (
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/packages/urllib3/connection.py", line 45, in <module>
from .util.ssl_ import (
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/packages/urllib3/util/__init__.py", line 5, in <module>
from .ssl_ import (
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/packages/urllib3/util/ssl_.py", line 2, in <module>
from hashlib import md5, sha1, sha256
ImportError: cannot import name md5
</code></pre>
<p>I tried the solution from <a href="https://stackoverflow.com/questions/59269208/errorrootcode-for-hash-md5-was-not-found-not-able-to-use-any-hg-mercurial-co">this issue</a> but they do not work:</p>
<pre><code>brew reinstall python@2
==> Reinstalling python@2
Error: An exception occurred within a child process:
FormulaUnavailableError: No available formula with the name "/usr/local/opt/python@2/.brew/python@2.rb"
</code></pre>
<p>I thought it might not be installed, but it already is:</p>
<pre><code>brew install python@2
Warning: python@2 2.7.15_1 is already installed and up-to-date
To reinstall 2.7.15_1, run `brew reinstall python@2`
</code></pre>
<p>Running <code>brew doctor</code> shows that <code>python</code> is unliked, but running <code>brew link python</code> fails because of a symlink belonging to <code>python@2</code>.</p>
<pre><code>brew link python
Linking /usr/local/Cellar/python/3.7.6_1...
Error: Could not symlink Frameworks/Python.framework/Headers
Target /usr/local/Frameworks/Python.framework/Headers
is a symlink belonging to python@2. You can unlink it:
brew unlink python@2
To force the link and overwrite all conflicting files:
brew link --overwrite python
To list all files that would be deleted:
brew link --overwrite --dry-run python
</code></pre>
<p>The commands recommended seem to go in circle and none of them manage to solve the issue. I am a bit stuck - how do I recover from these errors?</p>
| 0debug
|
alert('Hello ' + user_input);
| 1threat
|
Remove NA values in R : <p>How can I remove rows which include NA values in a subset of columns?</p>
<p>For the following data.frame, I want to remove rows which have NA in both columns ID1 and ID2:</p>
<pre><code>name ID1 ID2
a NA NA
b NA 2
c 3 NA
</code></pre>
<p>I want to receive this one:</p>
<pre><code>name ID1 ID2
b NA 2
c 3 NA
</code></pre>
| 0debug
|
Separate frontend and backend with Heroku : <p>I have an application, let's call it derpshow, that consists of two repositories, one for the frontend and one for the backend. </p>
<p>I would like to deploy these using Heroku, and preferably on the same domain. I would also like to use pipelines for both parts separate, with a staging and production environment for each.</p>
<p>Is it possible to get both apps running on the same domain, so that the frontend can call the backend on <code>/api/*</code>? Another option would be to serve the backend on <code>api.derpshow.com</code> and the frontend on <code>app.derpshow.com</code> but that complicates security somewhat.</p>
<p>What are the best practices for this? The frontend is simply static files, so it could even be served from S3 or similar, but I still need the staging and production environments and automatic testing and so and so forth.</p>
<p>Any advice is greatly appreciated!</p>
| 0debug
|
After encryption using RSA algorithm, what will be the size of 1 mb file : <p>I am developing an android app and in it I want to use encryption. Basically I want to encrypt files for the purpose but I'm afraid that encryption will increase the size of the file. So can you guyz please help me by telling me that if I encrypt a 1 MB of file what will its size be after encryption. I will be using java for programming.</p>
| 0debug
|
static gboolean gd_scroll_event(GtkWidget *widget, GdkEventScroll *scroll,
void *opaque)
{
VirtualConsole *vc = opaque;
InputButton btn;
if (scroll->direction == GDK_SCROLL_UP) {
btn = INPUT_BUTTON_WHEEL_UP;
} else if (scroll->direction == GDK_SCROLL_DOWN) {
btn = INPUT_BUTTON_WHEEL_DOWN;
} else {
return TRUE;
}
qemu_input_queue_btn(vc->gfx.dcl.con, btn, true);
qemu_input_event_sync();
qemu_input_queue_btn(vc->gfx.dcl.con, btn, false);
qemu_input_event_sync();
return TRUE;
}
| 1threat
|
Looping through HTML table with javascript/jquery : I am struggling to figure out how to loop through a table in HTML.
I have a 2D javascript object that I would like to populate cells with `index i,j` from `myObject[i][j]`. I have a basic html table template but with blank `<td></td>` tags. I have looked at ways to do it in jquery and javascript, but to no avail.
Any help would be greatly appreciated.
| 0debug
|
ngx-translate/core "Error: No provider for HttpClient!" : <p>I've downloaded the package ngx-translate/core, and been following the documentation instructions.</p>
<p>I can't get the translation to work.
The steps i made:</p>
<p>1] define everything in the AppModule</p>
<pre><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { TranslateModule } from '@ngx-translate/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { routing } from './app.routes';
import { AppComponent } from './app.component';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
routing,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
<p>2] define everything in AppComponent</p>
<pre><code>import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: []
})
export class AppComponent {
param = { value: 'world' };
constructor(private router: Router, translate: TranslateService) {
// this language will be used as a fallback when a translation isn't found in the current language
translate.setDefaultLang('en');
// the lang to use, if the lang isn't available, it will use the current loader to get them
translate.use('en');
}
}
</code></pre>
<p>3] the html</p>
<pre><code><div>{{ 'HELLO' | translate:param }}</div>
</code></pre>
<p>4] And finally created in the assets/i18n/en.json</p>
<pre><code>{
"HELLO": "Hi There"
}
</code></pre>
<p>I keep getting these errors in the screen shot below
<a href="https://i.stack.imgur.com/1C5Hn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1C5Hn.png" alt="Errors the popup in the browser console"></a></p>
<p>What am i doing wrong ?</p>
| 0debug
|
iframe in PHP does not work :
The following code in a PHP script used to work. But now it does not work any more. I tried with the URL directly and it works well. I replaced the URL with something else it works too. I could not figure out what could go wrong. Any ideas? thanks.
<iframe
src="http://www.pathwaycommons.org/pc/webservice.do?version=3.0&q=TP53&format=html&cmd=get_by_keyword&snapshot_id=GLOBAL_FILTER_SETTINGS&record_type=PATHWAY"
WIDTH="100%"
HEIGHT="600"
MARGINWIDTH=0
MARGINHEIGHT=0
FRAMEBORDER="NO"
SCROLLING="AUTO"
></iframe>
| 0debug
|
static int img_snapshot(int argc, char **argv)
{
BlockDriverState *bs;
QEMUSnapshotInfo sn;
char *filename, *snapshot_name = NULL;
int c, ret = 0, bdrv_oflags;
int action = 0;
qemu_timeval tv;
bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
for(;;) {
c = getopt(argc, argv, "la:c:d:h");
if (c == -1) {
break;
}
switch(c) {
case '?':
case 'h':
help();
return 0;
case 'l':
if (action) {
help();
return 0;
}
action = SNAPSHOT_LIST;
bdrv_oflags &= ~BDRV_O_RDWR;
break;
case 'a':
if (action) {
help();
return 0;
}
action = SNAPSHOT_APPLY;
snapshot_name = optarg;
break;
case 'c':
if (action) {
help();
return 0;
}
action = SNAPSHOT_CREATE;
snapshot_name = optarg;
break;
case 'd':
if (action) {
help();
return 0;
}
action = SNAPSHOT_DELETE;
snapshot_name = optarg;
break;
}
}
if (optind >= argc) {
help();
}
filename = argv[optind++];
bs = bdrv_new_open(filename, NULL, bdrv_oflags);
if (!bs) {
return 1;
}
switch(action) {
case SNAPSHOT_LIST:
dump_snapshots(bs);
break;
case SNAPSHOT_CREATE:
memset(&sn, 0, sizeof(sn));
pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
qemu_gettimeofday(&tv);
sn.date_sec = tv.tv_sec;
sn.date_nsec = tv.tv_usec * 1000;
ret = bdrv_snapshot_create(bs, &sn);
if (ret) {
error_report("Could not create snapshot '%s': %d (%s)",
snapshot_name, ret, strerror(-ret));
}
break;
case SNAPSHOT_APPLY:
ret = bdrv_snapshot_goto(bs, snapshot_name);
if (ret) {
error_report("Could not apply snapshot '%s': %d (%s)",
snapshot_name, ret, strerror(-ret));
}
break;
case SNAPSHOT_DELETE:
ret = bdrv_snapshot_delete(bs, snapshot_name);
if (ret) {
error_report("Could not delete snapshot '%s': %d (%s)",
snapshot_name, ret, strerror(-ret));
}
break;
}
bdrv_delete(bs);
if (ret) {
return 1;
}
return 0;
}
| 1threat
|
avoid multiple db calls sql server : i have a list of n records and for each record id i need to fetch a list of integers( partids ) from db..
currently from the app i am having to loop n times passing the main id to fetch each list from db.
Obv this is affecting the performance of the app.(dot net win app using vb.net)
Is there any way that i can avoid multiple calls?
like can i send a list of ids n get my desired result as output?
example
input : record1 having id 100
output:
id 100 ,partid 1,2,3
same for n rows
dont know how..any help please
| 0debug
|
Node events.js:167 throw er; // Unhandled 'error' event : <p>I'm trying to use JSON Server in a React App. However, I keep getting the following error. </p>
<pre><code>events.js:167
throw er; // Unhandled 'error' event
^
Emitted 'error' event at:
at GetAddrInfoReqWrap.doListen [as callback] (net.js:1498:12)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:50:17)
</code></pre>
<p>I've upgraded npm and node to the latest versions.
I've killed all processes with killall node and sudo killall -9 node</p>
<p>Any ideas what may be causing the issue? </p>
| 0debug
|
static void test_qemu_strtoul_negative(void)
{
const char *str = " \t -321";
char f = 'X';
const char *endptr = &f;
unsigned long res = 999;
int err;
err = qemu_strtoul(str, &endptr, 0, &res);
g_assert_cmpint(err, ==, 0);
g_assert_cmpint(res, ==, -321ul);
g_assert(endptr == str + strlen(str));
}
| 1threat
|
MQTT Socket error on client <unknown> : <p>I have setup MQTT on a Raspberry Pi and configured an Arduino Uno to the broker, but I am seeing the following entry in the /var/log/mosquitto/mosquitto.log file:</p>
<pre><code>New connection from 192.168.10.114 on port 1883.
Socket error on client <unknown>, disconnecting.
</code></pre>
<p>The Pi is setup with ETH0 wired to my local LAN and has an IP address of 192.168.1.50</p>
<p>There is also a WiFi AP setup on the Pi. The Arduino Uno connects via WiFi to send/receive MQTT messages. The WiFi AP has an IP address of 192.168.10.1 and provides DHCP leases via <code>dnsmasq</code>.</p>
<p>I have tried publishing and subscribing test on the local MQTT broker server (the Pi) and get the same error:</p>
<pre><code>Command:
mosquitto_sub -h 192.168.10.1 -t topic
mosquitto.log:
New connection from 192.168.10.1 on port 1883.
New client connected from 192.168.10.1 as mosqsub/1837-raspberryp (cl, k60).
Socket error on client <unknown>, disconnecting.
</code></pre>
<p>Here is /etc/mosquitto/mosquitto.conf:</p>
<pre><code>pid_file /var/run/mosquitto.pid
persistence true
log_dest file /var/log/mosquitto/mosquitto.log
allow_anonymous true
include_dir /etc/mosquitto/conf.d
</code></pre>
<p>sudo service mosquitto stop
sudo service mosquitto start:</p>
<pre><code>mosquitto version 1.4.8 terminating
mosquitto version 1.4.8 (build date Sun, 14 Feb 2016 15:06:55 +0000) starting
Config loaded from /etc/mosquitto/mosquitto.conf.
Opening ipv4 listen socket on port 1883.
Opening ipv6 listen socket on port 1883.
</code></pre>
<p>There might be an issue in my interfaces configuration. Here is /etc/network/interfaces:</p>
<pre><code>source-directory /etc/network/interfaces.d
auto lo
iface lo inet loopback
iface eth0 inet manual
auto wlan0
allow-hotplug wlan0
iface wlan0 inet static
address 192.168.10.1
netmask 255.255.255.0
</code></pre>
<p>Can anyone point me on where the socket error is coming from on MQTT?</p>
| 0debug
|
Why is this variable not defined in Python? : <p>I've been trying to make a python morse code translator and am over complicating it, I would like to continue on the path that I am going on for the morse code translator but I ran into a problem. </p>
<pre><code>Traceback (most recent call last):
File "python", line 114, in <module>
NameError: name 'firstletter' is not defined
</code></pre>
<p>I couldn't figure out why this variable was not being defined. Here's the code</p>
<pre><code>wordinput = input("What do you want to convert")
word = str(wordinput.upper)
if word[0] == 'A':
firstletter = ".-"
elif word[0] == "B":
firstletter = "-..."
elif word[0] == 'C':
firstletter = '-.-.'
elif word[0] == 'D':
firstletter = '-..'
elif word[0] == 'E':
firstletter = '.'
elif word[0] == 'F':
firstletter = '..-.'
elif word[0] == 'G':
firstletter = '--.'
elif word[0] == "H":
firstletter = '....'
elif word[0] == "I":
firstletter = '..'
elif word[0] == 'J':
firstletter = ".."
elif word[0] == 'K':
firstletter = '-.-'
elif word[0] == 'L':
firstletter = '.-..'
elif word[0] == 'M':
firstletter = '--'
elif word[0] == 'N':
firstletter = '-.'
elif word[0] == 'O':
firstletter = '---'
elif word[0] == 'P':
firstletter = '.--.'
elif word[0] == 'Q':
firstletter = '--.-'
elif word[0] == 'R':
firstletter = '.-.'
elif word[0] == 'S':
firstletter = '...'
elif word[0] == 'T':
firstletter = '-'
elif word[0] == 'U':
firstletter = '..-'
elif word[0] == 'V':
firstletter = '...-'
elif word[0] == 'W':
firstletter = '.--'
elif word[0] == 'X':
firstletter = '-..-'
elif word[0] == 'Y':
firstletter = '-.--'
elif word[0] == 'Z':
firstletter = '--..'
if word[1] == 'A':
secondletter = ".-"
elif word[1] == "B":
secondletter = "-..."
elif word[1] == 'C':
secondletter = '-.-.'
elif word[1] == 'D':
secondletter = '-..'
elif word[1] == 'E':
secondletter = '.'
elif word[1] == 'F':
secondletter = '..-.'
elif word[1] == 'G':
secondletter = '--.'
elif word[1] == "H":
secondletter = '....'
elif word[1] == "I":
secondletter = '..'
elif word[1] == 'J':
secondletter = ".."
elif word[1] == 'K':
secondletter = '-.-'
elif word[1] == 'L':
secondletter = '.-..'
elif word[1] == 'M':
secondletter = '--'
elif word[1] == 'N':
secondletter = '-.'
elif word[1] == 'O':
secondletter = '---'
elif word[1] == 'P':
secondletter = '.--.'
elif word[1] == 'Q':
secondletter = '--.-'
elif word[1] == 'R':
secondletter = '.-.'
elif word[1] == 'S':
secondletter = '...'
elif word[1] == 'T':
secondletter = '-'
elif word[1] == 'U':
secondletter = '..-'
elif word[1] == 'V':
secondletter = '...-'
elif word[1] == 'W':
secondletter = '.--'
elif word[1] == 'X':
secondletter = '-..-'
elif word[1] == 'Y':
secondletter = '-.--'
elif word[1] == 'Z':
secondletter = '--..'
print(firstletter + secondletter)
import os
os.system("pause")
</code></pre>
| 0debug
|
i want to conect a microcontroller to PC and play audio recived to pc by using naudio : i want to connect a microcontroller to PC and send wave file form micro to PC and play real-time and save it to PC
i can set a connection with USB between micro and PC to receive array
i should play this array and add next array in real-time without gaps in play
and i use C# to programming
| 0debug
|
Using numbers from css class as css values : I'm trying to streamline css styling. Is it possible to use a number in the css class as a value to be applied? Like parameters in a php or javascript function
Ex.
<div class="pad-left-35">Div with 35px padding left </div>
<div class="pad-left-10">Div with 10px padding left </div>
.pad-left-[value] { padding-left: 'value'px; }
.color-[value] { color: 'value'; }
| 0debug
|
purpose of declaring "new" with multidimensional arrays : <p>So I declare a multidimensional array of nodes like this</p>
<pre><code>Node[,] nodes;
</code></pre>
<p>In order to store Node objects in it I have to do this</p>
<pre><code>nodes = new Node[Xsize, Ysize];
</code></pre>
<p>but then when I go to store the actual Node objects I do this</p>
<pre><code>for(int x = 0; x < Xsize; x++)
{
for(int y = 0; y < Ysize; y++)
{
nodes[x,y] = new Node()
}
}
</code></pre>
<p>My question is, why is step 2 of this necessary? I am already saying <code>new Node()</code> when I place my individual node objects in my multidimensional array, and it already knows the array is of type Node.</p>
| 0debug
|
If statement to check if User has a product : One User has many products, one product only belongs to one user. In User profile, I want to implement this concept:
1/ If user does not have a product, "Create new product" button is available
2/ If user already has a store, both "Create new product" and list of products that can be clicked on to direct to the product itself
<% if @product.include? current_user.id %>
```ruby
<% if @product.include? current_user.id %>
<%= link_to 'My product', product_path %>
<% end %>
<%= link_to 'Create New Product', new_product_path %>
<%= link_to 'Edit', edit_user_registration_path %>
```
Expect:
1/ If user does not have a product, "Create new product" button is available
2/ If user already has a store, both "Create new product" and list of products that can be clicked on to direct to the product itself
| 0debug
|
static void create_header64(DumpState *s, Error **errp)
{
DiskDumpHeader64 *dh = NULL;
KdumpSubHeader64 *kh = NULL;
size_t size;
uint32_t block_size;
uint32_t sub_hdr_size;
uint32_t bitmap_blocks;
uint32_t status = 0;
uint64_t offset_note;
Error *local_err = NULL;
size = sizeof(DiskDumpHeader64);
dh = g_malloc0(size);
strncpy(dh->signature, KDUMP_SIGNATURE, strlen(KDUMP_SIGNATURE));
dh->header_version = cpu_to_dump32(s, 6);
block_size = s->dump_info.page_size;
dh->block_size = cpu_to_dump32(s, block_size);
sub_hdr_size = sizeof(struct KdumpSubHeader64) + s->note_size;
sub_hdr_size = DIV_ROUND_UP(sub_hdr_size, block_size);
dh->sub_hdr_size = cpu_to_dump32(s, sub_hdr_size);
dh->max_mapnr = cpu_to_dump32(s, MIN(s->max_mapnr, UINT_MAX));
dh->nr_cpus = cpu_to_dump32(s, s->nr_cpus);
bitmap_blocks = DIV_ROUND_UP(s->len_dump_bitmap, block_size) * 2;
dh->bitmap_blocks = cpu_to_dump32(s, bitmap_blocks);
strncpy(dh->utsname.machine, ELF_MACHINE_UNAME, sizeof(dh->utsname.machine));
if (s->flag_compress & DUMP_DH_COMPRESSED_ZLIB) {
status |= DUMP_DH_COMPRESSED_ZLIB;
#ifdef CONFIG_LZO
if (s->flag_compress & DUMP_DH_COMPRESSED_LZO) {
status |= DUMP_DH_COMPRESSED_LZO;
#endif
#ifdef CONFIG_SNAPPY
if (s->flag_compress & DUMP_DH_COMPRESSED_SNAPPY) {
status |= DUMP_DH_COMPRESSED_SNAPPY;
#endif
dh->status = cpu_to_dump32(s, status);
if (write_buffer(s->fd, 0, dh, size) < 0) {
error_setg(errp, "dump: failed to write disk dump header");
goto out;
size = sizeof(KdumpSubHeader64);
kh = g_malloc0(size);
kh->max_mapnr_64 = cpu_to_dump64(s, s->max_mapnr);
kh->phys_base = cpu_to_dump64(s, s->dump_info.phys_base);
kh->dump_level = cpu_to_dump32(s, DUMP_LEVEL);
offset_note = DISKDUMP_HEADER_BLOCKS * block_size + size;
kh->offset_note = cpu_to_dump64(s, offset_note);
kh->note_size = cpu_to_dump64(s, s->note_size);
if (write_buffer(s->fd, DISKDUMP_HEADER_BLOCKS *
block_size, kh, size) < 0) {
error_setg(errp, "dump: failed to write kdump sub header");
goto out;
s->note_buf = g_malloc0(s->note_size);
s->note_buf_offset = 0;
write_elf64_notes(buf_write_note, s, &local_err);
if (local_err) {
error_propagate(errp, local_err);
goto out;
if (write_buffer(s->fd, offset_note, s->note_buf,
s->note_size) < 0) {
error_setg(errp, "dump: failed to write notes");
goto out;
s->offset_dump_bitmap = (DISKDUMP_HEADER_BLOCKS + sub_hdr_size) *
block_size;
s->offset_page = (DISKDUMP_HEADER_BLOCKS + sub_hdr_size + bitmap_blocks) *
block_size;
out:
g_free(dh);
g_free(kh);
g_free(s->note_buf);
| 1threat
|
pandas.to_numeric - find out which string it was unable to parse : <p>Applying <code>pandas.to_numeric</code> to a dataframe column which contains strings that represent numbers (and possibly other unparsable strings) results in an error message like this:</p>
<pre><code>---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-66-07383316d7b6> in <module>()
1 for column in shouldBeNumericColumns:
----> 2 trainData[column] = pandas.to_numeric(trainData[column])
/usr/local/lib/python3.5/site-packages/pandas/tools/util.py in to_numeric(arg, errors)
113 try:
114 values = lib.maybe_convert_numeric(values, set(),
--> 115 coerce_numeric=coerce_numeric)
116 except:
117 if errors == 'raise':
pandas/src/inference.pyx in pandas.lib.maybe_convert_numeric (pandas/lib.c:53558)()
pandas/src/inference.pyx in pandas.lib.maybe_convert_numeric (pandas/lib.c:53344)()
ValueError: Unable to parse string
</code></pre>
<p>Wouldn't it be helpful to see which value failed to parse? </p>
| 0debug
|
Returning reversed array from a stack : <p>How do I write a method that when passed an array of integers, returns the array reversed, using a stack?</p>
<p>I am a total noob at Java please don't ask me for my own attempt as I don't know where to start. Any help would be greatly appreciated.</p>
| 0debug
|
bool qemu_clock_run_timers(QEMUClockType type)
{
return timerlist_run_timers(main_loop_tlg.tl[type]);
}
| 1threat
|
Python timedelta seconds vs total_seconds : <p>Looking at the datetime <a href="https://docs.python.org/3/library/datetime.html#timedelta-objects" rel="noreferrer">docs</a>, I can't seem to get the difference between the attribute <code>seconds</code> and the method <code>total_seconds()</code> used on a timedelta object. Is it just precision? Begin that the former is and <em>int</em> and the latter a <em>float</em>? Or am I missing something?</p>
| 0debug
|
Please if someone can center this for me, it's will be great : For the freaking code god, please if someone can center this code for me, it's will be great!
Ok i'm just gave up on this, i'm always coming into a problem about centering things and i have no idea why i cant understand how to freaking do that.
Please help me to center the code bellow and tell me how you did that :)
div.img {
margin: 5px;
border: 1px solid #ccc;
float: left;
width: 180px;
}
div.iframe:hover {
border: 1px solid #777;
}
div.img iframe {
width: 100%;
height: auto;
}
div.desc {
padding: 15px;
text-align: center;
}
https://jsfiddle.net/zuntcod0/
| 0debug
|
How to mock an @Input() object in angular2? : <p>I have looked on the angular2 website, as well as checked many SO posts and I could not find an example that illustrates by use case.</p>
<p>I want to mock data from an object that has an @Input() tag. My component looks like this</p>
<pre><code>...
export class DriftInfoDisplayComponent implements OnInit {
showThisDriftInfo:boolean;
headerText:string;
informationText:string;
linkText:string;
@Input() inputInfo:DriftInfo;
constructor(){}
ngOnInit() {
this.headerText = this.inputInfo.headerText;
this.informationText = this.inputInfo.informationText;
this.linkText = this.inputInfo.linkText;
this.showThisDriftInfo = this.inputInfo.visible;
}
toggleDriftInfo(){
this.showThisDriftInfo = ! this.showThisDriftInfo;
}
}
</code></pre>
<p>My unit test file for this component looks like this</p>
<pre><code>describe('DriftInfoComponent', () => {
let component: DriftInfoDisplayComponent;
let fixture: ComponentFixture<DriftInfoDisplayComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ DriftInfoDisplayComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DriftInfoDisplayComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
const fixture = TestBed.createComponent(DriftInfoDisplayComponent);
const drift = fixture.debugElement.componentInstance;
expect(drift).toBeTruthy();
});
});
</code></pre>
<p>I would like to write a test that mocks the inputInfo:DriftInfo and its object in DriftInfoDisplayComponent and its properties so that I can test that this data is being displayed properly in the html template. How can I do this?</p>
<p>Thanks for any help that may be provided!</p>
| 0debug
|
static int vp8_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_size)
{
VP56RangeCoder *c = &s->c;
int header_size, hscale, vscale, ret;
int width = s->avctx->width;
int height = s->avctx->height;
s->keyframe = !(buf[0] & 1);
s->profile = (buf[0]>>1) & 7;
s->invisible = !(buf[0] & 0x10);
header_size = AV_RL24(buf) >> 5;
buf += 3;
buf_size -= 3;
if (s->profile > 3)
av_log(s->avctx, AV_LOG_WARNING, "Unknown profile %d\n", s->profile);
if (!s->profile)
memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_epel_pixels_tab,
sizeof(s->put_pixels_tab));
else
memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_bilinear_pixels_tab,
sizeof(s->put_pixels_tab));
if (header_size > buf_size - 7 * s->keyframe) {
av_log(s->avctx, AV_LOG_ERROR, "Header size larger than data provided\n");
if (s->keyframe) {
if (AV_RL24(buf) != 0x2a019d) {
av_log(s->avctx, AV_LOG_ERROR,
"Invalid start code 0x%x\n", AV_RL24(buf));
width = AV_RL16(buf + 3) & 0x3fff;
height = AV_RL16(buf + 5) & 0x3fff;
hscale = buf[4] >> 6;
vscale = buf[6] >> 6;
buf += 7;
buf_size -= 7;
if (hscale || vscale)
avpriv_request_sample(s->avctx, "Upscaling");
s->update_golden = s->update_altref = VP56_FRAME_CURRENT;
vp78_reset_probability_tables(s);
memcpy(s->prob->pred16x16, vp8_pred16x16_prob_inter,
sizeof(s->prob->pred16x16));
memcpy(s->prob->pred8x8c, vp8_pred8x8c_prob_inter,
sizeof(s->prob->pred8x8c));
memcpy(s->prob->mvc, vp8_mv_default_prob,
sizeof(s->prob->mvc));
memset(&s->segmentation, 0, sizeof(s->segmentation));
memset(&s->lf_delta, 0, sizeof(s->lf_delta));
ff_vp56_init_range_decoder(c, buf, header_size);
buf += header_size;
buf_size -= header_size;
if (s->keyframe) {
s->colorspace = vp8_rac_get(c);
if (s->colorspace)
av_log(s->avctx, AV_LOG_WARNING, "Unspecified colorspace\n");
s->fullrange = vp8_rac_get(c);
if ((s->segmentation.enabled = vp8_rac_get(c)))
parse_segment_info(s);
else
s->segmentation.update_map = 0;
s->filter.simple = vp8_rac_get(c);
s->filter.level = vp8_rac_get_uint(c, 6);
s->filter.sharpness = vp8_rac_get_uint(c, 3);
if ((s->lf_delta.enabled = vp8_rac_get(c)))
if (vp8_rac_get(c))
update_lf_deltas(s);
if (setup_partitions(s, buf, buf_size)) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid partitions\n");
if (!s->macroblocks_base ||
width != s->avctx->width || height != s->avctx->height ||
(width+15)/16 != s->mb_width || (height+15)/16 != s->mb_height)
if ((ret = vp8_update_dimensions(s, width, height)) < 0)
return ret;
vp8_get_quants(s);
if (!s->keyframe) {
update_refs(s);
s->sign_bias[VP56_FRAME_GOLDEN] = vp8_rac_get(c);
s->sign_bias[VP56_FRAME_GOLDEN2 ] = vp8_rac_get(c);
if (!(s->update_probabilities = vp8_rac_get(c)))
s->prob[1] = s->prob[0];
s->update_last = s->keyframe || vp8_rac_get(c);
vp78_update_probability_tables(s);
if ((s->mbskip_enabled = vp8_rac_get(c)))
s->prob->mbskip = vp8_rac_get_uint(c, 8);
if (!s->keyframe) {
s->prob->intra = vp8_rac_get_uint(c, 8);
s->prob->last = vp8_rac_get_uint(c, 8);
s->prob->golden = vp8_rac_get_uint(c, 8);
vp78_update_pred16x16_pred8x8_mvc_probabilities(s, VP8_MVC_SIZE);
return 0;
| 1threat
|
void exit_program(int ret)
{
int i, j;
for (i = 0; i < nb_filtergraphs; i++) {
avfilter_graph_free(&filtergraphs[i]->graph);
for (j = 0; j < filtergraphs[i]->nb_inputs; j++)
av_freep(&filtergraphs[i]->inputs[j]);
av_freep(&filtergraphs[i]->inputs);
for (j = 0; j < filtergraphs[i]->nb_outputs; j++)
av_freep(&filtergraphs[i]->outputs[j]);
av_freep(&filtergraphs[i]->outputs);
av_freep(&filtergraphs[i]);
}
av_freep(&filtergraphs);
for (i = 0; i < nb_output_files; i++) {
AVFormatContext *s = output_files[i]->ctx;
if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
avio_close(s->pb);
avformat_free_context(s);
av_dict_free(&output_files[i]->opts);
av_freep(&output_files[i]);
}
for (i = 0; i < nb_output_streams; i++) {
AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
while (bsfc) {
AVBitStreamFilterContext *next = bsfc->next;
av_bitstream_filter_close(bsfc);
bsfc = next;
}
output_streams[i]->bitstream_filters = NULL;
if (output_streams[i]->output_frame) {
AVFrame *frame = output_streams[i]->output_frame;
if (frame->extended_data != frame->data)
av_freep(&frame->extended_data);
av_freep(&frame);
}
av_freep(&output_streams[i]->avfilter);
av_freep(&output_streams[i]->filtered_frame);
av_freep(&output_streams[i]);
}
for (i = 0; i < nb_input_files; i++) {
avformat_close_input(&input_files[i]->ctx);
av_freep(&input_files[i]);
}
for (i = 0; i < nb_input_streams; i++) {
av_freep(&input_streams[i]->decoded_frame);
av_dict_free(&input_streams[i]->opts);
free_buffer_pool(input_streams[i]);
av_freep(&input_streams[i]->filters);
av_freep(&input_streams[i]);
}
if (vstats_file)
fclose(vstats_file);
av_free(vstats_filename);
av_freep(&input_streams);
av_freep(&input_files);
av_freep(&output_streams);
av_freep(&output_files);
uninit_opts();
av_free(audio_buf);
allocated_audio_buf_size = 0;
av_free(async_buf);
allocated_async_buf_size = 0;
avfilter_uninit();
avformat_network_deinit();
if (received_sigterm) {
av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
(int) received_sigterm);
exit (255);
}
exit(ret);
}
| 1threat
|
Why mail send as spam message : <p>if you had solution please help me to fix it. please? mail was sent but it always visible on spam message. so how i keep it for inbox. please check my code deeply and give me right answer for matching my code.
i used this point i create user login part and i want to give user to recovery option. then user will try to recovery i will send user to mail.</p>
<pre><code><?php
session_start();
mysql_connect(***, ****, ***);
mysql_select_db('*****');
$email = $_POST["email"];
$_SESSION["email_id"]=$email;
$a = rand(100,999999);
//echo $a;
$_SESSION["random"]=$a;
$to = $email;
$subject = "Verification Code";
$message =
"<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2 style='color:#000CA5;'>Your Verification code is : </h2><br><h2><b>$a</b></h2>
</body>
</html>";
$header = "From:****@**.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html;charset=UTF-8" . "\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true ) {
// echo "Message sent successfully...";
$sql = "update random set ran_num='$a' where emailid='$email'";
mysql_query($sql);
IF(!mysql_query($sql)){
die("erroe processing :".mysql_error());
}
else{
echo "<script language='javascript' type='text/javascript'> location.href='password_update.php'
</script>";
}
}
?>
</code></pre>
| 0debug
|
static int decode_pce(AACContext * ac, enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
GetBitContext * gb) {
int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
skip_bits(gb, 2);
ac->m4ac.sampling_index = get_bits(gb, 4);
if(ac->m4ac.sampling_index > 11) {
av_log(ac->avccontext, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
return -1;
}
ac->m4ac.sample_rate = ff_mpeg4audio_sample_rates[ac->m4ac.sampling_index];
num_front = get_bits(gb, 4);
num_side = get_bits(gb, 4);
num_back = get_bits(gb, 4);
num_lfe = get_bits(gb, 2);
num_assoc_data = get_bits(gb, 3);
num_cc = get_bits(gb, 4);
if (get_bits1(gb))
skip_bits(gb, 4);
if (get_bits1(gb))
skip_bits(gb, 4);
if (get_bits1(gb))
skip_bits(gb, 3);
decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE, gb, num_side );
decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK, gb, num_back );
decode_channel_map(NULL, new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE, gb, num_lfe );
skip_bits_long(gb, 4 * num_assoc_data);
decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC, gb, num_cc );
align_get_bits(gb);
skip_bits_long(gb, 8 * get_bits(gb, 8));
return 0;
}
| 1threat
|
How to get nth-of-type patterns to work like 1-2-2-1? : <p>Trying to get nth-of-type to style elements with this pattern: 1-2-2-1.</p>
<p>For example, it needs to look like this:</p>
<p>blue red</p>
<p>red blue</p>
<p>blue red</p>
<p>red blue</p>
<p>blue red</p>
<p>red blue</p>
<p>I have a lot of links set in 1 container, I am trying to get it to be in 2 columns and to be designed in alternating colors (like shown in the red-blue list here).</p>
<p>I tried messing around with nth-of-type, but couldn't figure it out, for now, I am using something like this:</p>
<pre><code>.post-link:nth-of-type(2) {code...}
.post-link:nth-of-type(3) {code...}
.post-link:nth-of-type(6) {code...}
.post-link:nth-of-type(7) {code...}
.post-link:nth-of-type(10) {code...}
.post-link:nth-of-type(11) {code...}
</code></pre>
<p>But this manual approach only takes me so far, links are being added to the page all the time and I need it to work without setting a specific rule for each box.</p>
<p>I tried something like this with no success as well:</p>
<pre><code>.post-link {background: #3c6d84;}
.post-link:nth-of-type(2n) {background: #fe7625;}
.post-link:nth-of-type(3n) {background: #fe7625;}
</code></pre>
<p>Trying to get the right pattern as mentioned above.</p>
| 0debug
|
static int kvm_irqchip_create(KVMState *s)
{
QemuOptsList *list = qemu_find_opts("machine");
int ret;
if (QTAILQ_EMPTY(&list->head) ||
!qemu_opt_get_bool(QTAILQ_FIRST(&list->head),
"kernel_irqchip", true) ||
!kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
return 0;
}
ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
if (ret < 0) {
fprintf(stderr, "Create kernel irqchip failed\n");
return ret;
}
kvm_kernel_irqchip = true;
kvm_async_interrupts_allowed = true;
kvm_halt_in_kernel_allowed = true;
kvm_init_irq_routing(s);
return 0;
}
| 1threat
|
How to generate date in the format of YYYY-MM-DD in python? : <p>I want to generate list of dates between <code>20160711</code> to <code>20190921</code>. I don't want to miss a date. How to do that in Python2 or Python3?</p>
| 0debug
|
How to get indices of non-diagonal elements of a numpy array? : <p>How to get indices of non-diagonal elements of a numpy array?</p>
<pre><code>a = np.array([[7412, 33, 2],
[2, 7304, 83],
[3, 101, 7237]])
</code></pre>
<p>I tried as follows:</p>
<pre><code>diag_indices = np.diag_indices_from(a)
print diag_indices
(array([0, 1, 2], dtype=int64), array([0, 1, 2], dtype=int64))
</code></pre>
<p>After that, no idea...
The expected result should be:</p>
<pre><code>result = [[False, True, True],
[True, False, True],
[True, True, False]]
</code></pre>
| 0debug
|
Getting proportions from data sets in R : <p>I have a data set called 'md' which consists of 40 numbers 1-6, I need to get the proportion that the number 1 appears in the list, I've been looking for ways to get proportions but none of which seem to be relevant to my data set, the proportion is easily calculable, however, it is required to be done in R.</p>
| 0debug
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.