problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
Replace Single Quotes and Comma in Nested List : <p>Have a list of list that looks like this:</p>
<pre><code>mylist = [['A'],['A', 'B'], ['A', 'B', 'C']]
</code></pre>
<p>Need to remove and replace all ', ' instances with a comma only (no spaces). Output should look like this:</p>
<pre><code>mynewlist = [['A'],['A,B'], ['A,B,C']]
</code></pre>
<p>Tried the following:</p>
<pre><code>mynewlist = [[x.replace("', ''",",") for x in i] for i in mylist]
</code></pre>
<p>This works on other characters within the nested lists (e.g. replacing 'A' with 'D', but does not function for the purpose described above (something to do with with the commas not being literal strings?).</p>
| 0debug
|
def count_vowels(test_str):
res = 0
vow_list = ['a', 'e', 'i', 'o', 'u']
for idx in range(1, len(test_str) - 1):
if test_str[idx] not in vow_list and (test_str[idx - 1] in vow_list or test_str[idx + 1] in vow_list):
res += 1
if test_str[0] not in vow_list and test_str[1] in vow_list:
res += 1
if test_str[-1] not in vow_list and test_str[-2] in vow_list:
res += 1
return (res)
| 0debug
|
how to pass javascript variable value to another javascript function? : I need to pass javascript variable value to another javascript function
$("#myTabs form").on('submit', function (e) {
e.preventDefault();
var linkHref = $(this).parents('.tab-pane').attr('id');
$('#myLinks li a').removeClass('active');
$('#myLinks li')
.find('a[href="#' + linkHref + '"]')
.parent()
.next()
.find('a')
.tab('show')
.addClass('active')
.attr('data-toggle', 'tab');
$('a.nav-link').not('.active').css('pointer-events', 'none');
var SAPno = linkHref;
});
$('a.nav-link').not('.active').css('pointer-events', 'none');
For Example `var SAPno` value need to the passed to another javascript function
function GetInfo() {
var ID = SAPno;
}
| 0debug
|
static int decode_frame_apng(AVCodecContext *avctx,
void *data, int *got_frame,
AVPacket *avpkt)
{
PNGDecContext *const s = avctx->priv_data;
int ret;
AVFrame *p;
ff_thread_release_buffer(avctx, &s->last_picture);
FFSWAP(ThreadFrame, s->picture, s->last_picture);
p = s->picture.f;
if (!(s->state & PNG_IHDR)) {
int side_data_size = 0;
uint8_t *side_data = NULL;
if (avpkt)
side_data = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_data_size);
if (side_data_size) {
av_freep(&s->extra_data);
s->extra_data = av_mallocz(side_data_size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!s->extra_data)
return AVERROR(ENOMEM);
s->extra_data_size = side_data_size;
memcpy(s->extra_data, side_data, s->extra_data_size);
}
if (!s->extra_data_size)
return AVERROR_INVALIDDATA;
s->zstream.zalloc = ff_png_zalloc;
s->zstream.zfree = ff_png_zfree;
bytestream2_init(&s->gb, s->extra_data, s->extra_data_size);
if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
goto end;
}
if ((ret = inflateInit(&s->zstream)) != Z_OK) {
av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
ret = AVERROR_EXTERNAL;
goto end;
}
s->y = 0;
s->state &= ~(PNG_IDAT | PNG_ALLIMAGE);
bytestream2_init(&s->gb, avpkt->data, avpkt->size);
if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
goto end;
if (!(s->state & PNG_ALLIMAGE))
av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
ret = AVERROR_INVALIDDATA;
goto end;
}
if ((ret = av_frame_ref(data, s->picture.f)) < 0)
goto end;
*got_frame = 1;
ret = bytestream2_tell(&s->gb);
end:
inflateEnd(&s->zstream);
return ret;
}
| 1threat
|
When is it useful to use "strict wildcard" in Haskell, and what does it do? : <p>I was looking at some Haskell source code and came across a pattern match with <code>!_</code>, the code is here: <a href="http://hackage.haskell.org/package/base-4.9.0.0/docs/src/GHC.List.html#unsafeTake">http://hackage.haskell.org/package/base-4.9.0.0/docs/src/GHC.List.html#unsafeTake</a></p>
<pre><code>take n xs | 0 < n = unsafeTake n xs
| otherwise = []
-- A version of take that takes the whole list if it's given an argument less
-- than 1.
{-# NOINLINE [1] unsafeTake #-}
unsafeTake :: Int -> [a] -> [a]
unsafeTake !_ [] = []
unsafeTake 1 (x: _) = [x]
unsafeTake m (x:xs) = x : unsafeTake (m - 1) xs
</code></pre>
<p>I don't really understand how the "strict wildcard" works and why it's useful for this function (or any other function).</p>
| 0debug
|
static int decode_ref_pic_list_reordering(H264Context *h){
MpegEncContext * const s = &h->s;
int list, index, pic_structure;
print_short_term(h);
print_long_term(h);
if(h->slice_type==FF_I_TYPE || h->slice_type==FF_SI_TYPE) return 0;
for(list=0; list<h->list_count; list++){
memcpy(h->ref_list[list], h->default_ref_list[list], sizeof(Picture)*h->ref_count[list]);
if(get_bits1(&s->gb)){
int pred= h->curr_pic_num;
for(index=0; ; index++){
unsigned int reordering_of_pic_nums_idc= get_ue_golomb(&s->gb);
unsigned int pic_id;
int i;
Picture *ref = NULL;
if(reordering_of_pic_nums_idc==3)
break;
if(index >= h->ref_count[list]){
av_log(h->s.avctx, AV_LOG_ERROR, "reference count overflow\n");
return -1;
}
if(reordering_of_pic_nums_idc<3){
if(reordering_of_pic_nums_idc<2){
const unsigned int abs_diff_pic_num= get_ue_golomb(&s->gb) + 1;
int frame_num;
if(abs_diff_pic_num > h->max_pic_num){
av_log(h->s.avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");
return -1;
}
if(reordering_of_pic_nums_idc == 0) pred-= abs_diff_pic_num;
else pred+= abs_diff_pic_num;
pred &= h->max_pic_num - 1;
frame_num = pic_num_extract(h, pred, &pic_structure);
for(i= h->short_ref_count-1; i>=0; i--){
ref = h->short_ref[i];
assert(ref->reference);
assert(!ref->long_ref);
if(ref->data[0] != NULL &&
ref->frame_num == frame_num &&
(ref->reference & pic_structure) &&
ref->long_ref == 0)
break;
}
if(i>=0)
ref->pic_id= pred;
}else{
int long_idx;
pic_id= get_ue_golomb(&s->gb);
long_idx= pic_num_extract(h, pic_id, &pic_structure);
if(long_idx>31){
av_log(h->s.avctx, AV_LOG_ERROR, "long_term_pic_idx overflow\n");
return -1;
}
ref = h->long_ref[long_idx];
assert(!(ref && !ref->reference));
if(ref && (ref->reference & pic_structure)){
ref->pic_id= pic_id;
assert(ref->long_ref);
i=0;
}else{
i=-1;
}
}
if (i < 0) {
av_log(h->s.avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");
memset(&h->ref_list[list][index], 0, sizeof(Picture));
} else {
for(i=index; i+1<h->ref_count[list]; i++){
if(ref->long_ref == h->ref_list[list][i].long_ref && ref->pic_id == h->ref_list[list][i].pic_id)
break;
}
for(; i > index; i--){
h->ref_list[list][i]= h->ref_list[list][i-1];
}
h->ref_list[list][index]= *ref;
if (FIELD_PICTURE){
pic_as_field(&h->ref_list[list][index], pic_structure);
}
}
}else{
av_log(h->s.avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");
return -1;
}
}
}
}
for(list=0; list<h->list_count; list++){
for(index= 0; index < h->ref_count[list]; index++){
if(!h->ref_list[list][index].data[0])
h->ref_list[list][index]= s->current_picture;
}
}
if(h->slice_type==FF_B_TYPE && !h->direct_spatial_mv_pred)
direct_dist_scale_factor(h);
direct_ref_list_init(h);
return 0;
}
| 1threat
|
Object *user_creatable_add(const QDict *qdict,
Visitor *v, Error **errp)
{
char *type = NULL;
char *id = NULL;
Object *obj = NULL;
Error *local_err = NULL, *end_err = NULL;
QDict *pdict;
pdict = qdict_clone_shallow(qdict);
visit_start_struct(v, NULL, NULL, 0, &local_err);
if (local_err) {
goto out;
}
qdict_del(pdict, "qom-type");
visit_type_str(v, "qom-type", &type, &local_err);
if (local_err) {
goto out_visit;
}
qdict_del(pdict, "id");
visit_type_str(v, "id", &id, &local_err);
if (local_err) {
goto out_visit;
}
obj = user_creatable_add_type(type, id, pdict, v, &local_err);
if (local_err) {
goto out_visit;
}
out_visit:
visit_end_struct(v, &end_err);
if (end_err) {
error_propagate(&local_err, end_err);
if (obj) {
user_creatable_del(id, NULL);
}
goto out;
}
out:
QDECREF(pdict);
g_free(id);
g_free(type);
if (local_err) {
error_propagate(errp, local_err);
object_unref(obj);
return NULL;
}
return obj;
}
| 1threat
|
What's wrong with my code? Please help! (Java) :
public class night {
public static void main(String[] args) {
System.out.println(addition(1,1,1,1));
}
public static int addition (int...numberz){
int total=0;
for(int x=1; x<=numberz.length; x++) {
total+=x;
}
return total;
}
}
The above code doesn't add the numbers correctly.
When I use an enhanced for loop in the method "addition", I get desired results:-
---
public static int addition (int...numberz){
int total=0;
for(int x:numberz) {
total+=x;
}
return total;
}
---
I'm a noob, and this is my first question here.
Please answer in as simple terms as you can, as to why the first code doesn't work, and the second one does. Thank you.
| 0debug
|
How to get name of color from hexa code in java? : I use openCV for color identification and I get color in hexa form like #FF0000 Nnow I want to convert it in string. I have search alot but I didnt find any useful code please help and tell me if anyone knows the answer.
| 0debug
|
i dont get anything in my recylerview when i slect image from gallery to show in recylerview android : i am just trying to pick image from gallery and show in recylerview but when i go to the gallery and slect image it show blank recylerview here is my code
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == GALLERY)
{
if (data != null)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new ImageAdapter(imageArrayList);
recyclerView.setAdapter(adapter);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//ImageAdapter adapter = new ImageAdapter (data, MainActivity.this);
//recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.smoothScrollToPosition(0);
//Counter = false;
}
}
}
| 0debug
|
static int h264_probe(AVProbeData *p)
{
uint32_t code = -1;
int sps = 0, pps = 0, idr = 0, res = 0, sli = 0;
int i;
for (i = 0; i < p->buf_size; i++) {
code = (code << 8) + p->buf[i];
if ((code & 0xffffff00) == 0x100) {
int ref_idc = (code >> 5) & 3;
int type = code & 0x1F;
static const int8_t ref_zero[] = {
2, 0, 0, 0, 0, -1, 1, -1,
-1, 1, 1, 1, 1, -1, 2, 2,
2, 2, 2, 0, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2
};
if (code & 0x80)
return 0;
if (ref_zero[type] == 1 && ref_idc)
return 0;
if (ref_zero[type] == -1 && !ref_idc)
return 0;
if (ref_zero[type] == 2) {
if (!(code == 0x100 && !p->buf[i + 1] && !p->buf[i + 2]))
res++;
}
switch (type) {
case 1:
sli++;
break;
case 5:
idr++;
break;
case 7:
if (p->buf[i + 2] & 0x03)
return 0;
sps++;
break;
case 8:
pps++;
break;
}
}
}
ff_tlog(NULL, "sps:%d pps:%d idr:%d sli:%d res:%d\n", sps, pps, idr, sli, res);
if (sps && pps && (idr || sli > 3) && res < (sps + pps + idr))
return AVPROBE_SCORE_EXTENSION + 1;
return 0;
}
| 1threat
|
Cake PHP Godaddy installation issues : I just started using Cake PHP. I installed through the Godaddy app "installatron".
I am accessing the command line through Putty as they recommend, which works fine. Changed .htpaccess as instructed etc..
When ever I try to enter bin/cake bake it tells me "Permission Denied"
Anyone know how to fix this issue?
| 0debug
|
static void tcg_out_brcond(TCGContext *s, TCGCond cond, TCGReg arg1,
TCGReg arg2, int label_index)
{
static const MIPSInsn b_zero[16] = {
[TCG_COND_LT] = OPC_BLTZ,
[TCG_COND_GT] = OPC_BGTZ,
[TCG_COND_LE] = OPC_BLEZ,
[TCG_COND_GE] = OPC_BGEZ,
};
TCGLabel *l;
MIPSInsn s_opc = OPC_SLTU;
MIPSInsn b_opc;
int cmp_map;
switch (cond) {
case TCG_COND_EQ:
b_opc = OPC_BEQ;
break;
case TCG_COND_NE:
b_opc = OPC_BNE;
break;
case TCG_COND_LT:
case TCG_COND_GT:
case TCG_COND_LE:
case TCG_COND_GE:
if (arg2 == 0) {
b_opc = b_zero[cond];
arg2 = arg1;
arg1 = 0;
break;
}
s_opc = OPC_SLT;
case TCG_COND_LTU:
case TCG_COND_GTU:
case TCG_COND_LEU:
case TCG_COND_GEU:
cmp_map = mips_cmp_map[cond];
if (cmp_map & MIPS_CMP_SWAP) {
TCGReg t = arg1;
arg1 = arg2;
arg2 = t;
}
tcg_out_opc_reg(s, s_opc, TCG_TMP0, arg1, arg2);
b_opc = (cmp_map & MIPS_CMP_INV ? OPC_BEQ : OPC_BNE);
arg1 = TCG_TMP0;
arg2 = TCG_REG_ZERO;
break;
default:
tcg_abort();
break;
}
tcg_out_opc_br(s, b_opc, arg1, arg2);
l = &s->labels[label_index];
if (l->has_value) {
reloc_pc16(s->code_ptr - 1, l->u.value_ptr);
} else {
tcg_out_reloc(s, s->code_ptr - 1, R_MIPS_PC16, label_index, 0);
}
tcg_out_nop(s);
}
| 1threat
|
Ansible + Ubuntu 18.04 + MySQL = "The PyMySQL (Python 2.7 and Python 3.X) or MySQL-python (Python 2.X) module is required." : <p>I’m seeing the above message on multiple playbooks using Ansible 2.8 on Ubuntu 18.04. In the interests of simplicity I’ve reproduced it using this basic playbook for a single node Drupal server. <a href="https://github.com/geerlingguy/ansible-for-devops/tree/master/drupal" rel="noreferrer">https://github.com/geerlingguy/ansible-for-devops/tree/master/drupal</a>; this playbook works fine on earlier versions of ubuntu, but not on 18.04 which I understand includes python3 by default.</p>
<p>I’ve used vagrant to create the base machine, which shows the following:</p>
<pre><code>$ which python
/usr/bin/python
$ which python2
/usr/bin/python2
$ which python3
/usr/bin/python3
$ python --version
Python 2.7.15rc1
$ python2 --version
Python 2.7.15rc1
$ python3 --version
Python 3.6.7
</code></pre>
<p>Which seems to be telling me that both python 2 and python 3 are installed, but that 2.7 is the default as that is what responds to $ python --version. </p>
<p>I have tried all the suggestions described in this article: <a href="https://www.rollnorocks.com/2018/12/ansible-python-and-mysql-untangling-the-mess/" rel="noreferrer">https://www.rollnorocks.com/2018/12/ansible-python-and-mysql-untangling-the-mess/</a>
Including specifying the </p>
<pre><code>ansible_python_interpreter=/usr/bin/python3
</code></pre>
<p>But nothing affects the message. The edited -vvv output from the playbook run is below. Has anyone got any more ideas about either the problem or solution.</p>
<pre><code>TASK [Remove the MySQL test database.] ****************************************************************************************************************************
task path: /vagrant/provisioning/playbook.yml:96
<10.1.1.11> ESTABLISH SSH CONNECTION FOR USER: mt-ansible-user
<10.1.1.11> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o
.
.
.
Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/database/mysql/mysql_db.py
<10.1.1.11> PUT /home/mt-tools-user/.ansible/tmp/ansible-local-21287bh5dK5/tmp7pOKOH TO /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-16683638151793
1/AnsiballZ_mysql_db.py
<10.1.1.11> SSH: EXEC sftp -b - -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mt-tools-user/.ssh/mt_ansible_rsa"' -o KbdInteractiveAuthent
ication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="mt-ansible-user"' -o ConnectTimeout=
10 -o ControlPath=/home/mt-tools-user/.ansible/cp/af4de51057 '[10.1.1.11]'
<10.1.1.11> (0, 'sftp> put /home/mt-tools-user/.ansible/tmp/ansible-local-21287bh5dK5/tmp7pOKOH /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-166836
381517931/AnsiballZ_mysql_db.py\n', '')
<10.1.1.11> ESTABLISH SSH CONNECTION FOR USER: mt-ansible-user
<10.1.1.11> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mt-tools-user/.ssh/mt_ansible_rsa"' -o KbdInteractiveAuthenticatio
n=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="mt-ansible-user"' -o ConnectTimeout=10 -o
ControlPath=/home/mt-tools-user/.ansible/cp/af4de51057 10.1.1.11 '/bin/sh -c '"'"'chmod u+x /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-1668363815
17931/ /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-166836381517931/AnsiballZ_mysql_db.py && sleep 0'"'"''
<10.1.1.11> (0, '', '')
<10.1.1.11> ESTABLISH SSH CONNECTION FOR USER: mt-ansible-user
<10.1.1.11> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mt-tools-user/.ssh/mt_ansible_rsa"' -o KbdInteractiveAuthenticatio
n=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="mt-ansible-user"' -o ConnectTimeout=10 -o
ControlPath=/home/mt-tools-user/.ansible/cp/af4de51057 -tt 10.1.1.11 '/bin/sh -c '"'"'sudo -H -S -n -u root /bin/sh -c '"'"'"'"'"'"'"'"'echo BECOME-SUCCESS-qwjewg
qckuyapsxnkbqoegainrkyiinc ; /usr/bin/python3 /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-166836381517931/AnsiballZ_mysql_db.py'"'"'"'"'"'"'"'"' &
& sleep 0'"'"''
<10.1.1.11> (1, 'BECOME-SUCCESS-qwjewgqckuyapsxnkbqoegainrkyiinc\r\n\r\n{"msg": "The PyMySQL (Python 2.7 and Python 3.X) or MySQL-python (Python 2.X) module is req
uired.", "failed": true, "invocation": {"module_args": {"db": "test", "state": "absent", "name": "test", "login_host": "localhost", "login_port": 3306, "encoding":
"", "collation": "", "connect_timeout": 30, "config_file": "/root/.my.cnf", "single_transaction": false, "quick": true, "ignore_tables": [], "login_user": null, "
login_password": null, "login_unix_socket": null, "target": null, "client_cert": null, "client_key": null, "ca_cert": null}}}\r\n', 'Shared connection to 10.1.1.11
closed.\r\n')
<10.1.1.11> Failed to connect to the host via ssh: Shared connection to 10.1.1.11 closed.
<10.1.1.11> ESTABLISH SSH CONNECTION FOR USER: mt-ansible-user
<10.1.1.11> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mt-tools-user/.ssh/mt_ansible_rsa"' -o KbdInteractiveAuthenticatio
n=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="mt-ansible-user"' -o ConnectTimeout=10 -o
ControlPath=/home/mt-tools-user/.ansible/cp/af4de51057 10.1.1.11 '/bin/sh -c '"'"'rm -f -r /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-16683638151
7931/ > /dev/null 2>&1 && sleep 0'"'"''
<10.1.1.11> (0, '', '')
</code></pre>
| 0debug
|
how to clear history in safari while button clicked in objective c : Could you please let me know how to clear safari history while button clicked in our app using ios sdk?
Thanks,
| 0debug
|
Why are await and async valid variable names? : <p>I was experimenting with how <code>/</code> is interpreted when around different keywords and operators, and found that the following syntax is perfectly legal:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// awaiting something that isn't a Promise is fine, it's just strange to do:
const foo = await /barbaz/
myFn()</code></pre>
</div>
</div>
</p>
<p>Error:</p>
<blockquote>
<p>Uncaught ReferenceError: await is not defined</p>
</blockquote>
<p>It looks like it tries to parse the <code>await</code> as a <em>variable name</em>..? I was expecting</p>
<blockquote>
<p>await is only valid in async function</p>
</blockquote>
<p>or maybe something like</p>
<blockquote>
<p>Unexpected token await</p>
</blockquote>
<p>To my horror, you can even assign things to it:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const await = 'Wait, this actually works?';
console.log(await);</code></pre>
</div>
</div>
</p>
<p>Shouldn't something so obviously wrong cause a syntax error, as it does with <code>let</code>, <code>finally</code>, <code>break</code>, etc? Why is this allowed, and what the heck is going on in the first snippet?</p>
| 0debug
|
Opening a from from another form : I have no idea why this isn't working. Here's the code
private void button1_Click(object sender, EventArgs e)
{
this.Close();
new MainScreen().Show();
}
All that this is doing is closing the current form, it isn't opening the MainScreen form. What am I doing wrong? I've used this same code in another project
| 0debug
|
drawing a building by using python : I'm Creating a function to draw a office tower
:windows are 20 pixels square
the gap between the windows is 10 pixels
the door is 20 pixels wide, 50 pixels tall, and orange.
I can't draw it properly and here is my code:
from graphics import *
from random import *
def add_window(win, nH, nV):
w, h = win.getWidth(), win.getHeight()
rects = []
for x in range(nH):
rects.append([])
for y in range(nV):
r = Rectangle(Point( x *w//nH, y *h//vV),
Point((x+1)*w//nH, (y+1)*h//nV))
window = [ r,
True,
[ 'red', 'green' ]
]
rects[x].append(window)
rects[x][y][0].draw(win)
rects[x][y][0].setOutline('blue')
color = window[2][randint[0,1]]
rects[x][y][0].setFill(color)
return rects
WIN_W, WIN_H = 500, 400
#Top left coner of the building
BLDG_LEFT, BLDG_TOP = 50, 50
#How many floors, how many windows perfloor, window digit and gap
FLOORS, WIN_FLR, WIN_SZ, GAP = 10, 5, 20, 5
win = None
#Syntax : window[x][y]
# [0] : Rectangle() object
# [1] : True/False
windows = []
#--------------------------------------------------------------------
def draw_window(x, y):
global windows
windows = []
left = BLDG_LEFT + GAP + x* (WIN_SZ+GAP)
top = BLDG_TOP + GAP + y* (WIN_SZ+GAP)
r = Rectangle(Point( x *WIN_SZ+GAP, y *(WIN_SZ+GAP)),
Point((x+1)*WIN_SZ+GAP, (y+1)*(WIN_SZ+GAP)))
windows[x][y].append(r)
bit = randint(0,1)
windows[x][y].append(bool(bit))
windows[x][y][0].setFill(COLORS[bit])
windows[x][y][0].draw(win)
def draw_windows():
for i in range(WIN_FLR):
windows.append([])
for j in range(FLOORS):
windows[i].append([])
draw_window(i, j)
def office_tower():
global win
win = GraphWin("OFFICE TOWER", WIN_W, WIN_H)
draw_window(1, 1)
while True:
pt = win.getmouse()
if pt.x < 10 and pt.y < 10:
break
# windows coordinates
x = int((pt.x - BLDG_LEFT - GAP)/(WIN_SZ + GAP))
y = int((pt.y - BLDG_TOP - GAP)/(WIN_SZ + GAP))
print(str((pt.x, pt.y)) + ' --> ' + str((x, y)))
windows[x][y][1] = netwindows[x][y][1]
windows[x][y][0].setFill(COLORS[windows[x][y][1]])
def draw_building():
global windows
win = GraphWin("OFFICE TOWER", WIN_W, WIN_H)
N_H, N_V = 5, 10
while True:
pt = win.getMouse()
m_x, m_y = pt.getX(), pt.getY()
# Grid coordinates:
g_x = m_x // (WIN_W//N_H)
g_y = m_y // (WIN_H//N_V)
# For development purposes:
if m_x < 10 and m_y < 10:
break
| 0debug
|
static int dxva2_mpeg2_start_frame(AVCodecContext *avctx,
av_unused const uint8_t *buffer,
av_unused uint32_t size)
{
const struct MpegEncContext *s = avctx->priv_data;
AVDXVAContext *ctx = avctx->hwaccel_context;
struct dxva2_picture_context *ctx_pic =
s->current_picture_ptr->hwaccel_picture_private;
if (!DXVA_CONTEXT_VALID(avctx, ctx))
return -1;
assert(ctx_pic);
fill_picture_parameters(avctx, ctx, s, &ctx_pic->pp);
fill_quantization_matrices(avctx, ctx, s, &ctx_pic->qm);
ctx_pic->slice_count = 0;
ctx_pic->bitstream_size = 0;
ctx_pic->bitstream = NULL;
return 0;
}
| 1threat
|
C++ Putting a character into a cin for a while loop causes the loop to execute outside of it : <p>I decided to try to make a little game. It's a simple survival game. Part of it has people try to survive as long as they can by choosing options. I've scaled down the game as much as possible from 1000 lines to this for the minimum case.</p>
<p>At one part of the game it asks, "You were visited by a gifting clown. On a scale of 0-10, how badly do you want a gift?"</p>
<p>If they answer 0-10, the loop works fine. If they answer with a character, like y or n, the loop basically forces the game to execute where it no longer asks players for input on any other choices.</p>
<p>A previous while loop works, one where it will continue so long as the player is alive. This clown while loop is nested inside of it. I have broken up the while loop with the clown section to where I think the problem is... And also included the full code just in case it's not inside there.</p>
<p>My goal is simply if a character is put into it, that it doesn't break this game. </p>
<p>main.cpp - clown section</p>
<pre><code>encounterHurt = 0;
randomEncounter = rand() % 8;
cin.ignore(1, '\n');
if (randomEncounter == 1 && clown == true){
encounterChoice = 1;
cout << "\n\nYou were visited by a gifting clown. \nOn a scale of 0-10, how badly do you want a gift? ";
while (encounterChoice >= 0 && encounterChoice <= 10){
cin >> encounterChoice;
encounterFood = (rand() % 3) + encounterChoice / 2;
encounterWood = (rand() % 3) + encounterChoice / 2;
encounterMedicine = (rand() % 2);
encounterBullets = (rand() % 2);
if (encounterChoice > 0){
encounterHurt = (rand() % 10) - encounterChoice;
if (encounterHurt <= 1){
health--;
cout << "The crazy clown stabs you, but still provides gifts.";
}
}
if (encounterFood > 0) {
cout << "\nYou were provided with " << encounterFood << " food." << endl;
food += encounterFood;
}
if (encounterWood > 0) {
cout << "\nYou were provided with " << encounterWood << " wood." << endl;
wood += encounterWood;
}
if (encounterMedicine > 0) {
cout << "\nYou were provided with " << encounterMedicine << " medicine." << endl;
medicine += encounterMedicine;
}
if (encounterBullets > 0) {
cout << "\nYou were provided with " << encounterBullets << " bullets." << endl;
bullets += encounterBullets;
}
encounterChoice = 11;
}
</code></pre>
<p>main.cpp - Condensed code</p>
<pre><code>#include <iostream>
#include <iomanip>
#include <random>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
srand (time(NULL));
int randNumber = 0;
int food = 4;
int wood = 4;
int medicine = 2;
int bullets = 8;
int money = 25;
int randomEncounter = 0;
int hunt = 0;
bool axe = false;
int axeTemp = 0;
int axeBonus = 0;
int lumberTemp = 0;
int lumber = 0;
int findStore = 0;
int storeChoice = 0;
bool gun = false;
int gunSearch;
int gunTemp;
int gunBonus = 0;
int gunFind = 0;
// int searches;
// int searchesBonus;
int farmFind = 0;
int farmFood = 0;
int farmSearch = 0;
bool farm = false;
string description;
int foodTemp = 0;
int woodTemp = 0;
int medicineTemp = 0;
int bulletsTemp = 0;
int moneyTemp = 0;
int huntTemp = 0;
int huntSuccess = 0;
char huntChoice;
int encounterFood = 0;
int encounterWood = 0;
int encounterBullets = 0;
int encounterMedicine = 0;
int encounterHurt = 0;
unsigned int encounterChoice = 0;
int hurt = 0;
int health = 3;
int healthMax = 3;
int days = 1;
char action = '0';
char pause = '1';
char classChoice;
char mainChoice;
bool clown = true;
int clownHealth = 5;
char clownChoice;
int yourShot = 0;
int clownShot = 0;
string place;
//Food 1 per day per person. Can expand to include more people.
//Fuel 1 per day, takes that much to stay warm even if fewer people
//Medicine used one per wound
//Bullets 1 to hunt, though can spend more to increase chance of success.
//Days how many days that they have survied.
//Health, everyone starts with three health. Good, okay, bad, dead.
cout << "\nFood: " << food << " Wood: " << wood << " Medicine: " << medicine << " Bullets: " << bullets << " Health: " << health << endl;
while (health > 0){
cout << "\nDay: " << days;
cout << "\nFood: " << food
<< "\nWood: " << wood
<< "\nMedicine: " << medicine
<< "\nBullets: " << bullets
<< "\nHealth: " << health
<< "\nMoney: " << money << endl;
if (food >= 1){
food--;
}
if (wood >= 1){
wood--;
}
if (food <= 0){
health--;
cout << "Health lost due to lack of food" << endl;
}
if (health < healthMax && medicine > 0){
health++;
medicine--;
cout << "Health pack used to heal your character\nHealth : " << health << endl;
}
action = '0';
cout << "\n1: Find food" << endl;
cout << "What's your action? ";
cin >> action;
cout << endl;
if (action == '1'){
//
//Section for random sites to search.
//
//
randNumber = rand() % 4;
description = "";
//Maybe + days at the end, and subtract some, so that they eventually run out of places to check.
if (randNumber >= 0 && randNumber < 2) {
place = "supermarket";
foodTemp = (rand() % 4) + 1;
woodTemp = (rand() % 2) + 0;
bulletsTemp = (rand() % 2) + 0;
medicineTemp = (rand() % 2) + 1;
moneyTemp = (rand() % 5) + 5;
}
if (randNumber >= 2 && randNumber < 4) {
place = "boat house";
foodTemp = (rand() % 2) + 1;
woodTemp = (rand() % 4) + 1;
bulletsTemp = (rand() % 2) + 0;
medicineTemp = (rand() % 2) + 0;
moneyTemp = (rand() % 3) + 0;
}
cout << "You have come to the " << place << "." << endl;
cout << description << endl;
food += foodTemp;
wood += woodTemp;
bullets += bulletsTemp;
medicine += medicineTemp;
money += moneyTemp;
if (foodTemp > 0)
cout << "You have found " << foodTemp << " food." << endl;
if (woodTemp > 0)
cout << "You have found " << woodTemp << " wood." << endl;
if (medicineTemp > 0)
cout << "You have found " << medicineTemp << " medicine." << endl;
if (bulletsTemp > 0)
cout << "You have found " << bulletsTemp << " bullets." << endl;
if (moneyTemp > 0)
cout << "You have found " << moneyTemp << " money." << endl;
cout << "\nFood: " << food << " Wood: " << wood << " Medicine: " << medicine << " Bullets: " << bullets
<< " Health: " << health << " Money: " << money << endl;
//End of search rooms.
}
//Random encounter chance to see if they can gain additional items.
encounterHurt = 0;
randomEncounter = rand() % 8;
cin.ignore(1, '\n');
if (randomEncounter == 1 && clown == true){
encounterChoice = 1;
cout << "\n\nYou were visited by a gifting clown. \nOn a scale of 0-10, how badly do you want a gift? ";
while (encounterChoice >= 0 && encounterChoice <= 10){
cin >> encounterChoice;
encounterFood = (rand() % 3) + encounterChoice / 2;
encounterWood = (rand() % 3) + encounterChoice / 2;
encounterMedicine = (rand() % 2);
encounterBullets = (rand() % 2);
if (encounterChoice > 0){
encounterHurt = (rand() % 10) - encounterChoice;
if (encounterHurt <= 1){
health--;
cout << "The crazy clown stabs you, but still provides gifts.";
}
}
if (encounterFood > 0) {
cout << "\nYou were provided with " << encounterFood << " food." << endl;
food += encounterFood;
}
if (encounterWood > 0) {
cout << "\nYou were provided with " << encounterWood << " wood." << endl;
wood += encounterWood;
}
if (encounterMedicine > 0) {
cout << "\nYou were provided with " << encounterMedicine << " medicine." << endl;
medicine += encounterMedicine;
}
if (encounterBullets > 0) {
cout << "\nYou were provided with " << encounterBullets << " bullets." << endl;
bullets += encounterBullets;
}
encounterChoice = 11;
}
//Option to attack clown
//
//
}
//End of random encounter from the clown.
//Pause mechanic to prevent the game from cycling.
// pause = 'b';
// while (pause != 'a'){
// cout << "\nEnter a to continue: ";
// cin >> pause;
// }
//End of game message
cout << endl;
if (days == 100){
cout << "You have made it to 100 days. You have beaten this game. You can quit now, or try to see how long you'll last." << endl;
}
//Add day at end of while loop.
days++;
}
cout << "You have died after " << days << " days" << endl;
}
</code></pre>
| 0debug
|
def subject_marks(subjectmarks):
#subject_marks = [('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)])
subjectmarks.sort(key = lambda x: x[1])
return subjectmarks
| 0debug
|
php code to solve this i am new to php.I have 2 tables named "registration" table and "first_allotement" table : Please can anyone help me out with php code to solve this i am new to php.I have 2 tables named "registration" table and "first_allotement" table
'registration' Table:
Altno | pid | appno | name | college1 | college2 | college3 | college4 | college5 | college6 | college7 | college8 | college9 | college10
'first_allotement' Table:
Altno | appno | name | college | curdate | markdate | total | pdf
I need to empty the fields 'college1','college2'.....'college10' in 'registration' table, only if the 'college' field in 'first_allotement' table data is same as to any of the 'college1' or 'college2'....fields in registration table here datas from both tables are selected according to 'appno' field of both table
| 0debug
|
Best way to handle data for several options C# : <p>My program workflow:</p>
<p>1) Show menu</p>
<p>2) Catch option by switch</p>
<p>2.1)Add float to a list </p>
<p>2.2)Increment int1</p>
<p>2.3)Increment int2</p>
<p>2.4)Show inputs</p>
<p>Now I wanna to add a generator which will print in console how my fiber track looks like. For ex:</p>
<p>1) Added a section of 20km lenght</p>
<p>2) Added a weld in latest secion</p>
<p>3) Added a regenerator</p>
<p>4) Added connector</p>
<p>5) Added section of 10km lenght</p>
<p>And I want to get in my console:</p>
<blockquote>
<p>This is how your track looks like:
[Transmitter]-> [--20km track--] -> [Weld] -> [Regenerator] -> [Connector] > -> [--10km track--]</p>
</blockquote>
<p>First question is what kind of List should I create to handle my track design? I tought only to make a integer list, and make a encoding method to convert for example 1 to section 2 for weld 3 for connector etc.</p>
<p>Any suggestions would be nice! Thank you for your time and patience.</p>
<pre><code>public class Program
{
public int WeldCount;
public int ConnectroCount;
public List<float> section = new List<float>();
//public List<> TrackElements = new List<>();
public Program()
{
section.Add(0);
}
public void showResults()
{
float allSections = 0;
foreach (float item in section)
{
allSections += item;
}
Console.Clear();
Console.WriteLine("Weld count: {0}, connector count: {1}, sum of sections: {2}", WeldCount,ConnectroCount,allSections);
Console.ReadKey();
}
public void finalConstruction()
{
}
public static void mainMenu()
{
Console.Clear();
Console.WriteLine("\n");
Console.WriteLine("Add: \n1. Section \n2. Weld \n3. Regenerator\n4. Show results");
}
public void menuChoose()
{
var key = Console.ReadKey();
switch (key.Key)
{
case ConsoleKey.D1:
case ConsoleKey.NumPad1:
Console.Clear();
Console.WriteLine("Give lenght:");
float result;
float.TryParse(Console.ReadLine(), out result);
section.Add(result);
mainMenu();
menuChoose();
break;
case ConsoleKey.D2:
WeldCount++;
mainMenu();
menuChoose();
break;
case ConsoleKey.D3:
ConnectroCount++;
mainMenu();
menuChoose();
break;
case ConsoleKey.D4:
showResults();
mainMenu();
menuChoose();
break;
default:
Console.WriteLine("Coś ty odjebał");
break;
}
}
static void Main(string[] args)
{
Program program = new Program();
mainMenu();
program.menuChoose();
}
}
</code></pre>
| 0debug
|
static void vfio_pci_write_config(PCIDevice *pdev, uint32_t addr,
uint32_t val, int len)
{
VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
uint32_t val_le = cpu_to_le32(val);
DPRINTF("%s(%04x:%02x:%02x.%x, @0x%x, 0x%x, len=0x%x)\n", __func__,
vdev->host.domain, vdev->host.bus, vdev->host.slot,
vdev->host.function, addr, val, len);
if (pwrite(vdev->fd, &val_le, len, vdev->config_offset + addr) != len) {
error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x, 0x%x) failed: %m",
__func__, vdev->host.domain, vdev->host.bus,
vdev->host.slot, vdev->host.function, addr, val, len);
}
if (addr < PCI_CONFIG_HEADER_SIZE) {
pci_default_write_config(pdev, addr, val, len);
return;
}
if (pdev->cap_present & QEMU_PCI_CAP_MSI &&
ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size)) {
int is_enabled, was_enabled = msi_enabled(pdev);
pci_default_write_config(pdev, addr, val, len);
is_enabled = msi_enabled(pdev);
if (!was_enabled && is_enabled) {
vfio_enable_msi(vdev);
} else if (was_enabled && !is_enabled) {
vfio_disable_msi(vdev);
}
}
if (pdev->cap_present & QEMU_PCI_CAP_MSIX &&
ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) {
int is_enabled, was_enabled = msix_enabled(pdev);
pci_default_write_config(pdev, addr, val, len);
is_enabled = msix_enabled(pdev);
if (!was_enabled && is_enabled) {
vfio_enable_msix(vdev);
} else if (was_enabled && !is_enabled) {
vfio_disable_msix(vdev);
}
}
}
| 1threat
|
want to find specific string from given text using regex : <p>I want specific string from below text using regex.</p>
<pre><code>str = 'Supervision68 - Outdoor Supervision In Compliance922 KAR 2:100 -
Section 10(15) Each child'
</code></pre>
<p>Specific string : '68 - Outdoor Supervision In Compliance'</p>
<p>I have tried an get below result:</p>
<pre><code>re.findall('\d+(.*?)922', str)
</code></pre>
<p>result: ' - Outdoor Supervision In Compliance'</p>
| 0debug
|
import re
def end_num(string):
text = re.compile(r".*[0-9]$")
if text.match(string):
return True
else:
return False
| 0debug
|
How to access all children of linearLayout? : <p>I have imageviews inside a linearlayout. I am trying to get all the imageviews(children) when its parent(linearlayout) is clicked. Could you please tell me how to access all the children of linearlayout when the linearlayout is clicked? </p>
| 0debug
|
Android - Use cases of Context in Android Development (Fragment, etc) : In the time I have spent learning Android Development, I have realized that the use of "Context" is a common theme in nearly everything we do.<br>
I recently read the following Article, and all of it's references: [What is it about Context](http://lomza.totem-soft.com/what-is-it-about-context-in-android/)?<br>
<br>
In addition to this being an informative resource regarding Context, I had an additional question, based on something it states..<br>
It says (and I quote): `(6) When in fragment, assign a context to the one from onAttach(Context context) method`<br>
<br>
**QUESTION (1) :** I am currently trying to adjust some Preferences using the `Preferencec-API` from within a `PreferenceFragment`.. In terms of `Context`, how should I go about this?<br>
**NOTE :** I am doing this from within `onPreferenceChangedListener`.<br>
<br>
**QUESTION (2) :** Is there a simple answer, or must I follow the instructions from the Quote I provided from the Link? And if so, how would I go about doing this, as my PreferenceFragment does not have any `onAttach` Method?<br>
<br>
**Many thanks in advance!**
| 0debug
|
VBA Help: Simple Arithmetic Operations : I am completely new to VBA and I need some help. I have made the object so I will use that to describe my problem. I want to make program that takes in 4 user inputs (cost of product, number of units sold, number of units returned, and cost of fix per unit) and then calculates 6 things from it such as total earnings (cost of product x number of units sold) and total returned cost (cost of product x number of units returned). How would I go about writing the code?
Thank you so much for your time! Please check out object image here: http://imgur.com/a/qc3Kk
| 0debug
|
TS2531: Object is possibly 'null' : <p>I have the following function:-</p>
<pre><code>uploadPhoto() {
var nativeElement: HTMLInputElement = this.fileInput.nativeElement;
this.photoService.upload(this.vehicleId, nativeElement.files[0])
.subscribe(x => console.log(x));
}
</code></pre>
<p>however on the nativeElement.files[0], I am getting a typescript error, "Object is possibly 'null'". Anyone can help me solve this issue? </p>
<p>I tried to declare the nativeElement as a null value, however did not manage to succeed.</p>
<p>Thanks for your help and time.</p>
| 0debug
|
Refresh Today Widget every time opened : <p>I thought that Today View every time when i open it it calls "viewWillAppear" but its not. When i change something in my app, and then I slide down for Today View it sometimes refresh the view and sometimes not.</p>
<p>I do all logic in viewWillAppear (fetch data from coreData and put that data to labels), but its not called everytime.</p>
<pre><code>override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
fetchContent()
setLabels()
setContentHeight()
tableView.reloadData()
print("view will appear")
}
</code></pre>
<p>how to call fetchContent and setLabels every time when user opens Today Extensions?</p>
| 0debug
|
int slirp_is_inited(void)
{
return slirp_inited;
}
| 1threat
|
static void stereo_processing(PSContext *ps, INTFLOAT (*l)[32][2], INTFLOAT (*r)[32][2], int is34)
{
int e, b, k;
INTFLOAT (*H11)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H11;
INTFLOAT (*H12)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H12;
INTFLOAT (*H21)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H21;
INTFLOAT (*H22)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H22;
int8_t *opd_hist = ps->opd_hist;
int8_t *ipd_hist = ps->ipd_hist;
int8_t iid_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];
int8_t icc_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];
int8_t ipd_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];
int8_t opd_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];
int8_t (*iid_mapped)[PS_MAX_NR_IIDICC] = iid_mapped_buf;
int8_t (*icc_mapped)[PS_MAX_NR_IIDICC] = icc_mapped_buf;
int8_t (*ipd_mapped)[PS_MAX_NR_IIDICC] = ipd_mapped_buf;
int8_t (*opd_mapped)[PS_MAX_NR_IIDICC] = opd_mapped_buf;
const int8_t *k_to_i = is34 ? k_to_i_34 : k_to_i_20;
TABLE_CONST INTFLOAT (*H_LUT)[8][4] = (PS_BASELINE || ps->icc_mode < 3) ? HA : HB;
if (ps->num_env_old) {
memcpy(H11[0][0], H11[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H11[0][0][0]));
memcpy(H11[1][0], H11[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H11[1][0][0]));
memcpy(H12[0][0], H12[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H12[0][0][0]));
memcpy(H12[1][0], H12[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H12[1][0][0]));
memcpy(H21[0][0], H21[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H21[0][0][0]));
memcpy(H21[1][0], H21[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H21[1][0][0]));
memcpy(H22[0][0], H22[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H22[0][0][0]));
memcpy(H22[1][0], H22[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H22[1][0][0]));
}
if (is34) {
remap34(&iid_mapped, ps->iid_par, ps->nr_iid_par, ps->num_env, 1);
remap34(&icc_mapped, ps->icc_par, ps->nr_icc_par, ps->num_env, 1);
if (ps->enable_ipdopd) {
remap34(&ipd_mapped, ps->ipd_par, ps->nr_ipdopd_par, ps->num_env, 0);
remap34(&opd_mapped, ps->opd_par, ps->nr_ipdopd_par, ps->num_env, 0);
}
if (!ps->is34bands_old) {
map_val_20_to_34(H11[0][0]);
map_val_20_to_34(H11[1][0]);
map_val_20_to_34(H12[0][0]);
map_val_20_to_34(H12[1][0]);
map_val_20_to_34(H21[0][0]);
map_val_20_to_34(H21[1][0]);
map_val_20_to_34(H22[0][0]);
map_val_20_to_34(H22[1][0]);
ipdopd_reset(ipd_hist, opd_hist);
}
} else {
remap20(&iid_mapped, ps->iid_par, ps->nr_iid_par, ps->num_env, 1);
remap20(&icc_mapped, ps->icc_par, ps->nr_icc_par, ps->num_env, 1);
if (ps->enable_ipdopd) {
remap20(&ipd_mapped, ps->ipd_par, ps->nr_ipdopd_par, ps->num_env, 0);
remap20(&opd_mapped, ps->opd_par, ps->nr_ipdopd_par, ps->num_env, 0);
}
if (ps->is34bands_old) {
map_val_34_to_20(H11[0][0]);
map_val_34_to_20(H11[1][0]);
map_val_34_to_20(H12[0][0]);
map_val_34_to_20(H12[1][0]);
map_val_34_to_20(H21[0][0]);
map_val_34_to_20(H21[1][0]);
map_val_34_to_20(H22[0][0]);
map_val_34_to_20(H22[1][0]);
ipdopd_reset(ipd_hist, opd_hist);
}
}
for (e = 0; e < ps->num_env; e++) {
for (b = 0; b < NR_PAR_BANDS[is34]; b++) {
INTFLOAT h11, h12, h21, h22;
h11 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][0];
h12 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][1];
h21 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][2];
h22 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][3];
if (!PS_BASELINE && ps->enable_ipdopd && b < NR_IPDOPD_BANDS[is34]) {
INTFLOAT h11i, h12i, h21i, h22i;
INTFLOAT ipd_adj_re, ipd_adj_im;
int opd_idx = opd_hist[b] * 8 + opd_mapped[e][b];
int ipd_idx = ipd_hist[b] * 8 + ipd_mapped[e][b];
INTFLOAT opd_re = pd_re_smooth[opd_idx];
INTFLOAT opd_im = pd_im_smooth[opd_idx];
INTFLOAT ipd_re = pd_re_smooth[ipd_idx];
INTFLOAT ipd_im = pd_im_smooth[ipd_idx];
opd_hist[b] = opd_idx & 0x3F;
ipd_hist[b] = ipd_idx & 0x3F;
ipd_adj_re = AAC_MADD30(opd_re, ipd_re, opd_im, ipd_im);
ipd_adj_im = AAC_MSUB30(opd_im, ipd_re, opd_re, ipd_im);
h11i = AAC_MUL30(h11, opd_im);
h11 = AAC_MUL30(h11, opd_re);
h12i = AAC_MUL30(h12, ipd_adj_im);
h12 = AAC_MUL30(h12, ipd_adj_re);
h21i = AAC_MUL30(h21, opd_im);
h21 = AAC_MUL30(h21, opd_re);
h22i = AAC_MUL30(h22, ipd_adj_im);
h22 = AAC_MUL30(h22, ipd_adj_re);
H11[1][e+1][b] = h11i;
H12[1][e+1][b] = h12i;
H21[1][e+1][b] = h21i;
H22[1][e+1][b] = h22i;
}
H11[0][e+1][b] = h11;
H12[0][e+1][b] = h12;
H21[0][e+1][b] = h21;
H22[0][e+1][b] = h22;
}
for (k = 0; k < NR_BANDS[is34]; k++) {
LOCAL_ALIGNED_16(INTFLOAT, h, [2], [4]);
LOCAL_ALIGNED_16(INTFLOAT, h_step, [2], [4]);
int start = ps->border_position[e];
int stop = ps->border_position[e+1];
INTFLOAT width = Q30(1.f) / ((stop - start) ? (stop - start) : 1);
#if USE_FIXED
width = FFMIN(2U*width, INT_MAX);
#endif
b = k_to_i[k];
h[0][0] = H11[0][e][b];
h[0][1] = H12[0][e][b];
h[0][2] = H21[0][e][b];
h[0][3] = H22[0][e][b];
if (!PS_BASELINE && ps->enable_ipdopd) {
if ((is34 && k <= 13 && k >= 9) || (!is34 && k <= 1)) {
h[1][0] = -H11[1][e][b];
h[1][1] = -H12[1][e][b];
h[1][2] = -H21[1][e][b];
h[1][3] = -H22[1][e][b];
} else {
h[1][0] = H11[1][e][b];
h[1][1] = H12[1][e][b];
h[1][2] = H21[1][e][b];
h[1][3] = H22[1][e][b];
}
}
h_step[0][0] = AAC_MSUB31_V3(H11[0][e+1][b], h[0][0], width);
h_step[0][1] = AAC_MSUB31_V3(H12[0][e+1][b], h[0][1], width);
h_step[0][2] = AAC_MSUB31_V3(H21[0][e+1][b], h[0][2], width);
h_step[0][3] = AAC_MSUB31_V3(H22[0][e+1][b], h[0][3], width);
if (!PS_BASELINE && ps->enable_ipdopd) {
h_step[1][0] = AAC_MSUB31_V3(H11[1][e+1][b], h[1][0], width);
h_step[1][1] = AAC_MSUB31_V3(H12[1][e+1][b], h[1][1], width);
h_step[1][2] = AAC_MSUB31_V3(H21[1][e+1][b], h[1][2], width);
h_step[1][3] = AAC_MSUB31_V3(H22[1][e+1][b], h[1][3], width);
}
ps->dsp.stereo_interpolate[!PS_BASELINE && ps->enable_ipdopd](
l[k] + 1 + start, r[k] + 1 + start,
h, h_step, stop - start);
}
}
}
| 1threat
|
Mocking an API response type : <p>I have function which accepts an Oracle Jolt ServletResult. I'm looking to unit test this function to verify that it correctly uses the data that it's been passed. ServletResult has a protected Constructor and the objects seem to be created internally in Jolt by a Factory. </p>
<p>I've tried Mocking the ServletResult, but that almost requires re-implementing it. The other option I was thinking about was using reflection to create the object. It seems though that Spring ReflectionTestUtils doesn't seem to handle constructors. </p>
<p>What is the best way to deal with this sort of thing? Should such tests just be left to integration testing rather than unit testing? </p>
| 0debug
|
void check_aligned_anonymous_unfixed_colliding_mmaps(void)
{
char *p1;
char *p2;
char *p3;
uintptr_t p;
int i;
fprintf (stderr, "%s", __func__);
for (i = 0; i < 0x2fff; i++)
{
int nlen;
p1 = mmap(NULL, pagesize, PROT_READ,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
fail_unless (p1 != MAP_FAILED);
p = (uintptr_t) p1;
fail_unless ((p & pagemask) == 0);
memcpy (dummybuf, p1, pagesize);
p2 = mmap(NULL, pagesize, PROT_READ,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
fail_unless (p2 != MAP_FAILED);
p = (uintptr_t) p2;
fail_unless ((p & pagemask) == 0);
memcpy (dummybuf, p2, pagesize);
munmap (p1, pagesize);
nlen = pagesize * 8;
p3 = mmap(NULL, nlen, PROT_READ,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p3 < p2
&& (p3 + nlen) > p2)
fail_unless (0);
memcpy (dummybuf, p3, pagesize);
fail_unless (p3 != MAP_FAILED);
p = (uintptr_t) p3;
fail_unless ((p & pagemask) == 0);
munmap (p2, pagesize);
munmap (p3, nlen);
}
fprintf (stderr, " passed\n");
}
| 1threat
|
c#. How to Highlight Link in textbox : I have to create some controls similar to a control Textbox. But I want this control can Highlight link as Richtextbox, Because i have problem with Richtextbox so i can't use richtexbox , how to highlight link in textbox? or I have to set each property by a line of code?
| 0debug
|
How to Get File info from Multiple Folders : I have multiple file listed in files.txt These files are located in different folders. I need to get the file info such as date modified and size and then export them in a text or csv file.
Is there a command in Windows or how can I put it in batch file or Power shell script? Thanks!
contents of files.txt:
c:\windows\system32\file1.dll
c:\windows\temp\file2.dll
c:\program files\file3.exe
and so on....
| 0debug
|
how to remove Dynamic UITextField from Subview : how to remove array of UITextField from Scroll Subview, initially when i call Api i get some Array Value based on Count i have created Dynamic UITextFiled in My View, But i do no how to remove the Subview
**here my sample Code :**
// NSArray *strings;
// UIScrollView *scrollView;
// NSMutableArray *textFields;
self.textFields = [NSMutableArray array];
const CGFloat width = 320;
const CGFloat height = 31;
const CGFloat margin = 0;
CGFloat y = 0;
for(NSString *string in strings) {
UITextField *textField = [[UITextField alloc]
initWithFrame:CGRectMake(0, y, width, height)];
textField.delegate = self;
textField.text = string;
[scrollView addSubview:textField];
[textFields addObject:textField];
[textField release];
y += height + margin;
}
scrollView.contentSize = CGSizeMake(width, y - margin);
| 0debug
|
static void jpeg2000_flush(Jpeg2000DecoderContext *s)
{
if (*s->buf == 0xff)
s->buf++;
s->bit_index = 8;
s->buf++;
}
| 1threat
|
int inet_connect(const char *str, Error **errp)
{
QemuOpts *opts;
int sock = -1;
opts = qemu_opts_create(&dummy_opts, NULL, 0, NULL);
if (inet_parse(opts, str) == 0) {
sock = inet_connect_opts(opts, true, NULL, errp);
} else {
error_set(errp, QERR_SOCKET_CREATE_FAILED);
}
qemu_opts_del(opts);
return sock;
}
| 1threat
|
When I select the incorrect answer the next question loads with the the answer already displayed : I am completely new to coding and c#. I am studying a level 3 ICT and in my programming subject we are asked to make a quiz for essential skills students(Using forms.).
I have been asked to create a very basic login in screen, topic selection screen, level selection screen and the actual questions and answers; answers are buttons.
My issue is when I select the incorrect answer the next question loads but displays the correct answer for that question.
Not quite sure what I need to do. I wanted to get this fixed over the weekend so I am unable to ask my teacher.
The must remain very basic.
Here is my code. I appreciate any help on this topic, Thanks.
Level 0 Form -
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EssentialSkills.Numeracy
{
public partial class Level0num : Form
{
Point p1 = new Point(142, 303);
Point p2 = new Point(322, 303);
Point p3 = new Point(499, 303);
List<Point> points = new List<Point>();
public Level0num()
{
InitializeComponent();
Globals.listQuestionsNum0.Add("1 + 1");
Globals.listQuestionsNum0.Add("9 x 1");
Globals.listQuestionsNum0.Add("10 x 3");
Globals.listQuestionsNum0.Add("3 / 3");
Globals.listQuestionsNum0.Add("2 + 5 + 6");
Globals.listQuestionsNum0.Add("8 x 3");
Globals.listQuestionsNum0.Add("99 - 87");
Globals.listQuestionsNum0.Add("60 + 10 ");
Globals.listQuestionsNum0.Add("55 + 15");
Globals.listQuestionsNum0.Add("40 x 20");
Globals.listQuestionsNum0.Add("120 / 60");
Globals.listQuestionsNum0.Add("1.0 + 1.2");
Globals.listQuestionsNum0.Add("3 x 13");
Globals.listQuestionsNum0.Add("2 x 2");
Globals.listQuestionsNum0.Add("10 x 30");
Globals.listQuestionsNum0.Add("8 x 9");
Globals.listQuestionsNum0.Add("9 x 9");
Globals.listQuestionsNum0.Add("3 x 1");
Globals.listQuestionsNum0.Add("4 / 4");
Globals.listQuestionsNum0.Add("21 / 7");
Globals.listQuestionsNum0.Add("42 / 7");
Globals.listQuestionsNum0.Add("10 + 10 - 1");
Globals.listQuestionsNum0.Add("84 - 2 + 3");
Globals.listQuestionsNum0.Add("50 + 9 + 8");
Globals.listQuestionsNum0.Add("-1 + 2");
Globals.listQuestionsNum0.Add("33 + 88");
Globals.listQuestionsNum0.Add("10 - 3");
Globals.listQuestionsNum0.Add("32 + 2 x 1");
Globals.listQuestionsNum0.Add("1 x 543 + 1");
Globals.listQuestionsNum0.Add("3 + 10 x 2");
Globals.listAnswersNum0.Add(1 + 1);
Globals.listAnswersNum0.Add(9 * 1);
Globals.listAnswersNum0.Add(10 * 3);
Globals.listAnswersNum0.Add(3 / 3);
Globals.listAnswersNum0.Add(2 + 5 + 6);
Globals.listAnswersNum0.Add(8 * 3);
Globals.listAnswersNum0.Add(99 - 87);
Globals.listAnswersNum0.Add(60 + 10);
Globals.listAnswersNum0.Add(55 + 15);
Globals.listAnswersNum0.Add(40 * 20);
Globals.listAnswersNum0.Add(120 / 60);
Globals.listAnswersNum0.Add(1.0 + 1.2);
Globals.listAnswersNum0.Add(3 * 13);
Globals.listAnswersNum0.Add(2 * 2);
Globals.listAnswersNum0.Add(10 * 30);
Globals.listAnswersNum0.Add(8 * 9);
Globals.listAnswersNum0.Add(9 * 9);
Globals.listAnswersNum0.Add(3 * 1);
Globals.listAnswersNum0.Add(4 / 4);
Globals.listAnswersNum0.Add(21 / 7);
Globals.listAnswersNum0.Add(42 / 7);
Globals.listAnswersNum0.Add(10 + 10 - 1);
Globals.listAnswersNum0.Add(84 - 2 + 3);
Globals.listAnswersNum0.Add(50 + 9 + 8);
Globals.listAnswersNum0.Add(-1 + 2);
Globals.listAnswersNum0.Add(33 + 88);
Globals.listAnswersNum0.Add(10 - 3);
Globals.listAnswersNum0.Add(32 + 2 * 1);
Globals.listAnswersNum0.Add(1 * 543 * 1);
Globals.listAnswersNum0.Add(3 + 10 * 2);
points.Add(p1);
points.Add(p2);
points.Add(p3);
}
private void LoadQuestions()
{
lblCountdownval.Visible = false;
lblCountdown.Visible = false;
Globals.intQuestionNumber += 1;
lblQuestionsNumber.Text = "Question Number: " + Globals.intQuestionNumber.ToString();
Random random = new Random();
Globals.listIndex = random.Next(0, Globals.listAnswersNum0.Count - 1);
lblQuestion.Text = Globals.listQuestionsNum0.ElementAt(Globals.listIndex);
btnCorrect.Text = Globals.listAnswersNum0.ElementAt(Globals.listIndex).ToString();
btnAnswer1.Text = random.Next(100).ToString();
btnAnswer3.Text = random.Next(100).ToString();
int locationIndex = random.Next(0, 3);
btnCorrect.Location = points.ElementAt(locationIndex);
locationIndex = random.Next(0, 3);
btnAnswer1.Location = points.ElementAt(locationIndex);
while ((btnAnswer1.Location == btnCorrect.Location))
{
locationIndex = random.Next(0, 3);
btnAnswer1.Location = points.ElementAt(locationIndex);
}
locationIndex = random.Next(0, 3);
btnAnswer3.Location = points.ElementAt(locationIndex);
while ((btnAnswer3.Location == btnCorrect.Location) || (btnAnswer3.Location == btnAnswer1.Location))
{
locationIndex = random.Next(0, 3);
btnAnswer3.Location = points.ElementAt(locationIndex);
}
}
public void showCorrectAnswer()
{
timerLoadQuestion.Start();
lblCountdownval.Visible = true;
lblCountdown.Visible = true;
lblCountdownval.Text = "5";
lblCountdown.Text = "Next question will load in .... ";
btnAnswer1.Visible = false;
btnAnswer3.Visible = false;
btnCorrect.Location = p2;
btnCorrect.BackColor = Color.Green;
}
private void Level0num_Load(object sender, EventArgs e)
{
lblLoggedUser.Text = Globals.loggedUser;
lblQuestionsNumber.Text = "Question Number: ";
LoadQuestions();
Globals.s = 0;
lblScore.Text = "Score: " + Globals.s;
}
private void btnBack_Click(object sender, EventArgs e)
{
frmNumeracy back = new frmNumeracy();
this.Close();
back.ShowDialog();
}
private void btnAnswer1_Click(object sender, EventArgs e)
{
showCorrectAnswer();
MessageBox.Show("Incorrect");
LoadQuestions();
}
private void btnAnswer3_Click(object sender, EventArgs e)
{
showCorrectAnswer();
MessageBox.Show("Incorrect");
LoadQuestions();
}
private void btnCorrect_Click(object sender, EventArgs e)
{
MessageBox.Show("Correct!");
Globals.s += 1;
lblScore.Text = "Score: " + Globals.s.ToString();
LoadQuestions();
}
}
}
```
here is my globals class:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EssentialSkills
{
public static class Globals
{
public static string username, password;
public static string user1, user2, user3, user4, user5, user6, loggedUser, admin;
public static string pass1, pass2, pass3, pass4, pass5, pass6, adminPass1;
public static List<string> listQuestionsNum0 = new List<string>();
public static List<double> listAnswersNum0 = new List<double>();
public static int intQuestionNumber = 0;
public static int listIndex;
public static int s;
}
}
```
Many thanks.
| 0debug
|
How is this c++ code with default parameters can be compiled? : <p>Here is a simple example program which demonstrates what I want to asking for:</p>
<pre><code>class A {
public:
int writemem(FilInfo* file, IN BYTE* mem, IN DWORD memSize, BYTE obfs=0, BOOL bEnc=TRUE);
};
void main() {
...
(this->writemem(file, mem, memSize), obfs); // does not print compilation error!
...
}
</code></pre>
<p>How is the above code compilable? Compiling the above program was successful although it does not work what I intended.
I am working on Windows 8.1 with VisualStudio SDK 7.1.</p>
| 0debug
|
Django ImportError: cannot import name 'render_to_response' from 'django.shortcuts' : <p>After upgrading to Django 3.0, I get the following error:</p>
<pre><code>ImportError: cannot import name 'render_to_response' from 'django.shortcuts'
</code></pre>
<p>My view:</p>
<pre><code>from django.shortcuts import render_to_response
from django.template import RequestContext
def index(request):
context = {'foo': 'bar'}
return render_to_response('index.html', context, context_instance=RequestContext(request))
</code></pre>
<p>Here is the full traceback:</p>
<pre><code>Traceback (most recent call last):
File "./manage.py", line 21, in <module>
main()
File "./manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute
super().execute(*args, **options)
File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 95, in handle
self.run(**options)
File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 102, in run
autoreload.run_with_reloader(self.inner_run, **options)
File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/utils/autoreload.py", line 580, in run_with_reloader
start_django(reloader, main_func, *args, **kwargs)
File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/utils/autoreload.py", line 565, in start_django
reloader.run(django_main_thread)
File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/utils/autoreload.py", line 272, in run
get_resolver().urlconf_module
File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/urls/resolvers.py", line 572, in urlconf_module
return import_module(self.urlconf_name)
File "/Users/alasdair/.pyenv/versions/3.7.2/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/alasdair/dev/myproject/myproject/urls.py", line 19, in <module>
from myapp import views
File "/Users/alasdair/dev/myproject/myapp/views.py", line 8, in <module>
from django.shortcuts import render_to_response
ImportError: cannot import name 'render_to_response' from 'django.shortcuts' (/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/shortcuts.py)
</code></pre>
| 0debug
|
static void sun4uv_init(MemoryRegion *address_space_mem,
MachineState *machine,
const struct hwdef *hwdef)
{
SPARCCPU *cpu;
M48t59State *nvram;
unsigned int i;
uint64_t initrd_addr, initrd_size, kernel_addr, kernel_size, kernel_entry;
PCIBus *pci_bus, *pci_bus2, *pci_bus3;
ISABus *isa_bus;
qemu_irq *ivec_irqs, *pbm_irqs;
DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];
DriveInfo *fd[MAX_FD];
FWCfgState *fw_cfg;
cpu = cpu_devinit(machine->cpu_model, hwdef);
ram_init(0, machine->ram_size);
prom_init(hwdef->prom_addr, bios_name);
ivec_irqs = qemu_allocate_irqs(cpu_set_ivec_irq, cpu, IVEC_MAX);
pci_bus = pci_apb_init(APB_SPECIAL_BASE, APB_MEM_BASE, ivec_irqs, &pci_bus2,
&pci_bus3, &pbm_irqs);
pci_vga_init(pci_bus);
isa_bus = pci_ebus_init(pci_bus, -1, pbm_irqs);
i = 0;
if (hwdef->console_serial_base) {
serial_mm_init(address_space_mem, hwdef->console_serial_base, 0,
NULL, 115200, serial_hds[i], DEVICE_BIG_ENDIAN);
i++;
}
for(; i < MAX_SERIAL_PORTS; i++) {
if (serial_hds[i]) {
serial_isa_init(isa_bus, i, serial_hds[i]);
}
}
for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
if (parallel_hds[i]) {
parallel_init(isa_bus, i, parallel_hds[i]);
}
}
for(i = 0; i < nb_nics; i++)
pci_nic_init_nofail(&nd_table[i], pci_bus, "ne2k_pci", NULL);
ide_drive_get(hd, MAX_IDE_BUS);
pci_cmd646_ide_init(pci_bus, hd, 1);
isa_create_simple(isa_bus, "i8042");
for(i = 0; i < MAX_FD; i++) {
fd[i] = drive_get(IF_FLOPPY, 0, i);
}
fdctrl_init_isa(isa_bus, fd);
nvram = m48t59_init_isa(isa_bus, 0x0074, NVRAM_SIZE, 59);
initrd_size = 0;
initrd_addr = 0;
kernel_size = sun4u_load_kernel(machine->kernel_filename,
machine->initrd_filename,
ram_size, &initrd_size, &initrd_addr,
&kernel_addr, &kernel_entry);
sun4u_NVRAM_set_params(nvram, NVRAM_SIZE, "Sun4u", machine->ram_size,
machine->boot_order,
kernel_addr, kernel_size,
machine->kernel_cmdline,
initrd_addr, initrd_size,
0,
graphic_width, graphic_height, graphic_depth,
(uint8_t *)&nd_table[0].macaddr);
fw_cfg = fw_cfg_init(BIOS_CFG_IOPORT, BIOS_CFG_IOPORT + 1, 0, 0);
fw_cfg_add_i16(fw_cfg, FW_CFG_MAX_CPUS, (uint16_t)max_cpus);
fw_cfg_add_i32(fw_cfg, FW_CFG_ID, 1);
fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)ram_size);
fw_cfg_add_i16(fw_cfg, FW_CFG_MACHINE_ID, hwdef->machine_id);
fw_cfg_add_i64(fw_cfg, FW_CFG_KERNEL_ADDR, kernel_entry);
fw_cfg_add_i64(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);
if (machine->kernel_cmdline) {
fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE,
strlen(machine->kernel_cmdline) + 1);
fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, machine->kernel_cmdline);
} else {
fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, 0);
}
fw_cfg_add_i64(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);
fw_cfg_add_i64(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);
fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, machine->boot_order[0]);
fw_cfg_add_i16(fw_cfg, FW_CFG_SPARC64_WIDTH, graphic_width);
fw_cfg_add_i16(fw_cfg, FW_CFG_SPARC64_HEIGHT, graphic_height);
fw_cfg_add_i16(fw_cfg, FW_CFG_SPARC64_DEPTH, graphic_depth);
qemu_register_boot_set(fw_cfg_boot_set, fw_cfg);
}
| 1threat
|
void HELPER(wfe)(CPUARMState *env)
{
CPUState *cs = CPU(arm_env_get_cpu(env));
cs->exception_index = EXCP_YIELD;
cpu_loop_exit(cs);
}
| 1threat
|
Collapse and expand div without scrollbars appearing : <p>I am using Jquery to try to collapse a div. The element to be collapsed sits above a footer on the page, as illustrated below:</p>
<p><a href="https://i.stack.imgur.com/0Lvt3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Lvt3.png" alt="Initial state"></a></p>
<p>I have a button on the page that when clicked on, calls .animate() to move the div above the footer down so it appears to slide behind the footer and out of view - basically, to collapse down.</p>
<p>However, when the div moves beyond the bottom of the window, the browsers vertical scrollbar becomes active until I hide the div being collapsed, ie:</p>
<p><a href="https://i.stack.imgur.com/ysoAx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ysoAx.png" alt="div collapses down behind footer"></a></p>
<p>I would like to see the div collapse down to nothing WITHOUT the vertical scrollbar effect.</p>
<p>I also tried to animate on the height, but that causes the div to shrink starting at the bottom moving UP until the height is zero.</p>
<p>What is the trick to having a div collapse DOWN to nothing without having the vertical scroll bar becoming active? Do I have to adjust both top and height?</p>
<p>Thanks in advance.</p>
| 0debug
|
C++ code compiles but doesn't run : <p>I am currently writing a Texas Hold'em code in order to learn more about c++ and gain experience. But I recently ran into a problem in which I have no idea what to do.My code compiles just fine without errors but once I make it run and it arrive at a specific function it just stops working (as in I get an error from CodeBlock saying your program has stopped working). I have tried cutting out parts such as loops in the function to see which specific part is the problem but after a couple of days im still at a stop.
Here is the function and class that I believe is the problem:</p>
<pre><code>class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
public:
void set_name(string a){name=a;}
string print_name(){return name;}
void card_generator();
string set_cards(int c){return cards[c];}
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
int p=0,k;
while(p<6){
k=0;
final_card[0][k]=tempCards[p];
k++;
p++;
}
while(p<12){
k=0;
final_card[1][k]=tempCards[p];
k++;
p++;
}
while(p<17){
k=0;
table_cards[k]=tempCards[p];
k++;
p++;
}
}
</code></pre>
<p>Here is the full code in case I am wrong of the source of the problem:</p>
<pre><code>#include <iostream>
#include <string>
#include <stdlib.h>
#include <ctime>
using namespace std;
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
public:
void set_name(string a){name=a;}
string print_name(){return name;}
void card_generator();
string set_cards(int c){return cards[c];}
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
string Player::cards[53];
string Player::final_card[2][6];
string Player::table_cards[5];
int main () {
int choice1=0, i, max_i, tempV;
string username;
cout<< "Welcome to Texas Hold'Em!\n1-Play\n2-Quit\n";//menu
while((choice1!=1)&&(choice1!=2)){//Makes sure that user enters correct input```
cin>>choice1;
if ((choice1!=1)&&(choice1!=2)){
cout<<"Invalid Input!\nTry again!\n";
}
}
system ("cls");
if (choice1==2){//End Program
return 0;
}
cout<<"How many players?[2-6]"<<endl;
while((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){//Makes sure that user enters correct input
cin>>i;
if ((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){
cout<<"Invalid Input!\nTry again!\n";
}
}
Player player[i];//creating array of players
player[0].card_generator();
max_i = i;//max_i is nb of players
i--;//since arrays start at 0
system("cls");
player[0].set_final_card(i,max_i);
player[0].print_cards();
if (choice1==1) {//SET NAMES OF ALL PLAYERS
for(i=0; i<max_i; i++){
cout<< "Whats your name?\n";
cin>>username;
player[i].set_name(username);
cout<<"Your name is "<< player[i].print_name()<< " and you have "<< player[i].print_bank()<<"$\n";
tempV=i+1;//used bc arrays start at 0
if(tempV!=max_i){
cout<< "Give PC to player "<< i+2 <<endl;
}
_sleep(3000);
system("cls");
}
}
return 0;
}
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
int p=0,k;
while(p<6){
k=0;
final_card[0][k]=tempCards[p];
k++;
p++;
}
while(p<12){
k=0;
final_card[1][k]=tempCards[p];
k++;
p++;
}
while(p<17){
k=0;
table_cards[k]=tempCards[p];
k++;
p++;
}
}
void Player::card_generator(){
string card_value[13];
card_value[0]="1";
card_value[1]="2";
card_value[2]="3";
card_value[3]="4";
card_value[4]="5";
card_value[5]="6";
card_value[6]="7";
card_value[7]="8";
card_value[8]="9";
card_value[9]="10";
card_value[10]="J";
card_value[11]="Q";
card_value[12]="K";
string card_type[4];
card_type[0]="of hearts";
card_type[1]="of diamonds";
card_type[2]="of clubs";
card_type[3]="of spades";
string card[53];
int x=0;
fill_n(card,53,0);
for (int j=0;j<4;j++){
for (int q=0;q<13;q++){
card[x]=card_value[q]+" "+card_type[j];
cards[x]=card[x];
x++;
}
}
}
</code></pre>
<p>If you have any criticism about the code itself even if not directly linked to problem feel free to tell me as I'm doing this to learn :D. Thank you in advance!!</p>
| 0debug
|
NameError: name 'i' is not defined in python : i am using following code to find the sum of digit in python but it shows an error[enter image description here][1]
[1]: https://i.stack.imgur.com/ZX8WN.png
| 0debug
|
ReactorNotRestartable error in while loop with scrapy : <p>I get <code>twisted.internet.error.ReactorNotRestartable</code> error when I execute following code:</p>
<pre><code>from time import sleep
from scrapy import signals
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from scrapy.xlib.pydispatch import dispatcher
result = None
def set_result(item):
result = item
while True:
process = CrawlerProcess(get_project_settings())
dispatcher.connect(set_result, signals.item_scraped)
process.crawl('my_spider')
process.start()
if result:
break
sleep(3)
</code></pre>
<p>For the first time it works, then I get error. I create <code>process</code> variable each time, so what's the problem?</p>
| 0debug
|
static void avc_h_loop_filter_chroma422_msa(uint8_t *src,
int32_t stride,
int32_t alpha_in,
int32_t beta_in,
int8_t *tc0)
{
int32_t col, tc_val;
int16_t out0, out1, out2, out3;
v16u8 alpha, beta, res;
alpha = (v16u8) __msa_fill_b(alpha_in);
beta = (v16u8) __msa_fill_b(beta_in);
for (col = 0; col < 4; col++) {
tc_val = (tc0[col] - 1) + 1;
if (tc_val <= 0) {
src += (4 * stride);
continue;
}
AVC_LPF_H_CHROMA_422(src, stride, tc_val, alpha, beta, res);
out0 = __msa_copy_s_h((v8i16) res, 0);
out1 = __msa_copy_s_h((v8i16) res, 1);
out2 = __msa_copy_s_h((v8i16) res, 2);
out3 = __msa_copy_s_h((v8i16) res, 3);
STORE_HWORD((src - 1), out0);
src += stride;
STORE_HWORD((src - 1), out1);
src += stride;
STORE_HWORD((src - 1), out2);
src += stride;
STORE_HWORD((src - 1), out3);
src += stride;
}
}
| 1threat
|
static void gen_flt3_arith (DisasContext *ctx, uint32_t opc,
int fd, int fr, int fs, int ft)
{
const char *opn = "flt3_arith";
switch (opc) {
case OPC_ALNV_PS:
check_cp1_64bitmode(ctx);
{
TCGv t0 = tcg_temp_local_new();
TCGv_i32 fp = tcg_temp_new_i32();
TCGv_i32 fph = tcg_temp_new_i32();
int l1 = gen_new_label();
int l2 = gen_new_label();
gen_load_gpr(t0, fr);
tcg_gen_andi_tl(t0, t0, 0x7);
tcg_gen_brcondi_tl(TCG_COND_NE, t0, 0, l1);
gen_load_fpr32(fp, fs);
gen_load_fpr32h(ctx, fph, fs);
gen_store_fpr32(fp, fd);
gen_store_fpr32h(ctx, fph, fd);
tcg_gen_br(l2);
gen_set_label(l1);
tcg_gen_brcondi_tl(TCG_COND_NE, t0, 4, l2);
tcg_temp_free(t0);
#ifdef TARGET_WORDS_BIGENDIAN
gen_load_fpr32(fp, fs);
gen_load_fpr32h(ctx, fph, ft);
gen_store_fpr32h(ctx, fp, fd);
gen_store_fpr32(fph, fd);
#else
gen_load_fpr32h(ctx, fph, fs);
gen_load_fpr32(fp, ft);
gen_store_fpr32(fph, fd);
gen_store_fpr32h(ctx, fp, fd);
#endif
gen_set_label(l2);
tcg_temp_free_i32(fp);
tcg_temp_free_i32(fph);
}
opn = "alnv.ps";
break;
case OPC_MADD_S:
check_cop1x(ctx);
{
TCGv_i32 fp0 = tcg_temp_new_i32();
TCGv_i32 fp1 = tcg_temp_new_i32();
TCGv_i32 fp2 = tcg_temp_new_i32();
gen_load_fpr32(fp0, fs);
gen_load_fpr32(fp1, ft);
gen_load_fpr32(fp2, fr);
gen_helper_float_madd_s(fp2, cpu_env, fp0, fp1, fp2);
tcg_temp_free_i32(fp0);
tcg_temp_free_i32(fp1);
gen_store_fpr32(fp2, fd);
tcg_temp_free_i32(fp2);
}
opn = "madd.s";
break;
case OPC_MADD_D:
check_cop1x(ctx);
check_cp1_registers(ctx, fd | fs | ft | fr);
{
TCGv_i64 fp0 = tcg_temp_new_i64();
TCGv_i64 fp1 = tcg_temp_new_i64();
TCGv_i64 fp2 = tcg_temp_new_i64();
gen_load_fpr64(ctx, fp0, fs);
gen_load_fpr64(ctx, fp1, ft);
gen_load_fpr64(ctx, fp2, fr);
gen_helper_float_madd_d(fp2, cpu_env, fp0, fp1, fp2);
tcg_temp_free_i64(fp0);
tcg_temp_free_i64(fp1);
gen_store_fpr64(ctx, fp2, fd);
tcg_temp_free_i64(fp2);
}
opn = "madd.d";
break;
case OPC_MADD_PS:
check_cp1_64bitmode(ctx);
{
TCGv_i64 fp0 = tcg_temp_new_i64();
TCGv_i64 fp1 = tcg_temp_new_i64();
TCGv_i64 fp2 = tcg_temp_new_i64();
gen_load_fpr64(ctx, fp0, fs);
gen_load_fpr64(ctx, fp1, ft);
gen_load_fpr64(ctx, fp2, fr);
gen_helper_float_madd_ps(fp2, cpu_env, fp0, fp1, fp2);
tcg_temp_free_i64(fp0);
tcg_temp_free_i64(fp1);
gen_store_fpr64(ctx, fp2, fd);
tcg_temp_free_i64(fp2);
}
opn = "madd.ps";
break;
case OPC_MSUB_S:
check_cop1x(ctx);
{
TCGv_i32 fp0 = tcg_temp_new_i32();
TCGv_i32 fp1 = tcg_temp_new_i32();
TCGv_i32 fp2 = tcg_temp_new_i32();
gen_load_fpr32(fp0, fs);
gen_load_fpr32(fp1, ft);
gen_load_fpr32(fp2, fr);
gen_helper_float_msub_s(fp2, cpu_env, fp0, fp1, fp2);
tcg_temp_free_i32(fp0);
tcg_temp_free_i32(fp1);
gen_store_fpr32(fp2, fd);
tcg_temp_free_i32(fp2);
}
opn = "msub.s";
break;
case OPC_MSUB_D:
check_cop1x(ctx);
check_cp1_registers(ctx, fd | fs | ft | fr);
{
TCGv_i64 fp0 = tcg_temp_new_i64();
TCGv_i64 fp1 = tcg_temp_new_i64();
TCGv_i64 fp2 = tcg_temp_new_i64();
gen_load_fpr64(ctx, fp0, fs);
gen_load_fpr64(ctx, fp1, ft);
gen_load_fpr64(ctx, fp2, fr);
gen_helper_float_msub_d(fp2, cpu_env, fp0, fp1, fp2);
tcg_temp_free_i64(fp0);
tcg_temp_free_i64(fp1);
gen_store_fpr64(ctx, fp2, fd);
tcg_temp_free_i64(fp2);
}
opn = "msub.d";
break;
case OPC_MSUB_PS:
check_cp1_64bitmode(ctx);
{
TCGv_i64 fp0 = tcg_temp_new_i64();
TCGv_i64 fp1 = tcg_temp_new_i64();
TCGv_i64 fp2 = tcg_temp_new_i64();
gen_load_fpr64(ctx, fp0, fs);
gen_load_fpr64(ctx, fp1, ft);
gen_load_fpr64(ctx, fp2, fr);
gen_helper_float_msub_ps(fp2, cpu_env, fp0, fp1, fp2);
tcg_temp_free_i64(fp0);
tcg_temp_free_i64(fp1);
gen_store_fpr64(ctx, fp2, fd);
tcg_temp_free_i64(fp2);
}
opn = "msub.ps";
break;
case OPC_NMADD_S:
check_cop1x(ctx);
{
TCGv_i32 fp0 = tcg_temp_new_i32();
TCGv_i32 fp1 = tcg_temp_new_i32();
TCGv_i32 fp2 = tcg_temp_new_i32();
gen_load_fpr32(fp0, fs);
gen_load_fpr32(fp1, ft);
gen_load_fpr32(fp2, fr);
gen_helper_float_nmadd_s(fp2, cpu_env, fp0, fp1, fp2);
tcg_temp_free_i32(fp0);
tcg_temp_free_i32(fp1);
gen_store_fpr32(fp2, fd);
tcg_temp_free_i32(fp2);
}
opn = "nmadd.s";
break;
case OPC_NMADD_D:
check_cop1x(ctx);
check_cp1_registers(ctx, fd | fs | ft | fr);
{
TCGv_i64 fp0 = tcg_temp_new_i64();
TCGv_i64 fp1 = tcg_temp_new_i64();
TCGv_i64 fp2 = tcg_temp_new_i64();
gen_load_fpr64(ctx, fp0, fs);
gen_load_fpr64(ctx, fp1, ft);
gen_load_fpr64(ctx, fp2, fr);
gen_helper_float_nmadd_d(fp2, cpu_env, fp0, fp1, fp2);
tcg_temp_free_i64(fp0);
tcg_temp_free_i64(fp1);
gen_store_fpr64(ctx, fp2, fd);
tcg_temp_free_i64(fp2);
}
opn = "nmadd.d";
break;
case OPC_NMADD_PS:
check_cp1_64bitmode(ctx);
{
TCGv_i64 fp0 = tcg_temp_new_i64();
TCGv_i64 fp1 = tcg_temp_new_i64();
TCGv_i64 fp2 = tcg_temp_new_i64();
gen_load_fpr64(ctx, fp0, fs);
gen_load_fpr64(ctx, fp1, ft);
gen_load_fpr64(ctx, fp2, fr);
gen_helper_float_nmadd_ps(fp2, cpu_env, fp0, fp1, fp2);
tcg_temp_free_i64(fp0);
tcg_temp_free_i64(fp1);
gen_store_fpr64(ctx, fp2, fd);
tcg_temp_free_i64(fp2);
}
opn = "nmadd.ps";
break;
case OPC_NMSUB_S:
check_cop1x(ctx);
{
TCGv_i32 fp0 = tcg_temp_new_i32();
TCGv_i32 fp1 = tcg_temp_new_i32();
TCGv_i32 fp2 = tcg_temp_new_i32();
gen_load_fpr32(fp0, fs);
gen_load_fpr32(fp1, ft);
gen_load_fpr32(fp2, fr);
gen_helper_float_nmsub_s(fp2, cpu_env, fp0, fp1, fp2);
tcg_temp_free_i32(fp0);
tcg_temp_free_i32(fp1);
gen_store_fpr32(fp2, fd);
tcg_temp_free_i32(fp2);
}
opn = "nmsub.s";
break;
case OPC_NMSUB_D:
check_cop1x(ctx);
check_cp1_registers(ctx, fd | fs | ft | fr);
{
TCGv_i64 fp0 = tcg_temp_new_i64();
TCGv_i64 fp1 = tcg_temp_new_i64();
TCGv_i64 fp2 = tcg_temp_new_i64();
gen_load_fpr64(ctx, fp0, fs);
gen_load_fpr64(ctx, fp1, ft);
gen_load_fpr64(ctx, fp2, fr);
gen_helper_float_nmsub_d(fp2, cpu_env, fp0, fp1, fp2);
tcg_temp_free_i64(fp0);
tcg_temp_free_i64(fp1);
gen_store_fpr64(ctx, fp2, fd);
tcg_temp_free_i64(fp2);
}
opn = "nmsub.d";
break;
case OPC_NMSUB_PS:
check_cp1_64bitmode(ctx);
{
TCGv_i64 fp0 = tcg_temp_new_i64();
TCGv_i64 fp1 = tcg_temp_new_i64();
TCGv_i64 fp2 = tcg_temp_new_i64();
gen_load_fpr64(ctx, fp0, fs);
gen_load_fpr64(ctx, fp1, ft);
gen_load_fpr64(ctx, fp2, fr);
gen_helper_float_nmsub_ps(fp2, cpu_env, fp0, fp1, fp2);
tcg_temp_free_i64(fp0);
tcg_temp_free_i64(fp1);
gen_store_fpr64(ctx, fp2, fd);
tcg_temp_free_i64(fp2);
}
opn = "nmsub.ps";
break;
default:
MIPS_INVAL(opn);
generate_exception (ctx, EXCP_RI);
return;
}
(void)opn;
MIPS_DEBUG("%s %s, %s, %s, %s", opn, fregnames[fd], fregnames[fr],
fregnames[fs], fregnames[ft]);
}
| 1threat
|
C Program can help me? : Hello i am start programing c ut i dont know why my program is make bad outputs.
#include <stdio.h>
void main(void)
{
char res,res1;
float money=10;
printf("***Wealcome to Peace of Mind***");
printf("\nHello we have the menu please check::");
printf("\n***Menú***");
printf("\n");
printf("\n<<<Bebidas>>>");
printf("\n 1 - Coca-Cola = 1,5 2 - IceTea = 1,4");
printf("\n 3 - Super Bock = 1,70 4 - Sumol = 1,6");
printf("\n");
scanf("%d",&res);
switch(res)
{
case 1 || 'Coca-Cola':money - CocaCola;break;
}
printf("%.1f",money);
//Is that result i want:
printf("\n%.1f",10-1.5);
}
OutPut: [1]: http://prntscr.com/lkg1rd
| 0debug
|
static int proxy_statfs(FsContext *s, V9fsPath *fs_path, struct statfs *stbuf)
{
int retval;
retval = v9fs_request(s->private, T_STATFS, stbuf, "s", fs_path);
if (retval < 0) {
errno = -retval;
return -1;
}
return retval;
}
| 1threat
|
static void put_psr(target_ulong val)
{
env->psr = val & PSR_ICC;
env->psref = (val & PSR_EF)? 1 : 0;
env->psrpil = (val & PSR_PIL) >> 8;
#if ((!defined (TARGET_SPARC64)) && !defined(CONFIG_USER_ONLY))
cpu_check_irqs(env);
#endif
env->psrs = (val & PSR_S)? 1 : 0;
env->psrps = (val & PSR_PS)? 1 : 0;
#if !defined (TARGET_SPARC64)
env->psret = (val & PSR_ET)? 1 : 0;
#endif
set_cwp(val & PSR_CWP);
env->cc_op = CC_OP_FLAGS;
}
| 1threat
|
Google DevTools Timeline Panel missing : <p>If I open the google DevTools I cant find the Timeline Panel
as described here: </p>
<p><a href="https://i.stack.imgur.com/ab8nB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ab8nB.png" alt="enter image description here"></a> </p>
<p>There is simply no tag. Whats wrong?
I'am on Windows 7 and Chrome 61.0.3163.91</p>
| 0debug
|
make a GET call 100,000 times : <p>I have a requirement where I am writing a small utility to test apis(ofcourse there are existing tools but it has been decided to write one). I am required to bombard the api, for the same api call, with say 100 threads, around say 100,000 times.</p>
<p>I am using 'PoolingHttpClientConnectionManager' for the making the calls. I am using something as mentioned in the below link:</p>
<p><a href="https://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html" rel="nofollow">https://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html</a></p>
<p>My question is:</p>
<p>(1) How can I run the above code for 100,000 iterations? Using that many number of threads is obviously a bad idea. Initially thought of using ExecutorService for maintaining thread count and number of jobs to be submitted but it felt redundant.</p>
<p>(2)I read about 'setMaxTotal'(max connections) and 'setDefaultMaxPerRoute'(concurrent connections) but I dont think it will help achieve(1) though I will obviously be required to increase the values. </p>
<p>Please advise. Thanks in advance.</p>
| 0debug
|
static SCSIGenericReq *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun)
{
SCSIRequest *req;
req = scsi_req_alloc(sizeof(SCSIGenericReq), d, tag, lun);
return DO_UPCAST(SCSIGenericReq, req, req);
}
| 1threat
|
static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection *section)
{
KVMState *s = kvm_state;
unsigned long size, allocated_size = 0;
KVMDirtyLog d;
KVMSlot *mem;
int ret = 0;
hwaddr start_addr = section->offset_within_address_space;
hwaddr end_addr = start_addr + int128_get64(section->size);
d.dirty_bitmap = NULL;
while (start_addr < end_addr) {
mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);
if (mem == NULL) {
break;
}
size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
64) / 8;
if (!d.dirty_bitmap) {
d.dirty_bitmap = g_malloc(size);
} else if (size > allocated_size) {
d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
}
allocated_size = size;
memset(d.dirty_bitmap, 0, allocated_size);
d.slot = mem->slot;
if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
DPRINTF("ioctl failed %d\n", errno);
ret = -1;
break;
}
kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
start_addr = mem->start_addr + mem->memory_size;
}
g_free(d.dirty_bitmap);
return ret;
}
| 1threat
|
Warning: unable to access index for repository https://www.stats.ox.ac.uk/pub/RWin/src/contrib: : <p>From today, every time I try to install a new package on R (3.4.1) with Rstudio 1.0.143 I receive this error message:</p>
<p>Warning: unable to access index for repository <a href="https://www.stats.ox.ac.uk/pub/RWin/src/contrib" rel="noreferrer">https://www.stats.ox.ac.uk/pub/RWin/src/contrib</a>:
cannot open URL '<a href="https://www.stats.ox.ac.uk/pub/RWin/src/contrib/PACKAGES" rel="noreferrer">https://www.stats.ox.ac.uk/pub/RWin/src/contrib/PACKAGES</a>'</p>
<p>I change the CRAN mirror in Global options>packages but it still shows this error. The packages have started downloading from a different server than stats.ox.ac.uk but there is huge delay while R tries to connect to stats.ox.ac.uk. Is this a global problem, or just happening to me? If global, is there a workaround to stop this serror message from showing?</p>
<p>Thanks.
Deep
(Dwaipayan Adhya)</p>
| 0debug
|
Some functions in package appear as undefined Goe Ilang : I am attempting to create a Golang application. I have one function in my package which I can use fine, the GetCoin function. however my function CreateWallet keeps giving me an error saying it's not defined in the package, it's driving me crazy. The function name is in capitals so it's exported, but it's like my other file can't see it from the import.
Here is the package I am importing
https://github.com/pocockn/crypto-compare-go/blob/master/handlers/handlers.go
Here is my main file.
import (
"github.com/pocockn/crypto-compare-go/handlers"
)
func main() {
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.POST("/createWallet", handlers.CreateWallet)
}
| 0debug
|
How to pass argument while using apply in javascript : var Person = {
name: "jana",
getName: function(callBack){
callBack();
console.log("** "+this.name);
}
}
<br>
var anotherPerson = { name: "prabu"}
I have 2 object. I need "anotherPerson" is bind with Person object. As well as i want to send parameter as a function.
I have tired below methods, but its not working
Person.getName.apply(anotherPerson, function(){})
Person.getName.apply(anotherPerson)( function(){})
| 0debug
|
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
const char *model,
const char *name,
int fd, int is_connected)
{
struct sockaddr_in saddr;
int newfd;
socklen_t saddr_len;
VLANClientState *nc;
NetSocketState *s;
if (is_connected) {
if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
if (saddr.sin_addr.s_addr == 0) {
fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, "
"cannot setup multicast dst addr\n", fd);
return NULL;
}
newfd = net_socket_mcast_create(&saddr, NULL);
if (newfd < 0) {
close(fd);
return NULL;
}
dup2(newfd, fd);
close(newfd);
} else {
fprintf(stderr,
"qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
fd, strerror(errno));
return NULL;
}
}
nc = qemu_new_net_client(&net_dgram_socket_info, vlan, NULL, model, name);
snprintf(nc->info_str, sizeof(nc->info_str),
"socket: fd=%d (%s mcast=%s:%d)",
fd, is_connected ? "cloned" : "",
inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
s = DO_UPCAST(NetSocketState, nc, nc);
s->fd = fd;
qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
if (is_connected) s->dgram_dst=saddr;
return s;
}
| 1threat
|
how to find consecutive rows, that an employee is 'Absent'? I need it Urgent? : I have a table name employee. which has 4 columns: id, name, statuse and date_present. the date_present column contains all the dates an employee is present and absent. i need to write a query to find if any employee is continuously absent for more than 3 days.
id | name | statuse | date_presnet
1 | khan | present | 2016-12-1
2 | jan | present | 2016-12-2
3 | Kiran| absent | 2016-12-3
4 | jan | absent | 2016-12-4
4 | jan | absent | 2016-12-5
4 | jan | absent | 2016-12-6
| 0debug
|
Error: It looks like you called `mount()` without a global document being loaded : <p>I'm trying to mount a component for testing with enzyme, and get this error.</p>
| 0debug
|
validation not working in php on submission the form data by click the submit button plz help me by explaination : validation not working in php on submission the form data by click the submit button plz help me by explaination
<?php
if (isset($_POST['validate'])) {
if (empty($_POST['ename'])){
$nameErr = "name is required";
}
else{
$name = test_input($_POST['ename']);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST['mail'])){
$emailErr = "email is required";
}
else{
$email = test_input($_POST['mail']);
}
if (empty($_POST['gender'])){
$genderErr = "gender is required";
}
else{
$gender = test_input($_POST['gender']);
}
i want stop empty insertion
$query = "insert into inserttb (name,email,gender) values ('$name','$email','$gender')";
$result = mysqli_query($conn,$query);
if(!$result){
echo "data insertion failed";
}
}
//function to validate the input data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
| 0debug
|
Merging apps on Play and Store : I have a client for whom I have made three apps for different regions (App 1, App2, App3).
Now the client changed his strategy and instead of having a different brand for every region he wants just one global brand which also means one app. He obviously doesn't want to lose the users of the three old apps in the process so my question is: can I somehow merge all these apps into one on Google Play and Apple Store?
I couldn't find sufficient information anywhere. All I could think of was to update all three with a new package but that would mean that three apps (now with the same name and same everything) remain in the stores, which would probably result in deletion.
Is there any way to do this?
Thank you for your responses.
| 0debug
|
Javascript: How to put properties in an array into seperate <p> tags : I am trying to put each property (first name, last name, and credit) into separate p tags inside separate div. I managed to get them into separate divs but still can't seem to get each property in separate p tags instead it looks like this..[Here are my results][1] and
[Here is my code][2]
[1]: https://i.stack.imgur.com/C0HBT.png
[2]: https://i.stack.imgur.com/QVMRZ.png
| 0debug
|
Understanding how spring-data handles @EntityGraph : <p>(I made a <a href="https://github.com/ArnaudDenoyelle/sscce-entity-graph" rel="noreferrer">SSCCE</a> for this question.)</p>
<p>I have 2 simple entities : <code>Employee</code> and <code>Company</code>. <code>Employee</code> has a <code>@ManyToOne</code> relationship with <code>Company</code> with default fetch strategy (eager).</p>
<p>I want to be able to load the <code>Employee</code> without the <code>Company</code>without changing the fetch strategy defined in the <code>Employee</code> because I need to do that for only one use case.</p>
<p>JPA's entity graph seems to be intended for this purpose.</p>
<p>So I defined a <code>@NamedEntityGraph</code>on the class <code>Employee</code>:</p>
<pre><code>@Entity
@NamedEntityGraph(name = "employeeOnly")
public class Employee {
@Id
private Integer id;
private String name;
private String surname;
@ManyToOne
private Company company;
//Getters & Setters
</code></pre>
<p>And a <code>EmployeeRepository</code> like this : </p>
<pre><code>public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
@EntityGraph(value = "employeeOnly", type = EntityGraph.EntityGraphType.FETCH)
List<Employee> findByCompanyId(Integer companyId);
}
</code></pre>
<p>Despite the use of <code>@EntityGraph</code>, I can see in the logs that the <code>Company</code> is still loaded by hibernate : </p>
<pre><code>2016-11-07 23:16:08.738 DEBUG 1029 --- [nio-8080-exec-2] org.hibernate.SQL : select employee0_.id as id1_1_, employee0_.company_id as company_4_1_, employee0_.name as name2_1_, employee0_.surname as surname3_1_ from employee employee0_ left outer join company company1_ on employee0_.company_id=company1_.id where company1_.id=?
2016-11-07 23:16:08.744 DEBUG 1029 --- [nio-8080-exec-2] org.hibernate.SQL : select company0_.id as id1_0_0_, company0_.name as name2_0_0_ from company company0_ where company0_.id=?
</code></pre>
<p>Why? How to avoid that?</p>
| 0debug
|
How to get specific a word with Regular Expression ? please show the regex : I want to get "INFO","ERROR","DEBUG" with one Regular Expression.
Eg,when meet "1",will get INFO; when meet "2",will get ERROR;when meet "3",will get DEBUG.
1. [0;39m [http-nio-9000-exec-1] 2017-09-13 17:52:45,394 [34m|-INFO [0;39m [1;30mWatchHandlerInterceptor.java:59[0;39m [1;31m[0;39m | [35mreq monitor
2. [0;39m [http-nio-9000-exec-1] 2017-09-13 17:52:45,394 [34m|-ERROR[0;39m [1;30mWatchHandlerInterceptor.java:59[0;39m [1;31m[0;39m | [35mreq monitor
3. [0;39m [http-nio-9000-exec-1] 2017-09-13 17:52:45,394 [34m|- DEBUG[0;39m [1;30mWatchHandlerInterceptor.java:59[0;39m [1;31m[0;39m | [35mreq monitor
| 0debug
|
How can I enable a WinForms or WPF project in F#? : <p>I have the very latest version of Visual Studio 2017 installed. I selected F# language support and F# desktop support. After restarting and going to File -> New Project I was expecting to see an option to start a new WPF or WinForms project for F# but I don't have any such options. Only console, library, ASP.NET core, and the tutorial.</p>
<p>How can I enable or find the new project templates for F# desktop applications?</p>
| 0debug
|
static void bonito_cop_writel(void *opaque, target_phys_addr_t addr,
uint64_t val, unsigned size)
{
PCIBonitoState *s = opaque;
((uint32_t *)(&s->boncop))[addr/sizeof(uint32_t)] = val & 0xffffffff;
}
| 1threat
|
static inline int mpeg2_fast_decode_block_intra(MpegEncContext *s, int16_t *block, int n)
{
int level, dc, diff, j, run;
int component;
RLTable *rl;
uint8_t * scantable = s->intra_scantable.permutated;
const uint16_t *quant_matrix;
const int qscale = s->qscale;
if (n < 4) {
quant_matrix = s->intra_matrix;
component = 0;
} else {
quant_matrix = s->chroma_intra_matrix;
component = (n & 1) + 1;
}
diff = decode_dc(&s->gb, component);
if (diff >= 0xffff)
return -1;
dc = s->last_dc[component];
dc += diff;
s->last_dc[component] = dc;
block[0] = dc << (3 - s->intra_dc_precision);
if (s->intra_vlc_format)
rl = &ff_rl_mpeg2;
else
rl = &ff_rl_mpeg1;
{
OPEN_READER(re, &s->gb);
for (;;) {
UPDATE_CACHE(re, &s->gb);
GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
if (level == 127) {
break;
} else if (level != 0) {
scantable += run;
j = *scantable;
level = (level * qscale * quant_matrix[j]) >> 4;
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
} else {
run = SHOW_UBITS(re, &s->gb, 6) + 1; LAST_SKIP_BITS(re, &s->gb, 6);
UPDATE_CACHE(re, &s->gb);
level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
scantable += run;
j = *scantable;
if (level < 0) {
level = (-level * qscale * quant_matrix[j]) >> 4;
level = -level;
} else {
level = (level * qscale * quant_matrix[j]) >> 4;
}
}
block[j] = level;
}
CLOSE_READER(re, &s->gb);
}
s->block_last_index[n] = scantable - s->intra_scantable.permutated;
return 0;
}
| 1threat
|
Parse error: syntax error, unexpected '$result' (T_VARIABLE), expecting function (T_FUNCTION) : <p>we are trying to rewrite core shipping model in magento.we are trying following code : but we are getting error as follows : </p>
<p>we removed the line that we are getting error</p>
<p>but still the problem didt resolved.</p>
<pre><code> we are getting this error : Parse error: syntax error,
unexpected '$result' (T_VARIABLE), expecting function (T_FUNCTION) in
/app/code/local/Webkul/Mpperproductshipping/Model/Shipping.php on line 56
</code></pre>
<p>we are using following code, you can see error at the end of the line.</p>
<pre><code><?php
class Webkul_Mpperproductshipping_Model_Carrier_LocalDelivery extends Mage_Shipping_Model_Carrier_Abstract
{
/* Use group alias */
protected $_code = 'mpperproductshipping';
// Prateek code start
public function collectRates(Mage_Shipping_Model_Rate_Request $request) {
$storeId = $request->getStoreId();
if (!$request->getOrig()) {
$request
->setCountryId(Mage::getStoreConfig(self::XML_PATH_STORE_COUNTRY_ID, $request->getStore()))
->setRegionId(Mage::getStoreConfig(self::XML_PATH_STORE_REGION_ID, $request->getStore()))
->setCity(Mage::getStoreConfig(self::XML_PATH_STORE_CITY, $request->getStore()))
->setPostcode(Mage::getStoreConfig(self::XML_PATH_STORE_ZIP, $request->getStore()));
}
$postCode = $request->getDestPostcode();
$restrictedCodes = array(
110001,
110002
);
//restricted values. they can come from anywhere
if (!in_array($postCode, $restrictedCodes)) {
return $this;
}
$limitCarrier = $request->getLimitCarrier();
if (!$limitCarrier) {
$carriers = Mage::getStoreConfig('carriers', $storeId);
foreach ($carriers as $carrierCode => $carrierConfig) {
$this->collectCarrierRates($carrierCode, $request);
}
} else {
if (!is_array($limitCarrier)) {
$limitCarrier = array($limitCarrier);
}
foreach ($limitCarrier as $carrierCode) {
$carrierConfig = Mage::getStoreConfig('carriers/' . $carrierCode, $storeId);
if (!$carrierConfig) {
continue;
}
$this->collectCarrierRates($carrierCode, $request);
}
}
return $this;
}
// Prateek code end
// $result = Mage::getModel('shipping/rate_result');
/* Edited by vikas_mageworx */
$postcode=$request->getDestPostcode();
$countrycode=$request->getDestCountry();
$items=$request->getAllItems();
/* End Editing by vikas_mageworx */
$postcode=str_replace('-', '', $postcode);
$shippingdetail=array();
/* one start */
$shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode,'items'=>$items);
/* one end */
foreach($items as $item) {
$proid=$item->getProductId();
$options=$item->getProductOptions();
$mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
if(!$mpassignproductId) {
foreach($item->getOptions() as $option) {
$temp=unserialize($option['value']);
if($temp['mpassignproduct_id']) {
$mpassignproductId=$temp['mpassignproduct_id'];
}
}
}
if($mpassignproductId) {
$mpassignModel = Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId);
$partner = $mpassignModel->getSellerId();
} else {
$collection=Mage::getModel('marketplace/product')
->getCollection()->addFieldToFilter('mageproductid',array('eq'=>$proid));
foreach($collection as $temp) {
$partner=$temp->getUserid();
}
}
$product=Mage::getModel('catalog/product')->load($proid)->getWeight();
$weight=$product*$item->getQty();
if(count($shippingdetail)==0){
array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
}else{
$shipinfoflag=true;
$index=0;
foreach($shippingdetail as $itemship){
if($itemship['seller_id']==$partner){
$itemship['items_weight']=$itemship['items_weight']+$weight;
$itemship['product_name']=$itemship['product_name'].",".$item->getName();
$itemship['item_id']=$itemship['item_id'].",".$item->getId();
$itemship['qty']=$itemship['qty']+$item->getQty();
$shippingdetail[$index]=$itemship;
$shipinfoflag=false;
}
$index++;
}
if($shipinfoflag==true){
array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
}
}
}
$shippingpricedetail=$this->getShippingPricedetail($shippingdetail,$shippostaldetail);
if($shippingpricedetail['errormsg']!==""){
Mage::getSingleton('core/session')->setShippingCustomError($shippingpricedetail['errormsg']);
return $result;
}
/*store shipping in session*/
$shippingAll=Mage::getSingleton('core/session')->getData('shippinginfo');
$shippingAll[$this->_code]=$shippingpricedetail['shippinginfo'];
Mage::getSingleton('core/session')->setData('shippinginfo',$shippingAll);
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier($this->_code);
$method->setCarrierTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/title'));
/* Use method name */
$method->setMethod($this->_code);
$method->setMethodTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/name'));
$method->setCost($shippingpricedetail['handlingfee']);
$method->setPrice($shippingpricedetail['handlingfee']);
$result->append($method);
return $result;
}
public function getShippingPricedetail($shippingdetail,$shippostaldetail) {
$shippinginfo=array();
$handling=0;
$session = Mage::getSingleton('checkout/session');
$customerAddress = $session->getQuote()->getShippingAddress();
/* Edited by vikas_boy */
$customerPostCode = $shippostaldetail['postalcode'];
$items = $shippostaldetail['items'];
/* End Editing by vikas_boy */
/* one */
foreach($shippingdetail as $shipdetail) {
$seller = Mage::getModel("customer/customer")->load($shipdetail['seller_id']);
$sellerAddress = $seller->getPrimaryShippingAddress();
$distance = $this->getDistanse($sellerAddress->getPostcode(),$customerPostCode);
// echo "distance ".$distance;die;
$price = 0;
$itemsarray=explode(',',$shipdetail['item_id']);
foreach($items as $item) {
$proid=$item->getProductId();
$options=$item->getProductOptions();
$mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
if(!$mpassignproductId) {
foreach($item->getOptions() as $option) {
$temp=unserialize($option['value']);
if($temp['mpassignproduct_id']) {
$mpassignproductId=$temp['mpassignproduct_id'];
}
}
}
if (Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($proid))
{
continue;
}
$mpshippingcharge = 0;
$localDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/local_shipping_distance');
$regionalDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/regional_shipping_distance');
$stateDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/state_shipping_distance');
if(in_array($item->getId(),$itemsarray)) {
if($mpassignproductId) {
if($distance < $localDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getLocalShippingCharge();
} elseif($distance > $localDistance && $distance < $regionalDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getRegionalShippingCharge();
} elseif($distance > $regionalDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getStateShippingCharge();
}
} else {
// echo "imte ".$item->getProductId();
if($distance < $localDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpLocalShippingCharge();
// echo "imte ".$item->getProductId();
// echo "ship ".$mpshippingcharge;
} elseif($distance > $localDistance && $distance < $regionalDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpRegionalShippingCharge();
} elseif($distance > $regionalDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpStateShippingCharge();
}
}
/* tt */
// echo "test ".$mpshippingcharge;die;
if(!is_numeric($mpshippingcharge)){
$price=$price+floatval($this->getConfigData('defalt_ship_amount')* floatval($item->getQty()));
}else{
$price=$price+($mpshippingcharge * floatval($item->getQty()));
}
}
}
$handling = $handling+$price;
$submethod = array(array('method'=>Mage::getStoreConfig('carriers/'.$this->_code.'/title'),'cost'=>$price,'error'=>0));
array_push($shippinginfo,array('seller_id'=>$shipdetail['seller_id'],'methodcode'=>$this->_code,'shipping_ammount'=>$price,'product_name'=>$shipdetail['product_name'],'submethod'=>$submethod,'item_ids'=>$shipdetail['item_id']));
}
$msg="";
return array('handlingfee'=>$handling,'shippinginfo'=>$shippinginfo,'errormsg'=>$msg);
}
/* one end */
/* tt start */
private function getDistanse($origin,$destination) {
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin.",india&destinations=".$destination.",india&mode=driving&language=en-EN&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_all = json_decode($response);
$distance = $response_all->rows[0]->elements[0]->distance->value / 1000;
if($distance==0){
$zips = array(
$origin,$destination
// ... etc ...
);
$geocoded = array();
$serviceUrl = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:%s&sensor=false";
$curl = curl_init();
foreach ($zips as $zip) {
curl_setopt($curl, CURLOPT_URL, sprintf($serviceUrl, urlencode($zip)));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$data = json_decode(curl_exec($curl));
$info = curl_getinfo($curl);
if ($info['http_code'] != 200) {
// Request failed
} else if ($data->status !== 'OK') {
// Something happened, or there are no results
} else {
$geocoded[$zip] =$data->results[0]->geometry->location;
}
}
$distance=$this->DistAB($geocoded[$zips[0]]->lat,$geocoded[$zips[0]]->lng,$geocoded[$zips[1]]->lat,$geocoded[$zips[1]]->lng);
}
return $distance;
}
public function DistAB($lat_a,$lon_a,$lat_b,$lon_b)
{
$measure_unit = 'kilometers';
$measure_state = false;
$measure = 0;
$error = '';
$delta_lat = $lat_b - $lat_a ;
$delta_lon = $lon_b - $lon_a ;
$earth_radius = 6372.795477598;
$alpha = $delta_lat/2;
$beta = $delta_lon/2;
$a = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($this->lat_a)) * cos(deg2rad($this->lat_b)) * sin(deg2rad($beta)) * sin(deg2rad($beta)) ;
$c = asin(min(1, sqrt($a)));
$distance = 2*$earth_radius * $c;
$distance = round($distance, 4);
$measure = $distance;
return $measure;
}
}
/* tt end */
</code></pre>
| 0debug
|
static void vfio_pci_size_rom(VFIOPCIDevice *vdev)
{
uint32_t orig, size = cpu_to_le32((uint32_t)PCI_ROM_ADDRESS_MASK);
off_t offset = vdev->config_offset + PCI_ROM_ADDRESS;
DeviceState *dev = DEVICE(vdev);
char name[32];
int fd = vdev->vbasedev.fd;
if (vdev->pdev.romfile || !vdev->pdev.rom_bar) {
if (vfio_blacklist_opt_rom(vdev) && vdev->pdev.romfile) {
error_printf("Warning : Device at %04x:%02x:%02x.%x "
"is known to cause system instability issues during "
"option rom execution. "
"Proceeding anyway since user specified romfile\n",
vdev->host.domain, vdev->host.bus, vdev->host.slot,
vdev->host.function);
}
return;
}
if (pread(fd, &orig, 4, offset) != 4 ||
pwrite(fd, &size, 4, offset) != 4 ||
pread(fd, &size, 4, offset) != 4 ||
pwrite(fd, &orig, 4, offset) != 4) {
error_report("%s(%04x:%02x:%02x.%x) failed: %m",
__func__, vdev->host.domain, vdev->host.bus,
vdev->host.slot, vdev->host.function);
return;
}
size = ~(le32_to_cpu(size) & PCI_ROM_ADDRESS_MASK) + 1;
if (!size) {
return;
}
if (vfio_blacklist_opt_rom(vdev)) {
if (dev->opts && qemu_opt_get(dev->opts, "rombar")) {
error_printf("Warning : Device at %04x:%02x:%02x.%x "
"is known to cause system instability issues during "
"option rom execution. "
"Proceeding anyway since user specified non zero value for "
"rombar\n",
vdev->host.domain, vdev->host.bus, vdev->host.slot,
vdev->host.function);
} else {
error_printf("Warning : Rom loading for device at "
"%04x:%02x:%02x.%x has been disabled due to "
"system instability issues. "
"Specify rombar=1 or romfile to force\n",
vdev->host.domain, vdev->host.bus, vdev->host.slot,
vdev->host.function);
return;
}
}
trace_vfio_pci_size_rom(vdev->vbasedev.name, size);
snprintf(name, sizeof(name), "vfio[%04x:%02x:%02x.%x].rom",
vdev->host.domain, vdev->host.bus, vdev->host.slot,
vdev->host.function);
memory_region_init_io(&vdev->pdev.rom, OBJECT(vdev),
&vfio_rom_ops, vdev, name, size);
pci_register_bar(&vdev->pdev, PCI_ROM_SLOT,
PCI_BASE_ADDRESS_SPACE_MEMORY, &vdev->pdev.rom);
vdev->pdev.has_rom = true;
vdev->rom_read_failed = false;
}
| 1threat
|
how to spit this complex json array? : I have a array like
["1-India","2-xxx","3-yyyy"]
I want arry like
["India","xxxx"]
Please help me to this
| 0debug
|
unresolved external symbol _MsiLocateComponentW@12 : <p>I know that simply posting code and asking for a solution isn't a good idea, but I have no idea what's causing this.</p>
<p>I'm trying to find the installation path of PowerPoint based on <a href="https://docs.microsoft.com/en-us/previous-versions/office/troubleshoot/office-developer/find-office-installation-path" rel="nofollow noreferrer">this code</a>, however, the compiler gives this error:</p>
<pre><code>error LNK2019: unresolved external symbol _MsiLocateComponentW@12 referenced in function _WinMain@16
</code></pre>
<p>I'm using Visual Studio 2019 and IntelliSense doesn't notice the error, only the compiler. Here's the code:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <Windows.h>
#include <msi.h>
int APIENTRY WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd) {
LPCWSTR PowerPoint = L"{CC29E94B-7BC2-11D1-A921-00A0C91E2AA2}";
DWORD size = 300;
INSTALLSTATE installstate;
LPWSTR sPath;
sPath = new wchar_t[size];
installstate = MsiLocateComponent(PowerPoint, sPath, &size);
if (installstate == INSTALLSTATE_LOCAL || installstate == INSTALLSTATE_SOURCE)
MessageBox(NULL, sPath, L"PowerPoint path", MB_OK | MB_ICONASTERISK );
delete[] sPath;
return 0;
}
</code></pre>
<p>As you can see, I included the <code>msi.h</code> header. What's wrong with my code?</p>
| 0debug
|
What do I build in .Net to automatically generate a file every morning? : <p>I normally work directly in .aspx web files, but we have a need to generate files automatically every morning for use by the website and other processes. </p>
<p>The process of generating the day's files needs to run whether or not website is accessed.
Process: at 6am every morning, get database dataset and generate files from it. </p>
<p>What is the best and most simplistic way to do this? Wcf service? asmx web service? something i haven't heard of?</p>
| 0debug
|
How to loop until all lines read from a file : I'm trying to set up a score system where I need to input all the scores from a text file into an 'array of records'.
I'm fairly new to Python and hope for a simple solution.
In my program, the array of records would technically class as a list of namedtuples.
Currently I have:
Player = namedtuple("Player", ["name", "result", "difficulty", "score"])
Playerlist = []
while str(f.readline) != '':
player = Player(
f.readline(),
f.readline(),
f.readline(),
f.readline())
Playerlist.append(player)
I tried to print(Playerlist[0]), but nothing shows up.
I have also tried to print(Playerlist[0]) without any loop and got the expected result, though I won't have stored all the data from the text file into my program.
| 0debug
|
constructor vs componentWillMount; what a componentWillMount can do that a constructor cannot? : <p>As far as I could see, the only thing a <code>componentWillMount</code> can do and a <code>constructor</code> cannot is to call <code>setState</code>.</p>
<pre><code>componentWillMount() {
setState({ isLoaded: false });
}
</code></pre>
<p>Since we have not called <code>render</code> yet, a <code>setState</code> in <code>componentWillMount</code> will prepare the state object before we enter the first <code>render()</code> pass. Which is essentially the same thing a <code>constructor</code> does:</p>
<pre><code>constructor(props) {
super(props);
this.state = { isLoaded: false };
}
</code></pre>
<hr>
<p>But I see another use case where <code>componentWillMount</code> is useful (on server side).</p>
<p>Let's consider something asynchronous:</p>
<pre><code>componentWillMount() {
myAsyncMethod(params, (result) => {
this.setState({ data: result });
})
}
</code></pre>
<p>Here we cannot use the <code>constructor</code> as assignment to <code>this.state</code> won't trigger <code>render()</code>.</p>
<p>What about <code>setState</code> in <code>componentWillMount</code>? According to <a href="https://facebook.github.io/react/docs/react-component.html#componentwillmount" rel="noreferrer">React docs</a>:</p>
<blockquote>
<p><code>componentWillMount()</code> is invoked immediately before mounting occurs. It
is called before <code>render(</code>), therefore setting state in this method will
not trigger a re-rendering. Avoid introducing any side-effects or
subscriptions in this method.</p>
</blockquote>
<p>So, here I think React will use the new state value for the first render and avoids a re-render.</p>
<p><strong>Question 1:</strong> Does this means, inside <code>componentWillMount</code>, if we call <code>setState</code> in an async method's callback (can be a promise callback), React <strong>blocks initial rendering</strong> until the callback is executed?</p>
<p>Having this setup on <strong>client-side</strong> (yes I see that use case in server-side rendering), if I assume the above is true, I will not see anything until my asynchronous method completes.</p>
<p>Am I missing any concepts?</p>
<p><strong>Question 2:</strong> Are the any other use cases that I can achieve with <code>componentWillMount</code> only, but not using the <code>constructor</code> and <code>componentDidMount</code>?</p>
| 0debug
|
document.getElementById('input').innerHTML = user_input;
| 1threat
|
What is a changeset in Git? : <p>What is changeset in Git? I keep hearing this term said, but cannot seem to find the answer online, and wikipedia is very vague. Is it if you commit 5 files at once via a git repository and type git log and see a single commit for that 5 files, that entire change is called a changeset?</p>
<pre><code>commit 01304a265f5d8f9bfd6eb64d3390846adc61db75
i.e.:Author: Some guy <someguy@hotmail.com>
Date: Thu Jul 28 18:28:07 2016 -0400
First commit
</code></pre>
<p>This entire thing would be a changeset?</p>
| 0debug
|
Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean : <p>When i run the application using main application, i got the error in consoleUnable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.</p>
<p>Main Application</p>
<pre><code>@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
</code></pre>
<p>Servlet Initializer</p>
<pre><code>public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
</code></pre>
<p>build.gradle</p>
<pre><code> buildscript {
ext {
springBootVersion = '2.0.0.M4'
}
repositories {
jcenter()
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
plugins {
id "org.sonarqube" version "2.5"
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'eclipse-wtp'
apply plugin: 'jacoco'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'
group = 'com.demo'
version = '0.0.1-SNAPSHOT'
// Uses JDK 8
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
maven { url "https://repo.spring.io/milestone" }
jcenter()
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
}
configurations {
providedRuntime
}
dependencies {
// SPRING FRAMEWORK
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-aop')
compile('org.springframework.boot:spring-boot-starter-actuator')
// Tomcat Server
providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
//Spring Jpa
compile('org.springframework.boot:spring-boot-starter-data-jpa')
// SPRING SECURITY
compile('org.springframework.boot:spring-boot-starter-security')
// MYSQL and HIBERNATE
compile 'mysql:mysql-connector-java:5.1.34'
//compile 'org.hibernate:hibernate-core:5.2.11.Final'
//compile 'org.hibernate:hibernate-validator:5.1.3.Final'
}
</code></pre>
<p>Help Me</p>
| 0debug
|
pl/sql deduping : I have a data structure like the following
ID ID2 DATE
A AA 2017-01-01
A BB 2017-01-01
A CC 2017-01-01
B DD 2018-01-01
B DD 2018-01-01
C EE 2018-02-01
I would like to dedup by ID keeping only one ID2 and one date per row. I am trying this sql command, but it doesn't dedud:
SELECT DISTINCT A.ID, A.ID2, A.DATE FROM TABLE A
GROUP BY A.ID;
Any help will be appreciated
| 0debug
|
Ingress responding with 'default backend - 404' when using GKE : <p>Using the latest Kubernetes version in GCP (<code>1.6.4</code>), I have the following <code>Ingress</code> definition:</p>
<pre><code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: myproject
namespace: default
annotations:
ingress.kubernetes.io/rewrite-target: /
kubernetes.io/ingress.class: "gce"
spec:
rules:
- host: staging.myproject.io
http:
paths:
- path: /poller
backend:
serviceName: poller
servicePort: 8080
</code></pre>
<p>Here is my service and deployment:</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
name: poller
labels:
app: poller
tier: backend
role: service
spec:
type: NodePort
selector:
app: poller
tier: backend
role: service
ports:
- port: 8080
targetPort: 8080
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: poller
spec:
replicas: 1
template:
metadata:
labels:
app: poller
tier: backend
role: service
spec:
containers:
- name: poller
image: gcr.io/myproject-1364/poller:latest
imagePullPolicy: Always
env:
- name: SPRING_PROFILES_ACTIVE
value: staging
- name: GET_HOSTS_FROM
value: dns
ports:
- containerPort: 8080
</code></pre>
<p>In my <code>/etc/hosts</code> I have a line like:</p>
<pre><code>35.190.37.148 staging.myproject.io
</code></pre>
<p>However, I get <code>default backend - 404</code> when curling any endpoint on <code>staging.myproject.io</code>:</p>
<pre><code>$ curl staging.myproject.io/poller/cache/status
default backend - 404
</code></pre>
<p>I have the exact same configuration working locally inside Minikube, with the only difference being the domain (<code>dev.myproject.io</code>), and that works like a charm.</p>
<p>I have read and tried pretty much everything that I could find, including stuff from <a href="https://github.com/kubernetes/ingress/tree/master/controllers/nginx#running-multiple-ingress-controllers" rel="noreferrer">here</a> and <a href="https://github.com/kubernetes/ingress/blob/master/controllers/gce/BETA_LIMITATIONS.md#disabling-glbc" rel="noreferrer">here</a> and <a href="https://github.com/kubernetes/ingress/issues/349" rel="noreferrer">here</a>, but maybe I'm just missing something... any ideas?</p>
| 0debug
|
General K8s question If I create an object, how long to wait before a get succeeds? : If I create an object, how long to wait before a get succeeds? I don't want to add a sleep with arbitrary values.
If there is a better pattern , please advise
```
err := r.CreateSAandSecret()
370 if err != nil {
371 log.Info("Not able to create SA and secret ")
372 return "", err
373 }
374 // How long should the sleep be here ???
375 token, err := r.GetAuthorizationTokenfromSecret()
376 if err != nil {
377 log.Info("Not able to get token from secret")
```
| 0debug
|
static void copy_block(uint16_t *pdest, uint16_t *psrc, int block_size, int pitch)
{
int y;
for (y = 0; y != block_size; y++, pdest += pitch, psrc += pitch)
memcpy(pdest, psrc, block_size * sizeof(pdest[0]));
}
| 1threat
|
static int64_t cpu_get_clock_locked(void)
{
int64_t ti;
if (!timers_state.cpu_ticks_enabled) {
ti = timers_state.cpu_clock_offset;
} else {
ti = get_clock();
ti += timers_state.cpu_clock_offset;
}
return ti;
}
| 1threat
|
How I can use refs to change styling class in ReactJS? : <p>I'm trying to change background of a <code>div</code> when color value changes. Here is my function which receives color value:</p>
<pre><code>ChangeColor(oColor) {
this.props.ChangeColor(oColor);
console.log("Refs: ", this.refs.colorPicker.className);
},
</code></pre>
<p>Here is css class</p>
<pre><code>.colorPicker {
padding-right: 25px;
background: #000;
display: inline;
margin-right: 5px;
}
</code></pre>
<p>and here is my div element whose background needs to update on run-time.</p>
<pre><code><div ref='colorPicker' className={this.GetClass("colorPicker")} />
</code></pre>
<p>I'm not sure about refs synatx so please help to fix this issue. Thanks.</p>
| 0debug
|
static uint16_t nvme_identify_ns(NvmeCtrl *n, NvmeIdentify *c)
{
NvmeNamespace *ns;
uint32_t nsid = le32_to_cpu(c->nsid);
uint64_t prp1 = le64_to_cpu(c->prp1);
uint64_t prp2 = le64_to_cpu(c->prp2);
if (nsid == 0 || nsid > n->num_namespaces) {
return NVME_INVALID_NSID | NVME_DNR;
}
ns = &n->namespaces[nsid - 1];
return nvme_dma_read_prp(n, (uint8_t *)&ns->id_ns, sizeof(ns->id_ns),
prp1, prp2);
}
| 1threat
|
void dp83932_init(NICInfo *nd, target_phys_addr_t base, int it_shift,
qemu_irq irq, void* mem_opaque,
void (*memory_rw)(void *opaque, target_phys_addr_t addr, uint8_t *buf, int len, int is_write))
{
dp8393xState *s;
int io;
qemu_check_nic_model(nd, "dp83932");
s = qemu_mallocz(sizeof(dp8393xState));
s->mem_opaque = mem_opaque;
s->memory_rw = memory_rw;
s->it_shift = it_shift;
s->irq = irq;
s->watchdog = qemu_new_timer(vm_clock, dp8393x_watchdog, s);
s->regs[SONIC_SR] = 0x0004;
s->vc = qemu_new_vlan_client(nd->vlan, nd->model, nd->name,
nic_receive, nic_can_receive, s);
qemu_format_nic_info_str(s->vc, nd->macaddr);
qemu_register_reset(nic_reset, s);
nic_reset(s);
io = cpu_register_io_memory(0, dp8393x_read, dp8393x_write, s);
cpu_register_physical_memory(base, 0x40 << it_shift, io);
}
| 1threat
|
Got error in Android studio.. I am creating android app of wallpaper with admob and push notification. Please help me : Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : uses-sdk:minSdkVersion 14 cannot be smaller than version 15 declared in library [com.onesignal:OneSignal:3.8.1] G:\gradle-4.4.1\bin\caches\transforms-1\files-1.1\OneSignal-3.8.1.aar\4992f150d9197af17fab12064aa2676a\AndroidManifest.xml as the library might be using APIs not available in 14
Suggestion: use a compatible library with a minSdk of at most 14,
or increase this project's minSdk version to at least 15,
or use tools:overrideLibrary="com.onesignal" to force usage (may lead to runtime failures)
| 0debug
|
Xcode 9 - "Fixed Width Constraints May Cause Clipping" and Other Localization Warnings : <p>I downloaded the new Xcode and in Interface Builder I'm having a ton of problems with warnings that say things like:</p>
<blockquote>
<p>Fixed Width Constraints May Cause Clipping</p>
</blockquote>
<p>It looks like this:</p>
<p><a href="https://i.stack.imgur.com/H3FpD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/H3FpD.png" alt="enter image description here"></a></p>
<p>I do have localization for several languages and I understand the warning that in another language a label's size may change, but my app doesn't have this problem. I ran and tested it in Xcode 8 yesterday, it was fine. I don't want to spend hours and hours adding pointless new constraints. </p>
<p>Any suggested solutions?</p>
| 0debug
|
int ioinst_handle_schm(CPUS390XState *env, uint64_t reg1, uint64_t reg2,
uint32_t ipb)
{
uint8_t mbk;
int update;
int dct;
trace_ioinst("schm");
if (SCHM_REG1_RES(reg1)) {
program_interrupt(env, PGM_OPERAND, 2);
return -EIO;
}
mbk = SCHM_REG1_MBK(reg1);
update = SCHM_REG1_UPD(reg1);
dct = SCHM_REG1_DCT(reg1);
if (update && (reg2 & 0x0000000000000fff)) {
program_interrupt(env, PGM_OPERAND, 2);
return -EIO;
}
css_do_schm(mbk, update, dct, update ? reg2 : 0);
return 0;
}
| 1threat
|
static int nvdec_vc1_end_frame(AVCodecContext *avctx)
{
NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
int ret = ff_nvdec_end_frame(avctx);
ctx->bitstream = NULL;
return ret;
}
| 1threat
|
Fixed navbar separates from top of browser on Chrome for iPhone : <p>I have a website with a bootstrap fixed-to-top navigation bar (<a href="https://getbootstrap.com/examples/navbar-fixed-top/" rel="noreferrer">example here</a>), and noticed that, using Chrome on an iPhone, the navbar separates from the top of the screen by just a few pixels when scrolling quickly. This is shown in the following screenshot, from the bootstrap navbar example page:</p>
<p><a href="https://i.stack.imgur.com/zwExk.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/zwExk.jpg" alt="Fixed navbar separation"></a></p>
<p>This only happens on Chrome on an iPhone, and not on an iPad or any Mac/PC I've tested. It also happens on every website with a fixed navbar that I could find. The only thing I can think of is to extend the background color of the navbar up above the top of the browser so that, when the navbar is eventually pulled down, it doesn't fully separate from the screen. However, that still leaves the content of the navbar pulled down, and certainly seems like a dirty fix.</p>
<p>Has anyone else run into this issue, and is there any sort of known fix available?</p>
| 0debug
|
Laravel: Change base URL? : <p>When I use <code>secure_url()</code> or <code>asset()</code>, it links to my site's domain <strong><em>without</em></strong> "www", i.e. "example.com".</p>
<p>How can I change it to link to "www.example.com"?</p>
| 0debug
|
static void dummy_m68k_init(QEMUMachineInitArgs *args)
{
ram_addr_t ram_size = args->ram_size;
const char *cpu_model = args->cpu_model;
const char *kernel_filename = args->kernel_filename;
CPUM68KState *env;
MemoryRegion *address_space_mem = get_system_memory();
MemoryRegion *ram = g_new(MemoryRegion, 1);
int kernel_size;
uint64_t elf_entry;
target_phys_addr_t entry;
if (!cpu_model)
cpu_model = "cfv4e";
env = cpu_init(cpu_model);
if (!env) {
fprintf(stderr, "Unable to find m68k CPU definition\n");
exit(1);
}
env->vbr = 0;
memory_region_init_ram(ram, "dummy_m68k.ram", ram_size);
vmstate_register_ram_global(ram);
memory_region_add_subregion(address_space_mem, 0, ram);
if (kernel_filename) {
kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry,
NULL, NULL, 1, ELF_MACHINE, 0);
entry = elf_entry;
if (kernel_size < 0) {
kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL);
}
if (kernel_size < 0) {
kernel_size = load_image_targphys(kernel_filename,
KERNEL_LOAD_ADDR,
ram_size - KERNEL_LOAD_ADDR);
entry = KERNEL_LOAD_ADDR;
}
if (kernel_size < 0) {
fprintf(stderr, "qemu: could not load kernel '%s'\n",
kernel_filename);
exit(1);
}
} else {
entry = 0;
}
env->pc = entry;
}
| 1threat
|
Why scanf() function reads two values when we put spaces after formate specifier even we are passing one reference : #include<stdio.h>
main()
{
int a;
printf("Enter a value \n");
scanf("%d ",&a);
printf("a=%d \n",a);
}
in scanf() function i put space after formate specifier. when i compile this program scanf() function reading two values from user but the first value is assigned to 'a'.
1)
why scanf() function reading two values when we use spaces after formate specifier even though we are passing one reference in above program.
2)
why scanf() function reading one value when we use space before formate specifier even though we are passing one reference.
3)
how the scanf() function will work.
| 0debug
|
void HELPER(set_cp15)(CPUState *env, uint32_t insn, uint32_t val)
{
int op1;
int op2;
int crm;
op1 = (insn >> 21) & 7;
op2 = (insn >> 5) & 7;
crm = insn & 0xf;
switch ((insn >> 16) & 0xf) {
case 0:
if (arm_feature(env, ARM_FEATURE_XSCALE))
break;
if (arm_feature(env, ARM_FEATURE_OMAPCP))
break;
if (arm_feature(env, ARM_FEATURE_V7)
&& op1 == 2 && crm == 0 && op2 == 0) {
env->cp15.c0_cssel = val & 0xf;
break;
}
goto bad_reg;
case 1:
if (arm_feature(env, ARM_FEATURE_V7)
&& op1 == 0 && crm == 1 && op2 == 0) {
env->cp15.c1_scr = val;
break;
}
if (arm_feature(env, ARM_FEATURE_OMAPCP))
op2 = 0;
switch (op2) {
case 0:
if (!arm_feature(env, ARM_FEATURE_XSCALE) || crm == 0)
env->cp15.c1_sys = val;
tlb_flush(env, 1);
break;
case 1:
if (arm_feature(env, ARM_FEATURE_XSCALE)) {
env->cp15.c1_xscaleauxcr = val;
break;
}
break;
case 2:
if (arm_feature(env, ARM_FEATURE_XSCALE))
goto bad_reg;
if (env->cp15.c1_coproc != val) {
env->cp15.c1_coproc = val;
tb_flush(env);
}
break;
default:
goto bad_reg;
}
break;
case 2:
if (arm_feature(env, ARM_FEATURE_MPU)) {
switch (op2) {
case 0:
env->cp15.c2_data = val;
break;
case 1:
env->cp15.c2_insn = val;
break;
default:
goto bad_reg;
}
} else {
switch (op2) {
case 0:
env->cp15.c2_base0 = val;
break;
case 1:
env->cp15.c2_base1 = val;
break;
case 2:
val &= 7;
env->cp15.c2_control = val;
env->cp15.c2_mask = ~(((uint32_t)0xffffffffu) >> val);
env->cp15.c2_base_mask = ~((uint32_t)0x3fffu >> val);
break;
default:
goto bad_reg;
}
}
break;
case 3:
env->cp15.c3 = val;
tlb_flush(env, 1);
break;
case 4:
goto bad_reg;
case 5:
if (arm_feature(env, ARM_FEATURE_OMAPCP))
op2 = 0;
switch (op2) {
case 0:
if (arm_feature(env, ARM_FEATURE_MPU))
val = extended_mpu_ap_bits(val);
env->cp15.c5_data = val;
break;
case 1:
if (arm_feature(env, ARM_FEATURE_MPU))
val = extended_mpu_ap_bits(val);
env->cp15.c5_insn = val;
break;
case 2:
if (!arm_feature(env, ARM_FEATURE_MPU))
goto bad_reg;
env->cp15.c5_data = val;
break;
case 3:
if (!arm_feature(env, ARM_FEATURE_MPU))
goto bad_reg;
env->cp15.c5_insn = val;
break;
default:
goto bad_reg;
}
break;
case 6:
if (arm_feature(env, ARM_FEATURE_MPU)) {
if (crm >= 8)
goto bad_reg;
env->cp15.c6_region[crm] = val;
} else {
if (arm_feature(env, ARM_FEATURE_OMAPCP))
op2 = 0;
switch (op2) {
case 0:
env->cp15.c6_data = val;
break;
case 1:
case 2:
env->cp15.c6_insn = val;
break;
default:
goto bad_reg;
}
}
break;
case 7:
env->cp15.c15_i_max = 0x000;
env->cp15.c15_i_min = 0xff0;
if (op1 != 0) {
goto bad_reg;
}
if (arm_feature(env, ARM_FEATURE_VAPA)) {
switch (crm) {
case 4:
if (arm_feature(env, ARM_FEATURE_V7)) {
env->cp15.c7_par = val & 0xfffff6ff;
} else {
env->cp15.c7_par = val & 0xfffff1ff;
}
break;
case 8: {
uint32_t phys_addr;
target_ulong page_size;
int prot;
int ret, is_user = op2 & 2;
int access_type = op2 & 1;
if (op2 & 4) {
goto bad_reg;
}
ret = get_phys_addr(env, val, access_type, is_user,
&phys_addr, &prot, &page_size);
if (ret == 0) {
if (page_size == (1 << 24)
&& arm_feature(env, ARM_FEATURE_V7)) {
env->cp15.c7_par = (phys_addr & 0xff000000) | 1 << 1;
} else {
env->cp15.c7_par = phys_addr & 0xfffff000;
}
} else {
env->cp15.c7_par = ((ret & (10 << 1)) >> 5) |
((ret & (12 << 1)) >> 6) |
((ret & 0xf) << 1) | 1;
}
break;
}
}
}
break;
case 8:
switch (op2) {
case 0:
tlb_flush(env, 0);
break;
case 1:
tlb_flush_page(env, val & TARGET_PAGE_MASK);
break;
case 2:
tlb_flush(env, val == 0);
break;
case 3:
tlb_flush(env, 1);
break;
default:
goto bad_reg;
}
break;
case 9:
if (arm_feature(env, ARM_FEATURE_OMAPCP))
break;
if (arm_feature(env, ARM_FEATURE_STRONGARM))
break;
switch (crm) {
case 0:
switch (op1) {
case 0:
switch (op2) {
case 0:
env->cp15.c9_data = val;
break;
case 1:
env->cp15.c9_insn = val;
break;
default:
goto bad_reg;
}
break;
case 1:
break;
default:
goto bad_reg;
}
break;
case 1:
goto bad_reg;
case 12:
if (!arm_feature(env, ARM_FEATURE_V7)) {
goto bad_reg;
}
switch (op2) {
case 0:
env->cp15.c9_pmcr &= ~0x39;
env->cp15.c9_pmcr |= (val & 0x39);
break;
case 1:
val &= (1 << 31);
env->cp15.c9_pmcnten |= val;
break;
case 2:
val &= (1 << 31);
env->cp15.c9_pmcnten &= ~val;
break;
case 3:
env->cp15.c9_pmovsr &= ~val;
break;
case 4:
break;
case 5:
break;
default:
goto bad_reg;
}
break;
case 13:
if (!arm_feature(env, ARM_FEATURE_V7)) {
goto bad_reg;
}
switch (op2) {
case 0:
break;
case 1:
env->cp15.c9_pmxevtyper = val & 0xff;
break;
case 2:
break;
default:
goto bad_reg;
}
break;
case 14:
if (!arm_feature(env, ARM_FEATURE_V7)) {
goto bad_reg;
}
switch (op2) {
case 0:
env->cp15.c9_pmuserenr = val & 1;
tb_flush(env);
break;
case 1:
val &= (1 << 31);
env->cp15.c9_pminten |= val;
break;
case 2:
val &= (1 << 31);
env->cp15.c9_pminten &= ~val;
break;
}
break;
default:
goto bad_reg;
}
break;
case 10:
break;
case 12:
goto bad_reg;
case 13:
switch (op2) {
case 0:
if (env->cp15.c13_fcse != val)
tlb_flush(env, 1);
env->cp15.c13_fcse = val;
break;
case 1:
if (env->cp15.c13_context != val
&& !arm_feature(env, ARM_FEATURE_MPU))
tlb_flush(env, 0);
env->cp15.c13_context = val;
break;
default:
goto bad_reg;
}
break;
case 14:
goto bad_reg;
case 15:
if (arm_feature(env, ARM_FEATURE_XSCALE)) {
if (op2 == 0 && crm == 1) {
if (env->cp15.c15_cpar != (val & 0x3fff)) {
tb_flush(env);
env->cp15.c15_cpar = val & 0x3fff;
}
break;
}
goto bad_reg;
}
if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
switch (crm) {
case 0:
break;
case 1:
env->cp15.c15_ticonfig = val & 0xe7;
env->cp15.c0_cpuid = (val & (1 << 5)) ?
ARM_CPUID_TI915T : ARM_CPUID_TI925T;
break;
case 2:
env->cp15.c15_i_max = val;
break;
case 3:
env->cp15.c15_i_min = val;
break;
case 4:
env->cp15.c15_threadid = val & 0xffff;
break;
case 8:
cpu_interrupt(env, CPU_INTERRUPT_HALT);
break;
default:
goto bad_reg;
}
}
if (ARM_CPUID(env) == ARM_CPUID_CORTEXA9) {
switch (crm) {
case 0:
if ((op1 == 0) && (op2 == 0)) {
env->cp15.c15_power_control = val;
} else if ((op1 == 0) && (op2 == 1)) {
env->cp15.c15_diagnostic = val;
} else if ((op1 == 0) && (op2 == 2)) {
env->cp15.c15_power_diagnostic = val;
}
default:
break;
}
}
break;
}
return;
bad_reg:
cpu_abort(env, "Unimplemented cp15 register write (c%d, c%d, {%d, %d})\n",
(insn >> 16) & 0xf, crm, op1, op2);
}
| 1threat
|
continue to retrieve data even the result is null c# : I have a program that will retrieve Student information and Class information.
I already use "if (!reader.HasRows)" to check if the student is existing but the problem is not all student is already registered in a certain class and I want it continue retrieving data even the values in the class information is Null. I am new to C# and any help and recommendation is deeply appreciated.
Here is my code!
private void btnstudsearch_Click_1(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"data source = DELL-USER\SQLEXPRESS;integrated security = SSPI;database = Enrollment System");
DataTable dt = new DataTable();
con.Open();
SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand("select tbl_studregs.fname, tbl_studregs.mname, tbl_studregs.lname, tbl_studregs.age, tbl_studregs.sex,
tbl_studregs.address, tbl_studregs.gname, tbl_studregs.gcnum, tbl_studregs.educlevel, tbl_class.yglevel, tbl_class.section from tbl_studregs
inner join tbl_class on tbl_studregs.classid = tbl_class.classid where tbl_studregs.studid = @id ", con);
cmd.Parameters.AddWithValue("@id", txtstudsearch.Text);
reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
MessageBox.Show("Student not found!Please recheck the student ID!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
ClearAllTextBox();
}
else
{
while (reader.Read())
{
txtstudfname.Text = reader.GetValue(0).ToString();
txtmname.Text = reader.GetValue(1).ToString();
txtstudlname.Text = reader.GetValue(2).ToString();
txtage.Text = reader.GetValue(3).ToString();
cboxsex.Text = reader.GetValue(4).ToString();
rtxtaddress.Text = reader.GetValue(5).ToString();
txtgname.Text = reader.GetValue(6).ToString();
txtgcnum.Text = reader.GetValue(7).ToString();
cboxstudlevel.Text = reader.GetValue(8).ToString();
txtstudyearlev.Text = reader.GetValue(9).ToString();
txtstudsec.Text = reader.GetValue(10).ToString();
}
}
}
| 0debug
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.