problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
Composer update `The following exception is caused by a lack of memory and not having swap configured` error in vagrant : <p>I got php5.5 with composer installed in a vagrant VirtualBox environment. </p>
<p>When I try any composer's commands the following error appears randomly:</p>
<p><code>The following exception is caused by a lack of memory and not having swap configured</code></p>
<p>How can I get around this ?</p>
| 0debug |
Delete item from the table if it's date is passed : <p>Hey I have a table that every row contains several data and one of them is the date , I am trying to write a code in php that will run on the table and delete every row that its date have been expired for example if the date today is 06/01/2017 than every item that its date is smaller than today should be deleted, the thing is I don't really have an idea on how to write this function so if someone can send me a tutorial or example of how should I do it that will be great.</p>
| 0debug |
static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
{
cpu_dump_statistics(mon_get_cpu(), (FILE *)mon, &monitor_fprintf, 0);
}
| 1threat |
Return value of cell if adjacent cell contains specific text? : I have 2 columns in Sheet 1 (named Projects), "Projects" in column A and "Status" in column B. The number of rows is dynamic.
In Sheet 2, I want to extract the projects that meet a certain string criteria and populate a table. For example, if the Status is "Operating", take the project name in column A for that row and put it in a table.
I tried =IF(Projects!B1:B="Operating",Projects!A1:A,"") but it returns the names of the projects in the same row position as in Sheet 1. So if there is a 2 row gap in Sheet 1 between two operating projects, it keeps the 2 row gap in Sheet 2.
How do I get rid of the gaps? | 0debug |
int page_unprotect(target_ulong address, uintptr_t pc)
{
unsigned int prot;
PageDesc *p;
target_ulong host_start, host_end, addr;
mmap_lock();
p = page_find(address >> TARGET_PAGE_BITS);
if (!p) {
mmap_unlock();
return 0;
}
if ((p->flags & PAGE_WRITE_ORG) && !(p->flags & PAGE_WRITE)) {
host_start = address & qemu_host_page_mask;
host_end = host_start + qemu_host_page_size;
prot = 0;
for (addr = host_start ; addr < host_end ; addr += TARGET_PAGE_SIZE) {
p = page_find(addr >> TARGET_PAGE_BITS);
p->flags |= PAGE_WRITE;
prot |= p->flags;
if (tb_invalidate_phys_page(addr, pc)) {
mmap_unlock();
return 2;
}
#ifdef DEBUG_TB_CHECK
tb_invalidate_check(addr);
#endif
}
mprotect((void *)g2h(host_start), qemu_host_page_size,
prot & PAGE_BITS);
mmap_unlock();
return 1;
}
mmap_unlock();
return 0;
}
| 1threat |
void slirp_input(const uint8_t *pkt, int pkt_len)
{
struct mbuf *m;
int proto;
if (pkt_len < ETH_HLEN)
return;
proto = ntohs(*(uint16_t *)(pkt + 12));
switch(proto) {
case ETH_P_ARP:
arp_input(pkt, pkt_len);
break;
case ETH_P_IP:
m = m_get();
if (!m)
return;
m->m_len = pkt_len + 2;
memcpy(m->m_data + 2, pkt, pkt_len);
m->m_data += 2 + ETH_HLEN;
m->m_len -= 2 + ETH_HLEN;
ip_input(m);
break;
default:
break;
| 1threat |
How to make an array of buttons which change text upon clicking using Tkinter : <p>I'm trying to implement a simple GUI for the game of Tic Tac Toe using Tkinter. As a first step, I'm trying to make an array of buttons which change from being unlabeled to having the "X" label when clicked. I've tried the following:</p>
<pre><code>import Tkinter as tk
class ChangeButton:
def __init__(self, master, grid=np.diag(np.ones(3))):
frame = tk.Frame(master)
frame.pack()
self.grid = grid
self.buttons = [[tk.Button()]*3]*3
for i in range(3):
for j in range(3):
self.buttons[i][j] = tk.Button(frame, text="", command=self.toggle_text(self.buttons[i][j]))
self.buttons[i][j].grid(row=i, column=j)
def toggle_text(self, button):
if button["text"] == "":
button["text"] = "X"
root = tk.Tk()
root.title("Tic Tac Toe")
app = ChangeButton(root)
root.mainloop()
</code></pre>
<p>However, the resulting window looks like this:</p>
<p><a href="https://i.stack.imgur.com/Vl6N5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vl6N5.png" alt="enter image description here"></a></p>
<p>and the buttons don't change when clicked. Any ideas why this does not work?</p>
| 0debug |
JQuery, Button inside a form is not accessible : > This question is asked [here][1].
I'm trying to trigger the click event of a button inside a form using JQuery [Lib][2].
HTML:
<form class="form-inline" action="">
<button type="button" class="btn mr-3 btn-link transparent switchLang">${{index.keys.lng}}$</button>
<button type="button" class="btn mr-3 btn-outline-light">${{index.keys.login}}$</button>
<button type="button" class="btn btn-primary">${{index.keys.getStarted}}$</button>
</form>
JS:
$(".switchLang").on("click",function (e) {
console.log("Clicked!")
});
**The function above is not invoked!**
After research, I tried many solution but nothing's work. Like adding `e.preventDefault();` inside the function also remove `.click` and replaced with `.on` and so on.
But nothing works!
Thanks.
[1]: https://stackoverflow.com/questions/16192190/jquery-click-event-not-triggered-on-button-inside-form
[2]: https://jquery.com/ | 0debug |
Slow sass-loader Build Times with Webpack : <h1>Summary</h1>
<p>When we switched to using Webpack for handling our SASS files, we noticed that our build times in some cases became really slow. After measuring the performance of different parts of the build using the <a href="https://www.npmjs.com/package/speed-measure-webpack-plugin" rel="noreferrer">SpeedMeasurePlugin</a>, it seems that <a href="https://github.com/webpack-contrib/sass-loader" rel="noreferrer">sass-loader</a> is the culprit…it can easily take 10s to build (it used to take 20s before we made some fixes), which is longer than we’d like.</p>
<p>I’m curious if people have additional strategies for optimizing building Sass assets that I didn’t cover. I’ve gone through a fair number of them at this point (multiple times for some of them), and still can’t seem to get the build times low enough. In terms of goals, currently a large rebuild (such as making a change for a component used in many files), can easily take 10-12 seconds, I’m hoping to get it down closer to 5s if possible.</p>
<h2>Solutions Tried</h2>
<p>We tried a number of different solutions, some worked, others did not help much. </p>
<ul>
<li><a href="https://github.com/mzgoddard/hard-source-webpack-plugin" rel="noreferrer">HardSourcePlugin</a> - This one worked reasonably well. Depending on the caching for that build, it was able to reduce build times by several seconds.</li>
<li>Removing duplicated imports (like importing the same ‘variables.sass’ file into multiple places) - This also reduced build time by a few seconds</li>
<li>Changing our mix of SASS and SCSS to just SCSS - I’m not sure why this helped, but it did seem to shave a bit off our build times. Maybe because everything was the same file type, it was easier to compile? (It’s possible that something else was happening here to confound the results, but it did seem to consistently help).</li>
<li>Replace sass-loader with <a href="https://github.com/yibn2008/fast-sass-loader" rel="noreferrer">fast-sass-loader</a> - Many people recommended this, but when I got it to work, it didn’t seem to change the build time at all. I’m not sure why…maybe there was a configuration issue.</li>
<li>Utilizing <a href="https://github.com/webpack-contrib/cache-loader" rel="noreferrer">cache-loader</a> - This also didn’t seem to have any improvement.</li>
<li>Disabled source maps for Sass - This seems to have had a big effect, reducing the build times in half (from when the change was applied)</li>
<li>Tried using <code>includePaths</code> for SASS loaded from node_modules - This was suggested on a <a href="https://github.com/webpack-contrib/sass-loader/issues/296" rel="noreferrer">git issue</a> I found, where sass-loader had issues with something they called ’custom importers’. My understanding was that by using includePaths, SASS was able to rely on those provided absolute paths, instead of using an inefficient algorithm for resolving paths to places like node_modules</li>
</ul>
<p>From some brief stats, we appear to have about 16k lines of SASS code spread across 150 SASS files. Some have a fair amount of code, while others have less, with a simple average of the LOC across these files of about 107 LOC / file.</p>
<p>Below is the configuration that is being used. The application is a Rails application, and so much of the Webpack configuration is handled through the Webpacker gem.</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>{
"mode": "production",
"output": {
"filename": "js/[name].js",
"chunkFilename": "js/[name].js",
"hotUpdateChunkFilename": "js/[id]-[hash].hot-update.js",
"path": "myApp/public/packs",
"publicPath": "/packs/"
},
"resolve": {
"extensions": [".mjs", ".js", ".sass", ".scss", ".css", ".module.sass", ".module.scss", ".module.css", ".png", ".svg", ".gif", ".jpeg", ".jpg"],
"plugins": [{
"topLevelLoader": {}
}],
"modules": ["myApp/app/assets/javascript", "myApp/app/assets/css", "node_modules"]
},
"resolveLoader": {
"modules": ["node_modules"],
"plugins": [{}]
},
"node": {
"dgram": "empty",
"fs": "empty",
"net": "empty",
"tls": "empty",
"child_process": "empty"
},
"devtool": "source-map",
"stats": "normal",
"bail": true,
"optimization": {
"minimizer": [{
"options": {
"test": {},
"extractComments": false,
"sourceMap": true,
"cache": true,
"parallel": true,
"terserOptions": {
"output": {
"ecma": 5,
"comments": false,
"ascii_only": true
},
"parse": {
"ecma": 8
},
"compress": {
"ecma": 5,
"warnings": false,
"comparisons": false
},
"mangle": {
"safari10": true
}
}
}
}],
"splitChunks": {
"chunks": "all",
"name": false
},
"runtimeChunk": true
},
"externals": {
"moment": "moment"
},
"entry": {
"entry1": "myApp/app/assets/javascript/packs/entry1.js",
"entry2": "myApp/app/assets/javascript/packs/entry2.js",
"entry3": "myApp/app/assets/javascript/packs/entry3.js",
"entry4": "myApp/app/assets/javascript/packs/entry4.js",
"entry5": "myApp/app/assets/javascript/packs/entry5.js",
"entry6": "myApp/app/assets/javascript/packs/entry6.js",
"entry7": "myApp/app/assets/javascript/packs/entry7.js",
"entry8": "myApp/app/assets/javascript/packs/entry8.js",
"landing": "myApp/app/assets/javascript/packs/landing.js",
"entry9": "myApp/app/assets/javascript/packs/entry9.js",
"entry10": "myApp/app/assets/javascript/packs/entry10.js",
"entry11": "myApp/app/assets/javascript/packs/entry11.js",
"entry12": "myApp/app/assets/javascript/packs/entry12.js",
"entry13": "myApp/app/assets/javascript/packs/entry13.js",
"entry14": "myApp/app/assets/javascript/packs/entry14.js",
"entry15": "myApp/app/assets/javascript/packs/entry15.js"
},
"module": {
"strictExportPresence": true,
"rules": [{
"parser": {
"requireEnsure": false
}
}, {
"test": {},
"use": [{
"loader": "file-loader",
"options": {
"context": "app/assets/javascript"
}
}]
}, {
"test": {},
"use": ["myApp/node_modules/mini-css-extract-plugin/dist/loader.js", {
"loader": "css-loader",
"options": {
"sourceMap": true,
"importLoaders": 2,
"localIdentName": "[name]__[local]___[hash:base64:5]",
"modules": false
}
}, {
"loader": "postcss-loader",
"options": {
"config": {
"path": "myApp"
},
"sourceMap": true
}
}],
"sideEffects": true,
"exclude": {}
}, {
"test": {},
"use": ["myApp/node_modules/mini-css-extract-plugin/dist/loader.js", {
"loader": "css-loader",
"options": {
"sourceMap": true,
"importLoaders": 2,
"localIdentName": "[name]__[local]___[hash:base64:5]",
"modules": false
}
}, {
"loader": "postcss-loader",
"options": {
"config": {
"path": "myApp"
},
"sourceMap": false,
"plugins": [null, null]
}
}, {
"loader": "sass-loader",
"options": {
"sourceMap": false,
"sourceComments": true
}
}],
"sideEffects": true,
"exclude": {}
}, {
"test": {},
"use": ["myApp/node_modules/mini-css-extract-plugin/dist/loader.js", {
"loader": "css-loader",
"options": {
"sourceMap": true,
"importLoaders": 2,
"localIdentName": "[name]__[local]___[hash:base64:5]",
"modules": true
}
}, {
"loader": "postcss-loader",
"options": {
"config": {
"path": "myApp"
},
"sourceMap": true
}
}],
"sideEffects": false,
"include": {}
}, {
"test": {},
"use": ["myApp/node_modules/mini-css-extract-plugin/dist/loader.js", {
"loader": "css-loader",
"options": {
"sourceMap": true,
"importLoaders": 2,
"localIdentName": "[name]__[local]___[hash:base64:5]",
"modules": true
}
}, {
"loader": "postcss-loader",
"options": {
"config": {
"path": "myApp"
},
"sourceMap": true
}
}, {
"loader": "sass-loader",
"options": {
"sourceMap": true
}
}],
"sideEffects": false,
"include": {}
}, {
"test": {},
"include": {},
"exclude": {},
"use": [{
"loader": "babel-loader",
"options": {
"babelrc": false,
"presets": [
["@babel/preset-env", {
"modules": false
}]
],
"cacheDirectory": "tmp/cache/webpacker/babel-loader-node-modules",
"cacheCompression": true,
"compact": false,
"sourceMaps": false
}
}]
}, {
"test": {},
"include": ["myApp/app/assets/javascript", "myApp/app/assets/css"],
"exclude": {},
"use": [{
"loader": "babel-loader",
"options": {
"cacheDirectory": "tmp/cache/webpacker/babel-loader-node-modules",
"cacheCompression": true,
"compact": true
}
}]
}, {
"test": "myApp/node_modules/jquery/dist/jquery.js",
"use": [{
"loader": "expose-loader",
"options": "jQuery"
}, {
"loader": "expose-loader",
"options": "$"
}]
}, {
"test": "myApp/node_modules/popper.js/dist/umd/popper.js",
"use": [{
"loader": "expose-loader",
"options": "Popper"
}]
}, {
"test": "myApp/node_modules/scroll-depth/jquery.scrolldepth.js",
"use": [{
"loader": "expose-loader",
"options": "scrollDepth"
}]
}]
},
"plugins": [{
"environment_variables_plugin": "values don't really matter in this case I think"
}, {
"options": {},
"pathCache": {},
"fsOperations": 0,
"primed": false
}, {
"options": {
"filename": "css/[name]-[contenthash:8].css",
"chunkFilename": "css/[name]-[contenthash:8].chunk.css"
}
}, {}, {
"options": {
"test": {},
"cache": true,
"compressionOptions": {
"level": 9
},
"filename": "[path].gz[query]",
"threshold": 0,
"minRatio": 0.8,
"deleteOriginalAssets": false
}
}, {
"pluginDescriptor": {
"name": "OptimizeCssAssetsWebpackPlugin"
},
"options": {
"assetProcessors": [{
"phase": "compilation.optimize-chunk-assets",
"regExp": {}
}],
"assetNameRegExp": {},
"cssProcessorOptions": {},
"cssProcessorPluginOptions": {}
},
"phaseAssetProcessors": {
"compilation.optimize-chunk-assets": [{
"phase": "compilation.optimize-chunk-assets",
"regExp": {}
}],
"compilation.optimize-assets": [],
"emit": []
},
"deleteAssetsMap": {}
}, {
"definitions": {
"$": "jquery",
"jQuery": "jquery",
"jquery": "jquery",
"window.$": "jquery",
"window.jQuery": "jquery",
"window.jquery": "jquery",
"Popper": ["popper.js", "default"]
}
}, {
"definitions": {
"process.env": {
"MY_DEFINED_ENV_VARS": "my defined env var values"
}
}
}, {
"options": {}
}]
}</code></pre>
</div>
</div>
</p>
| 0debug |
why to use abstract class as type? : <p>I have fair understanding of interface/abstract class/class however just trying to understand something else. Look at below code:</p>
<pre><code>namespace AbstractClassExample
{
class Program
{
static void Main(string[] args)
{
BaseEmployee fullTimeEmployee = new FullTimeEmployee();
BaseEmployee contractEmployee = new ContractEmployee();
}
}
public abstract class BaseEmployee
{
public string EmployeeID { get; set; }
public string EmployeeName { get; set; }
public string EmployeeAddress { get; set; }
public abstract double CalculateSalary(int hoursWorked);
}
public class FullTimeEmployee : BaseEmployee
{
public override double CalculateSalary(int hoursWorked)
{
//do something
}
}
public class ContractEmployee : BaseEmployee
{
public override double CalculateSalary(int hoursWorked)
{
//do something
}
}
}
</code></pre>
<p>however I fail to get below lines (1st approach): </p>
<pre><code>BaseEmployee fullTimeEmployee = new FullTimeEmployee();
BaseEmployee contractEmployee = new ContractEmployee();
</code></pre>
<p>Why not written this way instead (2nd approach):</p>
<pre><code>FullTimeEmployee fullTimeEmployee = new FullTimeEmployee();
</code></pre>
<p>it is completely okay to use 2nd approach it will work coz of relation. How would any developer in the work know if above abstract class is in DLL. Probably, will use 1st approach when you've code with you or sort of documentation. Isn't it?</p>
<p>Similar example would also be valid for interface declaration. like:</p>
<pre><code>interface IPointy {
void MyMethod();
}
class Pencil : IPointy {
void MyMethod() {
}
void MyOtherMethod() {
}
}
IPointy itPt = new Pencil();
</code></pre>
<p>Isn't 1st approach making it complex? What's good practice? Any good practice vs bad practice with 1st & 2nd? </p>
| 0debug |
When to use "Do" function in dplyr : <p>I've learned that <code>Do</code> function is used when you want to apply a function to each group.</p>
<p>for example, if I want to pull top 2 rows from "A", "C", and "I" categories of variable <code>Index</code>, following syntax can be used.</p>
<pre><code>t <- mydata %>% filter(Index %in% c("A", "C", "I")) %>% group_by(Index) %>% do(head(.,2))
</code></pre>
<p>I understand that after grouping by index, <code>do</code> function is used to compute head(.,2) for each group.</p>
<p>However, on some occasions, <code>do</code> is not used at all. For example, To compute mean of variable <code>Y2014</code> grouped by variable <code>Index</code>, I thought that following code should be used.</p>
<pre><code>t <- mydata %>% group_by(Index) %>% do(summarise(Mean_2014 = mean(Y2014)))
</code></pre>
<p>however, above syntax returns error</p>
<pre><code>Error in mean(Y2014) : object 'Y2014' not found
</code></pre>
<p>But if I remove <code>do</code> from the syntax, it returns what I exactly wanted.</p>
<pre><code>t <- mydata %>% group_by(Index) %>% summarise(Mean_2014 = mean(Y2014))
</code></pre>
<p>I'm really confused about usage of <code>do</code> function in dplyr. It seems inconsistent to me. When should I use and not use <code>do</code> function? Why should I use <code>do</code> in the first case and not in the second case?</p>
| 0debug |
how to add read more in a page by using HTML,javascript : <p>I am needing to create a show more/less text function, but with just JavaScript and HTML.. I can't use any additional libraries such as jQuery and it can't be done with CSS.</p>
| 0debug |
static av_cold int cfhd_decode_init(AVCodecContext *avctx)
{
CFHDContext *s = avctx->priv_data;
avctx->bits_per_raw_sample = 10;
s->avctx = avctx;
avctx->width = 0;
avctx->height = 0;
return ff_cfhd_init_vlcs(s);
}
| 1threat |
static int RENAME(resample_common)(ResampleContext *c,
void *dest, const void *source,
int n, int update_ctx)
{
DELEM *dst = dest;
const DELEM *src = source;
int dst_index;
int index= c->index;
int frac= c->frac;
int sample_index = 0;
while (index >= c->phase_count) {
sample_index++;
index -= c->phase_count;
}
for (dst_index = 0; dst_index < n; dst_index++) {
FELEM *filter = ((FELEM *) c->filter_bank) + c->filter_alloc * index;
FELEM2 val= FOFFSET;
int i;
for (i = 0; i < c->filter_length; i++) {
val += src[sample_index + i] * (FELEM2)filter[i];
}
OUT(dst[dst_index], val);
frac += c->dst_incr_mod;
index += c->dst_incr_div;
if (frac >= c->src_incr) {
frac -= c->src_incr;
index++;
}
while (index >= c->phase_count) {
sample_index++;
index -= c->phase_count;
}
}
if(update_ctx){
c->frac= frac;
c->index= index;
}
return sample_index;
}
| 1threat |
static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
if ((uint64_t)atom.size > (1<<30))
return AVERROR_INVALIDDATA;
if (atom.size >= 10) {
unsigned size = avio_rb32(pb);
unsigned type = avio_rl32(pb);
avio_seek(pb, -8, SEEK_CUR);
if (type == MKTAG('f','i','e','l') && size == atom.size)
return mov_read_default(c, pb, atom);
}
av_free(st->codec->extradata);
st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
if (!st->codec->extradata)
return AVERROR(ENOMEM);
st->codec->extradata_size = atom.size;
avio_read(pb, st->codec->extradata, atom.size);
return 0;
}
| 1threat |
envlist_free(envlist_t *envlist)
{
struct envlist_entry *entry;
assert(envlist != NULL);
while (envlist->el_entries.lh_first != NULL) {
entry = envlist->el_entries.lh_first;
QLIST_REMOVE(entry, ev_link);
free((char *)entry->ev_var);
free(entry);
}
free(envlist);
}
| 1threat |
Kubernetes Deployments vs StatefulSets : <p>I've been doing a lot of digging on Kubernetes, and I'm liking what I see a lot! One thing I've been unable to get a clear idea about is what the exact distinctions are between the Deployment and StatefulSet resources and in which scenarios would you use each (or is one generally preferred over the other).</p>
<p>Any experiences people can share would be awesome!! </p>
| 0debug |
BETTER query and faster : <p>i would like to ask between these two query, what query is faster? if the data is 20k to 100k..</p>
<pre><code>SELECT SUM(price * quantity) as sales
FROM
(
SELECT price, quantity, date
FROM orderline
UNION ALL
SELECT price, quantity, date
FROM creditorderline
)
WHERE date BETWEEN '2010-01-01' AND '2016-01-01'
</code></pre>
<p>OR</p>
<pre><code>SELECT SUM(price * quantity) as sales
FROM
(
SELECT price, quantity, date
FROM orderline
WHERE date BETWEEN '2010-01-01' AND '2016-01-01'
UNION ALL
SELECT price, quantity, date
FROM creditorderline
WHERE date BETWEEN '2010-01-01' AND '2016-01-01'
)
</code></pre>
| 0debug |
Can't read POST values in PHP : <p>I have a problem and just can't figure out what's the issue:
In my php code I can't read any of the values included in the post request. </p>
<p>Even if I reduce the PHP-code to just reading the value, there comes a 500 error as response.</p>
<p>I inspected the POST-header: all the data is sent, so you should have access in php.</p>
<p>Here's the code:</p>
<pre><code>$('#contactForm').submit(function (e) {
e.preventDefault();
var $form = $(this);
// check if the input is valid
if (!$form.valid()) return false;
$.ajax({
type: 'POST',
url: 'contact.php',
data: $('#contactForm').serialize(),
success: function (response) {
$(".formSuccess").show();
$(".formError").hide();
},
error: function (response) {
$(".formSuccess").hide();
$(".formError").show();
}
});
</code></pre>
<p>});</p>
<pre><code>contact.php
<?php
$empfaenger = "info@heitech.co.at";
$betreff = "Formularnachricht";
$text = "Formularnachricht: \n\n";
if(isset($_POST["name1"]))
{
$text .= "Name: ".&_POST["name1"];
}
if(isset($_POST["email1"]))
{
$text .= "\n\nEmail: ".&_POST["email1"];
}
if(isset($_POST["message1"]))
{
$text .= "\n\nNachricht: ".&_POST["message1"];
}
//$text = wordwrap($text, 70);
mail($empfaenger, $betreff, $text);
?>
</code></pre>
<p>Thanks for your help! :)</p>
| 0debug |
static void coroutine_fn bdrv_rw_co_entry(void *opaque)
{
RwCo *rwco = opaque;
if (!rwco->is_write) {
rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset,
rwco->qiov->size, rwco->qiov,
rwco->flags);
} else {
rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset,
rwco->qiov->size, rwco->qiov,
rwco->flags);
}
}
| 1threat |
The shortest path int a directed graph that through some specified vertexs : There is a weighted directed graph.How to get the shortest path to the directed graph that through some specified vertexs. | 0debug |
extraction of data from PDF converted XBRL files : <p>I have some XBRL files converted into pdf. Now I want to develop a project that would automatically extract all the data from these files. The project would be developed in JAVA. I am unable to get any lead. Any suggestions regarding how to start the project would be very much appreciated as there is very limited information over the internet regarding this.</p>
| 0debug |
Find a comma saperated word from string in javascript : <p>I am trying to find word from a string
I have a string like</p>
<pre><code> var str="Roof Garden, Garden, Hall, Children Room, Guest Room, Roof_Garden";
</code></pre>
<p>Now i want to find "Garden" in this string
So i want to get only Garden not " Roof Garden" or Roof_Garden
Please suggest me any best way to find the exact word</p>
| 0debug |
How to install only "devDependencies" using npm : <p>I am trying to install ONLY the "devDependencies" listed in my package.json file. But none of the following commands work as I expect. All of the following commands install the production dependencies also which I do not want.</p>
<pre><code>npm install --dev
npm install --only=dev
npm install --only-dev
</code></pre>
<p>I cannot think of any more ways of telling the npm to install the devDependencies alone. :( </p>
| 0debug |
Uivewcontroller login to tab view controller segue : I am trying to present a certain tab on a tab view controller from a view controller when the user clicks login and is logged in but only iif they are logged in so this is why I am doing this programically. Would I make a segue with an identity or use something like self.present? | 0debug |
static void qpi_mem_writel(void *opaque, target_phys_addr_t addr, uint32_t val)
{
CPUState *env;
env = cpu_single_env;
if (!env)
return;
env->eflags = (env->eflags & ~(IF_MASK | IOPL_MASK)) |
(val & (IF_MASK | IOPL_MASK));
}
| 1threat |
static void test_acpi_asl(test_data *data)
{
int i;
AcpiSdtTable *sdt, *exp_sdt;
test_data exp_data;
memset(&exp_data, 0, sizeof(exp_data));
exp_data.ssdt_tables = load_expected_aml(data);
dump_aml_files(data);
for (i = 0; i < data->ssdt_tables->len; ++i) {
GString *asl, *exp_asl;
sdt = &g_array_index(data->ssdt_tables, AcpiSdtTable, i);
exp_sdt = &g_array_index(exp_data.ssdt_tables, AcpiSdtTable, i);
load_asl(data->ssdt_tables, sdt);
asl = normalize_asl(sdt->asl);
load_asl(exp_data.ssdt_tables, exp_sdt);
exp_asl = normalize_asl(exp_sdt->asl);
g_assert(!g_strcmp0(asl->str, exp_asl->str));
g_string_free(asl, true);
g_string_free(exp_asl, true);
}
free_test_data(&exp_data);
}
| 1threat |
this code is not answering the equations correctly : here I use this code to test if the output will be correct when it is variables so I put this two lines :
double t = (0.8*0.8*(10^5)*599*(10^-6)*1388.888889)/(287*(25+273)*14.7*3*(10^-3)*4);
Serial.println(t);
here the output on the serial port is 4.03 but it should be 3.5
how could I solve this problem please
I'm using arduino UNO and this was arduino code
| 0debug |
int64_t qmp_guest_fsfreeze_freeze(Error **err)
{
error_set(err, QERR_UNSUPPORTED);
return 0;
}
| 1threat |
(C++) How to use GetPixel() of x y on screen : <p>Could someone make some code that gets the pixel of an x y coord on screen and explain how the code works. I have read other examples but I dont know what all the functions and code do. Thanks.</p>
| 0debug |
Visitor *visitor_input_test_init(TestInputVisitorData *data,
const char *json_string, ...)
{
Visitor *v;
va_list ap;
va_start(ap, json_string);
v = visitor_input_test_init_internal(data, json_string, &ap);
va_end(ap);
return v;
}
| 1threat |
static void virtio_rng_process(VirtIORNG *vrng)
{
size_t size;
if (!is_guest_ready(vrng)) {
return;
}
size = get_request_size(vrng->vq);
size = MIN(vrng->quota_remaining, size);
if (size) {
rng_backend_request_entropy(vrng->rng, size, chr_read, vrng);
}
}
| 1threat |
How can we change the width/padding of a Flutter DropdownMenuItem in a Dropdown? : <p>In Flutter, I can build a Dropdown with DropdownMenuItems, like this:
<a href="https://i.stack.imgur.com/GnwfL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GnwfL.png" alt="enter image description here"></a></p>
<p>The DropdownMenuItems I add are always wider than the dropdown itself:</p>
<p><a href="https://i.stack.imgur.com/D5LI1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/D5LI1.png" alt="enter image description here"></a></p>
<p>How do you adjust the width of the DropdownMenuItem, or remove the extra horizontal padding?</p>
<p>My DropdownMenuItem widget looks like this:</p>
<pre><code>DropdownMenuItem(
value: unit.name,
child: Text('hey'),
);
</code></pre>
<p>while my Dropdown widget looks like this:</p>
<pre><code>return Container(
width: 300.0,
child: DropdownButtonHideUnderline(
child: DropdownButton(
value: name,
items: listOfDropdownMenuItems,
onChanged: onChanged,
style: Theme.of(context).textTheme.title,
),
),
);
</code></pre>
| 0debug |
How to fix a bug in my text calculator? - Python : <p>Im trying to make a really simple text calculator but I keep running into this problem.</p>
<p>Here is my code: </p>
<pre><code>num1 = input("Enter in the first number")
num2 = input("Enter in the second number")
sign = input("Enter in the calculator operator you would like")
elif sign = "+":
print(num1 + num2)
elif sign = "-":
print(num1 - num2)
elif sign = "*":
print(num1*num2)
elif sign = "/":
print(num1/num2)
</code></pre>
<p>Sorry im new to python...</p>
| 0debug |
static BlockDriver *find_protocol(const char *filename)
{
BlockDriver *drv1;
char protocol[128];
int len;
const char *p;
#ifdef _WIN32
if (is_windows_drive(filename) ||
is_windows_drive_prefix(filename))
return bdrv_find_format("raw");
#endif
p = strchr(filename, ':');
if (!p)
return bdrv_find_format("raw");
len = p - filename;
if (len > sizeof(protocol) - 1)
len = sizeof(protocol) - 1;
memcpy(protocol, filename, len);
protocol[len] = '\0';
QLIST_FOREACH(drv1, &bdrv_drivers, list) {
if (drv1->protocol_name &&
!strcmp(drv1->protocol_name, protocol)) {
return drv1;
}
}
return NULL;
}
| 1threat |
What is the syntax of passing the entire array of struct pointers to a function? : <p>I'm really confused on what the correct syntax is to passing an array of struct pointers to a function? For the reason of being to be able to access each and every single one, e.g. BookList[0], BookList[5] or BookList[8].</p>
<p>Here is my struct and an array of pointers;</p>
<pre><code>struct Book{
char Category[20];
int ID;
char BookName[40];
char Author[10];};
struct Book *BookList[10];
</code></pre>
<p>So lets say I create a new void function;</p>
<pre><code>void ListBooks();
</code></pre>
<p>Now, how would the parameter syntax be? is it BookList[]? is it *BookList[10]; Apologies but I'm an extreme newbie, just trying to learn.</p>
| 0debug |
Query for the following out put from the given table : [enter image description here][1]
[1]: https://i.stack.imgur.com/ZThsS.png
I want a output in following ways
table name is exampackage
Free Cardiology Pack(2 Papers Accessible-1 Internal Medicine + 1 Cardiology)
Cardiology Mini Pack (20 Papers) - 2900 RS
Cardiology Mega Pack (43 Papers) - 4900 RS
Free Neurology Pack (2 Papers Accessible-1 Internal Medicine + 1 Neurology)
Neurology Mini Pack (15 papers) - 3900 RS
Neurology Mega Pack(40 Papers)-4900 RS
and so on.... Please help me out | 0debug |
static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
QDict *options, Error **errp)
{
int ret, open_flags;
const char *filename;
const char *driver_name = NULL;
const char *node_name = NULL;
QemuOpts *opts;
BlockDriver *drv;
Error *local_err = NULL;
assert(bs->file == NULL);
assert(options != NULL && bs->options != options);
opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
qemu_opts_absorb_qdict(opts, options, &local_err);
if (local_err) {
error_propagate(errp, local_err);
ret = -EINVAL;
goto fail_opts;
}
driver_name = qemu_opt_get(opts, "driver");
drv = bdrv_find_format(driver_name);
assert(drv != NULL);
if (file != NULL) {
filename = file->bs->filename;
} else {
filename = qdict_get_try_str(options, "filename");
}
if (drv->bdrv_needs_filename && !filename) {
error_setg(errp, "The '%s' block driver requires a file name",
drv->format_name);
ret = -EINVAL;
goto fail_opts;
}
trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
drv->format_name);
node_name = qemu_opt_get(opts, "node-name");
bdrv_assign_node_name(bs, node_name, &local_err);
if (local_err) {
error_propagate(errp, local_err);
ret = -EINVAL;
goto fail_opts;
}
bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
error_setg(errp,
!bs->read_only && bdrv_is_whitelisted(drv, true)
? "Driver '%s' can only be used for read-only devices"
: "Driver '%s' is not whitelisted",
drv->format_name);
ret = -ENOTSUP;
goto fail_opts;
}
assert(bs->copy_on_read == 0);
if (bs->open_flags & BDRV_O_COPY_ON_READ) {
if (!bs->read_only) {
bdrv_enable_copy_on_read(bs);
} else {
error_setg(errp, "Can't use copy-on-read on read-only device");
ret = -EINVAL;
goto fail_opts;
}
}
if (filename != NULL) {
pstrcpy(bs->filename, sizeof(bs->filename), filename);
} else {
bs->filename[0] = '\0';
}
pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
bs->drv = drv;
bs->opaque = g_malloc0(drv->instance_size);
update_flags_from_options(&bs->open_flags, opts);
open_flags = bdrv_open_flags(bs, bs->open_flags);
if (drv->bdrv_file_open) {
assert(file == NULL);
assert(!drv->bdrv_needs_filename || filename != NULL);
ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
} else {
if (file == NULL) {
error_setg(errp, "Can't use '%s' as a block driver for the "
"protocol level", drv->format_name);
ret = -EINVAL;
goto free_and_fail;
}
bs->file = file;
ret = drv->bdrv_open(bs, options, open_flags, &local_err);
}
if (ret < 0) {
if (local_err) {
error_propagate(errp, local_err);
} else if (bs->filename[0]) {
error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
} else {
error_setg_errno(errp, -ret, "Could not open image");
}
goto free_and_fail;
}
ret = refresh_total_sectors(bs, bs->total_sectors);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not refresh total sector count");
goto free_and_fail;
}
bdrv_refresh_limits(bs, &local_err);
if (local_err) {
error_propagate(errp, local_err);
ret = -EINVAL;
goto free_and_fail;
}
assert(bdrv_opt_mem_align(bs) != 0);
assert(bdrv_min_mem_align(bs) != 0);
assert(is_power_of_2(bs->request_alignment) || bdrv_is_sg(bs));
qemu_opts_del(opts);
return 0;
free_and_fail:
bs->file = NULL;
g_free(bs->opaque);
bs->opaque = NULL;
bs->drv = NULL;
fail_opts:
qemu_opts_del(opts);
return ret;
}
| 1threat |
How to resolve a Nullpointer exception? : I am using two Recyclerviews in my app, one in the MainActivity and one in another activity. The one in the MainActivity works fine but the other has a NullpointerException and I don't know where the problem is.
I know what this problem causes but I don't see it in my code. Here is a code snippet of the second Recyclerview, where Logcat says that there is a Null object reference. I used the same code as the first Recyclerview where everything works (I changed of course the names in this file)
The error message says that there is a problem in this line: recyclerView.setLayoutManager(layoutManager);
and in this line
initRecyclerViewFreundesUebersicht();
```private void initRecyclerViewFreundesUebersicht() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
RecyclerView recyclerView = findViewById(R.id.recyclerViewFreundesUebersicht);
recyclerView.setLayoutManager(layoutManager);
RecyclerViewAdapterFreundesUebersicht adpater = new RecyclerViewAdapterFreundesUebersicht(mNames, mImageUrls, this);
recyclerView.setAdapter(adpater);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spielen_uebersicht);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
init();
initRecyclerViewFreundesUebersicht();
getImages();
}
| 0debug |
what's the diffirence between __dict__ and getattr? : I'm trying to iterate all the variables of the class `A` which contains some coroutine methods in the module `a.py`. I use two ways to achieve my purpose, but the results are different:
Method 1: use `getattr()`
a = __import__('a')
print('===========getattr()=============')
func_sync = getattr(a, 'func_sync')
func_async = getattr(a, 'func_async')
print(func_sync) # <function func_sync at 0x7f827b98f510>
print(func_async) # <function func_async at 0x7f8279cd01e0>
print(asyncio.iscoroutinefunction(func_async)) # True
# getattr class
A = getattr(a, 'A')
print(A) # <class 'a.A'>
method_aa = getattr(A, 'aa')
method_bb = getattr(A, 'bb')
method_cc = getattr(A, 'cc')
print(method_aa) # <bound method A.aa of <class 'a.A'>> <----notice this
print(method_bb) # <function A.bb at 0x7f8279cd00d0>
print(method_cc) # <function A.cc at 0x7f8279cd0158>
print(asyncio.iscoroutinefunction(method_aa)) # True <---- meet my expectations
print(asyncio.iscoroutinefunction(method_bb)) # True
print(asyncio.iscoroutinefunction(method_cc)) # False
It seems that all the results meet my expectations. But when I use `__dict__`, problem occurs
print('=========== __dict__ =============')
A = a.__dict__['A']
func_sync = a.__dict__['func_sync']
func_async = a.__dict__['func_async']
print(asyncio.iscoroutinefunction(func_async)) # True
print(A) # <class 'a.A'>
method_aa = A.__dict__['aa']
method_bb = A.__dict__['bb']
method_cc = A.__dict__['cc']
print(method_aa) # <classmethod object at 0x7f827a21c908> <---- different from before
print(method_bb) # <function A.bb at 0x7f8279cd00d0>
print(method_cc) # <function A.cc at 0x7f8279cd0158>
print(asyncio.iscoroutinefunction(method_aa)) # False <----- I think it should be True
print(asyncio.iscoroutinefunction(method_bb)) # True
print(asyncio.iscoroutinefunction(method_cc)) # False
Can someone explain for me?
This is `a.py`
class A:
@classmethod
async def aa(cls):
return 123
async def bb(self):
return 456
def cc(self):
return 789
def func_sync():
return 'sync'
async def func_async():
return 'async' | 0debug |
dont know how to phrase? google style currency converter? VB.NBET : ok i have a bit of a weird question here. have a program similar to a currency converter (it performs a mathematical function in order to produce a value to go in another textbox) what i want it to be able to do is identify the last textbox that you edited (there are 4) and then update the rest based on what you have inputted, the user then must be able to change a different textbox to change all of them.
if anyone can get me started on how to do it or even some sample code that would be much appreciated, thanks!
sorry if im not making sense, just have a look at the google currency converter and think that with two more editable boxes. | 0debug |
e1000_can_receive(VLANClientState *nc)
{
E1000State *s = DO_UPCAST(NICState, nc, nc)->opaque;
return (s->mac_reg[RCTL] & E1000_RCTL_EN);
}
| 1threat |
String to Boolean : <p>I've read numerous examples converting from String to Boolean.</p>
<p>For example,</p>
<p>myString = (myString == "true");</p>
<p>But I'm unable to apply the logic to my code. Can someone help?</p>
<blockquote>
<p>CommonConfig.getFeatureFlags['analytics.demo'] returns "true" (Note
the "").(That's how backend returns it)</p>
</blockquote>
<pre><code>var FeatureFlag = _.extend(CommonConfig, {
demoFeature: String == CommonConfig.getFeatureFlags['analytics.demo'], //either "true" or "false" but I want to make it to true or false
});
</code></pre>
<p>Question: I want to convert from String "true" to boolean. And pass true or false based upon!</p>
<p>Can someone help?</p>
| 0debug |
Ruby @@vaiable vs self.variable : In Ruby, What is the difference between `@@variable` to `self.variable`
1. In the scope of main.
2. In the scope of the class
3. In the scope of a method
| 0debug |
Order of component life cycle with react-redux connect and redux data : <p>We all know that <code>constructor -> componentWillMount -> componentDidMount</code> is order of execution. </p>
<p>Now when redux comes into play and trying to access redux properties in our component life cycle. What is the order in which <strong>connect will execute</strong> so that <strong>data is available lifecycle methods</strong> ignoring and data updation to redux. The possibilities are</p>
<pre><code>1. Connect (DATA AVAILABLE) -> constructor & componentWillMount & componentDidMount
2. constructor -> Connect (DATA AVAILABLE) -> componentWillMount & componentDidMount
3. constructor -> componentWillMount -> Connect (DATA AVAILABLE) -> componentDidMount
4. constructor -> componentWillMount -> componentDidMount -> Connect (DATA AVAILABLE)
</code></pre>
<p>and is the <strong>order consistent</strong> or <strong>depends</strong> on the data that is loaded?</p>
<p>and is it different between <strong>react and react native</strong></p>
<p>and is it okay to defined redux properties as <strong>required in PropType</strong></p>
| 0debug |
regex to add a ? at he end of all non punctuated sentences.in a text document using edit pad pro or Power GREP : **for ex**
Lichen planus occurs most frequently on the
A. buccal mucosa.
B. tongue.
C. floor of the mouth.
D. gingiva.
In the absence of “Hanks balanced salt solution”, what is the most appropriate media to transport an avulsed
A. Saliva.
B. Milk.
C. Saline.
D. Tap water.
Which of the following is the most likely cause of osteoporosis, glaucoma, hypertension and peptic ulcers in a 65 year old with Crohn’s disease
A. Uncontrolled diabetes.
B. Systemic corticosteroid therapy.
C. Chronic renal failure.
D. Prolonged NSAID therapy.
E. Malabsorption syndrome.
**DESIRED RESULT**
Lichen planus occurs most frequently on the?
A. buccal mucosa.
B. tongue.
C. floor of the mouth.
D. gingiva.
In the absence of “Hanks balanced salt solution”, what is the most appropriate media to transport an avulsed?
A. Saliva.
B. Milk.
C. Saline.
D. Tap water.
Which of the following is the most likely cause of osteoporosis, glaucoma, hypertension and peptic ulcers in a 65 year old with Crohn’s disease?
A. Uncontrolled diabetes.
B. Systemic corticosteroid therapy.
C. Chronic renal failure.
D. Prolonged NSAID therapy.
E. Malabsorption syndrome. | 0debug |
expected ',' javascript firebase : <p>i have this problem in javascript code</p>
<p>expected ',' in line <code>like: like + 1;</code></p>
<p>expected ',' in line <code>dislike: dislike + 1;</code></p>
<p><strong>html code</strong></p>
<pre><code><div class="container">
<div class="button-container like-container">
<a href="#">
<i class="fa fa-heart-o"> Like</i>
</a>
</div>
<div class="button-container dislike-container">
<a href="#">
<i class="fa fa-heart"> Dislike</i>
</a>
</div>
</div>
</code></pre>
<p><strong>javascript code</strong> </p>
<pre><code>var likeDislike = new Firebase("https://like-unlike.firebaseio.com/");
var like;
var dislike;
likeDislike.on("value", function(likeDislikeData) {
var data = likeDislikeData.val();
like = data.like;
dislike = data.dislike;
});
$('.like-container').on('click', function() {
likeDislike.update({
like: like + 1;
});
console.log("Number of likes:" + like);
});
$('.dislike-container a').on('click', function() {
likeDislike.update({
dislike: dislike + 1;
});
console.log("Number of dislikes: " + dislike);
});
</code></pre>
| 0debug |
Add additional ID : <p>How can I add additional ID without deleting the first one</p>
<pre><code><div id="first-id"></div>
</code></pre>
<p>to</p>
<pre><code><div id="first-id second-id"></div>
</code></pre>
| 0debug |
How to get the byte array from the file path in the array from? : <p>I need to get the byte array from file path to upload the image. But the byte array in the form of array.How do i get the byte array. I have followed the following steps but could not found the solutions.</p>
<p>I have tried the following code but does not work.</p>
<pre><code>byte []buffer=new byte[1024];
ByteArrayOutputStream os=new ByteArrayOutputStream();
FileInputStream fis=new FileInputStream(f);
int read;
while ((read=fis.read(buffer))!=-1){
os.write(buffer,0,read);
}
fis.close();
os.close();
</code></pre>
<p>It return the byte array object but i need the array. When i used Array.toString(bytearray) it return in the string form but i need the array form. Please help me how can i do this.</p>
| 0debug |
void os_mem_prealloc(int fd, char *area, size_t memory)
{
int ret;
struct sigaction act, oldact;
sigset_t set, oldset;
memset(&act, 0, sizeof(act));
act.sa_handler = &sigbus_handler;
act.sa_flags = 0;
ret = sigaction(SIGBUS, &act, &oldact);
if (ret) {
perror("os_mem_prealloc: failed to install signal handler");
exit(1);
}
sigemptyset(&set);
sigaddset(&set, SIGBUS);
pthread_sigmask(SIG_UNBLOCK, &set, &oldset);
if (sigsetjmp(sigjump, 1)) {
fprintf(stderr, "os_mem_prealloc: Insufficient free host memory "
"pages available to allocate guest RAM\n");
exit(1);
} else {
int i;
size_t hpagesize = fd_getpagesize(fd);
size_t numpages = DIV_ROUND_UP(memory, hpagesize);
for (i = 0; i < numpages; i++) {
memset(area + (hpagesize * i), 0, 1);
}
ret = sigaction(SIGBUS, &oldact, NULL);
if (ret) {
perror("os_mem_prealloc: failed to reinstall signal handler");
exit(1);
}
pthread_sigmask(SIG_SETMASK, &oldset, NULL);
}
}
| 1threat |
Why my spinner in android studio doesn't display anything even though i have followed some tutorial? : I'm working a project, and i want to use spinner in it. Firstly, i try some tutorial on youtube and my code successfully to compile, but the problem is my spinner doesn't show any text. Then, i try another tutorial and find solution for my problem from any resource. But, it still not working.
Then i try to make new project that only contains spinner with the same code, it's working perfectly. I don't know why this is happen.
The different between my project and the new project is, my project have navigation drawer. I don't know, but maybe this is related.
sorry for my bad english
this is my xml code for spinner
```xml
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"/>
```
and this is for my java
```java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_home);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
List<String> categories = new ArrayList<>();
categories.add(0, "Choose Station");
categories.add("Station A (Asrama Mahanaim)");
categories.add("Station B (Asrama Mamre)");
categories.add("Station C (Asrama Nazareth)");
categories.add("Station D (Kantin Lama)");
categories.add("Station E (Studio)");
categories.add("Station F (GD 8)");
categories.add("Station G (GD 9)");
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (adapterView.getItemAtPosition(i).equals("Choose Station")) {
//do nothing
} else {
String item = adapterView.getItemAtPosition(i).toString();
Toast.makeText(adapterView.getContext(), "Selected : " + item, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
//TODO auto-generated method stub
}
});
}
```
this is the output when compiled
[enter image description here][1]
[1]: https://i.stack.imgur.com/r8kfM.jpg | 0debug |
hard code large hex value throws error in C# : <p>ulong va = 0xffffffe0;</p>
<p>This throws the below errors:</p>
<pre><code>Error 1 Unexpected character ''
Error 2 Invalid expression term ''
Error 3 ; expected
Error 4 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
</code></pre>
<p>why is it so? How can i fix?</p>
| 0debug |
C - Binary to Decimal segmentation error : I am using a pointer in place of an array, I'm aware that a pointer needs to be freed unlike an array. Why is it that using a pointer in place of an array gives me a segmentation memory error.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void bin(void){
char *input;
int choice;
int x = 0;
printf("Enter Decimal Code:\n");
scanf("%s",&input);
int leng = strlen(input);
for(int i = 0; i <= leng ; ++i){
if(input[i] == '1'){
x += pow(2,i);
}
else if(input[i] == '0'){
input[i] = 0;
}
free(input);
}
printf("Binary-Dec: %d\n",x);
}
int main()
{
bin();
}
| 0debug |
Extracting entry positions in R : <p>I have a vector, A, with lots of entries, for example</p>
<pre><code>1 4 2 5 6 7 8 3 5
</code></pre>
<p>I want to get a list of all the positions of entries in that vector that are in [2,6], so id like the output to be </p>
<pre><code>2 3 4 5 8 9
</code></pre>
<p>please help</p>
| 0debug |
static inline int *DEC_UPAIR(int *dst, unsigned idx, unsigned sign)
{
dst[0] = (idx & 15) * (1 - (sign & 0xFFFFFFFE));
dst[1] = (idx >> 4 & 15) * (1 - ((sign & 1) << 1));
return dst + 2;
}
| 1threat |
PPC_OP(addic)
{
T1 = T0;
T0 += PARAM(1);
if (T0 < T1) {
xer_ca = 1;
} else {
xer_ca = 0;
}
RETURN();
}
| 1threat |
Posting from AWS-API Gateway to Lambda : <p>I have a simple C# Aws Lambda function which succeeds to a test from the Lambda console test but fails with a 502 (Bad Gateway) if called from the API Gateway (which i generated from the Lambda trigger option) and also if I use postman.(this initial function has open access (no security))</p>
<pre><code>// request header
Content-Type: application/json
// request body
{
"userid":22,
"files":["File1","File2","File3","File4"]
}
</code></pre>
<p>The error I get in the logs is:</p>
<pre><code>Wed Feb 08 14:14:54 UTC 2017 : Endpoint response body before transformations: {
"errorType": "NullReferenceException",
"errorMessage": "Object reference not set to an instance of an object.",
"stackTrace": [
"at blahblahmynamespace.Function.FunctionHandler(ZipRequest input, ILambdaContext context)",
"at lambda_method(Closure , Stream , Stream , ContextInfo )"
]
}
</code></pre>
<p>It seems like the posted object is not being passed to the lambda input argument.</p>
<p>Code below</p>
<pre><code>// Lambda function
public LambdaResponse FunctionHandler(ZipRequest input, ILambdaContext context)
{
try
{
var logger = context.Logger;
var headers = new Dictionary<string, string>();
if (input == null || input.files.Count == 0)
{
logger.LogLine($"input was null");
headers.Add("testheader", "ohdear");
return new LambdaResponse { body = "fail", headers = headers, statusCode = HttpStatusCode.BadRequest };
}
else
{
logger.LogLine($"recieved request from user{input?.userid}");
logger.LogLine($"recieved {input?.files?.Count} items to zip");
headers.Add("testheader", "yeah");
return new LambdaResponse { body = "hurrah", headers = headers, statusCode = HttpStatusCode.OK };
}
}
catch (Exception ex)
{
throw ex;
}
}
</code></pre>
<p>//Lambda response/ZipRequest class</p>
<pre><code>public class LambdaResponse
{
public HttpStatusCode statusCode { get; set; }
public Dictionary<string, string> headers { get; set; }
public string body { get; set; }
}
public class ZipRequest
{
public int userid { get; set; }
public IList<string> files { get; set; }
}
</code></pre>
| 0debug |
Installing OpenMP on Mac OS X 10.11 : <p>How can I get OpenMP to run on Mac OSX 10.11, so that I can execute scripts <strong>via terminal</strong>?</p>
<p>I have installed OpenMP: <code>brew install clang-omp</code>.</p>
<p>When I run, for example: <code>gcc -fopenmp -o Parallel.b Parallel.c</code> the following expression returns: <code>fatal error: 'omp.h' file not found</code></p>
<p>I have also tried: <code>brew install gcc --without-multilib</code> but unfortunately this eventually returned the following (after first installing some dependencies): </p>
<pre><code>The requested URL returned error: 404 Not Found
Error: Failed to download resource "mpfr--patch"
</code></pre>
<p><strong>Any recommended work arounds?</strong></p>
| 0debug |
ERROR: unsatisfiable constraints using apk in dockerfile : <p>I'm trying to install postgis into a postgres container.
Dockerfile:</p>
<pre><code>FROM postgres:9.6.4-alpine
RUN apk update \
&& apk add -u postgresql-9.6-postgis-2.4 postgresql-9.6-postgis-2.4-scripts \
&& rm -rf /var/lib/apt/lists/*
COPY ./scripts/postgis.sh /docker-entrypoint-initdb.d/postgis.sh
</code></pre>
<p>postgis.sh:</p>
<pre><code>#!/bin/sh
for DB in $(psql -t -c "SELECT datname from pg_database where datname = 'backend'"); do
echo "Loading PostGIS extensions into $DB"
"${psql[@]}" --dbname="$DB" <<-'EOSQL'
CREATE EXTENSION IF NOT EXISTS postgis;
EOSQL
done
</code></pre>
<p>I got this error:</p>
<blockquote>
<p>ERROR: unsatisfiable constraints:
postgresql-9.6-postgis-2.4 (missing):
required by:
world[postgresql-9.6-postgis-2.4]
postgresql-9.6-postgis-2.4-scripts (missing):
required by:
world[postgresql-9.6-postgis-2.4-scripts]
The command '/bin/sh -c apk update && apk add -u postgresql-9.6-postgis-2.4 postgresql-9.6-postgis-2.4-scripts && rm -rf /var/lib/apt/lists/*' returned a non-zero code: 2</p>
</blockquote>
<p>I found similar questions such as :</p>
<ol>
<li><a href="https://stackoverflow.com/questions/48417891/error-unsatisfiable-constraints-while-installing-package-in-alpine">ERROR: unsatisfiable constraints: while installing package in alpine
</a></li>
<li><a href="https://stackoverflow.com/questions/36530620/error-unsatisfiable-constraints-on-php7-fpm-alpine">ERROR: unsatisfiable constraints - on php:7-fpm-alpine</a></li>
</ol>
<p>But it doesn't solve my problem.How can I add postgis extension to my postgres container with apk?</p>
| 0debug |
Add cognalys sdk to android app : I am making and android app which needs phone no verification. I want to and Cognalys SDK in my application so help me how to add this to my application. | 0debug |
How to display the snack bar on page load : <p>Hi i want to show snack bar on my page after the page load without any clicking. I have a piece of code but it works in onclick. But i want to show the message without any click after the page load. </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>function snackBar() {
var x = document.getElementById("snackbar")
x.className = "show";
setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#snackbar {
visibility: hidden;
min-width: 250px;
margin-left: -125px;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 2px;
padding: 16px;
position: fixed;
z-index: 1;
right:0;
bottom: 30px;
font-size: 17px;
}
#snackbar.show {
visibility: visible;
-webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
animation: fadein 0.5s, fadeout 0.5s 2.5s;
}
@-webkit-keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
@keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
@-webkit-keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 0; opacity: 0;}
}
@keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 0; opacity: 0;}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="snackBar()">Show Snackbar</button>
<div id="snackbar">Some text some message..</div></code></pre>
</div>
</div>
</p>
| 0debug |
How to search & increment a value in a .txt file loop : I have to search & increment certain data from .txt file. I could extact(print out) the data, but am not sure on how to update/increment it ?
> There is data on a line in the .txt which I want to increment by 15%
> in a loop.
> +abc0 = 0.5 tg = 0.512 kjkj = 7543, (I want to increment the value beside abc0 in a loop, 15 % each time, write it to text file, run it &
> repeat.)
open my $fh, "<" ,".....lib" or die "$!";
for(my $i= 0; $i < 10; $i++) {
while(my $line = <$fh>){
if( my ($xyz0) = $line =~m/xyz0 = (\S+)/){
print $xyz0,"\n"; # this prints 0.005
$new_value = $xyzo * 1.15;
$xyz0 =~ s/$xyz0/$new_value/;}}}
| 0debug |
How to manually parse a JSON string in net-core 2.0 : <p>I have a json string with the following structure</p>
<pre><code>{
"resource": "user",
"method": "create",
"fields": {
"name": "John",
"surname: "Smith",
"email": "john@gmail.com"
}
}
</code></pre>
<p>The keys inside <em>fields</em> are variable, that means I don't know them in advance</p>
<p>So, instead of deserializing a json string to an object, I need to traverse the json, in order to get the properties inside <em>fields</em> in a Dictionary or something like that.</p>
<p>I heard about the Json.NET library and it's ability to parse dynamic jsons, but I'm not sure it it's already included in net-core or not.</p>
<p>What would be the standard / easiest way to accomplish that in net-core 2.0. Code example would be appreciated.</p>
| 0debug |
I want to make a snake game in a C# console, movement problem : <p>To change snakes direction I first have to press upArrow and then the new direction of the snake, and the snake is going in that direction until I hit upArrow again. So, to change direction to the left you need to press upArrow and then leftArrow. I want that to disappear, when I press left to make snake go left. Basically up arrow is pausing the game and I dont know why. </p>
<pre><code> if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.UpArrow)
{
keyinfo = Console.ReadKey();
Console.WriteLine(ConsoleKey.UpArrow);
}
if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.DownArrow)
{
keyinfo = Console.ReadKey();
Console.WriteLine(ConsoleKey.DownArrow);
}
if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.LeftArrow)
{
keyinfo = Console.ReadKey();
Console.WriteLine(ConsoleKey.LeftArrow);
}
if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.RightArrow)
{
keyinfo = Console.ReadKey();
Console.WriteLine(ConsoleKey.RightArrow);
}
if (keyinfo.Key == ConsoleKey.UpArrow)
{
j--;
}
if (keyinfo.Key == ConsoleKey.DownArrow)
{
j++;
}
if (keyinfo.Key == ConsoleKey.LeftArrow)
{
k--;
}
if (keyinfo.Key == ConsoleKey.RightArrow)
{
k++;
}
</code></pre>
| 0debug |
int target_munmap(target_ulong start, target_ulong len)
{
target_ulong end, real_start, real_end, addr;
int prot, ret;
#ifdef DEBUG_MMAP
printf("munmap: start=0x%lx len=0x%lx\n", start, len);
#endif
if (start & ~TARGET_PAGE_MASK)
return -EINVAL;
len = TARGET_PAGE_ALIGN(len);
if (len == 0)
return -EINVAL;
end = start + len;
real_start = start & qemu_host_page_mask;
real_end = HOST_PAGE_ALIGN(end);
if (start > real_start) {
prot = 0;
for(addr = real_start; addr < start; addr += TARGET_PAGE_SIZE) {
prot |= page_get_flags(addr);
}
if (real_end == real_start + qemu_host_page_size) {
for(addr = end; addr < real_end; addr += TARGET_PAGE_SIZE) {
prot |= page_get_flags(addr);
}
end = real_end;
}
if (prot != 0)
real_start += qemu_host_page_size;
}
if (end < real_end) {
prot = 0;
for(addr = end; addr < real_end; addr += TARGET_PAGE_SIZE) {
prot |= page_get_flags(addr);
}
if (prot != 0)
real_end -= qemu_host_page_size;
}
if (real_start < real_end) {
ret = munmap((void *)real_start, real_end - real_start);
if (ret != 0)
return ret;
}
page_set_flags(start, start + len, 0);
return 0;
}
| 1threat |
db.execute('SELECT * FROM products WHERE product_id = ' + product_input) | 1threat |
How to compare System.Enum to enum (implementation) without boxing? : <p>How can I compare a <code>System.Enum</code> to an <code>enum</code> without boxing? For example, how can I make the following code work without boxing the <code>enum</code>?</p>
<pre><code>enum Color
{
Red,
Green,
Blue
}
...
System.Enum myEnum = GetEnum(); // Returns a System.Enum.
// May be a Color, may be some other enum type.
...
if (myEnum == Color.Red) // ERROR!
{
DoSomething();
}
</code></pre>
<p>To be specific, the intent here is not to compare the underlying values. In this case, the underlying values are not meant to matter. Instead, if two Enums have the same underlying value, they should not be considered equal if they are two different kinds of enums:</p>
<pre><code>enum Fruit
{
Apple = 0,
Banana = 1,
Orange = 2
}
enum Vegetable
{
Tomato = 0,
Carrot = 1,
Celery = 2
}
myEnum = Vegetable.Tomato;
if (myEnum != Fruit.Apple) // ERROR!
{
// Code should reach this point
// even though they're the same underlying int values
Log("Works!");
}
</code></pre>
<p>This is basically the same functionality as <code>Enum.Equals(Object)</code>. Unfortunately <code>Equals()</code> requires boxing the enum, which in our case would be a naughty thing to do.</p>
<p>Is there a nice way to compare two arbitrary enums without boxing or otherwise creating a bunch of overhead?</p>
<p>Thanks for any help!</p>
| 0debug |
void ff_h263_encode_mb(MpegEncContext * s,
int16_t block[6][64],
int motion_x, int motion_y)
{
int cbpc, cbpy, i, cbp, pred_x, pred_y;
int16_t pred_dc;
int16_t rec_intradc[6];
int16_t *dc_ptr[6];
const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1);
if (!s->mb_intra) {
cbp= get_p_cbp(s, block, motion_x, motion_y);
if ((cbp | motion_x | motion_y | s->dquant | (s->mv_type - MV_TYPE_16X16)) == 0) {
put_bits(&s->pb, 1, 1);
if(interleaved_stats){
s->misc_bits++;
s->last_bits++;
}
s->skip_count++;
return;
}
put_bits(&s->pb, 1, 0);
cbpc = cbp & 3;
cbpy = cbp >> 2;
if(s->alt_inter_vlc==0 || cbpc!=3)
cbpy ^= 0xF;
if(s->dquant) cbpc+= 8;
if(s->mv_type==MV_TYPE_16X16){
put_bits(&s->pb,
ff_h263_inter_MCBPC_bits[cbpc],
ff_h263_inter_MCBPC_code[cbpc]);
put_bits(&s->pb, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
if(s->dquant)
put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
if(interleaved_stats){
s->misc_bits+= get_bits_diff(s);
}
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
if (!s->umvplus) {
ff_h263_encode_motion_vector(s, motion_x - pred_x,
motion_y - pred_y, 1);
}
else {
h263p_encode_umotion(s, motion_x - pred_x);
h263p_encode_umotion(s, motion_y - pred_y);
if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
put_bits(&s->pb,1,1);
}
}else{
put_bits(&s->pb,
ff_h263_inter_MCBPC_bits[cbpc+16],
ff_h263_inter_MCBPC_code[cbpc+16]);
put_bits(&s->pb, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
if(s->dquant)
put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
if(interleaved_stats){
s->misc_bits+= get_bits_diff(s);
}
for(i=0; i<4; i++){
ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
motion_x = s->current_picture.motion_val[0][s->block_index[i]][0];
motion_y = s->current_picture.motion_val[0][s->block_index[i]][1];
if (!s->umvplus) {
ff_h263_encode_motion_vector(s, motion_x - pred_x,
motion_y - pred_y, 1);
}
else {
h263p_encode_umotion(s, motion_x - pred_x);
h263p_encode_umotion(s, motion_y - pred_y);
if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
put_bits(&s->pb,1,1);
}
}
}
if(interleaved_stats){
s->mv_bits+= get_bits_diff(s);
}
} else {
assert(s->mb_intra);
cbp = 0;
if (s->h263_aic) {
for(i=0; i<6; i++) {
int16_t level = block[i][0];
int scale;
if(i<4) scale= s->y_dc_scale;
else scale= s->c_dc_scale;
pred_dc = ff_h263_pred_dc(s, i, &dc_ptr[i]);
level -= pred_dc;
if (level >= 0)
level = (level + (scale>>1))/scale;
else
level = (level - (scale>>1))/scale;
if (level == 0 && s->block_last_index[i] == 0)
s->block_last_index[i] = -1;
if(!s->modified_quant){
if (level < -127)
level = -127;
else if (level > 127)
level = 127;
}
block[i][0] = level;
rec_intradc[i] = scale*level + pred_dc;
rec_intradc[i] |= 1;
if (rec_intradc[i] < 0)
rec_intradc[i] = 0;
else if (rec_intradc[i] > 2047)
rec_intradc[i] = 2047;
*dc_ptr[i] = rec_intradc[i];
if (s->block_last_index[i] >= 0)
cbp |= 1 << (5 - i);
}
}else{
for(i=0; i<6; i++) {
if (s->block_last_index[i] >= 1)
cbp |= 1 << (5 - i);
}
}
cbpc = cbp & 3;
if (s->pict_type == AV_PICTURE_TYPE_I) {
if(s->dquant) cbpc+=4;
put_bits(&s->pb,
ff_h263_intra_MCBPC_bits[cbpc],
ff_h263_intra_MCBPC_code[cbpc]);
} else {
if(s->dquant) cbpc+=8;
put_bits(&s->pb, 1, 0);
put_bits(&s->pb,
ff_h263_inter_MCBPC_bits[cbpc + 4],
ff_h263_inter_MCBPC_code[cbpc + 4]);
}
if (s->h263_aic) {
put_bits(&s->pb, 1, 0);
}
cbpy = cbp >> 2;
put_bits(&s->pb, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
if(s->dquant)
put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
if(interleaved_stats){
s->misc_bits+= get_bits_diff(s);
}
}
for(i=0; i<6; i++) {
h263_encode_block(s, block[i], i);
if (s->h263_aic && s->mb_intra) {
block[i][0] = rec_intradc[i];
}
}
if(interleaved_stats){
if (!s->mb_intra) {
s->p_tex_bits+= get_bits_diff(s);
s->f_count++;
}else{
s->i_tex_bits+= get_bits_diff(s);
s->i_count++;
}
}
}
| 1threat |
Vue Y U NO UPDATE :
Working my way learning about Vue. I chose it as the better alternative after looking at React, Angular and Svelte.
I have a simple example that its not working probably because I'm not getting/understanding the reactive behaviour of Vue.
Plain simple App:
> <template>
> <div id="app">
> <app-header></app-header>
> <router-view/>
> <app-footer></app-footer>
> </div>
> </template>
>
> <script>
> import Header from './components/Header.vue';
> import Home from './components/Home.vue';
> import Footer from './components/Footer.vue';
> export default {
> components: {
> name: 'App',
> 'app-header': Header,
> 'app-footer': Footer
> }
> }
Where Home.vue and Footer.vue have plain HTML content on the template.
On Header.vue I have:
> <template>
> <div>
> <h1> The Header </h1>
> <nav>
> <ul>
> <li>Curr Player: {{ethaccount}}</li>
>
> <li>Prop owner: {{propOwner}}</li>
>
> </ul>
> </nav>
>
> <hr>
> </div>
>
> </template>
>
> <script>
>
>
> export default {
> data() {
> return {
> ethaccount: "N/A",
> propOwner: "N/A"
> }
> },
> methods: {
>
> update() {
>
> var ethaccount = "0xAAAAAA123456789123456789123456789";
> console.log("ETH Account: " + ethaccount);
>
> var propOwner = "0xPPPPPPPPPPP987654321987654321";
> console.log("Prop Account: " + propOwner);
> }
>
> },
> mounted() {
> this.update()
> }
> };
> </script>
But I'm unable to get the header updated and unable to find what I'm doing wrong. Help.
| 0debug |
How can I simplify this code in python? : <p>The task is to get all the multiples of 3 below 100, and then add them together.</p>
<pre><code>num1 = 0
l = []
while num1 < 100:
num1 = num1 + 3
l.append(num1)
# I used this to delete the last element in the list which is 102,
del l[-1]
print l
# sum of all the numbers in l
b = sum(l)
print b
</code></pre>
| 0debug |
static int mjpeg_decode_com(MJpegDecodeContext *s)
{
int len = get_bits(&s->gb, 16);
if (len >= 2 && len < 32768) {
uint8_t *cbuf = av_malloc(len - 1);
if (cbuf) {
int i;
for (i = 0; i < len - 2; i++)
cbuf[i] = get_bits(&s->gb, 8);
if (i > 0 && cbuf[i-1] == '\n')
cbuf[i-1] = 0;
else
cbuf[i] = 0;
if(s->avctx->debug & FF_DEBUG_PICT_INFO)
av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
if (!strcmp(cbuf, "AVID"))
{
s->buggy_avid = 1;
}
else if(!strcmp(cbuf, "CS=ITU601")){
s->cs_itu601= 1;
}
av_free(cbuf);
}
}
return 0;
}
| 1threat |
How to throw custom error message from API Gateway custom authorizer : <p><a href="https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints/blob/master/blueprints/python/api-gateway-authorizer-python.py#L30-L31" rel="noreferrer">Here</a> in the blue print says, API gateway will respond with 401: Unauthorized. </p>
<p>I wrote the same <code>raise Exception('Unauthorized')</code> in my lambda and was able to test it from Lambda Console. But in POSTMAN, I'm receiving status <code>500</code>
with body: </p>
<pre><code>{
message: null`
}
</code></pre>
<p>I want to add custom error messages such as "Invalid signature", "TokenExpired", etc., Any documentation or guidance would be appreciated.</p>
| 0debug |
static void virtio_scsi_command_complete(SCSIRequest *r, uint32_t status,
size_t resid)
{
VirtIOSCSIReq *req = r->hba_private;
uint8_t sense[SCSI_SENSE_BUF_SIZE];
uint32_t sense_len;
if (r->io_canceled) {
return;
}
req->resp.cmd->response = VIRTIO_SCSI_S_OK;
req->resp.cmd->status = status;
if (req->resp.cmd->status == GOOD) {
req->resp.cmd->resid = tswap32(resid);
} else {
req->resp.cmd->resid = 0;
sense_len = scsi_req_get_sense(r, sense, sizeof(sense));
sense_len = MIN(sense_len, req->resp_size - sizeof(req->resp.cmd));
memcpy(req->resp.cmd->sense, sense, sense_len);
req->resp.cmd->sense_len = tswap32(sense_len);
}
virtio_scsi_complete_cmd_req(req);
}
| 1threat |
C++ how to handle class types when writing a scripting language : <p>I've been stumped by this for some time although I believe it may be quite simple. I am writing a simple programming language in c++ and I can't figure out the best way to handle variable types withing my language.</p>
<p>For example I may have eight different variable types including string, number, bool, table, etc! I need to know the best way to store these within c++ because they are all different types, which means all different classes! I will have many more than eight types though. The code is line based with a compiler. Please help!</p>
| 0debug |
group by average in R : <p>I have data structure (data frame), which contains 3 column, age (integer), weight (float) and height (float), I want to calculate average and median weight/height in each age group (e.g. average weight/height in age 10, average weight/height in age 11, average weight/height in age 12, etc.). Wondering if there are any reference code examples?</p>
<p>Currently, I am doing group-by alike function outside R using Python numpy/pandas package. If there is R built-in solution for group-by, it will be great.</p>
<p>regards,
Lin</p>
| 0debug |
iscsi_set_events(IscsiLun *iscsilun)
{
struct iscsi_context *iscsi = iscsilun->iscsi;
int ev = iscsi_which_events(iscsi);
if (ev != iscsilun->events) {
aio_set_fd_handler(iscsilun->aio_context,
iscsi_get_fd(iscsi),
(ev & POLLIN) ? iscsi_process_read : NULL,
(ev & POLLOUT) ? iscsi_process_write : NULL,
iscsilun);
iscsilun->events = ev;
}
if (!ev) {
timer_mod(iscsilun->event_timer,
qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);
}
}
| 1threat |
C++ change from struct to classes? : <p>How can I change from using struct to class? The code doesn't have any problem. But I wanna how can I put put it in classes.
What would you suggest in way of changing it over. There is no problem there. just a simple change over question.</p>
<p>This is my header file in the c++.</p>
<pre><code>struct SpaceShip
{
int ID;
int x;
int y;
int lives;
int speed;
int boundx;
int boundy;
int score;
};
struct Bullet
{
int ID;
int x;
int y;
bool live;
int speed;
};
struct Comet
{
int ID;
int x;
int y;
bool live;
int speed;
int boundx;
int boundy;
};
</code></pre>
<p>and this is my main.cpp file.</p>
<pre><code>#include <allegro5\allegro.h>
#include <allegro5\allegro_primitives.h>
#include <allegro5\allegro_font.h>
#include <allegro5\allegro_ttf.h>
#include "objects.h"
//GLOBALS==============================
const int WIDTH = 800;
const int HEIGHT = 400;
const int NUM_BULLETS = 5;
const int NUM_COMETS = 10;
enum KEYS { UP, DOWN, LEFT, RIGHT, SPACE };
bool keys[5] = { false, false, false, false, false };
//prototypes
void InitShip(SpaceShip &ship);
void DrawShip(SpaceShip &ship);
void MoveShipUp(SpaceShip &ship);
void MoveShipDown(SpaceShip &ship);
void MoveShipLeft(SpaceShip &ship);
void MoveShipRight(SpaceShip &ship);
void InitBullet(Bullet bullet[], int size);
void DrawBullet(Bullet bullet[], int size);
void FireBullet(Bullet bullet[], int size, SpaceShip &ship);
void UpdateBullet(Bullet bullet[], int size);
void CollideBullet(Bullet bullet[], int bSize, Comet comets[], int cSize, SpaceShip &ship);
void InitComet(Comet comets[], int size);
void DrawComet(Comet comets[], int size);
void StartComet(Comet comets[], int size);
void UpdateComet(Comet comets[], int size);
void CollideComet(Comet comets[], int cSize, SpaceShip &ship);
int main(void)
{
//primitive variable
bool done = false;
bool redraw = true;
const int FPS = 60;
bool isGameOver = false;
//object variables
SpaceShip ship;
Bullet bullets[NUM_BULLETS];
Comet comets[NUM_COMETS];
//Allegro variables
ALLEGRO_DISPLAY *display = NULL;
ALLEGRO_EVENT_QUEUE *event_queue = NULL;
ALLEGRO_TIMER *timer = NULL;
ALLEGRO_FONT *font18 = NULL;
//Initialization Functions
if (!al_init()) //initialize Allegro
return -1;
display = al_create_display(WIDTH, HEIGHT); //create our display object
if (!display) //test display object
return -1;
al_init_primitives_addon();
al_install_keyboard();
al_init_font_addon();
al_init_ttf_addon();
event_queue = al_create_event_queue();
timer = al_create_timer(1.0 / FPS);
srand(time(NULL));
InitShip(ship);
InitBullet(bullets, NUM_BULLETS);
InitComet(comets, NUM_COMETS);
font18 = al_load_font("arial.ttf", 18, 0);
al_register_event_source(event_queue, al_get_keyboard_event_source());
al_register_event_source(event_queue, al_get_timer_event_source(timer));
al_register_event_source(event_queue, al_get_display_event_source(display));
al_start_timer(timer);
while (!done)
{
ALLEGRO_EVENT ev;
al_wait_for_event(event_queue, &ev);
if (ev.type == ALLEGRO_EVENT_TIMER)
{
redraw = true;
if (keys[UP])
MoveShipUp(ship);
if (keys[DOWN])
MoveShipDown(ship);
if (keys[LEFT])
MoveShipLeft(ship);
if (keys[RIGHT])
MoveShipRight(ship);
if (!isGameOver)
{
UpdateBullet(bullets, NUM_BULLETS);
StartComet(comets, NUM_COMETS);
UpdateComet(comets, NUM_COMETS);
CollideBullet(bullets, NUM_BULLETS, comets, NUM_COMETS, ship);
CollideComet(comets, NUM_COMETS, ship);
if (ship.lives <= 0)
isGameOver = true;
}
}
else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
{
done = true;
}
else if (ev.type == ALLEGRO_EVENT_KEY_DOWN)
{
switch (ev.keyboard.keycode)
{
case ALLEGRO_KEY_ESCAPE:
done = true;
break;
case ALLEGRO_KEY_UP:
keys[UP] = true;
break;
case ALLEGRO_KEY_DOWN:
keys[DOWN] = true;
break;
case ALLEGRO_KEY_LEFT:
keys[LEFT] = true;
break;
case ALLEGRO_KEY_RIGHT:
keys[RIGHT] = true;
break;
case ALLEGRO_KEY_SPACE:
keys[SPACE] = true;
FireBullet(bullets, NUM_BULLETS, ship);
break;
}
}
else if (ev.type == ALLEGRO_EVENT_KEY_UP)
{
switch (ev.keyboard.keycode)
{
case ALLEGRO_KEY_ESCAPE:
done = true;
break;
case ALLEGRO_KEY_UP:
keys[UP] = false;
break;
case ALLEGRO_KEY_DOWN:
keys[DOWN] = false;
break;
case ALLEGRO_KEY_LEFT:
keys[LEFT] = false;
break;
case ALLEGRO_KEY_RIGHT:
keys[RIGHT] = false;
break;
case ALLEGRO_KEY_SPACE:
keys[SPACE] = false;
break;
}
}
if (redraw && al_is_event_queue_empty(event_queue))
{
redraw = false;
if (!isGameOver)
{
DrawShip(ship);
DrawBullet(bullets, NUM_BULLETS);
DrawComet(comets, NUM_COMETS);
al_draw_textf(font18, al_map_rgb(255, 0, 255), 5, 5, 0, "Player has %i lives left. Player has destroyed %i objects", ship.lives, ship.score);
}
else
{
al_draw_textf(font18, al_map_rgb(0, 255, 255), WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "Game Over. Final Score: %i", ship.score);
}
al_flip_display();
al_clear_to_color(al_map_rgb(0, 0, 0));
}
}
al_destroy_event_queue(event_queue);
al_destroy_timer(timer);
al_destroy_font(font18);
al_destroy_display(display); //destroy our display object
return 0;
}
void InitShip(SpaceShip &ship)
{
ship.x = 20;
ship.y = HEIGHT / 2;
ship.ID = PLAYER;
ship.lives = 3;
ship.speed = 7;
ship.boundx = 6;
ship.boundy = 7;
ship.score = 0;
}
void DrawShip(SpaceShip &ship)
{
al_draw_filled_rectangle(ship.x, ship.y - 9, ship.x + 10, ship.y - 7, al_map_rgb(255, 0, 0));
al_draw_filled_rectangle(ship.x, ship.y + 9, ship.x + 10, ship.y + 7, al_map_rgb(255, 0, 0));
al_draw_filled_triangle(ship.x - 12, ship.y - 17, ship.x + 12, ship.y, ship.x - 12, ship.y + 17, al_map_rgb(0, 255, 0));
al_draw_filled_rectangle(ship.x - 12, ship.y - 2, ship.x + 15, ship.y + 2, al_map_rgb(0, 0, 255));
}
void MoveShipUp(SpaceShip &ship)
{
ship.y -= ship.speed;
if (ship.y < 0)
ship.y = 0;
}
void MoveShipDown(SpaceShip &ship)
{
ship.y += ship.speed;
if (ship.y > HEIGHT)
ship.y = HEIGHT;
}
void MoveShipLeft(SpaceShip &ship)
{
ship.x -= ship.speed;
if (ship.x < 0)
ship.x = 0;
}
void MoveShipRight(SpaceShip &ship)
{
ship.x += ship.speed;
if (ship.x > 300)
ship.x = 300;
}
void InitBullet(Bullet bullet[], int size)
{
for (int i = 0; i < size; i++)
{
bullet[i].ID = BULLET;
bullet[i].speed = 10;
bullet[i].live = false;
}
}
void DrawBullet(Bullet bullet[], int size)
{
for (int i = 0; i < size; i++)
{
if (bullet[i].live)
al_draw_filled_circle(bullet[i].x, bullet[i].y, 2, al_map_rgb(255, 255, 255));
}
}
void FireBullet(Bullet bullet[], int size, SpaceShip &ship)
{
for (int i = 0; i < size; i++)
{
if (!bullet[i].live)
{
bullet[i].x = ship.x + 17;
bullet[i].y = ship.y;
bullet[i].live = true;
break;
}
}
}
void UpdateBullet(Bullet bullet[], int size)
{
for (int i = 0; i < size; i++)
{
if (bullet[i].live)
{
bullet[i].x += bullet[i].speed;
if (bullet[i].x > WIDTH)
bullet[i].live = false;
}
}
}
void CollideBullet(Bullet bullet[], int bSize, Comet comets[], int cSize, SpaceShip &ship)
{
for (int i = 0; i < bSize; i++)
{
if (bullet[i].live)
{
for (int j = 0; j < cSize; j++)
{
if (comets[j].live)
{
if (bullet[i].x >(comets[j].x - comets[j].boundx) &&
bullet[i].x < (comets[j].x + comets[j].boundx) &&
bullet[i].y >(comets[j].y - comets[j].boundy) &&
bullet[i].y < (comets[j].y + comets[j].boundy))
{
bullet[i].live = false;
comets[j].live = false;
ship.score++;
}
}
}
}
}
}
void InitComet(Comet comets[], int size)
{
for (int i = 0; i < size; i++)
{
comets[i].ID = ENEMY;
comets[i].live = false;
comets[i].speed = 5;
comets[i].boundx = 18;
comets[i].boundy = 18;
}
}
void DrawComet(Comet comets[], int size)
{
for (int i = 0; i < size; i++)
{
if (comets[i].live)
{
al_draw_filled_circle(comets[i].x, comets[i].y, 20, al_map_rgb(255, 0, 0));
}
}
}
void StartComet(Comet comets[], int size)
{
for (int i = 0; i < size; i++)
{
if (!comets[i].live)
{
if (rand() % 500 == 0)
{
comets[i].live = true;
comets[i].x = WIDTH;
comets[i].y = 30 + rand() % (HEIGHT - 60);
break;
}
}
}
}
void UpdateComet(Comet comets[], int size)
{
for (int i = 0; i < size; i++)
{
if (comets[i].live)
{
comets[i].x -= comets[i].speed;
}
}
}
void CollideComet(Comet comets[], int cSize, SpaceShip &ship)
{
for (int i = 0; i < cSize; i++)
{
if (comets[i].live)
{
if (comets[i].x - comets[i].boundx < ship.x + ship.boundx &&
comets[i].x + comets[i].boundx > ship.x - ship.boundx &&
comets[i].y - comets[i].boundy < ship.y + ship.boundy &&
comets[i].y + comets[i].boundy > ship.y - ship.boundy)
{
ship.lives--;
comets[i].live = false;
}
else if (comets[i].x < 0)
{
comets[i].live = false;
ship.lives--;
}
}
}
}
</code></pre>
| 0debug |
Faster way to convert a vector of vectors to a single contiguous vector with opposite storage order : <p>I have a <code>std::vector<std::vector<double>></code> that I am trying to convert to a single contiguous vector as fast as possible. My vector has a shape of roughly <code>4000 x 50</code>. </p>
<p>The problem is, sometimes I need my output vector in column-major contiguous order (just concatenating the interior vectors of my 2d input vector), and sometimes I need my output vector in row-major contiguous order, effectively requiring a transpose. </p>
<p>I have found that a naive for loop is quite fast for conversion to a column-major vector:</p>
<pre><code>auto to_dense_column_major_naive(std::vector<std::vector<double>> const & vec)
-> std::vector<double>
{
auto n_col = vec.size();
auto n_row = vec[0].size();
std::vector<double> out_vec(n_col * n_row);
for (size_t i = 0; i < n_col; ++i)
for (size_t j = 0; j < n_row; ++j)
out_vec[i * n_row + j] = vec[i][j];
return out_vec;
}
</code></pre>
<p>But obviously a similar approach is very slow for row-wise conversion, because of all of the cache misses. So for row-wise conversion, I thought a blocking strategy to promote cache locality might be my best bet:</p>
<pre><code>auto to_dense_row_major_blocking(std::vector<std::vector<double>> const & vec)
-> std::vector<double>
{
auto n_col = vec.size();
auto n_row = vec[0].size();
std::vector<double> out_vec(n_col * n_row);
size_t block_side = 8;
for (size_t l = 0; l < n_col; l += block_side) {
for (size_t k = 0; k < n_row; k += block_side) {
for (size_t j = l; j < l + block_side && j < n_col; ++j) {
auto const &column = vec[j];
for (size_t i = k; i < k + block_side && i < n_row; ++i)
out_vec[i * n_col + j] = column[i];
}
}
}
return out_vec;
}
</code></pre>
<p>This is considerably faster than a naive loop for row-major conversion, but still almost an order of magnitude slower than naive column-major looping on my input size. </p>
<p><a href="https://i.stack.imgur.com/YfgCj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YfgCj.png" alt="enter image description here"></a></p>
<p><strong>My question is</strong>, is there a faster approach to converting a (column-major) vector of vectors of doubles to a single contiguous row-major vector? I am struggling to reason about what the limit of speed of this code should be, and am thus questioning whether I'm missing something obvious. My assumption was that blocking would give me a <em>much</em> larger speedup then it appears to actually give. </p>
<hr>
<p>The chart was generated using QuickBench (and somewhat verified with GBench locally on my machine) with this code: (Clang 7, C++20, -O3)</p>
<pre><code>auto to_dense_column_major_naive(std::vector<std::vector<double>> const & vec)
-> std::vector<double>
{
auto n_col = vec.size();
auto n_row = vec[0].size();
std::vector<double> out_vec(n_col * n_row);
for (size_t i = 0; i < n_col; ++i)
for (size_t j = 0; j < n_row; ++j)
out_vec[i * n_row + j] = vec[i][j];
return out_vec;
}
auto to_dense_row_major_naive(std::vector<std::vector<double>> const & vec)
-> std::vector<double>
{
auto n_col = vec.size();
auto n_row = vec[0].size();
std::vector<double> out_vec(n_col * n_row);
for (size_t i = 0; i < n_col; ++i)
for (size_t j = 0; j < n_row; ++j)
out_vec[j * n_col + i] = vec[i][j];
return out_vec;
}
auto to_dense_row_major_blocking(std::vector<std::vector<double>> const & vec)
-> std::vector<double>
{
auto n_col = vec.size();
auto n_row = vec[0].size();
std::vector<double> out_vec(n_col * n_row);
size_t block_side = 8;
for (size_t l = 0; l < n_col; l += block_side) {
for (size_t k = 0; k < n_row; k += block_side) {
for (size_t j = l; j < l + block_side && j < n_col; ++j) {
auto const &column = vec[j];
for (size_t i = k; i < k + block_side && i < n_row; ++i)
out_vec[i * n_col + j] = column[i];
}
}
}
return out_vec;
}
auto to_dense_column_major_blocking(std::vector<std::vector<double>> const & vec)
-> std::vector<double>
{
auto n_col = vec.size();
auto n_row = vec[0].size();
std::vector<double> out_vec(n_col * n_row);
size_t block_side = 8;
for (size_t l = 0; l < n_col; l += block_side) {
for (size_t k = 0; k < n_row; k += block_side) {
for (size_t j = l; j < l + block_side && j < n_col; ++j) {
auto const &column = vec[j];
for (size_t i = k; i < k + block_side && i < n_row; ++i)
out_vec[j * n_row + i] = column[i];
}
}
}
return out_vec;
}
auto make_vecvec() -> std::vector<std::vector<double>>
{
std::vector<std::vector<double>> vecvec(50, std::vector<double>(4000));
std::mt19937 mersenne {2019};
std::uniform_real_distribution<double> dist(-1000, 1000);
for (auto &vec: vecvec)
for (auto &val: vec)
val = dist(mersenne);
return vecvec;
}
static void NaiveColumnMajor(benchmark::State& state) {
// Code before the loop is not measured
auto vecvec = make_vecvec();
for (auto _ : state) {
benchmark::DoNotOptimize(to_dense_column_major_naive(vecvec));
}
}
BENCHMARK(NaiveColumnMajor);
static void NaiveRowMajor(benchmark::State& state) {
// Code before the loop is not measured
auto vecvec = make_vecvec();
for (auto _ : state) {
benchmark::DoNotOptimize(to_dense_row_major_naive(vecvec));
}
}
BENCHMARK(NaiveRowMajor);
static void BlockingRowMajor(benchmark::State& state) {
// Code before the loop is not measured
auto vecvec = make_vecvec();
for (auto _ : state) {
benchmark::DoNotOptimize(to_dense_row_major_blocking(vecvec));
}
}
BENCHMARK(BlockingRowMajor);
static void BlockingColumnMajor(benchmark::State& state) {
// Code before the loop is not measured
auto vecvec = make_vecvec();
for (auto _ : state) {
benchmark::DoNotOptimize(to_dense_column_major_blocking(vecvec));
}
}
BENCHMARK(BlockingColumnMajor);
</code></pre>
| 0debug |
static av_cold int yop_decode_init(AVCodecContext *avctx)
{
YopDecContext *s = avctx->priv_data;
s->avctx = avctx;
if (avctx->width & 1 || avctx->height & 1 ||
av_image_check_size(avctx->width, avctx->height, 0, avctx) < 0) {
av_log(avctx, AV_LOG_ERROR, "YOP has invalid dimensions\n");
return -1;
avctx->pix_fmt = PIX_FMT_PAL8;
avcodec_get_frame_defaults(&s->frame);
s->num_pal_colors = avctx->extradata[0];
s->first_color[0] = avctx->extradata[1];
s->first_color[1] = avctx->extradata[2];
if (s->num_pal_colors + s->first_color[0] > 256 ||
s->num_pal_colors + s->first_color[1] > 256) {
av_log(avctx, AV_LOG_ERROR,
"YOP: palette parameters invalid, header probably corrupt\n");
return 0; | 1threat |
void helper_sysret(int dflag)
{
int cpl, selector;
if (!(env->efer & MSR_EFER_SCE)) {
raise_exception_err(EXCP06_ILLOP, 0);
}
cpl = env->hflags & HF_CPL_MASK;
if (!(env->cr[0] & CR0_PE_MASK) || cpl != 0) {
raise_exception_err(EXCP0D_GPF, 0);
}
selector = (env->star >> 48) & 0xffff;
if (env->hflags & HF_LMA_MASK) {
if (dflag == 2) {
cpu_x86_load_seg_cache(env, R_CS, (selector + 16) | 3,
0, 0xffffffff,
DESC_G_MASK | DESC_P_MASK |
DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |
DESC_L_MASK);
env->eip = ECX;
} else {
cpu_x86_load_seg_cache(env, R_CS, selector | 3,
0, 0xffffffff,
DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
env->eip = (uint32_t)ECX;
}
cpu_x86_load_seg_cache(env, R_SS, selector + 8,
0, 0xffffffff,
DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
DESC_W_MASK | DESC_A_MASK);
load_eflags((uint32_t)(env->regs[11]), TF_MASK | AC_MASK | ID_MASK |
IF_MASK | IOPL_MASK | VM_MASK | RF_MASK | NT_MASK);
cpu_x86_set_cpl(env, 3);
} else {
cpu_x86_load_seg_cache(env, R_CS, selector | 3,
0, 0xffffffff,
DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
env->eip = (uint32_t)ECX;
cpu_x86_load_seg_cache(env, R_SS, selector + 8,
0, 0xffffffff,
DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
DESC_W_MASK | DESC_A_MASK);
env->eflags |= IF_MASK;
cpu_x86_set_cpl(env, 3);
}
#ifdef CONFIG_KQEMU
if (kqemu_is_ok(env)) {
if (env->hflags & HF_LMA_MASK)
CC_OP = CC_OP_EFLAGS;
env->exception_index = -1;
cpu_loop_exit();
}
#endif
}
| 1threat |
How can I assign a color to a font in EPPlus? : <p>I can set the background color of a cell or range of cells like so:</p>
<pre><code>rowRngprogramParamsRange.Style.Fill.PatternType = ExcelFillStyle.Solid;
rowRngprogramParamsRange.Style.Fill.BackgroundColor.SetColor(Color.DarkRed);
</code></pre>
<p>I have not been able to set the font color, though. I tried this:</p>
<pre><code>rowRngprogramParamsRange.Style.Font.Color = Color.Red;
</code></pre>
<p>...which failed to compile with two err msgs: the first, that I cannot assign System.Drawing.Color to OfficeOpenXml.Style.ExcelColor, and the second that the property is readonly anyway.</p>
<p>Just for grin and bear its, I tried casting the value:</p>
<pre><code>rowRngprogramParamsRange.Style.Font.Color = (OfficeOpenXml.Style.ExcelColor)Color.Red;
</code></pre>
<p>...and I now get, "<em>Cannot convert type 'System.Drawing.Color' to 'OfficeOpenXml.Style.ExcelColor'</em>"</p>
<p>Most everything in EPPlus is pretty easy, certainly easier than Excel Interop, but this one has me baffled. How <em>does</em> one assign a color to a font for a range in EPPlus?</p>
| 0debug |
jquery data when element has children : suppose I have in html
<li class="media_item upload" data-actions-permissions="{}" data-info="{}">
<p></p>
</li>
how do I get the `data-info`?
What i know is if I have
<li class="media_item upload" data-actions-permissions="{}" data-info="{}">
</li>
I can use `$(".media_item.upload").data("info")` | 0debug |
What does ampersand & do in a function name? : <p>I understand that having an ampersand before declaring a variable in a function is a call by reference, and it will modify variable i created in my <code>main</code> function.</p>
<pre><code>int my_func(int &my_var){
my_var += 9;
return my_var;
}
int main(void){
int some_var = 1;
my_func(some_var); // value of some_var is now 10
return 0;
</code></pre>
<p>However, what does an ampersand before a function name do? For example</p>
<pre><code>int &my_func(int &my_var){
my_var +=9;
return my_var;
}
</code></pre>
| 0debug |
def new_tuple(test_list, test_str):
res = tuple(test_list + [test_str])
return (res) | 0debug |
python statement with or inside bracket : This is a code snippet I pasted from a setup.py python file. I am new to python and don't understand this `build_args` variable. Could someone give me some explanation for that?
build_args = [NINJA or MAKE]
# control the number of concurrent jobs
if self.jobs is not None:
build_args.extend(['-j', str(self.jobs)])
subprocess.check_call(build_args) | 0debug |
HTML How to turn a link into a button : <a href="#">
<div class="col-md-4 promo-item item-1">
<h3>
Unleash
</h3>
</div>
</a>
I got a template online, the above (with css/bootstrap?), is an image that is a link. I want to change it so that instead of a link (href), its a clickable button.
My plan is for the button to use javascript to change some of the content on the page, basing it off the javascript below;
<button type="button" onclick="document.getElementById('demo').innerHTML='Hello JavaScript!' ">Click Me!</button>
So how do i change this href into a button?? | 0debug |
static void usage(void)
{
printf("Escape an input string, adopting the av_get_token() escaping logic\n");
printf("usage: ffescape [OPTIONS]\n");
printf("\n"
"Options:\n"
"-e echo each input line on output\n"
"-h print this help\n"
"-i INFILE set INFILE as input file, stdin if omitted\n"
"-l LEVEL set the number of escaping levels, 1 if omitted\n"
"-m ESCAPE_MODE select escape mode between 'full', 'lazy', 'quote', default is 'lazy'\n"
"-o OUTFILE set OUTFILE as output file, stdout if omitted\n"
"-p PROMPT set output prompt, is '=> ' by default\n"
"-s SPECIAL_CHARS set the list of special characters\n");
}
| 1threat |
search many min in java : <p>i'm newbie in java. i have problem search many min in java.
i have a big data. but example data like this.</p>
<pre><code> k[][] = [74 85 123
73 84 122
72 83 121
70 81 119
69 80 118
76 87 125
77 88 126
78 89 127];
</code></pre>
<p>and i want output like this.</p>
<pre><code>min1 = 69 min1 = 80 min1 = 118
min2 = 70 min2 = 81 min2 = 119
min3 = 72 min3 = 83 min3 = 121
</code></pre>
<p>i use sorting in this data but the results it's not eficient.
someone help me
thx</p>
| 0debug |
static int vivo_probe(AVProbeData *p)
{
const unsigned char *buf = p->buf;
unsigned c, length = 0;
if (*buf++ != 0)
return 0;
c = *buf++;
length = c & 0x7F;
if (c & 0x80) {
c = *buf++;
length = (length << 7) | (c & 0x7F);
}
if (c & 0x80 || length > 1024 || length < 21)
return 0;
if (memcmp(buf, "\r\nVersion:Vivo/", 15))
return 0;
buf += 15;
if (*buf < '0' && *buf > '2')
return 0;
return AVPROBE_SCORE_MAX;
}
| 1threat |
static void vfio_realize(PCIDevice *pdev, Error **errp)
{
VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
VFIODevice *vbasedev_iter;
VFIOGroup *group;
char *tmp, group_path[PATH_MAX], *group_name;
Error *err = NULL;
ssize_t len;
struct stat st;
int groupid;
int i, ret;
if (!vdev->vbasedev.sysfsdev) {
if (!(~vdev->host.domain || ~vdev->host.bus ||
~vdev->host.slot || ~vdev->host.function)) {
error_setg(errp, "No provided host device");
error_append_hint(errp, "Use -vfio-pci,host=DDDD:BB:DD.F "
"or -vfio-pci,sysfsdev=PATH_TO_DEVICE\n");
return;
}
vdev->vbasedev.sysfsdev =
g_strdup_printf("/sys/bus/pci/devices/%04x:%02x:%02x.%01x",
vdev->host.domain, vdev->host.bus,
vdev->host.slot, vdev->host.function);
}
if (stat(vdev->vbasedev.sysfsdev, &st) < 0) {
error_setg_errno(errp, errno, "no such host device");
error_prepend(errp, ERR_PREFIX, vdev->vbasedev.sysfsdev);
return;
}
vdev->vbasedev.name = g_strdup(basename(vdev->vbasedev.sysfsdev));
vdev->vbasedev.ops = &vfio_pci_ops;
vdev->vbasedev.type = VFIO_DEVICE_TYPE_PCI;
tmp = g_strdup_printf("%s/iommu_group", vdev->vbasedev.sysfsdev);
len = readlink(tmp, group_path, sizeof(group_path));
g_free(tmp);
if (len <= 0 || len >= sizeof(group_path)) {
error_setg_errno(errp, len < 0 ? errno : ENAMETOOLONG,
"no iommu_group found");
goto error;
}
group_path[len] = 0;
group_name = basename(group_path);
if (sscanf(group_name, "%d", &groupid) != 1) {
error_setg_errno(errp, errno, "failed to read %s", group_path);
goto error;
}
trace_vfio_realize(vdev->vbasedev.name, groupid);
group = vfio_get_group(groupid, pci_device_iommu_address_space(pdev), errp);
if (!group) {
goto error;
}
QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
if (strcmp(vbasedev_iter->name, vdev->vbasedev.name) == 0) {
error_setg(errp, "device is already attached");
vfio_put_group(group);
goto error;
}
}
ret = vfio_get_device(group, vdev->vbasedev.name, &vdev->vbasedev, errp);
if (ret) {
vfio_put_group(group);
goto error;
}
vfio_populate_device(vdev, &err);
if (err) {
error_propagate(errp, err);
goto error;
}
ret = pread(vdev->vbasedev.fd, vdev->pdev.config,
MIN(pci_config_size(&vdev->pdev), vdev->config_size),
vdev->config_offset);
if (ret < (int)MIN(pci_config_size(&vdev->pdev), vdev->config_size)) {
ret = ret < 0 ? -errno : -EFAULT;
error_setg_errno(errp, -ret, "failed to read device config space");
goto error;
}
vdev->emulated_config_bits = g_malloc0(vdev->config_size);
memset(vdev->emulated_config_bits + PCI_ROM_ADDRESS, 0xff, 4);
if (vdev->vendor_id != PCI_ANY_ID) {
if (vdev->vendor_id >= 0xffff) {
error_setg(errp, "invalid PCI vendor ID provided");
goto error;
}
vfio_add_emulated_word(vdev, PCI_VENDOR_ID, vdev->vendor_id, ~0);
trace_vfio_pci_emulated_vendor_id(vdev->vbasedev.name, vdev->vendor_id);
} else {
vdev->vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
}
if (vdev->device_id != PCI_ANY_ID) {
if (vdev->device_id > 0xffff) {
error_setg(errp, "invalid PCI device ID provided");
goto error;
}
vfio_add_emulated_word(vdev, PCI_DEVICE_ID, vdev->device_id, ~0);
trace_vfio_pci_emulated_device_id(vdev->vbasedev.name, vdev->device_id);
} else {
vdev->device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
}
if (vdev->sub_vendor_id != PCI_ANY_ID) {
if (vdev->sub_vendor_id > 0xffff) {
error_setg(errp, "invalid PCI subsystem vendor ID provided");
goto error;
}
vfio_add_emulated_word(vdev, PCI_SUBSYSTEM_VENDOR_ID,
vdev->sub_vendor_id, ~0);
trace_vfio_pci_emulated_sub_vendor_id(vdev->vbasedev.name,
vdev->sub_vendor_id);
}
if (vdev->sub_device_id != PCI_ANY_ID) {
if (vdev->sub_device_id > 0xffff) {
error_setg(errp, "invalid PCI subsystem device ID provided");
goto error;
}
vfio_add_emulated_word(vdev, PCI_SUBSYSTEM_ID, vdev->sub_device_id, ~0);
trace_vfio_pci_emulated_sub_device_id(vdev->vbasedev.name,
vdev->sub_device_id);
}
vdev->emulated_config_bits[PCI_HEADER_TYPE] =
PCI_HEADER_TYPE_MULTI_FUNCTION;
if (vdev->pdev.cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
vdev->pdev.config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
} else {
vdev->pdev.config[PCI_HEADER_TYPE] &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
}
memset(&vdev->pdev.config[PCI_BASE_ADDRESS_0], 0, 24);
memset(&vdev->pdev.config[PCI_ROM_ADDRESS], 0, 4);
vfio_pci_size_rom(vdev);
vfio_msix_early_setup(vdev, &err);
if (err) {
error_propagate(errp, err);
goto error;
}
vfio_bars_setup(vdev);
ret = vfio_add_capabilities(vdev, errp);
if (ret) {
goto out_teardown;
}
if (vdev->vga) {
vfio_vga_quirk_setup(vdev);
}
for (i = 0; i < PCI_ROM_SLOT; i++) {
vfio_bar_quirk_setup(vdev, i);
}
if (!vdev->igd_opregion &&
vdev->features & VFIO_FEATURE_ENABLE_IGD_OPREGION) {
struct vfio_region_info *opregion;
if (vdev->pdev.qdev.hotplugged) {
error_setg(errp,
"cannot support IGD OpRegion feature on hotplugged "
"device");
goto out_teardown;
}
ret = vfio_get_dev_region_info(&vdev->vbasedev,
VFIO_REGION_TYPE_PCI_VENDOR_TYPE | PCI_VENDOR_ID_INTEL,
VFIO_REGION_SUBTYPE_INTEL_IGD_OPREGION, &opregion);
if (ret) {
error_setg_errno(errp, -ret,
"does not support requested IGD OpRegion feature");
goto out_teardown;
}
ret = vfio_pci_igd_opregion_init(vdev, opregion, errp);
g_free(opregion);
if (ret) {
goto out_teardown;
}
}
if (pdev->cap_present & QEMU_PCI_CAP_MSIX) {
memset(vdev->emulated_config_bits + pdev->msix_cap, 0xff,
MSIX_CAP_LENGTH);
}
if (pdev->cap_present & QEMU_PCI_CAP_MSI) {
memset(vdev->emulated_config_bits + pdev->msi_cap, 0xff,
vdev->msi_cap_size);
}
if (vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1)) {
vdev->intx.mmap_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,
vfio_intx_mmap_enable, vdev);
pci_device_set_intx_routing_notifier(&vdev->pdev, vfio_intx_update);
ret = vfio_intx_enable(vdev, errp);
if (ret) {
goto out_teardown;
}
}
vfio_register_err_notifier(vdev);
vfio_register_req_notifier(vdev);
vfio_setup_resetfn_quirk(vdev);
return;
out_teardown:
pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
vfio_teardown_msi(vdev);
vfio_bars_exit(vdev);
error:
error_prepend(errp, ERR_PREFIX, vdev->vbasedev.name);
}
| 1threat |
Primary Key and Natural Join : If I perform A naturalJoin B, where:
A's schema is: (aID), where aID is a primary key.
B's schema is: (aID,bID), where aID,bID are a composite primary key.
Would performing the natural join work in this case? Or is it necessary for A to
have both aID and bID for this to work. | 0debug |
Capture only ssl handshake with tcpdump : <p>I have a server to which many clients connect using SSL. Recently I'm observing SSL handshake errors in the server logs (ex SSL MAC error). The error itself is not important, but I want to see why some clients are able to connect while others are failing, and also need to identify which clients are failing.</p>
<p>For debugging this issue, I want to capture all SSL handshakes happening at server and since I don't know when the problematic clients connect, I don't want to capture all the traffic till that happens. I just want to capture all the SSL handshakes and later analyze them with Wireshark. Assume that I only have access to tcpdump and no other tools for capturing.</p>
| 0debug |
int virtio_set_status(VirtIODevice *vdev, uint8_t val)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
trace_virtio_set_status(vdev, val);
if (virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
if (!(vdev->status & VIRTIO_CONFIG_S_FEATURES_OK) &&
val & VIRTIO_CONFIG_S_FEATURES_OK) {
int ret = virtio_validate_features(vdev);
if (ret) {
return ret;
}
}
}
if (k->set_status) {
k->set_status(vdev, val);
}
vdev->status = val;
return 0;
}
| 1threat |
static BlockDriverAIOCB *raw_aio_submit(BlockDriverState *bs,
int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
BlockDriverCompletionFunc *cb, void *opaque, int type)
{
BDRVRawState *s = bs->opaque;
if (fd_open(bs) < 0)
return NULL;
if ((bs->open_flags & BDRV_O_NOCACHE)) {
if (!qiov_is_aligned(bs, qiov)) {
type |= QEMU_AIO_MISALIGNED;
#ifdef CONFIG_LINUX_AIO
} else if (s->use_aio) {
return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
nb_sectors, cb, opaque, type);
#endif
}
}
return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
cb, opaque, type);
}
| 1threat |
ImportError: No module named timeutils : <p>I trying to follow tutorial install of django-celery. After install i need run migrate to make the necessary tables but appears that error:</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/guilherme/.virtualenvs/martizi-api/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/home/guilherme/.virtualenvs/martizi-api/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute
django.setup()
File "/home/guilherme/.virtualenvs/martizi-api/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/guilherme/.virtualenvs/martizi-api/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/guilherme/.virtualenvs/martizi-api/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/guilherme/.virtualenvs/martizi-api/local/lib/python2.7/site-packages/djcelery/models.py", line 15, in <module>
from celery.utils.timeutils import timedelta_seconds
ImportError: No module named timeutils
</code></pre>
<p>im not finding anything about this timeutils on web</p>
<p>im using:</p>
<p>django==1.9.8
django-celery==3.1.17</p>
<p>Thanks!</p>
| 0debug |
static int ssi_sd_load(QEMUFile *f, void *opaque, int version_id)
{
SSISlave *ss = SSI_SLAVE(opaque);
ssi_sd_state *s = (ssi_sd_state *)opaque;
int i;
if (version_id != 1)
s->mode = qemu_get_be32(f);
s->cmd = qemu_get_be32(f);
for (i = 0; i < 4; i++)
s->cmdarg[i] = qemu_get_be32(f);
for (i = 0; i < 5; i++)
s->response[i] = qemu_get_be32(f);
s->arglen = qemu_get_be32(f);
s->response_pos = qemu_get_be32(f);
s->stopping = qemu_get_be32(f);
ss->cs = qemu_get_be32(f);
return 0;
| 1threat |
static void test_ivshmem_memdev(void)
{
IVState state;
setup_vm_cmd(&state, "-object memory-backend-ram,size=1M,id=mb1"
" -device ivshmem,x-memdev=mb1", false);
qtest_quit(state.qtest);
}
| 1threat |
What is wrong with my Blackjack game code? : <p>The code works mostly well, however, after trying the play again command I made it exits the program and doesn't cycle as expected. The code causing issues is below.</p>
<pre><code>play_again = 'y' or 'n'
draw_again = 'hit' or 'hold'
print("This is a simple game of blackjack. The main objective is to stay under or equal to 21 in value.")
print("Number cards are worth their number. Face cards are worth 11. Aces are worth either 1 or 11")
print("If you want to draw again type hit. To finish type hold.")
play_game = input("would you like to play? (y/n):")
if play_game == 'y':
shuffleDeck()
print ("your starting hand is")
drawFaceUp()
drawFaceUp()
draw_again = input("hit, or hold (hit/hold):")
while draw_again == 'hit':
print("your next card is")
drawFaceUp()
draw_again = input("hit, or hold (hit/hold):")
if draw_again == 'hold':
score = input("Enter your score <score number>:")
if score <= '15':
print("good job, but try and get a little closer to 21 next time")
play_again = input("Play again? (y/n):")
if play_again == 'y':
newDeck()
shuffleDeck()
print ("your starting hand is")
drawFaceUp()
drawFaceUp()
draw_again = input("hit, or hold (hit/hold):")
while draw_again == 'hit':
print("your next card is")
drawFaceUp()
draw_again = input("hit, or hold (hit/hold):")
if draw_again == 'hold':
score = input("Enter your score <score number>:")
elif play_again == 'n':
print ("end of program")
elif score > '15' and score < '21':
print("Nice. you should test you luck again.")
play_again = input("Play again? (y/n):")
if play_again == 'y':
newDeck()
shuffleDeck()
print ("your starting hand is")
drawFaceUp()
drawFaceUp()
draw_again = input("hit, or hold (hit/hold):")
while draw_again == 'hit':
print("your next card is")
drawFaceUp()
draw_again = input("hit, or hold (hit/hold):")
if draw_again == 'hold':
score = input("Enter your score <score number>:")
elif play_again == 'n':
print("end of program")
elif score == '21':
print("you got a perfect score. see if you can do it again.")
play_again = input("Play again? (y/n):")
if play_again == 'y':
newDeck()
shuffleDeck()
print ("your starting hand is")
drawFaceUp()
drawFaceUp()
draw_again = input("hit, or hold (hit/hold):")
while draw_again == 'hit':
print("your next card is")
drawFaceUp()
draw_again = input("hit, or hold (hit/hold):")
if draw_again == 'hold':
score = input("Enter your score <score number>:")
elif play_again == 'n':
print("end of program")
elif play_game == 'n':
print("end of program")
</code></pre>
<p>I expect the game to be able to endlessly cycle until told not to. the actual output causes the game to close after 2 rounds of playing.</p>
| 0debug |
Codeigniter Where_In Operator Does Return Any Result : <p>I'm using Codeigniter to query a list of result by passing Array into the modal. But the return result alway empty. I had checked and try to a few method that i found on stackoverflow but none of it work.</p>
<p>Eg.
Array
(
[0] => 12
[1] => 13
)</p>
<p>My code :</p>
<pre><code><?php
ini_set('max_execution_time', 0);
ini_set('memory_limit','2048M');
defined('BASEPATH') OR exit('No direct script access allowed');
class Sms_model extends CI_Model
{
//Return Selected Customer ID
public function getCustomerInfo($data){
$ids = array();
foreach ($data['customerID'] as $id)
{
$ids[] = $id;
}
print_r($ids);
$this->db->select('Handphone');
$this->db->from('tblcustomer');
$this->db->where_in('CustomerID', $ids);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
}
else {
return false;
}
}
}
</code></pre>
<p>What did i do wrong on the query?
Please guide me, thanks</p>
| 0debug |
static void gen_jumpi(DisasContext *dc, uint32_t dest, int slot)
{
TCGv_i32 tmp = tcg_const_i32(dest);
if (((dc->pc ^ dest) & TARGET_PAGE_MASK) != 0) {
slot = -1;
}
gen_jump_slot(dc, tmp, slot);
tcg_temp_free(tmp);
}
| 1threat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.