problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
static void nfs_client_close(NFSClient *client)
{
if (client->context) {
if (client->fh) {
nfs_close(client->context, client->fh);
}
aio_set_fd_handler(client->aio_context, nfs_get_fd(client->context),
false, NULL, NULL, NULL, NULL);
nfs_destroy_context(client->context);
}
memset(client, 0, sizeof(NFSClient));
}
| 1threat
|
How to implement the ftruncate function : Hi I just have a simple question; I am trying to use the function "ftruncate" to truncate a file, so my question is how do you inplement this function?
Thanks
| 0debug
|
Angular2 HTTP - How to understand that the backend server is down : <p>I am developing a front end which consumes JSON services provided by a server. </p>
<p>I happily use HTTP of Angular2 and I can catch errors via <code>.catch()</code> operator.</p>
<p>If I find a problem related to a specific service (e.g. the service is not defined by the server) the <code>catch()</code> operator receives a <code>Response</code> with status <code>404</code> and I can easily manage the situation.</p>
<p>On the other hand, if it is the server that is completely down, the <code>catch()</code> operator receives a Response with status code <code>200</code>and no specific sign or text related to the cause of the problem (which is that the whole server is down).
On the console I see that angular (<strong>http.dev.js</strong>) writes a message <code>net::ERR_CONNECTION_REFUSED</code> but I do not know how to do something similar (i.e. understand what is happening and react appropriately) from within my code. </p>
<p>Any help would be appreciated.</p>
| 0debug
|
static void *data_plane_thread(void *opaque)
{
VirtIOBlockDataPlane *s = opaque;
do {
aio_poll(s->ctx, true);
} while (!s->stopping || s->num_reqs > 0);
return NULL;
}
| 1threat
|
C# - Running code asynchronously in parallel : <p>I have a C# console app that I'm using for experimentation. I have some blocks of code that I know that I want to run 1) Asynchronously 2) in Parallel and 3) Run some shared cleanup code when each block finishes. </p>
<p>I need to run the blocks asynchronously because each one is calling a web service. I need to run each block in parallel for performance reasons and no block is dependent on the other. Finally, I have a significant amount of clean-up and logging code that I want to run when each block finishes. For that reason, this code is shared. </p>
<p>I'm getting stuck in how to do this. Thus far, I've looked the following C# concepts:</p>
<p>1) <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1?view=netframework-4.7.1" rel="nofollow noreferrer">Tasks</a> - Pros: Good at running code asynchronously Cons: a) I do not see a way to define a task and pass it to a shared method so that I can run my clean up code. b) I do not see a good way to pass parameters to a Task</p>
<p>2) <a href="https://msdn.microsoft.com/en-us/library/system.action(v=vs.110).aspx" rel="nofollow noreferrer">Actions</a> - Pros: a) Can define code blocks inline i.e. <code>var myAction = (Action)(() => { });</code>. b) Can easily pass parameters to the <code>Action</code>. Cons: Doesn't seem to be a way to run actions asynchronously, thus b) Not sure I can run actions in parallel.</p>
<p>As I write this question, it's clear I'm missing something. At first glance, Tasks seem like the correct road to go down. However, I do feel stuck in the fact that</p>
<pre><code>public void RunTaskInParallel(Task task)
{
var startTime = DateTime.UtcNow;
// Execute task code
var executionTime = DateTime.UtcNow.Subtract(startTime);
// Log the execution time
// Execute Clean-up Code
}
</code></pre>
<p>How do I run a block of code, asynchronously, in parallel, in a way that allows me to execute some shared clean-up code when all is said and done? I feel like I'm always getting two-of-three requirements, but struggling to get all three.</p>
<p>Thank you for your help!</p>
| 0debug
|
static int16_t square_root(int val)
{
return (ff_sqrt(val << 1) >> 1) & (~1);
}
| 1threat
|
static uint32_t drc_unisolate_physical(sPAPRDRConnector *drc)
{
if (!drc->dev) {
return RTAS_OUT_NO_SUCH_INDICATOR;
}
drc->isolation_state = SPAPR_DR_ISOLATION_STATE_UNISOLATED;
return RTAS_OUT_SUCCESS;
}
| 1threat
|
RxJS: Observable.create() vs. Observable.from() : <p>What's the difference between these two?</p>
<pre><code>return Observable.create(function(observer) {
if (array)
observer.next([]);
else
observer.next(null);
observer.complete();
});
</code></pre>
<p>and </p>
<pre><code>return Observable.from( array ? [] : null );
</code></pre>
<p>I thought it could be the same but didn't work the same.</p>
| 0debug
|
Andoid database SQLite Datatype mismatch : This is not a duplicate question. I understand that there are a lot of questions about this but none of them solved the problem for me.
Why is the datatype mismatched and why is the insertion of the row happening as (name,_id) and not (_id,name) when I call the createRecords method?
package com.caldroidsample;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import static android.R.attr.text;
import static android.R.id.primary;
import static com.caldroidsample.R.id.email;
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "DBName";
private static final int DATABASE_VERSION = 2;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table MyEmployees( _id integer primary key, name varchar(255) not null);";
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
// Method is called during an upgrade of the database,
@Override
public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
Log.w(MyDatabaseHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS MyEmployees");
onCreate(database);
}
}
This is the class MyDB.java
package com.caldroidsample;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class MyDB{
private MyDatabaseHelper dbHelper;
public SQLiteDatabase database;
public final static String EMP_TABLE="MyEmployees"; // name of table
public final static String EMP_ID="_id"; // id value for employee
public final static String EMP_NAME="name"; // name of employee
public final static String EMP_EMAIL="email"; // email of employee
public final static String EMP_ADDRESS="address";
public final static String EMP_GENDER="gender";
/**
*
* @param context
*/
public MyDB(Context context){
dbHelper = new MyDatabaseHelper(context);
database = dbHelper.getWritableDatabase();
}
public long createRecords(String id, String name){
ContentValues values = new ContentValues();
values.put(EMP_NAME, name);
values.put(EMP_ID, id);
return database.insert(EMP_TABLE, EMP_ID, values);
}
public Cursor selectRecords() {
String[] cols = new String[] {EMP_ID, EMP_NAME};
Cursor mCursor = database.query(true, EMP_TABLE,cols,null
, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor; // iterate to get each value.
}
}
| 0debug
|
enum AVCodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
const char *filename, const char *mime_type,
enum AVMediaType type)
{
if (av_match_name("segment", fmt->name) || av_match_name("ssegment", fmt->name)) {
fmt = av_guess_format(NULL, filename, NULL);
}
if (type == AVMEDIA_TYPE_VIDEO) {
enum AVCodecID codec_id = AV_CODEC_ID_NONE;
#if CONFIG_IMAGE2_MUXER
if (!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")) {
codec_id = ff_guess_image2_codec(filename);
}
#endif
if (codec_id == AV_CODEC_ID_NONE)
codec_id = fmt->video_codec;
return codec_id;
} else if (type == AVMEDIA_TYPE_AUDIO)
return fmt->audio_codec;
else if (type == AVMEDIA_TYPE_SUBTITLE)
return fmt->subtitle_codec;
else
return AV_CODEC_ID_NONE;
}
| 1threat
|
uint32_t kvm_arch_get_supported_cpuid(CPUState *env, uint32_t function,
uint32_t index, int reg)
{
struct kvm_cpuid2 *cpuid;
int i, max;
uint32_t ret = 0;
uint32_t cpuid_1_edx;
int has_kvm_features = 0;
max = 1;
while ((cpuid = try_get_cpuid(env->kvm_state, max)) == NULL) {
max *= 2;
}
for (i = 0; i < cpuid->nent; ++i) {
if (cpuid->entries[i].function == function &&
cpuid->entries[i].index == index) {
if (cpuid->entries[i].function == KVM_CPUID_FEATURES) {
has_kvm_features = 1;
}
switch (reg) {
case R_EAX:
ret = cpuid->entries[i].eax;
break;
case R_EBX:
ret = cpuid->entries[i].ebx;
break;
case R_ECX:
ret = cpuid->entries[i].ecx;
break;
case R_EDX:
ret = cpuid->entries[i].edx;
switch (function) {
case 1:
ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
break;
case 0x80000001:
cpuid_1_edx = kvm_arch_get_supported_cpuid(env, 1, 0, R_EDX);
ret |= cpuid_1_edx & 0x183f7ff;
break;
}
break;
}
}
}
qemu_free(cpuid);
if (!has_kvm_features && (function == KVM_CPUID_FEATURES)) {
ret = get_para_features(env);
}
return ret;
}
| 1threat
|
how can I make a table field predefined in mysql? : I've not worked on such case before so asking you . like I'll create a table where inside the table fields field3=field1+field2 by default. mean i don't need to make it on frontend.
check the imaga-
[enter image description here][1]
please give a suggestion.
Thanks
[1]: https://i.stack.imgur.com/tO5ks.jpg
| 0debug
|
Android create backup database inside app : I have an app similar to contacts app and uses the sqlite to store data. I want that whenever the database version is changed,a backup of current database is taken inside the app and the customer has option to fall back to previous version.
In onUpgrade() method,if i create a new table with different name, then i am unable to copy the data from older version.
Please suggest some good way to implement this. I have searched on internet, but was unable to find.
| 0debug
|
RecyclerView skips the first few views i dont know why : For some reason,Recyclerview skips views and when it first loads up it makes all views of the same object in the array and still comes up empty till i scroll down and up then they start to appear. I dont seem to see the problem because it does work, it just does not work as it should. i am using volley so i dont need to make a another thread to run the network calls so i dont know.
enter code here
public class ForecastActivity extends AppCompatActivity {
RecyclerView recyclerView;
ListAdapter listAdapter;
RequestQueue requestQueue;
JSONParser jsonParser = JSONParser.getJsonParser();
ForecastListItem[] mArrayList;
TextView mForecastCityandCountyText;
String mForecastCityandContryString;
String mForecastCityNameString;
String mForecastCountryString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forcast);
initializeUI();
requestQueue = Volley.newRequestQueue(this);
netWorkRequest();
}
public void initializeUI() {
mForecastCityandCountyText = (TextView) findViewById(R.id.ForecastCityName);
recyclerView = (RecyclerView) findViewById(R.id.Recylerviewlayout);
listAdapter = new ListAdapter();
recyclerView.setAdapter(listAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mArrayList = new ForecastListItem[10];
mArrayList[0] = new ForecastListItem();
mArrayList[1] = new ForecastListItem();
mArrayList[2] = new ForecastListItem();
mArrayList[3] = new ForecastListItem();
mArrayList[4] = new ForecastListItem();
mArrayList[5] = new ForecastListItem();
mArrayList[6] = new ForecastListItem();
mArrayList[7] = new ForecastListItem();
mArrayList[8] = new ForecastListItem();
mArrayList[9] = new ForecastListItem();
}
public void netWorkRequest() {
JsonObjectRequest JsonObjectRequest = new JsonObjectRequest(Request.Method.GET, jsonParser.getForecastUrl(), null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
String UniverSalIconString;
Log.d(jsonParser.getForecastUrl(), "");
JSONObject mJsonCityObject = response.getJSONObject("city");
Log.d("here is the object", mJsonCityObject.toString());
mForecastCityNameString = jsonParser.getString("name", mJsonCityObject);
mForecastCountryString = jsonParser.getString("country", mJsonCityObject);
mForecastCityandContryString = mForecastCityNameString + "," + mForecastCountryString;
mForecastCityandCountyText.setText(mForecastCityandContryString);
//*********************************************************************************************************************************************
// add all the information to arraylist so i can be processed by recycler view
// add refresh button
JSONArray JsonListArray = jsonParser.getJSONArray("list", response);
JSONObject Day1 = jsonParser.getJSONObject(0, JsonListArray);
JSONObject TempObj = jsonParser.getJSONObject("temp", Day1);
mArrayList[0].setmForecastTempDouble(jsonParser.getDouble("day", TempObj));
JSONArray JsonDay1WeatherArray = jsonParser.getJSONArray("weather", Day1);
JSONObject Day1WeatherJsonObject = jsonParser.getJSONObject(0, JsonDay1WeatherArray);
UniverSalIconString = jsonParser.getString("icon", Day1WeatherJsonObject);
mArrayList[0].setmForecastDescriptionString(jsonParser.getString("description", Day1WeatherJsonObject));
mArrayList[0].setmForecastIconUrl(jsonParser.getCurrentWeatherIconUrl(UniverSalIconString));
mArrayList[0].setMYNUMBER(1);
UniverSalIconString = null;
JSONObject Day2 = jsonParser.getJSONObject(1, JsonListArray);
JSONObject TempObj2 = jsonParser.getJSONObject("temp", Day2);
mArrayList[1].setmForecastTempDouble(jsonParser.getDouble("day", TempObj2));
JSONArray JsonDay2WeatherArray = jsonParser.getJSONArray("weather", Day2);
JSONObject Day2WeatherJsonObject = jsonParser.getJSONObject(0, JsonDay2WeatherArray);
UniverSalIconString = jsonParser.getString("icon", Day2WeatherJsonObject);
mArrayList[1].setmForecastDescriptionString(jsonParser.getString("description", Day2WeatherJsonObject));
mArrayList[1].setmForecastIconUrl(jsonParser.getCurrentWeatherIconUrl(UniverSalIconString));
mArrayList[1].setMYNUMBER(2);
UniverSalIconString = null;
JSONObject Day3 = jsonParser.getJSONObject(2, JsonListArray);
JSONObject TempObj3 = jsonParser.getJSONObject("temp", Day3);
mArrayList[2].setmForecastTempDouble(jsonParser.getDouble("day", TempObj3));
JSONArray JsonDay3WeatherArray = jsonParser.getJSONArray("weather", Day3);
JSONObject Day3WeatherJsonObject = jsonParser.getJSONObject(0, JsonDay3WeatherArray);
UniverSalIconString = jsonParser.getString("icon", Day3WeatherJsonObject);
mArrayList[2].setmForecastDescriptionString(jsonParser.getString("description", Day3WeatherJsonObject));
mArrayList[2].setmForecastIconUrl(jsonParser.getCurrentWeatherIconUrl(UniverSalIconString));
mArrayList[2].setMYNUMBER(3);
UniverSalIconString = null;
JSONObject Day4 = jsonParser.getJSONObject(3, JsonListArray);
JSONObject TempObj4 = jsonParser.getJSONObject("temp", Day4);
mArrayList[3].setmForecastTempDouble(jsonParser.getDouble("day", TempObj4));
JSONArray JsonDay4WeatherArray = jsonParser.getJSONArray("weather", Day4);
JSONObject Day4WeatherJsonObject = jsonParser.getJSONObject(0, JsonDay4WeatherArray);
UniverSalIconString = jsonParser.getString("icon", Day4WeatherJsonObject);
mArrayList[3].setmForecastDescriptionString(jsonParser.getString("description", Day4WeatherJsonObject));
mArrayList[3].setmForecastIconUrl(jsonParser.getCurrentWeatherIconUrl(UniverSalIconString));
mArrayList[3].setMYNUMBER(4);
UniverSalIconString = null;
JSONObject Day5 = jsonParser.getJSONObject(4, JsonListArray);
JSONObject TempObj5 = jsonParser.getJSONObject("temp", Day5);
mArrayList[4].setmForecastTempDouble(jsonParser.getDouble("day", TempObj5));
JSONArray JsonDay5WeatherArray = jsonParser.getJSONArray("weather", Day5);
JSONObject Day5WeatherJsonObject = jsonParser.getJSONObject(0, JsonDay5WeatherArray);
UniverSalIconString = jsonParser.getString("icon", Day5WeatherJsonObject);
mArrayList[4].setmForecastDescriptionString(jsonParser.getString("description", Day5WeatherJsonObject));
mArrayList[4].setmForecastIconUrl(jsonParser.getCurrentWeatherIconUrl(UniverSalIconString));
mArrayList[4].setMYNUMBER(5);
UniverSalIconString = null;
JSONObject Day6 = jsonParser.getJSONObject(5, JsonListArray);
JSONObject TempObj6 = jsonParser.getJSONObject("temp", Day6);
mArrayList[5].setmForecastTempDouble(jsonParser.getDouble("day", TempObj6));
JSONArray JsonDay6WeatherArray = jsonParser.getJSONArray("weather", Day6);
JSONObject Day6WeatherJsonObject = jsonParser.getJSONObject(0, JsonDay6WeatherArray);
UniverSalIconString = jsonParser.getString("icon", Day6WeatherJsonObject);
mArrayList[5].setmForecastDescriptionString(jsonParser.getString("description", Day6WeatherJsonObject));
mArrayList[5].setmForecastIconUrl(jsonParser.getCurrentWeatherIconUrl(UniverSalIconString));
mArrayList[5].setMYNUMBER(6);
UniverSalIconString = null;
JSONObject Day7 = jsonParser.getJSONObject(6, JsonListArray);
JSONObject TempObj7 = jsonParser.getJSONObject("temp", Day7);
mArrayList[6].setmForecastTempDouble(jsonParser.getDouble("day", TempObj7));
JSONArray JsonDay7WeatherArray = jsonParser.getJSONArray("weather", Day7);
JSONObject Day7WeatherJsonObject = jsonParser.getJSONObject(0, JsonDay7WeatherArray);
UniverSalIconString = jsonParser.getString("icon", Day7WeatherJsonObject);
mArrayList[6].setmForecastDescriptionString(jsonParser.getString("description", Day7WeatherJsonObject));
mArrayList[6].setmForecastIconUrl(jsonParser.getCurrentWeatherIconUrl(UniverSalIconString));
mArrayList[6].setMYNUMBER(7);
UniverSalIconString = null;
JSONObject Day8 = jsonParser.getJSONObject(7, JsonListArray);
JSONObject TempObj8 = jsonParser.getJSONObject("temp", Day8);
mArrayList[7].setmForecastTempDouble(jsonParser.getDouble("day", TempObj8));
JSONArray JsonDay8WeatherArray = jsonParser.getJSONArray("weather", Day8);
JSONObject Day8WeatherJsonObject = jsonParser.getJSONObject(0, JsonDay8WeatherArray);
UniverSalIconString = jsonParser.getString("icon", Day8WeatherJsonObject);
mArrayList[7].setmForecastDescriptionString(jsonParser.getString("description", Day8WeatherJsonObject));
mArrayList[7].setmForecastIconUrl(jsonParser.getCurrentWeatherIconUrl(UniverSalIconString));
mArrayList[7].setMYNUMBER(8);
UniverSalIconString = null;
JSONObject Day9 = jsonParser.getJSONObject(8, JsonListArray);
JSONObject TempObj9 = jsonParser.getJSONObject("temp", Day9);
mArrayList[8].setmForecastTempDouble(jsonParser.getDouble("day", TempObj9));
JSONArray JsonDay9WeatherArray = jsonParser.getJSONArray("weather", Day9);
JSONObject Day9WeatherJsonObject = jsonParser.getJSONObject(0, JsonDay9WeatherArray);
UniverSalIconString = jsonParser.getString("icon", Day9WeatherJsonObject);
mArrayList[8].setmForecastDescriptionString(jsonParser.getString("description", Day9WeatherJsonObject));
mArrayList[8].setmForecastIconUrl(jsonParser.getCurrentWeatherIconUrl(UniverSalIconString));
mArrayList[8].setMYNUMBER(9);
UniverSalIconString = null;
JSONObject Day10 = jsonParser.getJSONObject(9, JsonListArray);
JSONObject TempObj10 = jsonParser.getJSONObject("temp", Day10);
mArrayList[9].setmForecastTempDouble(jsonParser.getDouble("day", TempObj10));
JSONArray JsonDay10WeatherArray = jsonParser.getJSONArray("weather", Day10);
JSONObject Day10WeatherJsonObject = jsonParser.getJSONObject(0, JsonDay10WeatherArray);
UniverSalIconString = jsonParser.getString("icon", Day10WeatherJsonObject);
mArrayList[9].setmForecastDescriptionString(jsonParser.getString("description", Day10WeatherJsonObject));
mArrayList[9].setmForecastIconUrl(jsonParser.getCurrentWeatherIconUrl(UniverSalIconString));
mArrayList[9].setMYNUMBER(10);
UniverSalIconString = null;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(JsonObjectRequest);
}
class ListHolder extends RecyclerView.ViewHolder {
TextView DescriptionText;
TextView TempText;
TextView DateText;
NetworkImageView ForecastIconImageView;
ImageLoader imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(10);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
public ListHolder(View itemView) {
super(itemView);
DescriptionText = (TextView) itemView.findViewById(R.id.ForcastWeatherDescriptionText);
TempText = (TextView) itemView.findViewById(R.id.ForecastWeatherTempText);
ForecastIconImageView = (NetworkImageView) itemView.findViewById(R.id.ForecastWeatherIconImageview);
// DateText = (TextView) itemView.findViewById(R.id.DateText);
}
void OnBind(ForecastListItem item) {
DescriptionText.setText(item.getmForecastDescriptionString());
TempText.setText(Integer.toString(item.getmForecastTempDouble()));
// DateText.setText(item.getmForecastDateString());
ForecastIconImageView.setImageUrl(item.getmForecastIconUrl(), imageLoader);
}
}
class ListAdapter extends RecyclerView.Adapter<ListHolder> {
@Override
public ListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ListHolder listHolder = new ListHolder(getLayoutInflater().inflate(R.layout.forecast_item_view, parent, false));
return listHolder;
}
@Override
public void onBindViewHolder(ListHolder holder, int position) {
Log.d("ARRAY NUM", Integer.toString(mArrayList[position].getMYNUMBER()));
holder.OnBind(mArrayList[position]);
// send the array to ViewHolder to set up the UI
}
@Override
public int getItemCount() {
return mArrayList.length;
}
}
| 0debug
|
How can I group by name in R and apply sum to the other 2 columns? : <p>I am trying to summarize this dataset by grouping by name (Almeria, Ath Bilbao,...) and have the sum of its corresponding values in column 2 (HalfTimeResult) and 3 (FullTimeResult). I tried with the <strong>aggregate</strong> and <strong>group_by</strong> functions but have not been able to obtain the right output.</p>
<p>What function and how would I use it to obtain an output like this?</p>
<p><a href="https://i.stack.imgur.com/aDweT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aDweT.png" alt="enter image description here"></a></p>
<p>This is the dataset that I am working with:</p>
<p><a href="https://i.stack.imgur.com/ORB4p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ORB4p.png" alt="enter image description here"></a></p>
| 0debug
|
static target_ulong h_protect(PowerPCCPU *cpu, sPAPRMachineState *spapr,
target_ulong opcode, target_ulong *args)
{
CPUPPCState *env = &cpu->env;
target_ulong flags = args[0];
target_ulong pte_index = args[1];
target_ulong avpn = args[2];
uint64_t token;
target_ulong v, r;
if (!valid_pte_index(env, pte_index)) {
return H_PARAMETER;
}
token = ppc_hash64_start_access(cpu, pte_index);
v = ppc_hash64_load_hpte0(cpu, token, 0);
r = ppc_hash64_load_hpte1(cpu, token, 0);
ppc_hash64_stop_access(token);
if ((v & HPTE64_V_VALID) == 0 ||
((flags & H_AVPN) && (v & ~0x7fULL) != avpn)) {
return H_NOT_FOUND;
}
r &= ~(HPTE64_R_PP0 | HPTE64_R_PP | HPTE64_R_N |
HPTE64_R_KEY_HI | HPTE64_R_KEY_LO);
r |= (flags << 55) & HPTE64_R_PP0;
r |= (flags << 48) & HPTE64_R_KEY_HI;
r |= flags & (HPTE64_R_PP | HPTE64_R_N | HPTE64_R_KEY_LO);
ppc_hash64_store_hpte(cpu, pte_index,
(v & ~HPTE64_V_VALID) | HPTE64_V_HPTE_DIRTY, 0);
ppc_hash64_tlb_flush_hpte(cpu, pte_index, v, r);
ppc_hash64_store_hpte(cpu, pte_index, v | HPTE64_V_HPTE_DIRTY, r);
return H_SUCCESS;
}
| 1threat
|
Init an object conforming to Codable with a dictionary/array : <p>Primarily my use case is to create an object using a dictionary: e.g. </p>
<pre><code>struct Person: Codable { let name: String }
let dictionary = ["name": "Bob"]
let person = Person(from: dictionary)
</code></pre>
<p>I would like to avoid writing custom implementations and want to be as efficient as possible.</p>
| 0debug
|
Cannot read property 'push' of undefined(…) in angular2 : <p>this is the error saying <strong><em>" cannot read property 'push' of undefined "</em></strong> when using the code below</p>
<pre><code> let deal = new Deal( 5, 'afaf', 'dafa',5,23 )
this.publicDeals.push( deal ) // gives a error saying Cannot read property 'push' of undefined(…)
</code></pre>
<p>The whole is shown below</p>
<pre><code>export class Deal {
constructor(
public id: number,
public name: string,
public description: string,
public originalPrice: number,
public salePrice: number
) { }
}
</code></pre>
<p>In another component, </p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { Deal } from '../deal';
import { DealService } from '../deal.service';
@Component({
selector: 'public-deals',
templateUrl: 'public-deals.component.html',
styleUrls: ['public-deals.component.css']
})
export class PublicDealsComponent implements OnInit {
publicDeals: Deal[];
constructor(
private dealService: DealService) {
}
ngOnInit(): void {
let deal = new Deal( 5, 'afaf', 'dafa',5,23 )
this.publicDeals.push( deal ) // gives a error saying Cannot read property 'push' of undefined(…)
}
purchase(item){
alert("You bought the: " + item.name);
}
}
</code></pre>
| 0debug
|
static void decode_src_opc(CPUTriCoreState *env, DisasContext *ctx, int op1)
{
int r1;
int32_t const4;
TCGv temp, temp2;
r1 = MASK_OP_SRC_S1D(ctx->opcode);
const4 = MASK_OP_SRC_CONST4_SEXT(ctx->opcode);
switch (op1) {
case OPC1_16_SRC_ADD:
gen_addi_d(cpu_gpr_d[r1], cpu_gpr_d[r1], const4);
break;
case OPC1_16_SRC_ADD_A15:
gen_addi_d(cpu_gpr_d[r1], cpu_gpr_d[15], const4);
break;
case OPC1_16_SRC_ADD_15A:
gen_addi_d(cpu_gpr_d[15], cpu_gpr_d[r1], const4);
break;
case OPC1_16_SRC_ADD_A:
tcg_gen_addi_tl(cpu_gpr_a[r1], cpu_gpr_a[r1], const4);
break;
case OPC1_16_SRC_CADD:
gen_condi_add(TCG_COND_NE, cpu_gpr_d[r1], const4, cpu_gpr_d[r1],
cpu_gpr_d[15]);
break;
case OPC1_16_SRC_CADDN:
gen_condi_add(TCG_COND_EQ, cpu_gpr_d[r1], const4, cpu_gpr_d[r1],
cpu_gpr_d[15]);
break;
case OPC1_16_SRC_CMOV:
temp = tcg_const_tl(0);
temp2 = tcg_const_tl(const4);
tcg_gen_movcond_tl(TCG_COND_NE, cpu_gpr_d[r1], cpu_gpr_d[15], temp,
temp2, cpu_gpr_d[r1]);
tcg_temp_free(temp);
tcg_temp_free(temp2);
break;
case OPC1_16_SRC_CMOVN:
temp = tcg_const_tl(0);
temp2 = tcg_const_tl(const4);
tcg_gen_movcond_tl(TCG_COND_EQ, cpu_gpr_d[r1], cpu_gpr_d[15], temp,
temp2, cpu_gpr_d[r1]);
tcg_temp_free(temp);
tcg_temp_free(temp2);
break;
case OPC1_16_SRC_EQ:
tcg_gen_setcondi_tl(TCG_COND_EQ, cpu_gpr_d[15], cpu_gpr_d[r1],
const4);
break;
case OPC1_16_SRC_LT:
tcg_gen_setcondi_tl(TCG_COND_LT, cpu_gpr_d[15], cpu_gpr_d[r1],
const4);
break;
case OPC1_16_SRC_MOV:
tcg_gen_movi_tl(cpu_gpr_d[r1], const4);
break;
case OPC1_16_SRC_MOV_A:
const4 = MASK_OP_SRC_CONST4(ctx->opcode);
tcg_gen_movi_tl(cpu_gpr_a[r1], const4);
break;
case OPC1_16_SRC_MOV_E:
if (tricore_feature(env, TRICORE_FEATURE_16)) {
tcg_gen_movi_tl(cpu_gpr_d[r1], const4);
tcg_gen_sari_tl(cpu_gpr_d[r1+1], cpu_gpr_d[r1], 31);
}
break;
case OPC1_16_SRC_SH:
gen_shi(cpu_gpr_d[r1], cpu_gpr_d[r1], const4);
break;
case OPC1_16_SRC_SHA:
gen_shaci(cpu_gpr_d[r1], cpu_gpr_d[r1], const4);
break;
}
}
| 1threat
|
Index and length must refer to a location within the string when I try to add an extra digit? : <p>Hello so I have a program that generates a Key when you fill in some info in some text boxes. When ever I generate a key that adds an extra 1 or 0 it tells me Index and length must refer to a location within the string, this is the code: </p>
<pre><code>public virtual string GenerateKey(string BreedPub)
{
return GenerateKey() + BreedPub.Substring(0, 3);
}
</code></pre>
<p>and I think it's conflicting with this:</p>
<pre><code>public override string GenerateKey(string BreedPub)
{
string key = null;
if (Pedigree == "1")
{
key = GenerateKey() + BreedPub.Substring(0, 3) + "1";
}
else
{
key = GenerateKey() + BreedPub.Substring(0, 3) + "0";
}
return key;
</code></pre>
<p>now i've tried to change the substring to (0,4) or doing this:</p>
<pre><code>public virtual string GenerateKey(string BreedPub)
{
if (Pedigree == "1")
{
return GenerateKey() + BreedPub.Substring(0, 3) + "1";
}
else if (Pedigree == "0")
{
return GenerateKey() + BreedPub.Substring(0, 3) + "0";
}
else
{
return GenerateKey() + BreedPub.Substring(0, 3);
}
}
</code></pre>
<p>but it still gives me the same error message, what could I be doing wrong?</p>
| 0debug
|
PHP only returns the the first value : This has 3 rows and 3 buttons each rows. So, when I input a value at the first row and click it's button, it inserts the data. And then when I input at the second row and click its button, it inserts the value at the first row. And there's also something wrong with the button. I think it's because they have the same div class. Is there any way or solution for this?
//AJAX + JQUERY.
$(.btn).click(function() {
$getComment = $(".divComment").val();
$getId= $(".inputId").val();
$("#divHolder").load("insertData.php",{
passComment: $getComment ,
passId: $getId
});
});
//PHP
<?php foreach($query as $querySHOW) {?>
<div id="divHolder">
<textarea class="divComment">COMMENT</textarea> //GET COMMENT
<input type="text" class="inputId" value"<?php echo $querySHOW['id'];?>"> //GET ID
<input type="button" class="btn"> //BUTTON CLICK
</div>
<?php } ?> //SHOWS 3 ROWS with 3 BUTTONS EACH ROWS
| 0debug
|
Header with lines on either side : <p>I<code>m writing a website, i</code>m newbie. Needs help with header, i don`t know how to create line on either side of header. Here is image [1]: <a href="https://imgur.com/a/slm22Pg" rel="nofollow noreferrer">https://imgur.com/a/slm22Pg</a> with that's what I mean.</p>
| 0debug
|
static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
{
target_long *stack = (void *)infop->start_stack;
memset(regs, 0, sizeof(*regs));
regs->ARM_cpsr = 0x10;
regs->ARM_pc = infop->entry;
regs->ARM_sp = infop->start_stack;
regs->ARM_r2 = tswapl(stack[2]);
regs->ARM_r1 = tswapl(stack[1]);
}
| 1threat
|
static void thumb_tr_translate_insn(DisasContextBase *dcbase, CPUState *cpu)
{
DisasContext *dc = container_of(dcbase, DisasContext, base);
CPUARMState *env = cpu->env_ptr;
uint32_t insn;
bool is_16bit;
if (arm_pre_translate_insn(dc)) {
return;
}
insn = arm_lduw_code(env, dc->pc, dc->sctlr_b);
is_16bit = thumb_insn_is_16bit(dc, insn);
dc->pc += 2;
if (!is_16bit) {
uint32_t insn2 = arm_lduw_code(env, dc->pc, dc->sctlr_b);
insn = insn << 16 | insn2;
dc->pc += 2;
}
dc->insn = insn;
if (dc->condexec_mask && !thumb_insn_is_unconditional(dc, insn)) {
uint32_t cond = dc->condexec_cond;
if (cond != 0x0e) {
dc->condlabel = gen_new_label();
arm_gen_test_cc(cond ^ 1, dc->condlabel);
dc->condjmp = 1;
}
}
if (is_16bit) {
disas_thumb_insn(dc, insn);
} else {
if (disas_thumb2_insn(dc, insn)) {
gen_exception_insn(dc, 4, EXCP_UDEF, syn_uncategorized(),
default_exception_el(dc));
}
}
if (dc->condexec_mask) {
dc->condexec_cond = ((dc->condexec_cond & 0xe) |
((dc->condexec_mask >> 4) & 1));
dc->condexec_mask = (dc->condexec_mask << 1) & 0x1f;
if (dc->condexec_mask == 0) {
dc->condexec_cond = 0;
}
}
arm_post_translate_insn(dc);
if (dc->base.is_jmp == DISAS_NEXT
&& (dc->pc >= dc->next_page_start
|| (dc->pc >= dc->next_page_start - 3
&& insn_crosses_page(env, dc)))) {
dc->base.is_jmp = DISAS_TOO_MANY;
}
}
| 1threat
|
python: How can I split and merge the dataframe? : Q1. I want to split the dataframe (from df1 to df2)
Q2. and also How I can i turn merge the dataframe (from df1 to df2)?
Dataframe df1
c1 c2
0 0 [{'a':1 ,'b':2},{'a':3 ,'b':4}]
1 1 [{'a':5 ,'b':6},{'a':7 ,'b':8}]
2 2 [{'a':9 ,'b':10},{'a':11,'b':12}]
Dataframe df2
c1 c2
0 0 {'a':1 ,'b':2}
1 0 {'a':3 ,'b':4}
2 1 {'a':5 ,'b':6}
3 1 {'a':7 ,'b':8}
4 2 {'a':9 ,'b':10}
5 2 {'a':11 ,'b':12}
| 0debug
|
How to use HTML5 color picker in Django admin : <p>I'm trying to implement the HTML5 colorpicker in Django's admin page.</p>
<p>Here is my model:</p>
<pre><code>#model.py
...
class Category(models.Model):
...
color = models.CharField(max_length=7)
</code></pre>
<p>Here is the form:</p>
<pre><code>#form.py
from django.forms import ModelForm
from django.forms.widgets import TextInput
from .models import Category
class CategoryForm(ModelForm):
class Meta:
model = Category
fields = '__all__'
widgets = {
'color': TextInput(attrs={'type': 'color'}),
}
class CategoryAdminForm(ModelForm):
form = CategoryForm
</code></pre>
<p>And finally the admin:</p>
<pre><code>#admin.py
...
from .forms import CategoryAdminForm
...
class CategoryAdmin(admin.ModelAdmin):
form_class = CategoryAdminForm
filter_horizontal = ('questions',)
fieldsets = (
(None, {
'fields': (('name', 'letter'), 'questions', 'color')
}),
)
</code></pre>
<p>However, the type for the field is still text. How do I change the type for the input field to color in the admin page?</p>
| 0debug
|
Front Degradation Issue : I'm beginning to learn the basics of HTML and CSS and am currently working through the FreeCodeCamp program. Currently, I cannot create an account to access the forums there so I'm going to attempt to solve it here. Within the problem, it's asking the user to add a second font and comment out the Google font import at the top. Everything is correct and accepted as so yet it's saying the H2 element must use the "Lobster" font. The problem is that the current font is already set the "Lobster".
I've tried adding a separate font-family beneath the Lobster font, but this removes the functionality of the degradation feature. This did not work. I also attempted to rearrange the formatting of the code but doing so breaks it even more. Here are the directions.
Your h2 element should use the font Lobster.
Your h2 element should degrade to the font monospace when Lobster is not available.
Comment out your call to Google for the Lobster font by putting <!-- in front of it.
Be sure to close your comment by adding -->.
<!--<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">-->
<style>
.red-text {
color: red;
}
h2 {
font-family: Lobster, monospace;
}
p {
font-size: 16px;
font-family: monospace;
}
</style>
<h2 class="red-text">CatPhotoApp</h2>
<main>
<p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<a href="#"><img src="image-removed" alt="A cute orange cat lying on its back."></a>
<div>
<p>Things cats love:</p>
<ul>
<li>cat nip</li>
<li>laser pointers</li>
<li>lasagna</li>
</ul>
<p>Top 3 things cats hate:</p>
<ol>
<li>flea treatment</li>
<li>thunder</li>
<li>other cats</li>
</ol>
</div>
<form action="/submit-cat-photo">
<label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<label><input type="checkbox" name="personality" checked> Loving</label>
<label><input type="checkbox" name="personality"> Lazy</label>
<label><input type="checkbox" name="personality"> Energetic</label><br>
<input type="text" placeholder="cat photo URL" required>
<button type="submit">Submit</button>
</form>
</main>
I expect everything to be correct as is, and for this to be an error on the program's end. Unlikely.. but I'm confident I followed the directions accurately.
| 0debug
|
static int copy_parameter_set(void **to, void **from, int count, int size)
{
int i;
for (i = 0; i < count; i++) {
if (to[i] && !from[i]) {
av_freep(&to[i]);
} else if (from[i] && !to[i]) {
to[i] = av_malloc(size);
if (!to[i])
return AVERROR(ENOMEM);
}
if (from[i])
memcpy(to[i], from[i], size);
}
return 0;
}
| 1threat
|
Absolute and Relative links : <p>I have a question about absolute and relatives links as I am working on an assignment and seem to be a bit confused... what are the different situations that each type of link would be used in? </p>
<p>Thank you! </p>
| 0debug
|
Adding images in OpenCV : <p>You can add two images by OpenCV function, <code>cv2.add()</code> or simply by numpy operation, <code>res = img1 + img2</code>. Both images should be of same depth and type, or second image can just be a scalar value.
What should i use to compare their depth and type of images.i have studied about</p>
<pre><code>img.dtype
img.type()
img.depth()
</code></pre>
<p>Please help.</p>
| 0debug
|
static int inet_listen_saddr(InetSocketAddress *saddr,
int port_offset,
bool update_addr,
Error **errp)
{
struct addrinfo ai,*res,*e;
char port[33];
char uaddr[INET6_ADDRSTRLEN+1];
char uport[33];
int rc, port_min, port_max, p;
int slisten = 0;
int saved_errno = 0;
bool socket_created = false;
Error *err = NULL;
memset(&ai,0, sizeof(ai));
ai.ai_flags = AI_PASSIVE;
if (saddr->has_numeric && saddr->numeric) {
ai.ai_flags |= AI_NUMERICHOST | AI_NUMERICSERV;
}
ai.ai_family = inet_ai_family_from_address(saddr, &err);
ai.ai_socktype = SOCK_STREAM;
if (err) {
error_propagate(errp, err);
return -1;
}
if (saddr->host == NULL) {
error_setg(errp, "host not specified");
return -1;
}
if (saddr->port != NULL) {
pstrcpy(port, sizeof(port), saddr->port);
} else {
port[0] = '\0';
}
if (port_offset) {
unsigned long long baseport;
if (strlen(port) == 0) {
error_setg(errp, "port not specified");
return -1;
}
if (parse_uint_full(port, &baseport, 10) < 0) {
error_setg(errp, "can't convert to a number: %s", port);
return -1;
}
if (baseport > 65535 ||
baseport + port_offset > 65535) {
error_setg(errp, "port %s out of range", port);
return -1;
}
snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
}
rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,
strlen(port) ? port : NULL, &ai, &res);
if (rc != 0) {
error_setg(errp, "address resolution failed for %s:%s: %s",
saddr->host, port, gai_strerror(rc));
return -1;
}
for (e = res; e != NULL; e = e->ai_next) {
getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
uaddr,INET6_ADDRSTRLEN,uport,32,
NI_NUMERICHOST | NI_NUMERICSERV);
slisten = create_fast_reuse_socket(e);
if (slisten < 0) {
continue;
}
socket_created = true;
port_min = inet_getport(e);
port_max = saddr->has_to ? saddr->to + port_offset : port_min;
for (p = port_min; p <= port_max; p++) {
inet_setport(e, p);
rc = try_bind(slisten, saddr, e);
if (rc) {
if (errno == EADDRINUSE) {
continue;
} else {
error_setg_errno(errp, errno, "Failed to bind socket");
goto listen_failed;
}
}
if (!listen(slisten, 1)) {
goto listen_ok;
}
if (errno != EADDRINUSE) {
error_setg_errno(errp, errno, "Failed to listen on socket");
goto listen_failed;
}
closesocket(slisten);
slisten = create_fast_reuse_socket(e);
if (slisten < 0) {
error_setg_errno(errp, errno,
"Failed to recreate failed listening socket");
goto listen_failed;
}
}
}
error_setg_errno(errp, errno,
socket_created ?
"Failed to find an available port" :
"Failed to create a socket");
listen_failed:
saved_errno = errno;
if (slisten >= 0) {
closesocket(slisten);
}
freeaddrinfo(res);
errno = saved_errno;
return -1;
listen_ok:
if (update_addr) {
g_free(saddr->host);
saddr->host = g_strdup(uaddr);
g_free(saddr->port);
saddr->port = g_strdup_printf("%d",
inet_getport(e) - port_offset);
saddr->has_ipv6 = saddr->ipv6 = e->ai_family == PF_INET6;
saddr->has_ipv4 = saddr->ipv4 = e->ai_family != PF_INET6;
}
freeaddrinfo(res);
return slisten;
}
| 1threat
|
Why this is not giving compilation error : <pre><code>#include<stdio.h>
#define A -B
#define B -C
#define C 5
int main()
{
printf("The value of A is %d\n", A);
return 0;
}
</code></pre>
<p>In this, Macros as just get replaced -B becomes --C and finally --5.But This should give compilation error as 5 is a constant right?But it actually prints
"The value of A is 5"
Can anyone explain me clearly when will we get l-value error exactly? Because the following code actually gives l-value required error.</p>
<pre><code>#include <stdio.h>
#define PRINT(i, limit) do \
{ \
if (i++ < limit) \
{ \
printf("GeeksQuiz\n"); \
continue; \
} \
}while(1)
int main()
{
PRINT(0, 3);
return 0;
}
</code></pre>
<p>Please give me a clear idea when l-value error occurs.I'm tired many times searching an exact reason when will we get l-value error.</p>
| 0debug
|
static abi_long do_sendrecvmsg_locked(int fd, struct target_msghdr *msgp,
int flags, int send)
{
abi_long ret, len;
struct msghdr msg;
int count;
struct iovec *vec;
abi_ulong target_vec;
if (msgp->msg_name) {
msg.msg_namelen = tswap32(msgp->msg_namelen);
msg.msg_name = alloca(msg.msg_namelen+1);
ret = target_to_host_sockaddr(fd, msg.msg_name,
tswapal(msgp->msg_name),
msg.msg_namelen);
if (ret) {
goto out2;
}
} else {
msg.msg_name = NULL;
msg.msg_namelen = 0;
}
msg.msg_controllen = 2 * tswapal(msgp->msg_controllen);
msg.msg_control = alloca(msg.msg_controllen);
msg.msg_flags = tswap32(msgp->msg_flags);
count = tswapal(msgp->msg_iovlen);
target_vec = tswapal(msgp->msg_iov);
vec = lock_iovec(send ? VERIFY_READ : VERIFY_WRITE,
target_vec, count, send);
if (vec == NULL) {
ret = -host_to_target_errno(errno);
goto out2;
}
msg.msg_iovlen = count;
msg.msg_iov = vec;
if (send) {
if (fd_trans_target_to_host_data(fd)) {
ret = fd_trans_target_to_host_data(fd)(msg.msg_iov->iov_base,
msg.msg_iov->iov_len);
} else {
ret = target_to_host_cmsg(&msg, msgp);
}
if (ret == 0) {
ret = get_errno(safe_sendmsg(fd, &msg, flags));
}
} else {
ret = get_errno(safe_recvmsg(fd, &msg, flags));
if (!is_error(ret)) {
len = ret;
if (fd_trans_host_to_target_data(fd)) {
ret = fd_trans_host_to_target_data(fd)(msg.msg_iov->iov_base,
len);
} else {
ret = host_to_target_cmsg(msgp, &msg);
}
if (!is_error(ret)) {
msgp->msg_namelen = tswap32(msg.msg_namelen);
if (msg.msg_name != NULL) {
ret = host_to_target_sockaddr(tswapal(msgp->msg_name),
msg.msg_name, msg.msg_namelen);
if (ret) {
goto out;
}
}
ret = len;
}
}
}
out:
unlock_iovec(vec, target_vec, count, !send);
out2:
return ret;
}
| 1threat
|
Wy viewWithTag is returning nil : activite1Label as the tag 1
class StatsViewController: UIViewController {
@IBOutlet weak var activite1Label: UILabel!
@IBOutlet weak var activite2Label: UILabel!
@IBOutlet weak var activite3Label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
activite1Label.text = activite[0]
activite2Label.text = activite[1]
activite3Label.text = activite[2]
miseAjourTotal()
}
func miseAjourTotal() {
let leLabel = view.viewWithTag(1) as! UILabel
print("leLabel: \(leLabel.text)")
}
}
| 0debug
|
how to show selected item in another activityin android : <p>I am new in android. My app is basically is shoppping cart.Now I want help.
when user select items from custom listview.Those items display with image ,name and quantity to next activity such as view cart.I have been searching tutorial but cannot find a complete one. Can anyone guide me through proper code how could I do this?</p>
| 0debug
|
static enum AVPixelFormat get_chroma_format(SchroChromaFormat schro_pix_fmt)
{
int num_formats = sizeof(schro_pixel_format_map) /
sizeof(schro_pixel_format_map[0]);
int idx;
for (idx = 0; idx < num_formats; ++idx)
if (schro_pixel_format_map[idx].schro_pix_fmt == schro_pix_fmt)
return schro_pixel_format_map[idx].ff_pix_fmt;
return AV_PIX_FMT_NONE;
}
| 1threat
|
ES6 - is there an elegant way to import all named exports but not the default export? : <p>I am looking for an elegant way to import all named exports without having to import the default as well.</p>
<p>In one file I am exporting many named constants plus a default:</p>
<pre><code>// myModule.js
const myDefault = 'my default'
export const named1 = 'named1'
export const named2 = 'named2'
// many more named exports - otherwise this would not be an issue...
export default myDefault
</code></pre>
<p>In another file I would like to have an elegant way to import all named exports <strong>only</strong>, without having to import the default:</p>
<pre><code>// anotherFile.js
// this is what I would like to do, but syntax is not supported, right?
import { * as namedOnly } from './myModule'
</code></pre>
<p>I do <strong>not</strong> want to:</p>
<pre><code>// anotherFile.js
import myDefault, * as namedOnly from './myModule'
</code></pre>
<p>because I do not need the default in <code>anotherFile.js</code> and my linting tools bug me about
the defined but unused <code>myDefault</code>. Nor do I want to:</p>
<pre><code>// anotherFile.js
import {
named1,
named2,
... // many more
} from './myModule'
</code></pre>
<p>because that's too much typing. I also do <strong>not</strong> want to <code>object.omit</code> the default:</p>
<pre><code>// anotherFile.js
import omit from 'object.omit'
import * as all from './myModule'
const namedOnly = omit(all, 'default')
</code></pre>
<p>Thanks for any help!</p>
| 0debug
|
static int vorbis_packet(AVFormatContext *s, int idx)
{
struct ogg *ogg = s->priv_data;
struct ogg_stream *os = ogg->streams + idx;
struct oggvorbis_private *priv = os->private;
int duration;
if (!os->lastpts) {
int seg;
uint8_t *last_pkt = os->buf + os->pstart;
uint8_t *next_pkt = last_pkt;
int first_duration = 0;
avpriv_vorbis_parse_reset(&priv->vp);
duration = 0;
for (seg = 0; seg < os->nsegs; seg++) {
if (os->segments[seg] < 255) {
int d = avpriv_vorbis_parse_frame(&priv->vp, last_pkt, 1);
if (d < 0) {
duration = os->granule;
break;
}
if (!duration)
first_duration = d;
duration += d;
last_pkt = next_pkt + os->segments[seg];
}
next_pkt += os->segments[seg];
}
os->lastpts = os->lastdts = os->granule - duration;
s->streams[idx]->start_time = os->lastpts + first_duration;
if (s->streams[idx]->duration)
s->streams[idx]->duration -= s->streams[idx]->start_time;
s->streams[idx]->cur_dts = AV_NOPTS_VALUE;
priv->final_pts = AV_NOPTS_VALUE;
avpriv_vorbis_parse_reset(&priv->vp);
}
if (os->psize > 0) {
duration = avpriv_vorbis_parse_frame(&priv->vp, os->buf + os->pstart, 1);
if (duration <= 0) {
os->pflags |= AV_PKT_FLAG_CORRUPT;
return 0;
}
os->pduration = duration;
}
if (os->flags & OGG_FLAG_EOS) {
if (os->lastpts != AV_NOPTS_VALUE) {
priv->final_pts = os->lastpts;
priv->final_duration = 0;
}
if (os->segp == os->nsegs)
os->pduration = os->granule - priv->final_pts - priv->final_duration;
priv->final_duration += os->pduration;
}
return 0;
}
| 1threat
|
How can I change the control sourse in TFS2018 : Could you please tell me how I can change the control source in one project with TFS on Git. Thanks.
| 0debug
|
Glob Sync Pattern on multiple directories : <p>I am trying to achieve a <code>glob</code> sync pattern that allows me to meet the following criteria, but unfortunately, im having a hard time working out why the pattern isn't working.</p>
<p><strong>Glob Pattern</strong></p>
<p><code>glob.sync("./src/handlebar/{a, b, c, d}/**/*.hbs")</code></p>
<p><strong>File Path Patterns</strong></p>
<pre><code>src/handlebar/b/a/header.hbs
src/handlebar/b/header.hbs
src/handlebar/a/head.hbs [MATCH]
src/handlebar/a/foot.hbs [MATCH]
src/handlebar/c/a/something.hbs
src/handlebar/d/a/button.hbs
</code></pre>
<p>What am i doing wrong?</p>
| 0debug
|
Will I be able to test this PHP? : <p>So I have 2 websites. One is currently hosted on a domain and one is just local on my computer (viewing it using brackets live preview).</p>
<p>I used the hosted website (#1) to create a mysql database. </p>
<p>Then for my local website (#2) I created a login page and created a index.php document to handle the submission. In the index.php of the local website I told it to connect to the mysql database of the hosted website.</p>
<p>Then when I try to preview the local page and submit it, I get this error</p>
<p><strong>"Cannot GET /POST?name=JohnDoe&password=123"</strong></p>
<p>So I am wondering, since my sql database is hosted online, can I actually test my website locally or not?</p>
| 0debug
|
static int decode_header(MPADecodeContext *s, uint32_t header)
{
int sample_rate, frame_size, mpeg25, padding;
int sample_rate_index, bitrate_index;
if (header & (1<<20)) {
s->lsf = (header & (1<<19)) ? 0 : 1;
mpeg25 = 0;
} else {
s->lsf = 1;
mpeg25 = 1;
}
s->layer = 4 - ((header >> 17) & 3);
sample_rate_index = (header >> 10) & 3;
sample_rate = mpa_freq_tab[sample_rate_index] >> (s->lsf + mpeg25);
sample_rate_index += 3 * (s->lsf + mpeg25);
s->sample_rate_index = sample_rate_index;
s->error_protection = ((header >> 16) & 1) ^ 1;
s->sample_rate = sample_rate;
bitrate_index = (header >> 12) & 0xf;
padding = (header >> 9) & 1;
s->mode = (header >> 6) & 3;
s->mode_ext = (header >> 4) & 3;
if (s->mode == MPA_MONO)
s->nb_channels = 1;
else
s->nb_channels = 2;
if (bitrate_index != 0) {
frame_size = mpa_bitrate_tab[s->lsf][s->layer - 1][bitrate_index];
s->bit_rate = frame_size * 1000;
switch(s->layer) {
case 1:
frame_size = (frame_size * 12000) / sample_rate;
frame_size = (frame_size + padding) * 4;
break;
case 2:
frame_size = (frame_size * 144000) / sample_rate;
frame_size += padding;
break;
default:
case 3:
frame_size = (frame_size * 144000) / (sample_rate << s->lsf);
frame_size += padding;
break;
}
s->frame_size = frame_size;
} else {
if (!s->free_format_frame_size)
return 1;
s->frame_size = s->free_format_frame_size;
switch(s->layer) {
case 1:
s->frame_size += padding * 4;
s->bit_rate = (s->frame_size * sample_rate) / 48000;
break;
case 2:
s->frame_size += padding;
s->bit_rate = (s->frame_size * sample_rate) / 144000;
break;
default:
case 3:
s->frame_size += padding;
s->bit_rate = (s->frame_size * (sample_rate << s->lsf)) / 144000;
break;
}
}
#if defined(DEBUG)
dprintf("layer%d, %d Hz, %d kbits/s, ",
s->layer, s->sample_rate, s->bit_rate);
if (s->nb_channels == 2) {
if (s->layer == 3) {
if (s->mode_ext & MODE_EXT_MS_STEREO)
dprintf("ms-");
if (s->mode_ext & MODE_EXT_I_STEREO)
dprintf("i-");
}
dprintf("stereo");
} else {
dprintf("mono");
}
dprintf("\n");
#endif
return 0;
}
| 1threat
|
static ram_addr_t kqemu_ram_alloc(ram_addr_t size)
{
ram_addr_t addr;
if ((last_ram_offset + size) > kqemu_phys_ram_size) {
fprintf(stderr, "Not enough memory (requested_size = %" PRIu64 ", max memory = %" PRIu64 ")\n",
(uint64_t)size, (uint64_t)kqemu_phys_ram_size);
abort();
}
addr = last_ram_offset;
last_ram_offset = TARGET_PAGE_ALIGN(last_ram_offset + size);
return addr;
}
| 1threat
|
Is it possible to start a stopped container from another container : <p>There are two containers A and B. Once container A starts, one process will be executed, then the container will stop. Container B is just an web application (say expressjs). Is it possible to kickstart A from container B ?</p>
| 0debug
|
static int w64_read_header(AVFormatContext *s)
{
int64_t size, data_ofs = 0;
AVIOContext *pb = s->pb;
WAVDemuxContext *wav = s->priv_data;
AVStream *st;
uint8_t guid[16];
int ret;
avio_read(pb, guid, 16);
if (memcmp(guid, ff_w64_guid_riff, 16))
if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8)
avio_read(pb, guid, 16);
if (memcmp(guid, ff_w64_guid_wave, 16)) {
av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
}
wav->w64 = 1;
st = avformat_new_stream(s, NULL);
if (!st)
return AVERROR(ENOMEM);
while (!avio_feof(pb)) {
if (avio_read(pb, guid, 16) != 16)
break;
size = avio_rl64(pb);
if (size <= 24 || INT64_MAX - size < avio_tell(pb))
if (!memcmp(guid, ff_w64_guid_fmt, 16)) {
ret = ff_get_wav_header(s, pb, st->codecpar, size - 24, 0);
if (ret < 0)
return ret;
avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
} else if (!memcmp(guid, ff_w64_guid_fact, 16)) {
int64_t samples;
samples = avio_rl64(pb);
if (samples > 0)
st->duration = samples;
} else if (!memcmp(guid, ff_w64_guid_data, 16)) {
wav->data_end = avio_tell(pb) + size - 24;
data_ofs = avio_tell(pb);
if (!(pb->seekable & AVIO_SEEKABLE_NORMAL))
break;
avio_skip(pb, size - 24);
} else if (!memcmp(guid, ff_w64_guid_summarylist, 16)) {
int64_t start, end, cur;
uint32_t count, chunk_size, i;
start = avio_tell(pb);
end = start + FFALIGN(size, INT64_C(8)) - 24;
count = avio_rl32(pb);
for (i = 0; i < count; i++) {
char chunk_key[5], *value;
if (avio_feof(pb) || (cur = avio_tell(pb)) < 0 || cur > end - 8 )
break;
chunk_key[4] = 0;
avio_read(pb, chunk_key, 4);
chunk_size = avio_rl32(pb);
value = av_mallocz(chunk_size + 1);
if (!value)
return AVERROR(ENOMEM);
ret = avio_get_str16le(pb, chunk_size, value, chunk_size);
avio_skip(pb, chunk_size - ret);
av_dict_set(&s->metadata, chunk_key, value, AV_DICT_DONT_STRDUP_VAL);
}
avio_skip(pb, end - avio_tell(pb));
} else {
av_log(s, AV_LOG_DEBUG, "unknown guid: "FF_PRI_GUID"\n", FF_ARG_GUID(guid));
avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
}
}
if (!data_ofs)
return AVERROR_EOF;
ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
handle_stream_probing(st);
st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
avio_seek(pb, data_ofs, SEEK_SET);
set_spdif(s, wav);
return 0;
}
| 1threat
|
Regular expression to get a string between two strings in Javascript. The 2 strings are bookended by quotes : I have the below string that I need help pulling an ID from in Presto. Presto uses the javascript regex.
I need to pull the GA Client ID which looks like this:
```75714ae471df63202106404675dasd800097erer1849995367```
Below is a snipped where it sits in the string.
The struggle is that the "s:38:" is not constant. The number can be anything. For example, it could be s:40: or s:1000: etc. I need it to return just the alphanumeric id.
String Snippet
```
"GA_ClientID__c";s:38:"75714ae471df63202106404675dasd800097erer1849995367";
```
Full string listed below
```
99524";s:9:"FirstName";s:2:"John";s:8:"LastName";s:8:"Doe";s:7:"Company";s:10:"Sample";s:5:"Email";s:20:"xxxxx@gmail.com";s:5:"Phone";s:10:"8888888888";s:7:"Country";s:13:"United States";s:5:"Title";s:8:"Creative";s:5:"State";s:2:"NC";s:13:"Last_Asset__c";s:40:"White Paper: Be a More Strategic Partner";s:16:"Last_Campaign__c";s:18:"70160000000q6TgAAI";s:16:"Referring_URL__c";s:8:"[direct]";s:19:"leadPriorityMarketo";s:2:"P2";s:18:"ProductInterest__c";s:9:"sample";s:14:"landingpageurl";s:359:"https://www.sample.com;mkt_tok=samplesamplesamplesample";s:14:"GA_ClientID__c";s:38:"75714ae471df63202106404675dasd800097erer1849995367";s:13:"Drupal_SID__c";s:36:"e1380c07-0258-47de-aaf8-82d4d8061e1a";s:4:"form";s:4:"1046";} ```
| 0debug
|
static uint32_t pmac_ide_readl (void *opaque,target_phys_addr_t addr)
{
uint32_t retval;
MACIOIDEState *d = opaque;
addr = (addr & 0xFFF) >> 4;
if (addr == 0) {
retval = ide_data_readl(&d->bus, 0);
} else {
retval = 0xFFFFFFFF;
}
retval = bswap32(retval);
return retval;
}
| 1threat
|
How can I create JavaScript sliders that emulate the ones on the New York Times "Rent or Buy" web site? : <p>I love the way the sliders on this web site work. How in the world can I make ones that look and act like them? In particular, I love that everything they are connected to update on the fly. I love that they are non-linear. They have a large touch input grab zone but a small slider icon. And I love that the don't engage if a mobile users touches them but then slides their finger off. It does a great job of preventing accidental touches. </p>
<p><a href="https://www.nytimes.com/interactive/2014/upshot/buy-rent-calculator.html" rel="nofollow noreferrer">https://www.nytimes.com/interactive/2014/upshot/buy-rent-calculator.html</a></p>
<p>I tried using a JS library called ionRangeSlider, but it doesn't feel as slick as the NYT ones. And it doesn't prevent accidental touch inputs.</p>
<p>Any help would be very appreciated.</p>
| 0debug
|
Jupyter Notebook: interactive plot with widgets : <p>I am trying to generate an interactive plot that depends on widgets.
The problem I have is that when I change parameters using the slider, a new plot is done after the previous one, instead I would expect only one plot changing according to the parameters.</p>
<p><strong>Example:</strong></p>
<pre><code>from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
def plot_func(freq):
x = np.linspace(0, 2*np.pi)
y = np.sin(x * freq)
plt.plot(x, y)
interact(plot_func, freq = widgets.FloatSlider(value=7.5,
min=1,
max=5.0,
step=0.5))
</code></pre>
<p>After moving the slider to 4.0, I have:</p>
<p><a href="https://i.stack.imgur.com/7zhnE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7zhnE.png" alt="enter image description here"></a></p>
<p>while I just want one figure to change as I move the slider.
How can I achieve this?</p>
<p>(I am using Python 2.7, matplotlib 2.0 and I have just updated notebook and jupyter to the latest version. let me know if further info is needed.)</p>
| 0debug
|
Type 'string' is not assignable to type '"inherit" | "initial" | "unset" | "fixed" | "absolute" | "static" | "relative" | "sticky"' : <p>I get the following error in my application (npm 5.4.2, react 15.4, typescript 2.5.3, webpack 2.2.1, webpack-dev-server 2.4.1).</p>
<p>This will work:</p>
<pre><code><div style={{position: 'absolute'}}>working</div>
</code></pre>
<p>This will not compile:</p>
<pre><code>const mystyle = {
position: 'absolute'
}
<div style={mystyle}>not working</div>
</code></pre>
<p>The compile error is:</p>
<pre><code>ERROR in ./src/components/Resource.tsx
(61,18): error TS2322: Type '{ style: { position: string; }; children: string; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.
Type '{ style: { position: string; }; children: string; }' is not assignable to type 'HTMLAttributes<HTMLDivElement>'.
Types of property 'style' are incompatible.
Type '{ position: string; }' is not assignable to type 'CSSProperties'.
Types of property 'position' are incompatible.
Type 'string' is not assignable to type '"inherit" | "initial" | "unset" | "fixed" | "absolute" | "static" | "relative" | "sticky"'.
webpack: Failed to compile.
</code></pre>
<p>But what't the difference?
I can fix it with: </p>
<pre><code>const mystyle = {
position: 'absolute' as 'absolute'
}
</code></pre>
<p>but is this a good solution? </p>
<p>I don't have this problem with other style/css properties.</p>
<p>I found a similar problem on github:
<a href="https://github.com/Microsoft/TypeScript/issues/11465" rel="noreferrer">https://github.com/Microsoft/TypeScript/issues/11465</a>
but if understand it right, it was a typescript bug in an ealier version. </p>
<p>Any help appreciated.</p>
| 0debug
|
How do I serialize an object for the query in a GET request? : <p>I'm trying to serialize an object in JavaScript so that I can query it in a GET request.</p>
| 0debug
|
sorry if this question is so simple. how to produce output string and numbering from the same statement in python?eg. "output_CH = 0.7 and CH_healthy" : if input_CH in range (185, 211):
if input_CH >= 185 and input_CH < 190:
output_CH = (1/5 * input_CH) - 37
elif input_CH >= 190 and input_CH <= 200:
output_CH = 1
else:
output_CH = (-1/10 * input_CH) + 21
output_CH = "CH_healthy"
| 0debug
|
What are best practises with Django to handle big dropdown list? : Problem is simple, for fields based on foreign key dropdowns generated some dropdowns, eventually those can become very big and it is difficult to select needed value for end user.(currently we use crispy forms for auto formating.)
I subdivided the values to categories but I do not like this solution because it forces end user to maintain unnecessary business logic.
What is the besttechnique to address this issue in Django ?
| 0debug
|
static IOMMUTLBEntry spapr_tce_translate_iommu(MemoryRegion *iommu, hwaddr addr,
bool is_write)
{
sPAPRTCETable *tcet = container_of(iommu, sPAPRTCETable, iommu);
uint64_t tce;
IOMMUTLBEntry ret = {
.target_as = &address_space_memory,
.iova = 0,
.translated_addr = 0,
.addr_mask = ~(hwaddr)0,
.perm = IOMMU_NONE,
};
if ((addr >> tcet->page_shift) < tcet->nb_table) {
hwaddr page_mask = IOMMU_PAGE_MASK(tcet->page_shift);
tce = tcet->table[addr >> tcet->page_shift];
ret.iova = addr & page_mask;
ret.translated_addr = tce & page_mask;
ret.addr_mask = ~page_mask;
ret.perm = spapr_tce_iommu_access_flags(tce);
}
trace_spapr_iommu_xlate(tcet->liobn, addr, ret.iova, ret.perm,
ret.addr_mask);
return ret;
}
| 1threat
|
static void v9fs_rename(void *opaque)
{
int32_t fid;
ssize_t err = 0;
size_t offset = 7;
V9fsString name;
int32_t newdirfid;
V9fsFidState *fidp;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dds", &fid, &newdirfid, &name);
if (err < 0) {
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
BUG_ON(fidp->fid_type != P9_FID_NONE);
if (!(pdu->s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT)) {
err = -EOPNOTSUPP;
goto out;
v9fs_path_write_lock(s);
err = v9fs_complete_rename(pdu, fidp, newdirfid, &name);
v9fs_path_unlock(s);
if (!err) {
err = offset;
out:
put_fid(pdu, fidp);
out_nofid:
pdu_complete(pdu, err);
v9fs_string_free(&name);
| 1threat
|
How do I add 1 element to array with loops? : <p>I'm trying to loop through array and if element is null I will add a string inputted by the user. When I run it, it spits out the loop however big my array is. I want just to add 1 string and go back to a switch. How do i go about this?</p>
<pre><code>public void insertNames() {
int i;
for(i=0; i < names.length; i++) {
if(names[i] == null) {
System.out.println("Enter name: ");
names[i] = input.toString();
while(i == names.length); {
System.err.println("Array is full, cannot add any more elements");
</code></pre>
<p>I expect just looping through till I find null and adding string inputted by user and go back to switch
Im experiencing when I find null it will prompt user for input, but then move to the next element</p>
| 0debug
|
static int xan_huffman_decode(unsigned char *dest, int dest_len,
const unsigned char *src, int src_len)
{
unsigned char byte = *src++;
unsigned char ival = byte + 0x16;
const unsigned char * ptr = src + byte*2;
int ptr_len = src_len - 1 - byte*2;
unsigned char val = ival;
unsigned char *dest_end = dest + dest_len;
GetBitContext gb;
if (ptr_len < 0)
return AVERROR_INVALIDDATA;
init_get_bits(&gb, ptr, ptr_len * 8);
while ( val != 0x16 ) {
val = src[val - 0x17 + get_bits1(&gb) * byte];
if ( val < 0x16 ) {
if (dest >= dest_end)
return 0;
*dest++ = val;
val = ival;
}
}
return 0;
}
| 1threat
|
syntax error: `(' unexpected in shell script : <p>I have a shell script which contains some functions in it. One of those functions has to be executed through perl. The perl functions checks whether port is opened on a remote server or not.</p>
<pre><code>#!/usr/bin/ksh
function1
function2
telnet_check()
{
#!/usr/bin/perl -w
use IO::Socket;
use IO::Socket::INET;
my ($host,$port);
$host=Ip address ;
$port=9443;
my $sock=IO::Socket::INET->new("Ip address:$port") or die "" ;
}
some shell commands
</code></pre>
<p>while executing the above script, am getting the error </p>
<pre><code> syntax error at line: `(' unexpected [which falls in the line my ($host,$port); under the Perl function]
</code></pre>
<p>Could any one help what can be done to fix the above error.</p>
<p>Cheers in Advance :)</p>
| 0debug
|
int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
{
int ret, i, err;
AVStream *st;
for (;;) {
AVPacketList *pktl = s->internal->raw_packet_buffer;
if (pktl) {
*pkt = pktl->pkt;
st = s->streams[pkt->stream_index];
if (s->internal->raw_packet_buffer_remaining_size <= 0)
if ((err = probe_codec(s, st, NULL)) < 0)
return err;
if (st->request_probe <= 0) {
s->internal->raw_packet_buffer = pktl->next;
s->internal->raw_packet_buffer_remaining_size += pkt->size;
av_free(pktl);
return 0;
pkt->data = NULL;
pkt->size = 0;
av_init_packet(pkt);
ret = s->iformat->read_packet(s, pkt);
if (ret < 0) {
if (ret == FFERROR_REDO)
continue;
if (!pktl || ret == AVERROR(EAGAIN))
return ret;
for (i = 0; i < s->nb_streams; i++) {
st = s->streams[i];
if (st->probe_packets || st->request_probe > 0)
if ((err = probe_codec(s, st, NULL)) < 0)
return err;
av_assert0(st->request_probe <= 0);
continue;
if (!pkt->buf) {
AVPacket tmp = { 0 };
ret = av_packet_ref(&tmp, pkt);
if (ret < 0)
return ret;
*pkt = tmp;
if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
(pkt->flags & AV_PKT_FLAG_CORRUPT)) {
av_log(s, AV_LOG_WARNING,
"Dropped corrupted packet (stream = %d)\n",
pkt->stream_index);
av_packet_unref(pkt);
continue;
if (pkt->stream_index >= (unsigned)s->nb_streams) {
av_log(s, AV_LOG_ERROR, "Invalid stream index %d\n", pkt->stream_index);
continue;
st = s->streams[pkt->stream_index];
if (update_wrap_reference(s, st, pkt->stream_index, pkt) && st->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET) {
if (!is_relative(st->first_dts))
st->first_dts = wrap_timestamp(st, st->first_dts);
if (!is_relative(st->start_time))
st->start_time = wrap_timestamp(st, st->start_time);
if (!is_relative(st->cur_dts))
st->cur_dts = wrap_timestamp(st, st->cur_dts);
pkt->dts = wrap_timestamp(st, pkt->dts);
pkt->pts = wrap_timestamp(st, pkt->pts);
force_codec_ids(s, st);
if (s->use_wallclock_as_timestamps)
pkt->dts = pkt->pts = av_rescale_q(av_gettime(), AV_TIME_BASE_Q, st->time_base);
if (!pktl && st->request_probe <= 0)
return ret;
err = add_to_pktbuf(&s->internal->raw_packet_buffer, pkt,
&s->internal->raw_packet_buffer_end, 0);
if (err)
return err;
s->internal->raw_packet_buffer_remaining_size -= pkt->size;
if ((err = probe_codec(s, st, pkt)) < 0)
return err;
| 1threat
|
Git, error: remote unpack failed: unable to create temporary object directory - By creating new Branch : <p>Good Day.</p>
<p>I Try to create a new Branch in my Repo.</p>
<p>I made this:</p>
<blockquote>
<p>Git branch events</p>
<p>Git Checkout events</p>
</blockquote>
<p>That worked. So I changed some files and made</p>
<blockquote>
<p>Git Status</p>
<p>Git add --all</p>
<p>Git Commit -m "Commit"</p>
</blockquote>
<p>That worked well but I tried to push it and that didn't work:</p>
<blockquote>
<p>Git push -u origin events</p>
</blockquote>
<p>This is the Error:</p>
<blockquote>
<p>Enumerating objects: 9, done.<br>
Counting objects: 100% (9/9), done.<br>
Delta compression using up to 4 threads.<br>
Compressing objects: 100% (5/5), done.<br>
Writing objects: 100% (5/5), 716 bytes | 716.00 KiB/s, done.<br>
Total 5 (delta 4), reused 0 (delta 0)<br>
error: remote unpack failed: unable to create temporary object directory<br>
To <a href="http://git.int.censoredlink/scm/freeb/freebrep.git" rel="noreferrer">http://git.int.censoredlink/scm/freeb/freebrep.git</a><br>
! [remote rejected] events -> events (unpacker error)<br>
error: failed to push some refs to '<a href="http://stsu@git.int.censoredlink/scm/freeb/freebrep.git" rel="noreferrer">http://stsu@git.int.censoredlink/scm/freeb/freebrep.git</a>'</p>
</blockquote>
<p>I don't know why it don't work.</p>
<p>I have Admin rights on the Repo. I censored the link to the repo because its a Intern Repo with Private link hope thats ok.</p>
<p>Hope someone can help me.</p>
| 0debug
|
Angular/RxJS 6: How to prevent duplicate HTTP requests? : <p>Currently have a scenario where a method within a shared service is used by multiple components. This method makes an HTTP call to an endpoint that will always have the same response and returns an Observable. Is it possible to share the first response with all subscribers to prevent duplicate HTTP requests?</p>
<p>Below is a simplified version of the scenario described above: </p>
<pre class="lang-js prettyprint-override"><code>class SharedService {
constructor(private http: HttpClient) {}
getSomeData(): Observable<any> {
return this.http.get<any>('some/endpoint');
}
}
class Component1 {
constructor(private sharedService: SharedService) {
this.sharedService.getSomeData().subscribe(
() => console.log('do something...')
);
}
}
class Component2 {
constructor(private sharedService: SharedService) {
this.sharedService.getSomeData().subscribe(
() => console.log('do something different...')
);
}
}
</code></pre>
| 0debug
|
How to bind default value in mat-radio-group angular reactive forms : <p>In my case it needs to active option 01 as default selection. It is working with checked=true property, but value is not binding with the formControlName="options", it is binding when user select any option. if no any user selection options value shows as "null".</p>
<pre class="lang-html prettyprint-override"><code> <div class="row">
<mat-radio-group formControlName="options">
<mat-radio-button checked=true value="1">Option 01</mat-radio-button>
<mat-radio-button value="2">Option 02</mat-radio-button>
</mat-radio-group>
</div>
</code></pre>
<p>Please kindly help me to resolve this issue. Thank you.</p>
| 0debug
|
static int pic_arrays_init(HEVCContext *s, const HEVCSPS *sps)
{
int log2_min_cb_size = sps->log2_min_cb_size;
int width = sps->width;
int height = sps->height;
int pic_size_in_ctb = ((width >> log2_min_cb_size) + 1) *
((height >> log2_min_cb_size) + 1);
int ctb_count = sps->ctb_width * sps->ctb_height;
int min_pu_size = sps->min_pu_width * sps->min_pu_height;
s->bs_width = (width >> 2) + 1;
s->bs_height = (height >> 2) + 1;
s->sao = av_mallocz_array(ctb_count, sizeof(*s->sao));
s->deblock = av_mallocz_array(ctb_count, sizeof(*s->deblock));
if (!s->sao || !s->deblock)
goto fail;
s->skip_flag = av_malloc(sps->min_cb_height * sps->min_cb_width);
s->tab_ct_depth = av_malloc_array(sps->min_cb_height, sps->min_cb_width);
if (!s->skip_flag || !s->tab_ct_depth)
goto fail;
s->cbf_luma = av_malloc_array(sps->min_tb_width, sps->min_tb_height);
s->tab_ipm = av_mallocz(min_pu_size);
s->is_pcm = av_malloc((sps->min_pu_width + 1) * (sps->min_pu_height + 1));
if (!s->tab_ipm || !s->cbf_luma || !s->is_pcm)
goto fail;
s->filter_slice_edges = av_malloc(ctb_count);
s->tab_slice_address = av_malloc_array(pic_size_in_ctb,
sizeof(*s->tab_slice_address));
s->qp_y_tab = av_malloc_array(pic_size_in_ctb,
sizeof(*s->qp_y_tab));
if (!s->qp_y_tab || !s->filter_slice_edges || !s->tab_slice_address)
goto fail;
s->horizontal_bs = av_mallocz_array(s->bs_width, s->bs_height);
s->vertical_bs = av_mallocz_array(s->bs_width, s->bs_height);
if (!s->horizontal_bs || !s->vertical_bs)
goto fail;
s->tab_mvf_pool = av_buffer_pool_init(min_pu_size * sizeof(MvField),
av_buffer_allocz);
s->rpl_tab_pool = av_buffer_pool_init(ctb_count * sizeof(RefPicListTab),
av_buffer_allocz);
if (!s->tab_mvf_pool || !s->rpl_tab_pool)
goto fail;
return 0;
fail:
pic_arrays_free(s);
return AVERROR(ENOMEM);
}
| 1threat
|
Is it suitable to use 200 http code for forbidden web page : what is the difference when we use 200 response code for a forbidden page with an error message saying 'access denied' instead of using 403 response code?
are there any security implications of this
| 0debug
|
static inline void gen_op_eval_ble(TCGv dst, TCGv_i32 src)
{
gen_mov_reg_N(cpu_tmp0, src);
gen_mov_reg_V(dst, src);
tcg_gen_xor_tl(dst, dst, cpu_tmp0);
gen_mov_reg_Z(cpu_tmp0, src);
tcg_gen_or_tl(dst, dst, cpu_tmp0);
}
| 1threat
|
Change color of react-big-calendar events : <p>I need to make a calendar with events and I decided to use <a href="http://intljusticemission.github.io/react-big-calendar/examples/index.html" rel="noreferrer">react-big-calendar</a>. But I need to make events of different colors. So each event will have some category and each category has corresponding color. How can I change the color of the event with react? <a href="https://i.stack.imgur.com/vtw4o.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vtw4o.png" alt="react-big-calendar same color example"></a></p>
<p>Result should look something like this <a href="https://i.stack.imgur.com/9iKRo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9iKRo.png" alt="react-big-calendar different colors example"></a></p>
| 0debug
|
i am new to angular js trying to addclass but getting error addclass not a function : i am new to angular js trying to addclass but getting error addclass not a function plz help
$scope.viewReport = function(ev,element) {
window.location="#tab7";
$scope.tabact = document.getElementById('tab7');
console.log($scope.tabact);
$scope.tabact.addClass('active');
$rootScope.callOrder = false
$rootScope.step1=true
$rootScope.step2=false
$rootScope.step3=false
}
| 0debug
|
difference between np.inf and float('Inf') : <p>Is there some difference between NumPy <code>np.inf</code> and <code>float('Inf')</code>?
<code>float('Inf') == np.inf</code> returns <code>True</code>, so it seems they are interchangeable, thus I was wondering why NumPy has defined its own "inf" constant, and when should I use one constant instead of the other (considering style concerns too)?</p>
| 0debug
|
static int config_input_overlay(AVFilterLink *inlink)
{
AVFilterContext *ctx = inlink->dst;
OverlayContext *over = inlink->dst->priv;
char *expr;
double var_values[VAR_VARS_NB], res;
int ret;
const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
av_image_fill_max_pixsteps(over->overlay_pix_step, NULL, pix_desc);
var_values[VAR_MAIN_W ] = var_values[VAR_MW] = ctx->inputs[MAIN ]->w;
var_values[VAR_MAIN_H ] = var_values[VAR_MH] = ctx->inputs[MAIN ]->h;
var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
goto fail;
over->x = res;
if ((ret = av_expr_parse_and_eval(&res, (expr = over->y_expr), var_names, var_values,
NULL, NULL, NULL, NULL, NULL, 0, ctx)))
goto fail;
over->y = res;
if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
goto fail;
over->x = res;
over->overlay_is_packed_rgb =
ff_fill_rgba_map(over->overlay_rgba_map, inlink->format) >= 0;
over->overlay_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
av_log(ctx, AV_LOG_VERBOSE,
"main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
av_get_pix_fmt_name(ctx->inputs[MAIN]->format),
over->x, over->y,
ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
av_get_pix_fmt_name(ctx->inputs[OVERLAY]->format));
if (over->x < 0 || over->y < 0 ||
over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
over->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
av_log(ctx, AV_LOG_ERROR,
"Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
over->x, over->y,
(int)(over->x + var_values[VAR_OVERLAY_W]),
(int)(over->y + var_values[VAR_OVERLAY_H]),
(int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
return AVERROR(EINVAL);
}
return 0;
fail:
av_log(NULL, AV_LOG_ERROR,
"Error when evaluating the expression '%s'\n", expr);
return ret;
}
| 1threat
|
void replay_account_executed_instructions(void)
{
if (replay_mode == REPLAY_MODE_PLAY) {
replay_mutex_lock();
if (replay_state.instructions_count > 0) {
int count = (int)(replay_get_current_step()
- replay_state.current_step);
replay_state.instructions_count -= count;
replay_state.current_step += count;
if (replay_state.instructions_count == 0) {
assert(replay_state.data_kind == EVENT_INSTRUCTION);
replay_finish_event();
qemu_notify_event();
}
}
replay_mutex_unlock();
}
}
| 1threat
|
Find the approximate value in the vector : <p>I have a number of the vector with the numbers.</p>
<pre><code>test <- 0.495
vector <- c(0.5715122, 2.2860487, 5.1436096, 9.1441949)
</code></pre>
<p>This vector is the need to take an approximate number to the number 0.495.
Help me. </p>
| 0debug
|
Are you writing opencv programs in ubuntu? : I need your help!
I have been troubled by the problem these days. I want to write opencv-3.0.0 programs with c language in the terminal of my ubuntu 14.04 in the VM.
Could you please give me an example of yours?
| 0debug
|
Url-loader vs File-loader Webpack : <p>I'm trying to figure out the difference between url-loader vs file-loader. What does <code>DataURl</code> mean?</p>
<blockquote>
<p>The url-loader works like the file-loader, but can return a DataURL if
the file is smaller than a byte limit.</p>
</blockquote>
| 0debug
|
Convert LINQ nested Any's to take N parameters : Requirement: check if a list of successive words exists in a dataset. If it does, return a boolean to show the success.
Here is my code so far with unit tests:
[Test]
public void PhraseSearch()
{
var DataSet = new List<Word>
{
new Word { Text = "First", Sequence = 0 },
new Word { Text = "Second", Sequence = 1 },
new Word { Text = "Third", Sequence = 2 },
new Word { Text = "Forth", Sequence = 3 },
new Word { Text = "Five", Sequence = 4 }
};
var goodSearch = new string[]{ "First", "Second", "Third" };
var badSearch = new string[] { "First", "NOTFOUND", "Third" };
// successful test for 2 words
var result = DataSet.Any(wrd1 => wrd1.Text == goodSearch[0] && DataSet.Any(wrd2 => wrd2.Text == goodSearch[1] && wrd2.Sequence == wrd1.Sequence + 1));
Assert.That(result, Is.True);
result = DataSet.Any(wrd1 => wrd1.Text == badSearch[0] &&
DataSet.Any(wrd2 => wrd2.Text == badSearch[1] && wrd2.Sequence == wrd1.Sequence + 1));
// successful test for 2 words that don't match the data
Assert.That(result, Is.False);
// successful test for 3 words
result = DataSet.Any(wrd1 => wrd1.Text == goodSearch[0] &&
DataSet.Any(wrd2 => wrd2.Text == goodSearch[1] && wrd2.Sequence == wrd1.Sequence + 1 &&
DataSet.Any(wrd3 => wrd3.Text == goodSearch[2] && wrd3.Sequence == wrd2.Sequence + 1)));
Assert.That(result, Is.True);
// test for N words
result = .....
}
I want to expand the Linq code to do N words, but i'm not sure how to do this with Linq, I'm leaning towards a hard coded method for each number of words but that seems really smelly.
| 0debug
|
static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis)
{
PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
uint64_t remote_hps, remote_tps;
trace_loadvm_postcopy_handle_advise();
if (ps != POSTCOPY_INCOMING_NONE) {
error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
return -1;
}
if (!postcopy_ram_supported_by_host()) {
postcopy_state_set(POSTCOPY_INCOMING_NONE);
return -1;
}
remote_hps = qemu_get_be64(mis->from_src_file);
if (remote_hps != getpagesize()) {
error_report("Postcopy needs matching host page sizes (s=%d d=%d)",
(int)remote_hps, getpagesize());
return -1;
}
remote_tps = qemu_get_be64(mis->from_src_file);
if (remote_tps != (1ul << qemu_target_page_bits())) {
error_report("Postcopy needs matching target page sizes (s=%d d=%d)",
(int)remote_tps, 1 << qemu_target_page_bits());
return -1;
}
if (ram_postcopy_incoming_init(mis)) {
return -1;
}
postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
return 0;
}
| 1threat
|
create dict from lists using key list again : <p>I have two list</p>
<pre><code>listA = (1,2,3,4)
listB = (A,B,C,D,A,B,C,D,A,B,C,D,A,B,C,D,A,B,C,D)
</code></pre>
<p>I want to build a dictionary reusing <code>listA</code> as the key to all values in <code>listB</code></p>
<pre><code>dict = {1:A,2:B,3:C,4:D,1:A,2:B,3:C,4:D,1:A,2:B,3:C,4:D,1:A,2:B,3:C,4:D,1:A,2:B,3:C,4:D}
</code></pre>
<p>I am not able to use <code>itertools</code> I also have to take in to consideration that some of my values are empty so I am trying to build the <code>dict</code> like this</p>
<pre><code>def create_dict(keys,values):
return dict(zip(keys, values + [None] * (len(keys) - len(values))))
</code></pre>
<p>Which works but only for length of the keys.</p>
| 0debug
|
SwiftUI and MVVM - Communication between model and view model : <p>I've been experimenting with the MVVM model that's used in <code>SwiftUI</code> and there are some things I don't quite get yet.</p>
<p><code>SwiftUI</code> uses <code>@ObservableObject</code>/<code>@ObservedObject</code> to detect changes in a view model that trigger a recalculation of the <code>body</code> property to update the view.</p>
<p>In the MVVM model, that's the communication between the view and the view model. What I don't quite understand is how the model and the view model communicate.</p>
<p>When the model changes, how is the view model supposed to know that? I thought about manually using the new <code>Combine</code> framework to create publishers inside the model that the view model can subscribe to.</p>
<p>However, I created a simple example that makes this approach pretty tedious, I think. There's a model called <code>Game</code> that holds an array of <code>Game.Character</code> objects. A character has a <code>strength</code> property that can change.</p>
<p>So what if a view model changes that <code>strength</code> property of a character? To detect that change, the model would have to subscribe to every single character that the game has (among possibly many other things). Isn't that a little too much? Or is it normal to have many publishers and subscribers?</p>
<p>Or is my example not properly following MVVM? Should my view model not have the actual model <code>game</code> as property? If so, what would be a better way?</p>
<pre class="lang-swift prettyprint-override"><code>// My Model
class Game {
class Character {
let name: String
var strength: Int
init(name: String, strength: Int) {
self.name = name
self.strength = strength
}
}
var characters: [Character]
init(characters: [Character]) {
self.characters = characters
}
}
// ...
// My view model
class ViewModel: ObservableObject {
let objectWillChange = PassthroughSubject<ViewModel, Never>()
let game: Game
init(game: Game) {
self.game = game
}
public func changeCharacter() {
self.game.characters[0].strength += 20
}
}
// Now I create a demo instance of the model Game.
let bob = Game.Character(name: "Bob", strength: 10)
let alice = Game.Character(name: "Alice", strength: 42)
let game = Game(characters: [bob, alice])
// ..
// Then for one of my views, I initialize its view model like this:
MyView(viewModel: ViewModel(game: game))
// When I now make changes to a character, e.g. by calling the ViewModel's method "changeCharacter()", how do I trigger the view (and every other active view that displays the character) to redraw?
</code></pre>
<p>I hope it's clear what I mean. It's difficult to explain because it is confusing</p>
<p>Thanks!</p>
| 0debug
|
char *desc_get_buf(DescInfo *info, bool read_only)
{
PCIDevice *dev = PCI_DEVICE(info->ring->r);
size_t size = read_only ? le16_to_cpu(info->desc.tlv_size) :
le16_to_cpu(info->desc.buf_size);
if (size > info->buf_size) {
info->buf = g_realloc(info->buf, size);
info->buf_size = size;
}
if (!info->buf) {
return NULL;
}
if (pci_dma_read(dev, le64_to_cpu(info->desc.buf_addr), info->buf, size)) {
return NULL;
}
return info->buf;
}
| 1threat
|
why is macro acting different while not using namespace std and while using namespace std? : <p>in this below code <b><i>macro 1</i></b> is always fine</p>
<p>but, <b><i>macro 2 </i></b>is not working if statement 1 is not written..why is this happening?</p>
<pre><code>#include<iostream>
#include<conio.h>
//using namespace std; //--statement 1
#define l std::cout<< //--macro 1
#define nl std::cout<<endl; //--macro 2
int main(){
l "testing";
nl // this is not working if i dont use statement 1
l "a new line";
getch();
return 0;
}
</code></pre>
<p>when <b><i>statement 1</i></b> is not written <b><i>macro 2</i></b> is producing a error stating that <i>'[Error]endl was not declared in this scope'</i></p>
<p>if <code>cout<<</code> is the short version of <code>std::cout<<</code>, this error should not happen...i can not understand why is this happening...</p>
| 0debug
|
Changing the value of a copy also changes the value of the original : <p>Changing the value of a variable b, which is a copy of a, also changes the value of a.</p>
<pre><code>a = [[0]]
b = a.copy()
print("a before", a)
b[0][0] = 1
print("a after ", a)
</code></pre>
<p>prints:</p>
<pre><code>a before [[0]]
a after [[1]]
</code></pre>
<p>Although this works:</p>
<pre><code>a = [0]
b = a.copy()
print("a before", a)
b[0] = 1
print("a after ", a)
</code></pre>
<p>prints:</p>
<pre><code>a before [[0]]
a after [[0]]
</code></pre>
| 0debug
|
static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s,
Jpeg2000CodingStyle *codsty,
Jpeg2000ResLevel *rlevel, int precno,
int layno, uint8_t *expn, int numgbits)
{
int bandno, cblkno, ret, nb_code_blocks;
if (!(ret = get_bits(s, 1))) {
jpeg2000_flush(s);
return 0;
} else if (ret < 0)
return ret;
for (bandno = 0; bandno < rlevel->nbands; bandno++) {
Jpeg2000Band *band = rlevel->band + bandno;
Jpeg2000Prec *prec = band->prec + precno;
if (band->coord[0][0] == band->coord[0][1] ||
band->coord[1][0] == band->coord[1][1])
continue;
prec->yi0 = 0;
prec->xi0 = 0;
nb_code_blocks = prec->nb_codeblocks_height *
prec->nb_codeblocks_width;
for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
Jpeg2000Cblk *cblk = prec->cblk + cblkno;
int incl, newpasses, llen;
if (cblk->npasses)
incl = get_bits(s, 1);
else
incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
if (!incl)
continue;
else if (incl < 0)
return incl;
if (!cblk->npasses)
cblk->nonzerobits = expn[bandno] + numgbits - 1 -
tag_tree_decode(s, prec->zerobits + cblkno,
100);
if ((newpasses = getnpasses(s)) < 0)
return newpasses;
if ((llen = getlblockinc(s)) < 0)
return llen;
cblk->lblock += llen;
if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
return ret;
cblk->lengthinc = ret;
cblk->npasses += newpasses;
}
}
jpeg2000_flush(s);
if (codsty->csty & JPEG2000_CSTY_EPH) {
if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
bytestream2_skip(&s->g, 2);
else
av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
}
for (bandno = 0; bandno < rlevel->nbands; bandno++) {
Jpeg2000Band *band = rlevel->band + bandno;
Jpeg2000Prec *prec = band->prec + precno;
nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
Jpeg2000Cblk *cblk = prec->cblk + cblkno;
if (bytestream2_get_bytes_left(&s->g) < cblk->lengthinc)
return AVERROR(EINVAL);
if (cblk->lengthinc > 0) {
bytestream2_get_bufferu(&s->g, cblk->data, cblk->lengthinc);
} else {
cblk->data[0] = 0xFF;
cblk->data[1] = 0xFF;
}
cblk->length += cblk->lengthinc;
cblk->lengthinc = 0;
}
}
return 0;
}
| 1threat
|
static int virtio_9p_init_pci(PCIDevice *pci_dev)
{
VirtIOPCIProxy *proxy = DO_UPCAST(VirtIOPCIProxy, pci_dev, pci_dev);
VirtIODevice *vdev;
vdev = virtio_9p_init(&pci_dev->qdev, &proxy->fsconf);
vdev->nvectors = proxy->nvectors;
virtio_init_pci(proxy, vdev,
PCI_VENDOR_ID_REDHAT_QUMRANET,
0x1009,
0x2,
0x00);
proxy->nvectors = vdev->nvectors;
return 0;
}
| 1threat
|
Error when defining variables within a defined function (Python) : <p>Consider the following code (I received a name error when running this)</p>
<pre><code>item = input("What food???")
def itemcheck():
if item == "chex":
cereal = "Yummy"
else:
cereal = "Yuck!"
itemcheck()
print(cereal)
</code></pre>
<p>the error was name 'cereal' is not defined. What error am I making/how do I fix it? What is the correct way to define a variable in your own function?</p>
| 0debug
|
What is SYCL 1.2? : <p>I am trying to install tensorflow</p>
<pre><code>Please specify the location where ComputeCpp for SYCL 1.2 is installed. [Default is /usr/local/computecpp]:
Invalid SYCL 1.2 library path. /usr/local/computecpp/lib/libComputeCpp.so cannot be found
</code></pre>
<p>What should I do?What is SYCL 1.2?</p>
| 0debug
|
What is the simplest way to create a form in java swing? : <p>I need advise about layout manager in swing for such form:</p>
<pre><code> Label1 TextField1
Label1 TextField1
ButtonWideAsForm
</code></pre>
<p>Can you tell me what layout to use ?</p>
| 0debug
|
Finding the mean of all of the integers in an ArrayList : I am currently making a simulator for fake basketball players but am currently stuck on finding the mean of all of the numbers in the arraylist. I know how to add all of them up but when ever I try to make a counter variable to divide the list or list.getSize() non of them work. Hopefully this makes sense to you, I am happy to explain in more detail the problem.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Application {
private JFrame frame;
private JTextField pst;
private JTextField pg;
private JTextField sg;
private JTextField pf;
private JTextField C;
private JTextField sf;
private JTextField txtPlayerName;
private JTextField ED;
private JTextField CJ;
private JTextField SB;
private JTextField SW;
private JTextField JO;
private JTextField num;
private JTextField edNum;
private JTextField cjNum;
private JTextField sbNum;
private JTextField swNum;
private JTextField joNum;
private JTextField ppg;
private JTextField ppgED;
private JTextField ppgCJ;
private JTextField ppgSB;
private JTextField ppgJO;
private JTextField ppgSW;
private JButton btnPlay;
private List<Integer> ppgList;
private int sum;
private int counter;
// Launch the application.
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Application window = new Application();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Application() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
initComponenets();
createEvents();
}
////////////////////////////////////////////////////////////////////////
//Contains all of the code for creating events
private void createEvents() {
}
//Contains all of the code for creating and initializing components
private void initComponenets() {
////////////////////////////////////////////////////////////Frame
frame = new JFrame();
frame.setTitle("Title");
frame.setBounds(100, 100, 801, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
////////////////////////////////////////////////////////////Title
JTextPane title = new JTextPane();
title.setBackground(Color.LIGHT_GRAY);
title.setEditable(false);
title.setFont(new Font("Tahoma", Font.PLAIN, 20));
title.setForeground(Color.DARK_GRAY);
title.setBounds(237, 11, 296, 50);
title.setText(" Basketball Simulation Game");
frame.getContentPane().add(title);
/////////////////////////////////////////////////////////// Position TextBox
pst = new JTextField();
pst.setHorizontalAlignment(SwingConstants.CENTER);
pst.setEditable(false);
pst.setFont(new Font("Tahoma", Font.BOLD, 14));
pst.setText("PST");
pst.setBounds(10, 64, 50, 35);
frame.getContentPane().add(pst);
pst.setColumns(10);
pg = new JTextField();
pg.setHorizontalAlignment(SwingConstants.CENTER);
pg.setText("PG");
pg.setFont(new Font("Tahoma", Font.BOLD, 14));
pg.setEditable(false);
pg.setColumns(10);
pg.setBounds(10, 99, 50, 50);
frame.getContentPane().add(pg);
sg = new JTextField();
sg.setHorizontalAlignment(SwingConstants.CENTER);
sg.setText("SG");
sg.setFont(new Font("Tahoma", Font.BOLD, 14));
sg.setEditable(false);
sg.setColumns(10);
sg.setBounds(10, 148, 50, 50);
frame.getContentPane().add(sg);
sf = new JTextField();
sf.setText("SF");
sf.setHorizontalAlignment(SwingConstants.CENTER);
sf.setFont(new Font("Tahoma", Font.BOLD, 14));
sf.setEditable(false);
sf.setColumns(10);
sf.setBounds(10, 196, 50, 50);
frame.getContentPane().add(sf);
pf = new JTextField();
pf.setText("PF");
pf.setHorizontalAlignment(SwingConstants.CENTER);
pf.setFont(new Font("Tahoma", Font.BOLD, 14));
pf.setEditable(false);
pf.setColumns(10);
pf.setBounds(10, 242, 50, 50);
frame.getContentPane().add(pf);
C = new JTextField();
C.setText("C");
C.setHorizontalAlignment(SwingConstants.CENTER);
C.setFont(new Font("Tahoma", Font.BOLD, 14));
C.setEditable(false);
C.setColumns(10);
C.setBounds(10, 291, 50, 50);
frame.getContentPane().add(C);
/////////////////////////////////////////////// PlayerName
txtPlayerName = new JTextField();
txtPlayerName.setText("Player Name");
txtPlayerName.setHorizontalAlignment(SwingConstants.CENTER);
txtPlayerName.setFont(new Font("Tahoma", Font.BOLD, 14));
txtPlayerName.setEditable(false);
txtPlayerName.setColumns(10);
txtPlayerName.setBounds(59, 64, 95, 35);
frame.getContentPane().add(txtPlayerName);
ED = new JTextField();
ED.setText("ED");
ED.setHorizontalAlignment(SwingConstants.CENTER);
ED.setFont(new Font("Tahoma", Font.BOLD, 14));
ED.setEditable(false);
ED.setColumns(10);
ED.setBounds(59, 99, 95, 50);
frame.getContentPane().add(ED);
CJ = new JTextField();
CJ.setText("CJ");
CJ.setHorizontalAlignment(SwingConstants.CENTER);
CJ.setFont(new Font("Tahoma", Font.BOLD, 14));
CJ.setEditable(false);
CJ.setColumns(10);
CJ.setBounds(59, 148, 95, 50);
frame.getContentPane().add(CJ);
SB = new JTextField();
SB.setText("SB");
SB.setHorizontalAlignment(SwingConstants.CENTER);
SB.setFont(new Font("Tahoma", Font.BOLD, 14));
SB.setEditable(false);
SB.setColumns(10);
SB.setBounds(59, 196, 95, 50);
frame.getContentPane().add(SB);
SW = new JTextField();
SW.setText("Swanigan");
SW.setHorizontalAlignment(SwingConstants.CENTER);
SW.setFont(new Font("Tahoma", Font.BOLD, 14));
SW.setEditable(false);
SW.setColumns(10);
SW.setBounds(59, 245, 95, 47);
frame.getContentPane().add(SW);
JO = new JTextField();
JO.setText("Jordan");
JO.setHorizontalAlignment(SwingConstants.CENTER);
JO.setFont(new Font("Tahoma", Font.BOLD, 14));
JO.setEditable(false);
JO.setColumns(10);
JO.setBounds(59, 291, 95, 50);
frame.getContentPane().add(JO);
/////////////////////////////////////////////Numbers
num = new JTextField();
num.setText("#");
num.setHorizontalAlignment(SwingConstants.CENTER);
num.setFont(new Font("Tahoma", Font.BOLD, 14));
num.setEditable(false);
num.setColumns(10);
num.setBounds(153, 64, 50, 35);
frame.getContentPane().add(num);
edNum = new JTextField();
edNum.setText("0");
edNum.setHorizontalAlignment(SwingConstants.CENTER);
edNum.setFont(new Font("Tahoma", Font.BOLD, 14));
edNum.setEditable(false);
edNum.setColumns(10);
edNum.setBounds(153, 99, 50, 50);
frame.getContentPane().add(edNum);
cjNum = new JTextField();
cjNum.setText("3");
cjNum.setHorizontalAlignment(SwingConstants.CENTER);
cjNum.setFont(new Font("Tahoma", Font.BOLD, 14));
cjNum.setEditable(false);
cjNum.setColumns(10);
cjNum.setBounds(153, 148, 50, 50);
frame.getContentPane().add(cjNum);
sbNum = new JTextField();
sbNum.setText("24");
sbNum.setHorizontalAlignment(SwingConstants.CENTER);
sbNum.setFont(new Font("Tahoma", Font.BOLD, 14));
sbNum.setEditable(false);
sbNum.setColumns(10);
sbNum.setBounds(153, 196, 50, 50);
frame.getContentPane().add(sbNum);
swNum = new JTextField();
swNum.setText("8");
swNum.setHorizontalAlignment(SwingConstants.CENTER);
swNum.setFont(new Font("Tahoma", Font.BOLD, 14));
swNum.setEditable(false);
swNum.setColumns(10);
swNum.setBounds(153, 245, 50, 47);
frame.getContentPane().add(swNum);
joNum = new JTextField();
joNum.setText("23");
joNum.setHorizontalAlignment(SwingConstants.CENTER);
joNum.setFont(new Font("Tahoma", Font.BOLD, 14));
joNum.setEditable(false);
joNum.setColumns(10);
joNum.setBounds(153, 291, 50, 50);
frame.getContentPane().add(joNum);
//////////////////////////////////Points per game
ppg = new JTextField();
ppg.setText("PPG");
ppg.setHorizontalAlignment(SwingConstants.CENTER);
ppg.setFont(new Font("Tahoma", Font.BOLD, 14));
ppg.setEditable(false);
ppg.setColumns(10);
ppg.setBounds(201, 64, 50, 35);
frame.getContentPane().add(ppg);
ppgED = new JTextField();
ppgED.setText("0.0");
ppgED.setHorizontalAlignment(SwingConstants.CENTER);
ppgED.setFont(new Font("Tahoma", Font.BOLD, 14));
ppgED.setEditable(false);
ppgED.setColumns(10);
ppgED.setBounds(201, 99, 50, 50);
frame.getContentPane().add(ppgED);
ppgCJ = new JTextField();
ppgCJ.setText("0.0");
ppgCJ.setHorizontalAlignment(SwingConstants.CENTER);
ppgCJ.setFont(new Font("Tahoma", Font.BOLD, 14));
ppgCJ.setEditable(false);
ppgCJ.setColumns(10);
ppgCJ.setBounds(201, 148, 50, 50);
frame.getContentPane().add(ppgCJ);
ppgSB = new JTextField();
ppgSB.setText("0.0");
ppgSB.setHorizontalAlignment(SwingConstants.CENTER);
ppgSB.setFont(new Font("Tahoma", Font.BOLD, 14));
ppgSB.setEditable(false);
ppgSB.setColumns(10);
ppgSB.setBounds(201, 196, 50, 50);
frame.getContentPane().add(ppgSB);
ppgJO = new JTextField();
ppgJO.setText("0.0");
ppgJO.setHorizontalAlignment(SwingConstants.CENTER);
ppgJO.setFont(new Font("Tahoma", Font.BOLD, 14));
ppgJO.setEditable(false);
ppgJO.setColumns(10);
ppgJO.setBounds(201, 291, 50, 50);
frame.getContentPane().add(ppgJO);
ppgSW = new JTextField();
ppgSW.setText("0.0");
ppgSW.setHorizontalAlignment(SwingConstants.CENTER);
ppgSW.setFont(new Font("Tahoma", Font.BOLD, 14));
ppgSW.setEditable(false);
ppgSW.setColumns(10);
ppgSW.setBounds(201, 245, 50, 47);
frame.getContentPane().add(ppgSW);
////////////////////////////////////////Play JButton
btnPlay = new JButton("PLAY");
btnPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getPPG(33, ppgED);
}
});
btnPlay.setFont(new Font("Tahoma", Font.PLAIN, 24));
btnPlay.setBounds(304, 344, 160, 56);
frame.getContentPane().add(btnPlay);
}
public void getPPG(int num, JTextField box){
Random rand = new Random();
String text;
ppgList = new ArrayList<Integer>();
for(int xy = 0; xy < 1; xy++){
num = num + rand.nextInt(10);
ppgList.add(num);
}
for(int i = 0; i < ppgList.size(); i++)
{
counter++;
sum = sum + ppgList.get(i) / counter;
}
Integer.toString(sum);
text = String.valueOf(sum);
box.setText(text);
}
}
| 0debug
|
Propertly would not be serialize into a Parcel in Kotlin : <p>I wish to have my variables <strong>that are not</strong> from my constructor, part of my Parcelable.
However, I face this warning "Propertly would not be serialize into a Parcel", that inform me I can't do that currently.</p>
<p>I am using Kotlin in <em>experimental</em> v.1.2.41.</p>
<p>How can I do ? </p>
<pre><code>@Parcelize
data class MyClass(private val myList: List<Stuff>) : Parcelable {
val average: List<DayStat> by lazy {
calculateAverage(myList)
}
</code></pre>
| 0debug
|
ping: http://google.com: Name or service not known : <p>I'm using centos7 in virtualbox on windows. And vagrant made it, got ping error with http or https. also curl. someone can help me how to fix it and let it work.</p>
<pre><code>[root@localhost ~]# ping google.com
PING google.com (61.91.161.217) 56(84) bytes of data.
64 bytes from chatenabled.mail.google.com (61.91.161.217): icmp_seq=1 ttl=43 time=404 ms
64 bytes from chatenabled.mail.google.com (61.91.161.217): icmp_seq=2 ttl=43 time=408 ms
64 bytes from chatenabled.mail.google.com (61.91.161.217): icmp_seq=3 ttl=43 time=407 ms
64 bytes from chatenabled.mail.google.com (61.91.161.217): icmp_seq=4 ttl=43 time=408 ms
^C
--- google.com ping statistics ---
5 packets transmitted, 4 received, 20% packet loss, time 4000ms
rtt min/avg/max/mdev = 404.297/407.234/408.956/1.887 ms
[root@localhost ~]# ping https://google.com
ping: https://google.com: Name or service not known
[root@localhost ~]# ping https://61.91.161.217
ping: https://61.91.161.217: Name or service not known
</code></pre>
<p>`</p>
<p>resolv.conf </p>
<pre><code>[root@localhost ~]# cat /etc/resolv.conf
nameserver 10.0.2.3
nameserver 8.8.8.8
nameserver 8.8.4.4
search localhost
</code></pre>
<p>`</p>
<p>ifconfig </p>
<pre><code>[root@localhost ~]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.0.2.15 netmask 255.255.255.0 broadcast 10.0.2.255
inet6 fe80::5054:ff:fe73:fb1 prefixlen 64 scopeid 0x20<link>
ether 52:54:00:73:0f:b1 txqueuelen 1000 (Ethernet)
RX packets 610587 bytes 48453952 (46.2 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 468759 bytes 41290880 (39.3 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
eth1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.33.10 netmask 255.255.255.0 broadcast 192.168.33.255
inet6 fe80::a00:27ff:fe0e:ae16 prefixlen 64 scopeid 0x20<link>
ether 08:00:27:0e:ae:16 txqueuelen 1000 (Ethernet)
RX packets 3069145 bytes 2674132747 (2.4 GiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 2531212 bytes 213727091 (203.8 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
</code></pre>
<p>network file automatically created from vagrant</p>
<pre><code>[root@localhost ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0
NAME="eth0"
ONBOOT=yes
NETBOOT=yes
UUID="704aa015-53dd-4ba7-9689-b9b8bf6e09a5"
IPV6INIT=yes
BOOTPROTO=dhcp
TYPE=Ethernet
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
PEERDNS=yes
PEERROUTES=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
HWADDR=52:54:00:73:0f:b1
DNS1=8.8.8.8
[root@localhost ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth1
NM_CONTROLLED=no
BOOTPROTO=none
ONBOOT=yes
IPADDR=192.168.33.10
NETMASK=255.255.255.0
DEVICE=eth1
PEERDNS=no
DNS1=8.8.8.8
</code></pre>
| 0debug
|
Error calling RCTDeviceEventEmitter.emit in ReactNative : <p>I am begginer in ReactNative ... After install the first project in my Device This error was displayed:</p>
<blockquote>
<p>Error calling RCTDeviceEventEmitter.emit</p>
</blockquote>
<p>What is the problem ? <a href="https://i.stack.imgur.com/clgDX.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/clgDX.jpg" alt="enter image description here"></a></p>
| 0debug
|
Using `std::min` as an algorithm parameter : <p>So I ran into this problem: I need to replace every element of the <code>std::vector<int></code> with the minimum of whatever came before it (inclusive). </p>
<p>Naturally <code>std::partial_sum</code> comes to mind - if I could pass <code>std::min</code> as the <code>BinaryOp</code>, it would do the job. </p>
<p>Well turns out I can't do that because <code>std::min<int></code> is an overloaded function - it works for both <code>int</code> and <code>initializer_list<int></code> and <code>partial_sum</code> template can't be instantiated with the unknown type. </p>
<p>Usually this is resolved by having a class with a templated <code>operator()</code>, like <code>std::plus<void></code> etc, but standard library doesn't seem to have one for <code>min</code> and <code>max</code>. </p>
<p>I feel like I either have to implement my own <code>T min<T>(T,T)</code>, which will be an exact clone of <code>std::min</code> with the exception of not having an <code>initializer_list</code> overload, or to implement my own <code>class min</code> akin to <code>std::plus</code>. Both feel kinda wrong because one would expect standard library to have such a basic thing, and also basic things are often tricky to implement:) </p>
<p>So here are my questions: </p>
<ol>
<li>Is there any <strong>proper</strong> way to solve the problem in question? i.e. without introducing new vague constructs/writing more than a couple of lines of code.</li>
<li>Is it correct to assume that this became a problem in C++11, after <code>initializer_list</code> overload of <code>min</code> was introduced? So C++11 broke the code that relied on explicitly instantiated <code>std::min</code>?</li>
</ol>
<p>Thank you!</p>
| 0debug
|
uint64_t HELPER(neon_abdl_u32)(uint32_t a, uint32_t b)
{
uint64_t tmp;
uint64_t result;
DO_ABD(result, a, b, uint16_t);
DO_ABD(tmp, a >> 16, b >> 16, uint16_t);
return result | (tmp << 32);
}
| 1threat
|
static bool migrate_params_check(MigrationParameters *params, Error **errp)
{
if (params->has_compress_level &&
(params->compress_level < 0 || params->compress_level > 9)) {
error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
"is invalid, it should be in the range of 0 to 9");
return false;
}
if (params->has_compress_threads &&
(params->compress_threads < 1 || params->compress_threads > 255)) {
error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
"compress_threads",
"is invalid, it should be in the range of 1 to 255");
return false;
}
if (params->has_decompress_threads &&
(params->decompress_threads < 1 || params->decompress_threads > 255)) {
error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
"decompress_threads",
"is invalid, it should be in the range of 1 to 255");
return false;
}
if (params->has_cpu_throttle_initial &&
(params->cpu_throttle_initial < 1 ||
params->cpu_throttle_initial > 99)) {
error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
"cpu_throttle_initial",
"an integer in the range of 1 to 99");
return false;
}
if (params->has_cpu_throttle_increment &&
(params->cpu_throttle_increment < 1 ||
params->cpu_throttle_increment > 99)) {
error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
"cpu_throttle_increment",
"an integer in the range of 1 to 99");
return false;
}
if (params->has_max_bandwidth &&
(params->max_bandwidth < 0 || params->max_bandwidth > SIZE_MAX)) {
error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
" range of 0 to %zu bytes/second", SIZE_MAX);
return false;
}
if (params->has_downtime_limit &&
(params->downtime_limit < 0 ||
params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
"the range of 0 to %d milliseconds",
MAX_MIGRATE_DOWNTIME);
return false;
}
if (params->has_x_checkpoint_delay && (params->x_checkpoint_delay < 0)) {
error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
"x_checkpoint_delay",
"is invalid, it should be positive");
return false;
}
if (params->has_x_multifd_channels &&
(params->x_multifd_channels < 1 || params->x_multifd_channels > 255)) {
error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
"multifd_channels",
"is invalid, it should be in the range of 1 to 255");
return false;
}
if (params->has_x_multifd_page_count &&
(params->x_multifd_page_count < 1 ||
params->x_multifd_page_count > 10000)) {
error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
"multifd_page_count",
"is invalid, it should be in the range of 1 to 10000");
return false;
}
if (params->has_xbzrle_cache_size &&
(params->xbzrle_cache_size < qemu_target_page_size() ||
!is_power_of_2(params->xbzrle_cache_size))) {
error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
"xbzrle_cache_size",
"is invalid, it should be bigger than target page size"
" and a power of two");
return false;
}
return true;
}
| 1threat
|
The output is number that signifies the smallest number of hops/jumps : <p>Create an app that receives input from the terminal console/UI and gives the output on the console/UI. </p>
<p>1st input - A list of 3 letter words.
2nd input - One word from the above list.
3rd input - Another word from the list. </p>
<p>The output is number that signifies the smallest number of hops/jumps that one can make from the 2nd input to reach the 3rd input. Every hop/jump has the following rules :
1. In every hop/jump you can change only one character at a time.
2. The resulting word should be in the list.
Example :</p>
<p>1st Input = ["cat","cii","sim","xim","yep","syd","pol","sit","sii","mat","sat","cit"]
2nd Input = "cat"
3rd Input = "sii"</p>
<p>Hops/Jumps path :</p>
<p>"cat" -> "cit" -> "cii" -> "sii"</p>
<p>Output - 4</p>
| 0debug
|
def move_first(test_list):
test_list = test_list[-1:] + test_list[:-1]
return test_list
| 0debug
|
void *qemu_vmalloc(size_t size)
{
if (!size) {
abort();
}
return oom_check(VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE));
}
| 1threat
|
C2106: '=' : left operand must be l-value : <p>So, I'm learning C as my first language and as doing some coding for practise I got the error above. I done everything as the book says (Stephen G. Kochan: Programming in C, Third Edition).
What am I doing wrong?
I'm using Microsoft Visual Studio 2015.</p>
<p>Thanks for your help!
Mark</p>
<pre><code>struct date
{
int month;
int day;
int year;
};
int main(void)
{
struct date today, tomorrow;
int numberOfDays(struct date d);
printf("Adja meg a mai datumot (hh nn eeee): ");
scanf_s("%i%i%i", &today.month, &today.day, &today.year);
if (today.day != numberOfDays(today))
{
tomorrow.day = today.day + 1;
tomorrow.month = today.month;
tomorrow.year = today.year;
}
else if (today.month == 12)
{
tomorrow.day = 1;
tomorrow.month = 1;
tomorrow.year = today.year + 1;
}
else
{
tomorrow.day = 1;
tomorrow.month = today.month + 1;
tomorrow.year = today.year;
}
printf("A holnapi datum: %i/%i/%.2i.\n", tomorrow.month, tomorrow.day, tomorrow.year % 100);
return 0;
}
int numberOfDays(struct date d)
{
int days;
bool isLeapYear(struct date d);
const int daysPerMonth[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (isLeapYear(d) == true && d.month == 2)
days = 29;
else
days = daysPerMonth[d.month - 1];
return days;
}
bool isLeapYear(struct date d)
{
bool leapYearFlag;
if ( (d.year % 4 == 0 && d.year % 100 = 0) || d.year % 400 == 00) //The error shows up here
leapYearFlag = true;
else
leapYearFlag = false;
return leapYearFlag;
}
</code></pre>
| 0debug
|
static void gd_change_page(GtkNotebook *nb, gpointer arg1, guint arg2,
gpointer data)
{
GtkDisplayState *s = data;
VirtualConsole *vc;
gboolean on_vga;
if (!gtk_widget_get_realized(s->notebook)) {
return;
}
vc = gd_vc_find_by_page(s, arg2);
if (!vc) {
return;
}
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(vc->menu_item),
TRUE);
on_vga = (vc->type == GD_VC_GFX);
if (!on_vga) {
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(s->grab_item),
FALSE);
} else if (s->full_screen) {
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(s->grab_item),
TRUE);
}
gtk_widget_set_sensitive(s->grab_item, on_vga);
gd_update_cursor(vc);
}
| 1threat
|
window.location.href = 'http://attack.com?user=' + user_input;
| 1threat
|
qcrypto_block_luks_open(QCryptoBlock *block,
QCryptoBlockOpenOptions *options,
const char *optprefix,
QCryptoBlockReadFunc readfunc,
void *opaque,
unsigned int flags,
Error **errp)
{
QCryptoBlockLUKS *luks;
Error *local_err = NULL;
int ret = 0;
size_t i;
ssize_t rv;
uint8_t *masterkey = NULL;
size_t masterkeylen;
char *ivgen_name, *ivhash_name;
QCryptoCipherMode ciphermode;
QCryptoCipherAlgorithm cipheralg;
QCryptoIVGenAlgorithm ivalg;
QCryptoCipherAlgorithm ivcipheralg;
QCryptoHashAlgorithm hash;
QCryptoHashAlgorithm ivhash;
char *password = NULL;
if (!(flags & QCRYPTO_BLOCK_OPEN_NO_IO)) {
if (!options->u.luks.key_secret) {
error_setg(errp, "Parameter '%skey-secret' is required for cipher",
optprefix ? optprefix : "");
return -1;
}
password = qcrypto_secret_lookup_as_utf8(
options->u.luks.key_secret, errp);
if (!password) {
return -1;
}
}
luks = g_new0(QCryptoBlockLUKS, 1);
block->opaque = luks;
rv = readfunc(block, 0,
(uint8_t *)&luks->header,
sizeof(luks->header),
opaque,
errp);
if (rv < 0) {
ret = rv;
goto fail;
}
be16_to_cpus(&luks->header.version);
be32_to_cpus(&luks->header.payload_offset);
be32_to_cpus(&luks->header.key_bytes);
be32_to_cpus(&luks->header.master_key_iterations);
for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
be32_to_cpus(&luks->header.key_slots[i].active);
be32_to_cpus(&luks->header.key_slots[i].iterations);
be32_to_cpus(&luks->header.key_slots[i].key_offset);
be32_to_cpus(&luks->header.key_slots[i].stripes);
}
if (memcmp(luks->header.magic, qcrypto_block_luks_magic,
QCRYPTO_BLOCK_LUKS_MAGIC_LEN) != 0) {
error_setg(errp, "Volume is not in LUKS format");
ret = -EINVAL;
goto fail;
}
if (luks->header.version != QCRYPTO_BLOCK_LUKS_VERSION) {
error_setg(errp, "LUKS version %" PRIu32 " is not supported",
luks->header.version);
ret = -ENOTSUP;
goto fail;
}
ivgen_name = strchr(luks->header.cipher_mode, '-');
if (!ivgen_name) {
ret = -EINVAL;
error_setg(errp, "Unexpected cipher mode string format %s",
luks->header.cipher_mode);
goto fail;
}
*ivgen_name = '\0';
ivgen_name++;
ivhash_name = strchr(ivgen_name, ':');
if (!ivhash_name) {
ivhash = 0;
} else {
*ivhash_name = '\0';
ivhash_name++;
ivhash = qcrypto_block_luks_hash_name_lookup(ivhash_name,
&local_err);
if (local_err) {
ret = -ENOTSUP;
error_propagate(errp, local_err);
goto fail;
}
}
ciphermode = qcrypto_block_luks_cipher_mode_lookup(luks->header.cipher_mode,
&local_err);
if (local_err) {
ret = -ENOTSUP;
error_propagate(errp, local_err);
goto fail;
}
cipheralg = qcrypto_block_luks_cipher_name_lookup(luks->header.cipher_name,
ciphermode,
luks->header.key_bytes,
&local_err);
if (local_err) {
ret = -ENOTSUP;
error_propagate(errp, local_err);
goto fail;
}
hash = qcrypto_block_luks_hash_name_lookup(luks->header.hash_spec,
&local_err);
if (local_err) {
ret = -ENOTSUP;
error_propagate(errp, local_err);
goto fail;
}
ivalg = qcrypto_block_luks_ivgen_name_lookup(ivgen_name,
&local_err);
if (local_err) {
ret = -ENOTSUP;
error_propagate(errp, local_err);
goto fail;
}
if (ivalg == QCRYPTO_IVGEN_ALG_ESSIV) {
if (!ivhash_name) {
ret = -EINVAL;
error_setg(errp, "Missing IV generator hash specification");
goto fail;
}
ivcipheralg = qcrypto_block_luks_essiv_cipher(cipheralg,
ivhash,
&local_err);
if (local_err) {
ret = -ENOTSUP;
error_propagate(errp, local_err);
goto fail;
}
} else {
ivcipheralg = cipheralg;
}
if (!(flags & QCRYPTO_BLOCK_OPEN_NO_IO)) {
if (qcrypto_block_luks_find_key(block,
password,
cipheralg, ciphermode,
hash,
ivalg,
ivcipheralg,
ivhash,
&masterkey, &masterkeylen,
readfunc, opaque,
errp) < 0) {
ret = -EACCES;
goto fail;
}
block->kdfhash = hash;
block->niv = qcrypto_cipher_get_iv_len(cipheralg,
ciphermode);
block->ivgen = qcrypto_ivgen_new(ivalg,
ivcipheralg,
ivhash,
masterkey, masterkeylen,
errp);
if (!block->ivgen) {
ret = -ENOTSUP;
goto fail;
}
block->cipher = qcrypto_cipher_new(cipheralg,
ciphermode,
masterkey, masterkeylen,
errp);
if (!block->cipher) {
ret = -ENOTSUP;
goto fail;
}
}
block->payload_offset = luks->header.payload_offset *
QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
luks->cipher_alg = cipheralg;
luks->cipher_mode = ciphermode;
luks->ivgen_alg = ivalg;
luks->ivgen_hash_alg = ivhash;
luks->hash_alg = hash;
g_free(masterkey);
g_free(password);
return 0;
fail:
g_free(masterkey);
qcrypto_cipher_free(block->cipher);
qcrypto_ivgen_free(block->ivgen);
g_free(luks);
g_free(password);
return ret;
}
| 1threat
|
Why duplicate code is needed with const reference arguments? : <p>In this <a href="http://www.stlport.org/resources/StepanovUSA.html">interview</a> Stepanov shows how to implement generic <code>max</code> function in C++. </p>
<blockquote>
<p>Try to implement a simple thing in the object oriented way, say, max.
I do not know how it can be done. Using generic programming I can
write:</p>
<pre><code>template <class StrictWeakOrdered>
inline StrictWeakOrdered& max(StrictWeakOrdered& x,
StrictWeakOrdered& y) {
return x < y ? y : x;
}
and
template <class StrictWeakOrdered>
inline const StrictWeakOrdered& max(const StrictWeakOrdered& x,
const StrictWeakOrdered& y) {
return x < y ? y : x;
}
</code></pre>
<p>(you do need both & and const &).</p>
</blockquote>
<p>Why is there need to write the code twice? Is this needed to aid compiler for optimization or a convention to reduce bugs? Is <code>max</code> a special case where body of a <code>const</code> version is identical? </p>
<p>How many valid <code>const</code> and non-<code>const</code> permutations a function of N arguments should have to define a complete API?</p>
| 0debug
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.