problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
C language how to print to file without overwriting it in a recurssive function? : <p>I have multiple functions that are recursive. They print multiple times the results. I need to create a file that contains all those outputs.
The functions that print are:void print_inorder,void print_preorder, void print pre_order;</p>
<p>EXAMPLE INPUT: 1 (case option-preorder), 1 2 3 4 5 q(the numbers that are inserted into the tree, q ends the scanf);
OUTPUT: 1 2 3 4 5, I need this to be printed into a file too.</p>
<p>MY code:</p>
<pre><code>#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<pthread.h>
struct node1
{
int key1;
struct node1 *left1, *right1;
};
// A utility function to create a new BST node1
struct node1 *newnode1(int item)
{
struct node1 *temp1 = (struct node1 *)malloc(sizeof(struct node1));
temp1->key1 = item;
temp1->left1 = temp1->right1 = NULL;
return temp1;
}
// A utility function to do inorder traversal of BST
void inorder(struct node1 *root1)
{
if (root1 != NULL)
{
inorder(root1->left1);
printf("%d ", root1->key1);
inorder(root1->right1);
}
}
/* A utility function to insert1 a new node1 with given key1 in BST */
struct node1* insert1(struct node1* node1, int key1)
{
/* If the tree is empty, return a new node1 */
if (node1 == NULL) return newnode1(key1);
/* Otherwise, recur down the tree */
if (key1 < node1->key1)
node1->left1 = insert1(node1->left1, key1);
else
node1->right1 = insert1(node1->right1, key1);
/* return the (unchanged) node1 pointer */
return node1;
}
/* Given a non-empty binary search tree, return the node1 with minimum
key1 value found in that tree. Note that the entire tree does not
need to be searched. */
struct node1 * minValuenode1(struct node1* node1)
{
struct node1* current = node1;
/* loop down to find the left1most leaf */
while (current->left1 != NULL)
current = current->left1;
return current;
}
/* Given a binary search tree and a key1, this function deletes the key1
and returns the new root1 */
struct node1* deletenode1(struct node1* root1, int key1)
{
// base case
if (root1 == NULL) return root1;
// If the key1 to be deleted is smaller than the root1's key1,
// then it lies in left1 subtree
if (key1 < root1->key1)
root1->left1 = deletenode1(root1->left1, key1);
// If the key1 to be deleted is greater than the root1's key1,
// then it lies in right1 subtree
else if (key1 > root1->key1)
root1->right1 = deletenode1(root1->right1, key1);
// if key1 is same as root1's key1, then This is the node1
// to be deleted
else
{
// node1 with only one child or no child
if (root1->left1 == NULL)
{
struct node1 *temp1 = root1->right1;
free(root1);
return temp1;
}
else if (root1->right1 == NULL)
{
struct node1 *temp1 = root1->left1;
free(root1);
return temp1;
}
// node1 with two children: Get the inorder successor (smallest
// in the right1 subtree)
struct node1* temp1 = minValuenode1(root1->right1);
// Copy the inorder successor's content to this node1
root1->key1 = temp1->key1;
// Delete the inorder successor
root1->right1 = deletenode1(root1->right1, temp1->key1);
}
return root1;
}
struct bin_tree {
int data;
struct bin_tree * right, * left;
};
typedef struct bin_tree node;
void insert(node ** tree, int val)
{
node *temp = NULL;
if(!(*tree))
{
temp = (node *)malloc(sizeof(node));
temp->left = temp->right = NULL;
temp->data = val;
*tree = temp;
return;
}
if(val < (*tree)->data)
{
insert(&(*tree)->left, val);
}
else if(val > (*tree)->data)
{
insert(&(*tree)->right, val);
}
}
void print_preorder(node * tree)
{
if (tree)
{
printf("%d\n",tree->data);
print_preorder(tree->left);
print_preorder(tree->right);
}
}
void print_inorder(node * tree)
{
if (tree)
{
print_inorder(tree->left);
printf("%d\n",tree->data);
print_inorder(tree->right); // i want to print this as a tree
}
}
void print_postorder(node * tree)
{
if (tree)
{
print_postorder(tree->left);
print_postorder(tree->right);
printf("%d\n",tree->data);
}
}
void deltree(node * tree)
{
if (tree)
{
deltree(tree->left);
deltree(tree->right);
free(tree);
}
}
node* search(node ** tree, int val)
{
if(!(*tree))
{
return NULL;
}
if(val < (*tree)->data)
{
search(&((*tree)->left), val);
}
else if(val > (*tree)->data)
{
search(&((*tree)->right), val);
}
else if(val == (*tree)->data)
{
return *tree;
}
}
void main()
{
int a;
int searcharg;
int deletearg;
char option;
printf("1:PreOrder\n2:InOrder\n3:PostOrder\n4:search\n5:Delete Node\nYour Option: ");
scanf("%c", &option);
clock_t tic = clock();
node *root;
node *tmp;
//int i;
root = NULL;
struct node1 *root1 = NULL;
/* Inserting nodes into tree */
while (scanf("%d", &a) && a!='q'){insert(&root,a); root1 = insert1(root1, a);}
// these
/* Printing nodes of tree */
switch(option)
{
case '1':
printf("Pre Order Display\n");
print_preorder(root); // i want to print this as a tree
break;
case '2':
printf("In Order Display\n");
print_inorder(root); // i want to print this as a tree
break;
case '3':
printf("Post Order Display\n");
print_postorder(root); // i want to print this as a tree
break;
case '4':
scanf("%d", &searcharg);
tmp = search(&root, searcharg);
if (tmp)
{
printf("The searched node is present = %d\n", tmp->data);
}
else
{
printf("Data Not found in tree.\n");
}
break;
default:
printf("Error! operator is not correct\n");
break;
case '5':
// printf("scan");
// scanf("%d", &deletearg);
root1 = deletenode1(root1, 5);
inorder(root1);
}
// i want to print this as a tree
/* Deleting all nodes of tree */
deltree(root);
clock_t toc = clock();
printf("\nElapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC);
getch();
}
</code></pre>
| 0debug |
Why does console tell me that .filter is not a function? : <pre><code>var str = "I am a string.";
console.log(str.split(''));
var fil = function(val){
return val !== "a";
};
console.log(str.filter(fil));
</code></pre>
<p>When I run this, it says the str.filter is not a function.</p>
| 0debug |
int xtensa_get_physical_addr(CPUXtensaState *env, bool update_tlb,
uint32_t vaddr, int is_write, int mmu_idx,
uint32_t *paddr, uint32_t *page_size, unsigned *access)
{
if (xtensa_option_enabled(env->config, XTENSA_OPTION_MMU)) {
return get_physical_addr_mmu(env, update_tlb,
vaddr, is_write, mmu_idx, paddr, page_size, access, true);
} else if (xtensa_option_bits_enabled(env->config,
XTENSA_OPTION_BIT(XTENSA_OPTION_REGION_PROTECTION) |
XTENSA_OPTION_BIT(XTENSA_OPTION_REGION_TRANSLATION))) {
return get_physical_addr_region(env, vaddr, is_write, mmu_idx,
paddr, page_size, access);
} else {
*paddr = vaddr;
*page_size = TARGET_PAGE_SIZE;
*access = PAGE_READ | PAGE_WRITE | PAGE_EXEC | PAGE_CACHE_BYPASS;
return 0;
}
}
| 1threat |
Need help compressing .txt files in python 3.4.3 and not losing data whilst compressing them : I'm trying to compress my .txt file which are being made within another code but every time i compress them they go into a winrar file and lose all there data within them so all the text goes. This is the code i'm using:
import gzip
with gzip.open('dictionary.txt.gz', 'wb') as f:
f.write
I don't see anything wrong with it as it is actually working but like i said the winrar file (compressed file) loses all it's data and I'm very confused as to why. This isn't even the hard bit to what i have to do :( | 0debug |
Flask-SQLAlchemy import error. "Imported but unused" : <p>I used sqlacodegen to extract the a .py file containing classes of my db tables. I am using pythonanywhere. However for all the imports it is showing that "imported but unused".</p>
<p>You can see though column has been used, it shows the sqlalchemy.Column imported but unused.</p>
<p>Am I doing anything wrong here?<a href="https://i.stack.imgur.com/ow4H0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ow4H0.png" alt="Imported but unused"></a></p>
| 0debug |
Javascript to Group Array of Object into combination of two values : <pre><code>var data=[
{custType:1,code:'savings',efDate:'2/3/19',exDate'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'current',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'current',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'}
];
</code></pre>
<p>expected results</p>
<pre><code>var modifiedData=[
[
savings=[ {custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'}
],
current=[ {custType:1,code:'current',efDate:'2/3/19',exDate:'2/3/19'} ]
],
[
savings=[ {custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'} ],
current=[ {custType:2,code:'current',efDate:'2/3/19',exDate:'2/3/19'} ]
]
];
</code></pre>
<p>as i am trying to find a group with (custType and code), i am not able to generate the expected result. Which method i should use here? can i use reduce or groupBy. I am confused about it.</p>
| 0debug |
How do I make a basic c++ calculator calculate decimals : <p>I have a decent grasp with c++, and I made a basic calculator that can add, subtract, multiply, and divide. but I am having a hard time trying to get it to calculate decimals. Help please???</p>
| 0debug |
static inline int mdec_decode_block_intra(MDECContext *a, int16_t *block, int n)
{
int level, diff, i, j, run;
int component;
RLTable *rl = &ff_rl_mpeg1;
uint8_t * const scantable = a->scantable.permutated;
const uint16_t *quant_matrix = ff_mpeg1_default_intra_matrix;
const int qscale = a->qscale;
if (a->version == 2) {
block[0] = 2 * get_sbits(&a->gb, 10) + 1024;
} else {
component = (n <= 3 ? 0 : n - 4 + 1);
diff = decode_dc(&a->gb, component);
if (diff >= 0xffff)
return AVERROR_INVALIDDATA;
a->last_dc[component] += diff;
block[0] = a->last_dc[component] << 3;
}
i = 0;
{
OPEN_READER(re, &a->gb);
for (;;) {
UPDATE_CACHE(re, &a->gb);
GET_RL_VLC(level, run, re, &a->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
if (level == 127) {
break;
} else if (level != 0) {
i += run;
if (i > 63) {
av_log(a->avctx, AV_LOG_ERROR,
"ac-tex damaged at %d %d\n", a->mb_x, a->mb_y);
return AVERROR_INVALIDDATA;
}
j = scantable[i];
level = (level * qscale * quant_matrix[j]) >> 3;
level = (level ^ SHOW_SBITS(re, &a->gb, 1)) - SHOW_SBITS(re, &a->gb, 1);
LAST_SKIP_BITS(re, &a->gb, 1);
} else {
run = SHOW_UBITS(re, &a->gb, 6)+1; LAST_SKIP_BITS(re, &a->gb, 6);
UPDATE_CACHE(re, &a->gb);
level = SHOW_SBITS(re, &a->gb, 10); SKIP_BITS(re, &a->gb, 10);
i += run;
if (i > 63) {
av_log(a->avctx, AV_LOG_ERROR,
"ac-tex damaged at %d %d\n", a->mb_x, a->mb_y);
return AVERROR_INVALIDDATA;
}
j = scantable[i];
if (level < 0) {
level = -level;
level = (level * qscale * quant_matrix[j]) >> 3;
level = (level - 1) | 1;
level = -level;
} else {
level = (level * qscale * quant_matrix[j]) >> 3;
level = (level - 1) | 1;
}
}
block[j] = level;
}
CLOSE_READER(re, &a->gb);
}
a->block_last_index[n] = i;
return 0;
}
| 1threat |
Enable logging in docker mysql container : <p>I'm trying to get familiar with the docker ecosystem and tried to setup a mysql database container. With <code>docker-compose</code> this looks like:</p>
<pre><code>version: '2'
services:
db:
image: mysql:5.6.33@sha256:31ad2efd094a1336ef1f8efaf40b88a5019778e7d9b8a8579a4f95a6be88eaba
volumes:
- "./db/data:/var/lib/mysql"
- "./db/log:/var/log/mysql"
- "./db/conf:/etc/mysql/conf.d"
restart: "yes"
environment:
MYSQL_ROOT_PASSWORD: rootpw
MYSQL_DATABASE: db
MYSQL_USER: db
MYSQL_PASSWORD: dbpw
</code></pre>
<p>My conf directory contains one file:</p>
<pre><code>[mysqld]
log_error =/var/log/mysql/mysql_error.log
general_log_file=/var/log/mysql/mysql.log
general_log =1
slow_query_log =1
slow_query_log_file=/var/log/mysql/mysql_slow.log
long_query_time =2
log_queries_not_using_indexes = 1
</code></pre>
<p>Unfortunately I don't get any log files that way. The setup itself is correct and the cnf file is used. After connecting to the container and creating the 3 files, <code>chown</code> them to <code>mysql</code> and restarting the container, the logging is working as expected.</p>
<p>I'm pretty sure that this is a common scenario, and my current way to get it running seems really stupid. <strong>What is the correct way to do it?</strong> </p>
<p>I could improve my approach by moving all this stuff in a Dockerfile, but this still seem strange to me.</p>
| 0debug |
int kvm_coalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
{
int ret = -ENOSYS;
#ifdef KVM_CAP_COALESCED_MMIO
KVMState *s = kvm_state;
if (s->coalesced_mmio) {
struct kvm_coalesced_mmio_zone zone;
zone.addr = start;
zone.size = size;
ret = kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
}
#endif
return ret;
}
| 1threat |
How to check if an index exists in elasticsearch using a python script and perform exception handling over it? : <p>How do I check whether an index exists or not using a python query?</p>
<p>I'm passing my index as a variable assigned outside the query as :-</p>
<pre><code> i=int(datetime.datetime.now().strftime('%d'))+1
indextring="index"
for m in range (i-10,i):
d = datetime.datetime(2016, 10, m, 18, 00).strftime('%Y-%m-%d')
index1=datestring+d
subfix="_"+datetime.datetime(2016, 10, m, 18, 00).strftime('%Y-%m-%d')
es=Elasticsearch(['localhost:9200'])
res = **es.search(index='{0}'.format(index1)**, doc_type="log",size=10000, from_=0, body={ "query": {
"match": {
....Match condition follows
}
}
}})
</code></pre>
<p>Now, some of the index are not present for a particular date, however I want the process to run irrespective of that. I'm getting the following error when the index is not present--></p>
<p><strong>elasticsearch.exceptions.NotFoundError: TransportError(404, u'index_not_found_exception')</strong></p>
<p>I'm not sure how the exception handling works in elasticsearch.</p>
| 0debug |
PHP: Getting values by date : <p>Im new In PHP!.</p>
<p>I have an array that contains dates and vlaues. How do i get all values of
specific date?. EXp: I would like to get all values from year 2015. If someone Knows can guide me.</p>
| 0debug |
Multiple conditions in ngClass - Angular 4 : <p>How to use multiple conditions for ngClass? Example: </p>
<pre><code><section [ngClass]="[menu1 ? 'class1' : '' || menu2 ? 'class1' : '' || (something && (menu1 || menu2)) ? 'class2' : '']">
</code></pre>
<p>something like this. I got same class for 2 menus, and I need class when one of those menus is true and 'something' is true. Hope I explained well enough</p>
| 0debug |
static void visit_type_TestStruct(Visitor *v, TestStruct **obj,
const char *name, Error **errp)
{
Error *err = NULL;
visit_start_struct(v, (void **)obj, "TestStruct", name, sizeof(TestStruct),
&err);
if (err) {
goto out;
}
visit_type_int(v, &(*obj)->integer, "integer", &err);
visit_type_bool(v, &(*obj)->boolean, "boolean", &err);
visit_type_str(v, &(*obj)->string, "string", &err);
visit_end_struct(v, &err);
out:
error_propagate(errp, err);
}
| 1threat |
Are asserts disabled in release build? : <p>Are asserts disabled in 'release' build?</p>
<p>How optional flags like <code>-O0</code>,<code>-O3</code>,<code>-g</code> of <code>g++</code> affects it's behaviour?</p>
| 0debug |
Using array.push() inside my own array method gives error (JavaScript) : I have this code example:
function s () {
this.func = [];
this.func.addF = function (str) {
this.func.push(str);
}
}
When I create an Instance of that object:
var a = new s ();
a.func.addF ("hello");
I get an error saying: **Uncaught TypeError: Cannot read property 'push' of undefined**.
I can understand that `this.func` is undefined at that point, but what should I do to make this work. Pls help. | 0debug |
Visual Studio 2017 only has offline Nuget Packages for .NET Core 2.x. How to get online packages? : <p>I want to get NuGet Packages from Nuget online, but Visual Studio is only giving me 'Microsoft Visual Studio Offline Packages' as an option. </p>
<p><a href="https://i.stack.imgur.com/qGEWY.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/qGEWY.jpg" alt="enter image description here"></a></p>
<p>I have tried adding another package source using the following URLS:</p>
<ul>
<li><a href="https://www.nuget.org" rel="noreferrer">https://www.nuget.org</a></li>
<li><a href="https://packages/nuget.org" rel="noreferrer">https://packages/nuget.org</a></li>
</ul>
<p>and a few others, but I keep getting the following error(s):</p>
<p><code>[Package source] Unable to load the service index for source http://packagesource.
An error occurred while sending the request.
The remote name could not be resolved: 'packagesource'
[Nuget Online] The V2 feed at 'https://www.nuget.org/Search()?$filter=IsAbsoluteLatestVersion&searchTerm=''&targetFramework=''&includePrerelease=true&$skip=0&$top=26&semVerLevel=2.0.0' returned an unexpected status code '404 Not Found'.
</code></p>
<p>How can I get online packages for .NET Core?</p>
| 0debug |
static void virtio_ccw_stop_ioeventfd(VirtioCcwDevice *dev)
{
VirtIODevice *vdev;
int n, r;
if (!dev->ioeventfd_started) {
return;
}
vdev = virtio_bus_get_device(&dev->bus);
for (n = 0; n < VIRTIO_PCI_QUEUE_MAX; n++) {
if (!virtio_queue_get_num(vdev, n)) {
continue;
}
r = virtio_ccw_set_guest2host_notifier(dev, n, false, false);
assert(r >= 0);
}
dev->ioeventfd_started = false;
}
| 1threat |
Need to edit google script to copy a row and move to another sheet : Right now this script is erasing the data in the row and deleting the row after moving the row to the other sheet. The idea is to keep the data on the row and just copy over the row when the commissions have been verified. The companies and products our business is paid on, stays consistent. So I want this script to copy the row and keep it in the original sheet so that I can edit the cells we enter in how much we were paid each month. Thank you in advance!
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function Reporting() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('SunLife');
var range = s.getRange(2,1,s.getLastRow()-1,1).getValues()
for(i=s.getMaxRows()-2;i>0;i--){
var cell = range[i][0]
if(cell == 'Yes') {
var row = s.getRange(2+i,1).getRow();
var numColumns = s.getLastColumn();
var targetSheet = ss.getSheetByName("Reporting");
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
s.getRange(row, 1, 1, numColumns).moveTo(target);
}else{continue}
}
}
<!-- end snippet -->
| 0debug |
document.getElementById('input').innerHTML = user_input; | 1threat |
static int get_uint64_as_uint32(QEMUFile *f, void *pv, size_t size,
VMStateField *field)
{
uint64_t *v = pv;
*v = qemu_get_be32(f);
return 0;
}
| 1threat |
static void reset_used_window(DisasContext *dc)
{
dc->used_window = 0;
}
| 1threat |
How to code in python a system $dF/dt=A$ with $F$ and $A$ matrices? : I'd like to code in python a coupled system of differential equations like :
$dF_{ij}/dt=A_{ij}$ where $A_{ij}$ is a function of the matrix $F$.
Meaning a system of 1st order differential equations.
For the same system but with vectors : $dF_{i}/dt=A_{i}$ I'm using scipy.integrate.odeint.
But it doesn't work for matrices.
Could you help please ?
PS: how is it possible to write the math in latex on stackoverflow ? | 0debug |
Spiting a line to object in java : i am reading a file.i need to convert each value to java object.
` String sCurrentLine;
BufferedReader br = null;
int pointer = 1;
try {
br = new BufferedReader(new FileReader("src/main/java/com/ali/trillium/p0f.log"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
System.out.println("---------------");
System.out.println(pointer++);
System.out.println("---------------");
}`
Output of program
`<Tue Apr 10 09:21:42 2018> 172.20.16.36:62385 - Windows XP/2000 (RFC1323+, w+, tstamp-) (ECN) [low cost] [GENERIC] Signature: [8192:113:1:52:M1352,N,W8,N,N,S:.:Windows:?] -> 172.20.16.23:3391 (distance 15, link: unknown-1392)` | 0debug |
Could anyone give suggestion on where to start learning Python? : <p>I'm a beginner, and looking to learn the python language. If you have any suggestions on where I should start it would be nice if you would leave a comment.</p>
<p>Thanks.</p>
| 0debug |
static void find_best_state(uint8_t best_state[256][256],
const uint8_t one_state[256])
{
int i, j, k, m;
double l2tab[256];
for (i = 1; i < 256; i++)
l2tab[i] = log2(i / 256.0);
for (i = 0; i < 256; i++) {
double best_len[256];
double p = i / 256.0;
for (j = 0; j < 256; j++)
best_len[j] = 1 << 30;
for (j = FFMAX(i - 10, 1); j < FFMIN(i + 11, 256); j++) {
double occ[256] = { 0 };
double len = 0;
occ[j] = 1.0;
for (k = 0; k < 256; k++) {
double newocc[256] = { 0 };
for (m = 1; m < 256; m++)
if (occ[m]) {
len -= occ[m] * (p * l2tab[m] +
(1 - p) * l2tab[256 - m]);
}
if (len < best_len[k]) {
best_len[k] = len;
best_state[i][k] = j;
}
for (m = 0; m < 256; m++)
if (occ[m]) {
newocc[one_state[m]] += occ[m] * p;
newocc[256 - one_state[256 - m]] += occ[m] * (1 - p);
}
memcpy(occ, newocc, sizeof(occ));
}
}
}
}
| 1threat |
Haskell - Tranform leters into numbers : i'm very new to haskell and would like to make a program to turn characters in a string into numbers. Something like this:
A = 06
B = 07
C = 08
... Z
So for example:
Input: Hi
Output: 14 15
Does anyone know how I can go about doing this? Thanks In advanced. | 0debug |
static int kvm_get_debugregs(CPUState *env)
{
#ifdef KVM_CAP_DEBUGREGS
struct kvm_debugregs dbgregs;
int i, ret;
if (!kvm_has_debugregs()) {
return 0;
}
ret = kvm_vcpu_ioctl(env, KVM_GET_DEBUGREGS, &dbgregs);
if (ret < 0) {
return ret;
}
for (i = 0; i < 4; i++) {
env->dr[i] = dbgregs.db[i];
}
env->dr[4] = env->dr[6] = dbgregs.dr6;
env->dr[5] = env->dr[7] = dbgregs.dr7;
#endif
return 0;
}
| 1threat |
how to parse the JSON data start with "/{}" in android : I want to parse the JSON data which response starts with the slash. I am using retrofit for parsing the data. thanks in advance.
/{
"data": [
{
"id": "1",
"text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
},
{
"id": "2",
"text": "Felis donec et odio pellentesque diam volutpat commodo sed. Non arcu risus quis varius quam quisque. Nibh nisl condimentum id venenatis a condimentum vitae. Vel pharetra vel turpis nunc eget. "
},
{
"id": "3",
"text": "Volutpat sed cras ornare arcu dui vivamus arcu felis bibendum. Lobortis mattis aliquam faucibus purus in. Aliquam sem fringilla ut morbi tincidunt augue interdum."
},
{
"id": "4",
"text": "Elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi tristique. Bibendum at varius vel pharetra vel turpis nunc. Pellentesque sit amet porttitor eget dolor morbi non."
},
{
"id": "5",
"text": "Urna condimentum mattis pellentesque id. Ac tincidunt vitae semper quis. Massa tincidunt dui ut ornare lectus sit amet. Netus et malesuada fames ac turpis. Nulla facilisi cras fermentum odio eu feugiat pretium nibh."
},
{
"id": "6",
"text": "Tincidunt id aliquet risus feugiat in ante. Id donec ultrices tincidunt arcu non sodales neque sodales. Turpis massa tincidunt dui ut ornare lectus sit amet est. At ultrices mi tempus imperdiet nulla malesuada pellentesque elit."
},
{
"id": "7",
"text": "Fermentum posuere urna nec tincidunt praesent semper feugiat. Nulla facilisi etiam dignissim diam quis enim lobortis scelerisque fermentum. At auctor urna nunc id cursus metus aliquam eleifend mi."
},
{
"id": "8",
"text": "Quisque sagittis purus sit amet volutpat consequat mauris nunc congue. Malesuada fames ac turpis egestas sed. Volutpat ac tincidunt vitae semper. Aliquam nulla facilisi cras fermentum."
}
]
}
I am getting this error
com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 2 path $ | 0debug |
How to group an object in Javascript? : <p>I have two arrays:</p>
<pre><code>let props = ['a', 'b', 'c', 'd', 'e'];
let values = ['a', 'f', 'k', 'd', 'l'];
</code></pre>
<p>I need to get an object like:</p>
<pre><code>{
"a": [
{
"b": "f",
"c": "k"
}
],
"d": [
{
"e": "l"
}
]
}
</code></pre>
<p>How can i do that in Javascript? Thanks</p>
| 0debug |
How to get Current Location with SwiftUI? : <p>Trying to get current location with using swiftUI. Below code, couldn't initialize with didUpdateLocations delegate. </p>
<pre><code>class GetLocation : BindableObject {
var didChange = PassthroughSubject<GetLocation,Never>()
var location : CLLocation {
didSet {
didChange.send(self)
}
}
init() {}
}
</code></pre>
| 0debug |
START_TEST(invalid_array_comma)
{
QObject *obj = qobject_from_json("[32,}");
fail_unless(obj == NULL);
}
| 1threat |
See which domains use a Google Maps API key? : <p>Is there any way to check which domains/websites use a specific API like "Google Maps Embed API" in console.cloud.google.com?</p>
<p>It's a project with multiple keys which don't indicate where they were used.</p>
<p>Background: There is a key used on multiple sites and I want to see which site causes the most traffic.</p>
| 0debug |
static int nbd_co_writev(BlockDriverState *bs, int64_t sector_num,
int nb_sectors, QEMUIOVector *qiov)
{
BDRVNBDState *s = bs->opaque;
return nbd_client_session_co_writev(&s->client, sector_num,
nb_sectors, qiov);
}
| 1threat |
MigrationState *migrate_get_current(void)
{
static bool once;
static MigrationState current_migration = {
.state = MIGRATION_STATUS_NONE,
.xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
.mbps = -1,
.parameters = {
.compress_level = DEFAULT_MIGRATE_COMPRESS_LEVEL,
.compress_threads = DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT,
.decompress_threads = DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT,
.cpu_throttle_initial = DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL,
.cpu_throttle_increment = DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT,
.max_bandwidth = MAX_THROTTLE,
.downtime_limit = DEFAULT_MIGRATE_SET_DOWNTIME,
.x_checkpoint_delay = DEFAULT_MIGRATE_X_CHECKPOINT_DELAY,
},
};
if (!once) {
current_migration.parameters.tls_creds = g_strdup("");
current_migration.parameters.tls_hostname = g_strdup("");
once = true;
}
return ¤t_migration;
}
| 1threat |
Camunda - Configurar Service task como external task : **Camunda**
Como configurar uma service task como external task? | 0debug |
How to delete text between a word and a Cell marker : [enter image description here][1]
[1]: https://i.stack.imgur.com/nPAjA.png
How Can I delete the text between <\de> and cell marker throughout my word document?.
| 0debug |
How to download and install Microsoft's Visual Studio C/C++ compiler without Visual Studio : <p>I'm trying to run c code on my windows. (I had been running it so far on repl.it). But it is proving harder than it is supposed to be.
MinGW is not installing due to some reason. And I've spent a lot of time trying to run it some other way. From my research, I think the best way to go about it is to download Visual Studio, but I have a low-end PC and I don't think I <em>should</em> install Visual Studio. Can I, somehow, only install the C/C++ compiler that comes with it without installing Visual Studio itself.</p>
<p>If it helps, I usually run my (python) code in atom, but also have Visual Studio Code installed on my machine.</p>
<p>I apologize if my question is stupid, I am a self-taught programmer who learned to code from MIT's 6.00.1x and 6.00.2x and am currently trying to learn C from 'The C Programming Language' by Kernighan and Ritchie. I've never formally studied computer science.</p>
| 0debug |
r: convert a string to date : <p>I have a string like that:</p>
<pre><code>201601
201603
201604
201606
201501
</code></pre>
<p>And I'd like to convert to Date, like so:</p>
<pre><code>2016-01
2016-03
2016-04
2016-06
2015-01
</code></pre>
<p>I have tried:<code>df$month_key=as.Date(df$month_key,format="YYYYmm")</code>
But it asks for the origin, which we don't need to care about.
Is there a way to do that, or maybe add a dash between character 4 and 5 in the whole column?
Thanks</p>
| 0debug |
how to create an UIImage by pdf file in Xcode : [use the pdf as icon][1]
[1]: http://i.stack.imgur.com/N3OVK.png
when i want to use the pdf icon in project,i do like this
[UIImage imageNamed:@"icon_file_open"];
but is that ok? [UIImage imageNamed:] will always retain the image in memory,is there any other way that i can create the image by pdf? | 0debug |
Zip single file : <p>I am trying to zip a single file in python. For whatever reason, I'm having a hard time getting down the syntax. What I am trying to do is keep the original file and create a new zipped file of the original (like what a Mac or Windows would do if you archive a file).</p>
<p>Here is what I have so far:</p>
<pre><code>import zipfile
myfilepath = '/tmp/%s' % self.file_name
myzippath = myfilepath.replace('.xml', '.zip')
zipfile.ZipFile(myzippath, 'w').write(open(myfilepath).read()) # does not zip the file properly
</code></pre>
| 0debug |
checkbox in MVC controller to convert into bit : I have a scenario in MVC where in
One table from my DB row contains Active(bit) how to update the row in MVC using Checkbox. If it's checked then the value must be 1 if not it must take 0 how to do these any one please help here.
Please help me out by model view and controller script without using entity framework
Thanx in advance | 0debug |
Does the "new" Facebook Marketplace have a listing API? : <p>Facebook recently launched a slightly better, and certainly more prominent, Marketplace to sell goods locally. Is there an API for adding listings or does anyone know if there will be an API?</p>
| 0debug |
static void block_dirty_bitmap_add_prepare(BlkActionState *common,
Error **errp)
{
Error *local_err = NULL;
BlockDirtyBitmapAdd *action;
BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
common, common);
if (action_check_completion_mode(common, errp) < 0) {
return;
}
action = common->action->u.block_dirty_bitmap_add;
qmp_block_dirty_bitmap_add(action->node, action->name,
action->has_granularity, action->granularity,
&local_err);
if (!local_err) {
state->prepared = true;
} else {
error_propagate(errp, local_err);
}
}
| 1threat |
Getter-Setter method and Array List : <p>I have a class NewClass2 and a class with main method. Basically what I want to to is I wanna save a book title, release date, number of pages and the isbn number in an ArrayList and then print the Info.</p>
<pre><code>public class NewClass2 {
int pages;
String released;
String title;
int isbn;
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public String getReleased() {
return released;
}
public void setReleased(String released) {
this.released = released;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getIsbn() {
return isbn;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
public NewClass2(int pages, String released, String title, int isbn) {
this.pages = pages;
this.released = released;
this.title = title;
this.isbn = isbn;
}
public NewClass2() {
}
public void printInfo(){
System.out.println("The book has "+pages+" pages and was released on "+released+" and is called "+title);
}
}
</code></pre>
<p>And the main class:</p>
<pre><code> public class mainClass {
public static void main(String[] args){
ArrayList<NewClass2> listTest = new ArrayList<>( );
listTest.add(new NewClass2( 200,"Book 1", "8.9.14",2222) );
listTest.add(new NewClass2( 200,"Book 2", "1.2.04",5555) );
listTest.add(new NewClass2( 200,"Book 3", "5.4.06",6666) );
listTest.add(new NewClass2( 200,"Book 4", "7.4.13",7777) );
listTest.add(new NewClass2( 200,"Book 5", "2.2.03",8888) );
NewClass2 book = new NewClass2(listTest);
book.printInfo();
}
}
</code></pre>
<p>The IDE tells me that </p>
<pre><code>NewClass2 book = new NewClass2(listTest);
</code></pre>
<p>is wrong but why? and how to i fix it??</p>
| 0debug |
StrongARMState *sa1110_init(MemoryRegion *sysmem,
unsigned int sdram_size, const char *rev)
{
StrongARMState *s;
int i;
s = g_new0(StrongARMState, 1);
if (!rev) {
rev = "sa1110-b5";
}
if (strncmp(rev, "sa1110", 6)) {
error_report("Machine requires a SA1110 processor.");
exit(1);
}
s->cpu = ARM_CPU(cpu_generic_init(TYPE_ARM_CPU, rev));
if (!s->cpu) {
error_report("Unable to find CPU definition");
exit(1);
}
memory_region_allocate_system_memory(&s->sdram, NULL, "strongarm.sdram",
sdram_size);
memory_region_add_subregion(sysmem, SA_SDCS0, &s->sdram);
s->pic = sysbus_create_varargs("strongarm_pic", 0x90050000,
qdev_get_gpio_in(DEVICE(s->cpu), ARM_CPU_IRQ),
qdev_get_gpio_in(DEVICE(s->cpu), ARM_CPU_FIQ),
NULL);
sysbus_create_varargs("pxa25x-timer", 0x90000000,
qdev_get_gpio_in(s->pic, SA_PIC_OSTC0),
qdev_get_gpio_in(s->pic, SA_PIC_OSTC1),
qdev_get_gpio_in(s->pic, SA_PIC_OSTC2),
qdev_get_gpio_in(s->pic, SA_PIC_OSTC3),
NULL);
sysbus_create_simple(TYPE_STRONGARM_RTC, 0x90010000,
qdev_get_gpio_in(s->pic, SA_PIC_RTC_ALARM));
s->gpio = strongarm_gpio_init(0x90040000, s->pic);
s->ppc = sysbus_create_varargs(TYPE_STRONGARM_PPC, 0x90060000, NULL);
for (i = 0; sa_serial[i].io_base; i++) {
DeviceState *dev = qdev_create(NULL, TYPE_STRONGARM_UART);
qdev_prop_set_chr(dev, "chardev", serial_hds[i]);
qdev_init_nofail(dev);
sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0,
sa_serial[i].io_base);
sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0,
qdev_get_gpio_in(s->pic, sa_serial[i].irq));
}
s->ssp = sysbus_create_varargs(TYPE_STRONGARM_SSP, 0x80070000,
qdev_get_gpio_in(s->pic, SA_PIC_SSP), NULL);
s->ssp_bus = (SSIBus *)qdev_get_child_bus(s->ssp, "ssi");
return s;
}
| 1threat |
On Android Studio, the inspection "Unused resources" doesn't work for all modules on my project : <p>I run it this way "Menu -> Analyze -> Run Inspection by Name -> Unused resources" and I select entire project but it doesn't find any unused resources outside my main App Module. So I then run it for individual modules and it finds stuff but it also finds items that are used on other modules. </p>
<p>For example, I have a shared module which has some common strings in it, like "dismiss" for dialogs. The string is not used in that module. When I run the inspection just for that module it finds it as unused. </p>
<p>On the other hand, I have some string on that same shared module that I no longer use anywhere, and when I run the inspections for the entire project, it won't find that string. </p>
<p>I think the issue might be the way I did shared modules, basically they are on different directories I import them putting this on settings.gradle:</p>
<pre><code>include ':androidutils'
project(':androidutils').projectDir = new File( '../sharedlibs/androidutils')
</code></pre>
<p>Then in my build.gradle I just import <code>:androidutils</code> as a dependency. </p>
<p>Anyone else have this issue?</p>
<p>Thanks. </p>
| 0debug |
Explain Why StackOverFlow error raised in this Program..? : <p>I was practicing java, and i wrote this program and once i run it, this raise an error StackOverFlow Error why ?</p>
<pre><code>public class MyClass {
MyClass s=new MyClass();
public static void main(String args[]) {
MyClass s1=new MyClass();
System.out.println("Sum of x+y = ");
}
}
</code></pre>
<p>Exception StackTrace :</p>
<pre><code>Exception in thread "main" java.lang.StackOverflowError
at com.practice.java.dev.MyClass.<init>(MyClass.java:3)
at com.practice.java.dev.MyClass.<init>(MyClass.java:5)
at com.practice.java.dev.MyClass.MyClass.<init>(MyClass.java:5)
at com.practice.java.dev.MyClass.<init>(MyClass.java:5)
at com.practice.java.dev.MyClass.<init>(MyClass.java:5)
at com.practice.java.dev.MyClass.<init>(MyClass.java:5)
</code></pre>
<p>Why so, Please explain it in deep ??</p>
| 0debug |
static uint64_t get_cluster_offset(BlockDriverState *bs,
uint64_t offset, int allocate,
int compressed_size,
int n_start, int n_end)
{
BDRVQcowState *s = bs->opaque;
int min_index, i, j, l1_index, l2_index;
uint64_t l2_offset, *l2_table, cluster_offset, tmp;
uint32_t min_count;
int new_l2_table;
l1_index = offset >> (s->l2_bits + s->cluster_bits);
l2_offset = s->l1_table[l1_index];
new_l2_table = 0;
if (!l2_offset) {
if (!allocate)
return 0;
l2_offset = bdrv_getlength(bs->file->bs);
l2_offset = (l2_offset + s->cluster_size - 1) & ~(s->cluster_size - 1);
s->l1_table[l1_index] = l2_offset;
tmp = cpu_to_be64(l2_offset);
if (bdrv_pwrite_sync(bs->file,
s->l1_table_offset + l1_index * sizeof(tmp),
&tmp, sizeof(tmp)) < 0)
return 0;
new_l2_table = 1;
}
for(i = 0; i < L2_CACHE_SIZE; i++) {
if (l2_offset == s->l2_cache_offsets[i]) {
if (++s->l2_cache_counts[i] == 0xffffffff) {
for(j = 0; j < L2_CACHE_SIZE; j++) {
s->l2_cache_counts[j] >>= 1;
}
}
l2_table = s->l2_cache + (i << s->l2_bits);
goto found;
}
}
min_index = 0;
min_count = 0xffffffff;
for(i = 0; i < L2_CACHE_SIZE; i++) {
if (s->l2_cache_counts[i] < min_count) {
min_count = s->l2_cache_counts[i];
min_index = i;
}
}
l2_table = s->l2_cache + (min_index << s->l2_bits);
if (new_l2_table) {
memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
if (bdrv_pwrite_sync(bs->file, l2_offset, l2_table,
s->l2_size * sizeof(uint64_t)) < 0)
return 0;
} else {
if (bdrv_pread(bs->file, l2_offset, l2_table,
s->l2_size * sizeof(uint64_t)) !=
s->l2_size * sizeof(uint64_t))
return 0;
}
s->l2_cache_offsets[min_index] = l2_offset;
s->l2_cache_counts[min_index] = 1;
found:
l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
cluster_offset = be64_to_cpu(l2_table[l2_index]);
if (!cluster_offset ||
((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) {
if (!allocate)
return 0;
if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&
(n_end - n_start) < s->cluster_sectors) {
if (decompress_cluster(bs, cluster_offset) < 0)
return 0;
cluster_offset = bdrv_getlength(bs->file->bs);
cluster_offset = (cluster_offset + s->cluster_size - 1) &
~(s->cluster_size - 1);
if (bdrv_pwrite(bs->file, cluster_offset, s->cluster_cache,
s->cluster_size) !=
s->cluster_size)
return -1;
} else {
cluster_offset = bdrv_getlength(bs->file->bs);
if (allocate == 1) {
cluster_offset = (cluster_offset + s->cluster_size - 1) &
~(s->cluster_size - 1);
bdrv_truncate(bs->file, cluster_offset + s->cluster_size, NULL);
if (bs->encrypted &&
(n_end - n_start) < s->cluster_sectors) {
uint64_t start_sect;
assert(s->cipher);
start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
for(i = 0; i < s->cluster_sectors; i++) {
if (i < n_start || i >= n_end) {
Error *err = NULL;
memset(s->cluster_data, 0x00, 512);
if (encrypt_sectors(s, start_sect + i,
s->cluster_data, 1,
true, &err) < 0) {
error_free(err);
errno = EIO;
return -1;
}
if (bdrv_pwrite(bs->file,
cluster_offset + i * 512,
s->cluster_data, 512) != 512)
return -1;
}
}
}
} else if (allocate == 2) {
cluster_offset |= QCOW_OFLAG_COMPRESSED |
(uint64_t)compressed_size << (63 - s->cluster_bits);
}
}
tmp = cpu_to_be64(cluster_offset);
l2_table[l2_index] = tmp;
if (bdrv_pwrite_sync(bs->file, l2_offset + l2_index * sizeof(tmp),
&tmp, sizeof(tmp)) < 0)
return 0;
}
return cluster_offset;
}
| 1threat |
JAVA: How do I determine if the input is a palindrome? : <p>Please use the method below. </p>
<p>I am trying to get rid of all white spaces, punctuations and make everything lowercase. Then I want to see whether the string is a palindrome (same when read from the front and back.</p>
<p>I can't figure it out.</p>
<pre><code>public static void main(String[] args) {
String word=null;
String reverse="";
Scanner console = new Scanner(System.in);
System.out.print("Please enter a word or a phrase:");
word = console.nextLine();
word=word.replaceAll("\\s+",""); //removes white space
word=word.replaceAll("[^a-zA-Z ]", ""); //removes all punctuation
word=word.toLowerCase();
for(int i=word.length()-1; i>=0; i--) {
reverse +=word.charAt(i);
}
for(int i=0; i<word.length(); i++) {
System.out.print(word);
if(word.charAt(i) != reverse.charAt(i)) {
System.out.println("Not a Palindrome");
}else {
System.out.println("Palindrome");```
</code></pre>
| 0debug |
Docker ERROR: Error processing tar file(exit status 1): unexpected EOF : <p>I needed space and executed: <code>docker rmi $(docker images -f "dangling=true" -q)</code></p>
<p>Since then I can't with docker-compose: <code>docker-compose build</code>, I get the error: <code>ERROR: Error processing tar file(exit status 1): unexpected EOF</code>.</p>
<p>I tried to remove all images, reinstall docker, but nothing will do: always the same error, after quite some time.</p>
<p>I built on another system and it worked, which <em>suggests</em> that this is a wrong-state issue.</p>
<p>Any idea what I should clean?</p>
<p>Using:</p>
<pre><code>▶ docker version
Client:
Version: 17.03.0-ce
API version: 1.24 (downgraded from 1.26)
Go version: go1.7.5
Git commit: 3a232c8
Built: Tue Feb 28 08:01:32 2017
OS/Arch: linux/amd64
Server:
Version: 1.12.6
API version: 1.24 (minimum version )
Go version: go1.6.2
Git commit: 78d1802
Built: Tue Jan 31 23:35:14 2017
OS/Arch: linux/amd64
Experimental: false
▶ docker-compose version
docker-compose version 1.11.2, build dfed245
docker-py version: 2.1.0
CPython version: 2.7.13
OpenSSL version: OpenSSL 1.0.1t 3 May 2016
</code></pre>
| 0debug |
Front end "micro services" with Angular 2 : <p>I'm looking for a solution for a bit of an odd situation. Let's take a quick look at the angular2-seed project so I can better explain: <a href="https://github.com/mgechev/angular2-seed/tree/master/src/client/app" rel="noreferrer">https://github.com/mgechev/angular2-seed/tree/master/src/client/app</a>.</p>
<p>In that project, we have 3 isolated modules - about, home, shared. What I am looking for is a way to isolate development of these, so we're ultimately able to release each piece independently. For example, say Team A is working on the about section, and Team B is working on home. Work is complete for each, and we're ready to release, however we realize the about section is missing a critical piece of functionality, however we still want to release the change to the home section. What we're looking for is a way to achieve this.</p>
<p>Here are some solutions already explored, but I'm not really happy with:</p>
<ul>
<li>Have completely different applications for home/about (in my eyes, this eliminates many of the benefits of a SPA).</li>
<li>Have each module (about, home, shared) roll up into it's own NPM package. When we go to deploy, we would have some way to orchestrate pulling in all the published NPM packages for these modules.</li>
</ul>
| 0debug |
insert the values through a stored procedure in oracle : i have the following code in sql server,kindly let me know whats the appropriate code of inserting values through a stored procedure in oracle:
CREATE PROCEDURE INSERTPRODUCTRECORD
(
@PNAME VARCHAR(5),
@CATEGORY VARCHAR(50),
@PRICE INT
)
AS
BEGIN
INSERT INTO PRODUCT (PNAME,PRICE,CATEGORY)
VALUES(@PNAME, @CATEGORY, @PRICE INT)
END
| 0debug |
Run function in input if it is empty? : <p>Is there anyway I can check if an input is empty using javascript and then run a function? I'd like it to be in the input itself if possible. </p>
<p>There is <code>onChange</code> so is there an <code>ifEmpty</code> lol?</p>
| 0debug |
static int ffm_read_header(AVFormatContext *s, AVFormatParameters *ap)
{
FFMContext *ffm = s->priv_data;
AVStream *st;
ByteIOContext *pb = s->pb;
AVCodecContext *codec;
int i, nb_streams;
uint32_t tag;
tag = get_le32(pb);
if (tag != MKTAG('F', 'F', 'M', '1'))
goto fail;
ffm->packet_size = get_be32(pb);
if (ffm->packet_size != FFM_PACKET_SIZE)
goto fail;
ffm->write_index = get_be64(pb);
if (!url_is_streamed(pb)) {
ffm->file_size = url_fsize(pb);
if (ffm->write_index)
adjust_write_index(s);
} else {
ffm->file_size = (UINT64_C(1) << 63) - 1;
}
nb_streams = get_be32(pb);
get_be32(pb);
for(i=0;i<nb_streams;i++) {
char rc_eq_buf[128];
st = av_new_stream(s, 0);
if (!st)
goto fail;
av_set_pts_info(st, 64, 1, 1000000);
codec = st->codec;
codec->codec_id = get_be32(pb);
codec->codec_type = get_byte(pb);
codec->bit_rate = get_be32(pb);
st->quality = get_be32(pb);
codec->flags = get_be32(pb);
codec->flags2 = get_be32(pb);
codec->debug = get_be32(pb);
switch(codec->codec_type) {
case CODEC_TYPE_VIDEO:
codec->time_base.num = get_be32(pb);
codec->time_base.den = get_be32(pb);
codec->width = get_be16(pb);
codec->height = get_be16(pb);
codec->gop_size = get_be16(pb);
codec->pix_fmt = get_be32(pb);
codec->qmin = get_byte(pb);
codec->qmax = get_byte(pb);
codec->max_qdiff = get_byte(pb);
codec->qcompress = get_be16(pb) / 10000.0;
codec->qblur = get_be16(pb) / 10000.0;
codec->bit_rate_tolerance = get_be32(pb);
codec->rc_eq = av_strdup(get_strz(pb, rc_eq_buf, sizeof(rc_eq_buf)));
codec->rc_max_rate = get_be32(pb);
codec->rc_min_rate = get_be32(pb);
codec->rc_buffer_size = get_be32(pb);
codec->i_quant_factor = av_int2dbl(get_be64(pb));
codec->b_quant_factor = av_int2dbl(get_be64(pb));
codec->i_quant_offset = av_int2dbl(get_be64(pb));
codec->b_quant_offset = av_int2dbl(get_be64(pb));
codec->dct_algo = get_be32(pb);
codec->strict_std_compliance = get_be32(pb);
codec->max_b_frames = get_be32(pb);
codec->luma_elim_threshold = get_be32(pb);
codec->chroma_elim_threshold = get_be32(pb);
codec->mpeg_quant = get_be32(pb);
codec->intra_dc_precision = get_be32(pb);
codec->me_method = get_be32(pb);
codec->mb_decision = get_be32(pb);
codec->nsse_weight = get_be32(pb);
codec->frame_skip_cmp = get_be32(pb);
codec->rc_buffer_aggressivity = av_int2dbl(get_be64(pb));
codec->codec_tag = get_be32(pb);
codec->thread_count = get_byte(pb);
codec->coder_type = get_be32(pb);
codec->me_cmp = get_be32(pb);
codec->partitions = get_be32(pb);
codec->me_subpel_quality = get_be32(pb);
codec->me_range = get_be32(pb);
codec->keyint_min = get_be32(pb);
codec->scenechange_threshold = get_be32(pb);
codec->b_frame_strategy = get_be32(pb);
codec->qcompress = av_int2dbl(get_be64(pb));
codec->qblur = av_int2dbl(get_be64(pb));
codec->max_qdiff = get_be32(pb);
codec->refs = get_be32(pb);
codec->directpred = get_be32(pb);
break;
case CODEC_TYPE_AUDIO:
codec->sample_rate = get_be32(pb);
codec->channels = get_le16(pb);
codec->frame_size = get_le16(pb);
codec->sample_fmt = get_le16(pb);
break;
default:
goto fail;
}
if (codec->flags & CODEC_FLAG_GLOBAL_HEADER) {
codec->extradata_size = get_be32(pb);
codec->extradata = av_malloc(codec->extradata_size);
if (!codec->extradata)
return AVERROR(ENOMEM);
get_buffer(pb, codec->extradata, codec->extradata_size);
}
}
while ((url_ftell(pb) % ffm->packet_size) != 0)
get_byte(pb);
ffm->packet_ptr = ffm->packet;
ffm->packet_end = ffm->packet;
ffm->frame_offset = 0;
ffm->dts = 0;
ffm->read_state = READ_HEADER;
ffm->first_packet = 1;
return 0;
fail:
for(i=0;i<s->nb_streams;i++) {
st = s->streams[i];
if (st) {
av_free(st);
}
}
return -1;
}
| 1threat |
jquery, i want with twoo thumbs buttons if i clic one other's change and vice versa...? : i try to do some thumb button, if i clic one other's is déclic, and vice versa, but if i clic, he other's stay cliqued, and vice versa,and he stay together cliqued and i can uncli, however, i try to remove or add class on toggle, and than doens'not work... Why ? Someone can help me ?..Thanks ...
echo '<button type="button" class="bout unlike bthumb boutontagthumbdown" id="unlike_'.$row['tag_number_id'].'" value="unlike"><i class="fas fa-thumbs-down fa-lg"></i></button>';
echo '<small class="text-muted" style="padding: 5px;"> ';
echo $this->totalunlikes($tagid);
echo ' TagUnTouch </small>';
echo '<button type="button" class="bout like bthumb boutontagthumbup" id="like_'.$row['tag_number_id'].'" value="like"><i class="fas fa-thumbs-up fa-lg"></i></button>';
echo '<small class="text-muted" style="padding: 5px;"> ';
<script type="text/javascript">
$(function(){
console.log( "ready!" );
$(".bout").click(function(){
var Id = this.id;
var Idunlike = ("#" + Id + ".bout.unlike");
var Idlike = ("#" + Id + ".bout.like");
if ( $(this).attr("value") == 'unlike' ){
$(Idunlike).toggleClass("boutontagthumbdownclic");
$(Idlike).addClass("boutontagthumbupclicreturn");
console.log(Idunlike);
} else if ( $(this).attr("value") == 'like' ) {
$(Idlike).toggleClass("boutontagthumbupclic");
$(Idunlike).addClass("boutontagthumbdownclicreturn");
console.log(Idlike);
}
});
});
</script>
| 0debug |
static unsigned int dec_move_pr(DisasContext *dc)
{
TCGv t0;
DIS(fprintf (logfile, "move $p%u, $r%u\n", dc->op1, dc->op2));
cris_cc_mask(dc, 0);
if (dc->op2 == PR_CCS)
cris_evaluate_flags(dc);
t0 = tcg_temp_new(TCG_TYPE_TL);
t_gen_mov_TN_preg(t0, dc->op2);
cris_alu(dc, CC_OP_MOVE,
cpu_R[dc->op1], cpu_R[dc->op1], t0, preg_sizes[dc->op2]);
tcg_temp_free(t0);
return 2;
}
| 1threat |
Changing indentation settings in the Spyder editor for Python : <p>I am using the Spyder editor for Python.
I need to change the indentation setting (e.g., let "tab" mean "4 spaces").</p>
<p>How do I accomplish this?</p>
| 0debug |
How to ask print questions statement? : What is questions written in python is it possible to get print **statement**?
> print statement | 0debug |
int i2c_send(I2CBus *bus, uint8_t data)
{
I2CSlaveClass *sc;
I2CNode *node;
int ret = 0;
QLIST_FOREACH(node, &bus->current_devs, next) {
sc = I2C_SLAVE_GET_CLASS(node->elt);
if (sc->send) {
ret = ret || sc->send(node->elt, data);
} else {
ret = -1;
}
}
return ret ? -1 : 0;
}
| 1threat |
static int dshow_read_header(AVFormatContext *avctx)
{
struct dshow_ctx *ctx = avctx->priv_data;
IGraphBuilder *graph = NULL;
ICreateDevEnum *devenum = NULL;
IMediaControl *control = NULL;
int ret = AVERROR(EIO);
int r;
if (!ctx->list_devices && !parse_device_name(avctx)) {
av_log(avctx, AV_LOG_ERROR, "Malformed dshow input string.\n");
goto error;
}
ctx->video_codec_id = avctx->video_codec_id ? avctx->video_codec_id
: AV_CODEC_ID_RAWVIDEO;
if (ctx->pixel_format != AV_PIX_FMT_NONE) {
if (ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO) {
av_log(avctx, AV_LOG_ERROR, "Pixel format may only be set when "
"video codec is not set or set to rawvideo\n");
ret = AVERROR(EINVAL);
goto error;
}
}
if (ctx->framerate) {
r = av_parse_video_rate(&ctx->requested_framerate, ctx->framerate);
if (r < 0) {
av_log(avctx, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", ctx->framerate);
goto error;
}
}
CoInitialize(0);
r = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
&IID_IGraphBuilder, (void **) &graph);
if (r != S_OK) {
av_log(avctx, AV_LOG_ERROR, "Could not create capture graph.\n");
goto error;
}
ctx->graph = graph;
r = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
&IID_ICreateDevEnum, (void **) &devenum);
if (r != S_OK) {
av_log(avctx, AV_LOG_ERROR, "Could not enumerate system devices.\n");
goto error;
}
if (ctx->list_devices) {
av_log(avctx, AV_LOG_INFO, "DirectShow video devices\n");
dshow_cycle_devices(avctx, devenum, VideoDevice, NULL);
av_log(avctx, AV_LOG_INFO, "DirectShow audio devices\n");
dshow_cycle_devices(avctx, devenum, AudioDevice, NULL);
ret = AVERROR_EXIT;
goto error;
}
if (ctx->list_options) {
if (ctx->device_name[VideoDevice])
dshow_list_device_options(avctx, devenum, VideoDevice);
if (ctx->device_name[AudioDevice])
dshow_list_device_options(avctx, devenum, AudioDevice);
ret = AVERROR_EXIT;
goto error;
}
if (ctx->device_name[VideoDevice]) {
if ((r = dshow_open_device(avctx, devenum, VideoDevice)) < 0 ||
(r = dshow_add_device(avctx, VideoDevice)) < 0) {
ret = r;
goto error;
}
}
if (ctx->device_name[AudioDevice]) {
if ((r = dshow_open_device(avctx, devenum, AudioDevice)) < 0 ||
(r = dshow_add_device(avctx, AudioDevice)) < 0) {
ret = r;
goto error;
}
}
ctx->mutex = CreateMutex(NULL, 0, NULL);
if (!ctx->mutex) {
av_log(avctx, AV_LOG_ERROR, "Could not create Mutex\n");
goto error;
}
ctx->event = CreateEvent(NULL, 1, 0, NULL);
if (!ctx->event) {
av_log(avctx, AV_LOG_ERROR, "Could not create Event\n");
goto error;
}
r = IGraphBuilder_QueryInterface(graph, &IID_IMediaControl, (void **) &control);
if (r != S_OK) {
av_log(avctx, AV_LOG_ERROR, "Could not get media control.\n");
goto error;
}
ctx->control = control;
r = IMediaControl_Run(control);
if (r == S_FALSE) {
OAFilterState pfs;
r = IMediaControl_GetState(control, 0, &pfs);
}
if (r != S_OK) {
av_log(avctx, AV_LOG_ERROR, "Could not run filter\n");
goto error;
}
ret = 0;
error:
if (ret < 0)
dshow_read_close(avctx);
if (devenum)
ICreateDevEnum_Release(devenum);
return ret;
}
| 1threat |
static int tiff_unpack_strip(TiffContext *s, uint8_t *dst, int stride,
const uint8_t *src, int size, int lines)
{
int c, line, pixels, code, ret;
const uint8_t *ssrc = src;
int width = ((s->width * s->bpp) + 7) >> 3;
if (size <= 0)
return AVERROR_INVALIDDATA;
if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
#if CONFIG_ZLIB
return tiff_unpack_zlib(s, dst, stride, src, size, width, lines);
#else
av_log(s->avctx, AV_LOG_ERROR,
"zlib support not enabled, "
"deflate compression not supported\n");
return AVERROR(ENOSYS);
#endif
}
if (s->compr == TIFF_LZW) {
if ((ret = ff_lzw_decode_init(s->lzw, 8, src, size, FF_LZW_TIFF)) < 0) {
av_log(s->avctx, AV_LOG_ERROR, "Error initializing LZW decoder\n");
return ret;
}
}
if (s->compr == TIFF_CCITT_RLE ||
s->compr == TIFF_G3 ||
s->compr == TIFF_G4) {
return tiff_unpack_fax(s, dst, stride, src, size, lines);
}
for (line = 0; line < lines; line++) {
if (src - ssrc > size) {
av_log(s->avctx, AV_LOG_ERROR, "Source data overread\n");
return AVERROR_INVALIDDATA;
}
switch (s->compr) {
case TIFF_RAW:
if (ssrc + size - src < width)
return AVERROR_INVALIDDATA;
if (!s->fill_order) {
memcpy(dst, src, width);
} else {
int i;
for (i = 0; i < width; i++)
dst[i] = ff_reverse[src[i]];
}
src += width;
break;
case TIFF_PACKBITS:
for (pixels = 0; pixels < width;) {
code = (int8_t) *src++;
if (code >= 0) {
code++;
if (pixels + code > width) {
av_log(s->avctx, AV_LOG_ERROR,
"Copy went out of bounds\n");
return AVERROR_INVALIDDATA;
}
memcpy(dst + pixels, src, code);
src += code;
pixels += code;
} else if (code != -128) {
code = (-code) + 1;
if (pixels + code > width) {
av_log(s->avctx, AV_LOG_ERROR,
"Run went out of bounds\n");
return AVERROR_INVALIDDATA;
}
c = *src++;
memset(dst + pixels, c, code);
pixels += code;
}
}
break;
case TIFF_LZW:
pixels = ff_lzw_decode(s->lzw, dst, width);
if (pixels < width) {
av_log(s->avctx, AV_LOG_ERROR, "Decoded only %i bytes of %i\n",
pixels, width);
return AVERROR_INVALIDDATA;
}
break;
}
dst += stride;
}
return 0;
}
| 1threat |
Value to be from a selection of 3 and not null : I'm using oracle to create a table called module:
Module(ModuleId, ModuleTitle, ModuleLeader, Credits, CourseworkPercentage, ExamPercentage)
ModuleId being the PK.
A constraint/check which i have to implement is for 'Credits' to be not null and it must be equal to one of the following three values: 10, 20 or 40.
What I have so far is:
CREATE TABLE "MODULE_CC"
("MODULEID" NUMBER,
"MODULETITLE" VARCHAR2(30) NOT NULL ENABLE,
"MODULELEADER" VARCHAR2(30) NOT NULL ENABLE,
"CREDITS" NUMBER NOT NULL ENABLE,
"COURSEWORKPERCENTAGE" NUMBER,
"EXAMPERCENTAGE" NUMBER,
PRIMARY KEY ("MODULEID") ENABLE,
CHECK (CourseworkPercentage + ExamPercentage = 100) ENABLE
);
What would be the check/constrains to make sure that credits will be equal to one of three values(10,20 or 40)? | 0debug |
static void migrate_fd_cleanup(void *opaque)
{
MigrationState *s = opaque;
qemu_bh_delete(s->cleanup_bh);
s->cleanup_bh = NULL;
if (s->file) {
trace_migrate_fd_cleanup();
qemu_mutex_unlock_iothread();
qemu_thread_join(&s->thread);
qemu_mutex_lock_iothread();
qemu_fclose(s->file);
s->file = NULL;
}
assert(s->state != MIG_STATE_ACTIVE);
if (s->state != MIG_STATE_COMPLETED) {
qemu_savevm_state_cancel();
if (s->state == MIG_STATE_CANCELLING) {
migrate_set_state(s, MIG_STATE_CANCELLING, MIG_STATE_CANCELLED);
}
}
notifier_list_notify(&migration_state_notifiers, s);
}
| 1threat |
In python argparse, is there a use case for nargs=1? : <p>It seems as though it would always make more sense to use the default action of <code>store</code> without specifying <code>nargs</code> so the output is always as expected, instead of sometimes being a <code>list</code> and sometimes not. I'm just curious if I missed something..</p>
<p>example</p>
<pre><code>>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
_StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('--bar', nargs=1)
_StoreAction(option_strings=['--bar'], dest='bar', nargs=1, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('--foo 1 --bar 1'.split())
Namespace(bar=['1'], foo='1')
>>> parser.parse_args('')
Namespace(bar=None, foo=None)
</code></pre>
| 0debug |
i am building an ios app in swift and when i enter a number this happens : on this line of code i get this error
if diceRoll == userGuessTextField.text {
2016-02-04 18:38:34.756 How Many Fingers[2972:158461] Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad; using 1336863583_PortraitChoco_iPhone-Simple-Pad_Default
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
import UIKit
class ViewController: UIViewController {
@IBOutlet var userGuessTextField: UITextField!
@IBOutlet var resultLabel: UILabel!
@IBAction func guess(sender: AnyObject) {
let diceRoll = String(arc4random_uniform(6))
if diceRoll == userGuessTextField.text {
resultLabel.text = "You're right!"
}
else {
resultLabel.text = "Wrong! It was a " + diceRoll
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}[enter image description here][1]
[1]: http://i.stack.imgur.com/Y8slL.png | 0debug |
static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent,
Error **errp)
{
int ret;
int l1_size, i;
l1_size = extent->l1_size * sizeof(uint32_t);
extent->l1_table = g_try_malloc(l1_size);
if (l1_size && extent->l1_table == NULL) {
return -ENOMEM;
}
ret = bdrv_pread(extent->file,
extent->l1_table_offset,
extent->l1_table,
l1_size);
if (ret < 0) {
error_setg_errno(errp, -ret,
"Could not read l1 table from extent '%s'",
extent->file->filename);
goto fail_l1;
}
for (i = 0; i < extent->l1_size; i++) {
le32_to_cpus(&extent->l1_table[i]);
}
if (extent->l1_backup_table_offset) {
extent->l1_backup_table = g_try_malloc(l1_size);
if (l1_size && extent->l1_backup_table == NULL) {
ret = -ENOMEM;
goto fail_l1;
}
ret = bdrv_pread(extent->file,
extent->l1_backup_table_offset,
extent->l1_backup_table,
l1_size);
if (ret < 0) {
error_setg_errno(errp, -ret,
"Could not read l1 backup table from extent '%s'",
extent->file->filename);
goto fail_l1b;
}
for (i = 0; i < extent->l1_size; i++) {
le32_to_cpus(&extent->l1_backup_table[i]);
}
}
extent->l2_cache =
g_new(uint32_t, extent->l2_size * L2_CACHE_SIZE);
return 0;
fail_l1b:
g_free(extent->l1_backup_table);
fail_l1:
g_free(extent->l1_table);
return ret;
}
| 1threat |
static int get_qPy_pred(HEVCContext *s, int xC, int yC,
int xBase, int yBase, int log2_cb_size)
{
HEVCLocalContext *lc = s->HEVClc;
int ctb_size_mask = (1 << s->sps->log2_ctb_size) - 1;
int MinCuQpDeltaSizeMask = (1 << (s->sps->log2_ctb_size -
s->pps->diff_cu_qp_delta_depth)) - 1;
int xQgBase = xBase - (xBase & MinCuQpDeltaSizeMask);
int yQgBase = yBase - (yBase & MinCuQpDeltaSizeMask);
int min_cb_width = s->sps->min_cb_width;
int min_cb_height = s->sps->min_cb_height;
int x_cb = xQgBase >> s->sps->log2_min_cb_size;
int y_cb = yQgBase >> s->sps->log2_min_cb_size;
int availableA = (xBase & ctb_size_mask) &&
(xQgBase & ctb_size_mask);
int availableB = (yBase & ctb_size_mask) &&
(yQgBase & ctb_size_mask);
int qPy_pred, qPy_a, qPy_b;
if (lc->first_qp_group || (!xQgBase && !yQgBase)) {
lc->first_qp_group = !lc->tu.is_cu_qp_delta_coded;
qPy_pred = s->sh.slice_qp;
} else {
qPy_pred = lc->qp_y;
if (log2_cb_size < s->sps->log2_ctb_size -
s->pps->diff_cu_qp_delta_depth) {
static const int offsetX[8][8] = {
{ -1, 1, 3, 1, 7, 1, 3, 1 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 3, 1, 3, 1, 3, 1, 3 },
{ 2, 2, 2, 2, 2, 2, 2, 2 },
{ 3, 5, 7, 5, 3, 5, 7, 5 },
{ 4, 4, 4, 4, 4, 4, 4, 4 },
{ 5, 7, 5, 7, 5, 7, 5, 7 },
{ 6, 6, 6, 6, 6, 6, 6, 6 }
};
static const int offsetY[8][8] = {
{ 7, 0, 1, 2, 3, 4, 5, 6 },
{ 0, 1, 2, 3, 4, 5, 6, 7 },
{ 1, 0, 3, 2, 5, 4, 7, 6 },
{ 0, 1, 2, 3, 4, 5, 6, 7 },
{ 3, 0, 1, 2, 7, 4, 5, 6 },
{ 0, 1, 2, 3, 4, 5, 6, 7 },
{ 1, 0, 3, 2, 5, 4, 7, 6 },
{ 0, 1, 2, 3, 4, 5, 6, 7 }
};
int xC0b = (xC - (xC & ctb_size_mask)) >> s->sps->log2_min_cb_size;
int yC0b = (yC - (yC & ctb_size_mask)) >> s->sps->log2_min_cb_size;
int idxX = (xQgBase & ctb_size_mask) >> s->sps->log2_min_cb_size;
int idxY = (yQgBase & ctb_size_mask) >> s->sps->log2_min_cb_size;
int idx_mask = ctb_size_mask >> s->sps->log2_min_cb_size;
int x, y;
x = FFMIN(xC0b + offsetX[idxX][idxY], min_cb_width - 1);
y = FFMIN(yC0b + (offsetY[idxX][idxY] & idx_mask), min_cb_height - 1);
if (xC0b == (lc->start_of_tiles_x >> s->sps->log2_min_cb_size) &&
offsetX[idxX][idxY] == -1) {
x = (lc->end_of_tiles_x >> s->sps->log2_min_cb_size) - 1;
y = yC0b - 1;
}
qPy_pred = s->qp_y_tab[y * min_cb_width + x];
}
}
if (availableA == 0)
qPy_a = qPy_pred;
else
qPy_a = s->qp_y_tab[(x_cb - 1) + y_cb * min_cb_width];
if (availableB == 0)
qPy_b = qPy_pred;
else
qPy_b = s->qp_y_tab[x_cb + (y_cb - 1) * min_cb_width];
av_assert2(qPy_a >= -s->sps->qp_bd_offset && qPy_a < 52);
av_assert2(qPy_b >= -s->sps->qp_bd_offset && qPy_b < 52);
return (qPy_a + qPy_b + 1) >> 1;
}
| 1threat |
Maintaining Qt Application as Module and Library : <p>How to Maintain 500 qt ui widget form in a single Application. Is it Possible to separate as form application as Module or library. If it is possible, how to links each modules.Is it possible to create separate folders for each modules.</p>
| 0debug |
Null Pointer Exception when adding GroundOverlay to gMap : <p>i'm working on a project for indoor navigation and need to add a groundOverlay with the floorplan of the building. I've followed the guidelines on the Documentation from Google dev site. But its giving me NullPointerException when i try to add the overlay to the map.
Heres my code:</p>
<pre><code>@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setIndoorEnabled(true);
mMap.setOnIndoorStateChangeListener(this);
mMap.setPadding(0,0,50,0);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-28.666957, -55.994823), 19));
//add mapOverlay
LatLngBounds iffBounds = new LatLngBounds(
new LatLng(-28.667177,-55.995104),
new LatLng(-28.667061,-55.994443)
);
GroundOverlayOptions iffMap = new GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromResource(R.raw.piso_1))
.positionFromBounds(iffBounds);
mapOverlay = mMap.addGroundOverlay(iffMap);
}
</code></pre>
<p>I have tried debbuging the code and i can't see anything wrong, everything is being correctly instantiated, but when it executes the last line</p>
<pre><code>mapOverlay = mMap.addGroundOverlay(iffmap);
</code></pre>
<p>My app crashes.</p>
<p>Here's the StackTrace from logCat:</p>
<pre><code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: br.com.imerljak.vegvisir, PID: 2390
java.lang.NullPointerException: null reference
at maps.w.c.a(Unknown Source)
at maps.ad.g$a.<init>(Unknown Source)
at maps.ad.g.a(Unknown Source)
at maps.ad.w.<init>(Unknown Source)
at maps.ad.u.a(Unknown Source)
at vo.onTransact(:com.google.android.gms.DynamiteModulesB:182)
at android.os.Binder.transact(Binder.java:380)
at com.google.android.gms.maps.internal.IGoogleMapDelegate$zza$zza.addGroundOverlay(Unknown Source)
at com.google.android.gms.maps.GoogleMap.addGroundOverlay(Unknown Source)
at br.com.imerljak.vegvisir.MapsActivity.onMapReady(MapsActivity.java:62)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:380)
at xz.a(:com.google.android.gms.DynamiteModulesB:82)
at maps.ad.u$5.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
</code></pre>
<p>PS: if anyone has any tips that will help me developing this app (like a good API for indoor navigation) i will be grateful :)</p>
| 0debug |
java class extends not working properly : Am playing a bit around with java and am learning step by step. To not write my whole life story, here it comes.
I am making a text game with some stats, a player, enemies, etc. For this I am using classes. Lately I came accross the "extends" function and am trying to implement it. I made a class character, which extends to player and enemy. When I execute the code it seems.as it wouldnt inherit anything. Would appreaciate any advice. Thanks!
P.S. which tags would be ok to use?
import java.util.Random;
public class Character
{
Random rand = new Random();
int cc;
int strength;
int life;
public int getCC()
{
return cc;
}
public void setCC(int c)
{
this.cc = c;
}
public int getStrength()
{
return strength;
}
public void setStrength(int s)
{
this.strength = s;
}
public int getLife()
{
return life;
}
public void setLife(int l)
{
this.life = l;
}
}
public class Player extends Character
{
int cc = rand.nextInt(20)+51;
int strength = rand.nextInt(3)+4;
int life = rand.nextInt(5)+16;
}
public class Enemy extends Character
{
int cc = rand.nextInt(10)+31;
int strength = rand.nextInt(3)+1;
int life = rand.nextInt(5)+6;
}
class myClass
{
public static void main(String[] args)
{
Player argens = new Player();
System.out.println("This is you:\n");
System.out.println("Close Combat " + argens.getCC());
System.out.println("Strength " + argens.getStrength());
System.out.println("Life " + argens.getLife());
Enemy kobold = new Enemy();
fight (argens, kobold);
fight (argens, kobold);
}
static void fight(Player p, Enemy e)
{
p.setLife(p.getLife() - e.getStrength());
System.out.println("\nRemaining life");
System.out.println(p.getLife());
System.out.println(e.getLife());
}
} | 0debug |
restore_sigcontext(CPUM68KState *env, struct target_sigcontext *sc, int *pd0)
{
int temp;
__get_user(env->aregs[7], &sc->sc_usp);
__get_user(env->dregs[1], &sc->sc_d1);
__get_user(env->aregs[0], &sc->sc_a0);
__get_user(env->aregs[1], &sc->sc_a1);
__get_user(env->pc, &sc->sc_pc);
__get_user(temp, &sc->sc_sr);
env->sr = (env->sr & 0xff00) | (temp & 0xff);
*pd0 = tswapl(sc->sc_d0);
}
| 1threat |
How is Complex number assignment from a double enabled? : <p>The Complex structure in System.Numerics allows assignment like this</p>
<pre><code>Complex c = 3.72;
</code></pre>
<p>If I wanted to make my own Complex struct, how would I program this capability? I like it better than using constructors as in</p>
<pre><code>Complex c = new Complex(3.72);
</code></pre>
| 0debug |
This is the python code and it gives unexpected answer : <pre><code>school = 'Massachusetts Institute of Technology'
numVowels = 0
numCons = 0
for char in school:
if char == 'a' or char == 'e' or char == 'i' \
or char == 'o' or char == 'u':
numVowels += 1
elif char == 'o' or char == 'M':
print char
else:
numCons -= 1
print 'numVowels is: ' + str(numVowels)
print 'numCons is: ' + str(numCons)
</code></pre>
<p>This is the python code logically it should print 'o' 3 times but it doesn't i am unable to figure out why also the value of numcons should be -21 but it's coming -25 does anyone has an answer</p>
| 0debug |
What alternatives are there to Hibernate Validator's @SafeHtml to validate Strings? : <p>As stated in the JavaDocs, it will be removed in a future release.
Is there any alternative library which works similarly via annotations?</p>
| 0debug |
int kvm_arch_on_sigbus_vcpu(CPUState *env, int code, void *addr)
{
#ifdef KVM_CAP_MCE
void *vaddr;
ram_addr_t ram_addr;
target_phys_addr_t paddr;
if ((env->mcg_cap & MCG_SER_P) && addr
&& (code == BUS_MCEERR_AR
|| code == BUS_MCEERR_AO)) {
vaddr = (void *)addr;
if (qemu_ram_addr_from_host(vaddr, &ram_addr) ||
!kvm_physical_memory_addr_from_ram(env->kvm_state, ram_addr, &paddr)) {
fprintf(stderr, "Hardware memory error for memory used by "
"QEMU itself instead of guest system!\n");
if (code == BUS_MCEERR_AO) {
return 0;
} else {
hardware_memory_error();
}
}
if (code == BUS_MCEERR_AR) {
kvm_mce_inj_srar_dataload(env, paddr);
} else {
if (!kvm_mce_in_progress(env)) {
kvm_mce_inj_srao_memscrub(env, paddr);
}
}
} else
#endif
{
if (code == BUS_MCEERR_AO) {
return 0;
} else if (code == BUS_MCEERR_AR) {
hardware_memory_error();
} else {
return 1;
}
}
return 0;
}
| 1threat |
Cannot infer groovy classpath when using gradle : <p>I have a trivial Gradle project:</p>
<pre><code>apply plugin: 'groovy'
apply plugin: 'application'
mainClassName = 'HelloWorld'
</code></pre>
<p>With one Groovy source file in <code>src/main/groovy</code>:</p>
<pre><code>public class HelloWorld {
public static void main(String[] args) {
print "hello world"
}
}
</code></pre>
<p>I type <code>gradle run</code> and get the following error:</p>
<pre><code>FAILURE: Build failed with an exception.
* What went wrong:
Cannot infer Groovy class path because no Groovy Jar was found on class path: [/Users/jzwolak/files/experimenting/gradle/groovy-project/build/classes/java/main]
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED in 0s
1 actionable task: 1 executed
</code></pre>
<p>How do I configure the Groovy classpath for Gradle?</p>
<p>I have Groovy at <code>/usr/local/opt/groovy/libexec/</code></p>
| 0debug |
match_insn_m68k (bfd_vma memaddr,
disassemble_info * info,
const struct m68k_opcode * best,
struct private * priv)
{
unsigned char *save_p;
unsigned char *p;
const char *d;
bfd_byte *buffer = priv->the_buffer;
fprintf_ftype save_printer = info->fprintf_func;
void (* save_print_address) (bfd_vma, struct disassemble_info *)
= info->print_address_func;
p = buffer + 2;
for (d = best->args; *d; d += 2)
{
if (d[0] == '#')
{
if (d[1] == 'l' && p - buffer < 6)
p = buffer + 6;
else if (p - buffer < 4 && d[1] != 'C' && d[1] != '8')
p = buffer + 4;
}
if ((d[0] == 'L' || d[0] == 'l') && d[1] == 'w' && p - buffer < 4)
p = buffer + 4;
switch (d[1])
{
case '1':
case '2':
case '3':
case '7':
case '8':
case '9':
case 'i':
if (p - buffer < 4)
p = buffer + 4;
break;
case '4':
case '5':
case '6':
if (p - buffer < 6)
p = buffer + 6;
break;
default:
break;
}
}
if (p - buffer < 4 && (best->match & 0xFFFF) != 0)
p = buffer + 4;
if (p - buffer < 6
&& (best->match & 0xffff) == 0xffff
&& best->args[0] == '#'
&& best->args[1] == 'w')
{
p = buffer + 6;
FETCH_DATA (info, p);
buffer[2] = buffer[4];
buffer[3] = buffer[5];
}
FETCH_DATA (info, p);
d = best->args;
save_p = p;
info->print_address_func = dummy_print_address;
info->fprintf_func = (fprintf_ftype) dummy_printer;
for (; *d; d += 2)
{
int eaten = print_insn_arg (d, buffer, p, memaddr + (p - buffer), info);
if (eaten >= 0)
p += eaten;
else if (eaten == -1)
{
info->fprintf_func = save_printer;
info->print_address_func = save_print_address;
return 0;
}
else
{
info->fprintf_func (info->stream,
_("<internal error in opcode table: %s %s>\n"),
best->name, best->args);
info->fprintf_func = save_printer;
info->print_address_func = save_print_address;
return 2;
}
}
p = save_p;
info->fprintf_func = save_printer;
info->print_address_func = save_print_address;
d = best->args;
info->fprintf_func (info->stream, "%s", best->name);
if (*d)
info->fprintf_func (info->stream, " ");
while (*d)
{
p += print_insn_arg (d, buffer, p, memaddr + (p - buffer), info);
d += 2;
if (*d && *(d - 2) != 'I' && *d != 'k')
info->fprintf_func (info->stream, ",");
}
return p - buffer;
}
| 1threat |
How to classify so similar samples? : I'm trying to do a binary classification task on a set of sentences which are so similar to each other. My problem is I'm not sure how to deal with this problem with such similarity between samples. Here are some of my questions:
(1). Which classification technique will be more suitable in this case?
(2). Will feature selection help in this case?
(3). Could sequence classification based on recurrent neural network (LSTM) be a potential approach to follow?
Thanks,
| 0debug |
When is `new Error()` better than `Error()`? : <p>The ES5 language spec <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.11.1" rel="noreferrer">clearly states</a> that <code>Error(foo)</code> does the same thing as <code>new Error(foo)</code>.</p>
<p>But I notice that in the wild, the longer <code>new Error(foo)</code> form is much more common.</p>
<p>Is there some reason for this?</p>
<p>Is there any situation where using <code>new Error(foo)</code> is preferable to using <code>Error(foo)</code>?</p>
| 0debug |
static int parse_filename(char *filename, char **representation_id,
char **initialization_pattern, char **media_pattern) {
char *underscore_pos = NULL;
char *period_pos = NULL;
char *temp_pos = NULL;
char *filename_str = av_strdup(filename);
if (!filename_str) return AVERROR(ENOMEM);
temp_pos = av_stristr(filename_str, "_");
while (temp_pos) {
underscore_pos = temp_pos + 1;
temp_pos = av_stristr(temp_pos + 1, "_");
}
if (!underscore_pos) return -1;
period_pos = av_stristr(underscore_pos, ".");
if (!period_pos) return -1;
*(underscore_pos - 1) = 0;
if (representation_id) {
*representation_id = av_malloc(period_pos - underscore_pos + 1);
if (!(*representation_id)) return AVERROR(ENOMEM);
av_strlcpy(*representation_id, underscore_pos, period_pos - underscore_pos + 1);
}
if (initialization_pattern) {
*initialization_pattern = av_asprintf("%s_$RepresentationID$.hdr",
filename_str);
if (!(*initialization_pattern)) return AVERROR(ENOMEM);
}
if (media_pattern) {
*media_pattern = av_asprintf("%s_$RepresentationID$_$Number$.chk",
filename_str);
if (!(*media_pattern)) return AVERROR(ENOMEM);
}
av_free(filename_str);
return 0;
}
| 1threat |
static int xvid_ff_2pass_after(struct xvid_context *ref,
xvid_plg_data_t *param) {
char *log = ref->twopassbuffer;
const char *frame_types = " ipbs";
char frame_type;
if( log == NULL )
return XVID_ERR_FAIL;
if( param->type < 5 && param->type > 0 ) {
frame_type = frame_types[param->type];
} else {
return XVID_ERR_FAIL;
}
snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
"%c %d %d %d %d %d %d\n",
frame_type, param->stats.quant, param->stats.kblks, param->stats.mblks,
param->stats.ublks, param->stats.length, param->stats.hlength);
return 0;
}
| 1threat |
void vnc_display_close(DisplayState *ds)
{
VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
if (!vs)
return;
if (vs->display) {
qemu_free(vs->display);
vs->display = NULL;
}
if (vs->lsock != -1) {
qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
close(vs->lsock);
vs->lsock = -1;
}
vs->auth = VNC_AUTH_INVALID;
#ifdef CONFIG_VNC_TLS
vs->subauth = VNC_AUTH_INVALID;
vs->x509verify = 0;
#endif
}
| 1threat |
Opening & Reading Hex File in C : I have a Hex file whose contents are like below:
0x14000800
0x52100000
0xD503201F
0xD503201F
0x0030A308
0x0032D138
0x00000000
0x00000000
0x00000000
0x00000000
I need to open and read this file. Below is my code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char ch, boot_rom_golden[16];
FILE *myFile = NULL;
myFile = fopen("/prj/vlsi/tests/boot_rom_fail/src/apps_proc0/sm6140_rom.a52100000_ROM_FULL.hex", "r");
if (myFile == NULL) {
printf("Error Reading File\n");
exit(0);
}
while ((ch = fgetc(myFile)) != EOF) {
printf("%x \n", ch);
}
I have two questions:
1. My understanding is if the file does not exist in the above mentioned path, then fopen should return a NULL. Observation is : even if the file does not exist in the above path (/prj/vlsi/....) , fopen is returning some value and then it goes to while loop trying to print the content. Why is this happening? My main.c and the hex file are residing in the same path. But still I tried giving the complete path which also gave the same results (i.e. even if file does not exist it is returning a non zero pointer value)
2. When the code executes while loop, it prints "FF" indefinitely. It should be because of reason stated above.
Please help to know the issue and how to debug these kind of issues ?
Regards,
| 0debug |
Why do we await next when using koa routers? : <p>Why do we do this</p>
<pre><code>router.get('/data', async (ctx, next) => {
ctx.body = dummyjson.parse(data);
await next();
});
router.get('/data/:x', async (ctx, next) => {
const newData = dataRepeat.replace('%(x)', ctx.params.x);
ctx.body = dummyjson.parse(newData);
await next();
});
</code></pre>
<p>What is the use of <code>await next()</code></p>
<p>It would work just fine without that. Similar thing was expected with koa 1. <code>yield next</code> was added at the end of the router.</p>
| 0debug |
def Sum(N):
SumOfPrimeDivisors = [0]*(N + 1)
for i in range(2,N + 1) :
if (SumOfPrimeDivisors[i] == 0) :
for j in range(i,N + 1,i) :
SumOfPrimeDivisors[j] += i
return SumOfPrimeDivisors[N] | 0debug |
How it works a nonetype function? : In order to create an updatescore function for a game I am developing a function that returns nonetype. I was serching some information about this kind of functions in Python 3 and as far as I know what I supossed to do is try to create it without printing because is a nonetype function, but How it really means that returns a nonetype?. I tried to code this function by using other function called word_score which it seems to work properly but I got stuck in the update_score function.
Any help will be useful
Thanks in advance
previos Function:
def word_score(word):
""" (str) -> int
Return the point value the word earns.
Word length: < 3: 0 points
3-6: 1 point per character for all characters in word
7-9: 2 points per character for all characters in word
10+: 3 points per character for all characters in word
>>> word_score('DRUDGERY')
16
>>> word_score('PEN')
3
>>> word_score('GRANDMOTHER')
33
"""
if len(word) < 3:
return 0
elif len(word) in range(3,7):
return len(word)
elif len(word) in range(7, 10):
return len(word)* 2
elif len(word) >= 10:
return len(word) * 3
return word_score
current function update_score:
def update_score(player_info, word):
""" ([str, int] list, str) -> NoneType
player_info is a list with the player's name and score. Update player_info
by adding the point value word earns to the player's score.
>>> update_score(['Jonathan', 4], 'ANT')
"""
return update_score(['player_info', word_score], 'word')
Do you see something strange in this one?
| 0debug |
Pug (formerly Jade) Variables Not Working (Interpolating) Correctly Inside Anchor Href : <p>I'm playing around with Node and Express and I'm using the Pug (formerly Jade) templating engine to render my html. Everything has been working fine up until I started trying to inject variables into the <code>href</code> of my anchor links. Whats odd is that if I change my Express app <code>view engine</code> to <code>jade</code> then things start working as expected.</p>
<p>Based upon <a href="https://github.com/pugjs/pug/issues/1028" rel="noreferrer">other articles</a> I've read the issue appears to be an interpolation issue, however I can't seem to find a resource or documentation that shows how to correctly fix this issue.</p>
<p>Ex.</p>
<p>I'm pulling in data from a <code>rooms</code> json array and then using a <code>for</code> loop to cycle through each array element and output the data for each room. Using <code>jade</code> the following works. </p>
<pre><code>table.table.table-striped
thead
tr
th Name
th Id
tbody
each room in rooms
tr
td(style="width: 50px;")
a(href!="/admin/rooms/delete/#{room.id}") Delete
td #{allTitleCase(room.name)}
td #{room.id}
</code></pre>
<p>Using <code>pug</code> the above does NOT work correctly. Specifically the <code>a(href='/admin/rooms/delete/#{room.id}') Delete</code> link doesn't work correctly. Instead of injecting the room id into the link href, it literally outputs <em>#{room.id}</em> as the end part the <code>href</code> link.</p>
<p>Any ideas how to fix this in <code>pug</code>? </p>
<p>Note that I've tried all of the following using <code>pug</code> but none of these options have worked.</p>
<ul>
<li><code>a(href="/admin/rooms/delete/#{room.id}") Delete</code></li>
<li><code>a(href!="/admin/rooms/delete/#{room.id}") Delete</code></li>
</ul>
| 0debug |
Execute .sql file in python : Hello everyone I have this sql file
Student.sql
Select * from student where age > 18;
Delet student_ name , studen_id if age > 18 ;
Commit;
Using cx_oracle pip
Any help | 0debug |
void spapr_events_init(sPAPREnvironment *spapr)
{
spapr->epow_irq = xics_alloc(spapr->icp, 0, 0, false);
spapr->epow_notifier.notify = spapr_powerdown_req;
qemu_register_powerdown_notifier(&spapr->epow_notifier);
spapr_rtas_register(RTAS_CHECK_EXCEPTION, "check-exception",
check_exception);
}
| 1threat |
For Each Loop in a Set Java : so my question is as follows.
Lets say I have a HashTable/HashMap with the following {4:1, 3:56, 4:3, 4:5, 9:89, etc.}
I then make the keys of this Map into a keyset by calling map.keySet().
How can I loop through that set to only output the values associated with the key of 4? I want the output to be 1,3,5, therefore I only want the values associated with the key 4? Is this possible, and if so how. Thanks!! | 0debug |
Webpage scrolls when keyboard pops up : <p>I've noticed that when I am on my ipad or iphone and I open up the chatbox on my site and start to type, the webpage behind the chatbox will scroll back to the top of the site and not stay where I scrolled down. My website is www.leormanelis.com. Does not seem to happen on android devices. Does anyone know a fix? </p>
<p>Video - <a href="https://screencast.com/t/uiWdL39Qg6" rel="nofollow noreferrer">https://screencast.com/t/uiWdL39Qg6</a></p>
| 0debug |
int kvm_s390_set_mem_limit(KVMState *s, uint64_t new_limit, uint64_t *hw_limit)
{
int rc;
struct kvm_device_attr attr = {
.group = KVM_S390_VM_MEM_CTRL,
.attr = KVM_S390_VM_MEM_LIMIT_SIZE,
.addr = (uint64_t) &new_limit,
};
if (!kvm_s390_supports_mem_limit(s)) {
return 0;
}
rc = kvm_s390_query_mem_limit(s, hw_limit);
if (rc) {
return rc;
} else if (*hw_limit < new_limit) {
return -E2BIG;
}
return kvm_vm_ioctl(s, KVM_SET_DEVICE_ATTR, &attr);
}
| 1threat |
What is the difference between NestedScrollView and CustomScrollView? : <p>I having hard to understand the difference between NestedScrollView and CustomScrollView?</p>
| 0debug |
QuickSort in C++ array.size() error : <p>I'm writing some code in C++ to do the quick sort algorithm to sort an array of integers. I have my complete code here:</p>
<pre><code>void swap(int A[], int x, int y)
{
int tmp;
tmp=A[x];
A[x]=A[y];
A[y]=tmp;
}
int partition(int A[], int start, int stop)
{
int big=start;
int pivot=A[stop];
for(int i=start; i<stop; i++)
{
if(A[i]<=pivot)
{
swap(A, i, big);
big++;
}
}
swap(A, big, stop);
return big;
}
void quick_Sort_Helper(int A[], int start, int stop)
{
//base cases
if(stop<=start)
{return;}
if(start+1==stop)
{
if(A[start]>A[stop])
{swap(A, start, stop);}
return;
}
//recursive cases
int pivot=partition(A,start, stop);
quick_Sort_Helper(A,start, pivot-1);
quick_Sort_Helper(A, pivot, stop);
}
void quick_Sort(int A[])
{
quick_Sort_Helper(A,0, A.size()-1);
}
</code></pre>
<p>I get an error when compiling the program on the line where I call A.size(). The error reads as follows:</p>
<p>error: request for member ‘size’ in ‘A’, which is of non-class type ‘int*’</p>
<p>I don't understand because the size() function of an array is supposed to return an integer with the length/ number of elements in the array.</p>
| 0debug |
retreiving URL from MySQL database : Okay, So I have a database which holds the following values; Restaurant Name, Address, Town, County, Postcode, Tel, Email, Website and Rating. I have a search box that allows the user to search via Town, County or Postcode and then echo's out those relevant using the attached code.
Problem is, my Website URL's when clicked just reload the same page the info is displayed on and not the actual website of the restaurants? I know this is going to be something silly!!!!
Thanks
<!-- language: lang-html -->
<td>
<?php echo $results[ 'RestaurantName']?>
</td>
<br>
<td>
<?php echo $results[ 'AddressLine1']?>
</td>
<br>
<td>
<?php echo $results[ 'AddressLine2']?>
</td>
<br>
<td>
<?php echo $results[ 'Town']?>
</td>
<br>
<td>
<?php echo $results[ 'County']?>
</td>
<br>
<td>
<?php echo $results[ 'Postcode']?>
</td>
<br>
<td>
<?php echo $results[ 'Telephone']?>
</td>
<br>
<td>
<?php echo $results[ 'Email']?>
</td>
<br>
<td>
<a href>
<?php echo $results[ 'Website']?>
</a>
</td>
<br>
<td>
<?php echo $results[ 'Rating']?>
</td>
<br>
<!-- end snippet -->
| 0debug |
Formula for deleting vectors? : Basically, I have a vector of a struct. I'm making the game Monopoly and I have a vector of a playerStruct. I have an option for a player to leave the game. However, I don't know how to delete any player as the vector becomes smaller and smaller. For example I have 3 players
Players 0,1,2
And I use the erase function,
erase(vect.begin()+turnNumber;
I first erase player 0 which is just erase(vect.begin()+0) and erases the first element. However, if I try to erase player 1 (vect.begin()+1) I end up erasing player 2 as the vector has shrunk to a size of 2.
TDLR: **How do I erase a player at any point while the vector decreases? I can't seem to think of a formula erase(vect.begin()+(a number)) to be able to erase any player from the game without erasing another player that isn't meant to be erased.**
Thank you. | 0debug |
Polymorphism inside monads : <p>I'm trying to pull a value out of a monad, but keep the <em>value</em>, which doesn't depend on the monad, polymorphic. Specifically:</p>
<pre><code>foo :: (Monad mon, Ring a) => mon a
foo = return 3
main :: IO ()
main = do
x <- foo
print (x :: Double)
print (x :: Int)
</code></pre>
<p>The point is that the monadic portion of the computation is expensive to compute, so I only want to do it once, while keeping the value in the monad polymorphic. All of my attempts so far:</p>
<ol>
<li>giving <code>x</code> the signature <code>forall a. (Ring a) => a</code>)</li>
<li>giving <code>foo :: (Monad mon) => mon (forall a . (Ring a) => a)</code> </li>
<li>enabling <code>-XNoMonomorphismRestriction</code> and <code>NoMonoLocalBins</code> </li>
</ol>
<p>have either not worked or given errors about impredicative polymorphism, which I'm not willing to use. Is there some way to pull a polymorphic value out of a monad without impredicative polymorphism (or alternatively: is there a safe way to use impredicative polymorphism in GHC)?</p>
| 0debug |
static int pci_device_hot_remove(Monitor *mon, const char *pci_addr)
{
PCIDevice *d;
int dom, bus;
unsigned slot;
Error *local_err = NULL;
if (pci_read_devaddr(mon, pci_addr, &dom, &bus, &slot)) {
return -1;
}
d = pci_find_device(pci_find_root_bus(dom), bus, PCI_DEVFN(slot, 0));
if (!d) {
monitor_printf(mon, "slot %d empty\n", slot);
return -1;
}
qdev_unplug(&d->qdev, &local_err);
if (error_is_set(&local_err)) {
monitor_printf(mon, "%s\n", error_get_pretty(local_err));
error_free(local_err);
return -1;
}
return 0;
}
| 1threat |
How to reverse an array without a loop or creating new array : <pre><code>class ReverseArrayElements1
{
public static void main ( String[] args )
{
int[] values = {10, 20, 30, 40};
int temp;
System.out.println( "Original Array: " + values[0] + "\n" + values[1] +
"\n" + values[2] + "\n" + values[3] );
// reverse the order of the numbers in the array
System.out.println( "Reversed Array: " + values[0] + "\n" + values[1] + "\n"
+ values[2] + "\n" + values[3] );
}
}
</code></pre>
<p>Task
I need to complete the program so that the numbers in the array appear in reversed order. This does not mean that I can just need to display the elements in reverse order; I will actually move the last element in the array into the the first element of the array, and so on. I can't use a loop or create a new array. </p>
<p>The output should be </p>
<pre><code>Original Array: 10 20 30 40
Reversed Array: 40 30 20 10
</code></pre>
| 0debug |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.