problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
How to sort the keys of a dictionary in Python? : <p>I have a dictionary whose keys are integers, but when iterating over it I would like the integers to appear in a non-sorted order. In a simple example this seems to work with an <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow noreferrer">OrderedDict</a>:</p>
<pre><code>In [16]: d3 = OrderedDict({k: k+1 for k in [3, 2, 1]})
In [17]: for k, v in d3.items():
...: print(k, v)
...:
3 4
2 3
1 2
</code></pre>
<p>However, in my 'real' application this is not working as expected. I'm trying to identify the strongly connected components (SCCs) of a directed graph. In my <code>Graph</code> class, I'm in the process of writing the <code>strongly_connected_component</code> method:</p>
<pre><code>import pytest
import collections
class Node(object):
def __init__(self):
self.color = 'white'
self.parent = None
self.d = None # Discovery time
self.f = None # Finishing time
class Graph(object):
def __init__(self, edges):
self.edges = edges
self.nodes = self.initialize_nodes()
self.adj = self.initialize_adjacency_list()
def initialize_nodes(self, node_indices=None):
if node_indices is None:
node_indices = sorted(list(set(node for edge in self.edges for node in edge)))
return collections.OrderedDict({node_index: Node() for node_index in node_indices})
def initialize_adjacency_list(self):
A = {node: [] for node in self.nodes}
for edge in self.edges:
u, v = edge
A[u].append(v)
return A
def dfs(self):
self.time = 0
for u, node in self.nodes.items():
if node.color == 'white':
self.dfs_visit(u)
def dfs_visit(self, u):
self.time += 1
self.nodes[u].d = self.time
self.nodes[u].color = 'gray'
for v in self.adj[u]:
if self.nodes[v].color == 'white':
self.nodes[v].parent = u
self.dfs_visit(v)
self.nodes[u].color = 'black'
self.time += 1
self.nodes[u].f = self.time
@staticmethod
def transpose(edges):
return [(v,u) for (u,v) in edges]
def strongly_connected_components(self):
self.dfs()
finishing_times = {u: node.f for u, node in self.nodes.items()}
# print(finishing_times)
self.__init__(self.transpose(self.edges))
node_indices = sorted(finishing_times, key=self.nodes.get, reverse=True)
# print(node_indices)
self.nodes = self.initialize_nodes(node_indices)
# print(self.nodes)
</code></pre>
<p>In order to verify that the <code>dfs</code> method is working, I reproduced the following example from Cormen et al., <em>Introduction to Algorithms</em>:</p>
<p><a href="https://i.stack.imgur.com/Om6KP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Om6KP.png" alt="enter image description here"></a></p>
<p>where I've replaced the node labels <em>u</em> through <em>z</em> with the numbers <code>1</code> through <code>6</code>, respectively. The following test,</p>
<pre><code>def test_dfs():
'''This example is taken from Cormen et al., Introduction to Algorithms (3rd ed.), Figure 22.4'''
edges = [(1,2), (1,4), (4,2), (5,4), (2,5), (3,5), (3,6), (6,6)]
graph = Graph(edges)
graph.dfs()
print("\n")
for index, node in graph.nodes.items():
print index, node.__dict__
</code></pre>
<p>prints</p>
<pre><code>1 {'color': 'black', 'd': 1, 'parent': None, 'f': 8}
2 {'color': 'black', 'd': 2, 'parent': 1, 'f': 7}
3 {'color': 'black', 'd': 9, 'parent': None, 'f': 12}
4 {'color': 'black', 'd': 4, 'parent': 5, 'f': 5}
5 {'color': 'black', 'd': 3, 'parent': 2, 'f': 6}
6 {'color': 'black', 'd': 10, 'parent': 3, 'f': 11}
</code></pre>
<p>which is readily seen to correspond with Figure 22.4(p) from the book. In order to compute the SCCs, I have to implement the following pseudocode:</p>
<p><a href="https://i.stack.imgur.com/4BBaP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4BBaP.png" alt="enter image description here"></a></p>
<p>In my <code>strongly_connected_components</code> method, I order the <code>node_indices</code> by finishing time in reverse order. Since it is initialized as an <code>OrderedDict</code> in the <code>initialize_nodes</code> methods, I would expect the following test to pass:</p>
<pre><code>def test_strongly_connected_components():
edges = [(1,2), (1,4), (4,2), (5,4), (2,5), (3,5), (3,6), (6,6)]
graph = Graph(edges)
graph.strongly_connected_components()
assert graph.nodes.keys() == [3, 2, 1, 4, 6, 5]
if __name__ == "__main__":
pytest.main([__file__, "-s"])
</code></pre>
<p>since <code>[3, 2, 1, 4, 6, 5]</code> is the reverse order in which the nodes were 'finished' in the depth-first search. However, this test fails:</p>
<pre><code>=================================== FAILURES ===================================
______________________ test_strongly_connected_components ______________________
def test_strongly_connected_components():
edges = [(1,2), (1,4), (4,2), (5,4), (2,5), (3,5), (3,6), (6,6)]
graph = Graph(edges)
graph.strongly_connected_components()
> assert graph.nodes.keys() == [3, 2, 1, 4, 6, 5]
E assert [1, 2, 3, 4, 5, 6] == [3, 2, 1, 4, 6, 5]
E At index 0 diff: 1 != 3
E Use -v to get the full diff
scc.py:94: AssertionError
</code></pre>
<p>Why do the keys not remain in the order specified in the initialization of the <code>OrderedDict</code>?</p>
| 0debug
|
What is the Java equivalent of Trim('/') in C# : <p>Consider this code:</p>
<pre><code>string xx = "/test/file2/".Trim('/');
Console.WriteLine(xx);
Console.Read();
</code></pre>
<p>This code returns <code>test/file2</code>. What is an efficient way to do this in Java?</p>
| 0debug
|
How to convert std::string to std::vector<uint8_t>? : <p>The data format required to save games on google play game services is : <code>std::vector<uint8_t></code> as specified under 'Data formats' on:
<a href="https://developers.google.com/games/services/cpp/savedgames" rel="noreferrer">https://developers.google.com/games/services/cpp/savedgames</a></p>
<p>I am assuming the vector represents some kind of byte array. Is that correct ? So how does one convert an <code>std::string</code> to <code>std::vector<uint8_t></code> ?</p>
| 0debug
|
Add Java import statements automatically via script : <p>Eclipse Java IDE has a shortcut <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>O</kbd> to automatically add unused imports. Where I can find script (bash, python or something other that can be executed via shell) to do this IDE-agnostically, for example, in text editor that can use scripted external tools like gedit?</p>
| 0debug
|
How do I allow access to all requests through squid proxy server? : <p>I want to enable access to all requests on Squid3 server ie. request from anywhere to anywhere through the proxy server should be allowed.</p>
<p>I've already tried adding this to the end of config file <code>/etc/squid3/squid.conf</code>:</p>
<pre><code>acl all src 0.0.0.0/0
http_access allow all
</code></pre>
<p>I'm still getting the TCP_DENIED_REPLY error:</p>
<pre><code>1490004026.216 0 10.142.224.249 TCP_DENIED_REPLY/403 3546 GET http://www.fb.com/ - HIER_NONE/- text/html
</code></pre>
<p>How do I do get this working?</p>
| 0debug
|
static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
{
ARMCPU *cpu = arm_env_get_cpu(env);
env->cp15.c3 = value;
tlb_flush(CPU(cpu), 1);
}
| 1threat
|
db.execute('SELECT * FROM products WHERE product_id = ' + product_input)
| 1threat
|
Can a progressive web app (PWA) run a background service on a mobile device to get data from hardware (accelerometer, gps...)? : <p>I see we can check the capabilities of a mobile browser using <a href="https://whatwebcando.today/" rel="noreferrer">https://whatwebcando.today/</a>, but can the hardware APIs be queried when not running on foreground?</p>
<p>I mean... With PWA am I able to build an app that gets hardware info while running in background, just like Octo U, for Android, and posts that info to a web server?</p>
| 0debug
|
IndexOutOfRangeException in CodinGame Manhattan : <p>i've stuck with IndexOutOfRangeException problem for a half of the day and can't find what the problem. The problem in</p>
<pre><code>for (int k = 0; k < 27; k++)
{
for (int i = 0; i < H; i++)
{
Alphabet[i,0,k] = "0";
}
}
</code></pre>
<p>I used Alphabet[i,0,k] = "0" for debug. Actually that expection throws even with Alphabet[0,0,0], though I have initialized that array proparly. H = 5. And the code seemed to work first time</p>
<pre><code>using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
class Solution
{
static void Main(string[] args)
{
int L = int.Parse(Console.ReadLine());
int H = int.Parse(Console.ReadLine());
string T = Console.ReadLine();
Console.Error.WriteLine(T);
Console.Error.WriteLine(T[0]);
int stringLenght = T.Length;
string [,] Row = new string [H,L*27];
string [,,] Alphabet = new string [H,0,27];
string [,] Word = new string [H,0];
for (int i = 0; i < H; i++)
{
string initRow = Console.ReadLine();
for (int j = 0; j < (L*27); j++)
{
Row[i,j] = Convert.ToString(initRow[j]);
}
}
for (int k = 0; k < 27; k++)
{
for (int i = 0; i < H; i++)
{
Console.Error.WriteLine("k=" + k);
Console.Error.WriteLine("i=" + i);
Alphabet[i,0,k] = "0";
}
}
for (int i =0; i < stringLenght; i++)
{
switch (T[i])
{
case 'E':
for (int j=0; j < H; j++)
{
Word[j,0] = Alphabet[j,0,3];
}
break;
default: break;
}
}
for (int i=0; i<H; i++)
{
Console.WriteLine(Word[i,0]);
}
}
}
}
for (int i =0; i < stringLenght; i++)
{
switch (T[i])
{
case 'E':
for (int j=0; j < H; j++)
{
Word[j,0] = Alphabet[j,0,3];
}
break;
default: break;
}
}
for (int i=0; i<H; i++)
{
Console.WriteLine(Word[i,0]);
} }
}
</code></pre>
| 0debug
|
static int spapr_nvram_init(VIOsPAPRDevice *dev)
{
sPAPRNVRAM *nvram = VIO_SPAPR_NVRAM(dev);
if (nvram->drive) {
nvram->size = bdrv_getlength(nvram->drive);
} else {
nvram->size = DEFAULT_NVRAM_SIZE;
nvram->buf = g_malloc0(nvram->size);
}
if ((nvram->size < MIN_NVRAM_SIZE) || (nvram->size > MAX_NVRAM_SIZE)) {
fprintf(stderr, "spapr-nvram must be between %d and %d bytes in size\n",
MIN_NVRAM_SIZE, MAX_NVRAM_SIZE);
return -1;
}
spapr_rtas_register(RTAS_NVRAM_FETCH, "nvram-fetch", rtas_nvram_fetch);
spapr_rtas_register(RTAS_NVRAM_STORE, "nvram-store", rtas_nvram_store);
return 0;
}
| 1threat
|
static inline void RENAME(bgr24ToUV)(uint8_t *dstU, uint8_t *dstV, uint8_t *src1, uint8_t *src2, long width)
{
#ifdef HAVE_MMX
asm volatile(
"mov %3, %%"REG_a" \n\t"
"movq "MANGLE(w1111)", %%mm5 \n\t"
"movq "MANGLE(bgr2UCoeff)", %%mm6 \n\t"
"pxor %%mm7, %%mm7 \n\t"
"lea (%%"REG_a", %%"REG_a", 2), %%"REG_d" \n\t"
"add %%"REG_d", %%"REG_d" \n\t"
ASMALIGN(4)
"1: \n\t"
PREFETCH" 64(%0, %%"REG_d") \n\t"
#if defined (HAVE_MMX2) || defined (HAVE_3DNOW)
"movq (%0, %%"REG_d"), %%mm0 \n\t"
"movq 6(%0, %%"REG_d"), %%mm2 \n\t"
"movq %%mm0, %%mm1 \n\t"
"movq %%mm2, %%mm3 \n\t"
"psrlq $24, %%mm0 \n\t"
"psrlq $24, %%mm2 \n\t"
PAVGB(%%mm1, %%mm0)
PAVGB(%%mm3, %%mm2)
"punpcklbw %%mm7, %%mm0 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
#else
"movd (%0, %%"REG_d"), %%mm0 \n\t"
"movd 3(%0, %%"REG_d"), %%mm2 \n\t"
"punpcklbw %%mm7, %%mm0 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
"paddw %%mm2, %%mm0 \n\t"
"movd 6(%0, %%"REG_d"), %%mm4 \n\t"
"movd 9(%0, %%"REG_d"), %%mm2 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
"paddw %%mm4, %%mm2 \n\t"
"psrlw $1, %%mm0 \n\t"
"psrlw $1, %%mm2 \n\t"
#endif
"movq "MANGLE(bgr2VCoeff)", %%mm1 \n\t"
"movq "MANGLE(bgr2VCoeff)", %%mm3 \n\t"
"pmaddwd %%mm0, %%mm1 \n\t"
"pmaddwd %%mm2, %%mm3 \n\t"
"pmaddwd %%mm6, %%mm0 \n\t"
"pmaddwd %%mm6, %%mm2 \n\t"
#ifndef FAST_BGR2YV12
"psrad $8, %%mm0 \n\t"
"psrad $8, %%mm1 \n\t"
"psrad $8, %%mm2 \n\t"
"psrad $8, %%mm3 \n\t"
#endif
"packssdw %%mm2, %%mm0 \n\t"
"packssdw %%mm3, %%mm1 \n\t"
"pmaddwd %%mm5, %%mm0 \n\t"
"pmaddwd %%mm5, %%mm1 \n\t"
"packssdw %%mm1, %%mm0 \n\t"
"psraw $7, %%mm0 \n\t"
#if defined (HAVE_MMX2) || defined (HAVE_3DNOW)
"movq 12(%0, %%"REG_d"), %%mm4 \n\t"
"movq 18(%0, %%"REG_d"), %%mm2 \n\t"
"movq %%mm4, %%mm1 \n\t"
"movq %%mm2, %%mm3 \n\t"
"psrlq $24, %%mm4 \n\t"
"psrlq $24, %%mm2 \n\t"
PAVGB(%%mm1, %%mm4)
PAVGB(%%mm3, %%mm2)
"punpcklbw %%mm7, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
#else
"movd 12(%0, %%"REG_d"), %%mm4 \n\t"
"movd 15(%0, %%"REG_d"), %%mm2 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
"paddw %%mm2, %%mm4 \n\t"
"movd 18(%0, %%"REG_d"), %%mm5 \n\t"
"movd 21(%0, %%"REG_d"), %%mm2 \n\t"
"punpcklbw %%mm7, %%mm5 \n\t"
"punpcklbw %%mm7, %%mm2 \n\t"
"paddw %%mm5, %%mm2 \n\t"
"movq "MANGLE(w1111)", %%mm5 \n\t"
"psrlw $2, %%mm4 \n\t"
"psrlw $2, %%mm2 \n\t"
#endif
"movq "MANGLE(bgr2VCoeff)", %%mm1 \n\t"
"movq "MANGLE(bgr2VCoeff)", %%mm3 \n\t"
"pmaddwd %%mm4, %%mm1 \n\t"
"pmaddwd %%mm2, %%mm3 \n\t"
"pmaddwd %%mm6, %%mm4 \n\t"
"pmaddwd %%mm6, %%mm2 \n\t"
#ifndef FAST_BGR2YV12
"psrad $8, %%mm4 \n\t"
"psrad $8, %%mm1 \n\t"
"psrad $8, %%mm2 \n\t"
"psrad $8, %%mm3 \n\t"
#endif
"packssdw %%mm2, %%mm4 \n\t"
"packssdw %%mm3, %%mm1 \n\t"
"pmaddwd %%mm5, %%mm4 \n\t"
"pmaddwd %%mm5, %%mm1 \n\t"
"add $24, %%"REG_d" \n\t"
"packssdw %%mm1, %%mm4 \n\t"
"psraw $7, %%mm4 \n\t"
"movq %%mm0, %%mm1 \n\t"
"punpckldq %%mm4, %%mm0 \n\t"
"punpckhdq %%mm4, %%mm1 \n\t"
"packsswb %%mm1, %%mm0 \n\t"
"paddb "MANGLE(bgr2UVOffset)", %%mm0 \n\t"
"movd %%mm0, (%1, %%"REG_a") \n\t"
"punpckhdq %%mm0, %%mm0 \n\t"
"movd %%mm0, (%2, %%"REG_a") \n\t"
"add $4, %%"REG_a" \n\t"
" js 1b \n\t"
: : "r" (src1+width*6), "r" (dstU+width), "r" (dstV+width), "g" (-width)
: "%"REG_a, "%"REG_d
);
#else
int i;
for(i=0; i<width; i++)
{
int b= src1[6*i + 0] + src1[6*i + 3];
int g= src1[6*i + 1] + src1[6*i + 4];
int r= src1[6*i + 2] + src1[6*i + 5];
dstU[i]= ((RU*r + GU*g + BU*b)>>(RGB2YUV_SHIFT+1)) + 128;
dstV[i]= ((RV*r + GV*g + BV*b)>>(RGB2YUV_SHIFT+1)) + 128;
}
#endif
assert(src1 == src2);
}
| 1threat
|
static void n8x0_i2c_setup(struct n800_s *s)
{
DeviceState *dev;
qemu_irq tmp_irq = qdev_get_gpio_in(s->cpu->gpio, N8X0_TMP105_GPIO);
s->i2c = omap_i2c_bus(s->cpu->i2c[0]);
dev = i2c_create_slave(s->i2c, "twl92230", N8X0_MENELAUS_ADDR);
qdev_connect_gpio_out(dev, 3, s->cpu->irq[0][OMAP_INT_24XX_SYS_NIRQ]);
dev = i2c_create_slave(s->i2c, "tmp105", N8X0_TMP105_ADDR);
qdev_connect_gpio_out(dev, 0, tmp_irq);
}
| 1threat
|
static int ftp_auth(FTPContext *s, char *auth)
{
const char *user = NULL, *pass = NULL;
char *end = NULL, buf[CONTROL_BUFFER_SIZE];
int err;
av_assert2(auth);
user = av_strtok(auth, ":", &end);
pass = av_strtok(end, ":", &end);
if (user) {
snprintf(buf, sizeof(buf), "USER %s\r\n", user);
if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
return err;
ftp_status(s, &err, NULL, NULL, NULL, -1);
if (err == 3) {
if (pass) {
snprintf(buf, sizeof(buf), "PASS %s\r\n", pass);
if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
return err;
ftp_status(s, &err, NULL, NULL, NULL, -1);
} else
return AVERROR(EACCES);
}
if (err != 2) {
return AVERROR(EACCES);
}
} else {
const char* command = "USER anonymous\r\n";
if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
return err;
ftp_status(s, &err, NULL, NULL, NULL, -1);
if (err == 3) {
if (s->anonymous_password) {
snprintf(buf, sizeof(buf), "PASS %s\r\n", s->anonymous_password);
} else
snprintf(buf, sizeof(buf), "PASS nopassword\r\n");
if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
return err;
ftp_status(s, &err, NULL, NULL, NULL, -1);
}
if (err != 2) {
return AVERROR(EACCES);
}
}
return 0;
}
| 1threat
|
How to select most frequent value in a column per each id group? : <p>I have a table in SQL that looks like this:</p>
<pre><code>user_id | data1
0 | 6
0 | 6
0 | 6
0 | 1
0 | 1
0 | 2
1 | 5
1 | 5
1 | 3
1 | 3
1 | 3
1 | 7
</code></pre>
<p>I want to write a query that returns two columns: a column for the user id, and a column for what the most frequently occurring value per id is. In my example, for user_id 0, the most frequent value is 6, and for user_id 1, the most frequent value is 3. I would want it to look like below:</p>
<pre><code>user_id | most_frequent_value
0 | 6
1 | 3
</code></pre>
<p>I am using the query below to get the most frequent value, but it runs against the whole table and returns the most common value for the whole table instead of for each id. What would I need to add to my query to get it to return the most frequent value for each id? I am thinking I need to use a subquery, but am unsure of how to structure it.</p>
<pre><code>SELECT user_id, data1 AS most_frequent_value
FROM my_table
GROUP BY user_id, data1
ORDER BY COUNT(*) DESC LIMIT 1
</code></pre>
| 0debug
|
def dict_filter(dict,n):
result = {key:value for (key, value) in dict.items() if value >=n}
return result
| 0debug
|
static uint32_t syborg_virtio_readl(void *opaque, target_phys_addr_t offset)
{
SyborgVirtIOProxy *s = opaque;
VirtIODevice *vdev = s->vdev;
uint32_t ret;
DPRINTF("readl 0x%x\n", (int)offset);
if (offset >= SYBORG_VIRTIO_CONFIG) {
return virtio_config_readl(vdev, offset - SYBORG_VIRTIO_CONFIG);
}
switch(offset >> 2) {
case SYBORG_VIRTIO_ID:
ret = SYBORG_ID_VIRTIO;
break;
case SYBORG_VIRTIO_DEVTYPE:
ret = s->id;
break;
case SYBORG_VIRTIO_HOST_FEATURES:
ret = vdev->get_features(vdev);
ret |= vdev->binding->get_features(s);
break;
case SYBORG_VIRTIO_GUEST_FEATURES:
ret = vdev->guest_features;
break;
case SYBORG_VIRTIO_QUEUE_BASE:
ret = virtio_queue_get_addr(vdev, vdev->queue_sel);
break;
case SYBORG_VIRTIO_QUEUE_NUM:
ret = virtio_queue_get_num(vdev, vdev->queue_sel);
break;
case SYBORG_VIRTIO_QUEUE_SEL:
ret = vdev->queue_sel;
break;
case SYBORG_VIRTIO_STATUS:
ret = vdev->status;
break;
case SYBORG_VIRTIO_INT_ENABLE:
ret = s->int_enable;
break;
case SYBORG_VIRTIO_INT_STATUS:
ret = vdev->isr;
break;
default:
BADF("Bad read offset 0x%x\n", (int)offset);
return 0;
}
return ret;
}
| 1threat
|
getServlet() replacement : I am coding for my changes from `Struts1` to `Struts2`. In this we find many instances where the `getServlet` is being used like the following code snippet. now, getServlet() is being deprecated. I would like to know what to use instead. I tried looking at google a lot but no luck till now.
protected XXXServlet getYYYActionServlet() {
try {
return (XXXServlet)getServlet();
} catch(ClassCastException ex) {
return null;
}
}
Please provide your suggested course of action with example.
| 0debug
|
Angular Clickable list : <p>can anyone please help me out on how to go to next form when you click on a list item using angular js ? using an example like I have a list of addresses in one form , when i click on any address , it should redirect to next page showing the directions . thanks a lot in advance </p>
| 0debug
|
int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
AVPacket *avpkt,
const AVFrame *frame,
int *got_packet_ptr)
{
AVFrame *extended_frame = NULL;
AVFrame *padded_frame = NULL;
int ret;
AVPacket user_pkt = *avpkt;
int needs_realloc = !user_pkt.data;
*got_packet_ptr = 0;
if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY) && !frame) {
av_free_packet(avpkt);
av_init_packet(avpkt);
return 0;
}
if (frame && !frame->extended_data) {
if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
avctx->channels > AV_NUM_DATA_POINTERS) {
av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
"with more than %d channels, but extended_data is not set.\n",
AV_NUM_DATA_POINTERS);
return AVERROR(EINVAL);
}
av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
extended_frame = av_frame_alloc();
if (!extended_frame)
return AVERROR(ENOMEM);
memcpy(extended_frame, frame, sizeof(AVFrame));
extended_frame->extended_data = extended_frame->data;
frame = extended_frame;
}
if (frame) {
AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_AUDIO_SERVICE_TYPE);
if (sd && sd->size >= sizeof(enum AVAudioServiceType))
avctx->audio_service_type = *(enum AVAudioServiceType*)sd->data;
}
if (frame) {
if (avctx->codec->capabilities & AV_CODEC_CAP_SMALL_LAST_FRAME) {
if (frame->nb_samples > avctx->frame_size) {
av_log(avctx, AV_LOG_ERROR, "more samples than frame size (avcodec_encode_audio2)\n");
ret = AVERROR(EINVAL);
goto end;
}
} else if (!(avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE)) {
if (frame->nb_samples < avctx->frame_size &&
!avctx->internal->last_audio_frame) {
ret = pad_last_frame(avctx, &padded_frame, frame);
if (ret < 0)
goto end;
frame = padded_frame;
avctx->internal->last_audio_frame = 1;
}
if (frame->nb_samples != avctx->frame_size) {
av_log(avctx, AV_LOG_ERROR, "nb_samples (%d) != frame_size (%d) (avcodec_encode_audio2)\n", frame->nb_samples, avctx->frame_size);
ret = AVERROR(EINVAL);
goto end;
}
}
}
ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
if (!ret) {
if (*got_packet_ptr) {
if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY)) {
if (avpkt->pts == AV_NOPTS_VALUE)
avpkt->pts = frame->pts;
if (!avpkt->duration)
avpkt->duration = ff_samples_to_time_base(avctx,
frame->nb_samples);
}
avpkt->dts = avpkt->pts;
} else {
avpkt->size = 0;
}
}
if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
needs_realloc = 0;
if (user_pkt.data) {
if (user_pkt.size >= avpkt->size) {
memcpy(user_pkt.data, avpkt->data, avpkt->size);
} else {
av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
avpkt->size = user_pkt.size;
ret = -1;
}
avpkt->buf = user_pkt.buf;
avpkt->data = user_pkt.data;
#if FF_API_DESTRUCT_PACKET
FF_DISABLE_DEPRECATION_WARNINGS
avpkt->destruct = user_pkt.destruct;
FF_ENABLE_DEPRECATION_WARNINGS
#endif
} else {
if (av_dup_packet(avpkt) < 0) {
ret = AVERROR(ENOMEM);
}
}
}
if (!ret) {
if (needs_realloc && avpkt->data) {
ret = av_buffer_realloc(&avpkt->buf, avpkt->size + AV_INPUT_BUFFER_PADDING_SIZE);
if (ret >= 0)
avpkt->data = avpkt->buf->data;
}
avctx->frame_number++;
}
if (ret < 0 || !*got_packet_ptr) {
av_free_packet(avpkt);
av_init_packet(avpkt);
goto end;
}
avpkt->flags |= AV_PKT_FLAG_KEY;
end:
av_frame_free(&padded_frame);
av_free(extended_frame);
#if FF_API_AUDIOENC_DELAY
avctx->delay = avctx->initial_padding;
#endif
return ret;
}
| 1threat
|
static char *ctime1(char *buf2, int buf_size)
{
time_t ti;
char *p;
ti = time(NULL);
p = ctime(&ti);
av_strlcpy(buf2, p, buf_size);
p = buf2 + strlen(p) - 1;
if (*p == '\n')
*p = '\0';
return buf2;
}
| 1threat
|
Is there a python function to replace a specific index in a specific list that is in a text file? : <p>What I want to do:
I have a few lists in a text file now and want to change just 1 element of 1 of the lists using python.
What I have done so far:</p>
<p>Current txt file:</p>
<pre><code>food,bought
oranges,yes
strawberry,no
apples,no
</code></pre>
<p>I want it to appear like this after using the code to replace one of the "no" to "yes":</p>
<pre><code>food,bought
oranges,yes
strawberry,no
apples,yes
</code></pre>
<p>Is there any way to specifically change one index of the list?</p>
| 0debug
|
Using an iterating variable in powershell script to create file names : I'm trying to automate an adb test procedure using a batch file. After each run a file, `.CloudData.txt` is made. I want to preface that file name with a trial number, `T1.CloudData.txt`, etc. I made this test code:
echo off
set /p loops="Enter a number of iterations: "
for /l %%i in (1,1,%loops%) do (
set file=//scard//mytest//T%%i.CloudData.txt
echo %file%
)
So that eventually I can have something along the lines of:
echo off
set /p loops="Enter a number of iterations: "
for /l %%i in (1,1,%loops%) do (
rem Execute adb commands for test
set file=//scard//mytest//T%%i.CloudData.txt
adb shell mv /sdcard/mytest/.CloudData.txt file
)
But the test returns, assuming `loops` = 3, `/sdcard/mytest/T3.CloudData.txt` 3 times. To be painfully specific, the number stored in `loops` is being added where `%%i` should be. From what I've read in the following post: https://stackoverflow.com/questions/2634590/bash-script-variable-inside-variable, I think I should be using an array, but that's impractical if one day I have to run the test for more than iterations than the array permits. How should I proceed?
| 0debug
|
static void blkdebug_refresh_filename(BlockDriverState *bs)
{
QDict *opts;
const QDictEntry *e;
bool force_json = false;
for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
if (strcmp(qdict_entry_key(e), "config") &&
strcmp(qdict_entry_key(e), "x-image") &&
strcmp(qdict_entry_key(e), "image") &&
strncmp(qdict_entry_key(e), "image.", strlen("image.")))
{
force_json = true;
break;
}
}
if (force_json && !bs->file->bs->full_open_options) {
return;
}
if (!force_json && bs->file->bs->exact_filename[0]) {
snprintf(bs->exact_filename, sizeof(bs->exact_filename),
"blkdebug:%s:%s",
qdict_get_try_str(bs->options, "config") ?: "",
bs->file->bs->exact_filename);
}
opts = qdict_new();
qdict_put_obj(opts, "driver", QOBJECT(qstring_from_str("blkdebug")));
QINCREF(bs->file->bs->full_open_options);
qdict_put_obj(opts, "image", QOBJECT(bs->file->bs->full_open_options));
for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
if (strcmp(qdict_entry_key(e), "x-image") &&
strcmp(qdict_entry_key(e), "image") &&
strncmp(qdict_entry_key(e), "image.", strlen("image.")))
{
qobject_incref(qdict_entry_value(e));
qdict_put_obj(opts, qdict_entry_key(e), qdict_entry_value(e));
}
}
bs->full_open_options = opts;
}
| 1threat
|
static void gen_st_asi(DisasContext *dc, TCGv src, TCGv addr,
int insn, int size)
{
TCGv_i32 r_asi, r_size;
r_asi = gen_get_asi(dc, insn);
r_size = tcg_const_i32(size);
#ifdef TARGET_SPARC64
gen_helper_st_asi(cpu_env, addr, src, r_asi, r_size);
#else
{
TCGv_i64 t64 = tcg_temp_new_i64();
tcg_gen_extu_tl_i64(t64, src);
gen_helper_st_asi(cpu_env, addr, t64, r_asi, r_size);
tcg_temp_free_i64(t64);
}
#endif
tcg_temp_free_i32(r_size);
tcg_temp_free_i32(r_asi);
}
| 1threat
|
static CharDriverState *qemu_chr_open_spice_vmc(const char *id,
ChardevBackend *backend,
ChardevReturn *ret,
Error **errp)
{
const char *type = backend->u.spicevmc->type;
const char **psubtype = spice_server_char_device_recognized_subtypes();
for (; *psubtype != NULL; ++psubtype) {
if (strcmp(type, *psubtype) == 0) {
break;
}
}
if (*psubtype == NULL) {
fprintf(stderr, "spice-qemu-char: unsupported type: %s\n", type);
print_allowed_subtypes();
return NULL;
}
return chr_open(type, spice_vmc_set_fe_open);
}
| 1threat
|
Laravel's 5.3 passport and api routes : <p>I'm using Laravel Framework version 5.3.9, fresh download nothing added on via composer(except <code>"laravel/passport": "^1.0"</code>).</p>
<p>I did all the things suggested in the <a href="https://laravel.com/docs/master/passport">docs</a>. Tables are created, routes are up, everything works fine. However I need passport for an API.</p>
<p>My routes look like so:</p>
<pre><code>+--------+----------+-----------------------------------------+----------------------+----------------------------------------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+-----------------------------------------+----------------------+----------------------------------------------------------------------------+------------+
| | GET|HEAD | / | | Closure | web |
| | GET|HEAD | api/v1/users/register | api::users::register | App\Http\Controllers\Api\V1\SocialController@register | api,auth |
| | POST | oauth/authorize | | \Laravel\Passport\Http\Controllers\ApproveAuthorizationController@approve | web,auth |
| | GET|HEAD | oauth/authorize | | \Laravel\Passport\Http\Controllers\AuthorizationController@authorize | web,auth |
| | DELETE | oauth/authorize | | \Laravel\Passport\Http\Controllers\DenyAuthorizationController@deny | web,auth |
| | GET|HEAD | oauth/clients | | \Laravel\Passport\Http\Controllers\ClientController@forUser | web,auth |
| | POST | oauth/clients | | \Laravel\Passport\Http\Controllers\ClientController@store | web,auth |
| | PUT | oauth/clients/{client_id} | | \Laravel\Passport\Http\Controllers\ClientController@update | web,auth |
| | DELETE | oauth/clients/{client_id} | | \Laravel\Passport\Http\Controllers\ClientController@destroy | web,auth |
| | GET|HEAD | oauth/personal-access-tokens | | \Laravel\Passport\Http\Controllers\PersonalAccessTokenController@forUser | web,auth |
| | POST | oauth/personal-access-tokens | | \Laravel\Passport\Http\Controllers\PersonalAccessTokenController@store | web,auth |
| | DELETE | oauth/personal-access-tokens/{token_id} | | \Laravel\Passport\Http\Controllers\PersonalAccessTokenController@destroy | web,auth |
| | GET|HEAD | oauth/scopes | | \Laravel\Passport\Http\Controllers\ScopeController@all | web,auth |
| | POST | oauth/token | | \Laravel\Passport\Http\Controllers\AccessTokenController@issueToken | |
| | POST | oauth/token/refresh | | \Laravel\Passport\Http\Controllers\TransientTokenController@refresh | web,auth |
| | GET|HEAD | oauth/tokens | | \Laravel\Passport\Http\Controllers\AuthorizedAccessTokenController@forUser | web,auth |
| | DELETE | oauth/tokens/{token_id} | | \Laravel\Passport\Http\Controllers\AuthorizedAccessTokenController@destroy | web,auth |
+--------+----------+-----------------------------------------+----------------------+----------------------------------------------------------------------------+------------+
</code></pre>
<p>All the <code>web</code> routes are there, there are no <code>api</code> related routes, since Passport doesn't provide anything of that sort out of the box.</p>
<p>The API itself is intended to be used by a trusted client, it's made for a mobile application that does require a login however, said login will bypass a few steps. </p>
<p>Once a user access the <code>/register</code> route, the registration process itself is quite simple: access the user's facebook account an grab a few fields - email, facebook id, name an profile picture and from that point onwards the users is considered registered. But the user will <strong>NOT</strong> login with facebook(this is a very important aspect). The consumer app will be issued a token and use that token to access various endpoints of the api(that require a token to use). </p>
<p>So it boils down to this. I need to issue an access token to the consumer app that access the API. The API itself will only have one client, that is the mobile app itself. Users that use the app are not considered clients of the API but clients of the mobile app itself.</p>
<p>So far Passport is a headache to work with when it comes to implementing API related stuff, either that or I can't figure out how to make it work properly.</p>
<p>I've created a test client in the <code>oauth_clients</code> table that looks like so:</p>
<p><a href="https://i.stack.imgur.com/4hYJh.png"><img src="https://i.stack.imgur.com/4hYJh.png" alt="enter image description here"></a></p>
<p>I'm using Postman to access <code>api/v1/users/register</code> route that has the <code>auth</code> middleware with the following <code>JSON application/json</code></p>
<pre><code>{
"grant_type" : "authorization_code",
"client_id" : 5,
"client_secet": "y5dvPIOxQJOjYn7w2zzg4c6TRrphsrNFWbG4gAUL"
}
</code></pre>
<p>Which of course will result in a </p>
<pre><code>{"error":"Unauthenticated."}
</code></pre>
<p>It makes perfect sense.
Out of pure curiosity I changed the <code>/register</code> route to this:</p>
<pre><code>Route::group([
'middleware' => [
],
], function ()
{
Route::group([
'prefix' => 'users',
'as' => 'users::',
], function ()
{
// Route::get('/register', ['as' => 'register', 'uses' => 'Api\V1\SocialController@register',]);
Route::post('/register', ['as' => 'register', 'uses' => '\Laravel\Passport\Http\Controllers\AccessTokenController@issueToken',]);
});
});
</code></pre>
<p>With the same <code>json</code> as before. That resulted in <code>{"error":"invalid_client","message":"Client authentication failed"}</code>. </p>
<p>I've tracked down the function that, I think, handles the <code>validateClient</code> part in <a href="https://github.com/thephpleague/oauth2-server/blob/master/src/Grant/AbstractGrant.php#L143"><code>vendor/league</code>oauth2-server/src/Grant/AbstractGrant`</a>.</p>
<p>The <code>$client</code> is null. Now this may or may not be related to Passport, since the documentation on it rather lacking and the thought of digging thru a monster of a package to track down the error that may be largely due to me not doing something right doesn't strike me as a good idea, I'm out of options. To be perfectly honest I don't even know what the problem is.</p>
<p>Really, at this point any sort pointing in the right direction is more than welcome.</p>
<p>The part in questions is </p>
| 0debug
|
Angular 6 Services: providedIn: 'root' vs CoreModule : <p>With Angular 6, below is the preferred way to create singleton services:</p>
<pre><code>import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class UserService {
}
</code></pre>
<p>From Angular doc:
When you provide the service at the root level, Angular creates a single, shared instance of HeroService and injects into any class that asks for it. Registering the provider in the @Injectable metadata also allows Angular to optimize an app by removing the service if it turns out not to be used after all.</p>
<p>Also,</p>
<pre><code>providers: [
// no need to place any providers due to the `providedIn` flag...
]
</code></pre>
<p>So, does that mean we no more need <a href="https://angular.io/guide/styleguide#core-feature-module" rel="noreferrer">CoreModule</a>? We can import services and other common modules directly into AppModule.</p>
| 0debug
|
How to shuffle imageIcons in an array? : <p>I am trying to code a memory matching game - the standard type of concentration game where the player is shown picture cards, they're flipped over, and they have to match the corresponding cards.</p>
<p>There's a few things that have me completely at a loss as to where I should even begin, and I would really appreciate it if I could get some advice. I'm not sure how I would shuffle the images in an array of Buttons each time I restarted the game. I considered making an integer matrix and shuffling the numbers and images separately, but 1) I'm not sure how to shuffle ImageIcons on a button, and 2) the 2 numbers that are supposed to match up would have different images.</p>
<p>I also considered making a String array to shuffle the filenames of the ImageIcons, but I think that would require reassigning each individual image icon (there are 48 cards and 24 pairs so that would take up a lot of time). Could I get some ideas on how to approach this problem? Is there an easier/more efficient solution than the ones I've thought up? I know there's a Fisher-Yates shuffle algorithm used for cards but I can't quite understand it. </p>
| 0debug
|
Why using Bash readonly variable to capture output fails to capture return code $? : <p>Here's example that tries to execute command and checks if it was executed successfully, while capturing it's output for further processing:</p>
<pre><code>#!/bin/bash
readonly OUTPUT=$(foo)
readonly RES=$?
if [[ ${RES} != 0 ]]
then
echo "failed to execute foo"
exit 1
else
echo "foo success: '${OUTPUT}'"
fi
</code></pre>
<p>It reports that it was a success, even there is no such <code>foo</code> executable. But, if I remove <code>readonly</code> from <code>OUTPUT</code> variable, it preserves erroneous exit code and failure is detected.</p>
<p>I try to use readonly as for "defensive programming" technique as recommended somewhere... but looks like it bites itself in this case.</p>
<p>Is there some clean solution to preserve <code>readonly</code> while still capturing exit code of command/subshell? It would be disappointing that one has to remember this kind of exceptional use case, or revert to not using <code>readonly</code> ever...</p>
<p>Using Bash 4.2.37(1) on Debian Wheezy.</p>
| 0debug
|
Angular2 rxjs - switchmap catch error : <p>I'd like to be able to handle any errors that error when calling <code>this.authService.refreshToken()</code>. Can errors be handled within the switchmap block, or how do I go about handling an error in this case?</p>
<pre><code>post3(endpoint: string, body: string) : Observable<any> {
if (this.authService.tokenRequiresRefresh()) {
this.authService.tokenIsBeingRefreshed.next(true);
return this.authService.refreshToken().switchMap(
data => {
this.authService.refreshTokenSuccessHandler(data);
if (this.authService.loggedIn()) {
this.authService.tokenIsBeingRefreshed.next(false);
return this.postInternal(endpoint, body);
} else {
this.authService.tokenIsBeingRefreshed.next(false);
this.router.navigate(['/sessiontimeout']);
Observable.throw(data);
}
}
);
}
else {
return this.postInternal(endpoint, body);
}
}
</code></pre>
| 0debug
|
How search whitespaces on < and > on link without tag html <a href=""> </a> : <p>simple find whitespaces <code>\s+</code> with regex:
exemplo match: <code>&lt;https://reg exr.com/&gt;</code></p>
| 0debug
|
Strore getcwd on a struct on a function :
typedef struct
{
char Path[100];
}DirectoryInformation;
void Getskelutofdirectorie(char *dir, int lvl)
{
DirectoryInformation DI[100];
char cwd[1024];
//Search recursive
//where i want to put the path on the struct to use on main
getcwd(cwd,sizeof(cwd));
strcpy(DI[0].Path, cwd);
}
int main(void)
{
DirecoryInformation DI[100];
printf("%s", DI[0].Path);
}
I can print the path but if i use on main function will work.
can somebody help me out?
Is execute with out error but when i print out make segmentation fault
| 0debug
|
Ruby <=> (spaceship) operator , Revoke method : I'm trying to revoke certificate from apple development portal using
Ruby <=> (spaceship) operator
most of the methods are working fine expect the revoke
example :
[52] pry(main)> Spaceship::Portal::Certificate::DevelopmentPush.all
will list to me all developmentpush certficate ,
there is revoke method but i couldn't figure out the right syntax for it
tested couple of syntax such :
[52] pry(main)> Spaceship::Portal::Certificate::revoke_certificate!('id', 'type')
NameError: wrong constant name RevokeCertificate!
from /var/lib/gems/2.1.0/gems/spaceship-0.22.0/lib/spaceship/base.rb:153:in `const_defined?'
anyone knows the right syntax as this spaceship has no good docs or reference at all ,
thanks in advance
| 0debug
|
VueJS 2 + ASP.NET MVC 5 : <p>I'm very new with VueJS.
I have to build a single page application inside a ASP.NET MVC5.</p>
<p>I follow this tutorial and works very well -> <a href="http://www.mithunvp.com/working-vuejs-asp-net-mvc-5-visual-studio/" rel="noreferrer">TUTORIAL</a></p>
<p>But when i create a .vue page to test VueJS2 Routes, the browser does not understand "Import", i read that i have to use a transpiler like Babel, someone know how i solve it?</p>
<p>App.VUE</p>
<pre><code> <template>
<div id="app">
{{msg}}
</div>
</template>
<script>
export default {
name: 'app',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
</code></pre>
<p>App.JS</p>
<pre><code> import Vue from 'vue'
import App from './App.vue'
new Vue({
el: '#app',
router,
render: h => h(App),
data: {
message: 'Hello Vue! in About Page'
}
});
</code></pre>
<p>_Layout.cshtml</p>
<pre><code><div class="container-fluid">
@RenderBody()
<div id="app">
{ { message } }
</div>
</div>
<script src="~/Scripts/essential/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/essential/bootstrap.min.js"></script>
<script src="~/Scripts/essential/inspinia.js"></script>
<script src="~/Scripts/essential/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/2.0.1/vue-router.js"></script>
<script src="~/Scripts/app.js"></script>
<script src="~/Scripts/plugin/metisMenu/jquery.metisMenu.js"></script>
<script src="~/Scripts/plugin/pace/pace.min.js"></script>
<script src="~/Scripts/plugin/slimscroll/jquery.slimscroll.min.js"></script>
</code></pre>
<p>Thanks a lot!!</p>
| 0debug
|
void OPPROTO op_check_subfo_64 (void)
{
if (likely(!(((uint64_t)(~T2) ^ (uint64_t)T1 ^ UINT64_MAX) &
((uint64_t)(~T2) ^ (uint64_t)T0) & (1ULL << 63)))) {
xer_ov = 0;
} else {
xer_ov = 1;
xer_so = 1;
}
RETURN();
}
| 1threat
|
Boolean , what is the correct answer and why? : <p>Boolean or "truth-valued" expressions are how we express conditions that control choices and repetition in computer languages. Consider the following Python Boolean expression, where variables beta and gamma are of type Boolean:</p>
<p>not (beta and gamma)</p>
<p>In any algebraic notation there are usually several different ways of writing the same expression. For instance, in integer arithmetic the value of expression '4 x (5 + 2)' is numerically equivalent to that of expression '(4 x 5) + (4 x 2)'. </p>
<p>Which of the following Boolean expressions is logically equivalent to the one above?</p>
<p>Answers:<br>
beta or gamma</p>
<p><strong>(not beta) and (not gamma)</strong> </p>
<p>not (not beta) or gamma</p>
<p>(not beta) or (not gamma)</p>
<p>beta and (not gamma)</p>
<p><strong>(not beta) and (not gamma)</strong> Is the answer i chose however its incorrect, can someone explain to me the right answer for this is ? </p>
| 0debug
|
What change in Powershell 5 changes meaning of block curly brackets : <p>We recently updated the Powershell version on our build servers from 4.0 to 5.0. This change caused one of our build scripts to start failing in an unexpected way. </p>
<p>The code is used to determine which user guides should be included in our product. The code processes a list of xml nodes that describe all available documents with version and culture. We group by document title and culture and then select the most fitting version.</p>
<pre><code>$documents = Get-ListItemsFromSharePoint
$documents = $documents |
Where-Object { $productVersion.CompareTo([version]$_.ows_Product_x0020_Version) -ge 0 } |
Where-Object { -not ($_.ows_EncodedAbsUrl.Contains('/Legacy/')) }
Write-Verbose -Message "Filtered to: $($documents.length) rows"
# Filter to the highest version for each unique title per language
$documents = $documents | Group-Object { $_.ows_Title, $_.ows_Localisation } |
ForEach-Object {
$_.Group | Sort-Object { [version]$_.ows_Product_x0020_Version } -Descending | Select-Object -First 1
}
</code></pre>
<p>In Powershell 4 this code correctly sorts the documents by title and culture and then selects the most suitable version. In Powershell 5 this code groups all documents in a single list and then selected the most suitable version from that list. Given that we have documents in multiple languages this means that only the language with the most suitable version will be present.</p>
<p>The issue was fixed by changing </p>
<pre><code>$documents = $documents | Group-Object { $_.ows_Title, $_.ows_Localisation } |
</code></pre>
<p>to</p>
<pre><code>$documents = $documents | Group-Object ows_Title, ows_Localisation |
</code></pre>
<p>Now I understand that the first syntax is not technically correct according to the documentation because Group-Object expects an array of property names to group on, however in Powershell 4 the code did return the desired results.</p>
<p>The question now is what changed in Powershell 5 that the original code worked in Powershell 4 but failed in Powershell 5.</p>
| 0debug
|
Is there an in memory messaging broker for functional testing of RabbitMq? : <p>I need to write functional tests flows that involve interaction with RabbitMq. But once the tests are run I will have to clear any existing message in the queue. Since RabbitMq is persistent I need some in memory substitute for RabbitMq. Just like the way we have HSQL for databases.</p>
<p>I have tried using <code>qpid</code> broker but with no luck.</p>
<p>I am using spring boot framework. So I just need to inject the bean of the inmemory queue instead of actual rabbit mq.</p>
| 0debug
|
int rom_load_fw(void *fw_cfg)
{
Rom *rom;
QTAILQ_FOREACH(rom, &roms, next) {
if (!rom->fw_file) {
continue;
}
fw_cfg_add_file(fw_cfg, rom->fw_dir, rom->fw_file, rom->data, rom->romsize);
}
return 0;
}
| 1threat
|
static int net_vde_init(VLANState *vlan, const char *model,
const char *name, const char *sock,
int port, const char *group, int mode)
{
VDEState *s;
char *init_group = strlen(group) ? (char *)group : NULL;
char *init_sock = strlen(sock) ? (char *)sock : NULL;
struct vde_open_args args = {
.port = port,
.group = init_group,
.mode = mode,
};
s = qemu_mallocz(sizeof(VDEState));
s->vde = vde_open(init_sock, (char *)"QEMU", &args);
if (!s->vde){
free(s);
return -1;
}
s->vc = qemu_new_vlan_client(vlan, model, name, NULL, vde_from_qemu,
NULL, vde_cleanup, s);
qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
sock, vde_datafd(s->vde));
return 0;
}
| 1threat
|
node js read files liny by line : I am quite new with Node.js. There is a folder on my computer where I have several textfiles(.fw4 format). I could found all the text files with the node-dir module. Furthermore I need to get some content of each file from specified columns. Actually this algorithm works fine, using the readline module.
I keep my files name in an array.
Something like this: [ '000037592.fw4', '000037593.fw4', '000037594.fw4' ] (Like this.)
What do I need actually?I would like that this whole system would work synchronously and when I get the first file content (000037592.fw4) it would log something like end of file..And it continue reading the other files from the array.
So far..It has not worked how I wanted..
Thank you so much in advance. I would appreciate any suggestion, how to get a solution for my problem.
| 0debug
|
Make Chrome Headless to Wait for Ajax Before Printing to PDF : <p>I'm trying to use chrome headless to print my webpage to a PDF file.
The PDf file is with no data, because the headless chrome is printing it before the ajax commands finish.</p>
<p>Any idea on how I can get it to wait?</p>
<p>Here's the command I currently use:</p>
<pre><code>chrome --headless http://localhost:8080/banana/key --run-all-compositor-stages-before-draw --print-to-pdf=C:\\tmp\\tmp.pdf
</code></pre>
| 0debug
|
What's the replacement for webpack-dev-server in Webpack 4? : <p>I've noticed that installing <code>webpack-dev-server@webpack/webpack#next</code> actually installs webpack (without any warning). However, there's no <code>webpack-dev-server</code> executable any more.</p>
<p>Is there a replacement for this in Webpack 4, or do I need a separate web server?</p>
<p>It was really convenient to quickly spin up a web server with hot reloading. What's the recommended way to do that in Webpack 4?</p>
<p>(Why I'm bothering with Webpack 4 at all? Because it supports native .mjs modules)</p>
| 0debug
|
Any good frameworks for mobile? : <p>Nice hybrid framework for both android/ios? I tried <code>ionic framework</code> and it's super easy to use but it slow compared to native framework.</p>
| 0debug
|
Visual Studio 2017 errors on standard headers : <p>I just upgraded to Visual Studio 2017 Community Edition and I have trouble loading standard header files. I get 507 errors from various header files. Here are some snippets:</p>
<p>Some of the errors:</p>
<pre><code>Severity Code Description Project File Line Suppression State
Error (active) E1696 cannot open source file "errno.h" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cerrno 7
Error (active) E1696 cannot open source file "float.h" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cfloat 7
Error (active) E0282 the global scope has no "acosf" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cmath 629
Error (active) E0282 the global scope has no "asinf" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cmath 629
Error (active) E0282 the global scope has no "atanf" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cmath 630
Error (active) E0282 the global scope has no "atan2f" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cmath 630
Error (active) E0282 the global scope has no "ceilf" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cmath 630
Error (active) E0282 the global scope has no "cosf" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cmath 631
Error (active) E0282 the global scope has no "coshf" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cmath 631
Error (active) E0282 the global scope has no "swprintf" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 21
Error (active) E0282 the global scope has no "swscanf" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 21
Error (active) E0282 the global scope has no "ungetwc" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 21
Error (active) E0282 the global scope has no "vfwprintf" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 22
Error (active) E0282 the global scope has no "vswprintf" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 22
Error (active) E0282 the global scope has no "vwprintf" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 22
Error (active) E0282 the global scope has no "wcrtomb" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 23
Error (active) E0282 the global scope has no "wprintf" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 23
Error (active) E0282 the global scope has no "wscanf" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 23
Error (active) E0282 the global scope has no "wcsrtombs" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 24
Error (active) E0282 the global scope has no "wcstol" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 24
Error (active) E0282 the global scope has no "wcscat" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 24
Error (active) E0282 the global scope has no "wcschr" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 25
Error (active) E0282 the global scope has no "wcscmp" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 25
Error (active) E0282 the global scope has no "wcscoll" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 25
Error (active) E0282 the global scope has no "wcscpy" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 26
Error (active) E0282 the global scope has no "wcscspn" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 26
Error (active) E0282 the global scope has no "wcslen" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 26
Error (active) E0282 the global scope has no "wcsncat" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 27
Error (active) E0282 the global scope has no "wcsncmp" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 27
Error (active) E0282 the global scope has no "wcsncpy" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 27
Error (active) E0282 the global scope has no "wcspbrk" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\cwchar 28
Error (active) E0282 the global scope has no "wcsrchr" RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools
Error (active) E0260 explicit type is missing ('int' assumed) RPGWorld c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\xtgmath.h 212
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\Graphics\Glsl.inl 40
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\Graphics\Texture.hpp 159
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\Graphics\VertexArray.hpp 64
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\Graphics\VertexArray.hpp 72
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\Graphics\VertexArray.hpp 88
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\Graphics\VertexArray.hpp 104
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\Graphics\VertexArray.hpp 129
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\System\String.hpp 58
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\System\String.hpp 332
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\System\String.hpp 345
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\System\String.hpp 365
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\System\String.hpp 387
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\System\String.hpp 387
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\System\String.hpp 399
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\System\String.hpp 413
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\System\String.hpp 413
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\System\String.hpp 427
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\System\String.hpp 427
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\System\String.hpp 456
Error (active) E0757 variable "size_t" is not a type name RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\packages\sfml-system.2.4.0.0\build\native\include\SFML\System\String.hpp 456
Error (active) E0020 identifier "rand" is undefined RPGWorld c:\Users\Fazil\Documents\Visual Studio 2017\Projects\Local\RPGWorld\RPGWorld\Blocks.cpp 23
Error C1083 Cannot open include file: 'corecrt.h': No such file or directory RPGWorld c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\crtdefs.h 10
Error C1083 Cannot open include file: 'corecrt.h': No such file or directory RPGWorld c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\crtdefs.h 10
Error C1083 Cannot open include file: 'corecrt.h': No such file or directory RPGWorld c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\crtdefs.h 10
Error C1083 Cannot open include file: 'corecrt.h': No such file or directory RPGWorld c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\crtdefs.h 10
Error C1083 Cannot open include file: 'corecrt.h': No such file or directory RPGWorld c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\crtdefs.h 10
Error C1083 Cannot open include file: 'corecrt.h': No such file or directory RPGWorld c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\crtdefs.h 10
Error C1083 Cannot open include file: 'corecrt.h': No such file or directory RPGWorld c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\crtdefs.h 10
Error C1083 Cannot open include file: 'corecrt.h': No such file or directory RPGWorld c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\crtdefs.h 10
</code></pre>
<p>I never had this issue with Visual Studio 2015 Community Edition. Am I missing some component from the Installer? Any help would be appreciated. Thank you!</p>
| 0debug
|
How can I give some clickable points in VR panorama image view in Android? : <p>I insert a 360 degree image in <strong>VrPanoramaView</strong> then image is showing and rotating successfully but and in this library only one click event which is <strong>panoramaView.setEventListener(new VrPanoramaEventListener()</strong> . I want to give some points in that image. So I want to know how I can give some selected points in Google VR View in android ? </p>
| 0debug
|
subscript out of bounds in r for loops :
In my script, it is possible to get d [[x]] "empty". I tried to do it with esle, but it does not go out.
how to write esle so that it can give a result of checking zero?
for (x in 1:licznik3)
{
if(a[[x]] > d[[x]])
{
out3[[x]] <- wspolne3[[x]]
}
else (a[[x]] < d[[x]])
{
out3[[x]] <- NA
}
}
variables:
> a
[1] 0.1
> d
numeric(0)
Error in d[[x]] : subscript out of bounds
| 0debug
|
Android WebView push notification? : <p>I need to send a notification (not necessarily a <em>push</em> notification) through an android webview. I saw that the <code>Notification API</code> was not compatible with Android Webview on <a href="https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API" rel="noreferrer">MDN</a>. The other APIs I saw seemed to be based off of <code>window.notification</code>.</p>
<p>Does anyone know of any API or JS that sends a notification through an android webview?</p>
<p>I saw <a href="https://stackoverflow.com/questions/51446220/push-notification-in-a-webview">this</a> post from 6 months ago with essentially no activity except a vague mention of firebase. Would that be helpful?</p>
<p>Thanks for your answers!</p>
| 0debug
|
bool bdrv_all_can_snapshot(BlockDriverState **first_bad_bs)
{
bool ok = true;
BlockDriverState *bs;
BdrvNextIterator it;
for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
AioContext *ctx = bdrv_get_aio_context(bs);
aio_context_acquire(ctx);
if (bdrv_is_inserted(bs) && !bdrv_is_read_only(bs)) {
ok = bdrv_can_snapshot(bs);
}
aio_context_release(ctx);
if (!ok) {
goto fail;
}
}
fail:
*first_bad_bs = bs;
return ok;
}
| 1threat
|
The subscription is not registered to use namespace 'Microsoft.DataFactory error : <p>Going through <a href="https://azure.microsoft.com/en-us/documentation/articles/data-factory-get-started-using-vs/" rel="noreferrer">this tutorial</a> "Create a pipeline with Copy Activity using Visual Studio"
and recieving this error when i hit publish.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Creating datafactory-Name:VSTutorialFactory,Tags:,Subscription:Pay-As-You-Go,ResourceGroup:MyAppGroup,Location:North Europe,
24/03/2016 11:30:34- Error creating data factory:
Microsoft.WindowsAzure.CloudException: MissingSubscriptionRegistration:
The subscription is not registered to use namespace 'Microsoft.DataFactory'.</code></pre>
</div>
</div>
</p>
<p>Error not mentioned anywhere on net and very little help/knowledge on azure generally on web.</p>
| 0debug
|
How to find wrong prediction cases in test set (CNNs using Keras) : <p>I'm using MNIST example with 60000 training image and 10000 testing image. How do I find which of the 10000 testing image that has an incorrect classification/prediction?</p>
| 0debug
|
Can i install later ssis,ssrs and ssas services in sql server 2016? : please tell me how to install SQL Server 2016 and can i install MSBI Tools (SSAS,SSRS,SSIS) Later.
| 0debug
|
Output abnormal .. WHY? : <p>I have many days that I can not run this script!</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>var b = [9,8,7,6,5,4,3,2,1];
var a = (function(){
var W = [];
for(var k in b){
W[W.length] = {
index : k,
fx : function(){
console.log(k);
}
}
}
return W;
})();
console.log(a);
for(var j = 0; a[j]; j++)a[j].fx();</code></pre>
</div>
</div>
</p>
<p>Because it does not produce as OUTPUT numerical sequence <strong>987654321</strong>?</p>
| 0debug
|
How to scrap all the hotel reviews from HolidayIQ using Rvest : I wand to scrape all the user reviews from this [hotel main page][1], using Rvest package in R. I am only able to retrieve first 10 reviews. Next set of reviews are loaded by clicking 'View more' button, which are generated by JavaScript. Please tell me how to collect all the reviews...
[1]: http://www.holidayiq.com/Taj-Exotica-Benaulim-hotel-2025.html
| 0debug
|
How to translate "bytes" objects into literal strings in pandas Dataframe, Python3.x? : <p>I have a Python3.x pandas DataFrame whereby certain columns are strings which as expressed as bytes (like in Python2.x)</p>
<pre><code>import pandas as pd
df = pd.DataFrame(...)
df
COLUMN1 ....
0 b'abcde' ....
1 b'dog' ....
2 b'cat1' ....
3 b'bird1' ....
4 b'elephant1' ....
</code></pre>
<p>When I access by column with <code>df.COLUMN1</code>, I see <code>Name: COLUMN1, dtype: object</code></p>
<p>However, if I access by element, it is a "bytes" object</p>
<pre><code>df.COLUMN1.ix[0].dtype
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'dtype'
</code></pre>
<p>How do I convert these into "regular" strings? That is, how can I get rid of this <code>b''</code> prefix? </p>
| 0debug
|
Find product of array elements : <p>Today, in the job interview i was asked a question:
we have an array</p>
<pre><code>[3,1,2,4]
</code></pre>
<p>write the function thatfind composition of elements not including one element during itearion and return new array,it's mean that</p>
<pre><code>for 3 composition will be : 1*2*4 = 8
for 1 : 3*2*4=24
for 2 : 3*1*4 = 12
for 4: 3*1*2 = 6
</code></pre>
<p>So answer will be <code>8,24,12,6</code>
It's pretty easy but i have 2 constraint</p>
<p>1) You can't use operator "/"</p>
<p>2) Your algorithm must be <code>O(n)</code></p>
<p>That i didn't write an answer. How this task should be done?</p>
| 0debug
|
How do I call a class from another class? : I am creating a program for my computer science program. I am trying to call a class called "StockBarChart". How would I call this class from my main class?
| 0debug
|
Problems importing global modules : Is there any problem I'm importing all my components and services directly into the app.module? Performance problems or something?
If there is a problem, what are the suggestions to try to solve?
| 0debug
|
Code to find the number of characters in the string. Unable to get a desired output. Unclear about what i am missing. Kindly suggest : Below code outputs only "Enter a string" and accepts user input however, does not display the number of characters in the string. Kindly help!
System.out.println("Enter a string");
Scanner scan = new Scanner (System.in);
String a = scan.nextLine();
try{
while(a != null){
count++;
}
}
catch(Exception e)
{
System.out.println("Invalid string");
}
System.out.println("The number of characters are : " + count);
| 0debug
|
Java - Random Class with seed :
long seed = 0;
Random rand = new Random(seed);
int rand100 = 0;
for(int i = 0; i < 100; i++)
rand100 = rand.nextInt();
System.out.println(rand100);
I wrote this code to get 100. random integer value of given seed. I want to know if there is a way to get 100. random integer value of given seed without using every single random integer in front of it.
| 0debug
|
Cannot set property of undefined angularjs : <p>I have a json object s.BdayDetails and i want to change the values of my s.BdayDetails.ProvID into another value.</p>
<p><pre><code></p>
<pre><code> for(var i=0;i<s.BdayDetails.length;i++){
</code></pre>
<p>h.post("../Event/getProvinceName?ProvID=" + s.BdayDetails[i].ProvID).then(function (r) {</p>
s.BdayDetails[i].ProvID = r.data.toString();
})
</code></pre>
<p>Returns an error Cannot set property 'ProvID' of undefined. But when I console.log(r.data.toString()) it shows the values.</p>
| 0debug
|
static void tcg_out_dat_rIN(TCGContext *s, int cond, int opc, int opneg,
TCGArg dst, TCGArg lhs, TCGArg rhs,
bool rhs_is_const)
{
if (rhs_is_const) {
int rot = encode_imm(rhs);
if (rot < 0) {
rhs = -rhs;
rot = encode_imm(rhs);
assert(rot >= 0);
opc = opneg;
}
tcg_out_dat_imm(s, cond, opc, dst, lhs, rotl(rhs, rot) | (rot << 7));
} else {
tcg_out_dat_reg(s, cond, opc, dst, lhs, rhs, SHIFT_IMM_LSL(0));
}
}
| 1threat
|
What is the mean of "bodyParser.urlencoded({ extended: true }))" and "bodyParser.json()" in NodeJS? : <pre><code>const bp = require("body-parser");
const express = require("express");
const app = express();
app.use(bp.json());
app.use(bp.urlencoded({ extended: true }));
</code></pre>
<p>I need to know what they do. I couldn't find any detailed information. Can you help me? And what is different between <code>extended:true</code> and <code>extended:false</code></p>
| 0debug
|
Difference between TextInputLayout and TextInputEditText : <p>Need to know what actually difference between TextInputEditText and TextInputLayout, When should we use one of them.</p>
| 0debug
|
Why does git worktree add create a branch, and can I delete it? : <p>I used <code>git worktree add</code> to create a new worktree. I noticed that is has created a new branch in the repo with the same name as the worktree. What is this branch for?</p>
<p>I have checked out an other, pre-existing branch in the second worktree. Am I free to delete the branch that <code>git worktree add</code> created?</p>
| 0debug
|
Angular2 : two way binding inside parent/child component : <p>Version: "angular2": "2.0.0-beta.6"</p>
<p>I would like to implement a two way binding inside a parent/child component case.</p>
<p>On my child component, I'm using two-way binding to display text while editing.</p>
<p>Child component (<code>InputTestComponent [selector:'input-test']</code>):</p>
<pre><code><form (ngSubmit)="onSubmit()" #testform="ngForm">
{{name}}
<textarea #textarea [(ngModel)]="name" ngControl="name" name="name"></textarea>
<button type="submit">Go</button>
</form>
</code></pre>
<p>Then, I would like to propagate this change to his parent component.
I tried with <code>[(name)]="name"</code> with no success.</p>
<p>Parent component:</p>
<pre><code><div>
{{name}}
<input-test [(name)]="name"></input-test>
</div>
</code></pre>
<p><a href="http://plnkr.co/edit/GO8BCcJleyNRURB29OOC">Code sample</a></p>
<p>What the easiest way to do it (less verbose) ?</p>
| 0debug
|
insert an URL in mysql database using php script and methode GET, the probleme is I always get the url missing the last part (after '&token=' ) : <?php
$urlFace=$_GET['urlFace'];
echo $urlFace;
?>
----------
this is the url
https://firebasestorage.googleapis.com/v0/b/carsstore-1c8c5.appspot.com/o/photos%2Fimage%3A60Sat+Dec+24+10%3A39%3A10+EST+2016?alt=media&token=908e383e-1901-4c04-855d-d6c7280b40a1
----------
and this is what I get
https://firebasestorage.googleapis.com/v0/b/carsstore-1c8c5.appspot.com/o/photos/image:60Sat Dec 24 10:39:10 EST 2016?alt=media
| 0debug
|
Attempt to invoke virtual method 'android.view.View android.support.v4.widget.NestedScrollView.findViewById(int)' on a null object reference : <p>I'm trying to put my NestedScrollView on my MapFragment, but when I'm trying to, this error appears :</p>
<blockquote>
<p>Attempt to invoke virtual method 'android.view.View android.support.v4.widget.NestedScrollView.findViewById(int)' on a null object reference</p>
</blockquote>
<p>Here is my MapFragment.java file</p>
<pre><code>package com.example.alexandre.list.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.alexandre.list.MainActivity;
import com.example.alexandre.list.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link OnMapClickListener} interface
* to handle interaction events.
* Use the {@link MapFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MapFragment extends Fragment implements OnMapReadyCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private GoogleMap mGoogleMap;
private MapView mMapView;
private OnMapClickListener mListener;
public MapFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment MapFragment.
*/
// TODO: Rename and change types and number of parameters
public static MapFragment newInstance(String param1, String param2) {
MapFragment fragment = new MapFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, container, false);
bindViews(view, savedInstanceState);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed() {
if (mListener != null) {
mListener.onMapClick();
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnMapClickListener) {
mListener = (OnMapClickListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnTweetListClickListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private void bindViews(View view, Bundle savedInstanceState) {
mMapView = view.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
LatLng castlePos = new LatLng(45.209299, 5.659144);
LatLng treePos = new LatLng(MainActivity.posx, MainActivity.posy);
CameraPosition liberty = CameraPosition.builder().target(castlePos).zoom(17)/*.bearing(0).tilt(0)*/.build();
Marker marker = mGoogleMap.addMarker(new MarkerOptions()
.position(treePos)
.title("Test du cèdre du Liban")
.snippet("Libani"));
marker.hideInfoWindow();
mGoogleMap.setOnMarkerClickListener(
new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
NestedScrollView nestedScrollView = null;
nestedScrollView = (NestedScrollView) nestedScrollView.findViewById(R.id.bottom_sheet);
nestedScrollView.setVisibility(View.VISIBLE);
return false;
}
}
);
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(liberty));
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnMapClickListener {
void onMapClick();
}
}
</code></pre>
<p>It looks like R.id.nestedScrollView return NULL, but why ?</p>
<p>Thanks !</p>
| 0debug
|
how to read text file orderly in Java? : <p>I know how to read a text file, but I don't know how to read it orderly. For instance, how to read this" Tosca|Giacomo Puccini|1900|Rome|Puccini’s melodrama about a volatile diva, a sadistic police chief, and an idealistic artist|<a href="https://www.youtube.com/watch?v=rkMx0CLWeRQ" rel="nofollow noreferrer">https://www.youtube.com/watch?v=rkMx0CLWeRQ</a>"? Different information is separated by | , and I want them to display on different JLabel. </p>
<p>I did this</p>
<pre><code>while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
</code></pre>
<p>What else should I do in the while loop?</p>
| 0debug
|
MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) : <p>I've tried multiple solutions from StackOverflow but haven't had any success. I'm on Mac OSX (Sierra 10.12.3) trying to create a new database and user. From terminal I enter:</p>
<pre><code>mysql -u root
</code></pre>
<p>which outputs this error:</p>
<blockquote>
<p>ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)</p>
</blockquote>
<p>To try and resolve it I stopped mysql from 'System Preferences', then from terminal typed:</p>
<pre><code>sudo mysqld_safe —skip-grant-tables
</code></pre>
<p>I opened a second tab and entered:</p>
<pre><code>mysql -u root
</code></pre>
<p>Then from in mysql:</p>
<pre><code>update mysql.user set password_expired = 'N', authentication_string=PASSWORD('newpassword') where user = 'root';
flush privileges;
</code></pre>
<p>I then restart the computer (killing the process with CMD + C doesn't work). After restarting, trying <code>mysql -u root</code> still produces the same error.</p>
<p>I am able to access mysql via a MySQL client and a non-root user.</p>
<p>Any help is appreciated.</p>
| 0debug
|
iOS - Objective C, Sort NSArray of NSDictionary(s) via key name : <p>How to sort NSArray of dictionaries on the basis of NSDictionary's key name.</p>
<p>lets say, JSON format of NSArray is</p>
<pre><code>[
{
"keyName" : "C",
"value" : "0.1"
},
{
"keyName" : "A",
"value" : "1.1"
},
{
"keyName" : "B",
"value" : "2.1"
}
]
</code></pre>
| 0debug
|
How to start elasticsearch 5.1 embedded in my java application? : <p>With elasticsearch 2.x I used the following code to launch an embedded Node for testing:</p>
<pre><code>@Bean
public Node elasticSearchTestNode() {
return NodeBuilder.nodeBuilder()
.settings(Settings.settingsBuilder()
.put("http.enabled", "true")
.put("path.home", "elasticsearch-data")
.build())
.node();
}
</code></pre>
<p>This does not compile any more. How can I start an embedded node in 5.x ?</p>
| 0debug
|
void bitmap_clear(unsigned long *map, long start, long nr)
{
unsigned long *p = map + BIT_WORD(start);
const long size = start + nr;
int bits_to_clear = BITS_PER_LONG - (start % BITS_PER_LONG);
unsigned long mask_to_clear = BITMAP_FIRST_WORD_MASK(start);
while (nr - bits_to_clear >= 0) {
*p &= ~mask_to_clear;
nr -= bits_to_clear;
bits_to_clear = BITS_PER_LONG;
mask_to_clear = ~0UL;
p++;
}
if (nr) {
mask_to_clear &= BITMAP_LAST_WORD_MASK(size);
*p &= ~mask_to_clear;
}
}
| 1threat
|
Calling a method from a different firm in C# : I have 2 forms. First one (Form1) has a datagrid, the second one (Form2) has a button to call a function in Form1 to refresh the datagrid.
All i want to achieve is; on clicking the button in form2 , form1 datagrid should refresh (this refresh will be as a result of calling the function temp_proj )
How can i achieve this?
| 0debug
|
static int decode_nal_units(HEVCContext *s, const uint8_t *buf, int length)
{
int i, consumed, ret = 0;
s->ref = NULL;
s->last_eos = s->eos;
s->eos = 0;
s->nb_nals = 0;
while (length >= 4) {
HEVCNAL *nal;
int extract_length = 0;
if (s->is_nalff) {
int i;
for (i = 0; i < s->nal_length_size; i++)
extract_length = (extract_length << 8) | buf[i];
buf += s->nal_length_size;
length -= s->nal_length_size;
if (extract_length > length) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid NAL unit size.\n");
ret = AVERROR_INVALIDDATA;
}
} else {
while (buf[0] != 0 || buf[1] != 0 || buf[2] != 1) {
++buf;
--length;
if (length < 4) {
av_log(s->avctx, AV_LOG_ERROR, "No start code is found.\n");
ret = AVERROR_INVALIDDATA;
}
}
buf += 3;
length -= 3;
}
if (!s->is_nalff)
extract_length = length;
if (s->nals_allocated < s->nb_nals + 1) {
int new_size = s->nals_allocated + 1;
void *tmp = av_realloc_array(s->nals, new_size, sizeof(*s->nals));
ret = AVERROR(ENOMEM);
if (!tmp) {
}
s->nals = tmp;
memset(s->nals + s->nals_allocated, 0,
(new_size - s->nals_allocated) * sizeof(*s->nals));
tmp = av_realloc_array(s->skipped_bytes_nal, new_size, sizeof(*s->skipped_bytes_nal));
if (!tmp)
s->skipped_bytes_nal = tmp;
tmp = av_realloc_array(s->skipped_bytes_pos_size_nal, new_size, sizeof(*s->skipped_bytes_pos_size_nal));
if (!tmp)
s->skipped_bytes_pos_size_nal = tmp;
tmp = av_realloc_array(s->skipped_bytes_pos_nal, new_size, sizeof(*s->skipped_bytes_pos_nal));
if (!tmp)
s->skipped_bytes_pos_nal = tmp;
s->skipped_bytes_pos_size_nal[s->nals_allocated] = 1024;
s->skipped_bytes_pos_nal[s->nals_allocated] = av_malloc_array(s->skipped_bytes_pos_size_nal[s->nals_allocated], sizeof(*s->skipped_bytes_pos));
s->nals_allocated = new_size;
}
s->skipped_bytes_pos_size = s->skipped_bytes_pos_size_nal[s->nb_nals];
s->skipped_bytes_pos = s->skipped_bytes_pos_nal[s->nb_nals];
nal = &s->nals[s->nb_nals];
consumed = ff_hevc_extract_rbsp(s, buf, extract_length, nal);
s->skipped_bytes_nal[s->nb_nals] = s->skipped_bytes;
s->skipped_bytes_pos_size_nal[s->nb_nals] = s->skipped_bytes_pos_size;
s->skipped_bytes_pos_nal[s->nb_nals++] = s->skipped_bytes_pos;
if (consumed < 0) {
ret = consumed;
}
ret = init_get_bits8(&s->HEVClc->gb, nal->data, nal->size);
if (ret < 0)
hls_nal_unit(s);
if (s->nal_unit_type == NAL_EOB_NUT ||
s->nal_unit_type == NAL_EOS_NUT)
s->eos = 1;
buf += consumed;
length -= consumed;
}
for (i = 0; i < s->nb_nals; i++) {
int ret;
s->skipped_bytes = s->skipped_bytes_nal[i];
s->skipped_bytes_pos = s->skipped_bytes_pos_nal[i];
ret = decode_nal_unit(s, &s->nals[i]);
if (ret < 0) {
av_log(s->avctx, AV_LOG_WARNING,
"Error parsing NAL unit #%d.\n", i);
}
}
fail:
if (s->ref && s->threads_type == FF_THREAD_FRAME)
ff_thread_report_progress(&s->ref->tf, INT_MAX, 0);
return ret;
}
| 1threat
|
CPUMIPSState *cpu_mips_init (const char *cpu_model)
{
CPUMIPSState *env;
const mips_def_t *def;
def = cpu_mips_find_by_name(cpu_model);
if (!def)
return NULL;
env = qemu_mallocz(sizeof(CPUMIPSState));
env->cpu_model = def;
cpu_exec_init(env);
env->cpu_model_str = cpu_model;
mips_tcg_init();
cpu_reset(env);
qemu_init_vcpu(env);
return env;
}
| 1threat
|
int ff_srtp_decrypt(struct SRTPContext *s, uint8_t *buf, int *lenptr)
{
uint8_t iv[16] = { 0 }, hmac[20];
int len = *lenptr;
int ext, seq_largest;
uint32_t ssrc, roc;
uint64_t index;
int rtcp;
if (len < s->hmac_size)
return AVERROR_INVALIDDATA;
rtcp = RTP_PT_IS_RTCP(buf[1]);
av_hmac_init(s->hmac, rtcp ? s->rtcp_auth : s->rtp_auth, sizeof(s->rtp_auth));
av_hmac_update(s->hmac, buf, len - s->hmac_size);
if (!rtcp) {
int seq = AV_RB16(buf + 2);
uint32_t v;
uint8_t rocbuf[4];
seq_largest = s->seq_initialized ? s->seq_largest : seq;
v = roc = s->roc;
if (seq_largest < 32768) {
if (seq - seq_largest > 32768)
v = roc - 1;
} else {
if (seq_largest - 32768 > seq)
v = roc + 1;
}
if (v == roc) {
seq_largest = FFMAX(seq_largest, seq);
} else if (v == roc + 1) {
seq_largest = seq;
roc = v;
}
index = seq + (((uint64_t)v) << 16);
AV_WB32(rocbuf, roc);
av_hmac_update(s->hmac, rocbuf, 4);
}
av_hmac_final(s->hmac, hmac, sizeof(hmac));
if (memcmp(hmac, buf + len - s->hmac_size, s->hmac_size)) {
av_log(NULL, AV_LOG_WARNING, "HMAC mismatch\n");
return AVERROR_INVALIDDATA;
}
len -= s->hmac_size;
*lenptr = len;
if (len < 12)
return AVERROR_INVALIDDATA;
if (rtcp) {
uint32_t srtcp_index = AV_RB32(buf + len - 4);
len -= 4;
*lenptr = len;
ssrc = AV_RB32(buf + 4);
index = srtcp_index & 0x7fffffff;
buf += 8;
len -= 8;
if (!(srtcp_index & 0x80000000))
return 0;
} else {
s->seq_initialized = 1;
s->seq_largest = seq_largest;
s->roc = roc;
ext = buf[0] & 0x10;
ssrc = AV_RB32(buf + 8);
buf += 12;
len -= 12;
if (ext) {
if (len < 4)
return AVERROR_INVALIDDATA;
ext = (AV_RB16(buf + 2) + 1) * 4;
if (len < ext)
return AVERROR_INVALIDDATA;
len -= ext;
buf += ext;
}
}
create_iv(iv, rtcp ? s->rtcp_salt : s->rtp_salt, index, ssrc);
av_aes_init(s->aes, rtcp ? s->rtcp_key : s->rtp_key, 128, 0);
encrypt_counter(s->aes, iv, buf, len);
return 0;
}
| 1threat
|
How to remove an old commit in Git : All:
I am pretty new in Git, I wonder say I have submitted several commits like:
1 -> 2 -> 3 -> 4
Could anyone show me the steps how to remove commit 3?
Say each commit I just append that order number to same file.
So for
1:
the file content is 1.
2:
the file content is 12.
3:
the file content is 123.
4:
the file content is 1234.
Thanks
| 0debug
|
How to convert the following line from jQuery 2.2.4 to jQuery version 3.1.1? : What's the jQuery 3.1.1 version of this jQuery 2.2.4 line:
expandDiv.style.width = Math.min(Math.max(scrollAndSpeed, 20), 95) + "%";
| 0debug
|
PyCharm debug console not working : <p>I can run the debugger and put breakpoints to active the console but it appears as if the console doesn't pick up the code I am entering.</p>
<p>I can just type anything but I don't get any ouput,</p>
<pre><code>a=2
print(a)
sfgsmk
..g.bbcvdgdggh
</code></pre>
<p>Any ideas how I can get the debug console to run the code I am typing and how to get it to show output.</p>
<p>I am using Community Edition 2017.1.4</p>
| 0debug
|
How to parse non-english mixed text in Python : <p>I have the following random data generated by parsing an image - <a href="https://dpaste.de/wwuj/raw" rel="nofollow noreferrer">https://dpaste.de/wwuj/raw</a></p>
<p>I want to generate a csv and need to extract the following data from the text </p>
<pre><code>नाम, पति का नाम, मकान संख्या, आयु, लिंग
</code></pre>
<p>Questions :</p>
<ol>
<li><p>Can we use regex to parse non-english characters in python? </p></li>
<li><p>It would be good if you could show a small demo on how to get the field values. </p></li>
</ol>
<p>Thanks. </p>
| 0debug
|
static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
{
BDRVQcowState *s = bs->opaque;
int ret;
qemu_co_mutex_lock(&s->lock);
ret = qcow2_cache_flush(bs, s->l2_table_cache);
if (ret < 0) {
qemu_co_mutex_unlock(&s->lock);
return ret;
}
ret = qcow2_cache_flush(bs, s->refcount_block_cache);
if (ret < 0) {
qemu_co_mutex_unlock(&s->lock);
return ret;
}
qemu_co_mutex_unlock(&s->lock);
return 0;
}
| 1threat
|
Is there any use for basic_string<T> where T is not a character type? : <p>The declaration of C++ string <a href="http://en.cppreference.com/w/cpp/string/basic_string" rel="noreferrer">is the following</a>:</p>
<pre><code>template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
> class basic_string;
</code></pre>
<p>The <code>CharT</code> is character type which can be <code>char</code>, <code>wchar_t</code>, <code>char16_t</code> and <code>char32_t</code>; but after all <code>basic_string</code> is a template so can be instantiated with other <code>CharT</code> and other allocators. While I can think in some use cases for other allocators I'm unable to think in use cases for strings of other data types, for example:</p>
<pre><code>using string = std::basic_string<int>;
</code></pre>
<p>Using a string of integers, we cannot initialize it as a string (obvious) nor u32 string (not that obvious, at least for me); but we can initialize it with <code>initializer_list</code> as long as the contained type of the list is convertible to <code>int</code>:</p>
<pre><code>string err1("test"); // Error!
string err2(U"test"); // Error!
string err3{"test"}; // Error!
string err4{U"test"}; // Error!
string err5 = "test"; // Error!
string err6 = U"test"; // Error!
string success1({U't', U'e', U's', U't'});
string success2 = {U't', U'e', U's', U't'};
string success3({'t', 'e', 's', 't'});
string success4 = {'t', 'e', 's', 't'};
</code></pre>
<p>But even if we manage to initialize a integer string, we cannot use it in the normal way:</p>
<pre><code>std::cout << success1; // Error! expected 116101115116
</code></pre>
<p>The only <code>basic_string</code> expected to be used with <code>cout</code> are the <em>normal</em> ones, that makes sense: after all we cannot assume how is supposed to be printed a string of integers or a string of <code>MyFancyClass</code>es.</p>
<p>But anyways, the creation of <em>strange</em> instances of <code>basic_string</code> isn't forbidden; on one hand is not forbidden due to the lack of features which forbids that use (a.k.a. concepts) and on the other coding <code>basic_string</code> without limiting the underlying type is easier than doing it on the opposite way (without concepts) so, that makes me wonder:</p>
<ul>
<li>Is there any use for <code>std::basic_string<T></code> where <code>T</code> is not a character type?</li>
</ul>
<p>As for <em>any use</em> I'm thinking about things that only can be achieved with strings of <code>T</code> and that cannot be done with vector of <code>T</code> (or it will be significantly harder to do), in other words:</p>
<ul>
<li>Have you ever faced a situation where a string of <code>T</code> is the better choice?</li>
</ul>
| 0debug
|
MKMapView center and zoom in : <p>I am using MKMapView on a project and would like to center the map on a coordinate and zoom in. Just like Google maps has:</p>
<pre><code>GMSCameraPosition.camera(withLatitude: -33.8683,
longitude: 151.2086,
zoom: 6)
</code></pre>
<p>Is there any Mapkit method for this?</p>
| 0debug
|
static void count_colors(AVCodecContext *avctx, unsigned hits[33],
const AVSubtitleRect *r)
{
DVDSubtitleContext *dvdc = avctx->priv_data;
unsigned count[256] = { 0 };
uint32_t *palette = (uint32_t *)r->pict.data[1];
uint32_t color;
int x, y, i, j, match, d, best_d, av_uninit(best_j);
uint8_t *p = r->pict.data[0];
for (y = 0; y < r->h; y++) {
for (x = 0; x < r->w; x++)
count[*(p++)]++;
p += r->pict.linesize[0] - r->w;
}
for (i = 0; i < 256; i++) {
if (!count[i])
continue;
color = palette[i];
match = color < 0x33000000 ? 0 : color < 0xCC000000 ? 1 : 17;
if (match) {
best_d = INT_MAX;
for (j = 0; j < 16; j++) {
d = color_distance(color & 0xFFFFFF, dvdc->global_palette[j]);
if (d < best_d) {
best_d = d;
best_j = j;
}
}
match += best_j;
}
hits[match] += count[i];
}
}
| 1threat
|
static void gen_mtc0 (DisasContext *ctx, int reg, int sel)
{
const char *rn = "invalid";
switch (reg) {
case 0:
switch (sel) {
case 0:
gen_op_mtc0_index();
rn = "Index";
break;
case 1:
rn = "MVPControl";
case 2:
rn = "MVPConf0";
case 3:
rn = "MVPConf1";
default:
goto die;
}
break;
case 1:
switch (sel) {
case 0:
rn = "Random";
break;
case 1:
rn = "VPEControl";
case 2:
rn = "VPEConf0";
case 3:
rn = "VPEConf1";
case 4:
rn = "YQMask";
case 5:
rn = "VPESchedule";
case 6:
rn = "VPEScheFBack";
case 7:
rn = "VPEOpt";
default:
goto die;
}
break;
case 2:
switch (sel) {
case 0:
gen_op_mtc0_entrylo0();
rn = "EntryLo0";
break;
case 1:
rn = "TCStatus";
case 2:
rn = "TCBind";
case 3:
rn = "TCRestart";
case 4:
rn = "TCHalt";
case 5:
rn = "TCContext";
case 6:
rn = "TCSchedule";
case 7:
rn = "TCScheFBack";
default:
goto die;
}
break;
case 3:
switch (sel) {
case 0:
gen_op_mtc0_entrylo1();
rn = "EntryLo1";
break;
default:
goto die;
}
break;
case 4:
switch (sel) {
case 0:
gen_op_mtc0_context();
rn = "Context";
break;
case 1:
rn = "ContextConfig";
default:
goto die;
}
break;
case 5:
switch (sel) {
case 0:
gen_op_mtc0_pagemask();
rn = "PageMask";
break;
case 1:
gen_op_mtc0_pagegrain();
rn = "PageGrain";
break;
default:
goto die;
}
break;
case 6:
switch (sel) {
case 0:
gen_op_mtc0_wired();
rn = "Wired";
break;
case 1:
rn = "SRSConf0";
case 2:
rn = "SRSConf1";
case 3:
rn = "SRSConf2";
case 4:
rn = "SRSConf3";
case 5:
rn = "SRSConf4";
default:
goto die;
}
break;
case 7:
switch (sel) {
case 0:
gen_op_mtc0_hwrena();
rn = "HWREna";
break;
default:
goto die;
}
break;
case 8:
rn = "BadVaddr";
break;
case 9:
switch (sel) {
case 0:
gen_op_mtc0_count();
rn = "Count";
break;
default:
goto die;
}
ctx->bstate = BS_STOP;
break;
case 10:
switch (sel) {
case 0:
gen_op_mtc0_entryhi();
rn = "EntryHi";
break;
default:
goto die;
}
break;
case 11:
switch (sel) {
case 0:
gen_op_mtc0_compare();
rn = "Compare";
break;
default:
goto die;
}
ctx->bstate = BS_STOP;
break;
case 12:
switch (sel) {
case 0:
gen_op_mtc0_status();
gen_save_pc(ctx->pc + 4);
ctx->bstate = BS_EXCP;
rn = "Status";
break;
case 1:
gen_op_mtc0_intctl();
ctx->bstate = BS_STOP;
rn = "IntCtl";
break;
case 2:
gen_op_mtc0_srsctl();
ctx->bstate = BS_STOP;
rn = "SRSCtl";
break;
case 3:
gen_op_mtc0_srsmap();
ctx->bstate = BS_STOP;
rn = "SRSMap";
break;
default:
goto die;
}
break;
case 13:
switch (sel) {
case 0:
gen_op_mtc0_cause();
rn = "Cause";
break;
default:
goto die;
}
ctx->bstate = BS_STOP;
break;
case 14:
switch (sel) {
case 0:
gen_op_mtc0_epc();
rn = "EPC";
break;
default:
goto die;
}
break;
case 15:
switch (sel) {
case 0:
rn = "PRid";
break;
case 1:
gen_op_mtc0_ebase();
rn = "EBase";
break;
default:
goto die;
}
break;
case 16:
switch (sel) {
case 0:
gen_op_mtc0_config0();
rn = "Config";
ctx->bstate = BS_STOP;
break;
case 1:
rn = "Config1";
break;
case 2:
gen_op_mtc0_config2();
rn = "Config2";
ctx->bstate = BS_STOP;
break;
case 3:
rn = "Config3";
break;
case 6:
rn = "Config6";
break;
case 7:
rn = "Config7";
break;
default:
rn = "Invalid config selector";
goto die;
}
break;
case 17:
switch (sel) {
case 0:
rn = "LLAddr";
break;
default:
goto die;
}
break;
case 18:
switch (sel) {
case 0 ... 7:
gen_op_mtc0_watchlo(sel);
rn = "WatchLo";
break;
default:
goto die;
}
break;
case 19:
switch (sel) {
case 0 ... 7:
gen_op_mtc0_watchhi(sel);
rn = "WatchHi";
break;
default:
goto die;
}
break;
case 20:
switch (sel) {
case 0:
#ifdef TARGET_MIPS64
gen_op_mtc0_xcontext();
rn = "XContext";
break;
#endif
default:
goto die;
}
break;
case 21:
switch (sel) {
case 0:
gen_op_mtc0_framemask();
rn = "Framemask";
break;
default:
goto die;
}
break;
case 22:
rn = "Diagnostic";
break;
case 23:
switch (sel) {
case 0:
gen_op_mtc0_debug();
gen_save_pc(ctx->pc + 4);
ctx->bstate = BS_EXCP;
rn = "Debug";
break;
case 1:
rn = "TraceControl";
ctx->bstate = BS_STOP;
case 2:
rn = "TraceControl2";
ctx->bstate = BS_STOP;
case 3:
ctx->bstate = BS_STOP;
rn = "UserTraceData";
ctx->bstate = BS_STOP;
case 4:
ctx->bstate = BS_STOP;
rn = "TraceBPC";
default:
goto die;
}
break;
case 24:
switch (sel) {
case 0:
gen_op_mtc0_depc();
rn = "DEPC";
break;
default:
goto die;
}
break;
case 25:
switch (sel) {
case 0:
gen_op_mtc0_performance0();
rn = "Performance0";
break;
case 1:
rn = "Performance1";
case 2:
rn = "Performance2";
case 3:
rn = "Performance3";
case 4:
rn = "Performance4";
case 5:
rn = "Performance5";
case 6:
rn = "Performance6";
case 7:
rn = "Performance7";
default:
goto die;
}
break;
case 26:
rn = "ECC";
break;
case 27:
switch (sel) {
case 0 ... 3:
rn = "CacheErr";
break;
default:
goto die;
}
break;
case 28:
switch (sel) {
case 0:
case 2:
case 4:
case 6:
gen_op_mtc0_taglo();
rn = "TagLo";
break;
case 1:
case 3:
case 5:
case 7:
gen_op_mtc0_datalo();
rn = "DataLo";
break;
default:
goto die;
}
break;
case 29:
switch (sel) {
case 0:
case 2:
case 4:
case 6:
gen_op_mtc0_taghi();
rn = "TagHi";
break;
case 1:
case 3:
case 5:
case 7:
gen_op_mtc0_datahi();
rn = "DataHi";
break;
default:
rn = "invalid sel";
goto die;
}
break;
case 30:
switch (sel) {
case 0:
gen_op_mtc0_errorepc();
rn = "ErrorEPC";
break;
default:
goto die;
}
break;
case 31:
switch (sel) {
case 0:
gen_op_mtc0_desave();
rn = "DESAVE";
break;
default:
goto die;
}
ctx->bstate = BS_STOP;
break;
default:
goto die;
}
#if defined MIPS_DEBUG_DISAS
if (loglevel & CPU_LOG_TB_IN_ASM) {
fprintf(logfile, "mtc0 %s (reg %d sel %d)\n",
rn, reg, sel);
}
#endif
return;
die:
#if defined MIPS_DEBUG_DISAS
if (loglevel & CPU_LOG_TB_IN_ASM) {
fprintf(logfile, "mtc0 %s (reg %d sel %d)\n",
rn, reg, sel);
}
#endif
generate_exception(ctx, EXCP_RI);
}
| 1threat
|
Node process object made available to browser client code : <p>I'm trying to understand how webpack uses DefinePlugin. I have:</p>
<pre><code>new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
}),
</code></pre>
<p>and a function:</p>
<pre><code>export const foo = () => {
console.log(process)
console.log(process.env.NODE_ENV)
}
window.foo = foo
</code></pre>
<p>when I print foo, I see the following in my browser console:</p>
<pre><code>ƒ foo() {
console.log(process);
console.log("development");
}
</code></pre>
<p>It seems like the variable "development" was injected while webpack was compiling the input file. At the same time webpack also injected the process object into the JavaScript code, and the browser did print out the process object when foo was called:</p>
<pre><code>{title: "browser", browser: true, env: {…}, argv: Array(0), nextTick: ƒ, …}
</code></pre>
<p>My question is, how can the process object, which is a Node concept, be made available to the browser?</p>
<p>In fact, if I do:</p>
<pre><code>window.process = process
</code></pre>
<p>I can use process.nextTick right inside the browser console! I thought the nextTick function was a Node-specific implementation! Could anybody explain this?</p>
<p>Thank you!</p>
| 0debug
|
after capture camera image when i save then not return in activity and crash app but everything is ok in my samsung mobile : #after capture camera image when i save then not return in activity and crash app but everything is ok in my samsung mobile but giving this error in redmii phone and others mobile #
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.toString()' on a null object reference
at com.logiclump.technologies.gigmedico.Home.onActivityResult(Home.java:101)
at android.app.Activity.dispatchActivityResult(Activity.java:6562)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3768)
#this is second activity where i m getting inttent#
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Log.e("ashish", bundle.getString("imgUrl") + "");
path = Uri.parse(bundle.getString("imgUrl"));
}
ImageView selfiiii = (ImageView) findViewById(R.id.mySelfie);
selfiiii.setImageURI(path);
| 0debug
|
static int do_packet_auto_bsf(AVFormatContext *s, AVPacket *pkt) {
AVStream *st = s->streams[pkt->stream_index];
int i, ret;
if (!(s->flags & AVFMT_FLAG_AUTO_BSF))
return 1;
if (s->oformat->check_bitstream) {
if (!st->internal->bitstream_checked) {
if ((ret = s->oformat->check_bitstream(s, pkt)) < 0)
return ret;
else if (ret == 1)
st->internal->bitstream_checked = 1;
}
}
#if FF_API_LAVF_MERGE_SD
FF_DISABLE_DEPRECATION_WARNINGS
if (st->internal->nb_bsfcs) {
ret = av_packet_split_side_data(pkt);
if (ret < 0)
av_log(s, AV_LOG_WARNING, "Failed to split side data before bitstream filter\n");
}
FF_ENABLE_DEPRECATION_WARNINGS
#endif
for (i = 0; i < st->internal->nb_bsfcs; i++) {
AVBSFContext *ctx = st->internal->bsfcs[i];
if (i > 0) {
AVBSFContext* prev_ctx = st->internal->bsfcs[i - 1];
if (prev_ctx->par_out->extradata_size != ctx->par_in->extradata_size) {
if ((ret = avcodec_parameters_copy(ctx->par_in, prev_ctx->par_out)) < 0)
return ret;
}
}
if ((ret = av_bsf_send_packet(ctx, pkt)) < 0) {
av_log(ctx, AV_LOG_ERROR,
"Failed to send packet to filter %s for stream %d\n",
ctx->filter->name, pkt->stream_index);
return ret;
}
if ((ret = av_bsf_receive_packet(ctx, pkt)) < 0) {
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
return 0;
av_log(ctx, AV_LOG_ERROR,
"Failed to send packet to filter %s for stream %d\n",
ctx->filter->name, pkt->stream_index);
return ret;
}
if (i == st->internal->nb_bsfcs - 1) {
if (ctx->par_out->extradata_size != st->codecpar->extradata_size) {
if ((ret = avcodec_parameters_copy(st->codecpar, ctx->par_out)) < 0)
return ret;
}
}
}
return 1;
}
| 1threat
|
static void handle_arg_log_filename(const char *arg)
{
qemu_set_log_filename(arg);
}
| 1threat
|
Exit Vim External Command Line Shell : <p>I accidentally put ping 8.8.8.8 in the Vim External Command Line Shell by executing
:! ping 8.8.8.8
Now the command won't stop and I am not able to return to my file editing buffer in Vim. When I press Ctrl+Z it suspends the entire vim process and takes me back to Linux Shell. Is there any way to suspend/kill the Vim Shell subprocess in case it goes into some kind of infinite execution and return back to Vim buffer ?</p>
| 0debug
|
change color of a white box using jquery : <p>hello I want to know how I can change the color of an image using different color boxes i have an image of a heart and i want to change color from white to red, blue, yellow ect. i want to be able to change it on command thank you </p>
<pre><code> <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
.foo {
float: left;
width: 20px;
height: 20px;
margin: 5px;
border: 1px solid rgba(0, 0, 0, .2);
}
.blue {
background: #0012E3;
}
.purple {
background: #ab3fdd;
}
.yellow {
background: #FFF728;
}
</style>
<style>
$('#background').on('change', changeColor);
function changeColor() {
var color = $('#background').val();
$('p').css('color', color);
}
.non {
margin: 15px;
padding: 15px;
clear: none;
float: none;
height: 15px;
width: 15px;
}
</style>
</head>
<body>
<div class="foo blue"></div>
<div class="foo purple"></div>
<div class="foo yellow"></div>
<p><img src="Pictures\heart.gif" width="550" height="712" border="0"></p>
</body>
</html>
</code></pre>
| 0debug
|
Two Digit next dot two digit next dot twodigittwoalphabets using regex in singleline of text field : Hi I need the digit to be displayed as follows
00.11.12aa or 00.12.55 or 11.48.61d
starts with 2 digit and decimal then 2 digit then decimal then twodigit or twodigit one alpha or twodigit two alpha.
I need to validate in single line of text field. Please tell me how to do it.
| 0debug
|
Are there any sample desktop apps/examples to practise mutithreading : I am new to multithreading . I had read theory a lot but not able to get good grip on this subject. Do you suggest any desktop apps/examples to practise to get better understanding of this subject.
Anytype of suggestion is welcomed.
| 0debug
|
python pandas\numpy encode unique by integers : <p>Say I have <code>x=["apple","orange","orange","apple","pear"]</code> I would like to have a categorical representation with integers e.g. <code>y=[1,2,2,1,3]</code>. What would be the best way to do so?</p>
| 0debug
|
static int vda_h264_start_frame(AVCodecContext *avctx,
av_unused const uint8_t *buffer,
av_unused uint32_t size)
{
VDAContext *vda = avctx->internal->hwaccel_priv_data;
struct vda_context *vda_ctx = avctx->hwaccel_context;
if (!vda_ctx->decoder)
return -1;
vda->bitstream_size = 0;
return 0;
}
| 1threat
|
java.lang.IllegalArgumentException: Plugin already initialized. How to fix? : <p>When I'm testing my new plugin an exception keeps getting thrown: java.lang.IllegalArgumentException: Plugin already initialized! Please help! Here's the code:</p>
<pre><code>package me.plugin.example;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.event.Listener;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;
public class Main extends JavaPlugin implements Listener {
@Override
public void onEnable() {
getServer().getPluginManager().registerEvents(new Main(), this);
}
@EventHandler
public void onPlayerJoinEvent(PlayerJoinEvent event) {
Player p = event.getPlayer();
event.setJoinMessage(ChatColor.AQUA + p.getPlayerListName() + " has joined the game.");
p.sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "Welcome to the server!");
p.setGameMode(GameMode.ADVENTURE);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = (Player) sender;
if (cmd.getName().equalsIgnoreCase("example")) {
player.sendMessage(ChatColor.BOLD + ""+ ChatColor.ITALIC + "Hello! Hope you like to be set on fire. lol :P");
player.setFireTicks(20);
}
return true;
}
@Override
public void onDisable() {
}
}
</code></pre>
<p>I know that you're only supposed to declare one JavaPlugin class per plugin, which I think I'm doing. But it keeps saying:</p>
<pre><code>java.lang.IllegalArgumentException: Plugin already initialized!
at org.bukkit.plugin.java.PluginClassLoader.initialize(PluginClassLoader.java:122) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
at org.bukkit.plugin.java.JavaPlugin.<init>(JavaPlugin.java:66) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
at me.plugin.example.Main.<init>(Main.java:19) ~[?:?]
at me.plugin.example.Main.onEnable(Main.java:27) ~[?:?]
at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:340) [spigot.jar:git-Spigot-db6de12-18fbb24]
at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405) [spigot.jar:git-Spigot-db6de12-18fbb24]
at org.bukkit.craftbukkit.v1_8_R3.CraftServer.loadPlugin(CraftServer.java:357) [spigot.jar:git-Spigot-db6de12-18fbb24]
at org.bukkit.craftbukkit.v1_8_R3.CraftServer.enablePlugins(CraftServer.java:317) [spigot.jar:git-Spigot-db6de12-18fbb24]
at net.minecraft.server.v1_8_R3.MinecraftServer.s(MinecraftServer.java:414) [spigot.jar:git-Spigot-db6de12-18fbb24]
at net.minecraft.server.v1_8_R3.MinecraftServer.k(MinecraftServer.java:378) [spigot.jar:git-Spigot-db6de12-18fbb24]
at net.minecraft.server.v1_8_R3.MinecraftServer.a(MinecraftServer.java:333) [spigot.jar:git-Spigot-db6de12-18fbb24]
at net.minecraft.server.v1_8_R3.DedicatedServer.init(DedicatedServer.java:263) [spigot.jar:git-Spigot-db6de12-18fbb24]
at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:525) [spigot.jar:git-Spigot-db6de12-18fbb24]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_201]
Caused by: java.lang.IllegalStateException: Initial initialization
at org.bukkit.plugin.java.PluginClassLoader.initialize(PluginClassLoader.java:125) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
at org.bukkit.plugin.java.JavaPlugin.<init>(JavaPlugin.java:66) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
at me.plugin.example.Main.<init>(Main.java:19) ~[?:?]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_201]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_201]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_201]
at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[?:1.8.0_201]
at java.lang.Class.newInstance(Unknown Source) ~[?:1.8.0_201]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:76) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:131) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:329) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:251) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
at org.bukkit.craftbukkit.v1_8_R3.CraftServer.loadPlugins(CraftServer.java:292) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
at net.minecraft.server.v1_8_R3.DedicatedServer.init(DedicatedServer.java:198) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
... 2 more
</code></pre>
<p>I really need to test this plugin to see if it works, and any help would be greatly appreciated! Thank you!</p>
| 0debug
|
static abi_long do_getsockname(int fd, abi_ulong target_addr,
abi_ulong target_addrlen_addr)
{
socklen_t addrlen;
void *addr;
abi_long ret;
if (target_addr == 0)
return get_errno(accept(fd, NULL, NULL));
if (get_user_u32(addrlen, target_addrlen_addr))
return -TARGET_EFAULT;
if (addrlen < 0)
return -TARGET_EINVAL;
addr = alloca(addrlen);
ret = get_errno(getsockname(fd, addr, &addrlen));
if (!is_error(ret)) {
host_to_target_sockaddr(target_addr, addr, addrlen);
if (put_user_u32(addrlen, target_addrlen_addr))
ret = -TARGET_EFAULT;
}
return ret;
}
| 1threat
|
Unhandled Promise rejection: Cannot match any routes : <p>When I run this unit test:</p>
<pre><code>it('can click profile link in template', () => {
const landingPageLinkDe = linkDes[0];
const profileLinkDe = linkDes[1];
const aboutLinkDe = linkDes[2];
const findLinkDe = linkDes[3];
const addLinkDe = linkDes[4];
const registerLinkDe = linkDes[5];
const landingPageLinkFull = links[0];
const profileLinkFull = links[1];
const aboutLinkFull = links[2];
const findLinkFull = links[3];
const addLinkFull = links[4];
const registerLinkFull = links[5];
navFixture.detectChanges();
expect(profileLinkFull.navigatedTo)
.toBeNull('link should not have navigated yet');
profileLinkDe.triggerEventHandler('click', { button: 0 });
landingPageLinkDe.triggerEventHandler('click', { button: 0 });
aboutLinkDe.triggerEventHandler('click', { button: 0 });
registerLinkDe.triggerEventHandler('click', { button: 0 });
findLinkDe.triggerEventHandler('click', { button: 0 });
addLinkDe.triggerEventHandler('click', { button: 0 });
navFixture.detectChanges();
expect(landingPageLinkFull.navigatedTo).toBe('/');
expect(profileLinkFull.navigatedTo).toBe('/profile');
expect(aboutLinkFull.navigatedTo).toBe('/about');
expect(findLinkFull.navigatedTo).toBe('/find');
expect(addLinkFull.navigatedTo).toBe('/add');
expect(registerLinkFull.navigatedTo).toBe('/register');
});
</code></pre>
<p>I get this error:</p>
<blockquote>
<p>zone.js:388 Unhandled Promise rejection: Cannot match any routes. URL
Segment: 'add' ; Zone: ProxyZone ; Task: Promise.then ; Value: Error:
Cannot match any routes. URL Segment: 'add'(…) Error: Cannot match any
routes. URL Segment: 'add'</p>
</blockquote>
<p>The test still passes but it would be interesting to know why I'm getting the error. I don't get the error when I use the application as a user would. I've researched the error and it's usually due to not providing a default path in the routes, however I have done that. </p>
<p><strong>Am I doing something wrong to cause this error?</strong></p>
<p>navbar.component.spec.ts</p>
<pre><code>import 'zone.js/dist/long-stack-trace-zone.js';
import 'zone.js/dist/async-test.js';
import 'zone.js/dist/fake-async-test.js';
import 'zone.js/dist/sync-test.js';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/jasmine-patch.js';
import {
ComponentFixture,
TestBed,
async,
fakeAsync
} from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
import { By } from '@angular/platform-browser';
import {
DebugElement,
Component,
ViewChild,
Pipe,
PipeTransform,
CUSTOM_ELEMENTS_SCHEMA,
NO_ERRORS_SCHEMA
} from '@angular/core';
import { DatePipe } from '@angular/common';
import { Router, RouterOutlet, RouterModule } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { NavbarComponent } from './navbar.component';
import { RouterLinkStubDirective } from '../../router-stubs';
import { click } from '../../test/utilities.spec';
describe('NavbarComponent', () => {
let navComponent: NavbarComponent;
let navFixture: ComponentFixture<NavbarComponent>;
let linkDes: any;
let links: any;
let landingPageLink: any;
let profileLink: any;
let aboutLink: any;
let findLink: any;
let addLink: any;
let registerLink: any;
beforeAll(() => {
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(BrowserDynamicTestingModule,
platformBrowserDynamicTesting());
});
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
NavbarComponent,
RouterLinkStubDirective
],
imports: [RouterTestingModule],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
navFixture = TestBed.createComponent(NavbarComponent);
navComponent = navFixture.componentInstance;
navFixture.detectChanges();
linkDes = navFixture.debugElement
.queryAll(By.directive(RouterLinkStubDirective));
links = linkDes
.map((de: any) => de.injector
.get(RouterLinkStubDirective) as RouterLinkStubDirective);
landingPageLink = links[0].linkParams;
profileLink = links[1].linkParams;
aboutLink = links[2].linkParams;
findLink = links[3].linkParams;
addLink = links[4].linkParams;
registerLink = links[5].linkParams;
});
it('can get RouterLinks from template', () => {
expect(links.length).toBe(6, 'should have 6 links');
expect(landingPageLink[0])
.toEqual('/', '1st link should go to landing page');
expect(profileLink[0])
.toEqual('/profile', '2nd link should go to profile');
expect(aboutLink[0])
.toEqual('/about', '3rd link should go to about');
expect(findLink[0])
.toEqual('/find', '4th link should go to find');
expect(addLink[0])
.toEqual('/add', '5th link should go to add');
expect(registerLink[0])
.toEqual('/register', '6th link should go to register');
});
it('can click profile link in template', () => {
const landingPageLinkDe = linkDes[0];
const profileLinkDe = linkDes[1];
const aboutLinkDe = linkDes[2];
const findLinkDe = linkDes[3];
const addLinkDe = linkDes[4];
const registerLinkDe = linkDes[5];
const landingPageLinkFull = links[0];
const profileLinkFull = links[1];
const aboutLinkFull = links[2];
const findLinkFull = links[3];
const addLinkFull = links[4];
const registerLinkFull = links[5];
navFixture.detectChanges();
expect(profileLinkFull.navigatedTo)
.toBeNull('link should not have navigated yet');
profileLinkDe.triggerEventHandler('click', { button: 0 });
landingPageLinkDe.triggerEventHandler('click', { button: 0 });
aboutLinkDe.triggerEventHandler('click', { button: 0 });
registerLinkDe.triggerEventHandler('click', { button: 0 });
findLinkDe.triggerEventHandler('click', { button: 0 });
addLinkDe.triggerEventHandler('click', { button: 0 });
navFixture.detectChanges();
expect(landingPageLinkFull.navigatedTo).toBe('/');
expect(profileLinkFull.navigatedTo).toBe('/profile');
expect(aboutLinkFull.navigatedTo).toBe('/about');
expect(findLinkFull.navigatedTo).toBe('/find');
expect(addLinkFull.navigatedTo).toBe('/add');
expect(registerLinkFull.navigatedTo).toBe('/register');
});
});
</code></pre>
<p>stub for test:</p>
<pre><code>import 'zone.js/dist/long-stack-trace-zone.js';
import 'zone.js/dist/async-test.js';
import 'zone.js/dist/fake-async-test.js';
import 'zone.js/dist/sync-test.js';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/jasmine-patch.js';
import {
EventEmitter,
Output,
trigger,
state,
style,
transition,
animate,
Directive,
Input
} from '@angular/core';
import {
ComponentFixture,
TestBed,
async,
fakeAsync
} from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
import { By } from '@angular/platform-browser';
import {
DebugElement,
Component,
ViewChild,
Pipe,
PipeTransform
} from '@angular/core';
import { DatePipe } from '@angular/common';
import { Router } from '@angular/router';
import { NavbarComponent } from './shared/subcomponents/navbar.component';
import { AppComponent } from './app.component';
import { click } from './test/utilities.spec';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
@Directive({
selector: '[routerLink]',
host: {
'(click)': 'onClick()'
}
})
export class RouterLinkStubDirective {
@Input('routerLink') linkParams: any;
navigatedTo: any = null;
onClick() {
this.navigatedTo = this.linkParams[0];
}
}
</code></pre>
<p>app.routes.ts:</p>
<pre><code>import { Routes } from '@angular/router';
import { LandingPageComponent } from './landing-page/landing-page.component';
import { FindPageComponent } from './find-page/find-page.component';
import { AddPageComponent } from './add-page/add-page.component';
import { RegisterPageComponent } from './register-page/register-page.component';
import { AboutPageComponent } from './about-page/about-page.component';
import { ProfilePageComponent } from './profile-page/profile-page.component';
export const routerConfig: Routes = [
{
path: '',
component: LandingPageComponent
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
},
{
path: 'find',
component: FindPageComponent
},
{
path: 'add',
component: AddPageComponent
},
{
path: 'register',
component: RegisterPageComponent
},
{
path: 'about',
component: AboutPageComponent
},
{
path: 'profile',
component: ProfilePageComponent
}
];
</code></pre>
<p>navbar.component.html:</p>
<pre><code><nav class="navbar navbar-dark navbar-fixed-top text-uppercase">
<div class="container-fluid">
<button class="navbar-toggler hidden-md-up pull-xs-right"
type="button"
data-toggle="collapse"
data-target="#nav-content">
&#9776;
</button>
<a class="navbar-brand" [routerLink]="['/']"
routerLinkActive="active">vepo</a>
<div class="collapse navbar-toggleable-sm" id="nav-content">
<ul class="nav navbar-nav pull-xs-right">
<li class="nav-item">
<a class="nav-link" [routerLink]="['/profile']"
routerLinkActive="active">profile</a>
</li>
<li class="nav-item">
<a class="nav-link" [routerLink]="['/about']"
routerLinkActive="active">about</a>
</li>
<li class="nav-item">
<a class="nav-link" [routerLink]="['/find']"
routerLinkActive="active">find</a>
</li>
<li class="nav-item">
<a class="nav-link" [routerLink]="['/add']"
routerLinkActive="active">add</a>
</li>
<li class="nav-item">
<button type="button" class="as-text nav-link
text-uppercase" (click)="openModal()">
login
</button>
</li>
<li class="nav-item">
<a class="nav-link signup" [routerLink]="['/register']"
routerLinkActive="active">sign up free</a>
</li>
</ul>
</div>
</div>
</nav>
<login #modal></login>
<router-outlet></router-outlet>
</code></pre>
| 0debug
|
PHP How to find the occurrence of each and every value in an array : i have this array and i would like to find the number of occurence of every value inside this array
$theArray = array(1,1,2,3,3,3,3);
I would like to have this result
1=2;
2=1;
3=4
Thanks
| 0debug
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.