problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
Is there any front-end architecture specifically well suited for building sites with sitecore? : <p>Brand new to sitecore, don't have a solid grasp of what the site we are building looks like functionality wise, but curious to get opinions, pros and cons, articles that might have helped others, and the like. I've heard angular isn't too well suited to interact with sitecore, also read about reactJS.net being well suited.</p>
<p>Specifically, does anyone have experience to share on prebuild tools; css preprocessors; and javascript frameworks, templating tools, or libraries that have integrated well into sitecore, or ones that have integrated very poorly?</p>
<p>I hope this isn't too broad, I guess in my wild dream I'm imagining someone with extensive experience with sitecore itching to share their vast knowledge on their front end architecture...</p>
| 0debug
|
Porn CMS with iframes : <p>I'm looking for a CMS that can at least facilitate my work to create approximately 50k pages that contain code like:</p>
<pre><code><Iframe src = "http://link.com/embed/rewh3487432hdd" frameborder = "0" width = "608" height = "468" scrolling = "no"> </ iframe>
</code></pre>
<p>In addition to every video I have information such as the list of categories for each video (more than one for video), and tags that you would like to submit to me in some ways ..</p>
<p>I know that the request is quite general and will need to adapt the database to CMS, but would like to explore the possibility of avoiding me to generate the code to 0 ..</p>
<p>Thank you</p>
| 0debug
|
static int tta_read_packet(AVFormatContext *s, AVPacket *pkt)
{
TTAContext *c = s->priv_data;
AVStream *st = s->streams[0];
int size, ret;
if (c->currentframe > c->totalframes)
return -1;
size = st->index_entries[c->currentframe].size;
ret = av_get_packet(s->pb, pkt, size);
pkt->dts = st->index_entries[c->currentframe++].timestamp;
return ret;
}
| 1threat
|
static void rv40_v_strong_loop_filter(uint8_t *src, const int stride,
const int alpha, const int lims,
const int dmode, const int chroma)
{
rv40_strong_loop_filter(src, 1, stride, alpha, lims, dmode, chroma);
}
| 1threat
|
Angular 4 : How to use await/async within subscribe : <p>I can honestly say await/async in angular is really a great stuff, it reduces a lot of braces, improves readability and prevent a lot of human error. However, one thing puzzles me a lot. how can I use await/async inside subscribe.</p>
<p>let's say</p>
<pre><code> @Injectable()
export class TableCom extends BaseCom {
public subject = new Subject<any>();
}
</code></pre>
<p>TableCom is a provider serves as a communicator between a signalr component and a page component. </p>
<p>so inside the page component constructor, it is using the observable subject to receive new data from signalr component as shown below.</p>
<pre><code>constructor(protected nav: NavController,
protected db: Storage,
protected alert: AlertController,
protected order: OrderData,
protected translate: TranslateService,
public navParams: NavParams,
public toastCtrl: ToastController,
private table_data: TableData,
private load: LoadingController,
private http: Http,
private com_table: TableCom
)
{
super(nav, db, alert, order, translate, undefined, false);
this.previous_page = navParams.get('previous_page');
this.subscribe_table = this.com_table.Receive().subscribe(res =>
{
await this.SaveTableAsync(res.data);
this.ReadTableAsync();
});
}
</code></pre>
<p>the issue is that the this.ReadTableAsync() basically has to wait this.SaveTableAsync to be finished before starting. await can be achieved here ? thank you in advance !!</p>
| 0debug
|
What does this syntax [0:1:5] mean (do)? : I thought it was a matrix, but it doesn't seem to match the syntax for a matrix.
Here is the entire context:
function [x , y] = plotTrajectory(Vo,O,t,g)
% calculating x and y values
x = Vo * cos(O) * t ;
y = Vo*(sin(O)*t)-(0.5*g*(t.^2));
plot (x,y);
hold on
end
for i = (0: (pi/8): pi);
[x,y] = plotTrajectory(10,i,[0:1:5],9.8);
end
| 0debug
|
VSCODE - Disable highlighting and outlining in html tags and editor line : <p>These are some of the things I really find visually annoying in VSCODE, I was hoping someone could help me disable them.</p>
<p><strong>1.) Outlining <> in tags.</strong></p>
<p><a href="https://i.stack.imgur.com/gO4I6.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/gO4I6.jpg" alt="Check out the outlines in the tag."></a></p>
<p><em>I don't know about you, but I find this very annoying.</em></p>
<p><strong>2.) Outline in the active line</strong></p>
<p><a href="https://i.stack.imgur.com/A11a6.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/A11a6.jpg" alt="enter image description here"></a></p>
<p>I ran through all the workspace settings and set to false all that might - or at least - in any way related to highlighting and outlining but no luck.</p>
| 0debug
|
ram_addr_t last_ram_offset(void)
{
RAMBlock *block;
ram_addr_t last = 0;
QTAILQ_FOREACH(block, &ram_list.blocks, next)
last = MAX(last, block->offset + block->length);
return last;
}
| 1threat
|
PyTorch Binary Classification - same network structure, 'simpler' data, but worse performance? : <p>To get to grips with PyTorch (and deep learning in general) I started by working through some basic classification examples. One such example was classifying a non-linear dataset created using sklearn (full code available as notebook <a href="https://github.com/philipobrien/colab-notebooks/blob/master/Non_Linear_Data_Classification.ipynb" rel="noreferrer">here</a>)</p>
<pre><code>n_pts = 500
X, y = datasets.make_circles(n_samples=n_pts, random_state=123, noise=0.1, factor=0.2)
x_data = torch.FloatTensor(X)
y_data = torch.FloatTensor(y.reshape(500, 1))
</code></pre>
<p><a href="https://i.stack.imgur.com/w20Tb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/w20Tb.png" alt="enter image description here"></a></p>
<p>This is then accurately classified using a pretty basic neural net</p>
<pre><code>class Model(nn.Module):
def __init__(self, input_size, H1, output_size):
super().__init__()
self.linear = nn.Linear(input_size, H1)
self.linear2 = nn.Linear(H1, output_size)
def forward(self, x):
x = torch.sigmoid(self.linear(x))
x = torch.sigmoid(self.linear2(x))
return x
def predict(self, x):
pred = self.forward(x)
if pred >= 0.5:
return 1
else:
return 0
</code></pre>
<p>As I have an interest in health data I then decided to try and use the same network structure to classify some a basic real-world dataset. I took heart rate data for one patient from <a href="https://physionet.org/physiobank/database/bidmc/" rel="noreferrer">here</a>, and altered it so all values > 91 would be labelled as anomalies (e.g. a <code>1</code> and everything <= 91 labelled a <code>0</code>). This is completely arbitrary, but I just wanted to see how the classification would work. The complete notebook for this example is <a href="https://github.com/philipobrien/colab-notebooks/blob/master/Basic_Heart_rate_Classification.ipynb" rel="noreferrer">here</a>.</p>
<p><a href="https://i.stack.imgur.com/6izzI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6izzI.png" alt="enter image description here"></a></p>
<p>What is not intuitive to me is why the first example reaches <strong>a loss of 0.0016 after 1,000 epochs</strong>, whereas the second example only reaches <strong>a loss of 0.4296 after 10,000 epochs</strong></p>
<p><a href="https://i.stack.imgur.com/rDag4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rDag4.png" alt="Training Loss for Example 1"></a></p>
<p><a href="https://i.stack.imgur.com/PMubT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PMubT.png" alt="Training Loss for Heart Rate Example"></a></p>
<p>Perhaps I am being naive in thinking that the heart rate example would be much easier to classify. Any insights to help me understand why this is not what I am seeing would be great!</p>
| 0debug
|
ASP.NET Core - Add role claim to User : <p>I've an ASP.NET Core (based on .NET Framework) using Windows Authentication. Point is, I need to add a role claim on that user and this role is stored in a distant database.</p>
<p>I've read so much thing about OWIN/Cookie/UserManager/UserStore/Identity and so on that I'm lost.</p>
<p>Question : How do I add a role claim for current user logged in (windows) for the whole application in the easiest way?</p>
<p>What I need is to easily use <code>[Authorize(Role= "MyAddedRole")]</code> or <code>bool res = User.IsInRole("MyAddedRole")</code></p>
<p>Thanks</p>
| 0debug
|
Trying to write a code in Python-where am I going wrong? : The question i attempted to answer is as follows: Write a Python function that computes the number of days, hours, and minutes in a given number of minutes
ie: def daysHoursMinutes(m): which ends as return (d, h, M)
I wrote the following code:
def daysHoursMinutes(m):
import math
d=m/1440 #integer
h=m/60 #integer
M=m #integer
return(d,h,M)
and when I input in daysHoursMinutes(241) what im expecting to get is (0,4,1), but I get ((0.1673611111111111, 4.016666666666667, 241)Im confused as to what I'm doing wrong??
| 0debug
|
C++ setprecision : <p>newbie learning C++ and not understanding the problem I have trying to use setprecision(2) says setprecision(2) is undefined. If anyone could help I'd be most grateful.</p>
<pre><code> #include <iostream>
#include <string>
using namespace std;
int main()
{
double price,shipping;
cout<<"Enter total price of of the order: "<<endl;
cin>>price;
if(price > 75)
shipping = 0;
else if(price > 50)
shipping = 5;
else if(price > 25)
shipping = 10;
else if(price > 0)
shipping = 15;
cout<<"Total price of order including shipping is: "<<fixed<<setprecision(2)
<<price + shipping<<endl;
return 0;
system("pause");
}
</code></pre>
| 0debug
|
How is C# string interpolation compiled? : <p>I know that interpolation is syntactic sugar for <code>string.Format()</code>, but does it have any special behavior/recognition of when it is being used with a string formatting method?</p>
<p>If I have a method:</p>
<pre><code>void Print(string format, params object[] parameters)
</code></pre>
<p>And the following call to it using interpolation:</p>
<pre><code>Print($"{foo} {bar}");
</code></pre>
<p>Which of the following calls lines is most equivalent to the compiled result of string interpolation?</p>
<pre><code>Print(string.Format("{0} {1}", new[] { foo, bar }));
Print("{0} {1}", new[] { foo, bar });
</code></pre>
<p>Reasoning behind the question: Logging frameworks such as NLog typically defer string formatting until they have determined that a log message will actually be written. In general I prefer the string interpolation syntax, but I need to know if it may incur an extra performance penalty.</p>
| 0debug
|
WatchOS app cannot start with error Domain: "IDELaunchErrorDomain Code: 15" on Xcode 11 beta : <p>Want to run app under watchOS getting error under Xcode beta:
Domain: IDELaunchErrorDomain Code: 15 Failure Reason: Build and Run launch failed as the app to run does not appear to be known by the system.</p>
| 0debug
|
How to get parent of clicked element in Vue.js : <p>How to get parent of clicked (this) element in Vue.js?
In jQuery this looks like:</p>
<pre><code>$(this).parents(':eq(2)').next('.press__news__nav--view').show();
</code></pre>
<p>Thanks!</p>
| 0debug
|
why the array is static : <p>i have watched tutorial that explain how to return array from function</p>
<p>and this is similar code</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *grn();
int main()
{
int *a;
a=grn();
for(int i = 0;i<10;i++){
printf("%d\n",a[i]);
}
return 0;
}
int *grn(){
static int arrayy[10];
srand((unsigned) time(NULL));
for(int i=0;i<10;i++){
arrayy[i]=rand();
}
return arrayy;
}
</code></pre>
<p>and i have some questions about it..
it is work fine and generate random values inside the array but </p>
<ul>
<li><p>why the function <code>grn</code> is pointer</p></li>
<li><p>and why <code>a variable</code> in the <code>main function</code> is pointer ?</p></li>
<li>why the <code>arrayy array</code> is static?</li>
<li>and why should i make the grn function pointer?</li>
</ul>
<p>when i try to run this code but the arrayy variable is not static i get <code>segmentation fault</code></p>
| 0debug
|
Convert date string swift : <p>I have a date string in this format:</p>
<pre><code>2016-06-20T13:01:46.457+02:00
</code></pre>
<p>and I need to change it to something like this:</p>
<pre><code>20/06/2016
</code></pre>
<p>Previously I have always used this library -> <a href="https://github.com/malcommac/SwiftDate/blob/master/Documentation/UserGuide.md" rel="noreferrer">SwiftDate</a> to manipulate the dates, but it doesn't work now.</p>
<p>I tried also something like:</p>
<pre><code>let myDate = self.dateNoteDict[indexPath.row]!
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"
let date = dateFormatter.dateFromString(myDate)
print("date -> \(date)")
</code></pre>
<p>but it doesn't work. How can I do?</p>
<p>Thanks in advance.</p>
| 0debug
|
Zoom to specified markers react-native-maps : <p>There is a section in the <a href="https://github.com/airbnb/react-native-maps#zoom-to-specified-markers" rel="noreferrer">react-native-maps</a> docs for zooming to an array of markers, however there are no code examples on how to do this either in the docs or in the examples folder (from what I can find)</p>
<p>Can anyone provide an example of how to do this?</p>
| 0debug
|
How to loop through each month of current year and get first and last date of each month : <p>I wanna loop through all the months of a given year or current year and get first and last date of each month.
For example. Current year is 2017 and month October. So i wanna loop from October, 2017 to Decemeber, 2017 and fetch first and last date of each month like october first date is 2017-10-01 and last date will be 2017-10-31.</p>
| 0debug
|
Exporting an imported interface in TypeScript : <p>I have a number of templates in different directories - I define an interface for each so I can be sure that what I am referencing in my TypeScript code will be available in the template.</p>
<p>I would like to define an interface for each of them and then collate all of the interfaces in a single file that can be imported (so I can always just import that file and auto complete will show what interfaces are available).</p>
<p>However, I'm having trouble doing this. What I currently have:</p>
<p><code>login/interface</code>:</p>
<pre><code>export interface Index {
error: string;
value: string;
}
</code></pre>
<p><code>interfaces.ts</code>:</p>
<pre><code>import * as login from './login/interface';
export let View = {
Login: login
};
</code></pre>
<p><code>login.ts</code>:</p>
<pre><code>import * as I from './interface';
...
let viewOutput: I.View.Login.Index = {
...
};
</code></pre>
<p>Results in:</p>
<blockquote>
<p>error TS2694: Namespace '"...interface"' has no exported member 'View'.</p>
</blockquote>
<p>However, if I try to access <code>I.View.Login.Index</code> as a simple variable then I get:</p>
<blockquote>
<p>Property 'Index' does not exist on type 'typeof "...interface"'.</p>
</blockquote>
<p>Which seems correct since the interface is not really a type, but it has been able to access <code>I.View.Login</code> to get that far.</p>
<p>I don't understand what I'm doing wrong or missing here I'm afraid. Any help would be greatly appreciated!</p>
| 0debug
|
implicit conversion of 'nsinteger' (aka 'long') to 'nsstring *' is disallowed with arc : -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"mnuSelected"])
{
ViewController *v = segue.destinationViewController;
if(self.searchDisplayController.active) {
NSIndexPath *indexPath = nil;
indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
v.str = [self.result objectAtIndex:indexPath.row];
NSIndexPath *rowSelected = nil;
rowSelected = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
v.UserSelected = rowSelected.row;
}
else {
NSIndexPath *indexPath = nil;
indexPath = [self.tableView indexPathForSelectedRow];
v.str = [self.monthName objectAtIndex:indexPath.row];
NSIndexPath *rowSelected = nil;
rowSelected = [self.tableView indexPathForSelectedRow];
v.UserSelected = rowSelected.row;
}
return; }
}
I have error in this line >> v.UserSelected = rowSelected.row;
this error >> implicit conversion of 'nsinteger' (aka 'long') to 'nsstring *' is disallowed with arc
| 0debug
|
static void bdrv_stats_iter(QObject *data, void *opaque)
{
QDict *qdict;
Monitor *mon = opaque;
qdict = qobject_to_qdict(data);
monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
monitor_printf(mon, " rd_bytes=%" PRId64
" wr_bytes=%" PRId64
" rd_operations=%" PRId64
" wr_operations=%" PRId64
" flush_operations=%" PRId64
"\n",
qdict_get_int(qdict, "rd_bytes"),
qdict_get_int(qdict, "wr_bytes"),
qdict_get_int(qdict, "rd_operations"),
qdict_get_int(qdict, "wr_operations"),
qdict_get_int(qdict, "flush_operations"));
}
| 1threat
|
How can my code create a code and call it then, in C? : <p>I am beginner in programming and in C. I want to create a "machine-learning" rubik's cube solver. In first place, the solution of cube, will be accomplished, by random cube's rotaions. I want to save somehow these steps, of the first way to solution.
How could I create a part of code, outside the main code, that includes the commands of the first solution, so I can call it,in the second time, I ll run the program? Is that even possible?</p>
| 0debug
|
static int xiph_parse_sdp_line(AVFormatContext *s, int st_index,
PayloadContext *data, const char *line)
{
const char *p;
char *value;
char attr[25];
int value_size = strlen(line), attr_size = sizeof(attr), res = 0;
AVCodecContext* codec = s->streams[st_index]->codec;
assert(codec->id == CODEC_ID_THEORA);
assert(data);
if (!(value = av_malloc(value_size))) {
av_log(codec, AV_LOG_ERROR, "Out of memory\n");
return AVERROR(ENOMEM);
}
if (av_strstart(line, "fmtp:", &p)) {
while (*p && *p == ' ') p++;
while (*p && *p != ' ') p++;
while (*p && *p == ' ') p++;
while (ff_rtsp_next_attr_and_value(&p,
attr, attr_size,
value, value_size)) {
res = xiph_parse_fmtp_pair(codec, data, attr, value);
if (res < 0 && res != AVERROR_PATCHWELCOME)
return res;
}
}
av_free(value);
return 0;
}
| 1threat
|
MENU BUTTON POSITION WHEN NOT ACTIVE but at media screen size 600px : MENU BUTTON POSITION WHEN NOT ACTIVE but at media screen size 600px
i have screen shots with what i need it to do, Im not worried about the look of the menu i can do that but been having trouble with menu button not where i want it after media screen resize.
I put screen shots of what im trying to do
I want the menu button in the position it is after clicking it. but when it hasn’t been yet.
screenshots:
https://i.imgur.com/temJiTu.png
https://i.imgur.com/LYAY1nN.png
CODE SOURCE/CODE PEN:
[https://codepen.io/techatyou/pen/JZyqQa/][1]
Thank you in advance, anyone that can help I appreciated
[1]: https://codepen.io/techatyou/pen/JZyqQa/
| 0debug
|
order wise match with batch and qty : I have a problem with excel sheet. i am sharing you my excel problem.
Col-A Col-B Col-C
Order.No Batch Qty
123451 211 5
123451 212 30
123451 213 50
123461 311 40
123471 411 50
123471 511 80
123481 611 20
123491 612 30
in col-A 123451 is repeating 3 time and 123471 2 time. i would like to max value from Col-3 and show batch No in front of it but only match 123451 order no.
like
Order.No Batch Qty
123451 213 50
123461 311 40
123471 411 80
123481 611 20
123491 612 30
as per this result you can see that Order.No-123451 find max value Qty and paste value batch-No as per maximum value criteria. remove duplicate Order No. the data can more then this. this is just example.
Thanks.
Please share this my Email:
majid_mug@yahoo.com
| 0debug
|
static inline void RENAME(yuy2ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, int width, uint32_t *unused)
{
#if COMPILE_TEMPLATE_MMX
__asm__ volatile(
"movq "MANGLE(bm01010101)", %%mm4 \n\t"
"mov %0, %%"REG_a" \n\t"
"1: \n\t"
"movq (%1, %%"REG_a",4), %%mm0 \n\t"
"movq 8(%1, %%"REG_a",4), %%mm1 \n\t"
"psrlw $8, %%mm0 \n\t"
"psrlw $8, %%mm1 \n\t"
"packuswb %%mm1, %%mm0 \n\t"
"movq %%mm0, %%mm1 \n\t"
"psrlw $8, %%mm0 \n\t"
"pand %%mm4, %%mm1 \n\t"
"packuswb %%mm0, %%mm0 \n\t"
"packuswb %%mm1, %%mm1 \n\t"
"movd %%mm0, (%3, %%"REG_a") \n\t"
"movd %%mm1, (%2, %%"REG_a") \n\t"
"add $4, %%"REG_a" \n\t"
" js 1b \n\t"
: : "g" ((x86_reg)-width), "r" (src1+width*4), "r" (dstU+width), "r" (dstV+width)
: "%"REG_a
);
#else
int i;
for (i=0; i<width; i++) {
dstU[i]= src1[4*i + 1];
dstV[i]= src1[4*i + 3];
}
#endif
assert(src1 == src2);
}
| 1threat
|
react-native style opacity for parent and child : <p>react-native : I have one View and the child of View is an Image , I applied opacity: 0.5 for View and opacity: 0.9 for an Image but it doesn't apply for Image ,the parent opacity is applying for child , the child doesn't take independent opacity </p>
| 0debug
|
static int mov_write_tfhd_tag(AVIOContext *pb, MOVTrack *track,
int64_t moof_offset)
{
int64_t pos = avio_tell(pb);
uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
MOV_TFHD_BASE_DATA_OFFSET;
if (!track->entry) {
flags |= MOV_TFHD_DURATION_IS_EMPTY;
} else {
flags |= MOV_TFHD_DEFAULT_FLAGS;
}
if (track->mode == MODE_ISM)
flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "tfhd");
avio_w8(pb, 0);
avio_wb24(pb, flags);
avio_wb32(pb, track->track_id);
if (flags & MOV_TFHD_BASE_DATA_OFFSET)
avio_wb64(pb, moof_offset);
if (flags & MOV_TFHD_DEFAULT_DURATION) {
track->default_duration = get_cluster_duration(track, 0);
avio_wb32(pb, track->default_duration);
}
if (flags & MOV_TFHD_DEFAULT_SIZE) {
track->default_size = track->entry ? track->cluster[0].size : 1;
avio_wb32(pb, track->default_size);
} else
track->default_size = -1;
if (flags & MOV_TFHD_DEFAULT_FLAGS) {
track->default_sample_flags =
track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
(MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
avio_wb32(pb, track->default_sample_flags);
}
return update_size(pb, pos);
}
| 1threat
|
How can I convert a a Json into a list using REST.Json in Delphi? : I have a json file like this **[{"id":1,"name":"JOHN"},{"id":2,"name":"PETER"}]** and I want to store this list into a ClientDataSet or something like that. I'm using Delphi Tokyo and REST.Json unit.
| 0debug
|
static uint32_t m5206_mbar_readl(void *opaque, target_phys_addr_t offset)
{
m5206_mbar_state *s = (m5206_mbar_state *)opaque;
int width;
offset &= 0x3ff;
if (offset > 0x200) {
hw_error("Bad MBAR read offset 0x%x", (int)offset);
}
width = m5206_mbar_width[offset >> 2];
if (width < 4) {
uint32_t val;
val = m5206_mbar_readw(opaque, offset) << 16;
val |= m5206_mbar_readw(opaque, offset + 2);
return val;
}
return m5206_mbar_read(s, offset, 4);
}
| 1threat
|
static int count_contiguous_free_clusters(int nb_clusters, uint64_t *l2_table)
{
int i;
for (i = 0; i < nb_clusters; i++) {
int type = qcow2_get_cluster_type(be64_to_cpu(l2_table[i]));
if (type != QCOW2_CLUSTER_UNALLOCATED) {
break;
}
}
return i;
}
| 1threat
|
Angular2 doesn't work Custom Reuse Strategy with Lazy module loading : <p>I tried to use <a href="https://www.softwarearchitekt.at/post/2016/12/02/sticky-routes-in-angular-2-3-with-routereusestrategy.aspx" rel="noreferrer"><strong>custom reuse strategy</strong></a> in my angular2 project,
but I found it doesn't work with <strong>lazy module loading</strong>.
Anyone who know about this? My project is angular 2.6.4</p>
<p>reuse-strategy.ts</p>
<pre><code>import {RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle} from "@angular/router";
export class CustomReuseStrategy implements RouteReuseStrategy {
handlers: {[key: string]: DetachedRouteHandle} = {};
shouldDetach(route: ActivatedRouteSnapshot): boolean {
console.debug('CustomReuseStrategy:shouldDetach', route);
return true;
}
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
console.debug('CustomReuseStrategy:store', route, handle);
this.handlers[route.routeConfig.path] = handle;
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
console.debug('CustomReuseStrategy:shouldAttach', route);
return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
console.debug('CustomReuseStrategy:retrieve', route);
if (!route.routeConfig) return null;
return this.handlers[route.routeConfig.path];
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
console.debug('CustomReuseStrategy:shouldReuseRoute', future, curr);
return future.routeConfig === curr.routeConfig;
}
}
</code></pre>
<p>app.module.ts</p>
<pre><code>const appRoutes: Routes = [
{ path: 'crisis-center', component: CrisisListComponent },
{ path: 'heroes', loadChildren: 'app/hero-list.module#HeroListModule' },
{ path: '', redirectTo: '/crisis-center', pathMatch: 'full' }
];
@NgModule({
imports: [ ... ],
declarations: [ ... ],
providers:[
{provide: RouteReuseStrategy, useClass: CustomReuseStrategy}
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
</code></pre>
<p>and I put <code><input></code> to both component and I tested it.</p>
<p>the value of input in <code>CrisisListComponent</code> is stored but, the value of <code>HeroListComponent lazy-loaded</code> is not preserved.</p>
<p>I don't know it's not supported yet.
Thank you for helping me.</p>
| 0debug
|
PHP: Create SQL query for available $_POST variable : <p>I have this $_POST Variable:</p>
<pre><code>Array
(
[phone_1] => 3123213
[phone_2] => 432423
[phone_3] => 4234
[phone_4] => 6456456
[phone_5] => 7567576
[phone_6] =>
)
</code></pre>
<p>Now I have this SQL statement:</p>
<pre><code>UPDATE table_name SET phone_1 = $_POST['phone1'],
phone_2 = $_POST['phone2'],
phone_3 = $_POST['phone3'],
phone_4 = $_POST['phone4'],
phone_5 = $_POST['phone5'],
phone_6 = $_POST['phone6']
WHERE id=$id
</code></pre>
<p>What I want to achieve is to dynamically build the SQL query based from the $_POST variable and only include those that have a post value. So the SQL statement should be:</p>
<pre><code>UPDATE table_name SET phone_1 = $_POST['phone1'],
phone_2 = $_POST['phone2'],
phone_3 = $_POST['phone3'],
phone_4 = $_POST['phone4'],
phone_5 = $_POST['phone5']
</code></pre>
<p>because phone_6 post variable is blank. And yes the $_POST key names is the same as the table field names. TIA!</p>
| 0debug
|
SSL handshake error on self-signed cert in Flutter : <p>I'm trying to connect server with self-signed cert, but I take error:<br>
E/flutter ( 3781): HandshakeException: Handshake error in client (OS Error:
<br>E/flutter ( 3781): CERTIFICATE_VERIFY_FAILED: Hostname mismatch(ssl_cert.c:345))<br>
Code, where I set cert:</p>
<pre><code>String path = '/storage/sdcard0/server.crt';
SecurityContext context = new SecurityContext();
context.setTrustedCertificates(path, password: 'hello');
_client = new HttpClient(context: context);
</code></pre>
<p>What I'm doing wrong?</p>
<p>If I don't set SecurityContext, I get SSL handshake error.</p>
| 0debug
|
How do I make a flowchart using markdown on my github blog : <p>I recently put some posts on my github jekyll blog.Everything is fine,except my flowchart.I used to make flowchart like this:</p>
<pre><code>```flow
my content
```
</code></pre>
<p>but when I preview the post,It can't display as a flowchart.
This is Ok in some other markdown editor.If I want to make flowchart on my github blog,what can I do?Thanks.</p>
| 0debug
|
Can someone explain C# static variables usage to me, when accessing from another script? : <p>Keep in mind I'm new to C#. Static variables don't seem to serve the same purpose as in C/C++, Fortran, etc. so I'm struggling a bit, esp. with this:</p>
<p>I want to be able to attach game objects to variables using the inspector, but access those variables (say, the color of Text UIs) from another script, without hard-coding object names (which could change) and using Find/GetComponent. </p>
<p>If I make the game objects static, I can access them instead with a statement like classname.objectname. However, the inspector no longer sees those variables (since they're static?), and so I can no longer attach a game object to them using inspector, so I'm back to using GameObject.Find or GetComponent and hard-coding the names somewhere in my code. Hopefully, I'm just ignorant about something, hence my question.</p>
<p>So: how can I declare a variable to which I can attach an object in the inspector (and avoid hard-coding the object name), yet access it in a different script without using Find/GetComponent?</p>
| 0debug
|
static int vhdx_parse_metadata(BlockDriverState *bs, BDRVVHDXState *s)
{
int ret = 0;
uint8_t *buffer;
int offset = 0;
uint32_t i = 0;
VHDXMetadataTableEntry md_entry;
buffer = qemu_blockalign(bs, VHDX_METADATA_TABLE_MAX_SIZE);
ret = bdrv_pread(bs->file, s->metadata_rt.file_offset, buffer,
VHDX_METADATA_TABLE_MAX_SIZE);
if (ret < 0) {
goto exit;
}
memcpy(&s->metadata_hdr, buffer, sizeof(s->metadata_hdr));
offset += sizeof(s->metadata_hdr);
vhdx_metadata_header_le_import(&s->metadata_hdr);
if (memcmp(&s->metadata_hdr.signature, "metadata", 8)) {
ret = -EINVAL;
goto exit;
}
s->metadata_entries.present = 0;
if ((s->metadata_hdr.entry_count * sizeof(md_entry)) >
(VHDX_METADATA_TABLE_MAX_SIZE - offset)) {
ret = -EINVAL;
goto exit;
}
for (i = 0; i < s->metadata_hdr.entry_count; i++) {
memcpy(&md_entry, buffer + offset, sizeof(md_entry));
offset += sizeof(md_entry);
vhdx_metadata_entry_le_import(&md_entry);
if (guid_eq(md_entry.item_id, file_param_guid)) {
if (s->metadata_entries.present & META_FILE_PARAMETER_PRESENT) {
ret = -EINVAL;
goto exit;
}
s->metadata_entries.file_parameters_entry = md_entry;
s->metadata_entries.present |= META_FILE_PARAMETER_PRESENT;
continue;
}
if (guid_eq(md_entry.item_id, virtual_size_guid)) {
if (s->metadata_entries.present & META_VIRTUAL_DISK_SIZE_PRESENT) {
ret = -EINVAL;
goto exit;
}
s->metadata_entries.virtual_disk_size_entry = md_entry;
s->metadata_entries.present |= META_VIRTUAL_DISK_SIZE_PRESENT;
continue;
}
if (guid_eq(md_entry.item_id, page83_guid)) {
if (s->metadata_entries.present & META_PAGE_83_PRESENT) {
ret = -EINVAL;
goto exit;
}
s->metadata_entries.page83_data_entry = md_entry;
s->metadata_entries.present |= META_PAGE_83_PRESENT;
continue;
}
if (guid_eq(md_entry.item_id, logical_sector_guid)) {
if (s->metadata_entries.present &
META_LOGICAL_SECTOR_SIZE_PRESENT) {
ret = -EINVAL;
goto exit;
}
s->metadata_entries.logical_sector_size_entry = md_entry;
s->metadata_entries.present |= META_LOGICAL_SECTOR_SIZE_PRESENT;
continue;
}
if (guid_eq(md_entry.item_id, phys_sector_guid)) {
if (s->metadata_entries.present & META_PHYS_SECTOR_SIZE_PRESENT) {
ret = -EINVAL;
goto exit;
}
s->metadata_entries.phys_sector_size_entry = md_entry;
s->metadata_entries.present |= META_PHYS_SECTOR_SIZE_PRESENT;
continue;
}
if (guid_eq(md_entry.item_id, parent_locator_guid)) {
if (s->metadata_entries.present & META_PARENT_LOCATOR_PRESENT) {
ret = -EINVAL;
goto exit;
}
s->metadata_entries.parent_locator_entry = md_entry;
s->metadata_entries.present |= META_PARENT_LOCATOR_PRESENT;
continue;
}
if (md_entry.data_bits & VHDX_META_FLAGS_IS_REQUIRED) {
ret = -ENOTSUP;
goto exit;
}
}
if (s->metadata_entries.present != META_ALL_PRESENT) {
ret = -ENOTSUP;
goto exit;
}
ret = bdrv_pread(bs->file,
s->metadata_entries.file_parameters_entry.offset
+ s->metadata_rt.file_offset,
&s->params,
sizeof(s->params));
if (ret < 0) {
goto exit;
}
le32_to_cpus(&s->params.block_size);
le32_to_cpus(&s->params.data_bits);
if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
if (s->metadata_entries.present & META_PARENT_LOCATOR_PRESENT) {
ret = -ENOTSUP;
goto exit;
} else {
ret = -EINVAL;
goto exit;
}
}
ret = bdrv_pread(bs->file,
s->metadata_entries.virtual_disk_size_entry.offset
+ s->metadata_rt.file_offset,
&s->virtual_disk_size,
sizeof(uint64_t));
if (ret < 0) {
goto exit;
}
ret = bdrv_pread(bs->file,
s->metadata_entries.logical_sector_size_entry.offset
+ s->metadata_rt.file_offset,
&s->logical_sector_size,
sizeof(uint32_t));
if (ret < 0) {
goto exit;
}
ret = bdrv_pread(bs->file,
s->metadata_entries.phys_sector_size_entry.offset
+ s->metadata_rt.file_offset,
&s->physical_sector_size,
sizeof(uint32_t));
if (ret < 0) {
goto exit;
}
le64_to_cpus(&s->virtual_disk_size);
le32_to_cpus(&s->logical_sector_size);
le32_to_cpus(&s->physical_sector_size);
if (s->logical_sector_size == 0 || s->params.block_size == 0) {
ret = -EINVAL;
goto exit;
}
s->sectors_per_block = s->params.block_size / s->logical_sector_size;
s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) *
(uint64_t)s->logical_sector_size /
(uint64_t)s->params.block_size;
if (s->logical_sector_size & (s->logical_sector_size - 1)) {
ret = -EINVAL;
goto exit;
}
if (s->sectors_per_block & (s->sectors_per_block - 1)) {
ret = -EINVAL;
goto exit;
}
if (s->chunk_ratio & (s->chunk_ratio - 1)) {
ret = -EINVAL;
goto exit;
}
s->block_size = s->params.block_size;
if (s->block_size & (s->block_size - 1)) {
ret = -EINVAL;
goto exit;
}
vhdx_set_shift_bits(s);
ret = 0;
exit:
qemu_vfree(buffer);
return ret;
}
| 1threat
|
How do I make my Discord bot join specific servers? The bot requires a paid subscription and I don't want the invite link to be leaked : <p>I want my Discord bot to only be added to servers where the owner has paid for a subscription. When I give them the bot invite link, I don't want the link to be leaked so how would I fix this problem?</p>
| 0debug
|
static void m68020_cpu_initfn(Object *obj)
{
M68kCPU *cpu = M68K_CPU(obj);
CPUM68KState *env = &cpu->env;
m68k_set_feature(env, M68K_FEATURE_M68000);
m68k_set_feature(env, M68K_FEATURE_USP);
m68k_set_feature(env, M68K_FEATURE_WORD_INDEX);
m68k_set_feature(env, M68K_FEATURE_QUAD_MULDIV);
m68k_set_feature(env, M68K_FEATURE_BRAL);
m68k_set_feature(env, M68K_FEATURE_BCCL);
m68k_set_feature(env, M68K_FEATURE_BITFIELD);
m68k_set_feature(env, M68K_FEATURE_EXT_FULL);
m68k_set_feature(env, M68K_FEATURE_SCALED_INDEX);
m68k_set_feature(env, M68K_FEATURE_LONG_MULDIV);
m68k_set_feature(env, M68K_FEATURE_FPU);
m68k_set_feature(env, M68K_FEATURE_CAS);
m68k_set_feature(env, M68K_FEATURE_BKPT);
m68k_set_feature(env, M68K_FEATURE_RTD);
}
| 1threat
|
partial submission on hacker rank : <p>why is my code <a href="http://ideone.com/zm6hP7" rel="nofollow">http://ideone.com/zm6hP7</a> not satisfying all test cases in the problem <a href="https://www.hackerrank.com/contests/opc-a/challenges/infinite-series" rel="nofollow">https://www.hackerrank.com/contests/opc-a/challenges/infinite-series</a> ?
I have downloaded unsatisfied test cases and still can't find any problem in my code....can somebody tell me what the problem is???</p>
<pre><code>#include<stdio.h>`
#define m 1000000007
int main()
{
long long int t;
scanf("%lld",&t);
for(long long int i=0;i<t;i++)
{
long long int l,r;
scanf("%lld %lld",&l,&r);
long long int x,y;
if(l%2==0)
x=(((l/2)%m)*((l-1)%m))%m;
else
x=((l%m)*(((l-1)/2)%m))%m;
if(r%2==0)
y=(((r/2)%m)*((r+1)%m))%m;
else
y=((r%m)*(((r+1)/2)%m))%m;
printf("%lld\n",y-x);
}
return 0;
}
</code></pre>
| 0debug
|
How to get ajax result in php I am using below code : when result exist its not going to if condition it will go to else.please any one help me.in query result $num>0 i want alert like.receipt number already exist
$.post("acceptajax.php?confirm1="+confirm+'&receipt='+receipt+'&amount='+amount,function(result,status){
//$('#divsub'+confirm).html(data);
if(result == 'exist'){
alert('Receipt number Alerady Exit');
}
else {
$('#accept_'+confirm).hide();
$('#unaccept_' +confirm).show();
}
});
acceptajax.php
$img_id=$_GET['confirm1'];
$receipt=$_GET['receipt'];
$receipt='HYD'.$receipt;
$amount=$_GET['amount'];
$sql=mysql_query("SELECT receipt FROM user WHERE receipt=$receipt");
$num=mysql_num_rows($sql);
if($num==0){
echo "suc";
}
else {
echo "exist";
}
| 0debug
|
void commit_start(BlockDriverState *bs, BlockDriverState *base,
BlockDriverState *top, int64_t speed,
BlockdevOnError on_error, BlockDriverCompletionFunc *cb,
void *opaque, Error **errp)
{
CommitBlockJob *s;
BlockReopenQueue *reopen_queue = NULL;
int orig_overlay_flags;
int orig_base_flags;
BlockDriverState *overlay_bs;
Error *local_err = NULL;
if ((on_error == BLOCKDEV_ON_ERROR_STOP ||
on_error == BLOCKDEV_ON_ERROR_ENOSPC) &&
!bdrv_iostatus_is_enabled(bs)) {
error_set(errp, QERR_INVALID_PARAMETER_COMBINATION);
return;
}
if (top == bs) {
error_setg(errp,
"Top image as the active layer is currently unsupported");
return;
}
if (top == base) {
error_setg(errp, "Invalid files for merge: top and base are the same");
return;
}
if (bdrv_find_backing_image(top, base->filename) != base) {
error_setg(errp,
"Base (%s) is not reachable from top (%s)",
base->filename, top->filename);
return;
}
overlay_bs = bdrv_find_overlay(bs, top);
if (overlay_bs == NULL) {
error_setg(errp, "Could not find overlay image for %s:", top->filename);
return;
}
orig_base_flags = bdrv_get_flags(base);
orig_overlay_flags = bdrv_get_flags(overlay_bs);
if (!(orig_base_flags & BDRV_O_RDWR)) {
reopen_queue = bdrv_reopen_queue(reopen_queue, base,
orig_base_flags | BDRV_O_RDWR);
}
if (!(orig_overlay_flags & BDRV_O_RDWR)) {
reopen_queue = bdrv_reopen_queue(reopen_queue, overlay_bs,
orig_overlay_flags | BDRV_O_RDWR);
}
if (reopen_queue) {
bdrv_reopen_multiple(reopen_queue, &local_err);
if (local_err != NULL) {
error_propagate(errp, local_err);
return;
}
}
s = block_job_create(&commit_job_type, bs, speed, cb, opaque, errp);
if (!s) {
return;
}
s->base = base;
s->top = top;
s->active = bs;
s->base_flags = orig_base_flags;
s->orig_overlay_flags = orig_overlay_flags;
s->on_error = on_error;
s->common.co = qemu_coroutine_create(commit_run);
trace_commit_start(bs, base, top, s, s->common.co, opaque);
qemu_coroutine_enter(s->common.co, s);
}
| 1threat
|
static uint32_t tpm_tis_data_read(TPMState *s, uint8_t locty)
{
TPMTISEmuState *tis = &s->s.tis;
uint32_t ret = TPM_TIS_NO_DATA_BYTE;
uint16_t len;
if ((tis->loc[locty].sts & TPM_TIS_STS_DATA_AVAILABLE)) {
len = tpm_tis_get_size_from_buffer(&tis->loc[locty].r_buffer);
ret = tis->loc[locty].r_buffer.buffer[tis->loc[locty].r_offset++];
if (tis->loc[locty].r_offset >= len) {
tis->loc[locty].sts = TPM_TIS_STS_VALID;
#ifdef RAISE_STS_IRQ
tpm_tis_raise_irq(s, locty, TPM_TIS_INT_STS_VALID);
#endif
}
DPRINTF("tpm_tis: tpm_tis_data_read byte 0x%02x [%d]\n",
ret, tis->loc[locty].r_offset-1);
}
return ret;
}
| 1threat
|
Best practice for handling error in Angular2 : <p>Hi i am trying to receive error sent from catch block (service).
in multiple components i need to show a popup with the error message displayed.
please let me know how to create a generic method and call it inside service block. Like what i am doing now with "showErrorPage()".</p>
<pre><code>import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'
@Injectable()
export class DataService {
private reqData = {};
private url: string;
constructor(private http: Http) {
}
getResult(searchObject: {}): Observable<Response> {
// some logic
return this.http.post(<my url>, <data to be sent>)
.map((response: Response) => {
return response;
})
.catch((error: any) => {
if (error.status === 302 || error.status === "302" ) {
// do some thing
}
else {
return Observable.throw(new Error(error.status));
}
});
}
}
</code></pre>
<p>And in my component i am calling it like</p>
<pre><code>import { Component,EventEmitter, Output, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
// importing DataService ';
@Component({
selector: 'o-result',
templateUrl: './o-result.component.html',
})
export class AComp implements OnInit {
constructor(
private dataService: DataService
){
}
ngOnInit() {
this.dataService.getResult(<url>, <params>)
.subscribe(
response => {
// doing logic with responce
}
,
error => {
this.showErrorPage();
}
)
}
showErrorPage(): void {
// displaying error in popup
}
}
</code></pre>
| 0debug
|
static inline void RENAME(hcscale_fast)(SwsContext *c, int16_t *dst1, int16_t *dst2,
int dstWidth, const uint8_t *src1,
const uint8_t *src2, int srcW, int xInc)
{
int32_t *filterPos = c->hChrFilterPos;
int16_t *filter = c->hChrFilter;
void *mmx2FilterCode= c->chrMmx2FilterCode;
int i;
#if defined(PIC)
DECLARE_ALIGNED(8, uint64_t, ebxsave);
#endif
__asm__ volatile(
#if defined(PIC)
"mov %%"REG_b", %7 \n\t"
#endif
"pxor %%mm7, %%mm7 \n\t"
"mov %0, %%"REG_c" \n\t"
"mov %1, %%"REG_D" \n\t"
"mov %2, %%"REG_d" \n\t"
"mov %3, %%"REG_b" \n\t"
"xor %%"REG_a", %%"REG_a" \n\t"
PREFETCH" (%%"REG_c") \n\t"
PREFETCH" 32(%%"REG_c") \n\t"
PREFETCH" 64(%%"REG_c") \n\t"
CALL_MMX2_FILTER_CODE
CALL_MMX2_FILTER_CODE
CALL_MMX2_FILTER_CODE
CALL_MMX2_FILTER_CODE
"xor %%"REG_a", %%"REG_a" \n\t"
"mov %5, %%"REG_c" \n\t"
"mov %6, %%"REG_D" \n\t"
PREFETCH" (%%"REG_c") \n\t"
PREFETCH" 32(%%"REG_c") \n\t"
PREFETCH" 64(%%"REG_c") \n\t"
CALL_MMX2_FILTER_CODE
CALL_MMX2_FILTER_CODE
CALL_MMX2_FILTER_CODE
CALL_MMX2_FILTER_CODE
#if defined(PIC)
"mov %7, %%"REG_b" \n\t"
#endif
:: "m" (src1), "m" (dst1), "m" (filter), "m" (filterPos),
"m" (mmx2FilterCode), "m" (src2), "m"(dst2)
#if defined(PIC)
,"m" (ebxsave)
#endif
: "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S, "%"REG_D
#if !defined(PIC)
,"%"REG_b
#endif
);
for (i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--) {
dst1[i] = src1[srcW-1]*128;
dst2[i] = src2[srcW-1]*128;
}
}
| 1threat
|
static int build_vlc(AVCodecContext *avctx, VLC *vlc, const uint32_t *table)
{
Node nodes[512];
uint32_t bits[256];
int16_t lens[256];
uint8_t xlat[256];
int cur_node, i, j, pos = 0;
ff_free_vlc(vlc);
for (i = 0; i < 256; i++) {
nodes[i].count = table[i];
nodes[i].sym = i;
nodes[i].n0 = -2;
nodes[i].l = i;
nodes[i].r = i;
}
cur_node = 256;
j = 0;
do {
for (i = 0; ; i++) {
int new_node = j;
int first_node = cur_node;
int second_node = cur_node;
int nd, st;
nodes[cur_node].count = -1;
do {
int val = nodes[new_node].count;
if (val && (val < nodes[first_node].count)) {
if (val >= nodes[second_node].count) {
first_node = new_node;
} else {
first_node = second_node;
second_node = new_node;
}
}
new_node += 1;
} while (new_node != cur_node);
if (first_node == cur_node)
break;
nd = nodes[second_node].count;
st = nodes[first_node].count;
nodes[second_node].count = 0;
nodes[first_node].count = 0;
nodes[cur_node].count = nd + st;
nodes[cur_node].sym = -1;
nodes[cur_node].n0 = cur_node;
nodes[cur_node].l = first_node;
nodes[cur_node].r = second_node;
cur_node++;
}
j++;
} while (cur_node - 256 == j);
get_tree_codes(bits, lens, xlat, nodes, cur_node - 1, 0, 0, &pos);
return ff_init_vlc_sparse(vlc, 10, pos, lens, 2, 2, bits, 4, 4, xlat, 1, 1, 0);
}
| 1threat
|
Do Ruby variables store value or address? : <p>Since in Ruby everything is an object, do Ruby variables store value or address of immediate types (read primitives)? In contrast to C that stores values in variables, if they are primitives.</p>
| 0debug
|
why is my MySQL ip different than physical server ip it is running : This may be hugely a dumb question, but i m no vice to mysql, and i just discovered that my sql has different ip i.e. *127.0.0.1* and its hostname(*localhost*) than the machine ip which is *192.168.1.3* and machine hostname is *ceres*, why is it so ?
I connected to MySQL running on different machine using MySQL workbench :
and it shows it logged me to mysql root user to 127.0.0.1 on *pi@192.168.1.3*
[![enter image description here][1]][1]
then
[![enter image description here][2]][2]
I wanted to insert data to db remotely using arduino MCU and i can definitely not write `127.0.0.1`
[1]: https://i.stack.imgur.com/vpFcj.png
[2]: https://i.stack.imgur.com/HKmdC.png
| 0debug
|
static gboolean serial_xmit(GIOChannel *chan, GIOCondition cond, void *opaque)
{
SerialState *s = opaque;
if (s->tsr_retry <= 0) {
if (s->fcr & UART_FCR_FE) {
s->tsr = fifo8_is_full(&s->xmit_fifo) ?
0 : fifo8_pop(&s->xmit_fifo);
if (!s->xmit_fifo.num) {
s->lsr |= UART_LSR_THRE;
}
} else if ((s->lsr & UART_LSR_THRE)) {
return FALSE;
} else {
s->tsr = s->thr;
s->lsr |= UART_LSR_THRE;
s->lsr &= ~UART_LSR_TEMT;
}
}
if (s->mcr & UART_MCR_LOOP) {
serial_receive1(s, &s->tsr, 1);
} else if (qemu_chr_fe_write(s->chr, &s->tsr, 1) != 1) {
if (s->tsr_retry >= 0 && s->tsr_retry < MAX_XMIT_RETRY &&
qemu_chr_fe_add_watch(s->chr, G_IO_OUT, serial_xmit, s) > 0) {
s->tsr_retry++;
return FALSE;
}
s->tsr_retry = 0;
} else {
s->tsr_retry = 0;
}
s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
if (s->lsr & UART_LSR_THRE) {
s->lsr |= UART_LSR_TEMT;
s->thr_ipending = 1;
serial_update_irq(s);
}
return FALSE;
}
| 1threat
|
static void qemu_rdma_signal_unregister(RDMAContext *rdma, uint64_t index,
uint64_t chunk, uint64_t wr_id)
{
if (rdma->unregistrations[rdma->unregister_next] != 0) {
fprintf(stderr, "rdma migration: queue is full!\n");
} else {
RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]);
if (!test_and_set_bit(chunk, block->unregister_bitmap)) {
DDPRINTF("Appending unregister chunk %" PRIu64
" at position %d\n", chunk, rdma->unregister_next);
rdma->unregistrations[rdma->unregister_next++] =
qemu_rdma_make_wrid(wr_id, index, chunk);
if (rdma->unregister_next == RDMA_SIGNALED_SEND_MAX) {
rdma->unregister_next = 0;
}
} else {
DDPRINTF("Unregister chunk %" PRIu64 " already in queue.\n",
chunk);
}
}
}
| 1threat
|
JAVA Date string without symbols : <p>I'm formatting <strong>Date</strong> to <strong>String</strong> without symbols <strong>:,/,-</strong> using <strong>SimpleDateFormat</strong>, but it formats it strangely.</p>
<p>Here's my code :</p>
<pre><code>public static String getFormatedDate(Date date, String format) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.format(date);
}
</code></pre>
<p>And I call it like this :</p>
<pre><code>DateUtil.getFormatedDate(new Date(), "DDMMYYYYHHMMSS")
</code></pre>
<p>Return of the call is incorrect <strong>2540920170909379</strong> it should look like this <strong>11092017093405</strong> = <strong>11/09/2017 09:34:05</strong></p>
| 0debug
|
How to add an object whose key is in a variable to an index in an array : <p>I have an array of objects and want to add a new object to it in a for loop. They key of the object is dynamic and inside a variable. How can I do this. My array:</p>
<pre><code>var myKey = "someStringThatIsDynamic";
var myArray[i].myKey = "myValue";
</code></pre>
| 0debug
|
Wordpress search strange behaviour : <p>Has anyone come across or have a fix for the following Wordpress search issue:</p>
<p>When you search '<strong><em>degrees</em></strong>', you get results.</p>
<p>If you search '<strong><em>degree</em></strong>', you get no results.</p>
<p>Very strange!</p>
<p>Live site demo here:
<a href="http://advice.milkround.com" rel="nofollow">http://advice.milkround.com</a></p>
| 0debug
|
static void pmac_ide_transfer_cb(void *opaque, int ret)
{
DBDMA_io *io = opaque;
MACIOIDEState *m = io->opaque;
IDEState *s = idebus_active_if(&m->bus);
int n = 0;
int64_t sector_num;
int unaligned;
if (ret < 0) {
MACIO_DPRINTF("DMA error\n");
m->aiocb = NULL;
qemu_sglist_destroy(&s->sg);
ide_dma_error(s);
io->remainder_len = 0;
goto done;
}
if (!m->dma_active) {
MACIO_DPRINTF("waiting for data (%#x - %#x - %x)\n",
s->nsector, io->len, s->status);
io->processing = false;
return;
}
sector_num = ide_get_sector(s);
MACIO_DPRINTF("io_buffer_size = %#x\n", s->io_buffer_size);
if (s->io_buffer_size > 0) {
m->aiocb = NULL;
qemu_sglist_destroy(&s->sg);
n = (s->io_buffer_size + 0x1ff) >> 9;
sector_num += n;
ide_set_sector(s, sector_num);
s->nsector -= n;
}
MACIO_DPRINTF("remainder: %d io->len: %d nsector: %d "
"sector_num: %" PRId64 "\n",
io->remainder_len, io->len, s->nsector, sector_num);
if (io->remainder_len && io->len) {
int remainder_len = MIN(io->remainder_len, io->len);
uint8_t *p = &io->remainder[0x200 - remainder_len];
MACIO_DPRINTF("copying remainder %d bytes at %#" HWADDR_PRIx "\n",
remainder_len, io->addr);
switch (s->dma_cmd) {
case IDE_DMA_READ:
cpu_physical_memory_write(io->addr, p, remainder_len);
break;
case IDE_DMA_WRITE:
cpu_physical_memory_read(io->addr, p, remainder_len);
bdrv_write(s->bs, sector_num - 1, io->remainder, 1);
break;
case IDE_DMA_TRIM:
break;
}
io->addr += remainder_len;
io->len -= remainder_len;
io->remainder_len -= remainder_len;
}
if (s->nsector == 0 && !io->remainder_len) {
MACIO_DPRINTF("end of transfer\n");
s->status = READY_STAT | SEEK_STAT;
ide_set_irq(s->bus);
m->dma_active = false;
}
if (io->len == 0) {
MACIO_DPRINTF("end of DMA\n");
goto done;
}
s->io_buffer_index = 0;
s->io_buffer_size = MIN(io->len, s->nsector * 512);
unaligned = io->len & 0x1ff;
if (unaligned) {
int nsector = io->len >> 9;
MACIO_DPRINTF("precopying unaligned %d bytes to %#" HWADDR_PRIx "\n",
unaligned, io->addr + io->len - unaligned);
switch (s->dma_cmd) {
case IDE_DMA_READ:
bdrv_read(s->bs, sector_num + nsector, io->remainder, 1);
cpu_physical_memory_write(io->addr + io->len - unaligned,
io->remainder, unaligned);
break;
case IDE_DMA_WRITE:
cpu_physical_memory_read(io->addr + io->len - unaligned,
io->remainder, unaligned);
break;
case IDE_DMA_TRIM:
break;
}
io->len -= unaligned;
}
MACIO_DPRINTF("io->len = %#x\n", io->len);
qemu_sglist_init(&s->sg, DEVICE(m), io->len / MACIO_PAGE_SIZE + 1,
&address_space_memory);
qemu_sglist_add(&s->sg, io->addr, io->len);
io->addr += io->len + unaligned;
io->remainder_len = (0x200 - unaligned) & 0x1ff;
MACIO_DPRINTF("set remainder to: %d\n", io->remainder_len);
if (!io->len) {
pmac_ide_transfer_cb(opaque, 0);
return;
}
io->len = 0;
MACIO_DPRINTF("sector_num=%" PRId64 " n=%d, nsector=%d, cmd_cmd=%d\n",
sector_num, n, s->nsector, s->dma_cmd);
switch (s->dma_cmd) {
case IDE_DMA_READ:
m->aiocb = dma_bdrv_read(s->bs, &s->sg, sector_num,
pmac_ide_transfer_cb, io);
break;
case IDE_DMA_WRITE:
m->aiocb = dma_bdrv_write(s->bs, &s->sg, sector_num,
pmac_ide_transfer_cb, io);
break;
case IDE_DMA_TRIM:
m->aiocb = dma_bdrv_io(s->bs, &s->sg, sector_num,
ide_issue_trim, pmac_ide_transfer_cb, io,
DMA_DIRECTION_TO_DEVICE);
break;
}
return;
done:
if (s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) {
bdrv_acct_done(s->bs, &s->acct);
}
io->dma_end(io);
}
| 1threat
|
AJAX returns undefined variable after called : <p>I´m developing a session system with Jquery, AJAX, PHP and JSON.</p>
<p>This is my generic AJAX function:</p>
<pre><code>function ajaxConn(incomingUrl,incomingData)
{
var returnValue;
$.ajax({
url:'backend/'+incomingUrl,
method:'POST',
data: JSON.stringify(incomingData),
contentType: "application/json; charset=UTF-8"
}).done(function(response){
returnValue = response.resp;
});
console.log(returnValue);
}
</code></pre>
<p>This is the call of the function and the storage of result to be used. variable data has inputs values previously filtered and validated.</p>
<pre><code>var data = {user:user,pass:pass};
var answer = ajaxConn('core_files/startSession.php',data);
console.log(answer);
</code></pre>
<p>This is the headers of my PHP code</p>
<pre><code>require 'connection.php';
mysqli_set_charset($conn,"utf8");
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);
$user = mysqli_real_escape_string($conn,$data["user"]);
$pass = mysqli_real_escape_string($conn,$data["pass"]);
$response = array();
</code></pre>
<p>After a lot of validations PHP returns a word depending of the session case:
It can returns </p>
<pre><code>$response["resp"] = 'N';
echo json_encode($response);
</code></pre>
<p>for wrong session or</p>
<pre><code>$response["resp"] = 'Y';
echo json_encode($response);
</code></pre>
<p>for success session.</p>
<p>The problem is coming on the value return, if I do <code>console.log(returnValue)</code> inside the AJAX call, it returns the correct word from PHP. But, if I exit from AJAX call and I try to do the same out the funcion it returns me undefined. Actually, in the return of the function it returns me undefined too, outside the </p>
<pre><code>ajaxConn();
</code></pre>
<p>What I'm doing wrong</p>
| 0debug
|
static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
unsigned long int req, void *buf,
BlockDriverCompletionFunc *cb, void *opaque)
{
BDRVRawState *s = bs->opaque;
if (fd_open(bs) < 0)
return NULL;
return paio_ioctl(bs, s->fd, req, buf, cb, opaque);
}
| 1threat
|
The best way to simply manage users in Symfony : <p>I am using Symfony 2.8 with FOSUserBundle and I would like to simply manage the users of a website. By "simply", I mean to view (by sorting them eventually) their main features (like name, email, roles...) and to edit their roles by promoting and demoting them. In absolute terms, I could use DataTables Editor which can make the job. But I have few questions:</p>
<ul>
<li>What is the difference between Sonata Admin Bundle and DataTables Editor?</li>
<li>What is the most complete plugin/bundle to manage users?</li>
<li>What is the best solution in my case?</li>
</ul>
| 0debug
|
av_cold int ff_ivi_decode_close(AVCodecContext *avctx)
{
IVI45DecContext *ctx = avctx->priv_data;
ivi_free_buffers(&ctx->planes[0]);
if (ctx->mb_vlc.cust_tab.table)
ff_free_vlc(&ctx->mb_vlc.cust_tab);
#if IVI4_STREAM_ANALYSER
if (ctx->is_indeo4) {
if (ctx->is_scalable)
av_log(avctx, AV_LOG_ERROR, "This video uses scalability mode!\n");
if (ctx->uses_tiling)
av_log(avctx, AV_LOG_ERROR, "This video uses local decoding!\n");
if (ctx->has_b_frames)
av_log(avctx, AV_LOG_ERROR, "This video contains B-frames!\n");
if (ctx->has_transp)
av_log(avctx, AV_LOG_ERROR, "Transparency mode is enabled!\n");
if (ctx->uses_haar)
av_log(avctx, AV_LOG_ERROR, "This video uses Haar transform!\n");
if (ctx->uses_fullpel)
av_log(avctx, AV_LOG_ERROR, "This video uses fullpel motion vectors!\n");
}
#endif
av_frame_free(&ctx->p_frame);
return 0;
}
| 1threat
|
In what situations unit testing should be avoided? : <p>When is unit testing harmful? it can't be used in all situations and it should be selective, do you know situations when it should be avoided?</p>
| 0debug
|
static void puv3_board_init(CPUUniCore32State *env, ram_addr_t ram_size)
{
MemoryRegion *ram_memory = g_new(MemoryRegion, 1);
memory_region_init_ram(ram_memory, NULL, "puv3.ram", ram_size,
&error_abort);
vmstate_register_ram_global(ram_memory);
memory_region_add_subregion(get_system_memory(), 0, ram_memory);
}
| 1threat
|
Is there a better solution to this JavaScript code? : I'm trying to create QR codes in tables.
Links from which i need QR code is in div tag innerHTML.
<script type="text/javascript">
function myfunction() {
// PAGE 1 STARTS
// ROW 1
var TextInsideA2 = document.getElementById('A2').innerHTML;
document.getElementById('barcodeA2').src = "https://api.qrserver.com/v1/create-qr-code/?data='" + TextInsideA2 +"'&size=85x85";
var TextInsideA3 = document.getElementById('A3').innerHTML;
document.getElementById('barcodeA3').src = "https://api.qrserver.com/v1/create-qr-code/?data='" + TextInsideA3 +"'&size=85x85";
var TextInsideA4 = document.getElementById('A4').innerHTML;
document.getElementById('barcodeA4').src = "https://api.qrserver.com/v1/create-qr-code/?data='" + TextInsideA4 +"'&size=85x85";
// ROW 2
var TextInsideA5 = document.getElementById('A5').innerHTML;
document.getElementById('barcodeA5').src = "https://api.qrserver.com/v1/create-qr-code/?data='" + TextInsideA5 +"'&size=85x85";
var TextInsideA6 = document.getElementById('A6').innerHTML;
document.getElementById('barcodeA6').src = "https://api.qrserver.com/v1/create-qr-code/?data='" + TextInsideA6 +"'&size=85x85";
var TextInsideA7 = document.getElementById('A7').innerHTML;
document.getElementById('barcodeA7').src = "https://api.qrserver.com/v1/create-qr-code/?data='" + TextInsideA7 +"'&size=85x85";
// ROW 3
var TextInsideA8 = document.getElementById('A8').innerHTML;
document.getElementById('barcodeA8').src = "https://api.qrserver.com/v1/create-qr-code/?data='" + TextInsideA8 +"'&size=85x85";
var TextInsideA9 = document.getElementById('A9').innerHTML;
document.getElementById('barcodeA9').src = "https://api.qrserver.com/v1/create-qr-code/?data='" + TextInsideA9 +"'&size=85x85";
var TextInsideA10 = document.getElementById('A10').innerHTML;
document.getElementById('barcodeA10').src = "https://api.qrserver.com/v1/create-qr-code/?data='" + TextInsideA10 +"'&size=85x85";
// ROW 4
var TextInsideA11 = document.getElementById('A11').innerHTML;
document.getElementById('barcodeA11').src = "https://api.qrserver.com/v1/create-qr-code/?data='" + TextInsideA11 +"'&size=85x85";
var TextInsideA12 = document.getElementById('A12').innerHTML;
document.getElementById('barcodeA12').src = "https://api.qrserver.com/v1/create-qr-code/?data='" + TextInsideA12 +"'&size=85x85";
var TextInsideA13 = document.getElementById('A13').innerHTML;
document.getElementById('barcodeA13').src = "https://api.qrserver.com/v1/create-qr-code/?data='" + TextInsideA13 +"'&size=85x85";
// PAGE 1 ENDS
}
window.onload = myfunction;
</script>
This code works but QRs are generating slow and I need more of them.
Is there any better or "lightweight" solution that I can use instead of this?
| 0debug
|
matroska_parse_cluster (MatroskaDemuxContext *matroska)
{
int res = 0;
uint32_t id;
uint64_t cluster_time = 0;
uint8_t *data;
int64_t pos;
int size;
av_log(matroska->ctx, AV_LOG_DEBUG,
"parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
while (res == 0) {
if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
res = AVERROR_IO;
break;
} else if (matroska->level_up) {
matroska->level_up--;
break;
}
switch (id) {
case MATROSKA_ID_CLUSTERTIMECODE: {
uint64_t num;
if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
break;
cluster_time = num;
break;
}
case MATROSKA_ID_BLOCKGROUP:
if ((res = ebml_read_master(matroska, &id)) < 0)
break;
res = matroska_parse_blockgroup(matroska, cluster_time);
break;
case MATROSKA_ID_SIMPLEBLOCK:
pos = url_ftell(&matroska->ctx->pb);
res = ebml_read_binary(matroska, &id, &data, &size);
if (res == 0)
res = matroska_parse_block(matroska, data, size, pos,
cluster_time, -1, NULL, NULL);
break;
default:
av_log(matroska->ctx, AV_LOG_INFO,
"Unknown entry 0x%x in cluster data\n", id);
case EBML_ID_VOID:
res = ebml_read_skip(matroska);
break;
}
if (matroska->level_up) {
matroska->level_up--;
break;
}
}
return res;
}
| 1threat
|
node.js noobie trying to follow a tutorial - need to change jade reference to pug : <p>I'm trying to follow this tutorial to learn about node.js: </p>
<p><a href="http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/" rel="noreferrer">http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/</a></p>
<p>When I run "npm install" some of the messages I see include this:</p>
<pre><code>npm WARN deprecated jade@1.11.0: Jade has been renamed to pug, please install the latest version of pug instead of jade
npm WARN deprecated transformers@2.1.0: Deprecated, use jstransformer
</code></pre>
<p>And then it goes ahead and seems to set up the application anyways.
My package.json file currently looks like this: </p>
<pre><code>{
"name": "testapp",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.13.2",
"cookie-parser": "~1.3.5",
"debug": "~2.2.0",
"express": "~4.13.1",
"jade": "~1.11.0",
"morgan": "~1.6.1",
"serve-favicon": "~2.3.0",
"mongodb": "^1.4.4",
"monk": "^1.0.1"
}
}
</code></pre>
<p><strong>Questions:</strong>
(these questions apply to both packages that I got warned about, but for discussion purposes, I'm just going to pick on jade / pug)</p>
<p>If I wanted to change jade to pug, do i need to specify a version number in this package.json file? Or can I just tell it to get latest somehow?
Also, do I need to blow away my folder structure and then rerun the npm install command? Or can I just edit the package.json file and retry npm install? </p>
<p>Lastly, based on your experience, how critical is it for me to change from jade to pug if i'm just trying to learn how node works? I'm tempted to just leave as is... but then again, if this app works, i know it's going to be rolled out into production..
so... i guess i should make the right decisions up front. </p>
<p>Thanks and sorry if my questions are really remedial. </p>
| 0debug
|
static void qbus_list_dev(BusState *bus, char *dest, int len)
{
DeviceState *dev;
const char *sep = " ";
int pos = 0;
pos += snprintf(dest+pos, len-pos, "devices at \"%s\":",
bus->name);
LIST_FOREACH(dev, &bus->children, sibling) {
pos += snprintf(dest+pos, len-pos, "%s\"%s\"",
sep, dev->info->name);
if (dev->id)
pos += snprintf(dest+pos, len-pos, "/\"%s\"", dev->id);
sep = ", ";
}
}
| 1threat
|
static int ram_load_postcopy(QEMUFile *f)
{
int flags = 0, ret = 0;
bool place_needed = false;
bool matching_page_sizes = qemu_host_page_size == TARGET_PAGE_SIZE;
MigrationIncomingState *mis = migration_incoming_get_current();
void *postcopy_host_page = postcopy_get_tmp_page(mis);
void *last_host = NULL;
bool all_zero = false;
while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
ram_addr_t addr;
void *host = NULL;
void *page_buffer = NULL;
void *place_source = NULL;
uint8_t ch;
addr = qemu_get_be64(f);
flags = addr & ~TARGET_PAGE_MASK;
addr &= TARGET_PAGE_MASK;
trace_ram_load_postcopy_loop((uint64_t)addr, flags);
place_needed = false;
if (flags & (RAM_SAVE_FLAG_COMPRESS | RAM_SAVE_FLAG_PAGE)) {
host = host_from_stream_offset(f, addr, flags);
if (!host) {
error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
ret = -EINVAL;
break;
}
page_buffer = host;
page_buffer = postcopy_host_page +
((uintptr_t)host & ~qemu_host_page_mask);
if (!((uintptr_t)host & ~qemu_host_page_mask)) {
all_zero = true;
} else {
if (host != (last_host + TARGET_PAGE_SIZE)) {
error_report("Non-sequential target page %p/%p",
host, last_host);
ret = -EINVAL;
break;
}
}
place_needed = (((uintptr_t)host + TARGET_PAGE_SIZE) &
~qemu_host_page_mask) == 0;
place_source = postcopy_host_page;
}
last_host = host;
switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
case RAM_SAVE_FLAG_COMPRESS:
ch = qemu_get_byte(f);
memset(page_buffer, ch, TARGET_PAGE_SIZE);
if (ch) {
all_zero = false;
}
break;
case RAM_SAVE_FLAG_PAGE:
all_zero = false;
if (!place_needed || !matching_page_sizes) {
qemu_get_buffer(f, page_buffer, TARGET_PAGE_SIZE);
} else {
qemu_get_buffer_in_place(f, (uint8_t **)&place_source,
TARGET_PAGE_SIZE);
}
break;
case RAM_SAVE_FLAG_EOS:
break;
default:
error_report("Unknown combination of migration flags: %#x"
" (postcopy mode)", flags);
ret = -EINVAL;
}
if (place_needed) {
if (all_zero) {
ret = postcopy_place_page_zero(mis,
host + TARGET_PAGE_SIZE -
qemu_host_page_size);
} else {
ret = postcopy_place_page(mis, host + TARGET_PAGE_SIZE -
qemu_host_page_size,
place_source);
}
}
if (!ret) {
ret = qemu_file_get_error(f);
}
}
return ret;
}
| 1threat
|
uint32_t pci_default_read_config(PCIDevice *d,
uint32_t address, int len)
{
uint32_t val;
switch(len) {
case 1:
val = d->config[address];
break;
case 2:
val = le16_to_cpu(*(uint16_t *)(d->config + address));
break;
default:
case 4:
val = le32_to_cpu(*(uint32_t *)(d->config + address));
break;
}
return val;
}
| 1threat
|
Style BottomNavigationBar in Flutter : <p>I am trying out Flutter and I am trying to change the colour of the <code>BottomNavigationBar</code> on the app but all I could achieve was change the colour of the <code>BottomNavigationItem</code> (icon and text). </p>
<p>Here is where i declare my <code>BottomNavigationBar</code>:</p>
<pre><code>class _BottomNavigationState extends State<BottomNavigationHolder>{
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: null,
body: pages(),
bottomNavigationBar:new BottomNavigationBar(
items: <BottomNavigationBarItem>[
new BottomNavigationBarItem(
icon: const Icon(Icons.home),
title: new Text("Home")
),
new BottomNavigationBarItem(
icon: const Icon(Icons.work),
title: new Text("Self Help")
),
new BottomNavigationBarItem(
icon: const Icon(Icons.face),
title: new Text("Profile")
)
],
currentIndex: index,
onTap: (int i){setState((){index = i;});},
fixedColor: Colors.white,
),
);
}
</code></pre>
<p>Earlier I thought I had it figured out by editing <code>canvasColor</code> to green on my main app theme but it messed up the entire app colour scheme:</p>
<pre><code>class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
canvasColor: Colors.green
),
home: new FirstScreen(),
);
}
}
</code></pre>
| 0debug
|
Bootstrap 4 row fill remaining height : <p>I'm struggling to make the a row stretch to fill the rest of the available height. I tried adding <code>h-100</code> to the row class but that causes a white space at the bottom of the screen. There must be a way to do it but I'm totally stumped.. Here is my code: </p>
<pre><code><div class="container-fluid h-100">
<div class="row justify-content-center h-100">
<div class="col-4 bg-red">
<div class="h-100">
<div class="row justify-content-center bg-purple">
<div class="text-white">
<div style="height:200px">ROW 1</div>
</div>
</div>
<div class="row justify-content-center bg-blue">
<div class="text-white">ROW 2</div>
</div>
</div>
</div>
<div class="col-8 bg-gray"></div>
</div>
</div>
</code></pre>
<p>codepen: <a href="https://codepen.io/ee92/pen/zjpjXW/?editors=1100" rel="noreferrer">https://codepen.io/ee92/pen/zjpjXW/?editors=1100</a></p>
<p><a href="https://i.stack.imgur.com/yNiBk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yNiBk.png" alt="enter image description here"></a></p>
<p>I'd like to make the the blue row (ROW 2) fill all the red space. Any suggestions?</p>
<p>Thanks</p>
| 0debug
|
static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)
{
IDEBus *bus = DO_UPCAST(IDEBus, qbus, dev->qdev.parent_bus);
IDEState *s = bus->ifs + dev->unit;
Error *err = NULL;
if (dev->conf.discard_granularity == -1) {
dev->conf.discard_granularity = 512;
} else if (dev->conf.discard_granularity &&
dev->conf.discard_granularity != 512) {
error_report("discard_granularity must be 512 for ide");
blkconf_serial(&dev->conf, &dev->serial);
if (kind != IDE_CD) {
blkconf_geometry(&dev->conf, &dev->chs_trans, 65536, 16, 255, &err);
if (err) {
error_report("%s", error_get_pretty(err));
error_free(err);
if (ide_init_drive(s, dev->conf.blk, kind,
dev->version, dev->serial, dev->model, dev->wwn,
dev->conf.cyls, dev->conf.heads, dev->conf.secs,
dev->chs_trans) < 0) {
if (!dev->version) {
dev->version = g_strdup(s->version);
if (!dev->serial) {
dev->serial = g_strdup(s->drive_serial_str);
add_boot_device_path(dev->conf.bootindex, &dev->qdev,
dev->unit ? "/disk@1" : "/disk@0");
return 0;
| 1threat
|
static void pc_init_isa(MachineState *machine)
{
has_pci_info = false;
has_acpi_build = false;
smbios_defaults = false;
if (!machine->cpu_model) {
machine->cpu_model = "486";
}
x86_cpu_compat_disable_kvm_features(FEAT_KVM, KVM_FEATURE_PV_EOI);
enable_compat_apic_id_mode();
pc_init1(machine, 0, 1);
}
| 1threat
|
static void vga_screen_dump_common(VGAState *s, const char *filename,
int w, int h)
{
DisplayState *saved_ds, ds1, *ds = &ds1;
DisplayChangeListener dcl;
vga_invalidate_display(s);
saved_ds = s->ds;
memset(ds, 0, sizeof(DisplayState));
memset(&dcl, 0, sizeof(DisplayChangeListener));
dcl.dpy_update = vga_save_dpy_update;
dcl.dpy_resize = vga_save_dpy_resize;
dcl.dpy_refresh = vga_save_dpy_refresh;
register_displaychangelistener(ds, &dcl);
ds->surface = qemu_create_displaysurface(ds, w, h);
s->ds = ds;
s->graphic_mode = -1;
vga_update_display(s);
ppm_save(filename, ds->surface);
qemu_free_displaysurface(ds);
s->ds = saved_ds;
}
| 1threat
|
What language are exe files? Can I make a .exe from python? : <p>I was wondering what language are windows programs coded in? Can a python program run on windows if the computer doesn't have python installed?</p>
| 0debug
|
static void cirrus_do_copy(CirrusVGAState *s, int dst, int src, int w, int h)
{
int sx, sy;
int dx, dy;
int width, height;
int depth;
int notify = 0;
depth = s->get_bpp((VGAState *)s) / 8;
s->get_resolution((VGAState *)s, &width, &height);
sx = (src % (width * depth)) / depth;
sy = (src / (width * depth));
dx = (dst % (width *depth)) / depth;
dy = (dst / (width * depth));
w /= depth;
if (s->cirrus_blt_dstpitch < 0) {
sx -= (s->cirrus_blt_width / depth) - 1;
dx -= (s->cirrus_blt_width / depth) - 1;
sy -= s->cirrus_blt_height - 1;
dy -= s->cirrus_blt_height - 1;
}
if (sx >= 0 && sy >= 0 && dx >= 0 && dy >= 0 &&
(sx + w) <= width && (sy + h) <= height &&
(dx + w) <= width && (dy + h) <= height) {
notify = 1;
}
if (*s->cirrus_rop != cirrus_bitblt_rop_fwd_src &&
*s->cirrus_rop != cirrus_bitblt_rop_bkwd_src)
notify = 0;
if (notify)
vga_hw_update();
(*s->cirrus_rop) (s, s->vram_ptr +
(s->cirrus_blt_dstaddr & s->cirrus_addr_mask),
s->vram_ptr +
(s->cirrus_blt_srcaddr & s->cirrus_addr_mask),
s->cirrus_blt_dstpitch, s->cirrus_blt_srcpitch,
s->cirrus_blt_width, s->cirrus_blt_height);
if (notify)
qemu_console_copy(s->ds,
sx, sy, dx, dy,
s->cirrus_blt_width / depth,
s->cirrus_blt_height);
if (!notify)
cirrus_invalidate_region(s, s->cirrus_blt_dstaddr,
s->cirrus_blt_dstpitch, s->cirrus_blt_width,
s->cirrus_blt_height);
}
| 1threat
|
How to run ExUnit tests within IEx : <p>I'm trying to launch <code>IEx.pry</code> within a test. However I cannot get to run the tests within an iex session. Note that I'm not using mix.</p>
<pre><code>ExUnit.start
defmodule Calc do
def add(a,b) do
a + b
end
end
defmodule TheTest do
use ExUnit.Case
test "adds two numbers" do
require IEx
IEx.pry
assert Calc.add(1, 2) == 3
end
end
</code></pre>
<p>I try run it with <code>ExUnit.run</code> hangs and eventually times out:</p>
<pre><code>manuel@laptop:~/exercism/elixir/nucleotide-count$ iex test.exs
Erlang/OTP 18 [erts-7.3] [source] [64-bit] [smp:4:4] [async-threads:10] [kernel-poll:false]
Interactive Elixir (1.3.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> ExUnit.run
** (exit) exited in: GenServer.call(ExUnit.Server, {:take_async_cases, 8}, 60000)
** (EXIT) time out
(elixir) lib/gen_server.ex:604: GenServer.call/3
(ex_unit) lib/ex_unit/runner.ex:71: ExUnit.Runner.loop/2
(stdlib) timer.erl:166: :timer.tc/1
(ex_unit) lib/ex_unit/runner.ex:13: ExUnit.Runner.run/2
</code></pre>
<p>The code is loaded correctly and I can invoke it directly with <code>TheTest."test adds two numbers"({})</code>. But I was hoping to do this launching the whole suite.</p>
| 0debug
|
what is the best responsive method for HTML template : <p>mostly we use bootstrap for responsive but there have many peoples need responsive without bootstrap framework. I know about LESS. is that any other way to do my web site responsive perfectly </p>
| 0debug
|
PHP connect to DB and check URLs : I try to build a PHP function to check if some URLs are still working of have expired.
I managed to connect to my database, retrieve the list of URLs to check and use a check function I found on stackoverflow. However I have problems loop through all the URLs and write back the results to the database.
Would be great if someone can help on that part in the end ("define URL" should loop through the list and "output" should write back the echo into the table).
Here the php
<?php
//DB Credentials
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Retrieve list of URLs to check
$sql = "SELECT product_id, link FROM link_check";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["product_id"]. " " . $row["link"]. "<br>";
}
} else {
echo "0 results";
}
//Function to check URLs
function check_url($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$headers = curl_getinfo($ch);
curl_close($ch);
return $headers['http_code'];
}
//Define URLs
$sql = "SELECT link FROM link_check";
$url = $conn->query($sql);
//Output
$check_url_status = check_url($url);
if ($check_url_status == '200')
echo "Link Works";
else
echo "Broken Link";
$conn->close();
?>
This question is related to this old post: [Check Link URL][1]
[1]: http://stackoverflow.com/questions/15770903/check-if-links-are-broken-in-php
| 0debug
|
How to avoid repetitive long generic constraints in Rust : <p>I'm trying to make my own implementation of big integers (just for education). The implementation is generic by data type:</p>
<pre><code>struct LongNum<T>
where T: Integer + MulAssign + CheckedMul + CheckedAdd + Copy + From<u8>
{
values: Vec<T>,
powers: Vec<u8>,
radix: u8,
}
</code></pre>
<p>The problem is that I need to repeat this verbose constraint for T in all impls. It's too cumbersome.</p>
<p>I can make my own trait combining these constraints, like this:</p>
<pre><code>trait LongNumValue: Integer + MulAssign + CheckedMul + CheckedAdd + Copy + From<u8> {}
struct LongNum<T: LongNumValue>
{
values: Vec<T>,
powers: Vec<u8>,
radix: u8,
}
</code></pre>
<p>But in this case I have to add impls for this LongNumValue trait to all types which can be used in LongNum:</p>
<pre><code>impl LongNumValue for u8 {}
impl LongNumValue for u16 {}
impl LongNumValue for u32 {}
...
</code></pre>
<p>This means that if I don't add some type to this list of impls, the user of my crate will be unable to use this type for LongNum, even if this type is passes all constraints.</p>
<p>Is there any way to avoid writing long repetitive costraints without adding unnecessary restrictions to user?</p>
| 0debug
|
Why images are not showing up in iframe? : <p>I am using iframe to show data from our media manager site. But iframe is not showing up images.</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MM Test IFrame</title>
</head>
<body>
<iframe width="100%" height="400" src="http://mediamanager.b-
yy.com/filemanager/newmediamanager/filemanager/dialog.php"
frameborder="0" style="overflow: scroll; overflow-x: hidden; overflow-
y: scroll; "></iframe>
</body>
</html>
</code></pre>
<p>But if we directly try url then all is fine.
url: <a href="http://mediamanager.b-" rel="nofollow noreferrer">http://mediamanager.b-</a>
yy.com/filemanager/newmediamanager/filemanager/dialog.php</p>
| 0debug
|
static void pc_init_pci_1_3(QEMUMachineInitArgs *args)
{
enable_compat_apic_id_mode();
pc_sysfw_flash_vs_rom_bug_compatible = true;
has_pvpanic = false;
pc_init_pci(args);
}
| 1threat
|
Fastest remove certain values from array : I have an array looking like this :
[[Wed Sep 20 09:00:00 GMT+02:00 2017, SKYSCANNER, 04b073133c7843248a7a3dbc968f75a0, network1, affiliate, 1141338.0, 18164.0, , 0.08, 0.07, 0.62, 0.06, 0.0138, 0.0738, 0.465, 0.10695, 0.57195, 0.0525, 0.012075, 0.064575], [Wed Sep 20 09:00:00 GMT+02:00 2017, SKYSCANNER, 4420cc109ec54214b68edc906b18e44a, network1, affiliate, 1141338.0, 18164.0, , 0.75, 0.67, 5.58, 0.5625, 0.129375, 0.691875, 4.185, 0.96255, 5.14755, 0.5025, 0.115575, 0.618075], [Wed Sep 20 09:00:00 GMT+02:00 2017, SKYSCANNER, 90a7cbf1cf4e4043889626c4119d4b4d, network1, affiliate, 1141338.0, 18164.0, , 0.08, 0.07, 0.62, 0.06, 0.0138, 0.0738, 0.465, 0.10695, 0.57195, 0.0525, 0.012075, 0.064575], [Wed Sep 20 09:00:00 GMT+02:00 2017, SKYSCANNER, 0f04f1ff385541d3a8d9ea2f0d85482b, network1, affiliate, 1141338.0, 18164.0, , 0.08, 0.07, 0.62, 0.06, 0.0138, 0.0738, 0.465, 0.10695, 0.57195, 0.0525, 0.012075, 0.064575],[Wed Sep 20 09:00:00 GMT+02:00 2017, SKYSCANNER, 0f04f1ff385541d3a8d9ea2f0d85482b, network1, affiliate, 1232113, 1232133, , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
What I want to achieve(but don't know how) is to delete all entries(in the fastest way) that look like the last one in this array, e.g. `[Wed Sep 20 09:00:00 GMT+02:00 2017, SKYSCANNER, 0f04f1ff385541d3a8d9ea2f0d85482b, network1, affiliate, 1232113, 1232133, , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`
Basically, if all values after the 8th position are zeroes the entry is not needed and must be removed.
Typically in my case such array can have between 5-15k entries, so I was wondering what is the fastest way to achieve this? Can someone provide a working snippet?
Thanks!
| 0debug
|
Delet files using .bat in Windows 10 : I'm gonna show the first part of my script:
@echo off
mode 34,18
color f0
del /s /q /f unsorted_frt.txt >nul 2>nul
del /s /q /f output_frt.txt >nul 2>nul
del /s /q /f frt.txt >nul 2>nul
del /s /q /f datas_futuros_rede_tan.txt >nul 2>nul
del /s /q /f datas_futuros_rede_tan.csv >nul 2>nul
del /s /q /f c:\datas_futuros_rede_tan.csv >nul 2>nul
(etc.)
When i was using Windows 7, the script was running well. If the files to delet woudn't exist, the `.bat` ignored and keeped running.
So i upgrade to Windows 10, and when i run the script, if doesn't exist these files to delet, the script stops and don't keep going.
I need make the script keep going even these files doesn't exist. It must ignore it. I 'don't know why in Windows 10 it isn't work...
Someone can help me saying what is wrong?
| 0debug
|
static int compare_litqobj_to_qobj(LiteralQObject *lhs, QObject *rhs)
{
if (lhs->type != qobject_type(rhs)) {
return 0;
}
switch (lhs->type) {
case QTYPE_QINT:
return lhs->value.qint == qint_get_int(qobject_to_qint(rhs));
case QTYPE_QSTRING:
return (strcmp(lhs->value.qstr, qstring_get_str(qobject_to_qstring(rhs))) == 0);
case QTYPE_QDICT: {
int i;
for (i = 0; lhs->value.qdict[i].key; i++) {
QObject *obj = qdict_get(qobject_to_qdict(rhs), lhs->value.qdict[i].key);
if (!compare_litqobj_to_qobj(&lhs->value.qdict[i].value, obj)) {
return 0;
}
}
return 1;
}
case QTYPE_QLIST: {
QListCompareHelper helper;
helper.index = 0;
helper.objs = lhs->value.qlist;
helper.result = 1;
qlist_iter(qobject_to_qlist(rhs), compare_helper, &helper);
return helper.result;
}
default:
break;
}
return 0;
}
| 1threat
|
'glog/logging.h' file not found : <p>some time ago, every time I start a new project of react-native or when I install the modules I present this error.</p>
<p><code>'glog/logging.h' file not found</code>.</p>
<p>I found a way to solve it</p>
<pre><code>cd node_modules/react-native/third-party/glog-0.3.4
../../scripts/ios-configure-glog.sh
</code></pre>
<p>but it is very tedious to be running this every time.</p>
<p>It seems to be some bad configuration of node or something like that</p>
| 0debug
|
Error occurs in saving data in a database and show them in a listview in a Fragment class in android : I'm developing an android application where it uses a side navigation drawer. In the Fragment class I have an image button and it navigate to a new form to collect user data. After clicks save button, data store in database and display them in a list view in the fragment class where the form creation button is in.
I successfully implement this scenario without using navigation drawer and fragments by following a tutorial. but when I try to implement this using fragment my app stops work. I read the logcat, but I couldn't find any error in those classes. Please If someone could help me to resolve this problem I really appreciate your help.
This is my Firs Fragment class
/**
* A simple {@link Fragment} subclass.
*/
public class FirstFragment extends ListFragment implements android.view.View.OnClickListener {
private View rootView;
ImageButton btnAccounts;
TextView getAll;
TextView student_Id;
Context context;
public FirstFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_first, container, false);
rootView = inflater.inflate(R.layout.fragment_first, container, false);
btnAccounts = rootView.findViewById(R.id.create_account_btn);
/* btnAccounts.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), AccountsType.class);
startActivity(intent);
}
}); */
btnAccounts.setOnClickListener(this);
getAll = rootView.findViewById(R.id.textView7);
getAll.setOnClickListener(this);
return rootView;
}
@Override
public void onClick(View view) {
if (view == view.findViewById(R.id.create_account_btn)) {
Intent intent = new Intent(getActivity(), AccountsType.class);
intent.putExtra("account_Id", 0);
startActivity(intent);
}else {
AccountRepo repo = new AccountRepo(this);
ArrayList<HashMap<String, String>> accountList = repo.getUserList();
if(accountList.size()!=0) {
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
student_Id = (TextView) view.findViewById(R.id.student_Id);
String accountId = student_Id.getText().toString();
Intent objIndent = new Intent(getActivity().getApplicationContext(),AccountsType.class);
objIndent.putExtra("student_Id", Integer.parseInt( accountId));
startActivity(objIndent);
}
});
ListAdapter adapter = new SimpleAdapter(getActivity(),accountList, R.layout.view_account_entry, new String[] { "id","name"}, new int[] {R.id.student_Id, R.id.student_name});
setListAdapter(adapter);
}else{
Toast.makeText(context,"No Created Invoices!",Toast.LENGTH_SHORT).show();
}
}
}
}
this is the AccountRepo class
/**
* Created by User on 10/10/2017.
*/
public class AccountRepo {
private DBHelper dbHelper;
public AccountRepo(Context context) {
dbHelper = new DBHelper(context);
}
public AccountRepo(FirstFragment firstFragment) {
}
public int insert(AccountTypesCl account1) {
//open connection to write data
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
//values.put(AccountTypesCl.KEY_discount, user1.discount);
values.put(AccountTypesCl.KEY_code, account1.code);
values.put(AccountTypesCl.KEY_name, account1.name);
values.put(AccountTypesCl.KEY_des, account1.des);
//values.put(User1.KEY_date, user1.date);
//Inserting row
long account_Id = db.insert(AccountTypesCl.TABLE, null, values);
db.close(); //close db connection
return (int) account_Id;
}
public void delete(int account_Id) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete(AccountTypesCl.TABLE, AccountTypesCl.KEY_ID + "= ?", new String[]{String.valueOf(account_Id)});
db.close();
}
public void update(AccountTypesCl account1) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
//values.put(User1.KEY_discount, user1.discount);
values.put(AccountTypesCl.KEY_code, account1.code);
values.put(AccountTypesCl.KEY_name, account1.name);
values.put(AccountTypesCl.KEY_des, account1.des);
//values.put(User1.KEY_date, user1.date);
db.update(AccountTypesCl.TABLE, values, AccountTypesCl.KEY_ID + "= ?", new String[]{String.valueOf(account1.Account_ID)});
db.close();
}
public ArrayList<HashMap<String, String>> getUserList() {
//Open connection to read only
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT " +
AccountTypesCl.KEY_ID + "," +
AccountTypesCl.KEY_code + "," +
AccountTypesCl.KEY_name + "," +
// User1.KEY_discount + "," +
//User1.KEY_date + "," +
AccountTypesCl.KEY_des +
" FROM " + AccountTypesCl.TABLE;
//Student student = new Student();
ArrayList<HashMap<String, String>> userList = new ArrayList<HashMap<String, String>>();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
HashMap<String, String> account1 = new HashMap<String, String>();
account1.put("id", cursor.getString(cursor.getColumnIndex(AccountTypesCl.KEY_ID)));
account1.put("name", cursor.getString(cursor.getColumnIndex(AccountTypesCl.KEY_name)));
userList.add(account1);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return userList;
}
public AccountTypesCl getUserById(int Id) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT " +
AccountTypesCl.KEY_ID + "," +
AccountTypesCl.KEY_code + "," +
AccountTypesCl.KEY_name + "," +
//User1.KEY_discount + "," +
//User1.KEY_date + "," +
AccountTypesCl.KEY_des +
" FROM " + AccountTypesCl.TABLE
+ " WHERE " +
AccountTypesCl.KEY_ID + "=?";// It's a good practice to use parameter ?, instead of concatenate string
int iCount = 0;
AccountTypesCl account1 = new AccountTypesCl();
Cursor cursor = db.rawQuery(selectQuery, new String[]{String.valueOf(Id)});
if (cursor.moveToFirst()) {
do {
account1.Account_ID = cursor.getInt(cursor.getColumnIndex(AccountTypesCl.KEY_ID));
account1.code = cursor.getString(cursor.getColumnIndex(AccountTypesCl.KEY_code));
account1.name = cursor.getString(cursor.getColumnIndex(AccountTypesCl.KEY_name));
account1.des = cursor.getString(cursor.getColumnIndex(AccountTypesCl.KEY_des));
// user1.date = cursor.getString(cursor.getColumnIndex(User1.KEY_date));
//user1.value = cursor.getString(cursor.getColumnIndex(User1.KEY_value));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return account1;
}
}
this is the logcat,
10-10 13:40:04.563 2853-2853/com.example.user.navigationdrawer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.navigationdrawer, PID: 2853
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
at com.example.user.navigationdrawer.AccountRepo.getUserList(AccountRepo.java:64)
at com.example.user.navigationdrawer.fragments.FirstFragment.onClick(FirstFragment.java:82)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
| 0debug
|
I want to add a number if user enters add 5 , i want to initialize the variable if user enters set 5. how can I do it in java? : enter code here
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
/*
* Complete the maximumProgramValue function below.
*/
static long maximumProgramValue(int n) {
/*
* Write your code here.
*/
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(System.getenv("OUTPUT_PATH")));
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])*");
long result = maximumProgramValue(n);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
help me for solving it, that how can i use it to get answer, i have been stuck here from long please help soon thanks
help me for solving it, that how can i use it to get answer, i have been stuck here from long please help soon thanks
help me for solving it, that how can i use it to get answer, i have been stuck here from long please help soon thanks**help me for solving it, that how can i use it to get answer, i have been stuck here from long please help soon thanks
help me for solving it, that how can i use it to get answer, i have been stuck here from long please help soon thanks
help me for solving it, that how can i use it to get answer, i have been stuck here from long please help soon thanks
help me for solving it, that how can i use it to get answer, i have been stuck here from long please help soon thanks
**
| 0debug
|
static int smush_read_packet(AVFormatContext *ctx, AVPacket *pkt)
{
SMUSHContext *smush = ctx->priv_data;
AVIOContext *pb = ctx->pb;
int done = 0;
while (!done) {
uint32_t sig, size;
if (url_feof(pb))
return AVERROR_EOF;
sig = avio_rb32(pb);
size = avio_rb32(pb);
switch (sig) {
case MKBETAG('F', 'R', 'M', 'E'):
if (smush->version)
break;
if (av_get_packet(pb, pkt, size) < 0)
return AVERROR(EIO);
pkt->stream_index = smush->video_stream_index;
done = 1;
break;
case MKBETAG('B', 'l', '1', '6'):
if (av_get_packet(pb, pkt, size) < 0)
return AVERROR(EIO);
pkt->stream_index = smush->video_stream_index;
pkt->duration = 1;
done = 1;
break;
case MKBETAG('W', 'a', 'v', 'e'):
if (size < 13)
return AVERROR_INVALIDDATA;
if (av_get_packet(pb, pkt, size) < 0)
return AVERROR(EIO);
pkt->stream_index = smush->audio_stream_index;
pkt->flags |= AV_PKT_FLAG_KEY;
pkt->duration = AV_RB32(pkt->data);
if (pkt->duration == 0xFFFFFFFFu)
pkt->duration = AV_RB32(pkt->data + 8);
done = 1;
break;
default:
avio_skip(pb, size);
break;
}
}
return 0;
}
| 1threat
|
VS 2015 C#-based solution with Linker failure : <p>I'm porting an existing VS 2013-based solution to VS 2015 Update 1 and I am receiving an error code:</p>
<p>The following is a post-build command that triggers the error:</p>
<pre><code>"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\al.exe" /out:"C:\p4\MMM-2015\blah\tm1\Assemblies\USSAdmin.resources.dll" /culture:en /embed:"C:\p4\MMM-2015\blah\tm1\blah\USSAdmin\USSAdmin.resources" /t:lib
</code></pre>
<p>I'm getting an error: exited with code -1073741819 with some Linker error dialogs also.</p>
<p>The above command works fine in a command-prompt.</p>
| 0debug
|
static void qmp_input_type_uint64(Visitor *v, const char *name, uint64_t *obj,
Error **errp)
{
QmpInputVisitor *qiv = to_qiv(v);
QObject *qobj = qmp_input_get_object(qiv, name, true, errp);
QInt *qint;
if (!qobj) {
return;
}
qint = qobject_to_qint(qobj);
if (!qint) {
error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",
"integer");
return;
}
*obj = qint_get_int(qint);
}
| 1threat
|
Efficiency in Andoid Native : Is more efficient in terms of memory and speed close an activity when you go to another and create a new one when go back or not finishing the activity and leave on the stack?
| 0debug
|
static void FUNC(put_hevc_pel_bi_w_pixels)(uint8_t *_dst, ptrdiff_t _dststride, uint8_t *_src, ptrdiff_t _srcstride,
int16_t *src2,
int height, int denom, int wx0, int wx1,
int ox0, int ox1, intptr_t mx, intptr_t my, int width)
{
int x, y;
pixel *src = (pixel *)_src;
ptrdiff_t srcstride = _srcstride / sizeof(pixel);
pixel *dst = (pixel *)_dst;
ptrdiff_t dststride = _dststride / sizeof(pixel);
int shift = 14 + 1 - BIT_DEPTH;
int log2Wd = denom + shift - 1;
ox0 = ox0 * (1 << (BIT_DEPTH - 8));
ox1 = ox1 * (1 << (BIT_DEPTH - 8));
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
dst[x] = av_clip_pixel(( (src[x] << (14 - BIT_DEPTH)) * wx1 + src2[x] * wx0 + ((ox0 + ox1 + 1) << log2Wd)) >> (log2Wd + 1));
}
src += srcstride;
dst += dststride;
src2 += MAX_PB_SIZE;
}
}
| 1threat
|
static inline void copy(LZOContext *c, int cnt)
{
register const uint8_t *src = c->in;
register uint8_t *dst = c->out;
if (cnt > c->in_end - src) {
cnt = FFMAX(c->in_end - src, 0);
c->error |= AV_LZO_INPUT_DEPLETED;
}
if (cnt > c->out_end - dst) {
cnt = FFMAX(c->out_end - dst, 0);
c->error |= AV_LZO_OUTPUT_FULL;
}
#if defined(INBUF_PADDED) && defined(OUTBUF_PADDED)
AV_COPY32U(dst, src);
src += 4;
dst += 4;
cnt -= 4;
if (cnt > 0)
#endif
memcpy(dst, src, cnt);
c->in = src + cnt;
c->out = dst + cnt;
}
| 1threat
|
Which Activity gets called when i start a application? : <p>I was going through my android beginners tutorials and I m not able to understand which activity is called when the app is started. </p>
| 0debug
|
static int64_t alloc_clusters_imrt(BlockDriverState *bs,
int cluster_count,
uint16_t **refcount_table,
int64_t *imrt_nb_clusters,
int64_t *first_free_cluster)
{
BDRVQcowState *s = bs->opaque;
int64_t cluster = *first_free_cluster, i;
bool first_gap = true;
int contiguous_free_clusters;
int ret;
for (contiguous_free_clusters = 0;
cluster < *imrt_nb_clusters &&
contiguous_free_clusters < cluster_count;
cluster++)
{
if (!(*refcount_table)[cluster]) {
contiguous_free_clusters++;
if (first_gap) {
*first_free_cluster = cluster;
first_gap = false;
}
} else if (contiguous_free_clusters) {
contiguous_free_clusters = 0;
}
}
if (contiguous_free_clusters < cluster_count) {
ret = realloc_refcount_array(s, refcount_table, imrt_nb_clusters,
cluster + cluster_count
- contiguous_free_clusters);
if (ret < 0) {
return ret;
}
}
cluster -= contiguous_free_clusters;
for (i = 0; i < cluster_count; i++) {
(*refcount_table)[cluster + i] = 1;
}
return cluster << s->cluster_bits;
}
| 1threat
|
Thread Sleep and ReadKey doesn't cooperate : <p>I want to stop the whole do-while loop by using space and write out my WriteLine, but it doesn't do anything on pressing spacebar. I think it's something to do with Thread.Sleep, maybe It doesn't allow user input while on Sleep. I would be really happy if someone could enlighten me why this doesn't work</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace casinov2
{
class Program
{
static void Main(string[] args)
{
int x=3;
int y = 15;
int[] elemek = new int[7];
do{
while (!Console.KeyAvailable){
for (int i = 0; i < 5; i++){
Console.Clear();
Console.SetCursorPosition(x, y);
x++;
Console.WriteLine("{0:██}{1:██}{2:██}", elemek[i], elemek[i + 1], elemek[i + 2]);
System.Threading.Thread.Sleep(100);
if (i >= 4){
for (int j = 0; j < 5; j++){
Console.Clear();
Console.SetCursorPosition(x, y);
x--;
Console.WriteLine("{0:██}{1:██}{2:██}", elemek[i], elemek[i + 1], elemek[i + 2]);
System.Threading.Thread.Sleep(100);
}
i = -1;
}
}
}
} while (Console.ReadKey(true).Key != ConsoleKey.Spacebar);
Console.WriteLine("ready");
Console.ReadLine();
}
}
}
</code></pre>
| 0debug
|
Android Json and AsyncTask Error : <p>i had written an code that sends data from the android application to the database using JSON Form but i am having some errors when it sends.</p>
<p>this is the class for registration:</p>
<pre><code>package com.subhi.tabhost;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Pattern;
import AddUser.AllUsersLoadSpinner;
import ConnectionDetector.ConnectionDetector;
import SpinnerFirstLoad.MultiSelectionSpinner;
import SpinnerFirstLoad.PlayersLoadSpinner;
import SpinnerFirstLoad.TeamsLoadSpinner;
public class Registeration extends AppCompatActivity {
ConnectionDetector connectionDetector;
private MultiSelectionSpinner multiSelectionSpinner;
private MultiSelectionSpinner PlayersSelectSpinier;
Button save;
TextView name, email, userexists;
ArrayList<String> TeamsList = new ArrayList<String>();
ArrayList<String> UsersList = new ArrayList<String>();
ArrayList<String> PlayersList = new ArrayList<String>();
public static final String MyPREFERENCES = "MyPrefs";
public static final String Name = "nameKey";
public static final String EMAIL = "emailKey";
SharedPreferences sharedpreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registeration);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String restoredText = sharedpreferences.getString(Name, null);
/* if (restoredText != null) {
// Intent intent = new Intent(getApplicationContext(), MainMenu.class);
//startActivity(intent);
// finish();
}*/
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// if (connectionDetector.isConnectingToInternet()) {
name = (TextView) findViewById(R.id.name);
email = (TextView) findViewById(R.id.email);
userexists = (TextView) findViewById(R.id.btnLinkToLoginScreen);
save = (Button) findViewById(R.id.btnRegister);
multiSelectionSpinner = (MultiSelectionSpinner) findViewById(R.id.mySpinner);
PlayersSelectSpinier = (MultiSelectionSpinner) findViewById(R.id.mySpinner2);
TeamsLoadSpinner x1 = new TeamsLoadSpinner(this);
x1.execute("http://192.168.1.106/add/index.php");
AllUsersLoadSpinner allUsersLoadSpinner = new AllUsersLoadSpinner(this);
allUsersLoadSpinner.execute("http://192.168.1.106/add/allusers.php");
PlayersLoadSpinner x2 = new PlayersLoadSpinner(this);
x2.execute("http://192.168.1.106/add/print.php");
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
InsertData adduser = new InsertData();
String txtname = name.getText().toString();
String txtemail = email.getText().toString();
if (txtname.equals(""))
Toast.makeText(getApplicationContext(), "UserName Cannot Be Empty", Toast.LENGTH_LONG).show();
else {
if (txtemail.equals(""))
Toast.makeText(getApplicationContext(), "Email Cannot Be Empty ", Toast.LENGTH_LONG).show();
else {
if (isValidEmail(txtemail)) {
boolean x = false;
for (int i = 0; i < UsersList.size(); i++) {
if (UsersList.get(i).equals(txtname)) {
x = true;
}
}
if (x == false) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, txtname);
editor.putString(EMAIL, txtemail);
editor.commit();
adduser.execute("192.168.1.106/add/add.php", txtname, txtemail, multiSelectionSpinner.getSelectedItemsAsString(), PlayersSelectSpinier.getSelectedItemsAsString());
} else {
//Toast.makeText(getApplicationContext(),"USER EXISTS",Toast.LENGTH_LONG).show();
userexists.setText("User Alerady Exists, Please Choose Differnent User name ");
}
} else
Toast.makeText(getApplicationContext(), "Please Enter A valid Email", Toast.LENGTH_LONG).show();
}
}
}
});
// }else {
// Internet connection is not present
// Ask user to connect to Internet
// showAlertDialog(Registeration.this, "No Internet Connection",
// "You don't have internet connection.", false);
// }
}
public void showAlertDialog(final Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
// Showing Alert Message
alertDialog.show();
}
private boolean isValidEmail(String email) {
Pattern pattern = Patterns.EMAIL_ADDRESS;
return pattern.matcher(email).matches();
}
public void SetTeams(ArrayList<String> list) {
TeamsList = list;
String[] stockArr = new String[TeamsList.size()];
stockArr = TeamsList.toArray(stockArr);
multiSelectionSpinner.setItems(stockArr);
}
public void SetUsers(ArrayList<String> list) {
UsersList = list;
}
public void SetPlayers(ArrayList<String> players) {
PlayersList = players;
String[] stockArr = new String[PlayersList.size()];
stockArr = PlayersList.toArray(stockArr);
PlayersSelectSpinier.setItems(stockArr);
}
private class InsertData extends AsyncTask<String,Void,Boolean>
{
@Override
protected Boolean doInBackground(String... urls) {
OutputStream os=null;
InputStream is=null;
HttpURLConnection conn=null;
try {
URL url =new URL(urls[0]);
JSONObject jsonObject=new JSONObject();
jsonObject.put("UserName", urls[1]);
jsonObject.put("Email", urls[2]);
jsonObject.put("Teams", urls[3]);
jsonObject.put("Players", urls[4]);
String message=jsonObject.toString();
Log.d(message, "Test");
conn=(HttpURLConnection)url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
conn.connect();
os=new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
os.flush();
is=conn.getInputStream();
} catch (MalformedURLException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();;
e.printStackTrace();
return false;
} catch (IOException e) {
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();;
e.printStackTrace();
return false;
} catch (JSONException e) {
e.printStackTrace();
}
finally {
try {
assert os != null;
os.close();
assert is != null;
is.close();
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
}
return true;
}
@Override
protected void onPostExecute(Boolean result) {
if(result)
{
Toast.makeText(getApplicationContext(),"Insert Success",Toast.LENGTH_LONG).show();;
}
else {
Toast.makeText(getApplicationContext(),"Insert Fail",Toast.LENGTH_LONG).show();;
}
}
}
}
</code></pre>
<p>and this is the php code script:</p>
<pre><code><?php
require ('config.php');
$con=mysqli_connect($servername,$username,$password,$db);
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$txtname=$obj['UserName'];//$_POST['txtname'];
$txtemail=$obj['Email'];//$_POST['txtemail'];
$txtteam=$obj['Teams'];//$_POST['txtemail'];
$txtplayer=$obj['Players'];//$_POST['txtemail'];
mysqli_query($con,"insert into user (UserName,Email,TeamsInterested,PlayersIterested) values('$txtname','$txtemail','$txtteam','$txtplayer') ");
echo "Inserted";
?>
</code></pre>
<p>and this is the log cat :</p>
<pre><code>02-11 12:06:15.197 2301-2319/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3
Process: com.subhi.tabhost, PID: 2301
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.subhi.tabhost.Registeration$InsertData.doInBackground(Registeration.java:287)
at com.subhi.tabhost.Registeration$InsertData.doInBackground(Registeration.java:221)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
02-11 12:06:15.201 530-843/? W/ActivityManager: Force finishing activity com.subhi.tabhost/.Registeration
02-11 12:06:15.265 153-502/? W/genymotion_audio: out_write() limiting sleep time 42152 to 39909
02-11 12:06:15.469 530-843/? D/dalvikvm: GC_FOR_ALLOC freed 621K, 27% free 9319K/12628K, paused 6ms, total 7ms
02-11 12:06:15.481 530-843/? D/dalvikvm: GC_FOR_ALLOC freed 376K, 27% free 9315K/12628K, paused 12ms, total 12ms
02-11 12:06:15.497 530-545/? D/dalvikvm: GC_FOR_ALLOC freed 13K, 23% free 9791K/12628K, paused 12ms, total 12ms
02-11 12:06:15.501 530-545/? I/dalvikvm-heap: Grow heap (frag case) to 10.747MB for 1127532-byte allocation
02-11 12:06:15.509 530-539/? D/dalvikvm: GC_FOR_ALLOC freed 15K, 21% free 10876K/13732K, paused 11ms, total 11ms
</code></pre>
<p>and the log cat errors shows that are in code in two places:</p>
<pre><code>1- `os.close();`
2- private class InsertData extends AsyncTask<String,Void,Boolean>
</code></pre>
<p>so if anyone can help me please?!</p>
| 0debug
|
java fraction calculator with simplifying fractions : Hi so i have a couple of problems with my code and although i have tried i haven't found out what was wrong with it
public class FracCalc {
public static void main(String[] args) {
// String to test
//String input = "5_3/4 - 6_7/8 + 3/4";
System.out.println(produceAnswer("-3_3/4 / -2_2/3"));
}
public static String produceAnswer(String input) {
// Splits everything at every space
String[] array = input.split(" ", 0);
int allWholes = 0;
int allNumerators = 0;
int allDenominators = 1;
// Multiplier is 1 or -1, 1 is add, -1 is subtract
int multiplier = 1;
// Operation mode; 0=+,-; 1=*; 2=/
int mode = 0;
// the for loop is used to identify and solve the the test
for (int i = 0; i < array.length; i++) {
String part = array[i];
//
int whole = 0;
int numerator = 0;
int denominator = 0;
// If it has a _, then it's a whole + fraction
if (part.contains("_")) {
// Convert Int from start of part (0) to the character before _, "55_30/40" -> 55
whole = Integer.parseInt(part.substring(0, part.indexOf("_")));
// Convert Int from the character AFTER _ to the character before /, "55_30/40" -> 30
numerator = Integer.parseInt(part.substring(part.indexOf("_") + 1, part.indexOf("/")));
// Convert Int from the character AFTER / to the end, "55_30/40" -> 40
denominator = Integer.parseInt(part.substring(part.indexOf("/") + 1, part.length()));
}
// If no _, but still has a / AND it is not just the symbol "/", then it's just a fraction
else if (part.contains("/") && part.length() != 1) {
numerator = Integer.parseInt(part.substring(0, part.indexOf("/")));
denominator = Integer.parseInt(part.substring(part.indexOf("/") + 1, part.length()));
} //else if(part.contains("*") && part.contains("/")){}
else if (part.contains("/") ) {
mode = 2;
}
// TODO: Make multiplication
// Negative sign(if number is negative)
else if (part.contains("-")) {
multiplier = -1;
}
// Positive sign(if number is positive)
else if (part.contains("+")) {
multiplier = 1;
}
// If neither _ nor /, then it's a whole
else {
whole = Integer.parseInt(part);
}
// Add all the wholes together
allWholes += whole * multiplier;
// If denom is the same
if (denominator == allDenominators) {
allNumerators += numerator * multiplier;
}
// If they're not the same
else if (numerator != 0 && denominator != 0) {
if (mode == 0 ) {
// Cross multiply
allNumerators *= denominator;
// Add
allNumerators += numerator * allDenominators * multiplier;
// Second part of cross multiply
allDenominators *= denominator;
}
// Multiplication
else if (mode == 1) {
allDenominators *= denominator;
allNumerators *= numerator;
}
// Division
else if (mode == 2) {
// Reverse multiply because (1/2)/(1/2) -> (1*1)/(2*2)
allNumerators = allNumerators * denominator;
allDenominators = allDenominators * numerator;
}
}
}
// Simplifies fraction by checking to see id the top is bigger than bottom
// 9/4 -> 2_1/4
while(allNumerators > allDenominators){
allWholes = allNumerators / allDenominators;
allNumerators %= allDenominators;
}
if (allWholes == 0) {
return (allNumerators + "/" + allDenominators);
}
else if (allNumerators == 0 || allDenominators == 0) {
return allWholes + "";
}
else {
return allWholes + "_" + (allNumerators + "/" + allDenominators);
}
}
}
My goal is too make a fraction calculator with a simplified answer (as a fraction) here is my code so far, i am pretty sure my multiplication, division and simplifying while loop is my problem. Thank you
| 0debug
|
Want to run the method again if its taking time first time. How to achieve it? : <p>I have a method (say execute()), if it takes more than 10 secs(per say)to return response i need to reexecute it.</p>
<p>Kindly help me how to achieve this?</p>
<p>Thanks</p>
| 0debug
|
Deserisation fails with when using null numeric primitives as map keys : Gson deserialization failed when using null number primitives as map keys
Gson gson = new GsonBuilder()
.serializeNulls()
.serializeSpecialFloatingPointValues()
.create();
Map<Integer, String> mapData = new HashMap<Integer, String>();
mapData.put(null, "abc");
String data = gson.toJson(mapData);
System.out.println(data);
Type type = TypeToken.getParameterized(HashMap.class, Integer.class, String.class).getType();
Object obj = gson.fromJson(data, type);
System.out.println(obj);
| 0debug
|
void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
{
if (key) {
if (!bdrv_is_encrypted(bs)) {
error_setg(errp, "Node '%s' is not encrypted",
bdrv_get_device_or_node_name(bs));
} else if (bdrv_set_key(bs, key) < 0) {
error_set(errp, QERR_INVALID_PASSWORD);
}
} else {
if (bdrv_key_required(bs)) {
error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
"'%s' (%s) is encrypted",
bdrv_get_device_or_node_name(bs),
bdrv_get_encrypted_filename(bs));
}
}
}
| 1threat
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.