problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
please help me ti fix this ...I want to remove these untracked files .....help me how to remove this? : [enter image description here][1]
[1]: https://i.stack.imgur.com/j8QR6.png
These only showing me permission denied and I am unable to remove this bug......please help me
I used git clean -n command to remove this but it's not working.
| 0debug |
UNIX: Too many spaces : I have code with two variables in echo. I don't know why it prints before $AEXT spaces even though I have just one space in code.
echo " Average file size .$ext: $AEXT"
Files .tar: 1 | 0debug |
how to store distance and time to reach between two location in Sqlite Database when open Google Map from An App using Intent in Android : how to parse and store distance and time to reach in SQlite Database in Android when open Google Map from using intent showing route and distance Automatically by navigating between two points.
| 0debug |
sort a string array by first two characters in swift : <p>I have a string array as strList = ["12abc", "23bcd", "12shsh", "23xyz"]
Is there any way to sort the array according to just first two characters of each string?</p>
| 0debug |
use node-redis with node 8 util.promisify : <p>node -v : 8.1.2</p>
<p>I use redis client <a href="https://github.com/NodeRedis/node_redis" rel="noreferrer">node_redis</a> with node 8 util.promisify , no blurbird. </p>
<p>the callback redis.get is ok, but promisify type get error message</p>
<blockquote>
<p>TypeError: Cannot read property 'internal_send_command' of undefined<br>
at get (D:\Github\redis-test\node_modules\redis\lib\commands.js:62:24)<br>
at get (internal/util.js:229:26)<br>
at D:\Github\redis-test\app.js:23:27<br>
at Object. (D:\Github\redis-test\app.js:31:3)<br>
at Module._compile (module.js:569:30)<br>
at Object.Module._extensions..js (module.js:580:10)<br>
at Module.load (module.js:503:32)<br>
at tryModuleLoad (module.js:466:12)<br>
at Function.Module._load (module.js:458:3)<br>
at Function.Module.runMain (module.js:605:10) </p>
</blockquote>
<p>my test code</p>
<pre><code>const util = require('util');
var redis = require("redis"),
client = redis.createClient({
host: "192.168.99.100",
port: 32768,
});
let get = util.promisify(client.get);
(async function () {
client.set(["aaa", JSON.stringify({
A: 'a',
B: 'b',
C: "C"
})]);
client.get("aaa", (err, value) => {
console.log(`use callback: ${value}`);
});
try {
let value = await get("aaa");
console.log(`use promisify: ${value}`);
} catch (e) {
console.log(`promisify error:`);
console.log(e);
}
client.quit();
})()
</code></pre>
| 0debug |
Nginx - Allowing origin IP : <p>Nginx supports <code>allow</code> and <code>deny</code> syntax to restrict IPs, e.g. <code>allow 192.168.1.1;</code>. But if traffic goes through a reverse proxy, the IP will refer to the proxy's IP. So how can it be configured to whitelist a specific origin IP and deny all other incoming requests?</p>
| 0debug |
void smbios_add_field(int type, int offset, const void *data, size_t len)
{
struct smbios_field *field;
smbios_check_collision(type, SMBIOS_FIELD_ENTRY);
if (!smbios_entries) {
smbios_entries_len = sizeof(uint16_t);
smbios_entries = g_malloc0(smbios_entries_len);
}
smbios_entries = g_realloc(smbios_entries, smbios_entries_len +
sizeof(*field) + len);
field = (struct smbios_field *)(smbios_entries + smbios_entries_len);
field->header.type = SMBIOS_FIELD_ENTRY;
field->header.length = cpu_to_le16(sizeof(*field) + len);
field->type = type;
field->offset = cpu_to_le16(offset);
memcpy(field->data, data, len);
smbios_entries_len += sizeof(*field) + len;
(*(uint16_t *)smbios_entries) =
cpu_to_le16(le16_to_cpu(*(uint16_t *)smbios_entries) + 1);
}
| 1threat |
solve 3 equation dependency variables by c++ : i tried to solve 3 pde equations by using FD method in c++, but i do not know why i got half of the exact answer at all time. these equations are dependency variable.
if(g[i][k][j]!=g[k][i][j] && i!=k)
u[i][k][j+1]=u[i][k][j]*(1.0 - 2.0*dt)
+(dt/(dx*dx))*(g[i+1][k][j]- 2.0*g[i][k][j]+g[i-1][k][j])
+(dt/(dx*dx))*(g[k+1][i][j]- 2.0*g[k][i][j]+g[k-1][i][j])
+(dt/(dy*dy))*(g[i][k+1][j]-2.0*g[i][k][j]+g[i][k-1][j])
+(dt/(dy*dy))*(g[k][i+1][j]-2.0*g[k][i][j]+g[k][i-1][j]);
g[i][k][j+1]=g[i][k][j]*(1 - dt)
+dt*u[i][k][j]
+(dt/(dy*dy))*(v[i][k+1][j]-2*v[i][k][j]+v[i][k-1][j])
+(dt/(dx*dx))*(v[i+1][k][j]-2*v[i][k][j]+v[i-1][k][j]);
v[i][k][j+1]=v[i][k][j]+(g[k][i][j] + g[i][k][j])*dt;
| 0debug |
angular2 - How do 'imports' and 'exports' work in Angular2 modules? : <p>I am completely new to Angular2 and it has been very difficult to understand what is going on with the <code>@NgModule</code> <strong>imports and exports in Angular2.</strong></p>
<p>Take the following code for example-:</p>
<pre><code>@NgModule({
imports: [
RouterModule.forChild(heroesRoutes)
],
exports: [
RouterModule
]
})
</code></pre>
<p>In the imports section <strong>what am I importing ?</strong> <em>The router module , or the forChild() function, or the module returned by the function forChild() ?</em>
Which one is it ?</p>
<p>Also when I export the <code>RouterModule</code> again, the <a href="https://angular.io/docs/ts/latest/guide/router.html#!#routing-module" rel="noreferrer">documentation</a> says the following-:</p>
<blockquote>
<p>Our last step is to re-export the RouterModule. By re-exporting the
RouterModule, our feature module will be provided with the Router
Directives when using our Routing Module.</p>
</blockquote>
<p><strong>So does that mean that whatever module imports the above NgModule, will have access to all the code in the RouterModule ?</strong> </p>
<p>Is it sort of like if I write a custom header file in C that includes math.h, if I now use that header file I no longer need to include math.h in my programme separately. <em>Is my analogy correct ?</em></p>
<p>Can someone explain the core concepts here, so that I don't get stumped every time I see new code.</p>
| 0debug |
How to display partial text from a MySQL column in PHP : <p>I have this table <code>plans</code></p>
<pre><code>id| plan_name| description
1 | basic | Good plan for startups <br>
Excellent quality <br>
Lorem ipsum Lorem
</code></pre>
<p>I would like to <code>echo</code> only the first two lines from the <code>description</code> column using a query in PHP.</p>
<p><strong>Query</strong></p>
<pre><code> $getuserplaninfo=mysqli_query($db, "SELECT * FROM plans WHERE membershipID='$userplanID'");
$userplaninforesults=mysqli_fetch_assoc($getuserplaninfo);
$userplaninfo=$userplaninforesults['description'];
echo $userplaninfo;
</code></pre>
<p><strong>Results should be</strong></p>
<pre><code>Good plan for startups
Excellent quality
</code></pre>
| 0debug |
static uint64_t getSSD(uint8_t *src1, uint8_t *src2, int stride1, int stride2, int w, int h){
int x,y;
uint64_t ssd=0;
for(y=0; y<h; y++){
for(x=0; x<w; x++){
int d= src1[x + y*stride1] - src2[x + y*stride2];
ssd+= d*d;
}
}
return ssd;
}
| 1threat |
I want to read text from motor plate image : <p>I have develop OCR Demo app using tessaract library its giving 100% result from image which keep simple text.but i want to read text from motor plate image.
if any one knows please help me.
<a href="https://i.stack.imgur.com/q2buH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q2buH.png" alt="i want to read text from this image"></a></p>
| 0debug |
static int img_open_password(BlockBackend *blk, const char *filename,
int flags, bool quiet)
{
BlockDriverState *bs;
char password[256];
bs = blk_bs(blk);
if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
!(flags & BDRV_O_NO_IO)) {
qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
if (qemu_read_password(password, sizeof(password)) < 0) {
error_report("No password given");
return -1;
}
if (bdrv_set_key(bs, password) < 0) {
error_report("invalid password");
return -1;
}
}
return 0;
}
| 1threat |
def mul_consecutive_nums(nums):
result = [b*a for a, b in zip(nums[:-1], nums[1:])]
return result | 0debug |
Is there an easy way to check if an object is JSON serializable in python? : <p>I was trying to check if objects were JSON serializable or not because I had a dictionary that had a bunch of things and at this point its just easier to loop through its keys and find if they are JSON serializable and remove them. Something like (though this checks if its function):</p>
<pre><code>def remove_functions_from_dict(arg_dict):
'''
Removes functions from dictionary and returns modified dictionary
'''
keys_to_delete = []
for key,value in arg_dict.items():
if hasattr(value, '__call__'):
keys_to_delete.append(key)
for key in keys_to_delete:
del arg_dict[key]
return arg_dict
</code></pre>
<p>is there a way that the if statement instead check for JSON serializable objects and deletes them from the dictionary in a similar way to above?</p>
| 0debug |
Play sound on hover that works for mobile? : Hello i am looking for a solution that will allow me to play a sound file when hovering an image.
i see a lot of solutions for desktop view but nothing that works on mobile for the popular browsers.
I tested this tutorial:
http://middleearmedia.com/demos/webaudio/playsoundbuffer.html
And also this one:
http://allwebco-templates.com/support/S_audio_onmouseover.htm
And also this:
https://stackoverflow.com/questions/27936837/play-sound-on-hover-with-image
B
ut none of then allow me to hover on cheome mobile, it just marks the image but the sound dosn't play.
Any solution on this matter ?
Shis is my site:
http://www.tenehealth.info/
You can see the mobile hovering works on desktop | 0debug |
Sqlsrv for PHP 5.6 on WAMP server : <p>After looking so many posts about this problem, I don't understand why it don't work because it should be working. I will post all the information I have so far:</p>
<ul>
<li><p>Windows 10 64-bit</p></li>
<li><p>WampServer 3 64-bit (<a href="http://www.wampserver.com/" rel="noreferrer">http://www.wampserver.com/</a>)</p></li>
<li><p>PHP 5.6.16 </p></li>
<li><p>Apache 2.4.17 </p></li>
<li>Microsoft SQL Server 2016</li>
</ul>
<p>I downloaded SQLSRV32.exe from microsoft. I extracted the dll files to C:\wamp\bin\php\php5.6.16\ext.</p>
<p>In my php.ini given by wampserver:</p>
<ul>
<li><p>extension_dir = "c:/wamp/bin/php/php5.6.16/ext/"</p></li>
<li><p>extension=php_sqlsrv_56_ts.dll</p></li>
<li><p>extension=php_pdo_sqlsrv_56_ts.dll</p></li>
</ul>
<p>I have php5ts.dll in my php5.6.16 folder, so I think I have thread safe which is why I am using ts.dll ones.</p>
<p>If I'm in phpinfo() I should see a 'sqlsrv' section in there, but I don't see one, so I guess I did something wrong here somewhere?</p>
<p>I even did restart on wampserver many times and run as an administrator. It still don't show up on phpinfo()... But I can see this in php extension at the Wampserver: <a href="https://i.stack.imgur.com/Rf2bk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Rf2bk.png" alt="Extension showed up here"></a></p>
<p>Any ideas to what I did wrong or why it don't show up in phpinfo()?</p>
| 0debug |
c++ safeness of code with implicit conversion between signed and unsigned : <p>According to the rules on implicit conversions between signed and unsigned integer types, discussed <a href="https://stackoverflow.com/questions/17832815/c-implicit-conversion-signed-unsigned">here</a> and <a href="https://stackoverflow.com/questions/50605/signed-to-unsigned-conversion-in-c-is-it-always-safe">here</a>, when summing an <code>unsigned int</code> with a <code>int</code>, the signed <code>int</code> is first converted to an <code>unsigned int</code>.</p>
<p>Consider, e.g., the following minimal program</p>
<pre><code>#include <iostream>
int main()
{
unsigned int n = 2;
int x = -1;
std::cout << n + x << std::endl;
return 0;
}
</code></pre>
<p>The output of the program is, nevertheless, 1 as expected: <code>x</code> is converted first to an <code>unsigned int</code>, and the sum with <code>n</code> leads to an integer overflow, giving the "right" answer.</p>
<p>In a code like the previous one, if I know for sure that <code>n + x</code> is positive, can I assume that the sum of <code>unsigned int n</code> and <code>int x</code> gives the expected value?</p>
| 0debug |
void load_seg(int seg_reg, int selector, unsigned int cur_eip)
{
uint32_t e1, e2;
int cpl, dpl, rpl;
SegmentCache *dt;
int index;
uint8_t *ptr;
if ((selector & 0xfffc) == 0) {
if (seg_reg == R_SS) {
EIP = cur_eip;
raise_exception_err(EXCP0D_GPF, 0);
} else {
cpu_x86_load_seg_cache(env, seg_reg, selector, NULL, 0, 0);
}
} else {
if (selector & 0x4)
dt = &env->ldt;
else
dt = &env->gdt;
index = selector & ~7;
if ((index + 7) > dt->limit) {
EIP = cur_eip;
raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
}
ptr = dt->base + index;
e1 = ldl_kernel(ptr);
e2 = ldl_kernel(ptr + 4);
if (!(e2 & DESC_S_MASK)) {
EIP = cur_eip;
raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
}
rpl = selector & 3;
dpl = (e2 >> DESC_DPL_SHIFT) & 3;
cpl = env->hflags & HF_CPL_MASK;
if (seg_reg == R_SS) {
if ((e2 & DESC_CS_MASK) || !(e2 & DESC_W_MASK)) {
EIP = cur_eip;
raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
}
if (rpl != cpl || dpl != cpl) {
EIP = cur_eip;
raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
}
} else {
if ((e2 & (DESC_CS_MASK | DESC_R_MASK)) == DESC_CS_MASK) {
EIP = cur_eip;
raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
}
if (!(e2 & DESC_CS_MASK) || !(e2 & DESC_C_MASK)) {
if (dpl < cpl || dpl < rpl) {
EIP = cur_eip;
raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
}
}
}
if (!(e2 & DESC_P_MASK)) {
EIP = cur_eip;
if (seg_reg == R_SS)
raise_exception_err(EXCP0C_STACK, selector & 0xfffc);
else
raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
}
if (!(e2 & DESC_A_MASK)) {
e2 |= DESC_A_MASK;
stl_kernel(ptr + 4, e2);
}
cpu_x86_load_seg_cache(env, seg_reg, selector,
get_seg_base(e1, e2),
get_seg_limit(e1, e2),
e2);
#if 0
fprintf(logfile, "load_seg: sel=0x%04x base=0x%08lx limit=0x%08lx flags=%08x\n",
selector, (unsigned long)sc->base, sc->limit, sc->flags);
#endif
}
}
| 1threat |
Regex matching only '0' or '1' char (not repeated) : <p>I want to have a regex that matches only the string <code>0</code> or <code>1</code>.</p>
<p>I don't want to get a match if the string is <code>00</code>, <code>11</code> or <code>0101001</code> or any other combination. Just match if <code>0</code> or <code>1</code>.</p>
<p>This is the closest I get:</p>
<p><code>(0|1){1}$</code> but as you can see here this matches the last 1 or zero in a string.</p>
| 0debug |
Ionic 4 how do I receive componentProps? : <p>In Ionic 4, I am trying to use the <code>modalController</code> to open a modal. I am able to open the modal and send <code>componentProps</code>, but I'm not sure how to receive those properties.</p>
<p>Here's how I open the modal component:</p>
<pre><code>async showUpsert() {
this.modal = await this.modalController.create({
component:UpsertComponent,
componentProps: {test: "123"}
});
return await this.modal.present();
}
</code></pre>
<p>My question is; in the actual modal, how do I get <code>test: "123"</code> into a variable?</p>
| 0debug |
"Missing argument labels 'arg1:arg2:' in call" : <pre><code>var sum1 = 0
func calculatorMath(arg1: Int, arg2: Int) -> Int {
sum1 = arg1 + arg2
return sum1
}
calculatorMath(20,50)
</code></pre>
<p>//the problem is "Missing argument labels 'arg1:arg2:' in call". What do I need to do?</p>
| 0debug |
static int glyph_enu_free(void *opaque, void *elem)
{
av_free(elem);
return 0;
} | 1threat |
Lower-bounded wild card causes trouble in javac, but not Eclipse : <p>This piece of code compiles in Eclipse but not in javac:</p>
<pre class="lang-java prettyprint-override"><code>import java.util.function.Consumer;
public class Test {
public static final void m1(Consumer<?> c) {
m2(c);
}
private static final <T> void m2(Consumer<? super T> c) {
}
}
</code></pre>
<p>javac output:</p>
<pre class="lang-none prettyprint-override"><code>C:\Users\lukas\workspace>javac -version
javac 1.8.0_92
C:\Users\lukas\workspace>javac Test.java
Test.java:5: error: method m2 in class Test cannot be applied to given types;
m2(c);
^
required: Consumer<? super T>
found: Consumer<CAP#1>
reason: cannot infer type-variable(s) T
(argument mismatch; Consumer<CAP#1> cannot be converted to Consumer<? super T>)
where T is a type-variable:
T extends Object declared in method <T>m2(Consumer<? super T>)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
1 error
----------------------------------------------------------------
</code></pre>
<p>Which compiler is wrong and why? (<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=497380">Eclipse bug report and parts of discussion here</a>)</p>
| 0debug |
Error after Updating play-services "Program type already present: com.google.android.gms.internal.measurement.zzabo" : <p>I updated play-services dependencies to version 15.0.0 and also added play-services-safetynet to my app.gradle. After that i always get </p>
<blockquote>
<p>Program type already present: com.google.android.gms.internal.measurement.zzabo
Message{kind=ERROR, text=Program type already present: com.google.android.gms.internal.measurement.zzabo, sources=[Unknown source file], tool name=Optional.of(D8)}</p>
</blockquote>
<p>when building the app. here is my app.build:</p>
<pre><code>apply plugin: 'com.android.application'
android {
signingConfigs {
}
compileSdkVersion 27
buildToolsVersion '27.0.3'
defaultConfig {
applicationId "XXXXXXX"
minSdkVersion 19
targetSdkVersion 27
versionCode 1
versionName "0.0.0.1"
setProperty("archivesBaseName", "XXXXXXX-$versionName")
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/ASL2.0'
exclude 'META-INF/LICENSE'
exclude 'META-INF/license.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/notice.txt'
}
productFlavors {
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:support-v4:27.1.1'
compile 'com.android.support:design:27.1.1'
compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support:recyclerview-v7:27.1.1'
compile 'com.android.support.constraint:constraint-layout:1.1.0'
compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'
compile 'com.fasterxml.jackson.core:jackson-databind:2.3.2'
compile 'com.koushikdutta.urlimageviewhelper:urlimageviewhelper:1.0.4'
implementation 'com.google.firebase:firebase-core:15.0.0'
implementation 'com.google.firebase:firebase-messaging:15.0.0'
implementation 'com.google.firebase:firebase-appindexing:15.0.0'
implementation 'com.google.android.gms:play-services-location:15.0.0'
implementation 'com.google.android.gms:play-services-safetynet:15.0.0'
compile 'org.kefirsf:kefirbb:1.5'
compile 'org.osmdroid:osmdroid-android:6.0.1'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code></pre>
| 0debug |
Why does chrome style inspector show style from .scss? : <p>When I use the 'styles' tab of the Google Chrome developer tools, it reports one of my styles as coming from the .scss file. How is this possible - I thought all .scss had to be flattened and read from a .css file:</p>
<p><a href="https://i.stack.imgur.com/aZIyA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aZIyA.png" alt="enter image description here"></a></p>
| 0debug |
How to hot reload Tomcat server in VSCode : <p>I'm migrating from Eclipse IDE (+ VSCode for coding Java servlets and HTML/CSS/JS webpages, respectively) to only Visual Studio Code for its lightweight.</p>
<hr>
<p>I have several Java extensions installed for VSCode:</p>
<ul>
<li><a href="https://marketplace.visualstudio.com/items?itemName=redhat.java" rel="noreferrer">Language Support for Java(TM) by Red Hat</a></li>
<li><a href="https://marketplace.visualstudio.com/items?itemName=adashen.vscode-tomcat" rel="noreferrer">Tomcat for Java</a></li>
<li><a href="https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-debug" rel="noreferrer">Debugger for Java</a></li>
</ul>
<hr>
<p>Eclipse has a series of settings for hot reloading:</p>
<pre><code>- Automatically publish when resources change
- Refresh using native hooks or polling
</code></pre>
<p>while VSCode doesn't seem to have any for me.</p>
<hr>
<p>A few things I've try to reload my Java and web code:</p>
<ul>
<li>Restart Tomcat server</li>
<li>Delete and re-adding Tomcat server</li>
<li>Delete and regenerate <code>.war</code> package (not sure if this does anything, it can run well without a <code>.war</code> package)</li>
</ul>
| 0debug |
Multi mapping each object with a list or collection using C# Dapper : <p>I am having trouble multi mapping the result from db to my objects. I want to map the production objects to a list that holds them to each workstation.</p>
<pre><code>Table1:
productProduction Workstation
----------------- -----------
es1 cell_1
es2 cell_1
es4 cell_3
est3 cell_4
table2 workstations:
Workstation
----
cell_1
cell_2
cell_3
cell_4
public class Workstation {
public string Cell { get; set; }
public List<Production> {get; set;}
}
public class Production {
public string product_name { get; set; }
}
</code></pre>
| 0debug |
Importing .py files in Google Colab : <p>Is there any way to upload my code in .py files and import them in colab code cells? </p>
<p>The other way I found is to create a local Jupyter notebook then upload it to Colab, is it the only way?</p>
| 0debug |
def string_length(str1):
count = 0
for char in str1:
count += 1
return count | 0debug |
Can you pay your domain with Amazon-Card : <p>I am just curious and want to know whether i can pay with amazon cards or not. Otherwise i am looking for another option like google cloud hosting which should be much cheaper</p>
| 0debug |
Performance hit from using std::find : <p>I have the following code to check whether a value belongs to a list of values. eg: <code>contains({1,2,3},3)</code>. Almost always, I could write a bunch of <code>if-else</code>s. How much performance hit does the <code>contains</code> approach create? Is there a way to avoid this?</p>
<pre><code>template<typename T1,typename T2>
std::enable_if_t<std::is_same<std::initializer_list<T2>,T1>::value, bool> contains(const T1 &container,const T2 &item)
{
return(std::find(container.begin(),container.end(),item)!=container.end());
}
</code></pre>
| 0debug |
static int vnc_display_disable_login(DisplayState *ds)
{
VncDisplay *vs = vnc_display;
if (!vs) {
return -1;
}
if (vs->password) {
g_free(vs->password);
}
vs->password = NULL;
if (vs->auth == VNC_AUTH_NONE) {
vs->auth = VNC_AUTH_VNC;
}
return 0;
}
| 1threat |
Difference between 'related_name' and 'related_query_name' attributes in Django? : <p>Can you explain the difference between <code>related_name</code> and <code>related_query_name</code> attributes for the Field object in Django ? When I use them, How to use them? Thanks!</p>
| 0debug |
def extract_index_list(l1, l2, l3):
result = []
for m, n, o in zip(l1, l2, l3):
if (m == n == o):
result.append(m)
return result | 0debug |
Import multiple components in vue using ES6 syntax doesn't work : <p>So I am trying to create a vue instance that needs other components from folder "views/"</p>
<p>Here is the file structure:</p>
<ul>
<li>Project
<ul>
<li>build/</li>
<li>config/</li>
<li>node_modules/</li>
<li>src/
<ul>
<li>views/</li>
<li>components/</li>
</ul></li>
<li>App.vue</li>
</ul></li>
</ul>
<p>If I do this in App.vue, the server will run with no error:</p>
<pre><code>import Navbar from 'layouts/Navbar'
import Topbar from 'layouts/Topbar'
import AppMain from 'layouts/AppMain'
</code></pre>
<p>But if I try this instead:</p>
<pre><code>import { AppMain, Navbar, Topbar } from 'layouts/'
</code></pre>
<p>The server won't run and will return:</p>
<pre><code>This dependency was not found:
* views/ in ./src/router/index.js
</code></pre>
<p>Here is the webpack.base.config.js</p>
<pre><code>function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json', '.scss'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
'layouts': resolve('src/layouts'),
'views': resolve('src/views'),
'components': resolve('src/components'),
'variables': path.resolve(__dirname, '../src/assets/common/variables.scss'),
},
},
</code></pre>
<p>I really have no idea what's wrong, plz help, thx</p>
| 0debug |
void cpu_reset(CPUSPARCState *env)
{
tlb_flush(env, 1);
env->cwp = 0;
env->wim = 1;
env->regwptr = env->regbase + (env->cwp * 16);
#if defined(CONFIG_USER_ONLY)
env->user_mode_only = 1;
#ifdef TARGET_SPARC64
env->cleanwin = env->nwindows - 2;
env->cansave = env->nwindows - 2;
env->pstate = PS_RMO | PS_PEF | PS_IE;
env->asi = 0x82;
#endif
#else
env->psret = 0;
env->psrs = 1;
env->psrps = 1;
#ifdef TARGET_SPARC64
env->pstate = PS_PRIV;
env->hpstate = HS_PRIV;
env->pc = 0x1fff0000020ULL;
env->tsptr = &env->ts[env->tl];
#else
env->pc = 0;
env->mmuregs[0] &= ~(MMU_E | MMU_NF);
env->mmuregs[0] |= env->mmu_bm;
#endif
env->npc = env->pc + 4;
#endif
}
| 1threat |
VISUAL BASIC(LISTBOX, ARRAY?,LOOP) : PLEASE HELP ME
Im struggling with my code for college work, i know this isnt right but i spend hours without figuring it out.[CODE[DESIGN][1] here][2]
so im trying to add a certain amount to the loan when the list or lists on the listbox is selected each items in the listbox have differ or same amount. i want the code to work even if i didnt have to choose or highlight any of the item in the listbox.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
'Extra Sevices
Dim extra As Integer
For i As Integer = 0 To ListBox1.SelectedItem.count
If ListBox1.SelectedItem = "insurance - O" Or
ListBox1.SelectedItem = "Hotel discount -O" Then
extra = 500
ElseIf ListBox1.SelectedItem = "One payment grace -F" Or
ListBox1.SelectedItem = "2-day late payment-F" Or
ListBox1.SelectedItem = "Frequent Borrowe benefits -F" Or
ListBox1.SelectedItem = "Online reversals -F" Or
ListBox1.SelectedItem = "GST waver -F" Then
extra = 500
ElseIf ListBox1.SelectedItem = "Face to face transactions -S" Or
ListBox1.SelectedItem = "Saturday visits -S" Or
ListBox1.SelectedItem = "Face to face consultations -S" Or
ListBox1.SelectedItem = "Phone reminders -S" Then
extra = 200
Else
extra = 0
End If
extra = extra + extra
Next
<!-- end snippet -->
please im begging anyone to help me with this. even a simple advice appreciated thanks.
[1]: https://i.stack.imgur.com/IPKaP.png
[2]: https://i.stack.imgur.com/BYrhQ.png | 0debug |
int bdrv_write(BlockDriverState *bs, int64_t sector_num,
const uint8_t *buf, int nb_sectors)
{
BlockDriver *drv = bs->drv;
if (!bs->drv)
return -ENOMEDIUM;
if (bs->read_only)
return -EACCES;
if (bdrv_check_request(bs, sector_num, nb_sectors))
return -EIO;
return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
}
| 1threat |
python - Delete lines in a file not started by a specific string : <p>Can you tell me a script in python to run on terminal on macOS, so I can open a .txt file and delete every lines not started by "2017" ?</p>
<p>Thakyou</p>
| 0debug |
static int img_create(int argc, char **argv)
{
int c, ret, flags;
const char *fmt = "raw";
const char *base_fmt = NULL;
const char *filename;
const char *base_filename = NULL;
BlockDriver *drv;
QEMUOptionParameter *param = NULL;
char *options = NULL;
flags = 0;
for(;;) {
c = getopt(argc, argv, "F:b:f:he6o:");
if (c == -1)
break;
switch(c) {
case 'h':
help();
break;
case 'F':
base_fmt = optarg;
break;
case 'b':
base_filename = optarg;
break;
case 'f':
fmt = optarg;
break;
case 'e':
flags |= BLOCK_FLAG_ENCRYPT;
break;
case '6':
flags |= BLOCK_FLAG_COMPAT6;
break;
case 'o':
options = optarg;
break;
}
}
drv = bdrv_find_format(fmt);
if (!drv)
error("Unknown file format '%s'", fmt);
if (options && !strcmp(options, "?")) {
print_option_help(drv->create_options);
return 0;
}
if (options) {
param = parse_option_parameters(options, drv->create_options, param);
if (param == NULL) {
error("Invalid options for file format '%s'.", fmt);
}
} else {
param = parse_option_parameters("", drv->create_options, param);
}
if (optind >= argc)
help();
filename = argv[optind++];
if (optind < argc) {
set_option_parameter(param, BLOCK_OPT_SIZE, argv[optind++]);
}
add_old_style_options(fmt, param, flags, base_filename, base_fmt);
if (get_option_parameter(param, BLOCK_OPT_SIZE)->value.n == 0) {
QEMUOptionParameter *backing_file =
get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
QEMUOptionParameter *backing_fmt =
get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
if (backing_file && backing_file->value.s) {
BlockDriverState *bs;
uint64_t size;
const char *fmt = NULL;
char buf[32];
if (backing_fmt && backing_fmt->value.s) {
if (bdrv_find_format(backing_fmt->value.s)) {
fmt = backing_fmt->value.s;
} else {
error("Unknown backing file format '%s'",
backing_fmt->value.s);
}
}
bs = bdrv_new_open(backing_file->value.s, fmt);
bdrv_get_geometry(bs, &size);
size *= 512;
bdrv_delete(bs);
snprintf(buf, sizeof(buf), "%" PRId64, size);
set_option_parameter(param, BLOCK_OPT_SIZE, buf);
} else {
error("Image creation needs a size parameter");
}
}
printf("Formatting '%s', fmt=%s ", filename, fmt);
print_option_parameters(param);
puts("");
ret = bdrv_create(drv, filename, param);
free_option_parameters(param);
if (ret < 0) {
if (ret == -ENOTSUP) {
error("Formatting or formatting option not supported for file format '%s'", fmt);
} else if (ret == -EFBIG) {
error("The image size is too large for file format '%s'", fmt);
} else {
error("Error while formatting");
}
}
return 0;
}
| 1threat |
Controlling State from outside of a StatefulWidget : <p>I'm trying to understand the best practice for controlling a StatefulWidget's state outside of that Widgets State. </p>
<p>I have the following interface defined. </p>
<pre><code>abstract class StartupView {
Stream<String> get onAppSelected;
set showActivity(bool activity);
set message(String message);
}
</code></pre>
<p>I would like to create a StatefulWidget <code>StartupPage</code> that implements this interface. I expect the Widget to do the following:</p>
<ol>
<li><p>When a button is pressed it would send an event over the onAppSelected stream. A controller would listen to this even and perform some action ( db call, service request etc ).</p></li>
<li><p>The controller can call <code>showActivity</code> or <code>set message</code> to have the view show progress with a message.</p></li>
</ol>
<p>Because a Stateful Widget does not expose it's State as a property, I don't know the best approach for accessing and modifying the State's attributes. </p>
<p>The way I would expect to use this would be something like:</p>
<pre><code>Widget createStartupPage() {
var page = new StartupPage();
page.onAppSelected.listen((app) {
page.showActivity = true;
//Do some work
page.showActivity = false;
});
}
</code></pre>
<p>I've thought about instantiating the Widget by passing in the state I want it to return in <code>createState()</code> but that feels wrong.</p>
<p>Some background on why we have this approach: We currently have a Dart web application. For view-controller separation, testability and forward thinking towards Flutter we decided that we would create an interface for every view in our application. This would allow a WebComponent or a Flutter Widget to implement this interface and leave all of the controller logic the same. </p>
| 0debug |
turn array with object to array : <p>Let's say I have this:</p>
<pre><code>[ { 'one': '8b45544b-6d35c53c3d423' },
{ 'two': '5a509481-a43k4d40r4c44' } ]
</code></pre>
<p>How can I turn it into this:</p>
<pre><code>[ 'one', 'two' ]
</code></pre>
| 0debug |
How to remove a created library in angular6 : <p>To create a library in angular6 we use the following:</p>
<pre><code>ng generate library my-lib
</code></pre>
<p>If we wish to remove the previously created library, what is the the command:</p>
| 0debug |
Regex in Javascript using OR : <p>I'm trying to write a regex expression to match multiple characters such as , OR . OR : OR ( OR )</p>
<p>I have this</p>
<pre><code>removePunctuation = /\.$|\,$|\:|\(|\)/;
word = rawList[j].replace(removePunctuation,"")
</code></pre>
<p>I just want to remove periods & commas at the end of the sentence but all instances of ( ) :</p>
<p>What am I doing wrong?</p>
| 0debug |
CSS Background Image overlay : <p>I was wondering. How do I make it to where when you scroll down the page on a website, the background kind of follows it. Example here, <a href="https://alexcican.com/post/455k-users/" rel="nofollow">https://alexcican.com/post/455k-users/</a> . I want something like the very top of the page to happen, can anyone point me in the right directional?s</p>
| 0debug |
Java program which execute after a specific time : <p>Is there any way to add a timer in java program? I mean the code will execute only after the time complete and then repeat it-self..</p>
| 0debug |
AWS lambda function stops working after timed out error : <p>I have a simple lambda function that asynchronously makes an API calls and then returns data. 99% of the time this works great. When ever the API takes longer then the lambda configured timeout, it gives an error as expected. Now the issue is that when I make any subsequent calls to the lambda function it permanently gives me the timeout error.</p>
<pre><code> "errorMessage": "2016-05-14T22:52:07.247Z {session} Task timed out after 3.00 seconds"
</code></pre>
<p>In order to test that this was the case I set the lambda timeout to 3 seconds and have a way to trigger these two functions within the lambda. </p>
<p><strong>Javascript</strong></p>
<pre><code>function now() {
return response.tell('success');
}
function wait() {
setTimeout(function() { return response.tell('success'); }, 4000);
}
</code></pre>
<p>When I call the <code>now</code> function there are no problems. When I call the <code>wait</code> function I get the timeout error and then any subsequent calls to <code>now</code> give me the same error.</p>
<p>Is this an expected behavior? I would think that any subsequent calls to the lambda function should work. I understand I can always increase the configuration timeout, but would rather not. </p>
| 0debug |
void palette_destroy(VncPalette *palette)
{
if (palette == NULL) {
qemu_free(palette);
}
}
| 1threat |
How can indexes be checked if they exist in a Laravel migration? : <p>Trying to check if a unique index exists on a table when preparing a migration, how can it be achieved?</p>
<pre><code>Schema::table('persons', function (Blueprint $table) {
if ($table->hasIndex('persons_body_unique')) {
$table->dropUnique('persons_body_unique');
}
})
</code></pre>
<p>Something that looks like the above. (apparently, hasIndex() doesn't exist)</p>
| 0debug |
static void rtc_update_timer(void *opaque)
{
RTCState *s = opaque;
int32_t irqs = REG_C_UF;
int32_t new_irqs;
assert((s->cmos_data[RTC_REG_A] & 0x60) != 0x60);
rtc_update_time(s);
s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;
if (check_alarm(s)) {
irqs |= REG_C_AF;
if (s->cmos_data[RTC_REG_B] & REG_B_AIE) {
qemu_system_wakeup_request(QEMU_WAKEUP_REASON_RTC);
}
}
new_irqs = irqs & ~s->cmos_data[RTC_REG_C];
s->cmos_data[RTC_REG_C] |= irqs;
if ((new_irqs & s->cmos_data[RTC_REG_B]) != 0) {
s->cmos_data[RTC_REG_C] |= REG_C_IRQF;
qemu_irq_raise(s->irq);
}
check_update_timer(s);
}
| 1threat |
how to list all databases names sql server in asp.net mvc 5 : i'm trying this code in controller but doesn't work ...
Server myserver = new Server(".");
DataTable servers = SqlDataSourceEnumerator.Instance.GetDataSources();
DatabaseCollection mydata = myserver.Databases;
foreach (Database db in myserver.Databases)
{
} | 0debug |
STL Stack: read access violation : <p>I have created a stack then using memcpy I copy the stack to a buffer. and later I try to create the stack object back using the buffer. But I am getting read access violation.</p>
<p>please see below the code that might explain the situation better.</p>
<pre><code>Byte *targetdata;
class DATA
{
std::stack<int> scatter;
}data;
...
...
memcpy(targetdata, &data, sizeof(DATA));
...
...
{
DATA data2;
memcpy(&data2, targetdata, sizeof(DATA));
}// Get a read access violation here.
</code></pre>
| 0debug |
Intel HAXM on macOS high sierra (10.13) : <p>Is there any way of using Android emulator on High Sierra (10.13)? </p>
<p>When I run</p>
<pre><code>./HAXM\ installation -u
</code></pre>
<p>It says:</p>
<pre><code>HAXM silent installation only supports macOS from 10.8 to 10.12 !
</code></pre>
| 0debug |
Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener : <p>I have a spring project and try to make it use spring boot and to run at embadded tomcat following :</p>
<p><a href="https://spring.io/guides/gs/rest-service/" rel="noreferrer">https://spring.io/guides/gs/rest-service/</a></p>
<p>This is my Application</p>
<pre><code>//@Configuration
//@EnableAspectJAutoProxy
@SpringBootApplication
@ComponentScan(basePackages = "gux.prome")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
</code></pre>
<p>If I use maven command: <code>mvn spring-boot:run</code>, the project starts fine, but I need to debug , so I run this main method at InteliJ, exception occurs:</p>
<pre><code>Exception in thread "main" java.lang.IllegalArgumentException: Cannot instantiate interface org.springframework.context.ApplicationListener : org.springframework.boot.logging.ClasspathLoggingApplicationListener
at org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:414)
at org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:394)
at org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:385)
at org.springframework.boot.SpringApplication.initialize(SpringApplication.java:263)
at org.springframework.boot.SpringApplication.<init>(SpringApplication.java:237)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180)
at gux.prome.config.Application.main(Application.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.lang.NoClassDefFoundError: org/springframework/context/event/GenericApplicationListener
....
</code></pre>
<p>This is the pom:</p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>gux</groupId>
<artifactId>prome-data</artifactId>
<version>1.0-SNAPSHOT</version>
<name>prome-data Maven Webapp</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<!-- end of guava -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
<properties>
<java.version>1.7</java.version>
</properties>
<build>
<finalName>prome-data</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!--<plugin>-->
<!-- use java 7 -->
<!--<artifactId> maven-compiler-plugin</artifactId>-->
<!--<version>3.1</version>-->
<!--<configuration>-->
<!--<source> 1.7</source> -->
<!--<target> 1.7</target>-->
<!--</configuration>-->
<!--</plugin>-->
</plugins>
</build>
<!--<repositories>-->
<!--<repository>-->
<!--<id>spring-releases</id>-->
<!--<url>http://repo.spring.io/libs-release</url>-->
<!--</repository>-->
<!--</repositories>-->
<!--<pluginRepositories>-->
<!--<pluginRepository>-->
<!--<id>spring-releases</id>-->
<!--<url>http://repo.spring.io/libs-release</url>-->
<!--</pluginRepository>-->
<!--</pluginRepositories>-->
</project>
</code></pre>
| 0debug |
How come this array has a length of 13? : <p>im confused as the following array has only 13 elements in it and shows the length as 13,Why so?</p>
<pre><code>class ArrayCopyOfDemo {
public static void main(String[] args) {
char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e','i', 'n', 'a', 't', 'e', 'd'};
char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 10);
System.out.println(new String(copyTo));
System.out.println(copyFrom.length);
}
</code></pre>
<p>}</p>
<p>It should be showing 12</p>
| 0debug |
static DisplaySurface *qemu_create_message_surface(int w, int h,
const char *msg)
{
DisplaySurface *surface = qemu_create_displaysurface(w, h);
pixman_color_t bg = color_table_rgb[0][COLOR_BLACK];
pixman_color_t fg = color_table_rgb[0][COLOR_WHITE];
pixman_image_t *glyph;
int len, x, y, i;
len = strlen(msg);
x = (w / FONT_WIDTH - len) / 2;
y = (h / FONT_HEIGHT - 1) / 2;
for (i = 0; i < len; i++) {
glyph = qemu_pixman_glyph_from_vgafont(FONT_HEIGHT, vgafont16, msg[i]);
qemu_pixman_glyph_render(glyph, surface->image, &fg, &bg,
x+i, y, FONT_WIDTH, FONT_HEIGHT);
qemu_pixman_image_unref(glyph);
}
return surface;
}
| 1threat |
Converting tokens to word vectors effectively with TensorFlow Transform : <p>I would like to use TensorFlow Transform to convert tokens to word vectors during my training, validation and inference phase. </p>
<p>I followed this <a href="https://stackoverflow.com/questions/45113130/how-to-add-new-embeddings-for-unknown-words-in-tensorflow-training-pre-set-fo">StackOverflow post</a> and implemented the initial conversion from tokens to vectors. The conversion works as expected and I obtain vectors of <code>EMB_DIM</code> for each token.</p>
<pre><code>import numpy as np
import tensorflow as tf
tf.reset_default_graph()
EMB_DIM = 10
def load_pretrained_glove():
tokens = ["a", "cat", "plays", "piano"]
return tokens, np.random.rand(len(tokens), EMB_DIM)
# sample string
string_tensor = tf.constant(["plays", "piano", "unknown_token", "another_unknown_token"])
pretrained_vocab, pretrained_embs = load_pretrained_glove()
vocab_lookup = tf.contrib.lookup.index_table_from_tensor(
mapping = tf.constant(pretrained_vocab),
default_value = len(pretrained_vocab))
string_tensor = vocab_lookup.lookup(string_tensor)
# define the word embedding
pretrained_embs = tf.get_variable(
name="embs_pretrained",
initializer=tf.constant_initializer(np.asarray(pretrained_embs), dtype=tf.float32),
shape=pretrained_embs.shape,
trainable=False)
unk_embedding = tf.get_variable(
name="unk_embedding",
shape=[1, EMB_DIM],
initializer=tf.random_uniform_initializer(-0.04, 0.04),
trainable=False)
embeddings = tf.cast(tf.concat([pretrained_embs, unk_embedding], axis=0), tf.float32)
word_vectors = tf.nn.embedding_lookup(embeddings, string_tensor)
with tf.Session() as sess:
tf.tables_initializer().run()
tf.global_variables_initializer().run()
print(sess.run(word_vectors))
</code></pre>
<p>When I refactor the code to run as a TFX Transform Graph, I am getting the error the <code>ConversionError</code> below.</p>
<pre><code>import pprint
import tempfile
import numpy as np
import tensorflow as tf
import tensorflow_transform as tft
import tensorflow_transform.beam.impl as beam_impl
from tensorflow_transform.tf_metadata import dataset_metadata
from tensorflow_transform.tf_metadata import dataset_schema
tf.reset_default_graph()
EMB_DIM = 10
def load_pretrained_glove():
tokens = ["a", "cat", "plays", "piano"]
return tokens, np.random.rand(len(tokens), EMB_DIM)
def embed_tensor(string_tensor, trainable=False):
"""
Convert List of strings into list of indices then into EMB_DIM vectors
"""
pretrained_vocab, pretrained_embs = load_pretrained_glove()
vocab_lookup = tf.contrib.lookup.index_table_from_tensor(
mapping=tf.constant(pretrained_vocab),
default_value=len(pretrained_vocab))
string_tensor = vocab_lookup.lookup(string_tensor)
pretrained_embs = tf.get_variable(
name="embs_pretrained",
initializer=tf.constant_initializer(np.asarray(pretrained_embs), dtype=tf.float32),
shape=pretrained_embs.shape,
trainable=trainable)
unk_embedding = tf.get_variable(
name="unk_embedding",
shape=[1, EMB_DIM],
initializer=tf.random_uniform_initializer(-0.04, 0.04),
trainable=False)
embeddings = tf.cast(tf.concat([pretrained_embs, unk_embedding], axis=0), tf.float32)
return tf.nn.embedding_lookup(embeddings, string_tensor)
def preprocessing_fn(inputs):
input_string = tf.string_split(inputs['sentence'], delimiter=" ")
return {'word_vectors': tft.apply_function(embed_tensor, input_string)}
raw_data = [{'sentence': 'This is a sample sentence'},]
raw_data_metadata = dataset_metadata.DatasetMetadata(dataset_schema.Schema({
'sentence': dataset_schema.ColumnSchema(
tf.string, [], dataset_schema.FixedColumnRepresentation())
}))
with beam_impl.Context(temp_dir=tempfile.mkdtemp()):
transformed_dataset, transform_fn = ( # pylint: disable=unused-variable
(raw_data, raw_data_metadata) | beam_impl.AnalyzeAndTransformDataset(
preprocessing_fn))
transformed_data, transformed_metadata = transformed_dataset # pylint: disable=unused-variable
pprint.pprint(transformed_data)
</code></pre>
<p>Error Message</p>
<pre><code>TypeError: Failed to convert object of type <class
'tensorflow.python.framework.sparse_tensor.SparseTensor'> to Tensor.
Contents: SparseTensor(indices=Tensor("StringSplit:0", shape=(?, 2),
dtype=int64), values=Tensor("hash_table_Lookup:0", shape=(?,),
dtype=int64), dense_shape=Tensor("StringSplit:2", shape=(2,),
dtype=int64)). Consider casting elements to a supported type.
</code></pre>
<p><strong>Questions</strong></p>
<ol>
<li>Why would the TF Transform step require an additional conversion/casting?</li>
<li>Is this approach of converting tokens to word vectors feasible? The word vectors might be multiple gigabytes in memory. How is Apache Beam handling the vectors? If Beam in a distributed setup, would it require <code>N x vector memory</code> with <code>N</code> the number of workers?</li>
</ol>
| 0debug |
How to create join table with foreign keys with sequelize or sequelize-cli : <p>I'm creating models and migrations for two types, Player and Team that have many to many relationship. I'm using sequelize model:create, but don't see how to specify foreign keys or join tables.</p>
<pre><code>sequelize model:create --name Player --attributes "name:string"
sequelize model:create --name Team --attributes "name:string"
</code></pre>
<p>After the model is created, I add associations.
In Player:</p>
<pre><code>Player.belongsToMany(models.Team, { through: 'PlayerTeam', foreignKey: 'playerId', otherKey: 'teamId' });
</code></pre>
<p>In Team:</p>
<pre><code>Team.belongsToMany(models.Player, { through: 'PlayerTeam', foreignKey: 'teamId', otherKey: 'playerId' });
</code></pre>
<p>Then the migrations are run with</p>
<pre><code>sequelize db:migrate
</code></pre>
<p>There are tables for Player and Team but there's no join table (nor foreign keys) in the database. How can the foreign keys and join table be created? Is there a definitive guide on how to do this? </p>
| 0debug |
How to fix Syntax error insert '}' to complete block : I'm keep getting an error with my code. I'm creating a simple user-defined function for Neo4j. Can anyone help me with this? No matter what I try I get "Syntax Error: Insert "}" to complete block." When I insert "}" it gives me an error saying that my code is "unreachable" and when I add a bracket to make it reachable it takes me back to the first error and it just loops.
Here is my code:
public class Join {
static Cipher cipher;
@UserFunction
@Description("example.DES ,, Decryption of any input values.")
public byte[] DES( @Name("set1") List<String> strings1) {
for (int i = 0; i < strings1.size(); i++) {
String dot;
dot = strings1.get(i);
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
cipher = Cipher.getInstance("AES");
String encryptedText = encrypt(dot, secretKey);
System.out.println("Encrypted Text After Encryption: " + encryptedText);
}
public static String encrypt(String dot, SecretKey secretKey)
throws Exception {
byte[] plainTextByte = dot.getBytes();
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedByte = cipher.doFinal(plainTextByte);
Base64.Encoder encoder = Base64.getEncoder();
String encryptedText = encoder.encodeToString(encryptedByte);
return encryptedText;
}
}
| 0debug |
Name and function for the following matrix operation in R : <p>I am trying to reproduce this [50 x 50] matrix generated with Python as:</p>
<pre><code>n = 50
a = np.linspace(-5, 5, n).reshape(-1,1)
b = a
np.sum(a**2, 1).reshape(-1, 1) + np.sum(b**2, 1)
</code></pre>
<p>using R. The problem is that the result is some sort of matrix, which cannot be reproduced through:</p>
<pre><code>n = 50
a = seq(-5, 5, length.out = n)
b = a
a^2 + b^2
</code></pre>
<p>which generates a vector.</p>
<p>I am not familiar with the object names in Python, but I see that <code>np.sum(a**2, 1).reshape(-1, 1)</code> produces what looks like a [50 x 1] column vector:</p>
<pre><code>array([[ 2.50000000e+01],
[ 2.30008330e+01],
...
[ 2.10849646e+01],
[ 2.30008330e+01],
[ 2.50000000e+01]])
</code></pre>
<p>while <code>np.sum(b**2, 1)</code>:</p>
<pre><code>array([ 2.50000000e+01, 2.30008330e+01, 2.10849646e+01,
1.92523948e+01, 1.75031237e+01, 1.58371512e+01,
...
1.27551020e+01, 1.42544773e+01, 1.58371512e+01,
1.75031237e+01, 1.92523948e+01, 2.10849646e+01,
2.30008330e+01, 2.50000000e+01])
</code></pre>
<p>looks like the transposed of that same vector. So we have an operation of the form [50 x 1] * [1 x 50] = [50 x 50].</p>
<p>What is the generic name of this operation? And how can I reproduce it in R?</p>
| 0debug |
bool timerlistgroup_run_timers(QEMUTimerListGroup *tlg)
{
QEMUClockType type;
bool progress = false;
for (type = 0; type < QEMU_CLOCK_MAX; type++) {
progress |= timerlist_run_timers(tlg->tl[type]);
}
return progress;
}
| 1threat |
How to count results from For Loop : <p>How do we count results from For Loop </p>
<pre><code>$starting_year=2001;
$ending_year=2015;
for ($x = $starting_year; $x <= $ending_year;$x++) {
echo "$x <br />";
}
</code></pre>
<p>how do I count the generation? For example above should be 5</p>
| 0debug |
bash replace single quotes with double qoutes : I have a directory full of SAS label files.
The label files have space, single qoute, space, single qoute in each file.
Looks like, VAR1 = ' 'SOME LABEL' '
I want a bash script that will replace these single qoutes with double quotes so that I end up with, VAR1 = "SOME LABEL"
Please help
| 0debug |
void qemu_chr_add_handlers(CharDriverState *s,
IOCanReadHandler *fd_can_read,
IOReadHandler *fd_read,
IOEventHandler *fd_event,
void *opaque)
{
if (!opaque) {
s->assigned = 0;
}
s->chr_can_read = fd_can_read;
s->chr_read = fd_read;
s->chr_event = fd_event;
s->handler_opaque = opaque;
if (s->chr_update_read_handler)
s->chr_update_read_handler(s);
if (s->opened) {
qemu_chr_generic_open(s);
}
}
| 1threat |
Rx - How to unsubscribe automatically after receiving onNext()? : <p>How to unsubscribe automatically after receiving onNext() ?</p>
<p>For now I use this code:</p>
<pre><code>rxObservable
.compose(bindToLifecycle()) // unsubscribe automatically in onPause() if method was called in onResume()
.subscribe(new Subscriber<Object>() {
...
@Override
public void onNext(Object o) {
unsubscribe();
}
});
</code></pre>
| 0debug |
Using TypeScript super() : <p>I am trying to extend a class in TypeScript. I keep receiving this error on compile: 'Supplied parameters do not match any signature of call target.' I have tried referencing the artist.name property in the super call as super(name) but is not working. </p>
<p>Any ideas and explanations you may have will be greatly appreciated. Thanks - Alex.</p>
<pre><code>class Artist {
constructor(
public name: string,
public age: number,
public style: string,
public location: string
){
console.log(`instantiated ${name}, whom is ${age} old, from ${location}, and heavily regarded in the ${style} community`);
}
}
class StreetArtist extends Artist {
constructor(
public medium: string,
public famous: boolean,
public arrested: boolean,
public art: Artist
){
super();
console.log(`instantiated ${this.name}. Are they famous? ${famous}. Are they locked up? ${arrested}`);
}
}
interface Human {
name: string,
age: number
}
function getArtist(artist: Human){
console.log(artist.name)
}
let Banksy = new Artist(
"Banksy",
40,
"Politcal Graffitti",
"England / Wolrd"
)
getArtist(Banksy);
</code></pre>
| 0debug |
Python List/Tupule : Hi i want to modify my list so it shows an '(x)' at the given coordinate via tupule.
Here is my code so far
#w=width
#h=height
#c=coordinates
new_grid = []
def coordiantes(w,h,c):
'''
>>> coordiantes(2, 4, (0, 1))
>>> print(new_grid)
[['(_)', '(x)'], ['(_)','(_)'], ['(_)', '(_)'], ['(_)', '(_)']]
'''
b=[]
for i in range(h):
grid.append(b)
for j in range(w):
c=('(_)')
b.append(c)
i am not sure how to implement '(x)' at the given coordinates, any help is appreciated
thanks
| 0debug |
scala array ArrayIndexOutOfBoundsException: : val str = line.split(":")
println(line.split(':')(1))
When the index is one I get the java.lang.ArrayIndexOutOfBoundsException: 1 but when I put the index as 0 no issues at all.
I am new to Scala btw.. | 0debug |
Xamarin Forms Android App Crashes Running Debug with VS Android Emulator : <p>I have a basic Xamarin Forms app I created. It works fine against the iOS simulator.</p>
<p>However when I try and run with a VS Android Emulator (5.1in Marshmallow) it crashes every time upon opening. Even when I try and run without debugging. Below is the error I keep seeing:</p>
<pre><code>01-14 16:22:10.290 D/Mono ( 1366): AOT module 'mscorlib.dll.so' not found: dlopen failed: library "/data/app-lib/App3.Droid-2/libaot-mscorlib.dll.so" not found
01-14 16:22:10.290 D/Mono ( 1366): AOT module '/Users/builder/data/lanes/2512/d3008455/source/monodroid/builds/install/mono-x86/lib/mono/aot-cache/x86/mscorlib.dll.so' not found: dlopen failed: library "/data/app-lib/App3.Droid-2/libaot-mscorlib.dll.so" not found
01-14 16:22:10.294 D/Mono ( 1366): Unloading image data-0x9659b010 [0xb93d5940].
</code></pre>
<p>I am running VS2015 + Xamarin Forms 2.0 latest and greatest.</p>
<p>What's going on here?</p>
| 0debug |
static int scsi_handle_rw_error(SCSIDiskReq *r, int error, int type)
{
int is_read = (type == SCSI_REQ_STATUS_RETRY_READ);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
BlockErrorAction action = bdrv_get_on_error(s->bs, is_read);
if (action == BLOCK_ERR_IGNORE) {
bdrv_mon_event(s->bs, BDRV_ACTION_IGNORE, is_read);
return 0;
}
if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)
|| action == BLOCK_ERR_STOP_ANY) {
type &= SCSI_REQ_STATUS_RETRY_TYPE_MASK;
r->status |= SCSI_REQ_STATUS_RETRY | type;
bdrv_mon_event(s->bs, BDRV_ACTION_STOP, is_read);
vm_stop(VMSTOP_DISKFULL);
} else {
if (type == SCSI_REQ_STATUS_RETRY_READ) {
scsi_req_data(&r->req, 0);
}
scsi_command_complete(r, CHECK_CONDITION,
HARDWARE_ERROR);
bdrv_mon_event(s->bs, BDRV_ACTION_REPORT, is_read);
}
return 1;
}
| 1threat |
static int pci_qdev_init(DeviceState *qdev, DeviceInfo *base)
{
PCIDevice *pci_dev = (PCIDevice *)qdev;
PCIDeviceInfo *info = container_of(base, PCIDeviceInfo, qdev);
PCIBus *bus;
int devfn, rc;
if (info->is_express) {
pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
}
bus = FROM_QBUS(PCIBus, qdev_get_parent_bus(qdev));
devfn = pci_dev->devfn;
pci_dev = do_pci_register_device(pci_dev, bus, base->name, devfn,
info->config_read, info->config_write,
info->header_type);
assert(pci_dev);
rc = info->init(pci_dev);
if (rc != 0)
return rc;
if (qdev->hotplugged)
bus->hotplug(pci_dev, 1);
return 0;
}
| 1threat |
int qdev_prop_check_globals(void)
{
GlobalProperty *prop;
int ret = 0;
QTAILQ_FOREACH(prop, &global_props, next) {
ObjectClass *oc;
DeviceClass *dc;
if (prop->used) {
continue;
}
if (!prop->user_provided) {
continue;
}
oc = object_class_by_name(prop->driver);
oc = object_class_dynamic_cast(oc, TYPE_DEVICE);
if (!oc) {
error_report("Warning: global %s.%s has invalid class name",
prop->driver, prop->property);
ret = 1;
continue;
}
dc = DEVICE_CLASS(oc);
if (!dc->hotpluggable && !prop->used) {
error_report("Warning: global %s.%s=%s not used",
prop->driver, prop->property, prop->value);
ret = 1;
continue;
}
}
return ret;
}
| 1threat |
Integrating Google Maps in vue.js : <p>I've been trying to initialize a Google map on my vue.js project while including the script :</p>
<pre><code><script src="https://maps.googleapis.com/maps/api/js?key="MY_API_KEY"&callback=initMap" async defer></script>
</code></pre>
<p>The problem is that my .vue files look like that : </p>
<pre><code><template>
...
</template>
<script>
...
</script>
</code></pre>
<p>And I can't include more than one script tag in my vue file, I can show the map while passing by the index.html but I dont really want to put js on the index.html, + I can't point the script callback on a vue method.</p>
<p>Do you guys have some ideas on how to show up that map using a .vue file ? I did use vue2-google-maps but I'd like to use the original google map. </p>
<p>I have a fiddle which is doing something ok : <a href="https://jsfiddle.net/okubdoqa/" rel="noreferrer">https://jsfiddle.net/okubdoqa/</a> without using a callback in the script tag, but it doesnt work for me ... Thanks</p>
| 0debug |
Math in csharp (Unity) : Im trying to use Math.pow in csharp, dont can't get it work...
The code I know that works, but with js:
var levelCost = Math.floor(200 * Math.pow(1.12, level));
I have been trying to convert it to csharp, but with not help. | 0debug |
static void read_id3(AVFormatContext *s, uint64_t id3pos)
{
ID3v2ExtraMeta *id3v2_extra_meta = NULL;
if (avio_seek(s->pb, id3pos, SEEK_SET) < 0)
return;
ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
if (id3v2_extra_meta)
ff_id3v2_parse_apic(s, &id3v2_extra_meta);
ff_id3v2_free_extra_meta(&id3v2_extra_meta);
}
| 1threat |
i have a question about to select the last line of the RichTextBox : <p>I have a Question to select the last line of the RichTextBox
When i click the Button1 it will show the last line in the Messagebox </p>
<p>I tried a lot of codes by it only select the index of the lines
i need your help</p>
<p>I want the output like </p>
<p>these are the lines i write in the RichTextBox</p>
<p>1.hello</p>
<p>2.world</p>
<p>3.welcome</p>
<p>when i click the button1 it will show the last line in messagebox</p>
<p>3.welcome // it will appears in the message box</p>
| 0debug |
which is better every user have a table or just a row : <p>I making android app part of it is that user will upload videos and inter some details and all this stuff and choose videos as favorite and found all videos he uploaded in one place , so which is better making for every user a table or just a row in a table </p>
| 0debug |
Testing POST ActionDispatch::Http::Parameters::ParseError: 765 : <p>It says there's an unexpected token in my params.</p>
<p><code>"ActionDispatch::Http::Parameters::ParseError: 765: unexpected token at 'conversation_identifier[participant_list][]=2&conversation_identifier[participant_list][]=1"</code></p>
<p>A version of the test with magic numbers for clarity:</p>
<pre><code>let(:headers) do
{ 'HTTP_CURRENT_USER_ID' => 2,
'Content-Type' => 'application/json' }
end
let(:params) { { conversation_identifier: { participant_list: [1, 2] } }
it 'is getting testy' do
post resource_url, params: params, headers: headers
assert_equal 201, response.status
end
</code></pre>
<p>Now here's what's weird. It has no trouble parsing those params if I give it no headers.</p>
| 0debug |
How do I see the permission of a file in Git? : <p>I'd like to see the file permission as it exists in the repository index.</p>
<p>How can this be done? </p>
| 0debug |
How to fix Android compatibility warnings : <p>I have an app that is targeting Android 9 and I noticed in the Google Play prelaunch report a new section called Android compatibility. This new section lists warnings or errors related to the usage of unsupported APIs. The following is one of the problems and is listed as a greylisted API. Can someone explain which is the unsupported API in this case? The usage seems to be coming from the Android support library and not my code.</p>
<pre><code>StrictMode policy violation: android.os.strictmode.NonSdkApiUsedViolation: Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V
at android.os.StrictMode.lambda$static$1(StrictMode.java:428)
at android.os.-$$Lambda$StrictMode$lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source:2)
at java.lang.Class.getDeclaredMethodInternal(Native Method)
at java.lang.Class.getPublicMethodRecursive(Class.java:2075)
at java.lang.Class.getMethod(Class.java:2063)
at java.lang.Class.getMethod(Class.java:1690)
at android.support.v7.widget.ViewUtils.makeOptionalFitsSystemWindows(ViewUtils.java:84)
at android.support.v7.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:685)
at android.support.v7.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:518)
at android.support.v7.app.AppCompatDelegateImpl.onPostCreate(AppCompatDelegateImpl.java:299)
at android.support.v7.app.AppCompatActivity.onPostCreate(AppCompatActivity.java:98)
at android.app.Instrumentation.callActivityOnPostCreate(Instrumentation.java:1342)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3002)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6718)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code></pre>
| 0debug |
Integer only input Javascript : <p>I am unsure on how to create an input box that only allows integers to be inputted. I have made a HTML version of the input but I need the same input type within JavaScript.</p>
<p>Here's my current HTML input</p>
<pre><code><input type="text" autocomplete="off" ondragstart="return false;" ondrop="return false;" onpaste="return false;" onkeypress="return event.charCode >= 48 && event.charCode <= 57;">Amount</input>
</code></pre>
| 0debug |
Mysql Query to find out third line manager : There is a employee table with id, manager_id, salary, department
I want to know the maximum salary department wise for third line managers | 0debug |
Passing any array type to a function in C : <p>I am trying to write a function that makes ordenations over any numeric array given to it.
The problem is that C needs to know the data type to iterate through the array properly, because of its "pointer nature".
Is there any way that I can pass any array without knowing the type? Maybe using the void type?</p>
<pre><code>void ordenation (void *array, ...) {}
</code></pre>
| 0debug |
PWA icons are not used in iOS 11.3 : <p>Now I'm testing PWA on iOS 11.3 and I use the manifest.json file below:</p>
<pre><code>{
"name": "Maplat PWA Sample",
"short_name": "Maplat PWA",
"background_color": "#fc980c",
"icons": [{
"src": "/Maplat/pwa/icon-96.png",
"sizes": "96x96",
"type": "image/png"
},{
"src": "/Maplat/pwa/icon-144.png",
"sizes": "144x144",
"type": "image/png"
},{
"src": "/Maplat/pwa/icon-192.png",
"sizes": "192x192",
"type": "image/png"
},{
"src": "/Maplat/pwa/icon-256.png",
"sizes": "256x256",
"type": "image/png"
}],
"start_url": "/Maplat/debug.html?overlay=true",
"display": "standalone"
}
</code></pre>
<p>This works well except icon setting.
In my iOS 11.3 on iPhoneX, icon files are not shown on home screen but screen capture is used as launcher button.</p>
<p>I compared my manifest with other sites, like <a href="https://www.ft.com/" rel="noreferrer">https://www.ft.com/</a> or <a href="https://r.nikkei.com/" rel="noreferrer">https://r.nikkei.com/</a>, but I couldn't find any differences in icon settings.
Icons of these sites work well with PWA on iOS 11.3.</p>
<p>What is wrong in my manifest.json?</p>
<p>P.S. My manifest.json works well with Android Chrome.</p>
| 0debug |
Java usage() method : <p>Hi Stackoverflow community</p>
<p>I have been trying to find a resource or reference that explains what the usage() method does. Unfortunately the word 'usage' is indexed so often in different contexts that I simply can't find a good resource. Would anybody be able to point me in the right direction?</p>
<pre><code>public static void main(String[] args) {
if (args.length == 0) {
usage();
} else if ("parse".equals(args[0])) {
final String[] parseArgs = new String[args.length - 1];
etc ....
</code></pre>
<p>I know that in C getusage() is used to get memory and CPU usage statistics. Is this the same case in Java? Any pointers would be highly appreciated.
Mike</p>
| 0debug |
static void filter_mb_mbaff_edgecv( H264Context *h, uint8_t *pix, int stride, const int16_t bS[7], int bsi, int qp ) {
const int qp_bd_offset = 6 * (h->sps.bit_depth_luma - 8);
int index_a = qp - qp_bd_offset + h->slice_alpha_c0_offset;
int alpha = alpha_table[index_a];
int beta = beta_table[qp - qp_bd_offset + h->slice_beta_offset];
if (alpha ==0 || beta == 0) return;
if( bS[0] < 4 ) {
int8_t tc[4];
tc[0] = tc0_table[index_a][bS[0*bsi]] + 1;
tc[1] = tc0_table[index_a][bS[1*bsi]] + 1;
tc[2] = tc0_table[index_a][bS[2*bsi]] + 1;
tc[3] = tc0_table[index_a][bS[3*bsi]] + 1;
h->h264dsp.h264_h_loop_filter_chroma_mbaff(pix, stride, alpha, beta, tc);
} else {
h->h264dsp.h264_h_loop_filter_chroma_mbaff_intra(pix, stride, alpha, beta);
}
}
| 1threat |
how do I create android app using wordpress database? : <p>I had completed my website in wordpress,so can I use my wordpress database to connect android app? how? give me perfect references.</p>
| 0debug |
Upgrade PHP version 5.6 -> 7 issues on Linux : <p>Maybe its an old question, but i have some difficulties installing php 7 on my ubuntu environment. Right now I have ubuntu 15.10 and this is php version:</p>
<pre><code>PHP 5.6.11-1ubuntu3.4 (cli)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
</code></pre>
<p>I tried this method to install it: </p>
<pre><code>sudo add-apt-repository ppa:ondrej/php
</code></pre>
<p>and this was the result:</p>
<pre><code>gpg: keyring `/tmp/tmpp_pz87v9/secring.gpg' created
gpg: keyring `/tmp/tmpp_pz87v9/pubring.gpg' created
gpg: requesting key E5267A6C from hkp server keyserver.ubuntu.com
gpg: /tmp/tmpp_pz87v9/trustdb.gpg: trustdb created
gpg: key E5267A6C: public key "Launchpad PPA for Ondřej Surý" imported
gpg: Total number processed: 1
gpg: imported: 1 (RSA: 1)
OK
</code></pre>
<p>afther I executed this: <code>sudo apt-get update</code> and then: </p>
<pre><code>sudo apt-get install php7.0
</code></pre>
<p>and the result of the last command is: </p>
<pre><code>Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package php7.0
E: Couldn't find any package by regex 'php7.0'
</code></pre>
<p>I have no idea what should I do next ? can you help me? thx </p>
| 0debug |
implement C=|A-B| with inc,dec,jnz (A,B are none negative) : Its a question I saw in an interview :
A,B are none negative numbers and you need to return C=|A-B| where you have only the following instruction :
**Inc register** - adds one to **register**
**Dec register** - substracts one from **register**
**JNZ LABEL** - jumps to labael if last instruction result was not zero
In addition you can use other registers that their initial value is zero;
Thanks for your help | 0debug |
static int tta_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
TTAContext *s = avctx->priv_data;
int i, ret;
int cur_chan = 0, framelen = s->frame_length;
int32_t *p;
if (avctx->err_recognition & AV_EF_CRCCHECK) {
if (buf_size < 4 || tta_check_crc(s, buf, buf_size - 4))
return AVERROR_INVALIDDATA;
}
init_get_bits(&s->gb, buf, buf_size*8);
s->total_frames--;
if (!s->total_frames && s->last_frame_length)
framelen = s->last_frame_length;
s->frame.nb_samples = framelen;
if ((ret = ff_get_buffer(avctx, &s->frame)) < 0) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
return ret;
}
if (s->bps == 3)
s->decode_buffer = (int32_t *)s->frame.data[0];
for (i = 0; i < s->channels; i++) {
s->ch_ctx[i].predictor = 0;
ttafilter_init(&s->ch_ctx[i].filter, ttafilter_configs[s->bps-1]);
rice_init(&s->ch_ctx[i].rice, 10, 10);
}
for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++) {
int32_t *predictor = &s->ch_ctx[cur_chan].predictor;
TTAFilter *filter = &s->ch_ctx[cur_chan].filter;
TTARice *rice = &s->ch_ctx[cur_chan].rice;
uint32_t unary, depth, k;
int32_t value;
unary = tta_get_unary(&s->gb);
if (unary == 0) {
depth = 0;
k = rice->k0;
} else {
depth = 1;
k = rice->k1;
unary--;
}
if (get_bits_left(&s->gb) < k) {
ret = AVERROR_INVALIDDATA;
goto error;
}
if (k) {
if (k > MIN_CACHE_BITS) {
ret = AVERROR_INVALIDDATA;
goto error;
}
value = (unary << k) + get_bits(&s->gb, k);
} else
value = unary;
switch (depth) {
case 1:
rice->sum1 += value - (rice->sum1 >> 4);
if (rice->k1 > 0 && rice->sum1 < shift_16[rice->k1])
rice->k1--;
else if(rice->sum1 > shift_16[rice->k1 + 1])
rice->k1++;
value += shift_1[rice->k0];
default:
rice->sum0 += value - (rice->sum0 >> 4);
if (rice->k0 > 0 && rice->sum0 < shift_16[rice->k0])
rice->k0--;
else if(rice->sum0 > shift_16[rice->k0 + 1])
rice->k0++;
}
*p = 1 + ((value >> 1) ^ ((value & 1) - 1));
ttafilter_process(filter, p);
#define PRED(x, k) (int32_t)((((uint64_t)x << k) - x) >> k)
switch (s->bps) {
case 1: *p += PRED(*predictor, 4); break;
case 2:
case 3: *p += PRED(*predictor, 5); break;
case 4: *p += *predictor; break;
}
*predictor = *p;
if (cur_chan < (s->channels-1))
cur_chan++;
else {
if (s->channels > 1) {
int32_t *r = p - 1;
for (*p += *r / 2; r > p - s->channels; r--)
*r = *(r + 1) - *r;
}
cur_chan = 0;
}
}
if (get_bits_left(&s->gb) < 32) {
ret = AVERROR_INVALIDDATA;
goto error;
}
skip_bits_long(&s->gb, 32);
if (s->bps == 2) {
int16_t *samples = (int16_t *)s->frame.data[0];
for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++)
*samples++ = *p;
} else {
int32_t *samples = (int32_t *)s->frame.data[0];
for (i = 0; i < framelen * s->channels; i++)
*samples++ <<= 8;
s->decode_buffer = NULL;
}
*got_frame_ptr = 1;
*(AVFrame *)data = s->frame;
return buf_size;
error:
if (s->bps == 3)
s->decode_buffer = NULL;
return ret;
}
| 1threat |
What is the right granularity for a microsrevice? : <p>We have a site that compares flight fares and books tickets via API calls to the aggregators who provide us with flight inventory and fares. Payment for tickets happen via API calls to paymentgateways from our site. We have similar capability for hotel booking. Hotel booking and flight booking are implemented as separate services using Lumen. Since hotel booking also uses the same payment gateways as flight, we end up duplicating that code under Hotel Services. May be it is a better idea to convert payment into a separate microservice. The question is, what is the right granularity for a micro service?</p>
| 0debug |
Recommendations on improving my built-in linked list garbage collection : <p>I'm currently learning about linked lists, and I'm building one myself in C++ in order to fully grasp the concept. Every method seems to work. However, I'm not confident in my implemented garbage collection of my Node class and LinkedList class. Can anyone look at it and give any suggestions for improval? Thank you!</p>
<pre><code>#include <iostream>
#include <vector>
#include <map>
template<class T>
struct Node
{
T value;
Node* next;
Node() {
next = nullptr; // Set the default of next to nullptr
}
~Node() {
if (next) {
delete next;
next = nullptr;
}
}
};
template<class T>
class LinkedList
{
private:
Node<T>* head;
Node<T>* tail;
unsigned int length;
Node<T>* traverseToIndex(const unsigned short& index);
public:
LinkedList();
~LinkedList();
void append(const T& value);
void prepend(const T& value);
void insert(const unsigned short& index, const T& value);
void remove(const unsigned short& index);
};
int main()
{
LinkedList<int> nums;
nums.append(5);
nums.append(1);
nums.append(3);
nums.append(4);
nums.remove(2);
return 0;
}
template<class T>
LinkedList<T>::LinkedList()
{
this->length = 0;
head = new Node<T>;
tail = head;
}
template<class T>
LinkedList<T>::~LinkedList()
{
delete head;
}
template<class T>
Node<T>* LinkedList<T>::traverseToIndex(const unsigned short& index)
{
if (index >= this->length) return tail;
Node<T>* currentNode = head;
for (unsigned short i = 0; i < index; i++) {
currentNode = currentNode->next;
}
return currentNode;
}
template<class T>
void LinkedList<T>::append(const T& value)
{
if (length == 0) {
head->value = value;
} else {
Node<T>* newNode = new Node<T>;
newNode->value = value;
tail->next = newNode;
tail = newNode;
}
length++;
}
template<class T>
void LinkedList<T>::prepend(const T& value)
{
Node<T>* newNode = new Node<T>;
newNode->value = value;
newNode->next = head;
head = newNode;
}
template<class T>
void LinkedList<T>::insert(const unsigned short& index, const T& value)
{
if (index >= this->length || index <= 0) return;
Node<T>* before = this->traverseToIndex(index - 1);
Node<T>* after = before->next;
Node<T>* newNode = new Node<T>;
newNode->value = value;
newNode->next = after;
before->next = newNode;
this->length++;
}
template<class T>
void LinkedList<T>::remove(const unsigned short& index)
{
Node<T>* before = this->traverseToIndex(index - 1);
Node<T>* deletedNode = before->next;
Node<T>* after = deletedNode->next;
before->next = after;
this->length--;
}
</code></pre>
| 0debug |
static const QListEntry *qmp_input_push(QmpInputVisitor *qiv, QObject *obj,
void *qapi, Error **errp)
{
GHashTable *h;
StackObject *tos = g_new0(StackObject, 1);
assert(obj);
tos->obj = obj;
tos->qapi = qapi;
if (qiv->strict && qobject_type(obj) == QTYPE_QDICT) {
h = g_hash_table_new(g_str_hash, g_str_equal);
qdict_iter(qobject_to_qdict(obj), qdict_add_key, h);
tos->h = h;
} else if (qobject_type(obj) == QTYPE_QLIST) {
tos->entry = qlist_first(qobject_to_qlist(obj));
}
QSLIST_INSERT_HEAD(&qiv->stack, tos, node);
return tos->entry;
}
| 1threat |
int ff_vp8_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
AVPacket *avpkt)
{
VP8Context *s = avctx->priv_data;
int ret, i, referenced, num_jobs;
enum AVDiscard skip_thresh;
VP8Frame *av_uninit(curframe), *prev_frame;
if ((ret = decode_frame_header(s, avpkt->data, avpkt->size)) < 0)
goto err;
prev_frame = s->framep[VP56_FRAME_CURRENT];
referenced = s->update_last || s->update_golden == VP56_FRAME_CURRENT ||
s->update_altref == VP56_FRAME_CURRENT;
skip_thresh = !referenced ? AVDISCARD_NONREF
: !s->keyframe ? AVDISCARD_NONKEY
: AVDISCARD_ALL;
if (avctx->skip_frame >= skip_thresh) {
s->invisible = 1;
memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4);
goto skip_decode;
}
s->deblock_filter = s->filter.level && avctx->skip_loop_filter < skip_thresh;
for (i = 0; i < 5; i++)
if (s->frames[i].tf.f->data[0] &&
&s->frames[i] != prev_frame &&
&s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&
&s->frames[i] != s->framep[VP56_FRAME_GOLDEN] &&
&s->frames[i] != s->framep[VP56_FRAME_GOLDEN2])
vp8_release_frame(s, &s->frames[i]);
for (i = 0; i < 5; i++)
if (&s->frames[i] != prev_frame &&
&s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&
&s->frames[i] != s->framep[VP56_FRAME_GOLDEN] &&
&s->frames[i] != s->framep[VP56_FRAME_GOLDEN2]) {
curframe = s->framep[VP56_FRAME_CURRENT] = &s->frames[i];
break;
}
if (i == 5) {
av_log(avctx, AV_LOG_FATAL, "Ran out of free frames!\n");
abort();
}
if (curframe->tf.f->data[0])
vp8_release_frame(s, curframe);
if (!s->keyframe && (!s->framep[VP56_FRAME_PREVIOUS] ||
!s->framep[VP56_FRAME_GOLDEN] ||
!s->framep[VP56_FRAME_GOLDEN2])) {
av_log(avctx, AV_LOG_WARNING,
"Discarding interframe without a prior keyframe!\n");
ret = AVERROR_INVALIDDATA;
goto err;
}
curframe->tf.f->key_frame = s->keyframe;
curframe->tf.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
: AV_PICTURE_TYPE_P;
if ((ret = vp8_alloc_frame(s, curframe, referenced))) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() failed!\n");
goto err;
}
if (s->update_altref != VP56_FRAME_NONE)
s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[s->update_altref];
else
s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[VP56_FRAME_GOLDEN2];
if (s->update_golden != VP56_FRAME_NONE)
s->next_framep[VP56_FRAME_GOLDEN] = s->framep[s->update_golden];
else
s->next_framep[VP56_FRAME_GOLDEN] = s->framep[VP56_FRAME_GOLDEN];
if (s->update_last)
s->next_framep[VP56_FRAME_PREVIOUS] = curframe;
else
s->next_framep[VP56_FRAME_PREVIOUS] = s->framep[VP56_FRAME_PREVIOUS];
s->next_framep[VP56_FRAME_CURRENT] = curframe;
ff_thread_finish_setup(avctx);
s->linesize = curframe->tf.f->linesize[0];
s->uvlinesize = curframe->tf.f->linesize[1];
memset(s->top_nnz, 0, s->mb_width * sizeof(*s->top_nnz));
if (!s->mb_layout)
memset(s->macroblocks + s->mb_height * 2 - 1, 0,
(s->mb_width + 1) * sizeof(*s->macroblocks));
if (!s->mb_layout && s->keyframe)
memset(s->intra4x4_pred_mode_top, DC_PRED, s->mb_width * 4);
memset(s->ref_count, 0, sizeof(s->ref_count));
if (s->mb_layout == 1) {
if (prev_frame && s->segmentation.enabled &&
!s->segmentation.update_map)
ff_thread_await_progress(&prev_frame->tf, 1, 0);
vp8_decode_mv_mb_modes(avctx, curframe, prev_frame);
}
if (avctx->active_thread_type == FF_THREAD_FRAME)
num_jobs = 1;
else
num_jobs = FFMIN(s->num_coeff_partitions, avctx->thread_count);
s->num_jobs = num_jobs;
s->curframe = curframe;
s->prev_frame = prev_frame;
s->mv_min.y = -MARGIN;
s->mv_max.y = ((s->mb_height - 1) << 6) + MARGIN;
for (i = 0; i < MAX_THREADS; i++) {
s->thread_data[i].thread_mb_pos = 0;
s->thread_data[i].wait_mb_pos = INT_MAX;
}
avctx->execute2(avctx, vp8_decode_mb_row_sliced,
s->thread_data, NULL, num_jobs);
ff_thread_report_progress(&curframe->tf, INT_MAX, 0);
memcpy(&s->framep[0], &s->next_framep[0], sizeof(s->framep[0]) * 4);
skip_decode:
if (!s->update_probabilities)
s->prob[0] = s->prob[1];
if (!s->invisible) {
if ((ret = av_frame_ref(data, curframe->tf.f)) < 0)
return ret;
*got_frame = 1;
}
return avpkt->size;
err:
memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4);
return ret;
}
| 1threat |
Is there a way to copy from ubunt to windows? like a command or feature I can install? : <p>So right now I'm running into two problems in windows:</p>
<p>1) Is there a way to connect the keyboard from windows to ubuntu virtual box? Because if I copy something in windows and right now I can't paste into ubuntu, and vice versa, do I need to install a feature?</p>
| 0debug |
Nodemon Doesn't Restart in Windows Docker Environment : <p>My goal is to set up a Docker container that automatically restarts a NodeJS server when file changes are detected from the host machine.</p>
<p>I have chosen nodemon to watch the files for changes.</p>
<p>On Linux and Mac environments, nodemon and docker are working flawlessly.</p>
<p>However, when I am in a <strong>Windows environment</strong>, nodemon doesn't restart the server.</p>
<p>The files are updated on the host machine, and are linked using the <code>volumes</code> parameter in my docker-compose.yml file. </p>
<p>I can see the files have changed when I run <code>docker exec <container-name> cat /path/to/fileChanged.js</code>. This way I know the files are being linked correctly and have been modified in the container.</p>
<p><strong>Is there any reason why nodemon doesn't restart the server for Windows?</strong> </p>
| 0debug |
static void filter_mb_fast( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize) {
MpegEncContext * const s = &h->s;
int mb_xy, mb_type;
int qp, qp0, qp1, qpc, qpc0, qpc1, qp_thresh;
mb_xy = mb_x + mb_y*s->mb_stride;
if(mb_x==0 || mb_y==0 || !s->dsp.h264_loop_filter_strength ||
(h->deblocking_filter == 2 && (h->slice_table[mb_xy] != h->slice_table[h->top_mb_xy] ||
h->slice_table[mb_xy] != h->slice_table[mb_xy - 1]))) {
filter_mb(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize);
return;
}
assert(!FRAME_MBAFF);
mb_type = s->current_picture.mb_type[mb_xy];
qp = s->current_picture.qscale_table[mb_xy];
qp0 = s->current_picture.qscale_table[mb_xy-1];
qp1 = s->current_picture.qscale_table[h->top_mb_xy];
qpc = get_chroma_qp( h, qp );
qpc0 = get_chroma_qp( h, qp0 );
qpc1 = get_chroma_qp( h, qp1 );
qp0 = (qp + qp0 + 1) >> 1;
qp1 = (qp + qp1 + 1) >> 1;
qpc0 = (qpc + qpc0 + 1) >> 1;
qpc1 = (qpc + qpc1 + 1) >> 1;
qp_thresh = 15 - h->slice_alpha_c0_offset;
if(qp <= qp_thresh && qp0 <= qp_thresh && qp1 <= qp_thresh &&
qpc <= qp_thresh && qpc0 <= qp_thresh && qpc1 <= qp_thresh)
return;
if( IS_INTRA(mb_type) ) {
int16_t bS4[4] = {4,4,4,4};
int16_t bS3[4] = {3,3,3,3};
if( IS_8x8DCT(mb_type) ) {
filter_mb_edgev( h, &img_y[4*0], linesize, bS4, qp0 );
filter_mb_edgev( h, &img_y[4*2], linesize, bS3, qp );
filter_mb_edgeh( h, &img_y[4*0*linesize], linesize, bS4, qp1 );
filter_mb_edgeh( h, &img_y[4*2*linesize], linesize, bS3, qp );
} else {
filter_mb_edgev( h, &img_y[4*0], linesize, bS4, qp0 );
filter_mb_edgev( h, &img_y[4*1], linesize, bS3, qp );
filter_mb_edgev( h, &img_y[4*2], linesize, bS3, qp );
filter_mb_edgev( h, &img_y[4*3], linesize, bS3, qp );
filter_mb_edgeh( h, &img_y[4*0*linesize], linesize, bS4, qp1 );
filter_mb_edgeh( h, &img_y[4*1*linesize], linesize, bS3, qp );
filter_mb_edgeh( h, &img_y[4*2*linesize], linesize, bS3, qp );
filter_mb_edgeh( h, &img_y[4*3*linesize], linesize, bS3, qp );
}
filter_mb_edgecv( h, &img_cb[2*0], uvlinesize, bS4, qpc0 );
filter_mb_edgecv( h, &img_cb[2*2], uvlinesize, bS3, qpc );
filter_mb_edgecv( h, &img_cr[2*0], uvlinesize, bS4, qpc0 );
filter_mb_edgecv( h, &img_cr[2*2], uvlinesize, bS3, qpc );
filter_mb_edgech( h, &img_cb[2*0*uvlinesize], uvlinesize, bS4, qpc1 );
filter_mb_edgech( h, &img_cb[2*2*uvlinesize], uvlinesize, bS3, qpc );
filter_mb_edgech( h, &img_cr[2*0*uvlinesize], uvlinesize, bS4, qpc1 );
filter_mb_edgech( h, &img_cr[2*2*uvlinesize], uvlinesize, bS3, qpc );
return;
} else {
DECLARE_ALIGNED_8(int16_t, bS[2][4][4]);
uint64_t (*bSv)[4] = (uint64_t(*)[4])bS;
int edges;
if( IS_8x8DCT(mb_type) && (h->cbp&7) == 7 ) {
edges = 4;
bSv[0][0] = bSv[0][2] = bSv[1][0] = bSv[1][2] = 0x0002000200020002ULL;
} else {
int mask_edge1 = (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16)) ? 3 :
(mb_type & MB_TYPE_16x8) ? 1 : 0;
int mask_edge0 = (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16))
&& (s->current_picture.mb_type[mb_xy-1] & (MB_TYPE_16x16 | MB_TYPE_8x16))
? 3 : 0;
int step = IS_8x8DCT(mb_type) ? 2 : 1;
edges = (mb_type & MB_TYPE_16x16) && !(h->cbp & 15) ? 1 : 4;
s->dsp.h264_loop_filter_strength( bS, h->non_zero_count_cache, h->ref_cache, h->mv_cache,
(h->slice_type == B_TYPE), edges, step, mask_edge0, mask_edge1 );
}
if( IS_INTRA(s->current_picture.mb_type[mb_xy-1]) )
bSv[0][0] = 0x0004000400040004ULL;
if( IS_INTRA(s->current_picture.mb_type[h->top_mb_xy]) )
bSv[1][0] = 0x0004000400040004ULL;
#define FILTER(hv,dir,edge)\
if(bSv[dir][edge]) {\
filter_mb_edge##hv( h, &img_y[4*edge*(dir?linesize:1)], linesize, bS[dir][edge], edge ? qp : qp##dir );\
if(!(edge&1)) {\
filter_mb_edgec##hv( h, &img_cb[2*edge*(dir?uvlinesize:1)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir );\
filter_mb_edgec##hv( h, &img_cr[2*edge*(dir?uvlinesize:1)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir );\
}\
}
if( edges == 1 ) {
FILTER(v,0,0);
FILTER(h,1,0);
} else if( IS_8x8DCT(mb_type) ) {
FILTER(v,0,0);
FILTER(v,0,2);
FILTER(h,1,0);
FILTER(h,1,2);
} else {
FILTER(v,0,0);
FILTER(v,0,1);
FILTER(v,0,2);
FILTER(v,0,3);
FILTER(h,1,0);
FILTER(h,1,1);
FILTER(h,1,2);
FILTER(h,1,3);
}
#undef FILTER
}
}
| 1threat |
def is_Isomorphic(str1,str2):
dict_str1 = {}
dict_str2 = {}
for i, value in enumerate(str1):
dict_str1[value] = dict_str1.get(value,[]) + [i]
for j, value in enumerate(str2):
dict_str2[value] = dict_str2.get(value,[]) + [j]
if sorted(dict_str1.values()) == sorted(dict_str2.values()):
return True
else:
return False | 0debug |
ER Diagram Design: Should every entity have a primary key? And can we have sub entity? : **Problem: Design a ER diagram such as:**
- An item has the attribute: description.
- An item can be sold by a company or a person.
- A person has the attributes: name, phone and email.
- A company has the attributes: company name, address and a contact person who is one from the person entity set.
- A contact person cannot sell the same item with the company he works for.
**This is my design:**
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/rSzPQ.png
I'm learning and I know this is a stupid question. But please correct and point out what are wrong in my design.
- I'm not sure that I should remove the primary key SellerID in Seller entity and add companyID to Company entity and personID entity.
- Is the Contact Person entity connected to Person entity correctly?
- How can I demonstrate the constraint: a contact person cannot sell the items (distinguished by item ID) his company is selling.
Thank you. | 0debug |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.