problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
How do you test a URL and get a status code in Swift 3? : <p>I'm using the most recent version of Xcode (8.1 at time of writing), which uses Swift 3.0.</p>
<p>All I'm trying to do is take a string, convert it to a URL and test that URL to see if it gives me a 404 error. I've been able to make a URL and URLRequest by using:</p>
<pre><code> let url = URL(string: fullURL)
let request = URLRequest(url: url!)
</code></pre>
<p>but I've found myself unable to get anything working beyond that. I've searched around for help, but most, if not all of it, is written in Swift 2.0, which I've tried to convert to no avail. It seems that even if you change the naming convention to remove the NS prefix, that isn't enough. I tried using:</p>
<pre><code> let response: AutoreleasingUnsafeMutablePointer<URLRequest> = nil
</code></pre>
<p>but that gives me an error that "fix-it" makes worse by sticking question marks and semi-colons everywhere.</p>
<p>Apple's documentation isn't helping me much, either. I'm seriously at a loss.</p>
<p>Does anybody know how to correctly set up and test a URL for 404 status in Swift 3.0?</p>
| 0debug
|
alert('Hello ' + user_input);
| 1threat
|
how to open only whatsapp application when click on a hyperlink/image/button : <p>A code required for html website, when user open my website from mobile device and click on hyper link/image/button, then the link should open only whatsapp application.</p>
<p>I only need to open whatsapp application when user click on a link in my html website. that's it.</p>
<p>please share the code.</p>
| 0debug
|
static av_cold int omx_encode_init(AVCodecContext *avctx)
{
OMXCodecContext *s = avctx->priv_data;
int ret = AVERROR_ENCODER_NOT_FOUND;
const char *role;
OMX_BUFFERHEADERTYPE *buffer;
OMX_ERRORTYPE err;
#if CONFIG_OMX_RPI
s->input_zerocopy = 1;
#endif
s->omx_context = omx_init(avctx, s->libname, s->libprefix);
if (!s->omx_context)
return AVERROR_ENCODER_NOT_FOUND;
pthread_mutex_init(&s->state_mutex, NULL);
pthread_cond_init(&s->state_cond, NULL);
pthread_mutex_init(&s->input_mutex, NULL);
pthread_cond_init(&s->input_cond, NULL);
pthread_mutex_init(&s->output_mutex, NULL);
pthread_cond_init(&s->output_cond, NULL);
s->mutex_cond_inited = 1;
s->avctx = avctx;
s->state = OMX_StateLoaded;
s->error = OMX_ErrorNone;
switch (avctx->codec->id) {
case AV_CODEC_ID_MPEG4:
role = "video_encoder.mpeg4";
break;
case AV_CODEC_ID_H264:
role = "video_encoder.avc";
break;
default:
return AVERROR(ENOSYS);
}
if ((ret = find_component(s->omx_context, avctx, role, s->component_name, sizeof(s->component_name))) < 0)
goto fail;
av_log(avctx, AV_LOG_INFO, "Using %s\n", s->component_name);
if ((ret = omx_component_init(avctx, role)) < 0)
goto fail;
if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
while (1) {
buffer = get_buffer(&s->output_mutex, &s->output_cond,
&s->num_done_out_buffers, s->done_out_buffers, 1);
if (buffer->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
if ((ret = av_reallocp(&avctx->extradata, avctx->extradata_size + buffer->nFilledLen + AV_INPUT_BUFFER_PADDING_SIZE)) < 0) {
avctx->extradata_size = 0;
goto fail;
}
memcpy(avctx->extradata + avctx->extradata_size, buffer->pBuffer + buffer->nOffset, buffer->nFilledLen);
avctx->extradata_size += buffer->nFilledLen;
memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
}
err = OMX_FillThisBuffer(s->handle, buffer);
if (err != OMX_ErrorNone) {
append_buffer(&s->output_mutex, &s->output_cond,
&s->num_done_out_buffers, s->done_out_buffers, buffer);
av_log(avctx, AV_LOG_ERROR, "OMX_FillThisBuffer failed: %x\n", err);
ret = AVERROR_UNKNOWN;
goto fail;
}
if (avctx->codec->id == AV_CODEC_ID_H264) {
int nals[32] = { 0 };
int i;
for (i = 0; i + 4 < avctx->extradata_size; i++) {
if (!avctx->extradata[i + 0] &&
!avctx->extradata[i + 1] &&
!avctx->extradata[i + 2] &&
avctx->extradata[i + 3] == 1) {
nals[avctx->extradata[i + 4] & 0x1f]++;
}
}
if (nals[NAL_SPS] && nals[NAL_PPS])
break;
} else {
if (avctx->extradata_size > 0)
break;
}
}
}
return 0;
fail:
return ret;
}
| 1threat
|
uint64_t helper_efdctsidz (uint64_t val)
{
CPU_DoubleU u;
u.ll = val;
if (unlikely(float64_is_nan(u.d)))
return 0;
return float64_to_int64_round_to_zero(u.d, &env->vec_status);
}
| 1threat
|
How to limit ListView to particular number of list items in android : I am working on a functionality in which I have a ListView and I want listView to show only 3 items. I have set ListView height to **"wrap_content"** and in adapter I have set **get count** to 3 so that it will show only 3 items but it is showing only 1 item. I am not able to figure out what is happening.
Code :
public int getCount() {
return 3;
}
| 0debug
|
I am using Swifty json library for json parsing.. and not getting value of country... I want value of Country.. I want value "GB".. Following is Json : {"status": true,
"message": "Country Details",
"content":
{
"country": "GB"
}
}
and code
let countryJson = response["content"]
let Country = countryJson["country"]
Please help me..i am stuck..
| 0debug
|
This class is not key value coding-compliant for the key cancel : <p>I keep getting this error: <code>Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<FoodTracker.MealViewController 0x7faa9ed189d0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key cancel.'</code></p>
<p>I'm trying to complete the Apple developer guide to getting started with iOS apps. My code and storyboard looks exactly like theirs does in the example file. I'm hoping that a fresh eye might be able to see something I am not?</p>
<pre><code>import UIKit
import os.log
class MealViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var ratingControl: RatingControl!
@IBOutlet weak var saveButton: UIBarButtonItem!
/*
This value is either passed by 'MealTableViewController' in
'prepare(for:sender) or constructed as part of adding a new meal.
*/
var meal: Meal?
override func viewDidLoad() {
super.viewDidLoad()
// Handle the text field's user input through delegate callbacks
nameTextField.delegate = self
// Enable save button only if text field has valid Meal name
updateSaveButtonState()
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
updateSaveButtonState()
navigationItem.title = textField.text
}
func textFieldDidBeginEditing(_ textField: UITextField) {
// Disable save button while editing
saveButton.isEnabled = false
}
//MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// Dismiss the picker if the user canceled
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// The info dictionary may contain multiple representations of the image. You want to use the original.
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
// Set photoImageView to display the selected image
photoImageView.image = selectedImage
// Dismiss the picker
dismiss(animated: true, completion: nil)
}
//MARK: Navigation
@IBAction func cancel(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
// Configure view controller before it's presented
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
// Configure destination view controller only when save button pressed
guard let button = sender as? UIBarButtonItem, button === saveButton else {
os_log("The save button was not pressed, cancelling", log: OSLog.default, type: .debug)
return
}
let name = nameTextField.text ?? ""
let photo = photoImageView.image
let rating = ratingControl.rating
// Set meal to be passed to MealTableViewController after unwind segue
meal = Meal(name: name, photo: photo, rating: rating)
}
//MARK: Actions
@IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) {
// Hide the keyboard
nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken
imagePickerController.sourceType = .photoLibrary
// Make sure ViewController is notified when the user picks an image
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
//MARK: Private Methods
private func updateSaveButtonState() {
// Disable the save button if the text field is empty
let text = nameTextField.text ?? ""
saveButton.isEnabled = !text.isEmpty
}
}
</code></pre>
<p>There are a few other files, but please just let me know what you need because I am very new to Swift/XCode and not sure what to provide/not provide.</p>
| 0debug
|
static int blend_frames(AVFilterContext *ctx, int interpolate)
{
FrameRateContext *s = ctx->priv;
AVFilterLink *outlink = ctx->outputs[0];
double interpolate_scene_score = 0;
if ((s->flags & FRAMERATE_FLAG_SCD)) {
if (s->score >= 0.0)
interpolate_scene_score = s->score;
else
interpolate_scene_score = s->score = get_scene_score(ctx, s->f0, s->f1);
ff_dlog(ctx, "blend_frames() interpolate scene score:%f\n", interpolate_scene_score);
}
if (interpolate_scene_score < s->scene_score) {
ThreadData td;
td.copy_src1 = s->f0;
td.copy_src2 = s->f1;
td.src2_factor = interpolate;
td.src1_factor = s->max - td.src2_factor;
s->work = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!s->work)
return AVERROR(ENOMEM);
av_frame_copy_props(s->work, s->f0);
ff_dlog(ctx, "blend_frames() INTERPOLATE to create work frame\n");
ctx->internal->execute(ctx, filter_slice, &td, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));
return 1;
}
return 0;
}
| 1threat
|
Why is 'Bring an umbrella' the correct answer? : <p>I am using the Grasshopper app on my phone and I do not understand an example they gave me for if then statements.</p>
<p>They give you the solution because I answered incorrectly, but I do not understand why the solution given is correct. </p>
<pre><code>var todayWeather = 'rainy';
var tommorrowWeather = 'cloudy';
if (todayWeather === 'rainy') {
print('Bring an umbrella');
}
if (todayWeather !== 'rainy') {
print('Maybe the sun will come out');
}
</code></pre>
<p>They say the correct answer is 'Bring an umbrella'. But why is this what this code will produce if it is run?</p>
| 0debug
|
Trying to think about how to build a multi step form in angular 2 : <p>I am trying to build a small, 3 step form. It would be something similar to this:</p>
<p><a href="https://i.stack.imgur.com/BysIo.jpg"><img src="https://i.stack.imgur.com/BysIo.jpg" alt="enter image description here"></a></p>
<p>The way I did this in react was by using redux to track form completion and rendering the form body markup based on the step number (0, 1, 2). </p>
<p>In angular 2, what would be a good way to do this? Here's what I am attempting at the moment, and I'm still working on it. Is my approach fine? Is there a better way to do it? </p>
<p>I have a parent component <code><app-form></code> and I will be nesting inside it <code><app-form-header></code> and <code><app-form-body></code>.</p>
<pre><code><app-form>
<app-header [step]="step"></app-header>
<app-body [formData]="formData"></app-body>
</app-form>
</code></pre>
<p>In <code><app-form></code> component I have a <code>step: number</code> and <code>formData: Array<FormData></code>. The step is just a index for each object in formData. This will be passed down to the header. formData will be responsible the form data from user. Each time the form input is valid, user can click Next to execute nextStep() to increment the index. Each step has an associated template markup. </p>
<p>Is there a better way to do something like this? </p>
| 0debug
|
static int tcp_write(URLContext *h, const uint8_t *buf, int size)
{
TCPContext *s = h->priv_data;
int ret, size1, fd_max, len;
fd_set wfds;
struct timeval tv;
size1 = size;
while (size > 0) {
if (url_interrupt_cb())
return AVERROR(EINTR);
fd_max = s->fd;
FD_ZERO(&wfds);
FD_SET(s->fd, &wfds);
tv.tv_sec = 0;
tv.tv_usec = 100 * 1000;
ret = select(fd_max + 1, NULL, &wfds, NULL, &tv);
if (ret > 0 && FD_ISSET(s->fd, &wfds)) {
len = send(s->fd, buf, size, 0);
if (len < 0) {
if (ff_neterrno() != FF_NETERROR(EINTR) &&
ff_neterrno() != FF_NETERROR(EAGAIN))
return ff_neterrno();
continue;
}
size -= len;
buf += len;
} else if (ret < 0) {
if (ff_neterrno() == FF_NETERROR(EINTR))
continue;
return -1;
}
}
return size1 - size;
}
| 1threat
|
static int cbr_bit_allocation(AC3EncodeContext *s)
{
int ch;
int bits_left;
int snr_offset, snr_incr;
bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
snr_offset = s->coarse_snr_offset << 4;
while (snr_offset >= 0 &&
bit_alloc(s, snr_offset) > bits_left) {
snr_offset -= 64;
}
if (snr_offset < 0)
return AVERROR(EINVAL);
FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
while (snr_offset + 64 <= 1023 &&
bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
snr_offset += snr_incr;
FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
}
}
FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
reset_block_bap(s);
s->coarse_snr_offset = snr_offset >> 4;
for (ch = 0; ch < s->channels; ch++)
s->fine_snr_offset[ch] = snr_offset & 0xF;
return 0;
}
| 1threat
|
Looking for advice with C arrays : Good afternoon,
I want to improve my program with user-input of array length. Is that possible in C?
| 0debug
|
def count_occurance(s):
count=0
for i in range(len(s)):
if (s[i]== 's' and s[i+1]=='t' and s[i+2]== 'd'):
count = count + 1
return count
| 0debug
|
How to decrypt smime file in c# application? : I have a file, which is encrypted using this command:
openssl smime -encrypt -aes256 -in fileToencrypt -binary -outform DEM -out encryptedFile public_key
It can be decrypted using command:
openssl smime -decrypt -in encryptedFile -binary -inform DEM -inkey private-key.pem -out decryptedFile
I need to decrypt it using private key (PEM format) in my .NET Core application. What could be the possible solution?
| 0debug
|
retain 0's when incrementing number : In ruby if I have this integer `003` and I increment it by 1 the number will be `4`. I want it to be `004`. How can I retain the 0's in this?
#### CODE:
num = 003
num += 1
`=> 4` I want `=> 004`
| 0debug
|
Syntax error on curl intilization : Why it says syntax error and could not feel the form with this no......hey guys today I am trying to put my number on external site and login without opening it but it couldn't work what is the problem I don't know...............any type of help is greatly appreciated
<?php
$phone=$_REQUEST['9155499248'];
function send_sms($phone) {
if (!function_exists('curl_init')) {
echo "Error : Curl library not installed";
return FALSE;
}
$user_agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36";
// LOGIN TO TOPPER
$url = "https://www.toppr.com/signup/";
$parameters = array("email"=>"$phone","button"=>"Signup");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($parameters));
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_NOBODY, FALSE);
$result = curl_exec ($ch);
curl_close ($ch);
// SEND OTP AGAIN AND AGAIN
?>
And now this is the source code of site on which I am trying to put My no. And login automatically............
<form action="/signup/" method="post" class="mdAuth_form">
<input type="hidden" name="next" value="">
<div class="mdAuth_inputGroup js-input-group">
<label class="mdAuth_inputGroup_label">Enter your phone number</label>
<input type="text" name="email" class="inputText mdAuth_inputGroup_input">
<label class="mdAuth_inputGroup_error js-error"></label>
</div>
<div class="ac mt-20 mb-25">
<button class="button button-big button-arrowed button-green mdAuth_centerBtn -strk" data-strk='{ "e": "ui.tapped", "ui_element_name": "submit_email"}'>
Signup <span class="arrowRight white inline-block ml-20"></span>
</button>
</div>
</form>
| 0debug
|
Type 'null' is not assignable to type 'HTMLInputElement' ReactJs : <p>I am trying to reference data into reactJS along with typescript. While doing this I am getting below error</p>
<pre><code>Type 'null' is not assignable to type 'HTMLInputElement'
</code></pre>
<p>Please let me know what exactly incorrect here, I used documentaiton from React
<a href="https://reactjs.org/docs/refs-and-the-dom.html" rel="noreferrer">https://reactjs.org/docs/refs-and-the-dom.html</a>
but I think I am doing something wrong here.
Below is the scope snippet</p>
<pre><code> class Results extends React.Component<{}, any> {
private textInput: HTMLInputElement;
.......
constructor(props: any) {
super(props);
this.state = { topics: [], isLoading: false };
this.handleLogin = this.handleLogin.bind(this);
}
componentDidMount() {.....}
handleLogin() {
this.textInput.focus();
var encodedValue = encodeURIComponent(this.textInput.value);
.......
}
render() {
const {topics, isLoading} = this.state;
if (isLoading) {
return <p>Loading...</p>;
}
return (
<div>
<input ref={(thisInput) => {this.textInput = thisInput}} type="text" className="form-control" placeholder="Search"/>
<div className="input-group-btn">
<button className="btn btn-primary" type="button" onClick={this.handleLogin}>
...............
</code></pre>
<p>Any idea what I may be missing here?</p>
| 0debug
|
How can I create a string by combining two strings and using substitution? : <p>I have code that creates two strings:</p>
<pre><code>var string1 = "ま|ちが|#";
var string2 = "間|違|う";
</code></pre>
<p>I'm looking for a way to combine these such the resulting output contains the characters from string1 but if the character is a "#" then it takes the alternate character from string2. </p>
<pre><code>string1 string2 desired output
ま|ちが|# 間|違|う まちがう
な|# 為|る なる
で|き|# 出|来|る できる
</code></pre>
<p>Does anyone have any suggestions as to how I can do this?</p>
| 0debug
|
Play Song displayed in the table view in x Code (Swift) : I have displayed all Songs of the iTunes Music Library in a table view. Now I would like to play the selected song in the table view as soon as the user taps on it.
Here's my Code:
import UIKit
import MediaPlayer
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var table: UITableView!
//Create an array with some elements for the table view rows
var myMusicPlayer = MPMusicPlayerController()
var allSongsArray: [MPMediaItem]!
let songsQuery = MPMediaQuery.songsQuery()
var abcArray = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z", "#"]
//Define the amount of sections in table view
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return abcArray.count
}
//Assign the amount of elements in the array to the amount of rows in one section
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allSongsArray.count
}
//Set up each element in abcArray as title for section
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.abcArray[section] as String
}
//Set up the Index Search
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
return abcArray
}
//Assign each element in the array a row in table view
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell")
var items = allSongsArray[indexPath.row]
cell?.textLabel?.text = items.title
cell?.detailTextLabel?.text = items.artist
var imageSize = CGSizeMake(100, 100)
cell?.imageView?.image = items.artwork?.imageWithSize(imageSize)
return cell!
}
override func viewDidLoad() {
super.viewDidLoad()
self.allSongsArray = songsQuery.items! as [MPMediaItem]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 0debug
|
Android NullPointException on getWritableDatabase : <p>I know this question was asked a thousand times and I read a lot of them and the answers. But I couldnt fix my problem in this case.
When I'm calling the getWritableDatabase() Function in my android app I get this Exception:</p>
<pre><code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.schneider_schwarz_inc.tagesablauf_log, PID: 12634
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.schneider_schwarz_inc.tagesablauf_log/de.schneider_schwarz_inc.tagesablauf_log.GUI.ToDo.ToDoList}: java.lang.RuntimeException: 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.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.RuntimeException: 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 de.schneider_schwarz_inc.tagesablauf_log.Database.ToDo.ToDoDao.insertToDo(ToDoDao.java:41)
at de.schneider_schwarz_inc.tagesablauf_log.Todo.createTodo(Todo.java:25)
at de.schneider_schwarz_inc.tagesablauf_log.GUI.ToDo.ToDoList.onCreate(ToDoList.java:47)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: 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.getWritableDatabase(SQLiteOpenHelper.java:163)
at de.schneider_schwarz_inc.tagesablauf_log.Database.ToDo.ToDoDao.insertToDo(ToDoDao.java:32)
at de.schneider_schwarz_inc.tagesablauf_log.Todo.createTodo(Todo.java:25)
at de.schneider_schwarz_inc.tagesablauf_log.GUI.ToDo.ToDoList.onCreate(ToDoList.java:47)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code></pre>
<p>My Sqliteopenhelper class:</p>
<pre><code>public ToDoDbHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
System.out.println("creating database");
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public static int getDatabaseVersion() {
return DATABASE_VERSION;
}
</code></pre>
<p>I use it in this class:</p>
<pre><code>public class ToDoDao {
private Context context;
private ToDoDbHelper toDoDbHelper;
public ToDoDao(Context context){
this.context = context;
toDoDbHelper = new ToDoDbHelper(context);
}
/**
* Inserts ToDos into Database
* @param data data to insert
* @return is -1 when error, else the id
*/
public long insertToDo(ToDoData data){
try{
SQLiteDatabase db = toDoDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ToDoStructure.ToDoEntry.COLUMN_NAME_TITLE, data.getTitle());
values.put(ToDoStructure.ToDoEntry.COLUMN_NAME_DATE, data.getDate());
return db.insert(ToDoStructure.ToDoEntry.TABLE_NAME, null, values);
}catch (Exception e){
System.out.println("ERROR!");
//TODO handling exception
throw new RuntimeException(e);
}
}
</code></pre>
<p>The Dao I use here:</p>
<pre><code>public class Todo {
private List<ToDoData> dataList;
private Context context;
private ToDoDao dao = new ToDoDao(context);
public Todo(Context context){
this.context = context;
//dataList = dao.getAllToDos();
dataList = new ArrayList<>();
}
public int createTodo(String title, String date){
ToDoData newData = new ToDoData(title, date);
long id = dao.insertToDo(newData);
if(id == -1){
return (int) id;
}
newData.setId(String.valueOf(id));
dataList.add(newData);
return 0;
}
</code></pre>
<p>And at least my activity where I get my Context:</p>
<pre><code>public class ToDoList extends Activity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState){
System.out.println("createListView");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
Todo todo = new Todo(this);
todo.createTodo("Test1", "20160910");
List<ToDoData> todoList = todo.getDataList();
System.out.println(todoList.get(0).getTitle());
mAdapter = new ToDoViewAdapter(getBaseContext(), todoList);
mRecyclerView.setAdapter(mAdapter);
}
</code></pre>
<p>I think the problem is my context. But I dont know to fix it...</p>
<p>Thanks!</p>
| 0debug
|
int RENAME(swri_resample)(ResampleContext *c, DELEM *dst, const DELEM *src, int *consumed, int src_size, int dst_size, int update_ctx){
int dst_index, i;
int index= c->index;
int frac= c->frac;
int dst_incr_frac= c->dst_incr % c->src_incr;
int dst_incr= c->dst_incr / c->src_incr;
av_assert1(c->filter_shift == FILTER_SHIFT);
av_assert1(c->felem_size == sizeof(FELEM));
if (c->filter_length == 1 && c->phase_shift == 0) {
int64_t index2= (1LL<<32)*c->frac/c->src_incr + (1LL<<32)*index;
int64_t incr= (1LL<<32) * c->dst_incr / c->src_incr;
int new_size = (src_size * (int64_t)c->src_incr - frac + c->dst_incr - 1) / c->dst_incr;
dst_size= FFMIN(dst_size, new_size);
for(dst_index=0; dst_index < dst_size; dst_index++){
dst[dst_index] = src[index2>>32];
index2 += incr;
}
index += dst_index * dst_incr;
index += (frac + dst_index * (int64_t)dst_incr_frac) / c->src_incr;
frac = (frac + dst_index * (int64_t)dst_incr_frac) % c->src_incr;
av_assert2(index >= 0);
*consumed= index;
index = 0;
} else if (index >= 0) {
int64_t end_index = (1LL + src_size - c->filter_length) << c->phase_shift;
int64_t delta_frac = (end_index - index) * c->src_incr - c->frac;
int delta_n = (delta_frac + c->dst_incr - 1) / c->dst_incr;
int n = FFMIN(dst_size, delta_n);
int sample_index;
if (!c->linear) {
sample_index = index >> c->phase_shift;
index &= c->phase_mask;
for (dst_index = 0; dst_index < n; dst_index++) {
FELEM *filter = ((FELEM *) c->filter_bank) + c->filter_alloc * index;
#ifdef COMMON_CORE
COMMON_CORE
#else
FELEM2 val=0;
for (i = 0; i < c->filter_length; i++) {
val += src[sample_index + i] * (FELEM2)filter[i];
}
OUT(dst[dst_index], val);
#endif
frac += dst_incr_frac;
index += dst_incr;
if (frac >= c->src_incr) {
frac -= c->src_incr;
index++;
}
sample_index += index >> c->phase_shift;
index &= c->phase_mask;
}
} else {
sample_index = index >> c->phase_shift;
index &= c->phase_mask;
for (dst_index = 0; dst_index < n; dst_index++) {
FELEM *filter = ((FELEM *) c->filter_bank) + c->filter_alloc * index;
FELEM2 val=0, v2 = 0;
#ifdef LINEAR_CORE
LINEAR_CORE
#else
for (i = 0; i < c->filter_length; i++) {
val += src[sample_index + i] * (FELEM2)filter[i];
v2 += src[sample_index + i] * (FELEM2)filter[i + c->filter_alloc];
}
#endif
val += (v2 - val) * (FELEML) frac / c->src_incr;
OUT(dst[dst_index], val);
frac += dst_incr_frac;
index += dst_incr;
if (frac >= c->src_incr) {
frac -= c->src_incr;
index++;
}
sample_index += index >> c->phase_shift;
index &= c->phase_mask;
}
}
*consumed = sample_index;
} else {
int sample_index = 0;
for(dst_index=0; dst_index < dst_size; dst_index++){
FELEM *filter;
FELEM2 val=0;
sample_index += index >> c->phase_shift;
index &= c->phase_mask;
filter = ((FELEM*)c->filter_bank) + c->filter_alloc*index;
if(sample_index + c->filter_length > src_size || -sample_index >= src_size){
break;
}else if(sample_index < 0){
for(i=0; i<c->filter_length; i++)
val += src[FFABS(sample_index + i)] * (FELEM2)filter[i];
OUT(dst[dst_index], val);
}else if(c->linear){
FELEM2 v2=0;
#ifdef LINEAR_CORE
LINEAR_CORE
#else
for(i=0; i<c->filter_length; i++){
val += src[sample_index + i] * (FELEM2)filter[i];
v2 += src[sample_index + i] * (FELEM2)filter[i + c->filter_alloc];
}
#endif
val+=(v2-val)*(FELEML)frac / c->src_incr;
OUT(dst[dst_index], val);
}else{
#ifdef COMMON_CORE
COMMON_CORE
#else
for(i=0; i<c->filter_length; i++){
val += src[sample_index + i] * (FELEM2)filter[i];
}
OUT(dst[dst_index], val);
#endif
}
frac += dst_incr_frac;
index += dst_incr;
if(frac >= c->src_incr){
frac -= c->src_incr;
index++;
}
}
*consumed= FFMAX(sample_index, 0);
index += FFMIN(sample_index, 0) << c->phase_shift;
}
if(update_ctx){
c->frac= frac;
c->index= index;
}
return dst_index;
}
| 1threat
|
Command line java programming basics : <p>Is it possible to edit varargs of main function in java program ?</p>
<pre><code>class Program1 {
public static void main(String args[]){
int i=44;
args[i]=34 +"";
System.out.println(args[i]);
}
}
</code></pre>
| 0debug
|
Calculating the difference between two dates in seconds : I need to know how much time elapsed from the moment the app was terminated to the time the app was launched again. I guess you'd have to store the startDate by saving it in the appDelegate when appIsTerminated. Then you'd have to access that value in appDidLaunch, also in appDelegate and then calculate the difference between those times. I need the difference in seconds and I want to use the difference in my viewController. How do I do this in swift 3, Xcode 8?
| 0debug
|
SSL handshake failed remote host closed connection during handshake (eclipse, svn) : I am trying to create a repository in Eclipse. The code that I need is hosted in a Visual SVN (VisualSVN) server. I am trying to use its truck URL as the repository location, but when I try to connect to the URL through Eclipse's SVN plug-in, it fails with error SSL handshake failed.
I am using a proxy server.
I have seen solutions mentioning modifying the settings like so:
-Dhttps.protocols=TLSv1.1,TLSv1.2
Source:
https://stackoverflow.com/questions/21245796/javax-net-ssl-sslhandshakeexception-remote-host-closed-connection-during-handsh
But I do not have any Java options file?
plz HALP
Tried disabling proxy, using open network where eclipse works (but then I can't connect to the visual svn server). Tried using Visual Studio Code instead ( no proxy issues but I need to download and svn .exe which I cannot do rn)
| 0debug
|
Nested objects in mongoose schemas : <p>i've seen many answers to this question here, but i still don't get it (maybe because they use more "complex" examples)...
So what im trying to do is a schema for a "Customer", and it will have two fields that will have nested "subfields", and others that may repeat. here is what i mean:</p>
<pre><code>let customerModel = new Schema({
firstName: String,
lastName: String,
company: String,
contactInfo: {
tel: [Number],
email: [String],
address: {
city: String,
street: String,
houseNumber: String
}
}
});
</code></pre>
<p><strong>tel</strong> and <strong>email</strong> might be an array.
and address will not be repeated, but have some sub fields as you can see.</p>
<p>How can i make this work?</p>
| 0debug
|
static void armv7m_nvic_realize(DeviceState *dev, Error **errp)
{
NVICState *s = NVIC(dev);
SysBusDevice *systick_sbd;
Error *err = NULL;
s->cpu = ARM_CPU(qemu_get_cpu(0));
assert(s->cpu);
if (s->num_irq > NVIC_MAX_IRQ) {
error_setg(errp, "num-irq %d exceeds NVIC maximum", s->num_irq);
return;
}
qdev_init_gpio_in(dev, set_irq_level, s->num_irq);
s->num_irq += NVIC_FIRST_IRQ;
object_property_set_bool(OBJECT(&s->systick), true, "realized", &err);
if (err != NULL) {
error_propagate(errp, err);
return;
}
systick_sbd = SYS_BUS_DEVICE(&s->systick);
sysbus_connect_irq(systick_sbd, 0,
qdev_get_gpio_in_named(dev, "systick-trigger", 0));
memory_region_init(&s->container, OBJECT(s), "nvic", 0x1000);
memory_region_init_io(&s->sysregmem, OBJECT(s), &nvic_sysreg_ops, s,
"nvic_sysregs", 0x1000);
memory_region_add_subregion(&s->container, 0, &s->sysregmem);
memory_region_add_subregion_overlap(&s->container, 0x10,
sysbus_mmio_get_region(systick_sbd, 0),
1);
sysbus_init_mmio(SYS_BUS_DEVICE(dev), &s->container);
}
| 1threat
|
JUnit Test + Eclipse : I am not familiar with Junit testing at all. How would I go about creating a junit test for this code? I am using Eclipse and have already set up the test file.
@WebServlet("/version")
public class TypeCheck extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 987654321;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BufferedReader read = null;
InputStream is = this.getClass().getClassLoader().getResourceAsStream("/version.txt");
try {
read = new BufferedReader(new InputStreamReader(is));
response.getWriter().write(read.readLine());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (read != null) { try { read.close(); } catch (IOException e) { e.printStackTrace(); } }
}
}
}
| 0debug
|
Android: multiple intentservices or one intentservice with multiple intents? : <p>I'm a little confused about intentService. The docs say that if you send an intentService multiple tasks (intents) then it will execute them one after the other on one separate thread. My question is - is it possible to have multiple intentService threads at the same time or not? How do you differentiate in the code between creating three different intents on the same intentService (the same thread), or three separate intentServices each with it's own thread and one intent each to execute?</p>
<p>In other words, when you perform the command startService(intent) are you putting the intent in a single queue or does it start a new queue every time?</p>
<pre><code>Intent someIntent1 = new Intent(this, myIntentService.class);
Intent someIntent2 = new Intent(this, myIntentService.class);
Intent someIntent3 = new Intent(this, myIntentService.class);
startService(someIntent1);
startService(someIntent2);
startService(someIntent3);
</code></pre>
| 0debug
|
How to get last seven days in laravel? : I am trying last seven days record using below query but it does not working
DB::table('data_table')
->select(DB::raw('SUM(fee) as counter, left(DATE(created_at),10) as date'))
->whereIn('user_id',$descendants)
->whereRaw('DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 7 DAY)')
->groupBy(DB::raw('left(DATE(created_at),10)'))
->get()
Can someone kindly guide me how make it correct
| 0debug
|
Given a latitude and longitude, How can I know if there is a restaurant at that location? : How do I know if there is a restaurant at a given lat long location.
Can we use google maps/ google places/ Yelp/ FourSquare for the same?
Input : lat, long pair ( 1.280634,103.845392 )
Output: Meii Sushi
| 0debug
|
Can we display HTML tables on UILabel : Up to now i can show some HTML tags like <p>, <li> on UILabel, but i want to display <td>, <tr> tags on UILable. Is it possible. I know we can display in WebView but for dynamic size in table view i want to put a lable kind of UI, is there any third party for it please let me know
| 0debug
|
Eloquent model relationship in Laravel : This is my Project.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $table = 'project';
protected $primaryKey = 'project_id';
}
<br>
This is my Developer.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Developer extends Model
{
//
protected $table = 'developer';
protected $primaryKey = 'id';
}
I want to join this two model as the SQL below :
> SELECT developer.developer_name, count(project.dev_id)<br>
> FROM project<br>
> JOIN developer ON developer.id = project.dev_id <br>
> GROUP BY developer.developer_name<br>
Can someone help me ? I am confused when looked through different documentation.<br>
Please guide me the correct way..
| 0debug
|
When adding string to Hashtable, string gains unrecognizable characters : <p>So currently I have a hash table that I create and populate it with keys and values</p>
<pre><code>Hashtable m_hash = new Hashtable();
</code></pre>
<p>I then have a string that I have created with a value that will replace a specific value in the hash table.</p>
<pre><code>string birthday = "1979/01/01"
</code></pre>
<p>I then remove the existing value from the hash table and we add in our new value into the hash table.</p>
<pre><code>//0x00080023 is the key in the hash table
m_hash.Remove(0x00080023);
//Then we add in the new value into the key location
m_hash.Add(0x00080023, birthday);
</code></pre>
<p>After we write the hash table to the file. However, when you open up the file the result is as follows:</p>
<p><a href="https://i.stack.imgur.com/VwYkn.png" rel="nofollow noreferrer">Results of our program</a></p>
<p>As you can see at the end of the string there are some unrecognizable characters in the string. Could this be because of the way that we are adding the string into the hash table? Should the string be formatted in a specific way? (Currently it's formatted normally as UTF 16) Any help is appreciated. </p>
| 0debug
|
how download Angular4 js : I want to develop my first app with Angular4 technology into PHP Symfony project. I don't use NodeJS server for executing JS source code. But the official tutorial angular4 don't specified another way for getting angular4 js.
I don't find CDN for Angular4.
How can find source code of Angular v4 ?
| 0debug
|
as in excel, an formulae are used to refer to cells, i'd like to know how to replicate that in R : <p>trying to keep it as simple as possible</p>
<p>Consider this simple excel formula. Lets presume that I'm in cell C2 currently and it holds this formula.
=if(A2=1,B2,<strong>C1</strong>)</p>
<p>i'm stuck at the referencing part. is there any way to do it?</p>
| 0debug
|
static void kvm_mem_ioeventfd_add(MemoryListener *listener,
MemoryRegionSection *section,
bool match_data, uint64_t data,
EventNotifier *e)
{
int fd = event_notifier_get_fd(e);
int r;
r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
data, true, int128_get64(section->size),
match_data);
if (r < 0) {
abort();
}
}
| 1threat
|
PHP PDO bindValue does not update the DB : <p>Could someone tell me what I am doing wrong.</p>
<p>If I use the code below, I am able to update the DB.</p>
<pre><code> $sUpdateSql = "UPDATE googleAnalytics SET $period = '$value' WHERE statisticName = '$item' ";
$preparedStatement = $db->query($sUpdateSql);
</code></pre>
<p>However, with the statement below the DB does not update.</p>
<pre><code> $sUpdateSql = "UPDATE googleAnalytics SET $period = '?' WHERE statisticName = '?' ";
$preparedStatement = $db->prepare($sUpdateSql);
/* bind parameters for markers */
$preparedStatement->bindValue(1, $value);
$preparedStatement->bindValue(2, $item);
$preparedStatement->execute();
</code></pre>
| 0debug
|
800A0401 - expected end of statement in vba : I am getting this error "800A0401 - expected end of statement" in VBA.
Please clarify on what is wrong
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:\Users\RAJDIQ\Desktop\Macros\11082017\SingleFile.txt", ForReading)
strLine = objTextFile.ReadLine
Set folder = objFSO.GetFolder("C:\Users\RAJDIQ\Desktop\Macros\11082017\")
Set outfile = objFSO.OpenTextFile("C:\Users\RAJDIQ\Desktop\Macros\11082017\comparedel.txt")
myFile ="C:\Users\RAJDIQ\Desktop\Macros\11082017\Output.txt"
Open myFile for Output As #1
t = 0
Do Until outfile.AtEndOfStream
strLine = outfile.ReadLine
If InStr(strLine, substrToFind) <> 0 Then
t = t+1
Else
[ Lines = Lines & t & ","
Write #1, Lines]
End If
Loop
MSGBOX "Complete"
| 0debug
|
static void check_exception(PowerPCCPU *cpu, sPAPRMachineState *spapr,
uint32_t token, uint32_t nargs,
target_ulong args,
uint32_t nret, target_ulong rets)
{
uint32_t mask, buf, len, event_len;
uint64_t xinfo;
sPAPREventLogEntry *event;
struct rtas_error_log *hdr;
if ((nargs < 6) || (nargs > 7) || nret != 1) {
rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
return;
}
xinfo = rtas_ld(args, 1);
mask = rtas_ld(args, 2);
buf = rtas_ld(args, 4);
len = rtas_ld(args, 5);
if (nargs == 7) {
xinfo |= (uint64_t)rtas_ld(args, 6) << 32;
}
event = rtas_event_log_dequeue(mask, true);
if (!event) {
goto out_no_events;
}
hdr = event->data;
event_len = be32_to_cpu(hdr->extended_length) + sizeof(*hdr);
if (event_len < len) {
len = event_len;
}
cpu_physical_memory_write(buf, event->data, len);
rtas_st(rets, 0, RTAS_OUT_SUCCESS);
g_free(event->data);
g_free(event);
if (rtas_event_log_contains(mask, true)) {
qemu_irq_pulse(xics_get_qirq(spapr->xics, spapr->check_exception_irq));
}
return;
out_no_events:
rtas_st(rets, 0, RTAS_OUT_NO_ERRORS_FOUND);
}
| 1threat
|
static int parse_channel_name(char **arg, int *rchannel, int *rnamed)
{
char buf[8];
int len, i, channel_id = 0;
int64_t layout, layout0;
if (sscanf(*arg, " %7[A-Z] %n", buf, &len)) {
layout0 = layout = av_get_channel_layout(buf);
for (i = 32; i > 0; i >>= 1) {
if (layout >= (int64_t)1 << i) {
channel_id += i;
layout >>= i;
}
}
if (channel_id >= MAX_CHANNELS || layout0 != (int64_t)1 << channel_id)
return AVERROR(EINVAL);
*rchannel = channel_id;
*rnamed = 1;
*arg += len;
return 0;
}
if (sscanf(*arg, " c%d %n", &channel_id, &len) &&
channel_id >= 0 && channel_id < MAX_CHANNELS) {
*rchannel = channel_id;
*rnamed = 0;
*arg += len;
return 0;
}
return AVERROR(EINVAL);
}
| 1threat
|
Get max + 1 without removing zeroes in SQL server : I have a varchar field contains numbers in this format "00001" , "00002" etc
when I try to get the next number by using Max(Field) + 1 I get an integer "3" for example.
how can I get the resutl "00003" instead of "3"?
What I have tried:
Reply Modify the comment. Delete the comment.
here's an working example I've just figure it out, but i think there's must be an easier way:
SELECT TOP (1) { fn REPEAT(0, LEN(ItemId) - LEN(MAX(ItemId) + 1)) } + CAST(MAX(ItemId) + 1 AS varchar(7)) AS Expr1
FROM Items
GROUP BY ItemId
ORDER BY ItemId DESC
the last query gives the correct result "0004916"
| 0debug
|
static QError *qerror_from_info(const char *fmt, va_list *va)
{
QError *qerr;
qerr = qerror_new();
loc_save(&qerr->loc);
qerr->error = error_obj_from_fmt_no_fail(fmt, va);
qerr->err_msg = qerror_format(fmt, qerr->error);
return qerr;
}
| 1threat
|
Is there a way to only save value of unchecked checkbox in android? : Is there a way to save values from listview with checkboxes, but to save only unchecked values. I am using Android Studio for development.
| 0debug
|
i have six array elements, what usage is better than others, and why? : <p>i have six variables, what usage is better than others, and why?</p>
<pre><code>$a["1"];
$a1['1'];
$a2[1];
$b['b'];
$b1["b"];
$b2[b];
</code></pre>
<p>question is only about code optimization, can't really understand what of that is better than other</p>
| 0debug
|
Using bootstrap cards as a hyperlink : <p>I have a bootstrap card Which is used as a link.</p>
<p>Trying to wrap it with <code><a></code> changes all of the styling of the card.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<div class="card" style="width: 15rem; display: inline-block">
<img class="card-img-top" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=318%C3%97180&w=318&h=180" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Normal card</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
<a href="">
<div class="card" style="width: 15rem; display: inline-block">
<img class="card-img-top" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=318%C3%97180&w=318&h=180" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Wrapped with a tag</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
</a></code></pre>
</div>
</div>
</p>
<p>How should I wrap the card in order to preserve its looks and use it as a link?</p>
| 0debug
|
static int nbd_receive_list(QIOChannel *ioc, const char *want, bool *match,
Error **errp)
{
nbd_opt_reply reply;
uint32_t len;
uint32_t namelen;
char name[NBD_MAX_NAME_SIZE + 1];
int error;
if (nbd_receive_option_reply(ioc, NBD_OPT_LIST, &reply, errp) < 0) {
return -1;
}
error = nbd_handle_reply_err(ioc, &reply, errp);
if (error <= 0) {
*match = true;
return error;
}
len = reply.length;
if (reply.type == NBD_REP_ACK) {
if (len != 0) {
error_setg(errp, "length too long for option end");
nbd_send_opt_abort(ioc);
return -1;
}
return 0;
} else if (reply.type != NBD_REP_SERVER) {
error_setg(errp, "Unexpected reply type %" PRIx32 " expected %x",
reply.type, NBD_REP_SERVER);
nbd_send_opt_abort(ioc);
return -1;
}
if (len < sizeof(namelen) || len > NBD_MAX_BUFFER_SIZE) {
error_setg(errp, "incorrect option length %" PRIu32, len);
nbd_send_opt_abort(ioc);
return -1;
}
if (read_sync(ioc, &namelen, sizeof(namelen), errp) < 0) {
error_prepend(errp, "failed to read option name length");
nbd_send_opt_abort(ioc);
return -1;
}
namelen = be32_to_cpu(namelen);
len -= sizeof(namelen);
if (len < namelen) {
error_setg(errp, "incorrect option name length");
nbd_send_opt_abort(ioc);
return -1;
}
if (namelen != strlen(want)) {
if (drop_sync(ioc, len, errp) < 0) {
error_prepend(errp, "failed to skip export name with wrong length");
nbd_send_opt_abort(ioc);
return -1;
}
return 1;
}
assert(namelen < sizeof(name));
if (read_sync(ioc, name, namelen, errp) < 0) {
error_prepend(errp, "failed to read export name");
nbd_send_opt_abort(ioc);
return -1;
}
name[namelen] = '\0';
len -= namelen;
if (drop_sync(ioc, len, errp) < 0) {
error_prepend(errp, "failed to read export description");
nbd_send_opt_abort(ioc);
return -1;
}
if (!strcmp(name, want)) {
*match = true;
}
return 1;
}
| 1threat
|
How can I access the database in a service in android? : public class BackServices extends BroadcastReceiver {
private boolean screenOff;
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, UpdateService.class));
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
I need to access the database and collect the phone number from it how can I do that.
| 0debug
|
static void scsi_write_do_fua(SCSIDiskReq *r)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
if (r->req.io_canceled) {
scsi_req_cancel_complete(&r->req);
goto done;
}
if (scsi_is_cmd_fua(&r->req.cmd)) {
block_acct_start(bdrv_get_stats(s->qdev.conf.bs), &r->acct, 0,
BLOCK_ACCT_FLUSH);
r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);
return;
}
scsi_req_complete(&r->req, GOOD);
done:
scsi_req_unref(&r->req);
}
| 1threat
|
Pass a typed function as a parameter in Dart : <p>I know the <a href="https://api.dartlang.org/stable/1.22.1/dart-core/Function-class.html" rel="noreferrer" title="Function">Function</a> class can be passed as a parameter to another function, like this:</p>
<pre><code>void doSomething(Function f) {
f(123);
}
</code></pre>
<p>But is there a way to constrain the arguments and the return type of the function parameter?</p>
<p>For instance, in this case <code>f</code> is being invoked directly on an integer, but what if it was a function accepting a different type?</p>
<p>I tried passing it as a <code>Function<Integer></code>, but Function is not a parametric type.</p>
<p>Is there any other way to specify the signature of the function being passed as a parameter?</p>
| 0debug
|
How to transfer project from one group to a user in gitlab CE 9? : <p>I want to transfer a project from a group to another user. For e.g from <a href="https://gitlab.local/groupname/projectname" rel="noreferrer">https://gitlab.local/groupname/projectname</a> to <a href="https://gitlab.local/userA/projectname" rel="noreferrer">https://gitlab.local/userA/projectname</a></p>
<p>How can I acheive this? I have gitadmin permissions.</p>
| 0debug
|
Finding out if a big number is a perfect square numbers using C# : <p>Is there a fast and simple way to write a program in C#, that finds out if a big (something like 25 digits big) number is a perfect square or not?</p>
<p>Perfect squares are the numbers: 0^2=0,1^2=1,2^2=4,3^2=9,4^2=16,...</p>
| 0debug
|
int kvm_log_start(target_phys_addr_t phys_addr, target_phys_addr_t end_addr)
{
return kvm_dirty_pages_log_change(phys_addr, end_addr,
KVM_MEM_LOG_DIRTY_PAGES,
KVM_MEM_LOG_DIRTY_PAGES);
}
| 1threat
|
static always_inline void gen_qemu_lds (TCGv t0, TCGv t1, int flags)
{
TCGv tmp = tcg_temp_new(TCG_TYPE_I32);
tcg_gen_qemu_ld32u(tmp, t1, flags);
tcg_gen_helper_1_1(helper_memory_to_s, t0, tmp);
tcg_temp_free(tmp);
}
| 1threat
|
yuv2rgb_1_c_template(SwsContext *c, const int16_t *buf0,
const int16_t *ubuf[2], const int16_t *vbuf[2],
const int16_t *abuf0, uint8_t *dest, int dstW,
int uvalpha, int y, enum PixelFormat target,
int hasAlpha)
{
const int16_t *ubuf0 = ubuf[0], *vbuf0 = vbuf[0];
int i;
if (uvalpha < 2048) {
for (i = 0; i < (dstW >> 1); i++) {
int Y1 = buf0[i * 2] >> 7;
int Y2 = buf0[i * 2 + 1] >> 7;
int U = ubuf0[i] >> 7;
int V = vbuf0[i] >> 7;
int A1, A2;
const void *r = c->table_rV[V],
*g = (c->table_gU[U] + c->table_gV[V]),
*b = c->table_bU[U];
if (hasAlpha) {
A1 = abuf0[i * 2 ] >> 7;
A2 = abuf0[i * 2 + 1] >> 7;
}
yuv2rgb_write(dest, i, Y1, Y2, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,
r, g, b, y, target, hasAlpha);
}
} else {
const int16_t *ubuf1 = ubuf[1], *vbuf1 = vbuf[1];
for (i = 0; i < (dstW >> 1); i++) {
int Y1 = buf0[i * 2] >> 7;
int Y2 = buf0[i * 2 + 1] >> 7;
int U = (ubuf0[i] + ubuf1[i]) >> 8;
int V = (vbuf0[i] + vbuf1[i]) >> 8;
int A1, A2;
const void *r = c->table_rV[V],
*g = (c->table_gU[U] + c->table_gV[V]),
*b = c->table_bU[U];
if (hasAlpha) {
A1 = abuf0[i * 2 ] >> 7;
A2 = abuf0[i * 2 + 1] >> 7;
}
yuv2rgb_write(dest, i, Y1, Y2, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,
r, g, b, y, target, hasAlpha);
}
}
}
| 1threat
|
Is there a way to get the app group identifier from host app and share extension on iOS? : <p>I have set up App Groups for both my host app and the share extension. The identifier looks like "group.com.abc.xyzApp". Is there a way to get this string out programmatically?
Also, how do I detect if app groups are set programmatically? Is trying to initialize a file container or user defaults with the app group identifier enough to know?
Eg: </p>
<p><code>[[NSUserDefaults alloc] initWithSuiteName:@"group.com.abc.xyzApp"].</code></p>
| 0debug
|
How to change Facebook iOS SDK's done button color when login? : <p><a href="https://i.stack.imgur.com/Bunc3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Bunc3.png" alt="enter image description here"></a></p>
<p>My app use white UITabBarItem text color and orange UINavigationBar BarTintColor, when click the Login button added from Facebook SDK, it will popup a webview for login.</p>
<p>but the topbar background color always light gray, if I change the UITabBarItem color, other view will all changed, How can I only custom the button color in Facebook login view or change the navbar background color?</p>
| 0debug
|
static int pva_read_packet(AVFormatContext *s, AVPacket *pkt) {
ByteIOContext *pb = s->pb;
PVAContext *pvactx = s->priv_data;
int ret, syncword, streamid, reserved, flags, length, pts_flag;
int64_t pva_pts = AV_NOPTS_VALUE;
recover:
syncword = get_be16(pb);
streamid = get_byte(pb);
get_byte(pb);
reserved = get_byte(pb);
flags = get_byte(pb);
length = get_be16(pb);
pts_flag = flags & 0x10;
if (syncword != PVA_MAGIC) {
av_log(s, AV_LOG_ERROR, "invalid syncword\n");
return AVERROR(EIO);
}
if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) {
av_log(s, AV_LOG_ERROR, "invalid streamid\n");
return AVERROR(EIO);
}
if (reserved != 0x55) {
av_log(s, AV_LOG_WARNING, "expected reserved byte to be 0x55\n");
}
if (length > PVA_MAX_PAYLOAD_LENGTH) {
av_log(s, AV_LOG_ERROR, "invalid payload length %u\n", length);
return AVERROR(EIO);
}
if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) {
pva_pts = get_be32(pb);
length -= 4;
} else if (streamid == PVA_AUDIO_PAYLOAD) {
if (!pvactx->continue_pes) {
int pes_signal, pes_header_data_length, pes_packet_length,
pes_flags;
unsigned char pes_header_data[256];
pes_signal = get_be24(pb);
get_byte(pb);
pes_packet_length = get_be16(pb);
pes_flags = get_be16(pb);
pes_header_data_length = get_byte(pb);
if (pes_signal != 1) {
av_log(s, AV_LOG_WARNING, "expected signaled PES packet, "
"trying to recover\n");
url_fskip(pb, length - 9);
goto recover;
}
get_buffer(pb, pes_header_data, pes_header_data_length);
length -= 9 + pes_header_data_length;
pes_packet_length -= 3 + pes_header_data_length;
pvactx->continue_pes = pes_packet_length;
if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20)
pva_pts = ff_parse_pes_pts(pes_header_data);
}
pvactx->continue_pes -= length;
if (pvactx->continue_pes < 0) {
av_log(s, AV_LOG_WARNING, "audio data corruption\n");
pvactx->continue_pes = 0;
}
}
if ((ret = av_get_packet(pb, pkt, length)) <= 0)
return AVERROR(EIO);
pkt->stream_index = streamid - 1;
if (pva_pts != AV_NOPTS_VALUE)
pkt->pts = pva_pts;
return ret;
}
| 1threat
|
barplot in R programming language : I have this package called gapminder.
I am trying to do this
a. A bar chart showing the life expectancy for the United States over the years. (Data source: gapminder)
Make a barchart showing the life expectancy of the United States over the years. But I am not entirely sure how to do this.
Can anybody show me how to do this I did names(gapminder) and I get
"country" "continent" "year" "lifeExp" "pop" "gdpPercap"
| 0debug
|
combobox not working with sql connection reader :
`
private void comboBox45_SelectedIndexChanged(object sender, EventArgs e)
{
baglanti.Open();
string str = "select * from satilikkonutlar where ilanbasligi='" + comboBox45.Text.Trim() + "";
SqlCommand com = new SqlCommand(str, baglanti);
SqlDataReader reader = com.ExecuteReader(); ``
while (reader.Read())
{
textBox4.Text = reader["fiyat"].ToString();
}
reader.Close();
baglanti.Close();
enter code here
reader not working help me guys ty.
| 0debug
|
static int v9fs_do_open2(V9fsState *s, V9fsString *path, int flags, mode_t mode)
{
return s->ops->open2(&s->ctx, path->data, flags, mode);
}
| 1threat
|
Docker Store Vs Docker Hub : <p>Did anyone actually figure out the difference between "Docker Store" that Docker introduced at DockerCon2016 and "Docker Hub"? </p>
<p>Is Docker just trying to make a fancy version of Docker hub to have something like Apple Store, Android Store etc? or are there any specific use cases it is trying to solve by introducing this? I think, it can very well use Docker hub for providing trusted, validated etc. enterprise images as it is now providing official images. Then why "Docker Store" ??? </p>
| 0debug
|
Variable doesn't exist outside of post function (java, android studio) : How would i make it so that i can reference my variable tag_found outside of the TrakkRestClient.post function so i can check if both that and user_found are true and then run code based on that?
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RequestParams tag_params = new RequestParams("Tag_ID", tag_id.getText().toString());
TrakkRestClient.post("check/item", tag_params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] header, JSONObject response){
if (response.toString().contains("No")){
TrakkRestClient.post("log/add/in", tag_params, new JsonHttpResponseHandler());
Boolean tag_found = false;
}else if (response.toString().contains("found")){
Boolean tag_found = true;
}else{
show_err_tag();
}
Log.d("log",response.toString());
}
});
RequestParams user_params = new RequestParams("email", user_email.getText().toString());
TrakkRestClient.post("check/user", user_params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] header, JSONObject response){
if (response.toString().contains("found")){
final Boolean user_found = true;
}
else{
show_err_user();
}
Log.d("log",response.toString());
}
});
Log.d("tag",tag_found.toString());
| 0debug
|
static bool use_goto_tb(DisasContext *ctx, target_ulong dest)
{
if ((ctx->base.tb->cflags & CF_LAST_IO) || ctx->base.singlestep_enabled) {
return false;
}
return true;
}
| 1threat
|
Taking a list of integers and displaying them in reverse using arrays : <p>If my input is 1 2 3 the output is also coming out as 1 2 3, how do I make these numbers to display 3 2 1?</p>
<pre><code> public static void main(String[] args) {
// TODO code application logic here
Scanner s = new Scanner(System.in);
String text = s.nextLine();
String[] entries = text.split(" ");
int[] nums = new int[entries.length];
for(int i = 0; i < entries.length; i++){
nums[i] = Integer.parseInt(entries[i]);
}
for(int i = 0; i < entries.length; i++){
System.out.println(nums[i]);
}
}
</code></pre>
<p>}</p>
| 0debug
|
Why's my code wrong when looking for duplicates? : <p>I'm trying to solve this Leetcode problem <a href="https://leetcode.com/problems/contains-duplicate-ii/" rel="nofollow noreferrer">https://leetcode.com/problems/contains-duplicate-ii/</a></p>
<p>I'm not sure why my code's incorrect. I've followed the problem and tried to write it out as best as I could but it didn't work.</p>
<p>Can someone point out what I did wrong?</p>
<pre><code>class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
boolean flag = false;
int ans = 0;
for(int i = 0; i < nums.length; i++) {
for(int j = i + 1; j < nums.length; j++) {
if(nums[i] == nums[j]) {
flag = true;
}
if(flag) {
ans = Math.abs(nums[i] - nums[j]);
}
if(ans <= k) {
return true;
}
}
}
return false;
}
}
</code></pre>
| 0debug
|
How to unique identify each request in a ASP.NET Core 2 application (for logging) : <p>In a ASP.NET Core 2 application, I need a unique identifier (e.g. Guid) for each request so I can include that id in each log and understand the sequence of logs of each request.</p>
<p>This is not hard to write it myself, but I wonder if there is a builtin feature that I can use or a ASP.NET Core 2 way of achieving this.</p>
| 0debug
|
Combining two Id String : I just want to combine two **string uids** (28 digit alphanumeric) without concatenation ,ie by addition to create another uid that is unique as well. Any help is appreciated
| 0debug
|
How do I fix alembic's "Requested revision overlaps with other requested revisions"? : <p>I work on a team using alembic to manage db migrations. I recently pulled master, and tried to run <code>alembic upgrade heads</code>. I got the following message;</p>
<pre><code>INFO [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO [alembic.runtime.migration] Will assume transactional DDL.
ERROR [alembic.util.messaging] Requested revision a04c53fd8c74 overlaps with other requested revisions 453d88f67d34
FAILED: Requested revision a04c53fd8c74 overlaps with other requested revisions 453d88f67d34
</code></pre>
<p>I got the same message when I tried to run <code>alembic downgrade -1</code>. Running <code>alembic history</code> prints this;</p>
<pre><code>453d88f67d34 -> a04c53fd8c74 (label_1, label_2) (head), Create such and such tables.
2f15c778e709, 9NZSZX -> 453d88f67d34 (label_1, label_2) (mergepoint), empty message
b1861bb8b23f, b8aa3acdf260 -> 2f15c778e709 (label_1, label_2) (mergepoint), Merge heads b18 and b8a
(...many more old revisions)
</code></pre>
<p>which to me looks like a perfectly fine history. <code>alembic heads</code> reports <code>a04c53fd8c74 (label_1, label_2) (head)</code>. </p>
<p>The only thing that looks odd to me is that my alembic version db has two values in it;</p>
<pre><code>my_postgres=# SELECT * FROM alembic_version;
version_num
--------------
a04c53fd8c74
453d88f67d34
(2 rows)
</code></pre>
<p>The only reference I can find from googling the exception is the <a href="https://github.com/zzzeek/alembic/blob/2df9c52/alembic/script/revision.py#L623" rel="noreferrer">source code</a>, which I'd rather not read through.</p>
<p>How could this situation have come about? How should I fix it? What does "overlaps" mean?</p>
| 0debug
|
How Read a selected text from the drop down ? : I need to save the user selected text to the db.I tried 3 different ways but all of them return null for the selected
value. value1 or value2 or value3 returns null. What I am doing to wrong here ?
<div id="reasonsList" style="display: none">
@foreach (var reason in Model.CorrectionReasonsList)
{
<option>@(reason)</option>
}
</div>
var value = '<option selected="selected" value="' + sData + '">' + sData + '</option>';
var reasonsSelect = '<select id="correction_reason_dropdown" ' +
'multiple ' +
'style="min-width:115px" ' +
'data-select-options={"searchField":"false","noValueText":"Select One"))"} ' +
'class="select multiple-as-single compact correction-reason" ' +
'>';
reasonsSelect += value + $("#reasonsList").html();
reasonsSelect += "</select>";
$(nTd).html(reasonsSelect);
var value1 = $('#reasonsList:selected').val();
var value2 = $('#reasonsList:selected').find('option:selected').text();
var value3 = $('#reasonsList:selected').text();
| 0debug
|
static int decode_block_progressive(MJpegDecodeContext *s, int16_t *block,
uint8_t *last_nnz, int ac_index,
uint16_t *quant_matrix,
int ss, int se, int Al, int *EOBRUN)
{
int code, i, j, level, val, run;
if (*EOBRUN) {
(*EOBRUN)--;
return 0;
}
{
OPEN_READER(re, &s->gb);
for (i = ss; ; i++) {
UPDATE_CACHE(re, &s->gb);
GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
run = ((unsigned) code) >> 4;
code &= 0xF;
if (code) {
i += run;
if (code > MIN_CACHE_BITS - 16)
UPDATE_CACHE(re, &s->gb);
{
int cache = GET_CACHE(re, &s->gb);
int sign = (~cache) >> 31;
level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
}
LAST_SKIP_BITS(re, &s->gb, code);
if (i >= se) {
if (i == se) {
j = s->scantable.permutated[se];
block[j] = level * (quant_matrix[se] << Al);
break;
}
av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
return AVERROR_INVALIDDATA;
}
j = s->scantable.permutated[i];
block[j] = level * (quant_matrix[i] << Al);
} else {
if (run == 0xF) {
i += 15;
if (i >= se) {
av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
return AVERROR_INVALIDDATA;
}
} else {
val = (1 << run);
if (run) {
UPDATE_CACHE(re, &s->gb);
val += NEG_USR32(GET_CACHE(re, &s->gb), run);
LAST_SKIP_BITS(re, &s->gb, run);
}
*EOBRUN = val - 1;
break;
}
}
}
CLOSE_READER(re, &s->gb);
}
if (i > *last_nnz)
*last_nnz = i;
return 0;
}
| 1threat
|
How to arrange two divs vertically with a space between them? : <div>
<div>TOP<div>
<div>BOTTOM<div>
<div>
TOP and BOTTOM should be centered and I'd like to have an arbitrary space margin between them. I've seen many answers in SO suggesting to use `margin: 0 auto;` . But that (AFAIK) prevents me to set an space between those two divs.
| 0debug
|
static void pc_compat_2_2(MachineState *machine)
{
pc_compat_2_3(machine);
rsdp_in_ram = false;
machine->suppress_vmdesc = true;
}
| 1threat
|
static void gen_delayed_conditional_jump(DisasContext * ctx)
{
int l1;
TCGv ds;
l1 = gen_new_label();
ds = tcg_temp_new();
tcg_gen_andi_i32(ds, cpu_flags, DELAY_SLOT_TRUE);
tcg_gen_brcondi_i32(TCG_COND_NE, ds, 0, l1);
gen_goto_tb(ctx, 1, ctx->pc + 2);
gen_set_label(l1);
tcg_gen_andi_i32(cpu_flags, cpu_flags, ~DELAY_SLOT_TRUE);
gen_jump(ctx);
}
| 1threat
|
I am facing a SQLite syntax error in Android Studio.Need help fast, this part of my project which I have to submit tomorrow : The below code generates this error and my app crashes:
android.database.sqlite.SQLiteException: near "@kiit": syntax error (code 1): , while compiling: Select * from LoginMaster where UserID = 1505293@kiit.ac.in and Password = harshit999;
when I enter the userid and password which i have already successfully inserted into the table.
package com.harshit.csdp;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class LoginActivity extends AppCompatActivity {
private EditText kiitmail, pass;
private Spinner spn;
private TextInputLayout inputKiitMail;
SQLiteDatabase sqldb;
Button register, login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
sqldb = openOrCreateDatabase("xyza", Context.MODE_PRIVATE,null);
final String adminEmail = "admin@kiit.ac.in";
final String adminPass = "admin123";
final String adminStatus = "Administrator" ;
boolean firstRun = getSharedPreferences("preferences", MODE_PRIVATE).getBoolean("firstRun", true);
if(firstRun){
getSharedPreferences("preferences", MODE_PRIVATE).edit().putBoolean("firstRun", false).commit();
Toast.makeText(getApplicationContext(),"First Run Detected.\nDatabase, tables and Administrator account created.",Toast.LENGTH_LONG).show();
sqldb.execSQL("Create table LoginMaster(UserID varchar, Password varchar,Status varchar)");
sqldb.execSQL("insert into LoginMaster values('"+adminEmail+"','"+adminPass+"','"+adminStatus+"')");
sqldb.execSQL("Create table StudentMaster(UserID varchar, RollNo varchar,Batch varchar, Branch varchar, Degree varchar, JoiningYear varchar)");
sqldb.execSQL("Create table FacultyMaster(UserID varchar, Degree varchar, JoiningYear varchar)");
sqldb.execSQL("Create table StudentPersonalMaster(UserID varchar, Name varchar, DOB varchar, Gender varchar, Address varchar, MobNumber varchar)");
sqldb.execSQL("Create table FacultyPersonalMaster(UserID varchar, Name varchar, DOB varchar, Gender varchar, MobNumber varchar)");
sqldb.execSQL("Create table StudentAcademicMaster(UserID varchar, AcademicAchievement varchar,Sports varchar, Cultural varchar, Others varchar, HighSchool varchar)");
sqldb.execSQL("Create table StudentTechnicalMaster(UserID varchar, PLanguage varchar,Database varchar, OS varchar, Software varchar, OtherSkill varchar, IndustryExperience varchar, AcademicProject varchar)");
sqldb.execSQL("Create table NoticeMaster(UserID varchar, Title varchar,Content varchar, Type varchar, Date varchar)");
}
kiitmail = (EditText)findViewById(R.id.editText1);
pass = (EditText)findViewById(R.id.editText2);
spn = (Spinner)findViewById(R.id.spinner1);
login = (Button)findViewById(R.id.button1);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(spn.getSelectedItem().toString().equals(adminStatus)){
Intent intent = new Intent(getApplicationContext(),AdminPage.class);
startActivity(intent);
}
else if(verifyLogin()&&spn.getSelectedItem().toString().equals("Student")){
String km = kiitmail.getText().toString();
Intent studentPage = new Intent(LoginActivity.this, StudentPage.class);
studentPage.putExtra("uid",km);
startActivity(studentPage);
}
else{
Toast.makeText(getApplicationContext(),"Fuck you",Toast.LENGTH_LONG).show();
}
}
});
Typeface font = Typeface.createFromAsset( getAssets(), "fontawesome.ttf" );
TextView textView7 = (TextView)findViewById(R.id.textView7);
TextView textView8 = (TextView)findViewById(R.id.textView8);
textView7.setTypeface(font);
textView8.setTypeface(font);
register = (Button)findViewById(R.id.button2);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),InitialRegistrationActivity.class);
startActivity(i);
}
});
}
public boolean verifyLogin(){
String checkMailID = kiitmail.getText().toString();
String checkPassword = pass.getText().toString();
Cursor cursor = sqldb.rawQuery("Select * from LoginMaster where UserID = "+checkMailID+" and Password = "+checkPassword+";", null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
}
| 0debug
|
C safely taking absolute value of integer : <p>Consider following program (C99):</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
int main(void)
{
printf("Enter int in range %jd .. %jd:\n > ", INTMAX_MIN, INTMAX_MAX);
intmax_t i;
if (scanf("%jd", &i) == 1)
printf("Result: |%jd| = %jd\n", i, imaxabs(i));
}
</code></pre>
<p>Now as I understand it, this contains easily triggerable <em>undefined behaviour</em>, like this:</p>
<pre><code>Enter int in range -9223372036854775808 .. 9223372036854775807:
> -9223372036854775808
Result: |-9223372036854775808| = -9223372036854775808
</code></pre>
<p>Questions:</p>
<ol>
<li><p>Is this really undefined behaviour, as in "code is allowed to trigger any code path, which any code that stroke compiler's fancy", when user enters the bad number? Or is it some other flavor of not-completely-defined?</p></li>
<li><p>How would a pedantic programmer go about guarding against this, <em>without</em> making any assumptions not guaranteed by standard?</p></li>
</ol>
<p>(There are a few related questions, but I didn't find one which answers question 2 above, so if you suggest duplicate, please make sure it answers that.)</p>
| 0debug
|
int main (int argc, char **argv)
{
int ret = 0, got_frame;
if (argc != 4) {
fprintf(stderr, "usage: %s input_file video_output_file audio_output_file\n"
"API example program to show how to read frames from an input file.\n"
"This program reads frames from a file, decodes them, and writes decoded\n"
"video frames to a rawvideo file named video_output_file, and decoded\n"
"audio frames to a rawaudio file named audio_output_file.\n"
"\n", argv[0]);
exit(1);
}
src_filename = argv[1];
video_dst_filename = argv[2];
audio_dst_filename = argv[3];
av_register_all();
if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {
fprintf(stderr, "Could not open source file %s\n", src_filename);
exit(1);
}
if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
fprintf(stderr, "Could not find stream information\n");
exit(1);
}
if (open_codec_context(&video_stream_idx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) {
video_stream = fmt_ctx->streams[video_stream_idx];
video_dec_ctx = video_stream->codec;
video_dst_file = fopen(video_dst_filename, "wb");
if (!video_dst_file) {
fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
ret = 1;
goto end;
}
ret = av_image_alloc(video_dst_data, video_dst_linesize,
video_dec_ctx->width, video_dec_ctx->height,
video_dec_ctx->pix_fmt, 1);
if (ret < 0) {
fprintf(stderr, "Could not allocate raw video buffer\n");
goto end;
}
video_dst_bufsize = ret;
}
if (open_codec_context(&audio_stream_idx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) {
int nb_planes;
audio_stream = fmt_ctx->streams[audio_stream_idx];
audio_dec_ctx = audio_stream->codec;
audio_dst_file = fopen(audio_dst_filename, "wb");
if (!audio_dst_file) {
fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
ret = 1;
goto end;
}
nb_planes = av_sample_fmt_is_planar(audio_dec_ctx->sample_fmt) ?
audio_dec_ctx->channels : 1;
audio_dst_data = av_mallocz(sizeof(uint8_t *) * nb_planes);
if (!audio_dst_data) {
fprintf(stderr, "Could not allocate audio data buffers\n");
ret = AVERROR(ENOMEM);
goto end;
}
}
av_dump_format(fmt_ctx, 0, src_filename, 0);
if (!audio_stream && !video_stream) {
fprintf(stderr, "Could not find audio or video stream in the input, aborting\n");
ret = 1;
goto end;
}
frame = avcodec_alloc_frame();
if (!frame) {
fprintf(stderr, "Could not allocate frame\n");
ret = AVERROR(ENOMEM);
goto end;
}
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;
if (video_stream)
printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);
if (audio_stream)
printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename);
while (av_read_frame(fmt_ctx, &pkt) >= 0)
decode_packet(&got_frame, 0);
pkt.data = NULL;
pkt.size = 0;
do {
decode_packet(&got_frame, 1);
} while (got_frame);
printf("Demuxing succeeded.\n");
if (video_stream) {
printf("Play the output video file with the command:\n"
"ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",
av_get_pix_fmt_name(video_dec_ctx->pix_fmt), video_dec_ctx->width, video_dec_ctx->height,
video_dst_filename);
}
if (audio_stream) {
const char *fmt;
if ((ret = get_format_from_sample_fmt(&fmt, audio_dec_ctx->sample_fmt)) < 0)
goto end;
printf("Play the output audio file with the command:\n"
"ffplay -f %s -ac %d -ar %d %s\n",
fmt, audio_dec_ctx->channels, audio_dec_ctx->sample_rate,
audio_dst_filename);
}
end:
if (video_dec_ctx)
avcodec_close(video_dec_ctx);
if (audio_dec_ctx)
avcodec_close(audio_dec_ctx);
avformat_close_input(&fmt_ctx);
if (video_dst_file)
fclose(video_dst_file);
if (audio_dst_file)
fclose(audio_dst_file);
av_free(frame);
av_free(video_dst_data[0]);
av_free(audio_dst_data);
return ret < 0;
}
| 1threat
|
How to use string interpolation in style tag in Angular component? : <pre><code>@Component({
selector: 'app-style',
template: `
<style>
.test {
color: {{ textColor }}
}
</style>
`
})
export class StyleComponent {
textColor = "red";
}
</code></pre>
<p>This doesn't seem to be working and I need my styles to be dynamic and in some specific CSS class. Is there some other way I could do this?</p>
| 0debug
|
Javascript Regex: Return number of the last occurrence of a pattern : I'm trying, with no sucess, to get a number inside of the **last occurence** of a pattern inside of a HTML code. The pattern is **data\\[\d{1,3}\\]**. How can i get the number "03" in the below example?
<body>
<h2>JavaScript Regular Expressions</h2>
<p>TEST</p>
<p>data[01]</p>
<button onclick="myFunction()">Try it</button>
<p>data[02]</p>
<p>TEST</p>
<p id="demo" test=data[03]></p>
</body>
I tried many combinations with $, but i could not make it work.
| 0debug
|
static int vorbis_parse_setup_hdr_floors(vorbis_context *vc)
{
GetBitContext *gb = &vc->gb;
int i,j,k;
vc->floor_count = get_bits(gb, 6) + 1;
vc->floors = av_mallocz(vc->floor_count * sizeof(*vc->floors));
for (i = 0; i < vc->floor_count; ++i) {
vorbis_floor *floor_setup = &vc->floors[i];
floor_setup->floor_type = get_bits(gb, 16);
av_dlog(NULL, " %d. floor type %d \n", i, floor_setup->floor_type);
if (floor_setup->floor_type == 1) {
int maximum_class = -1;
unsigned rangebits, rangemax, floor1_values = 2;
floor_setup->decode = vorbis_floor1_decode;
floor_setup->data.t1.partitions = get_bits(gb, 5);
av_dlog(NULL, " %d.floor: %d partitions \n",
i, floor_setup->data.t1.partitions);
for (j = 0; j < floor_setup->data.t1.partitions; ++j) {
floor_setup->data.t1.partition_class[j] = get_bits(gb, 4);
if (floor_setup->data.t1.partition_class[j] > maximum_class)
maximum_class = floor_setup->data.t1.partition_class[j];
av_dlog(NULL, " %d. floor %d partition class %d \n",
i, j, floor_setup->data.t1.partition_class[j]);
av_dlog(NULL, " maximum class %d \n", maximum_class);
for (j = 0; j <= maximum_class; ++j) {
floor_setup->data.t1.class_dimensions[j] = get_bits(gb, 3) + 1;
floor_setup->data.t1.class_subclasses[j] = get_bits(gb, 2);
av_dlog(NULL, " %d floor %d class dim: %d subclasses %d \n", i, j,
floor_setup->data.t1.class_dimensions[j],
floor_setup->data.t1.class_subclasses[j]);
if (floor_setup->data.t1.class_subclasses[j]) {
GET_VALIDATED_INDEX(floor_setup->data.t1.class_masterbook[j], 8, vc->codebook_count)
av_dlog(NULL, " masterbook: %d \n", floor_setup->data.t1.class_masterbook[j]);
for (k = 0; k < (1 << floor_setup->data.t1.class_subclasses[j]); ++k) {
int16_t bits = get_bits(gb, 8) - 1;
if (bits != -1)
VALIDATE_INDEX(bits, vc->codebook_count)
floor_setup->data.t1.subclass_books[j][k] = bits;
av_dlog(NULL, " book %d. : %d \n", k, floor_setup->data.t1.subclass_books[j][k]);
floor_setup->data.t1.multiplier = get_bits(gb, 2) + 1;
floor_setup->data.t1.x_list_dim = 2;
for (j = 0; j < floor_setup->data.t1.partitions; ++j)
floor_setup->data.t1.x_list_dim+=floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]];
floor_setup->data.t1.list = av_mallocz(floor_setup->data.t1.x_list_dim *
sizeof(*floor_setup->data.t1.list));
rangebits = get_bits(gb, 4);
rangemax = (1 << rangebits);
if (rangemax > vc->blocksize[1] / 2) {
"Floor value is too large for blocksize: %u (%"PRIu32")\n",
rangemax, vc->blocksize[1] / 2);
floor_setup->data.t1.list[0].x = 0;
floor_setup->data.t1.list[1].x = rangemax;
for (j = 0; j < floor_setup->data.t1.partitions; ++j) {
for (k = 0; k < floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]]; ++k, ++floor1_values) {
floor_setup->data.t1.list[floor1_values].x = get_bits(gb, rangebits);
av_dlog(NULL, " %u. floor1 Y coord. %d\n", floor1_values,
floor_setup->data.t1.list[floor1_values].x);
if (ff_vorbis_ready_floor1_list(vc->avccontext,
floor_setup->data.t1.list,
floor_setup->data.t1.x_list_dim)) {
} else if (floor_setup->floor_type == 0) {
unsigned max_codebook_dim = 0;
floor_setup->decode = vorbis_floor0_decode;
floor_setup->data.t0.order = get_bits(gb, 8);
floor_setup->data.t0.rate = get_bits(gb, 16);
floor_setup->data.t0.bark_map_size = get_bits(gb, 16);
floor_setup->data.t0.amplitude_bits = get_bits(gb, 6);
if (floor_setup->data.t0.amplitude_bits == 0) {
"Floor 0 amplitude bits is 0.\n");
floor_setup->data.t0.amplitude_offset = get_bits(gb, 8);
floor_setup->data.t0.num_books = get_bits(gb, 4) + 1;
floor_setup->data.t0.book_list =
av_malloc(floor_setup->data.t0.num_books);
if (!floor_setup->data.t0.book_list)
return AVERROR(ENOMEM);
{
int idx;
unsigned book_idx;
for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {
GET_VALIDATED_INDEX(book_idx, 8, vc->codebook_count)
floor_setup->data.t0.book_list[idx] = book_idx;
if (vc->codebooks[book_idx].dimensions > max_codebook_dim)
max_codebook_dim = vc->codebooks[book_idx].dimensions;
create_map(vc, i);
floor_setup->data.t0.lsp =
av_malloc((floor_setup->data.t0.order + 1 + max_codebook_dim)
* sizeof(*floor_setup->data.t0.lsp));
if (!floor_setup->data.t0.lsp)
return AVERROR(ENOMEM);
av_dlog(NULL, "floor0 order: %u\n", floor_setup->data.t0.order);
av_dlog(NULL, "floor0 rate: %u\n", floor_setup->data.t0.rate);
av_dlog(NULL, "floor0 bark map size: %u\n",
floor_setup->data.t0.bark_map_size);
av_dlog(NULL, "floor0 amplitude bits: %u\n",
floor_setup->data.t0.amplitude_bits);
av_dlog(NULL, "floor0 amplitude offset: %u\n",
floor_setup->data.t0.amplitude_offset);
av_dlog(NULL, "floor0 number of books: %u\n",
floor_setup->data.t0.num_books);
av_dlog(NULL, "floor0 book list pointer: %p\n",
floor_setup->data.t0.book_list);
{
int idx;
for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {
av_dlog(NULL, " Book %d: %u\n", idx + 1,
floor_setup->data.t0.book_list[idx]);
} else {
av_log(vc->avccontext, AV_LOG_ERROR, "Invalid floor type!\n");
return 0;
| 1threat
|
Developing a messenger : <p>So I’m developing a chat messenger app like WhatsApp but I’m trying to decide the best way to get the messages between phones. A lecturer of mine mentioned using a router but I couldn’t understand how that would work. Any ideas ? </p>
| 0debug
|
how to use sub query in sql? : i have 4 tables :
Travelers (TravelerID,FirstName,LastName)
Guides(GuideID,FirstName,LastName)
Locations(LocationID,LocationName)
Trips(TravelerID,GuideID,LocationID,Stars,StartDate,ReturnDate)
I want to return per guide the name of location which he guided the maximum number of travelers .
i have tried to use this sub query but it doesn't work :
SELECT G.FirstName,L.LocationName,count(distinct(TravelerID))as number_of_travelers_per_guide
FROM Guides AS G LEFT JOIN Trips AS T USING (GuideID) LEFT JOIN Locations AS L USING (LocationID)
GROUP BY G.FirstName,L.LocationName
HAVING max((SELECT T1.number_of_travelers_per_guide FROM Trips AS T1 WHERE T.GuideID=T1.GuideID))
;
i will appreciate any help
| 0debug
|
static int tiff_decode_tag(TiffContext *s)
{
unsigned tag, type, count, off, value = 0;
int i, j, k, pos, start;
int ret;
uint32_t *pal;
double *dp;
tag = tget_short(&s->gb, s->le);
type = tget_short(&s->gb, s->le);
count = tget_long(&s->gb, s->le);
off = tget_long(&s->gb, s->le);
start = bytestream2_tell(&s->gb);
if (type == 0 || type >= FF_ARRAY_ELEMS(type_sizes)) {
av_log(s->avctx, AV_LOG_DEBUG, "Unknown tiff type (%u) encountered\n",
type);
return 0;
}
if (count == 1) {
switch (type) {
case TIFF_BYTE:
case TIFF_SHORT:
bytestream2_seek(&s->gb, -4, SEEK_CUR);
value = tget(&s->gb, type, s->le);
break;
case TIFF_LONG:
value = off;
break;
case TIFF_STRING:
if (count <= 4) {
bytestream2_seek(&s->gb, -4, SEEK_CUR);
break;
}
default:
value = UINT_MAX;
bytestream2_seek(&s->gb, off, SEEK_SET);
}
} else {
if (count <= 4 && type_sizes[type] * count <= 4) {
bytestream2_seek(&s->gb, -4, SEEK_CUR);
} else {
bytestream2_seek(&s->gb, off, SEEK_SET);
}
}
switch (tag) {
case TIFF_WIDTH:
s->width = value;
break;
case TIFF_HEIGHT:
s->height = value;
break;
case TIFF_BPP:
s->bppcount = count;
if (count > 4) {
av_log(s->avctx, AV_LOG_ERROR,
"This format is not supported (bpp=%d, %d components)\n",
s->bpp, count);
return AVERROR_INVALIDDATA;
}
if (count == 1)
s->bpp = value;
else {
switch (type) {
case TIFF_BYTE:
s->bpp = (off & 0xFF) + ((off >> 8) & 0xFF) +
((off >> 16) & 0xFF) + ((off >> 24) & 0xFF);
break;
case TIFF_SHORT:
case TIFF_LONG:
s->bpp = 0;
if (bytestream2_get_bytes_left(&s->gb) < type_sizes[type] * count)
return AVERROR_INVALIDDATA;
for (i = 0; i < count; i++)
s->bpp += tget(&s->gb, type, s->le);
break;
default:
s->bpp = -1;
}
}
break;
case TIFF_SAMPLES_PER_PIXEL:
if (count != 1) {
av_log(s->avctx, AV_LOG_ERROR,
"Samples per pixel requires a single value, many provided\n");
return AVERROR_INVALIDDATA;
}
if (s->bppcount == 1)
s->bpp *= value;
s->bppcount = value;
break;
case TIFF_COMPR:
s->compr = value;
s->predictor = 0;
switch (s->compr) {
case TIFF_RAW:
case TIFF_PACKBITS:
case TIFF_LZW:
case TIFF_CCITT_RLE:
break;
case TIFF_G3:
case TIFF_G4:
s->fax_opts = 0;
break;
case TIFF_DEFLATE:
case TIFF_ADOBE_DEFLATE:
#if CONFIG_ZLIB
break;
#else
av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
return AVERROR(ENOSYS);
#endif
case TIFF_JPEG:
case TIFF_NEWJPEG:
av_log(s->avctx, AV_LOG_ERROR,
"JPEG compression is not supported\n");
return AVERROR_PATCHWELCOME;
default:
av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",
s->compr);
return AVERROR_INVALIDDATA;
}
break;
case TIFF_ROWSPERSTRIP:
if (type == TIFF_LONG && value == UINT_MAX)
value = s->height;
if (value < 1) {
av_log(s->avctx, AV_LOG_ERROR,
"Incorrect value of rows per strip\n");
return AVERROR_INVALIDDATA;
}
s->rps = value;
break;
case TIFF_STRIP_OFFS:
if (count == 1) {
s->strippos = 0;
s->stripoff = value;
} else
s->strippos = off;
s->strips = count;
if (s->strips == 1)
s->rps = s->height;
s->sot = type;
if (s->strippos > bytestream2_size(&s->gb)) {
av_log(s->avctx, AV_LOG_ERROR,
"Tag referencing position outside the image\n");
return AVERROR_INVALIDDATA;
}
break;
case TIFF_STRIP_SIZE:
if (count == 1) {
s->stripsizesoff = 0;
s->stripsize = value;
s->strips = 1;
} else {
s->stripsizesoff = off;
}
s->strips = count;
s->sstype = type;
if (s->stripsizesoff > bytestream2_size(&s->gb)) {
av_log(s->avctx, AV_LOG_ERROR,
"Tag referencing position outside the image\n");
return AVERROR_INVALIDDATA;
}
break;
case TIFF_TILE_BYTE_COUNTS:
case TIFF_TILE_LENGTH:
case TIFF_TILE_OFFSETS:
case TIFF_TILE_WIDTH:
av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n");
return AVERROR_PATCHWELCOME;
break;
case TIFF_PREDICTOR:
s->predictor = value;
break;
case TIFF_INVERT:
switch (value) {
case 0:
s->invert = 1;
break;
case 1:
s->invert = 0;
break;
case 2:
case 3:
break;
default:
av_log(s->avctx, AV_LOG_ERROR, "Color mode %d is not supported\n",
value);
return AVERROR_INVALIDDATA;
}
break;
case TIFF_FILL_ORDER:
if (value < 1 || value > 2) {
av_log(s->avctx, AV_LOG_ERROR,
"Unknown FillOrder value %d, trying default one\n", value);
value = 1;
}
s->fill_order = value - 1;
break;
case TIFF_PAL:
pal = (uint32_t *) s->palette;
off = type_sizes[type];
if (count / 3 > 256 || bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3)
return AVERROR_INVALIDDATA;
off = (type_sizes[type] - 1) << 3;
for (k = 2; k >= 0; k--) {
for (i = 0; i < count / 3; i++) {
if (k == 2)
pal[i] = 0xFFU << 24;
j = (tget(&s->gb, type, s->le) >> off) << (k * 8);
pal[i] |= j;
}
}
s->palette_is_set = 1;
break;
case TIFF_PLANAR:
if (value == 2) {
av_log(s->avctx, AV_LOG_ERROR, "Planar format is not supported\n");
return AVERROR_PATCHWELCOME;
}
break;
case TIFF_T4OPTIONS:
if (s->compr == TIFF_G3)
s->fax_opts = value;
break;
case TIFF_T6OPTIONS:
if (s->compr == TIFF_G4)
s->fax_opts = value;
break;
#define ADD_METADATA(count, name, sep)\
if ((ret = add_metadata(count, type, name, sep, s)) < 0) {\
av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\
return ret;\
}
case TIFF_MODEL_PIXEL_SCALE:
ADD_METADATA(count, "ModelPixelScaleTag", NULL);
break;
case TIFF_MODEL_TRANSFORMATION:
ADD_METADATA(count, "ModelTransformationTag", NULL);
break;
case TIFF_MODEL_TIEPOINT:
ADD_METADATA(count, "ModelTiepointTag", NULL);
break;
case TIFF_GEO_KEY_DIRECTORY:
ADD_METADATA(1, "GeoTIFF_Version", NULL);
ADD_METADATA(2, "GeoTIFF_Key_Revision", ".");
s->geotag_count = tget_short(&s->gb, s->le);
if (s->geotag_count > count / 4 - 1) {
s->geotag_count = count / 4 - 1;
av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n");
}
if (bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4)
return -1;
s->geotags = av_mallocz(sizeof(TiffGeoTag) * s->geotag_count);
if (!s->geotags) {
av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
return AVERROR(ENOMEM);
}
for (i = 0; i < s->geotag_count; i++) {
s->geotags[i].key = tget_short(&s->gb, s->le);
s->geotags[i].type = tget_short(&s->gb, s->le);
s->geotags[i].count = tget_short(&s->gb, s->le);
if (!s->geotags[i].type)
s->geotags[i].val = get_geokey_val(s->geotags[i].key, tget_short(&s->gb, s->le));
else
s->geotags[i].offset = tget_short(&s->gb, s->le);
}
break;
case TIFF_GEO_DOUBLE_PARAMS:
if (count >= INT_MAX / sizeof(int64_t))
return AVERROR_INVALIDDATA;
if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
return AVERROR_INVALIDDATA;
dp = av_malloc(count * sizeof(double));
if (!dp) {
av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
return AVERROR(ENOMEM);
}
for (i = 0; i < count; i++)
dp[i] = tget_double(&s->gb, s->le);
for (i = 0; i < s->geotag_count; i++) {
if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) {
if (s->geotags[i].count == 0
|| s->geotags[i].offset + s->geotags[i].count > count) {
av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
} else {
char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", ");
if (!ap) {
av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
av_freep(&dp);
return AVERROR(ENOMEM);
}
s->geotags[i].val = ap;
}
}
}
av_freep(&dp);
break;
case TIFF_GEO_ASCII_PARAMS:
pos = bytestream2_tell(&s->gb);
for (i = 0; i < s->geotag_count; i++) {
if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) {
if (s->geotags[i].count == 0
|| s->geotags[i].offset + s->geotags[i].count > count) {
av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
} else {
char *ap;
bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET);
if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count)
return AVERROR_INVALIDDATA;
ap = av_malloc(s->geotags[i].count);
if (!ap) {
av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
return AVERROR(ENOMEM);
}
bytestream2_get_bufferu(&s->gb, ap, s->geotags[i].count);
ap[s->geotags[i].count - 1] = '\0';
s->geotags[i].val = ap;
}
}
}
break;
case TIFF_ARTIST:
ADD_METADATA(count, "artist", NULL);
break;
case TIFF_COPYRIGHT:
ADD_METADATA(count, "copyright", NULL);
break;
case TIFF_DATE:
ADD_METADATA(count, "date", NULL);
break;
case TIFF_DOCUMENT_NAME:
ADD_METADATA(count, "document_name", NULL);
break;
case TIFF_HOST_COMPUTER:
ADD_METADATA(count, "computer", NULL);
break;
case TIFF_IMAGE_DESCRIPTION:
ADD_METADATA(count, "description", NULL);
break;
case TIFF_MAKE:
ADD_METADATA(count, "make", NULL);
break;
case TIFF_MODEL:
ADD_METADATA(count, "model", NULL);
break;
case TIFF_PAGE_NAME:
ADD_METADATA(count, "page_name", NULL);
break;
case TIFF_PAGE_NUMBER:
ADD_METADATA(count, "page_number", " / ");
break;
case TIFF_SOFTWARE_NAME:
ADD_METADATA(count, "software", NULL);
break;
default:
av_log(s->avctx, AV_LOG_DEBUG, "Unknown or unsupported tag %d/0X%0X\n",
tag, tag);
}
bytestream2_seek(&s->gb, start, SEEK_SET);
return 0;
}
| 1threat
|
static void ide_atapi_cmd(IDEState *s)
{
const uint8_t *packet;
uint8_t *buf;
int max_len;
packet = s->io_buffer;
buf = s->io_buffer;
#ifdef DEBUG_IDE_ATAPI
{
int i;
printf("ATAPI limit=0x%x packet:", s->lcyl | (s->hcyl << 8));
for(i = 0; i < ATAPI_PACKET_SIZE; i++) {
printf(" %02x", packet[i]);
printf("\n");
#endif
if (s->sense_key == SENSE_UNIT_ATTENTION &&
s->io_buffer[0] != GPCMD_REQUEST_SENSE &&
s->io_buffer[0] != GPCMD_INQUIRY) {
ide_atapi_cmd_check_status(s);
return;
switch(s->io_buffer[0]) {
case GPCMD_TEST_UNIT_READY:
if (bdrv_is_inserted(s->bs) && !s->cdrom_changed) {
ide_atapi_cmd_ok(s);
} else {
s->cdrom_changed = 0;
ide_atapi_cmd_error(s, SENSE_NOT_READY,
ASC_MEDIUM_NOT_PRESENT);
case GPCMD_MODE_SENSE_6:
case GPCMD_MODE_SENSE_10:
{
int action, code;
if (packet[0] == GPCMD_MODE_SENSE_10)
else
max_len = packet[4];
action = packet[2] >> 6;
code = packet[2] & 0x3f;
switch(action) {
case 0:
switch(code) {
case GPMODE_R_W_ERROR_PAGE:
cpu_to_ube16(&buf[0], 16 + 6);
buf[2] = 0x70;
buf[3] = 0;
buf[4] = 0;
buf[5] = 0;
buf[6] = 0;
buf[7] = 0;
buf[8] = 0x01;
buf[9] = 0x06;
buf[10] = 0x00;
buf[11] = 0x05;
buf[12] = 0x00;
buf[13] = 0x00;
buf[14] = 0x00;
buf[15] = 0x00;
ide_atapi_cmd_reply(s, 16, max_len);
case GPMODE_AUDIO_CTL_PAGE:
cpu_to_ube16(&buf[0], 24 + 6);
buf[2] = 0x70;
buf[3] = 0;
buf[4] = 0;
buf[5] = 0;
buf[6] = 0;
buf[7] = 0;
buf[17] = 0;
buf[19] = 0;
buf[21] = 0;
buf[23] = 0;
ide_atapi_cmd_reply(s, 24, max_len);
case GPMODE_CAPABILITIES_PAGE:
cpu_to_ube16(&buf[0], 28 + 6);
buf[2] = 0x70;
buf[3] = 0;
buf[4] = 0;
buf[5] = 0;
buf[6] = 0;
buf[7] = 0;
buf[8] = 0x2a;
buf[9] = 0x12;
buf[10] = 0x00;
buf[11] = 0x00;
buf[12] = 0x71;
buf[13] = 3 << 5;
buf[14] = (1 << 0) | (1 << 3) | (1 << 5);
if (bdrv_is_locked(s->bs))
buf[6] |= 1 << 1;
buf[15] = 0x00;
cpu_to_ube16(&buf[16], 706);
buf[18] = 0;
buf[19] = 2;
cpu_to_ube16(&buf[20], 512);
cpu_to_ube16(&buf[22], 706);
buf[24] = 0;
buf[25] = 0;
buf[26] = 0;
buf[27] = 0;
ide_atapi_cmd_reply(s, 28, max_len);
default:
goto error_cmd;
case 1:
goto error_cmd;
case 2:
goto error_cmd;
default:
case 3:
ASC_SAVING_PARAMETERS_NOT_SUPPORTED);
case GPCMD_REQUEST_SENSE:
max_len = packet[4];
memset(buf, 0, 18);
buf[0] = 0x70 | (1 << 7);
buf[2] = s->sense_key;
buf[7] = 10;
buf[12] = s->asc;
if (s->sense_key == SENSE_UNIT_ATTENTION)
s->sense_key = SENSE_NONE;
ide_atapi_cmd_reply(s, 18, max_len);
case GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL:
if (bdrv_is_inserted(s->bs)) {
bdrv_set_locked(s->bs, packet[4] & 1);
ide_atapi_cmd_ok(s);
} else {
ide_atapi_cmd_error(s, SENSE_NOT_READY,
ASC_MEDIUM_NOT_PRESENT);
case GPCMD_READ_10:
case GPCMD_READ_12:
{
int nb_sectors, lba;
if (packet[0] == GPCMD_READ_10)
nb_sectors = ube16_to_cpu(packet + 7);
else
nb_sectors = ube32_to_cpu(packet + 6);
lba = ube32_to_cpu(packet + 2);
if (nb_sectors == 0) {
ide_atapi_cmd_ok(s);
ide_atapi_cmd_read(s, lba, nb_sectors, 2048);
case GPCMD_READ_CD:
{
int nb_sectors, lba, transfer_request;
nb_sectors = (packet[6] << 16) | (packet[7] << 8) | packet[8];
lba = ube32_to_cpu(packet + 2);
if (nb_sectors == 0) {
ide_atapi_cmd_ok(s);
transfer_request = packet[9];
switch(transfer_request & 0xf8) {
case 0x00:
ide_atapi_cmd_ok(s);
case 0x10:
ide_atapi_cmd_read(s, lba, nb_sectors, 2048);
case 0xf8:
ide_atapi_cmd_read(s, lba, nb_sectors, 2352);
default:
case GPCMD_SEEK:
{
unsigned int lba;
uint64_t total_sectors;
bdrv_get_geometry(s->bs, &total_sectors);
total_sectors >>= 2;
if (total_sectors == 0) {
ide_atapi_cmd_error(s, SENSE_NOT_READY,
ASC_MEDIUM_NOT_PRESENT);
lba = ube32_to_cpu(packet + 2);
if (lba >= total_sectors) {
ASC_LOGICAL_BLOCK_OOR);
ide_atapi_cmd_ok(s);
case GPCMD_START_STOP_UNIT:
{
int start, eject, err = 0;
start = packet[4] & 1;
eject = (packet[4] >> 1) & 1;
if (eject) {
err = bdrv_eject(s->bs, !start);
switch (err) {
case 0:
ide_atapi_cmd_ok(s);
case -EBUSY:
ide_atapi_cmd_error(s, SENSE_NOT_READY,
ASC_MEDIA_REMOVAL_PREVENTED);
default:
ide_atapi_cmd_error(s, SENSE_NOT_READY,
ASC_MEDIUM_NOT_PRESENT);
case GPCMD_MECHANISM_STATUS:
{
max_len = ube16_to_cpu(packet + 8);
cpu_to_ube16(buf, 0);
buf[2] = 0;
buf[3] = 0;
buf[4] = 0;
buf[5] = 1;
cpu_to_ube16(buf + 6, 0);
ide_atapi_cmd_reply(s, 8, max_len);
case GPCMD_READ_TOC_PMA_ATIP:
{
int format, msf, start_track, len;
uint64_t total_sectors;
bdrv_get_geometry(s->bs, &total_sectors);
total_sectors >>= 2;
if (total_sectors == 0) {
ide_atapi_cmd_error(s, SENSE_NOT_READY,
ASC_MEDIUM_NOT_PRESENT);
format = packet[9] >> 6;
msf = (packet[1] >> 1) & 1;
start_track = packet[6];
switch(format) {
case 0:
len = cdrom_read_toc(total_sectors, buf, msf, start_track);
if (len < 0)
goto error_cmd;
ide_atapi_cmd_reply(s, len, max_len);
case 1:
memset(buf, 0, 12);
buf[1] = 0x0a;
buf[2] = 0x01;
buf[3] = 0x01;
ide_atapi_cmd_reply(s, 12, max_len);
case 2:
len = cdrom_read_toc_raw(total_sectors, buf, msf, start_track);
if (len < 0)
goto error_cmd;
ide_atapi_cmd_reply(s, len, max_len);
default:
error_cmd:
case GPCMD_READ_CDVD_CAPACITY:
{
uint64_t total_sectors;
bdrv_get_geometry(s->bs, &total_sectors);
total_sectors >>= 2;
if (total_sectors == 0) {
ide_atapi_cmd_error(s, SENSE_NOT_READY,
ASC_MEDIUM_NOT_PRESENT);
cpu_to_ube32(buf, total_sectors - 1);
cpu_to_ube32(buf + 4, 2048);
ide_atapi_cmd_reply(s, 8, 8);
case GPCMD_READ_DVD_STRUCTURE:
{
int media = packet[1];
int format = packet[7];
int ret;
max_len = ube16_to_cpu(packet + 8);
if (format < 0xff) {
if (media_is_cd(s)) {
ASC_INCOMPATIBLE_FORMAT);
} else if (!media_present(s)) {
memset(buf, 0, max_len > IDE_DMA_BUF_SECTORS * 512 + 4 ?
IDE_DMA_BUF_SECTORS * 512 + 4 : max_len);
switch (format) {
case 0x00 ... 0x7f:
case 0xff:
if (media == 0) {
ret = ide_dvd_read_structure(s, format, packet, buf);
if (ret < 0)
ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST, -ret);
else
ide_atapi_cmd_reply(s, ret, max_len);
case 0x80:
case 0x81:
case 0x82:
case 0x83:
case 0x90:
case 0xc0:
default:
case GPCMD_SET_SPEED:
ide_atapi_cmd_ok(s);
case GPCMD_INQUIRY:
max_len = packet[4];
buf[0] = 0x05;
buf[1] = 0x80;
buf[2] = 0x00;
buf[3] = 0x21;
buf[4] = 31;
buf[5] = 0;
buf[6] = 0;
buf[7] = 0;
padstr8(buf + 8, 8, "QEMU");
padstr8(buf + 16, 16, "QEMU DVD-ROM");
padstr8(buf + 32, 4, s->version);
ide_atapi_cmd_reply(s, 36, max_len);
case GPCMD_GET_CONFIGURATION:
{
uint32_t len;
uint8_t index = 0;
if (packet[2] != 0 || packet[3] != 0) {
if (max_len > 512)
max_len = 512;
memset(buf, 0, max_len);
if (media_is_dvd(s))
cpu_to_ube16(buf + 6, MMC_PROFILE_DVD_ROM);
else if (media_is_cd(s))
cpu_to_ube16(buf + 6, MMC_PROFILE_CD_ROM);
buf[10] = 0x02 | 0x01;
len = 12;
len += ide_atapi_set_profile(buf, &index, MMC_PROFILE_DVD_ROM);
len += ide_atapi_set_profile(buf, &index, MMC_PROFILE_CD_ROM);
cpu_to_ube32(buf, len - 4);
ide_atapi_cmd_reply(s, len, max_len);
default:
ASC_ILLEGAL_OPCODE);
| 1threat
|
Since C++17 supports shared_ptr of array, does this mean that an explicit deleter for T[] is no longer required in both ctor and reset? : <p>When create shared_ptr using a separated allocation, an explicit delete function must be provided in C++14 ctor and reset member function.</p>
<pre><code>using std::string;
using std::shared_ptr;
using std::default_delete;
int arr_size{};
...
auto string_arr_sptr_cpp14 =
shared_ptr<string[]>(new string[arr_size], default_delete<string[]>() );
string_arr_sptr_cpp14.reset(new string[arr_size], default_delete<string[]>() );
// define an explicit deleter,
// or otherwise, "delete ptr;" will internally be used incorrectly!
</code></pre>
<p>By supporting shared_ptr of array feature in C++17, would those be no longer required in both ctor and reset?</p>
<pre><code>auto string_arr_sptr_cpp17 = shared_ptr<string[]>(new string[arr_size]);
string_arr_sptr_cpp14.reset(new string[arr_size]);
// deduced delete function calls "delete[] ptr;" correctly now?
</code></pre>
| 0debug
|
int avpicture_layout(const AVPicture* src, enum AVPixelFormat pix_fmt,
int width, int height,
unsigned char *dest, int dest_size)
{
int i, j, nb_planes = 0, linesizes[4];
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
int size = avpicture_get_size(pix_fmt, width, height);
if (size > dest_size || size < 0)
return AVERROR(EINVAL);
for (i = 0; i < desc->nb_components; i++)
nb_planes = FFMAX(desc->comp[i].plane, nb_planes);
nb_planes++;
av_image_fill_linesizes(linesizes, pix_fmt, width);
for (i = 0; i < nb_planes; i++) {
int h, shift = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
const unsigned char *s = src->data[i];
h = (height + (1 << shift) - 1) >> shift;
for (j = 0; j < h; j++) {
memcpy(dest, s, linesizes[i]);
dest += linesizes[i];
s += src->linesize[i];
}
}
if (desc->flags & AV_PIX_FMT_FLAG_PAL)
memcpy((unsigned char *)(((size_t)dest + 3) & ~3),
src->data[1], 256 * 4);
return size;
}
| 1threat
|
static void encode_frame(MpegAudioContext *s,
unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT],
int padding)
{
int i, j, k, l, bit_alloc_bits, b, ch;
unsigned char *sf;
int q[3];
PutBitContext *p = &s->pb;
put_bits(p, 12, 0xfff);
put_bits(p, 1, 1 - s->lsf);
put_bits(p, 2, 4-2);
put_bits(p, 1, 1);
put_bits(p, 4, s->bitrate_index);
put_bits(p, 2, s->freq_index);
put_bits(p, 1, s->do_padding);
put_bits(p, 1, 0);
put_bits(p, 2, s->nb_channels == 2 ? MPA_STEREO : MPA_MONO);
put_bits(p, 2, 0);
put_bits(p, 1, 0);
put_bits(p, 1, 1);
put_bits(p, 2, 0);
j = 0;
for(i=0;i<s->sblimit;i++) {
bit_alloc_bits = s->alloc_table[j];
for(ch=0;ch<s->nb_channels;ch++) {
put_bits(p, bit_alloc_bits, bit_alloc[ch][i]);
}
j += 1 << bit_alloc_bits;
}
for(i=0;i<s->sblimit;i++) {
for(ch=0;ch<s->nb_channels;ch++) {
if (bit_alloc[ch][i])
put_bits(p, 2, s->scale_code[ch][i]);
}
}
for(i=0;i<s->sblimit;i++) {
for(ch=0;ch<s->nb_channels;ch++) {
if (bit_alloc[ch][i]) {
sf = &s->scale_factors[ch][i][0];
switch(s->scale_code[ch][i]) {
case 0:
put_bits(p, 6, sf[0]);
put_bits(p, 6, sf[1]);
put_bits(p, 6, sf[2]);
break;
case 3:
case 1:
put_bits(p, 6, sf[0]);
put_bits(p, 6, sf[2]);
break;
case 2:
put_bits(p, 6, sf[0]);
break;
}
}
}
}
for(k=0;k<3;k++) {
for(l=0;l<12;l+=3) {
j = 0;
for(i=0;i<s->sblimit;i++) {
bit_alloc_bits = s->alloc_table[j];
for(ch=0;ch<s->nb_channels;ch++) {
b = bit_alloc[ch][i];
if (b) {
int qindex, steps, m, sample, bits;
qindex = s->alloc_table[j+b];
steps = ff_mpa_quant_steps[qindex];
for(m=0;m<3;m++) {
sample = s->sb_samples[ch][k][l + m][i];
#if USE_FLOATS
{
float a;
a = (float)sample * s->scale_factor_inv_table[s->scale_factors[ch][i][k]];
q[m] = (int)((a + 1.0) * steps * 0.5);
}
#else
{
int q1, e, shift, mult;
e = s->scale_factors[ch][i][k];
shift = s->scale_factor_shift[e];
mult = s->scale_factor_mult[e];
if (shift < 0)
q1 = sample << (-shift);
else
q1 = sample >> shift;
q1 = (q1 * mult) >> P;
q1 += 1 << P;
if (q1 < 0)
q1 = 0;
q[m] = (unsigned)(q1 * steps) >> (P + 1);
}
#endif
if (q[m] >= steps)
q[m] = steps - 1;
av_assert2(q[m] >= 0 && q[m] < steps);
}
bits = ff_mpa_quant_bits[qindex];
if (bits < 0) {
put_bits(p, -bits,
q[0] + steps * (q[1] + steps * q[2]));
} else {
put_bits(p, bits, q[0]);
put_bits(p, bits, q[1]);
put_bits(p, bits, q[2]);
}
}
}
j += 1 << bit_alloc_bits;
}
}
}
for(i=0;i<padding;i++)
put_bits(p, 1, 0);
flush_put_bits(p);
}
| 1threat
|
static AVFilterContext *create_filter(AVFilterGraph *ctx, int index,
const char *name, const char *args,
AVClass *log_ctx)
{
AVFilterContext *filt;
AVFilter *filterdef;
char inst_name[30];
snprintf(inst_name, sizeof(inst_name), "Parsed filter %d", index);
if(!(filterdef = avfilter_get_by_name(name))) {
av_log(log_ctx, AV_LOG_ERROR,
"no such filter: '%s'\n", name);
return NULL;
}
if(!(filt = avfilter_open(filterdef, inst_name))) {
av_log(log_ctx, AV_LOG_ERROR,
"error creating filter '%s'\n", name);
return NULL;
}
if(avfilter_graph_add_filter(ctx, filt) < 0)
return NULL;
if(avfilter_init_filter(filt, args, NULL)) {
av_log(log_ctx, AV_LOG_ERROR,
"error initializing filter '%s' with args '%s'\n", name, args);
return NULL;
}
return filt;
}
| 1threat
|
static int translate_pages(S390CPU *cpu, vaddr addr, int nr_pages,
target_ulong *pages, bool is_write)
{
bool lowprot = is_write && lowprot_enabled(&cpu->env);
uint64_t asc = cpu->env.psw.mask & PSW_MASK_ASC;
CPUS390XState *env = &cpu->env;
int ret, i, pflags;
for (i = 0; i < nr_pages; i++) {
if (lowprot && (addr < 512 || (addr >= 4096 && addr < 4096 + 512))) {
trigger_access_exception(env, PGM_PROTECTION, ILEN_AUTO, 0);
return -EACCES;
}
ret = mmu_translate(env, addr, is_write, asc, &pages[i], &pflags, true);
if (ret) {
return ret;
}
if (!address_space_access_valid(&address_space_memory, pages[i],
TARGET_PAGE_SIZE, is_write)) {
program_interrupt(env, PGM_ADDRESSING, ILEN_AUTO);
return -EFAULT;
}
addr += TARGET_PAGE_SIZE;
}
return 0;
}
| 1threat
|
How to current array key inside foreach : <p>In my PHP code I want to check inside foreach iteration what is the current array key (In code below: key1/key2/key3/key4/key5).</p>
<p>I have assoc array which looks like this:</p>
<p>var_dump($myArray);</p>
<p>array(5) { </p>
<p> ["key1"]=> array(2) {....} </p>
<p> ["key2"]=> array(2) {....} </p>
<p> ["key3"]=> array(2) {....} </p>
<p> ["key4"]=> array(2) {....}</p>
<p> ["key5"]=> array(2) {....}</p>
<p>}</p>
<pre><code>foreach($myArray as $key) {
echo key($myArray);
}
</code></pre>
<p>For example this only returns: key1key1key1key1key1</p>
<p>My desired output should look like: key1key2key3key4key5</p>
<p>I've been searching for a while but I can't find any smart solution.</p>
<p>Thank you :)</p>
| 0debug
|
Decompression 'SNAPPY' not available with fastparquet : <p>I am trying to use fastparquet to open a file, but I get the error:</p>
<pre><code>RuntimeError: Decompression 'SNAPPY' not available. Options: ['GZIP', 'UNCOMPRESSED']
</code></pre>
<p>I have the following installed and have rebooted my interpreter:</p>
<pre><code>python 3.6.5 hc3d631a_2
python-snappy 0.5.2 py36_0 conda-forge
snappy 1.1.7 hbae5bb6_3
fastparquet 0.1.5 py36_0 conda-forge
</code></pre>
<p>Everything downloaded smoothly. I didn't know if I needed snappy or python-snappy so I got one had no fix and got the other, still with no success. All related issues I have found are fixed when downloading snappy, but I am still getting this error with having two snappys! Any help would be appreciated.</p>
| 0debug
|
static int dec_21154_pci_host_init(PCIDevice *d)
{
pci_config_set_vendor_id(d->config, PCI_VENDOR_ID_DEC);
pci_config_set_device_id(d->config, PCI_DEVICE_ID_DEC_21154);
pci_set_byte(d->config + PCI_REVISION_ID, 0x02);
pci_config_set_class(d->config, PCI_CLASS_BRIDGE_PCI);
return 0;
}
| 1threat
|
My nav code in Bootstrap doesn't works oke CSS : The code at the and of this message I use in WebStorm. Have you any idea what i doing wrong? Maybe some CDN errors or incorrect in the code?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>DateLab</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">DateLab</a>
</div>
<div>
<ul class="navbar navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Hoe werkt het</a></li>
<li><a href="#">Wie zijn wij</a></li>
<li><a href="#">FAQ</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</div>
</nav>
</body>
</html>
Output:
[output of the code][1]
[1]: https://i.stack.imgur.com/S7ZYl.png
| 0debug
|
static void opt_output_file(const char *filename)
{
AVFormatContext *oc;
int err, use_video, use_audio, use_subtitle;
int input_has_video, input_has_audio, input_has_subtitle;
AVFormatParameters params, *ap = ¶ms;
AVOutputFormat *file_oformat;
if (!strcmp(filename, "-"))
filename = "pipe:";
oc = avformat_alloc_context();
if (!oc) {
print_error(filename, AVERROR(ENOMEM));
ffmpeg_exit(1);
}
if (last_asked_format) {
file_oformat = av_guess_format(last_asked_format, NULL, NULL);
if (!file_oformat) {
fprintf(stderr, "Requested output format '%s' is not a suitable output format\n", last_asked_format);
ffmpeg_exit(1);
}
last_asked_format = NULL;
} else {
file_oformat = av_guess_format(NULL, filename, NULL);
if (!file_oformat) {
fprintf(stderr, "Unable to find a suitable output format for '%s'\n",
filename);
ffmpeg_exit(1);
}
}
oc->oformat = file_oformat;
av_strlcpy(oc->filename, filename, sizeof(oc->filename));
if (!strcmp(file_oformat->name, "ffm") &&
av_strstart(filename, "http:", NULL)) {
int err = read_ffserver_streams(oc, filename);
if (err < 0) {
print_error(filename, err);
ffmpeg_exit(1);
}
} else {
use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_name;
use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_name;
use_subtitle = file_oformat->subtitle_codec != CODEC_ID_NONE || subtitle_stream_copy || subtitle_codec_name;
if (nb_input_files > 0) {
check_audio_video_sub_inputs(&input_has_video, &input_has_audio,
&input_has_subtitle);
if (!input_has_video)
use_video = 0;
if (!input_has_audio)
use_audio = 0;
if (!input_has_subtitle)
use_subtitle = 0;
}
if (audio_disable) use_audio = 0;
if (video_disable) use_video = 0;
if (subtitle_disable) use_subtitle = 0;
if (use_video) new_video_stream(oc, nb_output_files);
if (use_audio) new_audio_stream(oc, nb_output_files);
if (use_subtitle) new_subtitle_stream(oc, nb_output_files);
oc->timestamp = recording_timestamp;
av_metadata_copy(&oc->metadata, metadata, 0);
av_metadata_free(&metadata);
}
output_files[nb_output_files++] = oc;
if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
if (!av_filename_number_test(oc->filename)) {
print_error(oc->filename, AVERROR_NUMEXPECTED);
ffmpeg_exit(1);
}
}
if (!(oc->oformat->flags & AVFMT_NOFILE)) {
if (!file_overwrite &&
(strchr(filename, ':') == NULL ||
filename[1] == ':' ||
av_strstart(filename, "file:", NULL))) {
if (url_exist(filename)) {
if (!using_stdin) {
fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
fflush(stderr);
if (!read_yesno()) {
fprintf(stderr, "Not overwriting - exiting\n");
ffmpeg_exit(1);
}
}
else {
fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
ffmpeg_exit(1);
}
}
}
if ((err = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE)) < 0) {
print_error(filename, err);
ffmpeg_exit(1);
}
}
memset(ap, 0, sizeof(*ap));
if (av_set_parameters(oc, ap) < 0) {
fprintf(stderr, "%s: Invalid encoding parameters\n",
oc->filename);
ffmpeg_exit(1);
}
oc->preload= (int)(mux_preload*AV_TIME_BASE);
oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
oc->loop_output = loop_output;
oc->flags |= AVFMT_FLAG_NONBLOCK;
set_context_opts(oc, avformat_opts, AV_OPT_FLAG_ENCODING_PARAM, NULL);
av_freep(&forced_key_frames);
}
| 1threat
|
find charecter(AND,OR) in string and make as array in javascript/jquery : example var string=(Firstname==test1) AND (Lastname==test2) OR (state=Tamilnadu) OR (country=india)
i required output like {AND,OR,OR}
| 0debug
|
I get an error when I print b1 and b3 seperatly.. But thers no error if I print b2 seperatly ..Pls Explaine : <pre><code>class Example{
public static void main(String args[]){
int x=100;
final int y=100;
final int z;
z=100;
byte b1,b2,b3;
b1=x;
b2=y;
b3=z;
System.out.println(b1);
}
</code></pre>
<p>}
I get an error when I print b1 and b3 seperatly.. But thers no error if I print b2 seperatly ..Pls Explaine</p>
| 0debug
|
PSQLException: ERROR: syntax error at or near : <p>I have what I thought was a straight forward relation in JPA. Looks like this. CompanyGroup:</p>
<pre><code>@Entity
@Table
public class CompanyGroup implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(name = "name")
private String name;
@JoinColumn(name = "companies")
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Company> companies;
}
</code></pre>
<p>Company:</p>
<pre><code>@Entity
@Table
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "name")
private String name;
@JoinColumn(name = "users")
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<User> users;
@Id
@GeneratedValue
private Long id;
}
</code></pre>
<p>User:</p>
<pre><code>@Entity
@Table
public class User {
@Column(name = "firstName")
private String firstName;
@Column(name = "lastName")
private String lastName;
@Column(name = "email")
private String email;
@Id
@GeneratedValue
private Long id;
}
</code></pre>
<p>I have omitted setters, getters, etc.</p>
<p>This is not working. I'm trying to save a CompanyGroup(Has 2 companies, each company has 2 users, all entities are unique) to a fully empty database. </p>
<p>I persist this using Spring-Data, accessed in a service like this:</p>
<pre><code>@Service
public class ConcreteCompanyGroupService implements CompanyGroupService {
@Autowired
private CompanyGroupRepository repository;
@Transactional
@Override
public void save(CompanyGroup group) {
repository.save(Collections.singleton(group));
}
}
</code></pre>
<p>When I try to call this method I receive this:</p>
<pre><code> org.postgresql.util.PSQLException: ERROR: syntax error at or near "User"
Position: 13
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2458)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2158)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:291)
</code></pre>
<p>Hopefully I have done something stupid that someone can find quickly. I don't know how to solve this.</p>
<p>EDIT:</p>
<p>The driver in my pom.xml:</p>
<pre><code><dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4.1211</version>
</dependency>
</code></pre>
| 0debug
|
Set state and then reading the state shows the previous value : <p>I have the following code that maintains the value when the textbox value is changed. However, whilst debugging the valueHasChangedEvent the variable x line shown below holds the previous value strangely. Is there something I'm doing wrong? The example shown is when I enter 'test123' into the textbox. </p>
<p>Thanks</p>
<p><strong>onChange event</strong></p>
<pre><code><Input onChange={this.valueHasChangedEvent}
type="text"
name="test"
id="test" />
</code></pre>
<p><strong>Method</strong></p>
<pre><code>valueHasChangedEvent = (event) => {
var self = this;
const { name, value } = event.target;
self.setState({test: value}); // value = 'test123'
var x = self.state.test; // x = 'test12'
}
</code></pre>
| 0debug
|
void ide_init_drive(IDEState *s, DriveInfo *dinfo, const char *version)
{
int cylinders, heads, secs;
uint64_t nb_sectors;
if (dinfo && dinfo->bdrv) {
s->bs = dinfo->bdrv;
bdrv_get_geometry(s->bs, &nb_sectors);
bdrv_guess_geometry(s->bs, &cylinders, &heads, &secs);
s->cylinders = cylinders;
s->heads = heads;
s->sectors = secs;
s->nb_sectors = nb_sectors;
s->smart_enabled = 1;
s->smart_autosave = 1;
s->smart_errors = 0;
s->smart_selftest_count = 0;
if (bdrv_get_type_hint(s->bs) == BDRV_TYPE_CDROM) {
s->is_cdrom = 1;
bdrv_set_change_cb(s->bs, cdrom_change_cb, s);
}
strncpy(s->drive_serial_str, drive_get_serial(s->bs),
sizeof(s->drive_serial_str));
}
if (strlen(s->drive_serial_str) == 0)
snprintf(s->drive_serial_str, sizeof(s->drive_serial_str),
"QM%05d", s->drive_serial);
if (version) {
pstrcpy(s->version, sizeof(s->version), version);
} else {
pstrcpy(s->version, sizeof(s->version), QEMU_VERSION);
}
ide_reset(s);
}
| 1threat
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.