problem
stringlengths
26
131k
labels
class label
2 classes
Returning value based on argument size : Is there a way in C++ to generate code (at compile time) which looks a bit like: T Func(T t){ if (sizeof(t) == 2){ return X(t); } Else if( size of(t) == 4){ return Y(t); } } (Where T is either int32 or int16) So at run-time i can call: Func(_myInt) And the code will just compile down to either X(_myInt) or Y(_myInt).
0debug
Failed to inflate ColorStateList, leaving it to the framework java.lang.UnsupportedOperationException: Can't convert to color: type=0x2 : <p>I have a login part and I use TextInputLayout for email and password. Both of them are the same. Also I use Data binding to show the Error message.</p> <p>The error is happening on API &lt; 20 when it should show an Error Hint.</p> <pre><code> @Override public void showEmailError() { inputLayoutEmail.setError(sInvalidEmail); } </code></pre> <p><strong>xml layout :</strong> </p> <pre><code> &lt;android.support.design.widget.TextInputLayout android:id="@+id/til_email" android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_marginLeft="@dimen/default_margin_16dp" android:layout_marginRight="@dimen/default_margin_16dp" android:layout_marginTop="16dp" android:layout_below="@id/login_img_logo" android:layout_centerHorizontal="true" android:textColorHint="@color/gray" android:background="@drawable/login_edittext" android:errorEnabled="@{viewmodel.obEmailErrorVisibility}" &gt; &lt;EditText android:id="@+id/et_login" android:layout_height="@dimen/login_view_height" android:layout_width="@dimen/login_view_width" android:inputType="text" android:maxLength="50" android:hint="@string/activity_login_hint_email" android:text="@={viewmodel.email}" android:textColor="@color/black" android:textColorHint="@color/gray" android:paddingLeft="@dimen/default_margin_16dp" android:enabled="@{viewmodel.obIsEmailFieldEnabled}" /&gt; &lt;/android.support.design.widget.TextInputLayout&gt; &lt;android.support.design.widget.TextInputLayout android:id="@+id/til_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/default_margin_16dp" android:layout_marginRight="@dimen/default_margin_16dp" android:layout_marginTop="@dimen/default_margin_8dp" android:layout_below="@id/til_email" android:layout_centerHorizontal="true" android:textColorHint="@color/gray" android:background="@drawable/login_edittext" android:errorEnabled="@{viewmodel.obPassErrorVisibility}" &gt; &lt;EditText android:id="@+id/et_password" android:layout_width="@dimen/login_view_width" android:layout_height="@dimen/login_view_height" android:hint="@string/activity_login_hint_password" android:maxLength="50" android:inputType="textPassword" android:text="@={viewmodel.password}" android:textColor="@color/black" android:textColorHint="@color/gray" android:paddingLeft="@dimen/default_margin_16dp" android:enabled="@{viewmodel.obIsPassFieldEnabled}" /&gt; &lt;/android.support.design.widget.TextInputLayout&gt; </code></pre> <p>as background I use <strong>login_edittext.xml</strong></p> <p></p> <pre><code>&lt;solid android:color="@color/white" /&gt; &lt;corners android:radius="@dimen/login_edittext_radius" /&gt; </code></pre> <p></p> <p>I have check similar answers, but most of them are related to <strong>styles</strong></p> <p><a href="https://stackoverflow.com/questions/27986204/cant-convert-to-color-type-0x2-error-when-inflating-layout-in-fragment-but-onl">Can&#39;t convert to color: type=0x2 error when inflating layout in fragment but only on Samsung Galaxy and Note 4</a></p>
0debug
plots the function with arraysin matlab : <p>funcplot that plots the following function on interval [-pi,pi] using 1000 linearly spaced data points.How can I do that with arrays ? Idon't have any idea.</p> <p>f(x) = 5cos (x4 /3)tan(e 0.2x )cos(ln(4x))</p>
0debug
Swft: IOS: How to create a clickable button with image over an ImageView : I'm a stater for IOS trying to design a small application. I have an ImageView as the Background a smaller imageView as panel. Now I'm trying to add a button with image on the panel, but the button is totally not visible. Then I remove the image and set a background color to it, the button becomes visible but not clickable. Below is the code I wrote: [enter image description here][1] [1]: http://i.stack.imgur.com/kBYDV.jpg
0debug
static inline TranslationBlock *tb_find(CPUState *cpu, TranslationBlock *last_tb, int tb_exit) { TranslationBlock *tb; target_ulong cs_base, pc; uint32_t flags; bool acquired_tb_lock = false; uint32_t cf_mask = curr_cflags(); tb = tb_lookup__cpu_state(cpu, &pc, &cs_base, &flags, cf_mask); if (tb == NULL) { mmap_lock(); tb_lock(); acquired_tb_lock = true; tb = tb_htable_lookup(cpu, pc, cs_base, flags, cf_mask); if (likely(tb == NULL)) { tb = tb_gen_code(cpu, pc, cs_base, flags, cf_mask); } mmap_unlock(); atomic_set(&cpu->tb_jmp_cache[tb_jmp_cache_hash_func(pc)], tb); } #ifndef CONFIG_USER_ONLY if (tb->page_addr[1] != -1) { last_tb = NULL; } #endif if (last_tb && !qemu_loglevel_mask(CPU_LOG_TB_NOCHAIN)) { if (!acquired_tb_lock) { tb_lock(); acquired_tb_lock = true; } if (!(tb->cflags & CF_INVALID)) { tb_add_jump(last_tb, tb_exit, tb); } } if (acquired_tb_lock) { tb_unlock(); } return tb; }
1threat
NameErron in Python3 : xx = str(23-Jun-2019 [8:41:44]) Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> xx = str(23-Jun-2019 [8:41:44]) NameError: name 'Jun' is not defined I am using Python3 in Windows 7 machine.
0debug
Removing additional spaces in a table td : I have some spaces around each and every td in the question palette. hereby i have attached the screenshot.[Problem is displayed][1] [1]: https://i.stack.imgur.com/VkvYh.jpg
0debug
select rows in sql with latest date for each ID repeated multiple times : <p>I have a table where each ID is repeated 3 times. there is a date in front of each id in each row.<br> I want to select entire row for each ID where date is latest. There are total 370 columns in this table i want all columns to get selected when i select that row.</p> <p>Sample -</p> <pre><code>ID Name Date Marks .. .. .. 1 XY 4/3/2017 27 1 fv 4/3/2014 98 1 jk 4/3/2016 09 2 RF 4/12/2015 87 2 kk 4/3/2009 56 2 PP 4/3/2011 76 3 ee 4/3/2001 12 3 ppp 4/3/2003 09 3 lll 4/3/2011 23 </code></pre> <p>The Answer should be </p> <pre><code>ID Name Date Marks .. .. .. 1 XY 4/3/2017 27 2 RF 4/12/2015 87 3 lll 4/3/2011 23 </code></pre> <p>I am attempting as below - </p> <pre><code>select distinct ID,*,max(date) as maxdate from table </code></pre> <p>Also i am trying this in Hive . so not sure if some sql functions dont work in Hive</p> <p>Thanks</p>
0debug
Method Stubs in Java : <p>This is what I have to do:</p> <p>Define stubs for the methods called by the below main(). Each stub should print "FIXME: Finish methodName()" followed by a newline, and should return -1. </p> <p>FIXME: Finish getUserNum()</p> <p>FIXME: Finish getUserNum()</p> <p>FIXME: Finish computeAvg()</p> <p>Avg: -1</p> <p>Here is the code that I have written so far:</p> <pre><code>import java.util.Scanner; public class MthdStubsStatistics { public static int methodName (int userNum1, int userNum2, int avgResult) { System.out.println("FIXME: Finish getUserNum( )"); System.out.println("FIXME: Finish getUserNum( )"); System.out.println("FIXME: Finish computeAvg( )"); System.out.println("Avg: -1"); return 0; } public static void main() { int userNum1 = 0; int userNum2 = 0; int avgResult = 0; userNum1 = getUserNum(); userNum2 = getUserNum(); avgResult = computeAvg(userNum1, userNum2); System.out.println("Avg: " + avgResult); return; } } </code></pre> <p>I can only edit the public static int methodName section. I thought I knew how method stubs operated, but I guess not. I swear that I am doing something wrong that is simple, but if someone could please help me out, that would be great.</p>
0debug
Find characters up to first occurrence of '\' in string rails : I'm still quite new to regex and can't find a similar question to what I am looking for. So I have a string with emails/numbers that is separated by \ string = "test@test.com\test@gmail.com\12345678\" What I am trying to do is get the first full email or number at the beginning of the string. I have been trying to do index of the first \ or match but am not getting the regex right. If: string = "test@test.com\test@gmail.com\12345678\" result = "test@test.com" Or: string = "1236784464\test@test.com\test@gmail.com\12345678\" result = "1236784464" Any help would be appreciated.
0debug
Why does my OpenCL kernel fail on the nVidia driver, but not Intel (possible driver bug)? : <p>I originally wrote an OpenCL program to calculate very large hermitian matrices, where the kernel calculates a single pair of entries in the matrix (the upper triangular portion, and its lower triangular complement). </p> <p>Very early on, I found a very odd problem in that, if my kernel size is exactly 55, the 27th kernel thread would not execute. This problem <em>only</em> occurs when using the nVidia driver and GPU acceleration. When I run it using the Intel driver on the CPU, I find the 27th kernel thread executes just fine. Larger and smaller kernel sizes don't seem to exhibit the problem.</p> <p>Thinking it might be something in my code, I distilled my problem down to the following very simple kernel:</p> <pre><code>__kernel void testIndex(__global float* outMatrix, unsigned int sizeN) { //k is the linear kernel ID (related to but not exactly the linear index into the outMatrix) int k = get_global_id(0); //i'th index (Row or Y) int i = floor((2 * sizeN+1 - sqrt((float)((2 * sizeN + 1) * (2 * sizeN + 1) -8 * k) )) /2); //j'th index (Column or X) int j = k - sizeN * i + i * (i - 1) / 2; j += i; //Index bounds check... If we're greater than sizeN, we're an idle core. //(OpenCL will queue up a fixed block size of worker threads, some of them may be out of bounds) if(j &gt;= sizeN || i &gt;= sizeN) { return; } //Identity case. The original kernel did some special stuff here, //but I've just replaced it with the K index code. if(i == j) { outMatrix[i * sizeN +j] = k; return; } outMatrix[i * sizeN + j] = k; //Since we only have to calculate the upper triangle of our matrix, //(the lower triangle is just the complement of the upper), //this test sets the lower triangle to -9999 so it's easier to see //how the indexing plays out... outMatrix[j * sizeN + i] = -9999.0; } </code></pre> <p><em>outMatrix</em> is the output matrix, and <em>sizeN</em> is the size of the square matrix on a side (i.e. the matrix is sizeN x sizeN). </p> <p>I calculate and execute my kernel size using the following host code:</p> <pre><code>size_t kernelSize = elems * (elems + 1) / 2; cl::NDRange globalRange(kernelSize); cl::NDRange localRange(1); cl::Event event; clCommandQueue.enqueueNDRangeKernel(testKernel, cl::NullRange, globalRange, cl::NullRange, NULL, &amp;event); event.wait(); </code></pre> <p><em>elems</em> is the same as <em>sizeN</em> (i.e. the square root of the matrix size). In this case, elems = 10 (thus giving a kernel size of 55).</p> <p>If I print out the matrix that I read back, I get the following (using boost ublas matrix formatting):</p> <pre><code>[10,10] (( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9), ((-9999, 10, 11, 12, 13, 14, 15, 16, 17, 18), ((-9999, -9999, 19, 20, 21, 22, 23, 24, 25, 26), ((-9999, -9999, -9999, JUNK, 28, 29, 30, 31, 32, 33), ((-9999, -9999, -9999, -9999, 34, 35, 36, 37, 38, 39), ((-9999, -9999, -9999, -9999, -9999, 40, 41, 42, 43, 44), ((-9999, -9999, -9999, -9999, -9999, -9999, 45, 46, 47, 48), ((-9999, -9999, -9999, -9999, -9999, -9999, -9999, 49, 50, 51), ((-9999, -9999, -9999, -9999, -9999, -9999, -9999, -9999, 52, 53), ((-9999, -9999, -9999, -9999, -9999, -9999, -9999, -9999, -9999, 54)) </code></pre> <p>Where "JUNK" is a random value based on whatever happens to be in that memory at the time. This is of course suspicious, as 27 is is basically the exact halfway point in the kernel. </p> <p>Just for completeness, the matrix result is read back using the following code:</p> <pre><code>boost::scoped_array&lt;float&gt; outMatrixReadback(new float[elems * elems]); clCommandQueue.enqueueReadBuffer(clOutputMatrixBuffer, CL_TRUE, 0, elems * elems * sizeof(float), outMatrixReadback.get()); </code></pre> <p>I am making the (perhaps incorrect) assumption that since the code executes fine on an Intel CPU, that there is not some fundamental bug in the code itself. </p> <p>So then, is there perhaps some gotcha I'm not aware of when programming OpenCL on an nVidia card, or am I unfortunate enough to have found a driver bug?</p> <p><strong>Hardware/OS specs</strong></p> <ul> <li><p>nVidia GTX 770</p></li> <li><p>RHEL Server release 6.4 (Santiago)</p></li> <li><p>Intel OpenCL 1.2 4.4.4.0.134 SDK headers</p></li> <li><p>nVidia GeForce driver 384.69</p></li> <li><p>Intel Xeon CPU E6520 @ 2.4 GHz</p></li> </ul>
0debug
How to get data submitted from HTML form that insert into redis database use Rust lang? : I have problem get data from HTML form store value into redis database when user submit. Use Nickel web framework, this is code: fn save_db<'a>(req: &mut Request, res: Response<'a>) -> MiddlewareResult<'a>{ let mut server = Nickel::new(); /* FIXME: connect redis*/ let client = Client::open("redis://127.0.0.1/").unwrap(); let conn = client.get_connection().unwrap(); server.post("/confirmation", middleware!{|req, res| let mut form_data = String::new(); req.origin.read_to_string(&mut form_data).unwrap(); let _: ()= conn.set("contents",form_data).unwrap(); println!("{}", form_data); let mut data = HashMap::<&str,String>::new(); data.insert("content", form_data); data.insert("page_title", "Save blog data".to_string()); return res.render("app/views/blog/save.tpl", &data); }); } //error: cannot infer an appropriate lifetime for lifetime parameter `'b` due to conflicting requirements [E0495](req.origin.read_to_string(&mut form_data).unwrap();)
0debug
How to set up VS-Code to open new files in current instance? : <p>So I've been using Visual Studio Code recently and I really like it. However, every time I open a file, a new window will open rather than a new "tab." I've already tried setting <code>window.openInNewWindow</code> to <code>false</code> and that doesn't work.</p>
0debug
Remove some part from a database field mysql : i am saving complete file path in single field now i want to split it. bellow is my current database file path. Current field name is "video_thumb" ../files/thumbs/2014-Oct/1413648778-sm.jpg now i want to split it into 2 fields folder path in one field i want to split the following to "thumb_path" ../files/thumbs/2014-Oct/ the file name in another field "file_name" 1413648778-sm.jpg i tried this but not access UPDATE video_thumb SET video_thumb = SUBSTRING(video_thumb, 24) WHERE video_thumb LIKE '_:%' any one can help me..
0debug
def maximum_segments(n, a, b, c) : dp = [-1] * (n + 10) dp[0] = 0 for i in range(0, n) : if (dp[i] != -1) : if(i + a <= n ): dp[i + a] = max(dp[i] + 1, dp[i + a]) if(i + b <= n ): dp[i + b] = max(dp[i] + 1, dp[i + b]) if(i + c <= n ): dp[i + c] = max(dp[i] + 1, dp[i + c]) return dp[n]
0debug
static int vqf_probe(AVProbeData *probe_packet) { if (AV_RL32(probe_packet->buf) != MKTAG('T','W','I','N')) return 0; if (!memcmp(probe_packet->buf + 4, "97012000", 8)) return AVPROBE_SCORE_MAX; if (!memcmp(probe_packet->buf + 4, "00052200", 8)) return AVPROBE_SCORE_MAX; return AVPROBE_SCORE_EXTENSION; }
1threat
How to set up SSL for naked domain from Google Domains to Heroku? : <p>I'm trying to use <a href="https://devcenter.heroku.com/articles/automated-certificate-management" rel="noreferrer">Heroku's Automatic Certificate Management</a> to set up SSL for my site. My app is on heroku at <code>myapp.herokuapp.com</code>, and I currently have <a href="https://support.google.com/domains/answer/6072198?hl=en" rel="noreferrer">Subdomain Forwarding</a> set up so that <code>http://www.myapp.com</code> properly shows my app.</p> <p>What I want is to have my site hosted at <code>https://myapp.com</code>.</p> <p>I ran <code>heroku certs:auto:enable</code>, but it shows:</p> <pre><code>=== Automatic Certificate Management is enabled on myapp Domain Status ───────────────── ─────────── www.myapp.com Failing </code></pre> <p>Running <code>heroku domains</code> shows:</p> <pre><code>=== myapp Heroku Domain myapp.herokuapp.com === myapp Custom Domains Domain Name DNS Target ───────────────── ─────────────────────────────── www.myapp.com www.myapp.com.herokudns.com </code></pre> <p>Right now, in Google Domains, I have a Subdomain Forward from <code>@.myapp.com</code> to <code>http://www.myapp.com</code>. I also have a Custom Resource Record with the name <code>www</code>, type <code>CNAME</code>, and data <code>myapp.herokuapp.com.</code>.</p> <p>What do I need to change in my setup so that I can host my site at <code>https://myapp.com</code>?</p>
0debug
static void pcie_aer_update_log(PCIDevice *dev, const PCIEAERErr *err) { uint8_t *aer_cap = dev->config + dev->exp.aer_cap; uint8_t first_bit = ffs(err->status) - 1; uint32_t errcap = pci_get_long(aer_cap + PCI_ERR_CAP); int i; assert(err->status); assert(!(err->status & (err->status - 1))); errcap &= ~(PCI_ERR_CAP_FEP_MASK | PCI_ERR_CAP_TLP); errcap |= PCI_ERR_CAP_FEP(first_bit); if (err->flags & PCIE_AER_ERR_HEADER_VALID) { for (i = 0; i < ARRAY_SIZE(err->header); ++i) { uint8_t *header_log = aer_cap + PCI_ERR_HEADER_LOG + i * sizeof err->header[0]; stl_be_p(header_log, err->header[i]); } } else { assert(!(err->flags & PCIE_AER_ERR_TLP_PREFIX_PRESENT)); memset(aer_cap + PCI_ERR_HEADER_LOG, 0, PCI_ERR_HEADER_LOG_SIZE); } if ((err->flags & PCIE_AER_ERR_TLP_PREFIX_PRESENT) && (pci_get_long(dev->config + dev->exp.exp_cap + PCI_EXP_DEVCAP2) & PCI_EXP_DEVCAP2_EETLPP)) { for (i = 0; i < ARRAY_SIZE(err->prefix); ++i) { uint8_t *prefix_log = aer_cap + PCI_ERR_TLP_PREFIX_LOG + i * sizeof err->prefix[0]; stl_be_p(prefix_log, err->prefix[i]); } errcap |= PCI_ERR_CAP_TLP; } else { memset(aer_cap + PCI_ERR_TLP_PREFIX_LOG, 0, PCI_ERR_TLP_PREFIX_LOG_SIZE); } pci_set_long(aer_cap + PCI_ERR_CAP, errcap); }
1threat
How to split string to sring array withou word splittig in C++ : I need to split input string (array of word, space delimited), into string array with max length 'M' without breakdown any word, How can do this in C++? for example: input string="I need to split input string"; where M=10; output array ={"I need to ","split ","input ","string"};
0debug
static inline void ff_h264_biweight_WxH_mmx2(uint8_t *dst, uint8_t *src, int stride, int log2_denom, int weightd, int weights, int offsetd, int offsets, int w, int h) { int x, y; int offset = ((offsets + offsetd + 1) | 1) << log2_denom; asm volatile( "movd %0, %%mm3 \n\t" "movd %1, %%mm4 \n\t" "movd %2, %%mm5 \n\t" "movd %3, %%mm6 \n\t" "pshufw $0, %%mm3, %%mm3 \n\t" "pshufw $0, %%mm4, %%mm4 \n\t" "pshufw $0, %%mm5, %%mm5 \n\t" "pxor %%mm7, %%mm7 \n\t" :: "g"(weightd), "g"(weights), "g"(offset), "g"(log2_denom+1) ); for(y=0; y<h; y++){ for(x=0; x<w; x+=4){ asm volatile( "movd %0, %%mm0 \n\t" "movd %1, %%mm1 \n\t" "punpcklbw %%mm7, %%mm0 \n\t" "punpcklbw %%mm7, %%mm1 \n\t" "pmullw %%mm3, %%mm0 \n\t" "pmullw %%mm4, %%mm1 \n\t" "paddw %%mm5, %%mm0 \n\t" "paddw %%mm1, %%mm0 \n\t" "psraw %%mm6, %%mm0 \n\t" "packuswb %%mm0, %%mm0 \n\t" "movd %%mm0, %0 \n\t" : "+m"(*(uint32_t*)(dst+x)) : "m"(*(uint32_t*)(src+x)) ); } src += stride; dst += stride; } }
1threat
Remove duplicates from JSON file : <p>My JSON file is very big so I won't show here all the data, but here's the example.</p> <pre><code>[ { "firstName": "C. Ronaldo", "lastName": "dos Santos Aveiro", "commonName": "Cristiano Ronaldo" }, { "firstName": "Luka", "lastName": "Modrić", "commonName": "" }, { "firstName": "C. Ronaldo", "lastName": "dos Santos Aveiro", "commonName": "Cristiano Ronaldo" } ] </code></pre> <p>What I want to achive is to remove duplicated players that have same values inside.</p> <p>So I want to get a result like:</p> <pre><code>[ { "firstName": "C. Ronaldo", "lastName": "dos Santos Aveiro", "commonName": "Cristiano Ronaldo" }, { "firstName": "Luka", "lastName": "Modrić", "commonName": "" } ] </code></pre> <p>Thx in advance :)</p>
0debug
python- changing the pen color in tkinter : I'm using tkinter to create a software that works like a sketchpad. One of the capabilities is for the user to be able to change the pen color. I have no idea how to do so. How can the user change the pen color?
0debug
int cpu_x86_register(X86CPU *cpu, const char *cpu_model) { CPUX86State *env = &cpu->env; x86_def_t def1, *def = &def1; Error *error = NULL; memset(def, 0, sizeof(*def)); if (cpu_x86_find_by_name(def, cpu_model) < 0) return -1; if (def->vendor1) { env->cpuid_vendor1 = def->vendor1; env->cpuid_vendor2 = def->vendor2; env->cpuid_vendor3 = def->vendor3; } else { env->cpuid_vendor1 = CPUID_VENDOR_INTEL_1; env->cpuid_vendor2 = CPUID_VENDOR_INTEL_2; env->cpuid_vendor3 = CPUID_VENDOR_INTEL_3; } env->cpuid_vendor_override = def->vendor_override; object_property_set_int(OBJECT(cpu), def->level, "level", &error); object_property_set_int(OBJECT(cpu), def->family, "family", &error); object_property_set_int(OBJECT(cpu), def->model, "model", &error); object_property_set_int(OBJECT(cpu), def->stepping, "stepping", &error); env->cpuid_features = def->features; env->cpuid_ext_features = def->ext_features; env->cpuid_ext2_features = def->ext2_features; env->cpuid_ext3_features = def->ext3_features; object_property_set_int(OBJECT(cpu), def->xlevel, "xlevel", &error); env->cpuid_kvm_features = def->kvm_features; env->cpuid_svm_features = def->svm_features; env->cpuid_ext4_features = def->ext4_features; env->cpuid_7_0_ebx = def->cpuid_7_0_ebx_features; env->cpuid_xlevel2 = def->xlevel2; object_property_set_int(OBJECT(cpu), (int64_t)def->tsc_khz * 1000, "tsc-frequency", &error); if (env->cpuid_vendor1 == CPUID_VENDOR_AMD_1 && env->cpuid_vendor2 == CPUID_VENDOR_AMD_2 && env->cpuid_vendor3 == CPUID_VENDOR_AMD_3) { env->cpuid_ext2_features &= ~CPUID_EXT2_AMD_ALIASES; env->cpuid_ext2_features |= (def->features & CPUID_EXT2_AMD_ALIASES); } if (!kvm_enabled()) { env->cpuid_features &= TCG_FEATURES; env->cpuid_ext_features &= TCG_EXT_FEATURES; env->cpuid_ext2_features &= (TCG_EXT2_FEATURES #ifdef TARGET_X86_64 | CPUID_EXT2_SYSCALL | CPUID_EXT2_LM #endif ); env->cpuid_ext3_features &= TCG_EXT3_FEATURES; env->cpuid_svm_features &= TCG_SVM_FEATURES; } object_property_set_str(OBJECT(cpu), def->model_id, "model-id", &error); if (error_is_set(&error)) { error_free(error); return -1; } return 0; }
1threat
void qio_dns_resolver_lookup_result(QIODNSResolver *resolver, QIOTask *task, size_t *naddrs, SocketAddress ***addrs) { struct QIODNSResolverLookupData *data = qio_task_get_result_pointer(task); size_t i; *naddrs = 0; *addrs = NULL; if (!data) { return; } *naddrs = data->naddrs; *addrs = g_new0(SocketAddress *, data->naddrs); for (i = 0; i < data->naddrs; i++) { (*addrs)[i] = QAPI_CLONE(SocketAddress, data->addrs[i]); } }
1threat
static int ffmal_update_format(AVCodecContext *avctx) { MMALDecodeContext *ctx = avctx->priv_data; MMAL_STATUS_T status; int ret = 0; MMAL_COMPONENT_T *decoder = ctx->decoder; MMAL_ES_FORMAT_T *format_out = decoder->output[0]->format; ffmmal_poolref_unref(ctx->pool_out); if (!(ctx->pool_out = av_mallocz(sizeof(*ctx->pool_out)))) { ret = AVERROR(ENOMEM); goto fail; } atomic_store(&ctx->pool_out->refcount, 1); if (!format_out) goto fail; if ((status = mmal_port_parameter_set_uint32(decoder->output[0], MMAL_PARAMETER_EXTRA_BUFFERS, ctx->extra_buffers))) goto fail; if ((status = mmal_port_parameter_set_boolean(decoder->output[0], MMAL_PARAMETER_VIDEO_INTERPOLATE_TIMESTAMPS, 0))) goto fail; if (avctx->pix_fmt == AV_PIX_FMT_MMAL) { format_out->encoding = MMAL_ENCODING_OPAQUE; } else { format_out->encoding_variant = format_out->encoding = MMAL_ENCODING_I420; } if ((status = mmal_port_format_commit(decoder->output[0]))) goto fail; if ((ret = ff_set_dimensions(avctx, format_out->es->video.crop.x + format_out->es->video.crop.width, format_out->es->video.crop.y + format_out->es->video.crop.height)) < 0) goto fail; if (format_out->es->video.par.num && format_out->es->video.par.den) { avctx->sample_aspect_ratio.num = format_out->es->video.par.num; avctx->sample_aspect_ratio.den = format_out->es->video.par.den; } avctx->colorspace = ffmmal_csp_to_av_csp(format_out->es->video.color_space); decoder->output[0]->buffer_size = FFMAX(decoder->output[0]->buffer_size_min, decoder->output[0]->buffer_size_recommended); decoder->output[0]->buffer_num = FFMAX(decoder->output[0]->buffer_num_min, decoder->output[0]->buffer_num_recommended) + ctx->extra_buffers; ctx->pool_out->pool = mmal_pool_create(decoder->output[0]->buffer_num, decoder->output[0]->buffer_size); if (!ctx->pool_out->pool) { ret = AVERROR(ENOMEM); goto fail; } return 0; fail: return ret < 0 ? ret : AVERROR_UNKNOWN; }
1threat
Regex to split string into groups : <p>How can I match this string in c# using regex so it returns 4 groups per line?</p> <p>1 or more digits|one or more letters|one or more letters|one ore more X-Digit(s)\n</p> <p>Example:</p> <pre><code>123|ABC|ABC|X-1;X-12;X-13 123|ABC|ABC|X-1 </code></pre> <p>I've tried this \d+\|(A-Z)\|(A-Z)\|(X-)d+</p>
0debug
PHP remove duplicated values from array : <p>I have an array with comma separated numbers and I want to remove all duplicated numbers. Is the approach below the best choice or is there a smarter one?</p> <pre><code>$filter_tags_array[] = '4,6,2,5,8'; $filter_tags_array[] = '6,8,1,3,5,7,2,4'; $filter_tags_array[] = '2,4,1,3,5'; $filter_tags_array[] = '6,3,5,8,2,4'; $filter_tags_array[] = '2,8,11,4,9,12'; $filter_tags_array[] = '9,11,2,8,10,12,4'; $tags_id = ''; foreach($filter_tags_array as $filter_tags) { $tags_id .= $filter_tags . ','; } $tags_id = implode(',', array_unique(explode(',', $tags_id))); echo "&lt;pre&gt;"; print_r($tags_id); </code></pre> <p><strong>print_r results: 4,6,2,5,8,1,3,7,11,9,12,10,</strong></p>
0debug
What's the difference between reshape and view in pytorch? : <p>In numpy, we use <code>ndarray.reshape()</code> for reshaping an array.</p> <p>I noticed that in pytorch, people use <code>torch.view(...)</code> for the same purpose, but at the same time, there is also a <code>torch.reshape(...)</code> existing.</p> <p>So I am wondering what the differences are between them and when I should use either of them?</p>
0debug
static int expand_rle_row16(SgiState *s, uint16_t *out_buf, int len, int pixelstride) { unsigned short pixel; unsigned char count; unsigned short *orig = out_buf; uint16_t *out_end = out_buf + len; while (out_buf < out_end) { if (bytestream2_get_bytes_left(&s->g) < 2) return AVERROR_INVALIDDATA; pixel = bytestream2_get_be16u(&s->g); if (!(count = (pixel & 0x7f))) break; if (pixelstride * (count - 1) >= len) { av_log(s->avctx, AV_LOG_ERROR, "Invalid pixel count.\n"); return AVERROR_INVALIDDATA; } if (pixel & 0x80) { while (count--) { pixel = bytestream2_get_ne16(&s->g); AV_WN16A(out_buf, pixel); out_buf += pixelstride; } } else { pixel = bytestream2_get_ne16(&s->g); while (count--) { AV_WN16A(out_buf, pixel); out_buf += pixelstride; } } } return (out_buf - orig) / pixelstride; }
1threat
void qemu_mutex_destroy(QemuMutex *mutex) { assert(mutex->owner == 0); DeleteCriticalSection(&mutex->lock); }
1threat
How can I update my UI controls from another class? : <p>I've got a form class (Form1) and another class (Calculator).</p> <p>In Calculator I've got this method:</p> <pre><code>public int Add(int number1, int number2) { return number1 + number2; } </code></pre> <p>On the form, when you click a button, the Add method should be invoked and the text of a label should be updated to the result.</p> <p>What is the correct way of updating the label? I'm not asking for the easiest way (I know tons of them), I wanna know how this is done in big Windows Form projects.</p> <p>I've seen lots of things how to do it (with Threads, Delegates, and the Invoke() methods, etc), but I'm not quite sure how to correctly do it myself.</p> <p>Thanks in advance!</p> <p>EDIT: Oh noo the downvoting :( Please help me I'm desperate</p>
0debug
static int local_opendir(FsContext *ctx, V9fsPath *fs_path, V9fsFidOpenState *fs) { char buffer[PATH_MAX]; char *path = fs_path->data; fs->dir = opendir(rpath(ctx, path, buffer)); if (!fs->dir) { return -1; } return 0; }
1threat
Can I just use POST and GET for all methods? : <p>Which is better? and why?</p> <p>Using <code>POST</code> and <code>GET</code> HTTP verbs for all APIs or use <code>PUT</code>, <code>PATCH</code> and <code>DELETE</code> as well.</p>
0debug
I'm trying to create a loop in VBA with an autofilter : ActiveSheet.Range("A:E").AutoFilter Field:=4, Criteria1:="=05*", _Operator:=xlAnd, Criteria2:="=*2014" Range([D2], Cells(Rows.Count, "D")).SpecialCells(xlCellTypeVisible)(1).Select Selection.NumberFormat = "[$-409]mmm-yy;@" ActiveCell.FormulaR1C1 = "5/1/2014" Range(Selection, Selection.End(xlDown)).Select Selection.FillDown ActiveSheet.Range("A:E").AutoFilter Field:=4, Criteria1:="=06*", _ Operator:=xlAnd, Criteria2:="=*2014" Range([D2], Cells(Rows.Count, "D")).SpecialCells(xlCellTypeVisible)(1).Select Selection.NumberFormat = "[$-409]mmm-yy;@" ActiveCell.FormulaR1C1 = "6/1/2014" Range(Selection, Selection.End(xlDown)).Select Selection.FillDown ActiveSheet.Range("A:E").AutoFilter Field:=4, Criteria1:="=07*", _ Operator:=xlAnd, Criteria2:="=*2014" Range([D2], Cells(Rows.Count, "D")).SpecialCells(xlCellTypeVisible)(1).Select Selection.NumberFormat = "[$-409]mmm-yy;@" ActiveCell.FormulaR1C1 = "7/1/2014" Range(Selection, Selection.End(xlDown)).Select Selection.FillDown ActiveSheet.Range("A:E").AutoFilter Field:=4, Criteria1:="=08*", _ Operator:=xlAnd, Criteria2:="=*2014" Range([D2], Cells(Rows.Count, "D")).SpecialCells(xlCellTypeVisible)(1).Select Selection.NumberFormat = "[$-409]mmm-yy;@" ActiveCell.FormulaR1C1 = "8/1/2014" Range(Selection, Selection.End(xlDown)).Select Selection.FillDown ActiveSheet.Range("A:E").AutoFilter Field:=4, Criteria1:="=09*", _ Operator:=xlAnd, Criteria2:="=*2014" Range([D2], Cells(Rows.Count, "D")).SpecialCells(xlCellTypeVisible)(1).Select Selection.NumberFormat = "[$-409]mmm-yy;@" ActiveCell.FormulaR1C1 = "9/1/2014" Range(Selection, Selection.End(xlDown)).Select Selection.FillDown
0debug
static int vc1_decode_p_mb_intfr(VC1Context *v) { MpegEncContext *s = &v->s; GetBitContext *gb = &s->gb; int i; int mb_pos = s->mb_x + s->mb_y * s->mb_stride; int cbp = 0; int mqdiff, mquant; int ttmb = v->ttfrm; int mb_has_coeffs = 1; int dmv_x, dmv_y; int val; int first_block = 1; int dst_idx, off; int skipped, fourmv = 0, twomv = 0; int block_cbp = 0, pat, block_tt = 0; int idx_mbmode = 0, mvbp; int stride_y, fieldtx; mquant = v->pq; if (v->skip_is_raw) skipped = get_bits1(gb); else skipped = v->s.mbskip_table[mb_pos]; if (!skipped) { if (v->fourmvswitch) idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_4MV_MBMODE_VLC_BITS, 2); else idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_NON4MV_MBMODE_VLC_BITS, 2); switch (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0]) { case MV_PMODE_INTFR_4MV: fourmv = 1; v->blk_mv_type[s->block_index[0]] = 0; v->blk_mv_type[s->block_index[1]] = 0; v->blk_mv_type[s->block_index[2]] = 0; v->blk_mv_type[s->block_index[3]] = 0; break; case MV_PMODE_INTFR_4MV_FIELD: fourmv = 1; v->blk_mv_type[s->block_index[0]] = 1; v->blk_mv_type[s->block_index[1]] = 1; v->blk_mv_type[s->block_index[2]] = 1; v->blk_mv_type[s->block_index[3]] = 1; break; case MV_PMODE_INTFR_2MV_FIELD: twomv = 1; v->blk_mv_type[s->block_index[0]] = 1; v->blk_mv_type[s->block_index[1]] = 1; v->blk_mv_type[s->block_index[2]] = 1; v->blk_mv_type[s->block_index[3]] = 1; break; case MV_PMODE_INTFR_1MV: v->blk_mv_type[s->block_index[0]] = 0; v->blk_mv_type[s->block_index[1]] = 0; v->blk_mv_type[s->block_index[2]] = 0; v->blk_mv_type[s->block_index[3]] = 0; break; } if (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_INTRA) { s->current_picture.f.motion_val[1][s->block_index[0]][0] = 0; s->current_picture.f.motion_val[1][s->block_index[0]][1] = 0; s->current_picture.f.mb_type[mb_pos] = MB_TYPE_INTRA; s->mb_intra = v->is_intra[s->mb_x] = 1; for (i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = 1; fieldtx = v->fieldtx_plane[mb_pos] = get_bits1(gb); mb_has_coeffs = get_bits1(gb); if (mb_has_coeffs) cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2); v->s.ac_pred = v->acpred_plane[mb_pos] = get_bits1(gb); GET_MQUANT(); s->current_picture.f.qscale_table[mb_pos] = mquant; s->y_dc_scale = s->y_dc_scale_table[mquant]; s->c_dc_scale = s->c_dc_scale_table[mquant]; dst_idx = 0; for (i = 0; i < 6; i++) { s->dc_val[0][s->block_index[i]] = 0; dst_idx += i >> 2; val = ((cbp >> (5 - i)) & 1); v->mb_type[0][s->block_index[i]] = s->mb_intra; v->a_avail = v->c_avail = 0; if (i == 2 || i == 3 || !s->first_slice_line) v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]]; if (i == 1 || i == 3 || s->mb_x) v->c_avail = v->mb_type[0][s->block_index[i] - 1]; vc1_decode_intra_block(v, s->block[i], i, val, mquant, (i & 4) ? v->codingset2 : v->codingset); if ((i>3) && (s->flags & CODEC_FLAG_GRAY)) continue; v->vc1dsp.vc1_inv_trans_8x8(s->block[i]); if (i < 4) { stride_y = s->linesize << fieldtx; off = (fieldtx) ? ((i & 1) * 8) + ((i & 2) >> 1) * s->linesize : (i & 1) * 8 + 4 * (i & 2) * s->linesize; } else { stride_y = s->uvlinesize; off = 0; } s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, stride_y); } } else { mb_has_coeffs = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][3]; if (mb_has_coeffs) cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2); if (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_2MV_FIELD) { v->twomvbp = get_vlc2(gb, v->twomvbp_vlc->table, VC1_2MV_BLOCK_PATTERN_VLC_BITS, 1); } else { if ((ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_4MV) || (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_4MV_FIELD)) { v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1); } } s->mb_intra = v->is_intra[s->mb_x] = 0; for (i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = 0; fieldtx = v->fieldtx_plane[mb_pos] = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][1]; dst_idx = 0; if (fourmv) { mvbp = v->fourmvbp; for (i = 0; i < 6; i++) { if (i < 4) { val = ((mvbp >> (3 - i)) & 1); if (val) { get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0); } vc1_pred_mv_intfr(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0]); vc1_mc_4mv_luma(v, i, 0); } else if (i == 4) { vc1_mc_4mv_chroma4(v); } } } else if (twomv) { mvbp = v->twomvbp; if (mvbp & 2) { get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0); } vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0]); vc1_mc_4mv_luma(v, 0, 0); vc1_mc_4mv_luma(v, 1, 0); if (mvbp & 1) { get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0); } vc1_pred_mv_intfr(v, 2, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0]); vc1_mc_4mv_luma(v, 2, 0); vc1_mc_4mv_luma(v, 3, 0); vc1_mc_4mv_chroma4(v); } else { mvbp = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][2]; if (mvbp) { get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0); } vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0]); vc1_mc_1mv(v, 0); } if (cbp) GET_MQUANT(); s->current_picture.f.qscale_table[mb_pos] = mquant; if (!v->ttmbf && cbp) ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2); for (i = 0; i < 6; i++) { s->dc_val[0][s->block_index[i]] = 0; dst_idx += i >> 2; val = ((cbp >> (5 - i)) & 1); if (!fieldtx) off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize); else off = (i & 4) ? 0 : ((i & 1) * 8 + ((i > 1) * s->linesize)); if (val) { pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : (s->linesize << fieldtx), (i & 4) && (s->flags & CODEC_FLAG_GRAY), &block_tt); block_cbp |= pat << (i << 2); if (!v->ttmbf && ttmb < 8) ttmb = -1; first_block = 0; } } } } else { s->mb_intra = v->is_intra[s->mb_x] = 0; for (i = 0; i < 6; i++) { v->mb_type[0][s->block_index[i]] = 0; s->dc_val[0][s->block_index[i]] = 0; } s->current_picture.f.mb_type[mb_pos] = MB_TYPE_SKIP; s->current_picture.f.qscale_table[mb_pos] = 0; v->blk_mv_type[s->block_index[0]] = 0; v->blk_mv_type[s->block_index[1]] = 0; v->blk_mv_type[s->block_index[2]] = 0; v->blk_mv_type[s->block_index[3]] = 0; vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0]); vc1_mc_1mv(v, 0); } if (s->mb_x == s->mb_width - 1) memmove(v->is_intra_base, v->is_intra, sizeof(v->is_intra_base[0])*s->mb_stride); return 0; }
1threat
JQuery add or remove class based on menu item clicked : I tried this, searched in the stackoverflow. $(".sub>li>a").click(function(e) { if( $(this).hasClass("open") ) { $(this).removeClass("open").addClass("closed"); } else { // if other menus are open remove open class and add closed $(this).siblings().removeClass("open").addClass("closed"); $(this).removeClass("closed").addClass("open"); } }); but i can't. can you help me? here is my fiddle. https://jsfiddle.net/v2oLfcnf/
0debug
TensorFlow TypeError: Value passed to parameter input has DataType uint8 not in list of allowed values: float16, float32 : <p>I am trying to get a simple CNN to train for the past 3 days. </p> <p>First, I have setup an input pipeline/queue configuration that reads images from a directory tree and prepares batches.</p> <p>I got the code for this at this <a href="http://ischlag.github.io/2016/06/19/tensorflow-input-pipeline-example/" rel="noreferrer">link</a>. So, I now have <strong>train_image_batch</strong> and <strong>train_label_batch</strong> that I need to feed to my CNN.</p> <pre><code>train_image_batch, train_label_batch = tf.train.batch( [train_image, train_label], batch_size=BATCH_SIZE # ,num_threads=1 ) </code></pre> <p>And I am unable to figure out how. I am using the code for CNN given at this <a href="https://github.com/rdcolema/tensorflow-image-classification/blob/master/cnn.ipynb" rel="noreferrer">link</a>.</p> <pre><code># Input Layer input_layer = tf.reshape(train_image_batch, [-1, IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS]) # Convolutional Layer #1 conv1 = new_conv_layer(input_layer, NUM_CHANNELS, 5, 32, 2) # Pooling Layer #1 pool1 = new_pooling_layer(conv1, 2, 2) </code></pre> <p>The input_layer on printing shows this</p> <blockquote> <p>Tensor("Reshape:0", shape=(5, 120, 120, 3), dtype=uint8)</p> </blockquote> <p>The next line crashes with TypeError; conv1 = new_conv_layer(...). The body of new_conv_layer function is given below</p> <pre><code>def new_conv_layer(input, # The previous layer. num_input_channels, # Num. channels in prev. layer. filter_size, # Width and height of each filter. num_filters, # Number of filters. stride): # Shape of the filter-weights for the convolution. # This format is determined by the TensorFlow API. shape = [filter_size, filter_size, num_input_channels, num_filters] # Create new weights aka. filters with the given shape. weights = tf.Variable(tf.truncated_normal(shape, stddev=0.05)) # Create new biases, one for each filter. biases = tf.Variable(tf.constant(0.05, shape=[num_filters])) # Create the TensorFlow operation for convolution. # Note the strides are set to 1 in all dimensions. # The first and last stride must always be 1, # because the first is for the image-number and # the last is for the input-channel. # But e.g. strides=[1, 2, 2, 1] would mean that the filter # is moved 2 pixels across the x- and y-axis of the image. # The padding is set to 'SAME' which means the input image # is padded with zeroes so the size of the output is the same. layer = tf.nn.conv2d(input=input, filter=weights, strides=[1, stride, stride, 1], padding='SAME') # Add the biases to the results of the convolution. # A bias-value is added to each filter-channel. layer += biases # Rectified Linear Unit (ReLU). # It calculates max(x, 0) for each input pixel x. # This adds some non-linearity to the formula and allows us # to learn more complicated functions. layer = tf.nn.relu(layer) # Note that ReLU is normally executed before the pooling, # but since relu(max_pool(x)) == max_pool(relu(x)) we can # save 75% of the relu-operations by max-pooling first. # We return both the resulting layer and the filter-weights # because we will plot the weights later. return layer, weights </code></pre> <p>Precisely it crashes at <strong><em>tf.nn.conv2d</em></strong> with this error </p> <blockquote> <p>TypeError: Value passed to parameter 'input' has DataType uint8 not in list of allowed values: float16, float32</p> </blockquote>
0debug
static int sh_pci_host_init(PCIDevice *d) { pci_config_set_vendor_id(d->config, PCI_VENDOR_ID_HITACHI); pci_config_set_device_id(d->config, PCI_DEVICE_ID_HITACHI_SH7751R); pci_set_word(d->config + PCI_COMMAND, PCI_COMMAND_WAIT); pci_set_word(d->config + PCI_STATUS, PCI_STATUS_CAP_LIST | PCI_STATUS_FAST_BACK | PCI_STATUS_DEVSEL_MEDIUM); return 0; }
1threat
How to use custom Input with Formik in React? : <p>I'm trying to use <a href="https://material-ui-pickers.firebaseapp.com/" rel="noreferrer">DatePicker</a> within <a href="https://github.com/jaredpalmer/formik/" rel="noreferrer">Formik</a>. But when I click DatePicker's date its form value is not changed. Instead, I got this error: </p> <blockquote> <p>Uncaught TypeError: e.persist is not a function at Formik._this.handleChange (formik.es6.js:5960)</p> </blockquote> <p>I shortify code, the code is below</p> <pre><code>const SomeComponent = () =&gt; ( &lt;Formik render={({ values, handleSubmit, handleChange, setFieldValue }) =&gt; { return ( &lt;div&gt; &lt;form onSubmit={handleSubmit}&gt; &lt;DatePicker name={'joinedAt'} value={values['joinedAt']} onChange={handleChange} /&gt; &lt;/form&gt; &lt;/div&gt; ) }} /&gt; ) </code></pre> <p>I googled few documents, <a href="https://github.com/jaredpalmer/formik/issues/187" rel="noreferrer">https://github.com/jaredpalmer/formik/issues/187</a> and <a href="https://github.com/jaredpalmer/formik/issues/86" rel="noreferrer">https://github.com/jaredpalmer/formik/issues/86</a></p> <p>So I tried like below, but it's not working. </p> <pre><code> ...setFieldValue &lt;DatePicker name={'joinedAt'} value={values['joinedAt']} onChange={setFieldValue} /&gt; </code></pre>
0debug
Schema Registry for Protobuf Schemas : <p>I'm conducting an investigation into the use of Protobuf for my organization and have a need to perform schema discovery. I've seen a number of articles related to Confluent Schema Registry with Avro. What are folks using for Protobuf?</p>
0debug
how to access first two digits of a number : I want to access first two digits of a number, and i have used sub string/sub str/slice none of them is working its throwing error like sub string is not defined render() { let trial123 = this.props.buildInfo["abc.version"]; var str = trial123.toString(); var strFirstThree = str.substring(0,3); console.log(strFirstThree); .... } i have tried above code output of(above code) trial123=19.0.0.1 i need only 19.0 how can i achieve this?
0debug
Represent Number in python3 : <p>I want to know if there are any build-in class of python3 that can represent the number in all <strong>hex</strong>, <strong>binary</strong>, <strong>integer</strong>. type.</p> <p>So I do not need to implment lots of methods to convert from one form to the another.</p> <p>For example</p> <pre><code>number = SomeClass(number,base) # then I can call the build in function hex(), int(), bin() to convert the number "0b0000" = bin(number) "0x0000" = hex(number) "0" = int(number) </code></pre>
0debug
Making second textbox"Required”(*) based upon β€œselected” value of Dropdown list : This is my dropdownlist <asp:DropDownList CssClass="DropDownForm" ID="PositionShift" runat="server"> <asp:ListItem Text="Please Select" Value="" /> <asp:ListItem Text="option1" Value="1" /> <asp:ListItem Text="option2" Value="2" /> <asp:ListItem Text="option3" Value="3" /> <asp:ListItem Text="option4" Value="4" /> <asp:ListItem Text="option5" Value="5" /> <asp:ListItem Text="option6" Value="6" /> <asp:ListItem Text="option7" Value="7" /> </asp:DropDownList> label <asp:Label ID="RequisitionNumberLabel" Text="Requisition Number" runat="server"></asp:Label> textbox <asp:TextBox ID="RequisitionNumberTextbox" runat="server" ></asp:TextBox> So, When ever user choose Option1, option5 , option6, then make RequisitionNumberTextbox as a required field with showing "*" on its label. Otherwise its not required and no need to show * on label. I found some related example but I cant figure out on my own.I was trying on Jquery Completely beginner.Thank you
0debug
react open file browser on click a div : <p>My react component:</p> <pre><code>import React, { PropTypes, Component } from 'react' class Content extends Component { handleClick(e) { console.log("Hellooww world") } render() { return ( &lt;div className="body-content"&gt; &lt;div className="add-media" onClick={this.handleClick.bind(this)}&gt; &lt;i className="plus icon"&gt;&lt;/i&gt; &lt;input type="file" id="file" style={{display: "none"}}/&gt; &lt;/div&gt; &lt;/div&gt; ) } } export default Content </code></pre> <p>Here when I click a div with icon I want to open a <code>&lt;input&gt;</code> file which shows me option to select photos. After selecting the photos I want to get the value which photo is selected. How can I do this in react ??</p>
0debug
static int vc1_decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; VC1Context *v = avctx->priv_data; MpegEncContext *s = &v->s; AVFrame *pict = data; uint8_t *buf2 = NULL; const uint8_t *buf_start = buf; if (buf_size == 0) { if (s->low_delay==0 && s->next_picture_ptr) { *pict= *(AVFrame*)s->next_picture_ptr; s->next_picture_ptr= NULL; *data_size = sizeof(AVFrame); } return 0; } if(s->current_picture_ptr==NULL || s->current_picture_ptr->data[0]){ int i= ff_find_unused_picture(s, 0); s->current_picture_ptr= &s->picture[i]; } if (s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){ if (v->profile < PROFILE_ADVANCED) avctx->pix_fmt = PIX_FMT_VDPAU_WMV3; else avctx->pix_fmt = PIX_FMT_VDPAU_VC1; } if (avctx->codec_id == CODEC_ID_VC1) { int buf_size2 = 0; buf2 = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE); if(IS_MARKER(AV_RB32(buf))){ const uint8_t *start, *end, *next; int size; next = buf; for(start = buf, end = buf + buf_size; next < end; start = next){ next = find_next_marker(start + 4, end); size = next - start - 4; if(size <= 0) continue; switch(AV_RB32(start)){ case VC1_CODE_FRAME: if (avctx->hwaccel || s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU) buf_start = start; buf_size2 = vc1_unescape_buffer(start + 4, size, buf2); break; case VC1_CODE_ENTRYPOINT: buf_size2 = vc1_unescape_buffer(start + 4, size, buf2); init_get_bits(&s->gb, buf2, buf_size2*8); vc1_decode_entry_point(avctx, v, &s->gb); break; case VC1_CODE_SLICE: av_log(avctx, AV_LOG_ERROR, "Sliced decoding is not implemented (yet)\n"); av_free(buf2); return -1; } } }else if(v->interlace && ((buf[0] & 0xC0) == 0xC0)){ const uint8_t *divider; divider = find_next_marker(buf, buf + buf_size); if((divider == (buf + buf_size)) || AV_RB32(divider) != VC1_CODE_FIELD){ av_log(avctx, AV_LOG_ERROR, "Error in WVC1 interlaced frame\n"); av_free(buf2); return -1; } buf_size2 = vc1_unescape_buffer(buf, divider - buf, buf2); av_free(buf2);return -1; }else{ buf_size2 = vc1_unescape_buffer(buf, buf_size, buf2); } init_get_bits(&s->gb, buf2, buf_size2*8); } else init_get_bits(&s->gb, buf, buf_size*8); if(v->profile < PROFILE_ADVANCED) { if(vc1_parse_frame_header(v, &s->gb) == -1) { av_free(buf2); return -1; } } else { if(vc1_parse_frame_header_adv(v, &s->gb) == -1) { av_free(buf2); return -1; } } if(s->pict_type != FF_I_TYPE && !v->res_rtm_flag){ av_free(buf2); return -1; } s->current_picture.pict_type= s->pict_type; s->current_picture.key_frame= s->pict_type == FF_I_TYPE; if(s->last_picture_ptr==NULL && (s->pict_type==FF_B_TYPE || s->dropable)){ av_free(buf2); return -1; } if(avctx->hurry_up && s->pict_type==FF_B_TYPE) return -1; if( (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type==FF_B_TYPE) || (avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type!=FF_I_TYPE) || avctx->skip_frame >= AVDISCARD_ALL) { av_free(buf2); return buf_size; } if(avctx->hurry_up>=5) { av_free(buf2); return -1; } if(s->next_p_frame_damaged){ if(s->pict_type==FF_B_TYPE) return buf_size; else s->next_p_frame_damaged=0; } if(MPV_frame_start(s, avctx) < 0) { av_free(buf2); return -1; } s->me.qpel_put= s->dsp.put_qpel_pixels_tab; s->me.qpel_avg= s->dsp.avg_qpel_pixels_tab; if ((CONFIG_VC1_VDPAU_DECODER || CONFIG_WMV3_VDPAU_DECODER) &&s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU) ff_vdpau_vc1_decode_picture(s, buf_start, (buf + buf_size) - buf_start); else if (avctx->hwaccel) { if (avctx->hwaccel->start_frame(avctx, buf, buf_size) < 0) return -1; if (avctx->hwaccel->decode_slice(avctx, buf_start, (buf + buf_size) - buf_start) < 0) return -1; if (avctx->hwaccel->end_frame(avctx) < 0) return -1; } else { ff_er_frame_start(s); v->bits = buf_size * 8; vc1_decode_blocks(v); ff_er_frame_end(s); } MPV_frame_end(s); assert(s->current_picture.pict_type == s->current_picture_ptr->pict_type); assert(s->current_picture.pict_type == s->pict_type); if (s->pict_type == FF_B_TYPE || s->low_delay) { *pict= *(AVFrame*)s->current_picture_ptr; } else if (s->last_picture_ptr != NULL) { *pict= *(AVFrame*)s->last_picture_ptr; } if(s->last_picture_ptr || s->low_delay){ *data_size = sizeof(AVFrame); ff_print_debug_info(s, pict); } av_free(buf2); return buf_size; }
1threat
WPF ICommand Implementation for ComboBoxItem : <p>How can I implement ICommand in WPF(4.5) ComboBoxItem? I tried CommandBinding but I getting error message "Command' property of type 'CommandBinding'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject"</p>
0debug
Getting Index -1 requested, with a size of 1 error while fetching data android : <p>I am using following code to get version of content </p> <pre><code>public String getNotificationVersion(String rootContentId) { String strVersion = ""; try { database.open(); Cursor cur = database.query(Database.DOWNLOAD_TABLE, new String[] { Database.KEY_VERSION }, Database.KEY_ROOT_CONTENT_ID + " = ?", new String[] { rootContentId }, null, null, null); Log.v("NOTIFICATION PRESENT IN DOWNLOAD GETTING DOWNLOAD", "TRUE"); strVersion = cur.getString(0); cur.close(); database.close(); } catch (Exception e) { Log.v("NOTIFICATION PRESENT IN DOWNLOAD GETTING DOWNLOAD", e.getMessage()); // TODO: handle exception } return strVersion; } </code></pre> <p>and at "strVersion = cur.getString(0);" line I am getting Index -1 requested, with a size of 1 error. I have checked database and there is value for this column. Where I am doing wrong?</p> <p>Thanks in Advance</p>
0debug
void qemu_boot_set(const char *boot_order, Error **errp) { Error *local_err = NULL; if (!boot_set_handler) { error_setg(errp, "no function defined to set boot device list for" " this architecture"); return; } validate_bootdevices(boot_order, &local_err); if (local_err) { error_propagate(errp, local_err); return; } if (boot_set_handler(boot_set_opaque, boot_order)) { error_setg(errp, "setting boot device list failed"); return; } }
1threat
void ff_avg_h264_qpel4_mc12_msa(uint8_t *dst, const uint8_t *src, ptrdiff_t stride) { avc_luma_midh_qrt_and_aver_dst_4w_msa(src - (2 * stride) - 2, stride, dst, stride, 4, 0); }
1threat
Elm http request returns NetworkError for successful requests : <p>I have a fair amount of experience building web apps with React but want to learn Elm. I've been banging my head against an HTTP request issue for a couple days now.</p> <p>I'm running an Elm app at localhost:8080 and my supporting API at localhost:8081. Whenever I make an HTTP request (I've tried both GET and POST requests) I get a NetworkError. I've been looking into Elm JSON decoders and think it's possible that this is where my problem exists but I've tried sending simple strings from my server and using the Decode.string decoder in my Elm app and I still get the NetworkError.</p> <p>Here's what my code looks like currently:</p> <p>Commands.elm</p> <pre><code>module Commands exposing (..) import Models exposing (..) import Msg exposing (..) import Http import Json.Decode as Decode import Json.Encode as Encode createTempUser : Model -&gt; Cmd Msg createTempUser model = let tempUserBody = [ ( "firstname", Encode.string model.firstname ) , ( "lastname", Encode.string model.lastname ) , ( "phone", Encode.string model.phone ) ] |&gt; Encode.object |&gt; Http.jsonBody url = myAPIUrl ++ "/endpoint" contentType = Http.header "Content-type" "text/plain" post = Http.request { method = "POST" , headers = [contentType] , url = url , body = tempUserBody , expect = Http.expectJson decodeApiResponse , timeout = Nothing , withCredentials = False } in Http.send Msg.TempUserCreated post decodeApiResponse : Decode.Decoder ApiResponse decodeApiResponse = Decode.map4 ApiResponse (Decode.at ["status"] Decode.int) (Decode.at ["message"] Decode.string) (Decode.at ["created"] Decode.int) (Decode.at ["error"] Decode.string) myAPIUrl : String myAPIUrl = "http://localhost:8081" </code></pre> <p>Models.elm</p> <pre><code>module Models exposing (..) type alias ApiResponse = { status: Int , message: String , created: Int , error: String } </code></pre> <p>Msg.elm</p> <pre><code>module Msg exposing (..) import Navigation exposing (Location) import Models exposing (..) import Http type Msg = ChangeLocation String | OnLocationChange Location | CreateTemporaryUser | TempUserCreated ( Result Http.Error ApiResponse ) </code></pre> <p>Update.elm</p> <pre><code>module Update exposing (..) import Msg exposing (Msg) import Models exposing (..) import Routing exposing (..) import Commands exposing (..) import Navigation update : Msg -&gt; Model -&gt; (Model, Cmd Msg) update msg model = case msg of Msg.ChangeLocation path -&gt; ( { model | changes = model.changes + 1 }, Navigation.newUrl path ) Msg.OnLocationChange location -&gt; ( { model | error = "", route = parseLocation(location) }, Cmd.none ) Msg.CreateTemporaryUser -&gt; ( model, createTempUser model ) Msg.TempUserCreated (Ok res) -&gt; update (Msg.ChangeLocation signupCodePath) { model | httpResponse = toString(res) } Msg.TempUserCreated (Err err) -&gt; ( { model | error = toString(err) }, Cmd.none ) </code></pre> <p>Chrome's Network devtools show the response as this</p> <pre><code>{"status":200,"message":"Successfully inserted temporary user","created":1518739596447,"error":""} </code></pre> <p>I think this may be all the relevant code but if there's more you need to see I'll make an update including the requested code. I'll admit that I don't have a full understanding of the Elm Json.Decode library but I was under the impression that if this was where the issue was I would get an UnexpectedPayload Error that included additional context.</p>
0debug
static void avoid_clipping(AACEncContext *s, SingleChannelElement *sce) { int start, i, j, w; if (sce->ics.clip_avoidance_factor < 1.0f) { for (w = 0; w < sce->ics.num_windows; w++) { start = 0; for (i = 0; i < sce->ics.max_sfb; i++) { float *swb_coeffs = sce->coeffs + start + w*128; for (j = 0; j < sce->ics.swb_sizes[i]; j++) swb_coeffs[j] *= sce->ics.clip_avoidance_factor; start += sce->ics.swb_sizes[i]; } } } }
1threat
static void spapr_memory_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev, Error **errp) { PCDIMMDevice *dimm = PC_DIMM(dev); PCDIMMDeviceClass *ddc = PC_DIMM_GET_CLASS(dimm); MemoryRegion *mr = ddc->get_memory_region(dimm); uint64_t size = memory_region_size(mr); char *mem_dev; if (size % SPAPR_MEMORY_BLOCK_SIZE) { error_setg(errp, "Hotplugged memory size must be a multiple of " "%lld MB", SPAPR_MEMORY_BLOCK_SIZE / M_BYTE); return; } mem_dev = object_property_get_str(OBJECT(dimm), PC_DIMM_MEMDEV_PROP, NULL); if (mem_dev && !kvmppc_is_mem_backend_page_size_ok(mem_dev)) { error_setg(errp, "Memory backend has bad page size. " "Use 'memory-backend-file' with correct mem-path."); return; } }
1threat
How to cast a quotient : <p>I'm making a simple calculator that lists everything when someone inputs two integers. Everything seems to be working well except for the quotient I just can't seem to find that casts.</p> <pre><code>#define _CRT_SECURE_NO_WARNINGS #include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #define SUM a + b #define AVG (SUM) /(float) 2 #define SUBTRACTION a - b #define MULTIPLICATION a * b #define QUOTIENT #define MODULUS a % b void main() { int a, b; printf("Enter two integers: "); scanf("%d%d", &amp;a, &amp;b); printf("\n\nThe Sum is %d\n", SUM); printf("The Difference is %d\n", SUBTRACTION); printf("The Multiplication is %d\n", MULTIPLICATION); printf("The Quotient is %d\n", QUOTIENT); printf("The Average is %0.2f\n", AVG); printf("The Modulus is %d\n", MODULUS); system("PAUSE"); } </code></pre>
0debug
Json to kotlin data classes : <p>Is there existing service for generating kotlin data classes from json model in the way how it works on <a href="http://www.jsonschema2pojo.org/" rel="noreferrer">http://www.jsonschema2pojo.org/</a> site? My new project has over complicated API responses, so it would save me time.</p>
0debug
Undefined reference to 'GetConsoleWindow' but _WIN32_WINNT and NTDDI_WIN7 defined : I am trying to get a handle for a consoleWindow the following: #include <Windows.h> #include <stdio.h> #include <stdlib.h> #define NTDDI_WIN7 as 0x06010000 #define _WIN32_WINNT as 0x0500 int main(int argc, char *argv[]) { HWND self = GetConsoleWindow(); someMoreCode... } I followed instructions from [microsoft][1] and [microsoftheaders][2], but I still get: > undefined reference to `GetConsoleWindow' [1]: https://docs.microsoft.com/en-us/windows/console/getconsolewindow [2]: https://msdn.microsoft.com/library/windows/desktop/aa383745
0debug
In .Net 1.1 TreeView , 'OnDrawNode' , 'OnNodeMouseClick' , 'OnNodeMouseDoubleClick' and 'TreeNodeMouseClickEventArgs' not found : <p>In .Net Framework 1.1 'System.Windows.Forms.TreeView' some virtual methods and one EventArgs not found. they are listed below </p> <ol> <li>'System.Windows.Forms.TreeView' does not contain a definition for 'OnDrawNode'</li> <li>'System.Windows.Forms.TreeView' does not contain a definition for 'OnNodeMouseClick'</li> <li>'System.Windows.Forms.TreeView' does not contain a definition for 'OnNodeMouseDoubleClick'</li> <li>The type or namespace name 'TreeNodeMouseClickEventArgs' could not be found (are you missing a using directive or an assembly reference?)</li> </ol>
0debug
Cannot set label's content to zero : <p>I've got the following coding where I am trying to step through a couple of <code>if</code> statements, but I've got a problem with setting my label's content to <code>0</code>;</p> <pre><code>private void UnderRunBumper() { lblGVMAmount.Content = 0; //Issue here if (Convert.ToInt32(txtExternalLength.Text) &gt;= 6000) lblUnderRunBumper.Content = "Under-Run Bumper"; else if (Convert.ToInt32(lblGVMAmount.Content.ToString()) &gt;= 8000) lblUnderRunBumper.Content = "Under-Run Bumper"; else if (cmbBodyType.SelectedIndex == 6 || cmbBodyType.SelectedIndex == 7 || cmbBodyType.SelectedIndex == 8 || cmbBodyType.SelectedIndex == 9 || cmbBodyType.SelectedIndex == 10) lblUnderRunBumper.Content = "Under-Run Bumper"; else lblUnderRunBumper.Content = ""; } </code></pre> <p>I get the error:</p> <blockquote> <p>Object reference not set to an instance of an object.</p> </blockquote> <p>I don't understand. Why can't I set my label's value to 0?</p>
0debug
How to create disabled state of the font awesome icons? : <p>I am using font awesome icons and I need to have a disabled state of the icons. is there any way to do this. I am also using bootstrap. </p> <p>This is how I am using icons.</p> <pre><code>&lt;i class="fa fa-slack"&gt;&lt;i/&gt; </code></pre> <p>I just need the icon to look like grayed out.</p>
0debug
static av_cold int ra144_encode_init(AVCodecContext * avctx) { RA144Context *ractx; int ret; if (avctx->channels != 1) { av_log(avctx, AV_LOG_ERROR, "invalid number of channels: %d\n", avctx->channels); return -1; } avctx->frame_size = NBLOCKS * BLOCKSIZE; avctx->delay = avctx->frame_size; avctx->bit_rate = 8000; ractx = avctx->priv_data; ractx->lpc_coef[0] = ractx->lpc_tables[0]; ractx->lpc_coef[1] = ractx->lpc_tables[1]; ractx->avctx = avctx; ret = ff_lpc_init(&ractx->lpc_ctx, avctx->frame_size, LPC_ORDER, FF_LPC_TYPE_LEVINSON); if (ret < 0) goto error; ff_af_queue_init(avctx, &ractx->afq); return 0; error: ra144_encode_close(avctx); return ret; }
1threat
How to understand tf.get_collection() in TensorFlow : <p>I am confused by <code>tf.get_collection()</code> form the <a href="https://www.tensorflow.org/versions/master/api_docs/python/framework.html#Graph.get_collection" rel="noreferrer">docs</a>, it says that </p> <blockquote> <p>Returns a list of values in the collection with the given name.</p> </blockquote> <p>And an example from the Internet is here</p> <pre><code>from_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, from_scope) </code></pre> <p>Is it means that it collects variables from <code>tf.GraphKeys.TRAINABLE_VARIABLES</code> to <code>from_scope</code>?</p> <p>However, how can I use this function if I want to get variables from another scope? Thank you!</p>
0debug
Creating ComboBox in XAML from XML : <p>I have an xml like this... </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;Actions&gt; &lt;Group Name="Process" Expand="true"&gt; &lt;Action Name="Configure Process" Type="LaunchProcess"&gt; &lt;Instructions&gt;Click the button to launch Process.&lt;/Instructions&gt; &lt;ActionDetails ProcessName="C:\program files (x86)\measure\process.exe"&gt; &lt;/ActionDetails&gt; &lt;/Action&gt; &lt;Action Name="Update Process" Type="LaunchProcess"&gt; &lt;Instructions&gt;Click the button to update process.&lt;/Instructions&gt; &lt;ActionDetails ProcessName="C:\Program Files\Updater.exe" WorkingDir="C:\Program Files\tools"&gt; &lt;/ActionDetails&gt; &lt;/Action&gt; &lt;/Group&gt; &lt;Group Name="Windows" Expand="false"&gt; &lt;Action Name="Set Time" Type="LaunchProcess"&gt; &lt;Instructions&gt;Set the time.&lt;/Instructions&gt; &lt;ActionDetails ProcessName="control.exe" Arguments="timedate.cpl"&gt; &lt;/ActionDetails&gt; &lt;/Action&gt; &lt;Action Name="Set Name" Type="LaunchProcess"&gt; &lt;Instructions&gt;Set the name.&lt;/Instructions&gt; &lt;ActionDetails ProcessName="control.exe" Arguments="sysdm.cpl"&gt; &lt;/ActionDetails&gt; &lt;/Action&gt; &lt;/Group&gt; &lt;Actions&gt;</code></pre> </div> </div> </p> <p>How would I go at making a ComboBox in XAML from this XML? I am working with Visual Studio 2013 in C# and WPF.</p>
0debug
static void s390_init(ram_addr_t ram_size, const char *boot_device, const char *kernel_filename, const char *kernel_cmdline, const char *initrd_filename, const char *cpu_model) { CPUState *env = NULL; ram_addr_t ram_addr; ram_addr_t kernel_size = 0; ram_addr_t initrd_offset; ram_addr_t initrd_size = 0; int i; if (!kvm_enabled()) { fprintf(stderr, "The S390 target only works with KVM enabled\n"); exit(1); } s390_bus = s390_virtio_bus_init(&ram_size); ram_addr = qemu_ram_alloc(NULL, "s390.ram", ram_size); cpu_register_physical_memory(0, ram_size, ram_addr); if (cpu_model == NULL) { cpu_model = "host"; } ipi_states = qemu_malloc(sizeof(CPUState *) * smp_cpus); for (i = 0; i < smp_cpus; i++) { CPUState *tmp_env; tmp_env = cpu_init(cpu_model); if (!env) { env = tmp_env; } ipi_states[i] = tmp_env; tmp_env->halted = 1; tmp_env->exception_index = EXCP_HLT; } env->halted = 0; env->exception_index = 0; if (kernel_filename) { kernel_size = load_image(kernel_filename, qemu_get_ram_ptr(0)); if (lduw_phys(KERN_IMAGE_START) != 0x0dd0) { fprintf(stderr, "Specified image is not an s390 boot image\n"); exit(1); } env->psw.addr = KERN_IMAGE_START; env->psw.mask = 0x0000000180000000ULL; } else { ram_addr_t bios_size = 0; char *bios_filename; if (bios_name == NULL) { bios_name = ZIPL_FILENAME; } bios_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name); bios_size = load_image(bios_filename, qemu_get_ram_ptr(ZIPL_LOAD_ADDR)); if ((long)bios_size < 0) { hw_error("could not load bootloader '%s'\n", bios_name); } if (bios_size > 4096) { hw_error("stage1 bootloader is > 4k\n"); } env->psw.addr = ZIPL_START; env->psw.mask = 0x0000000180000000ULL; } if (initrd_filename) { initrd_offset = INITRD_START; while (kernel_size + 0x100000 > initrd_offset) { initrd_offset += 0x100000; } initrd_size = load_image(initrd_filename, qemu_get_ram_ptr(initrd_offset)); stq_phys(INITRD_PARM_START, initrd_offset); stq_phys(INITRD_PARM_SIZE, initrd_size); } if (kernel_cmdline) { cpu_physical_memory_rw(KERN_PARM_AREA, (uint8_t *)kernel_cmdline, strlen(kernel_cmdline), 1); } for(i = 0; i < nb_nics; i++) { NICInfo *nd = &nd_table[i]; DeviceState *dev; if (!nd->model) { nd->model = qemu_strdup("virtio"); } if (strcmp(nd->model, "virtio")) { fprintf(stderr, "S390 only supports VirtIO nics\n"); exit(1); } dev = qdev_create((BusState *)s390_bus, "virtio-net-s390"); qdev_set_nic_properties(dev, nd); qdev_init_nofail(dev); } for(i = 0; i < MAX_BLK_DEVS; i++) { DriveInfo *dinfo; DeviceState *dev; dinfo = drive_get(IF_IDE, 0, i); if (!dinfo) { continue; } dev = qdev_create((BusState *)s390_bus, "virtio-blk-s390"); qdev_prop_set_drive_nofail(dev, "drive", dinfo->bdrv); qdev_init_nofail(dev); } }
1threat
Laravel 5 Naming Conventions : <p>I am bit confused with Laravel conventions as I am new to this framework. I am following Jeffrey Way Laracasts videos he uses <strong>Plural</strong> for Controller names.</p> <p>E.g.: <strong>PagesController, Cards Controller, PostsController</strong></p> <p>But if I refer official documentations of <a href="https://laravel.com/docs/5.3/controllers#resource-controllers" rel="noreferrer">Laravel > Controllers</a> and <a href="https://laravel.com/docs/5.2/quickstart-intermediate#the-task-controller" rel="noreferrer">Laravel > Tutorials > Quick Start > Intermediate Task List</a> it uses <strong>Singular</strong> names.</p> <p>E.g.: <strong>PhotoController, TaskController</strong></p> <p>Can anybody please list down the official coding conventions for following entities?</p> <p>Tables: <strong>posts, comments, post_comments</strong> or <strong>Post, Comment, PostComment</strong></p> <p>Columns: <strong>id, post_id, comment_id</strong> or <strong>id, postId, commentId</strong></p> <p>Controllers: <strong>PagesController, Cards Controller, PostsController</strong> or <strong>PhotoController, TaskController</strong></p> <p>Models: <strong>Pages, Cards, Posts</strong> or <strong>Page, Card, Post</strong> </p>
0debug
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename, AVInputFormat *fmt, int buf_size, AVFormatParameters *ap) { int err, probe_size; AVProbeData probe_data, *pd = &probe_data; ByteIOContext *pb = NULL; pd->filename = ""; if (filename) pd->filename = filename; pd->buf = NULL; pd->buf_size = 0; if (!fmt) { fmt = av_probe_input_format(pd, 0); } if (!fmt || !(fmt->flags & AVFMT_NOFILE)) { if ((err=url_fopen(&pb, filename, URL_RDONLY)) < 0) { goto fail; } if (buf_size > 0) { url_setbufsize(pb, buf_size); } for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){ int score= probe_size < PROBE_BUF_MAX ? AVPROBE_SCORE_MAX/4 : 0; pd->buf= av_realloc(pd->buf, probe_size + AVPROBE_PADDING_SIZE); pd->buf_size = get_buffer(pb, pd->buf, probe_size); memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE); if (url_fseek(pb, 0, SEEK_SET) < 0) { url_fclose(pb); if (url_fopen(&pb, filename, URL_RDONLY) < 0) { pb = NULL; err = AVERROR(EIO); goto fail; } } fmt = av_probe_input_format2(pd, 1, &score); } av_freep(&pd->buf); } if (!fmt) { err = AVERROR_NOFMT; goto fail; } if (fmt->flags & AVFMT_NEEDNUMBER) { if (!av_filename_number_test(filename)) { err = AVERROR_NUMEXPECTED; goto fail; } } err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap); if (err) goto fail; return 0; fail: av_freep(&pd->buf); if (pb) url_fclose(pb); *ic_ptr = NULL; return err; }
1threat
Set a property value to 0, when creating a user! MVC : how can i set the balance property to 0, when registering a new account on my create view in mvc. I want the balance to be 0 as default for the user who has just been registered! namespace CSGO_MVC.Models { public class SteamAccount { [Key] public int Id { get; set; } public long SteamId { get; set; } public Balance accountbalance { get; set; } public string UserName { get; set; } public string Password { get; set; } public bool UserStatus { get; set; } public string TradeLink { get; set; } } } Here is my controller [HttpGet] public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(SteamAccount acc) { if (ModelState.IsValid) { AccountRepo.Insert(acc); AccountRepo.Save(); return RedirectToAction("Index"); } else { return View(acc); } } Thank you guys!
0debug
void ppc_hash64_store_hpte(PowerPCCPU *cpu, hwaddr ptex, uint64_t pte0, uint64_t pte1) { CPUPPCState *env = &cpu->env; hwaddr offset = ptex * HASH_PTE_SIZE_64; if (env->external_htab == MMU_HASH64_KVM_MANAGED_HPT) { kvmppc_write_hpte(ptex, pte0, pte1); return; } if (env->external_htab) { stq_p(env->external_htab + offset, pte0); stq_p(env->external_htab + offset + HASH_PTE_SIZE_64 / 2, pte1); } else { hwaddr base = ppc_hash64_hpt_base(cpu); stq_phys(CPU(cpu)->as, base + offset, pte0); stq_phys(CPU(cpu)->as, base + offset + HASH_PTE_SIZE_64 / 2, pte1); } }
1threat
void lance_init(NICInfo *nd, int irq, uint32_t leaddr, uint32_t ledaddr) { LANCEState *s; int lance_io_memory, ledma_io_memory; s = qemu_mallocz(sizeof(LANCEState)); if (!s) return; s->irq = irq; lance_io_memory = cpu_register_io_memory(0, lance_mem_read, lance_mem_write, s); cpu_register_physical_memory(leaddr, 4, lance_io_memory); ledma_io_memory = cpu_register_io_memory(0, ledma_mem_read, ledma_mem_write, s); cpu_register_physical_memory(ledaddr, 16, ledma_io_memory); memcpy(s->macaddr, nd->macaddr, 6); lance_reset(s); s->vc = qemu_new_vlan_client(nd->vlan, lance_receive, s); snprintf(s->vc->info_str, sizeof(s->vc->info_str), "lance macaddr=%02x:%02x:%02x:%02x:%02x:%02x", s->macaddr[0], s->macaddr[1], s->macaddr[2], s->macaddr[3], s->macaddr[4], s->macaddr[5]); register_savevm("lance", leaddr, 1, lance_save, lance_load, s); qemu_register_reset(lance_reset, s); }
1threat
static uint64_t get_vb(ByteIOContext *bc){ uint64_t val=0; int i= get_v(bc); if(i>8) return UINT64_MAX; while(i--) val = (val<<8) + get_byte(bc); return val; }
1threat
static void pl061_write(void *opaque, hwaddr offset, uint64_t value, unsigned size) { PL061State *s = (PL061State *)opaque; uint8_t mask; if (offset < 0x400) { mask = (offset >> 2) & s->dir; s->data = (s->data & ~mask) | (value & mask); pl061_update(s); return; } switch (offset) { case 0x400: s->dir = value & 0xff; break; case 0x404: s->isense = value & 0xff; break; case 0x408: s->ibe = value & 0xff; break; case 0x40c: s->iev = value & 0xff; break; case 0x410: s->im = value & 0xff; break; case 0x41c: s->istate &= ~value; break; case 0x420: mask = s->cr; s->afsel = (s->afsel & ~mask) | (value & mask); break; case 0x500: s->dr2r = value & 0xff; break; case 0x504: s->dr4r = value & 0xff; break; case 0x508: s->dr8r = value & 0xff; break; case 0x50c: s->odr = value & 0xff; break; case 0x510: s->pur = value & 0xff; break; case 0x514: s->pdr = value & 0xff; break; case 0x518: s->slr = value & 0xff; break; case 0x51c: s->den = value & 0xff; break; case 0x520: s->locked = (value != 0xacce551); break; case 0x524: if (!s->locked) s->cr = value & 0xff; break; case 0x528: s->amsel = value & 0xff; break; default: qemu_log_mask(LOG_GUEST_ERROR, "pl061_write: Bad offset %x\n", (int)offset); } pl061_update(s); }
1threat
CSV file how to break lines? : <p>I've been struggling with parsing a csv file so that every new line is read as a new row. Unfortunately, I couldn't find an answer in the SO forums that addressed my problem. I opened the csv file with textEdit and saw this: </p> <p><a href="https://i.stack.imgur.com/k484Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k484Y.png" alt="enter image description here"></a></p> <p>I think the problem is how to tell the compiler when to break off a new line. For example, right now, it will read z (row 2) as being on the previous row. Please take a look at my code and output below (i am using Xcode v 9.2).</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;vector&gt; #include &lt;fstream&gt; using namespace std; int main() { ifstream ip("ebid2016.csv"); if (!ip.is_open()) { cout &lt;&lt; "can't open file" &lt;&lt; '\n'; } string title; string articleId; string department; string closeDate; string bid; string inventoryId; string vehicleId; string receiptNum; string fund; string nothing; while(ip.good()){ getline(ip,title,'\t'); getline(ip,articleId,'\t'); getline(ip,department,'\t'); getline(ip,closeDate,'\t'); getline(ip,bid,'\t'); getline(ip,inventoryId,'\t'); getline(ip,vehicleId,'\t'); getline(ip,receiptNum,'\t'); getline(ip,fund,'\t'); cout &lt;&lt; "Article Title:" &lt;&lt; title &lt;&lt; '\n'; cout &lt;&lt; "Article ID:" &lt;&lt; articleId &lt;&lt; '\n'; cout &lt;&lt; "Department:" &lt;&lt; department &lt;&lt; '\n'; cout &lt;&lt; "Close Date:" &lt;&lt; closeDate &lt;&lt; '\n'; cout &lt;&lt; "Bid:" &lt;&lt; bid &lt;&lt; '\n'; cout &lt;&lt; "Inventory ID:" &lt;&lt; inventoryId &lt;&lt; '\n'; cout &lt;&lt; "Vehicle ID:" &lt;&lt; vehicleId &lt;&lt; '\n'; cout &lt;&lt; "Receipt Number:" &lt;&lt; receiptNum &lt;&lt; '\n'; cout &lt;&lt; "Fund:" &lt;&lt; fund &lt;&lt; '\n'; cout &lt;&lt; "------------------" &lt;&lt; '\n'; } ip.close(); } </code></pre> <p>Output: </p> <pre><code>Article Title:ArticleTitle Article ID:ArticleID Department:Department Close Date:CloseDate Bid:WinningBid Inventory ID:InventoryID Vehicle ID:VehicleID Receipt Number:ReceiptNumber Fund:Fund z &lt;------------why does z show up here? ------------------ Article Title:97991 Article ID:POLICE PROPERTY AND EVIDENCE UNCLAIMED Department:12/1/16 Close Date:$27.00 Bid:PPEU-031C-149 Inventory ID: Vehicle ID:3689905552 Receipt Number:Enterprise Table Fund:97990 ------------------ etc. </code></pre>
0debug
Invalid syntax in executing SQL query using python : <p>I am trying to run the below SQL query using pymysql in python</p> <pre><code>cursor.execute(""SELECT count(1) from user_login WHERE user_id="+username + "and password="+password"") </code></pre> <p>Here username=abc and password=xyz are variables with values</p> <p>I know there is a problem with quotation marks.Can someone suggest me the right way to do this?</p>
0debug
using regex to match integer in C# : <p>I want a regex to match strings like "1" , "15000" and "15000." as integer, but do not match "15000.0"</p> <p>I have tried:</p> <pre><code>[0-9]+(\\.|[0-9]+)? </code></pre> <p>but failed</p> <p>How to write this regex in C#</p>
0debug
connection.query('SELECT * FROM users WHERE username = ' + input_string)
1threat
Jupyter autoreload fails when changing a class : <p>When using jupyter lab/notebook, most of the time, I put those 2 lines in the first cell of my notebook :</p> <pre><code>%reload_ext autoreload %autoreload 2 </code></pre> <p>Those usually allow me to modify the scripts I import and to use them without having to reimport them or to relaunch the kernel. Yesterday, I encountered an issue : I modified the script, and executing one cell on the notebook gave me an error. Restarting the kernel and redoing the imports fixed it. I investigated this issue, and tried to create a minimal example.</p> <p>Let's say you have the following working directory : </p> <pre><code>+-- nb.ipynb +-- scripts | +-- __init__.py | +-- script1.py </code></pre> <p>The notebook is composed of three cells :</p> <pre><code>%reload_ext autoreload %autoreload 2 </code></pre> <p>\</p> <pre><code>from scripts.script1 import Foo </code></pre> <p>\</p> <pre><code>a = Foo(42) </code></pre> <p>At the beginning of this experiment, script1 contains the following :</p> <pre><code>class Foo(): def __init__(self, x): self.x = x </code></pre> <p>Now, we execute the 3 cells of the notebook, and everything works fine. We then go to script1.py and replace its code by : </p> <pre><code>class Bar(): def __init__(self, x): self.x = x class Foo(Bar): def __init__(self, x): super().__init__(x) </code></pre> <p>We save the file, go back to the notebook, and execute the cell containg <code>a = Foo(42)</code> This gives the following error : </p> <pre><code>[autoreload of script.script failed: Traceback (most recent call last): File "/home/user/miniconda3/lib/python3.6/site-packages/IPython/extensions/autoreload.py", line 245, in check superreload(m, reload, self.old_objects) File "/home/user/miniconda3/lib/python3.6/site-packages/IPython/extensions/autoreload.py", line 384, in superreload update_generic(old_obj, new_obj) File "/home/user/miniconda3/lib/python3.6/site-packages/IPython/extensions/autoreload.py", line 323, in update_generic update(a, b) File "/home/user/miniconda3/lib/python3.6/site-packages/IPython/extensions/autoreload.py", line 288, in update_class if update_generic(old_obj, new_obj): continue File "/home/user/miniconda3/lib/python3.6/site-packages/IPython/extensions/autoreload.py", line 323, in update_generic update(a, b) File "/home/user/miniconda3/lib/python3.6/site-packages/IPython/extensions/autoreload.py", line 266, in update_function setattr(old, name, getattr(new, name)) ValueError: __init__() requires a code object with 0 free vars, not 1 ] </code></pre> <p>Restarting the kernel or executing the import line again fixes this. Why is <code>autoreload</code> not working in this case?</p> <p>PS : This was done in python 3.6, and my original issue with this was in python 3.7</p>
0debug
static int qdraw_probe(AVProbeData *p) { const uint8_t *b = p->buf; if (!b[10] && AV_RB32(b+11) == 0x1102ff0c && !b[15] || p->buf_size >= 528 && !b[522] && AV_RB32(b+523) == 0x1102ff0c && !b[527]) return AVPROBE_SCORE_EXTENSION + 1; return 0; }
1threat
Convert char* to uint16_t c++ : <p>Trying to convert a char* or string into a uint16_t</p> <p>convert this:</p> <pre><code>char* rawData = "9000, 4500, 650, 550, 650, 1650, 600, 550, 650, 550, 600, 1650, 650, 550, 600, 1650, 650, 1650, 650, 1650, 600, 550, 650, 1650, 650, 1650, 650, 550, 600, 1650, 650, 1650, 650, 550, 650, 550, 650, 1650, 650, 550, 650, 550, 650, 550, 600, 550, 650, 550, 650, 550, 650, 1650, 600, 550, 650, 1650, 650, 1650, 650, 1650, 650, 1650, 650, 1650, 650, 1650, 600"; char* rawData_leng = "67"; </code></pre> <p>Into this:</p> <pre><code>uint16_t blawData[67] = {9000, 4500, 650, 550, 650, 1650, 600, 550, 650, 550, 600, 1650, 650, 550, 600, 1650, 650, 1650, 650, 1650, 600, 550, 650, 1650, 650, 1650, 650, 550, 600, 1650, 650, 1650, 650, 550, 650, 550, 650, 1650, 650, 550, 650, 550, 650, 550, 600, 550, 650, 550, 650, 550, 650, 1650, 600, 550, 650, 1650, 650, 1650, 650, 1650, 650, 1650, 650, 1650, 650, 1650, 600}; </code></pre>
0debug
Simple JSON parsing with Jackson : <p>I did not write a lot in Java yet, but I wonder if there is a simple way, to parse JSON and work with the results into a map just like we would do it in other modern languages:</p> <pre><code>string = loadFromSomeWhere(URI) dictionary = JSON.parse(string) // do something with the dictionary </code></pre> <p>I do not want to define a POJO first, nor will I deal with the deepness of the JSON structure. And I can assume, that the file will stay small enought, so event driven parsing is not necessary.</p> <p>I need to use Jackson and found only way to complicated approaches.</p>
0debug
int coroutine_fn laio_co_submit(BlockDriverState *bs, LinuxAioState *s, int fd, uint64_t offset, QEMUIOVector *qiov, int type) { int ret; struct qemu_laiocb laiocb = { .co = qemu_coroutine_self(), .nbytes = qiov->size, .ctx = s, .is_read = (type == QEMU_AIO_READ), .qiov = qiov, }; ret = laio_do_submit(fd, &laiocb, offset, type); if (ret < 0) { return ret; } qemu_coroutine_yield(); return laiocb.ret; }
1threat
Visual studio warn a conflict in two exactly same tyope : This Warning make me crazy!!! Warning CS0436 The type 'TypeName' in TypeAddress conflicts with the imported type 'TypeName' in 'TypeAddress, TypeNames and TypeAddress are exactly the same. Why Visual studio should warn this?
0debug
int vnc_display_open(DisplayState *ds, const char *display) { VncState *vs = ds ? (VncState *)ds->opaque : vnc_state; const char *options; int password = 0; int reverse = 0; int to_port = 0; #ifdef CONFIG_VNC_TLS int tls = 0, x509 = 0; #endif vnc_display_close(ds); if (strcmp(display, "none") == 0) return 0; if (!(vs->display = strdup(display))) return -1; options = display; while ((options = strchr(options, ','))) { options++; if (strncmp(options, "password", 8) == 0) { password = 1; } else if (strncmp(options, "reverse", 7) == 0) { reverse = 1; } else if (strncmp(options, "to=", 3) == 0) { to_port = atoi(options+3) + 5900; #ifdef CONFIG_VNC_TLS } else if (strncmp(options, "tls", 3) == 0) { tls = 1; } else if (strncmp(options, "x509", 4) == 0) { char *start, *end; x509 = 1; if (strncmp(options, "x509verify", 10) == 0) vs->x509verify = 1; start = strchr(options, '='); end = strchr(options, ','); if (start && (!end || (start < end))) { int len = end ? end-(start+1) : strlen(start+1); char *path = qemu_malloc(len+1); pstrcpy(path, len, start + 1); path[len] = '\0'; VNC_DEBUG("Trying certificate path '%s'\n", path); if (vnc_set_x509_credential_dir(vs, path) < 0) { fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path); qemu_free(path); qemu_free(vs->display); vs->display = NULL; return -1; } qemu_free(path); } else { fprintf(stderr, "No certificate path provided\n"); qemu_free(vs->display); vs->display = NULL; return -1; } #endif } } if (password) { #ifdef CONFIG_VNC_TLS if (tls) { vs->auth = VNC_AUTH_VENCRYPT; if (x509) { VNC_DEBUG("Initializing VNC server with x509 password auth\n"); vs->subauth = VNC_AUTH_VENCRYPT_X509VNC; } else { VNC_DEBUG("Initializing VNC server with TLS password auth\n"); vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC; } } else { #endif VNC_DEBUG("Initializing VNC server with password auth\n"); vs->auth = VNC_AUTH_VNC; #ifdef CONFIG_VNC_TLS vs->subauth = VNC_AUTH_INVALID; } #endif } else { #ifdef CONFIG_VNC_TLS if (tls) { vs->auth = VNC_AUTH_VENCRYPT; if (x509) { VNC_DEBUG("Initializing VNC server with x509 no auth\n"); vs->subauth = VNC_AUTH_VENCRYPT_X509NONE; } else { VNC_DEBUG("Initializing VNC server with TLS no auth\n"); vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE; } } else { #endif VNC_DEBUG("Initializing VNC server with no auth\n"); vs->auth = VNC_AUTH_NONE; #ifdef CONFIG_VNC_TLS vs->subauth = VNC_AUTH_INVALID; } #endif } if (reverse) { if (strncmp(display, "unix:", 5) == 0) vs->lsock = unix_connect(display+5); else vs->lsock = inet_connect(display, SOCK_STREAM); if (-1 == vs->lsock) { free(vs->display); vs->display = NULL; return -1; } else { vs->csock = vs->lsock; vs->lsock = -1; vnc_connect(vs); } return 0; } else { char *dpy; dpy = qemu_malloc(256); if (strncmp(display, "unix:", 5) == 0) { strcpy(dpy, "unix:"); vs->lsock = unix_listen(display, dpy+5, 256-5); } else { vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900); } if (-1 == vs->lsock) { free(dpy); } else { free(vs->display); vs->display = dpy; } } return qemu_set_fd_handler2(vs->lsock, vnc_listen_poll, vnc_listen_read, NULL, vs); }
1threat
In GraphQL what's the meaning of "edges" and "node"? : <p>I am consuming a particular GraphQL endpoint and although I am supplying a clean JSON structure as a query, when I get the results I get "edges" and "node" tags. It seems as if it is polluting my data with no obvious benefit. Why is it there and is it possible to get rid of those for faster and simpler parsing of data?</p>
0debug
git rebase using sourcetree : <p>I think I am confused on how to use SourceTree GUI to do git rebase. I have two branches "master" and "dev". As seen, the two branch diverged. I want to do a rebase on "dev" branch, using command line, this would be:</p> <pre><code>git checkout dev git rebase master </code></pre> <p><a href="https://i.stack.imgur.com/POAIV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/POAIV.png" alt="enter image description here"></a></p> <p>I would have expected to right click "dev", and choose "Rebase current changes onto dev". I assume current changes means "new commits on master". But picking this option seems have no effect whatsoever. What would be the correct steps?</p>
0debug
bool aio_poll(AioContext *ctx, bool blocking) { AioHandler *node; int i; int ret = 0; bool progress; int64_t timeout; int64_t start = 0; if (blocking) { atomic_add(&ctx->notify_me, 2); } qemu_lockcnt_inc(&ctx->list_lock); if (ctx->poll_max_ns) { start = qemu_clock_get_ns(QEMU_CLOCK_REALTIME); } progress = try_poll_mode(ctx, blocking); if (!progress) { assert(npfd == 0); if (!aio_epoll_enabled(ctx)) { QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) { if (!node->deleted && node->pfd.events && aio_node_check(ctx, node->is_external)) { add_pollfd(node); } } } timeout = blocking ? aio_compute_timeout(ctx) : 0; if (aio_epoll_check_poll(ctx, pollfds, npfd, timeout)) { AioHandler epoll_handler; epoll_handler.pfd.fd = ctx->epollfd; epoll_handler.pfd.events = G_IO_IN | G_IO_OUT | G_IO_HUP | G_IO_ERR; npfd = 0; add_pollfd(&epoll_handler); ret = aio_epoll(ctx, pollfds, npfd, timeout); } else { ret = qemu_poll_ns(pollfds, npfd, timeout); } } if (blocking) { atomic_sub(&ctx->notify_me, 2); } if (ctx->poll_max_ns) { int64_t block_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - start; if (block_ns <= ctx->poll_ns) { } else if (block_ns > ctx->poll_max_ns) { int64_t old = ctx->poll_ns; if (ctx->poll_shrink) { ctx->poll_ns /= ctx->poll_shrink; } else { ctx->poll_ns = 0; } trace_poll_shrink(ctx, old, ctx->poll_ns); } else if (ctx->poll_ns < ctx->poll_max_ns && block_ns < ctx->poll_max_ns) { int64_t old = ctx->poll_ns; int64_t grow = ctx->poll_grow; if (grow == 0) { grow = 2; } if (ctx->poll_ns) { ctx->poll_ns *= grow; } else { ctx->poll_ns = 4000; } if (ctx->poll_ns > ctx->poll_max_ns) { ctx->poll_ns = ctx->poll_max_ns; } trace_poll_grow(ctx, old, ctx->poll_ns); } } aio_notify_accept(ctx); if (ret > 0) { for (i = 0; i < npfd; i++) { nodes[i]->pfd.revents = pollfds[i].revents; } } npfd = 0; qemu_lockcnt_dec(&ctx->list_lock); if (aio_dispatch(ctx, ret > 0)) { progress = true; } return progress; }
1threat
< operator in Go lang : <p>Well I am a newby in Go lang, but this doesn't make sense to me:</p> <pre><code>package main import ( "fmt" "log" ) var rectLen, rectWidth float64 = 0, 0 func init() { fmt.Println("init is initialized") if rectLen &lt; 0 { log.Fatal("rectLen smaller than 0") } if rectWidth &lt; 0 { log.Fatal("rectWidht smaller than 0") } } func main() { fmt.Println("Main is initialized") fmt.Println(rectLen, rectWidth ) } </code></pre> <p>This will print out:</p> <pre><code>init is initialized Main is initialized 0 0 </code></pre> <p>Why is 0 and 0 printed out when my init function is "guarding" that my rectLen, rectWidth variables should be strictly greater than 0? If I change the values to something less than 0, it works fine, I get: </p> <pre><code>init is initialized 2009/11/10 23:00:00 rectLen smaller than 0 </code></pre> <p>Thanks!</p>
0debug
int kqemu_cpu_exec(CPUState *env) { struct kqemu_cpu_state kcpu_state, *kenv = &kcpu_state; int ret, cpl, i; #ifdef CONFIG_PROFILER int64_t ti; #endif #ifdef _WIN32 DWORD temp; #endif #ifdef CONFIG_PROFILER ti = profile_getclock(); #endif LOG_INT("kqemu: cpu_exec: enter\n"); LOG_INT_STATE(env); for(i = 0; i < CPU_NB_REGS; i++) kenv->regs[i] = env->regs[i]; kenv->eip = env->eip; kenv->eflags = env->eflags; for(i = 0; i < 6; i++) kqemu_load_seg(&kenv->segs[i], &env->segs[i]); kqemu_load_seg(&kenv->ldt, &env->ldt); kqemu_load_seg(&kenv->tr, &env->tr); kqemu_load_seg(&kenv->gdt, &env->gdt); kqemu_load_seg(&kenv->idt, &env->idt); kenv->cr0 = env->cr[0]; kenv->cr2 = env->cr[2]; kenv->cr3 = env->cr[3]; kenv->cr4 = env->cr[4]; kenv->a20_mask = env->a20_mask; kenv->efer = env->efer; kenv->tsc_offset = 0; kenv->star = env->star; kenv->sysenter_cs = env->sysenter_cs; kenv->sysenter_esp = env->sysenter_esp; kenv->sysenter_eip = env->sysenter_eip; #ifdef TARGET_X86_64 kenv->lstar = env->lstar; kenv->cstar = env->cstar; kenv->fmask = env->fmask; kenv->kernelgsbase = env->kernelgsbase; #endif if (env->dr[7] & 0xff) { kenv->dr7 = env->dr[7]; kenv->dr0 = env->dr[0]; kenv->dr1 = env->dr[1]; kenv->dr2 = env->dr[2]; kenv->dr3 = env->dr[3]; } else { kenv->dr7 = 0; } kenv->dr6 = env->dr[6]; cpl = (env->hflags & HF_CPL_MASK); kenv->cpl = cpl; kenv->nb_pages_to_flush = nb_pages_to_flush; kenv->user_only = (env->kqemu_enabled == 1); kenv->nb_ram_pages_to_update = nb_ram_pages_to_update; nb_ram_pages_to_update = 0; kenv->nb_modified_ram_pages = nb_modified_ram_pages; kqemu_reset_modified_ram_pages(); if (env->cpuid_features & CPUID_FXSR) restore_native_fp_fxrstor(env); else restore_native_fp_frstor(env); #ifdef _WIN32 if (DeviceIoControl(kqemu_fd, KQEMU_EXEC, kenv, sizeof(struct kqemu_cpu_state), kenv, sizeof(struct kqemu_cpu_state), &temp, NULL)) { ret = kenv->retval; } else { ret = -1; } #else ioctl(kqemu_fd, KQEMU_EXEC, kenv); ret = kenv->retval; #endif if (env->cpuid_features & CPUID_FXSR) save_native_fp_fxsave(env); else save_native_fp_fsave(env); for(i = 0; i < CPU_NB_REGS; i++) env->regs[i] = kenv->regs[i]; env->eip = kenv->eip; env->eflags = kenv->eflags; for(i = 0; i < 6; i++) kqemu_save_seg(&env->segs[i], &kenv->segs[i]); cpu_x86_set_cpl(env, kenv->cpl); kqemu_save_seg(&env->ldt, &kenv->ldt); env->cr[0] = kenv->cr0; env->cr[4] = kenv->cr4; env->cr[3] = kenv->cr3; env->cr[2] = kenv->cr2; env->dr[6] = kenv->dr6; #ifdef TARGET_X86_64 env->kernelgsbase = kenv->kernelgsbase; #endif if (kenv->nb_pages_to_flush >= KQEMU_FLUSH_ALL) { tlb_flush(env, 1); } else { for(i = 0; i < kenv->nb_pages_to_flush; i++) { tlb_flush_page(env, pages_to_flush[i]); } } nb_pages_to_flush = 0; #ifdef CONFIG_PROFILER kqemu_time += profile_getclock() - ti; kqemu_exec_count++; #endif if (kenv->nb_ram_pages_to_update > 0) { cpu_tlb_update_dirty(env); } if (kenv->nb_modified_ram_pages > 0) { for(i = 0; i < kenv->nb_modified_ram_pages; i++) { unsigned long addr; addr = modified_ram_pages[i]; tb_invalidate_phys_page_range(addr, addr + TARGET_PAGE_SIZE, 0); } } { unsigned int new_hflags; #ifdef TARGET_X86_64 if ((env->hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) { new_hflags = HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK; } else #endif { new_hflags = (env->segs[R_CS].flags & DESC_B_MASK) >> (DESC_B_SHIFT - HF_CS32_SHIFT); new_hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >> (DESC_B_SHIFT - HF_SS32_SHIFT); if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK) || !(env->hflags & HF_CS32_MASK)) { new_hflags |= HF_ADDSEG_MASK; } else { new_hflags |= ((env->segs[R_DS].base | env->segs[R_ES].base | env->segs[R_SS].base) != 0) << HF_ADDSEG_SHIFT; } } env->hflags = (env->hflags & ~(HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)) | new_hflags; } env->hflags = (env->hflags & ~(HF_MP_MASK | HF_EM_MASK | HF_TS_MASK)) | ((env->cr[0] << (HF_MP_SHIFT - 1)) & (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK)); if (env->cr[4] & CR4_OSFXSR_MASK) env->hflags |= HF_OSFXSR_MASK; else env->hflags &= ~HF_OSFXSR_MASK; LOG_INT("kqemu: kqemu_cpu_exec: ret=0x%x\n", ret); if (ret == KQEMU_RET_SYSCALL) { return do_syscall(env, kenv); } else if ((ret & 0xff00) == KQEMU_RET_INT) { env->exception_index = ret & 0xff; env->error_code = 0; env->exception_is_int = 1; env->exception_next_eip = kenv->next_eip; #ifdef CONFIG_PROFILER kqemu_ret_int_count++; #endif LOG_INT("kqemu: interrupt v=%02x:\n", env->exception_index); LOG_INT_STATE(env); return 1; } else if ((ret & 0xff00) == KQEMU_RET_EXCEPTION) { env->exception_index = ret & 0xff; env->error_code = kenv->error_code; env->exception_is_int = 0; env->exception_next_eip = 0; #ifdef CONFIG_PROFILER kqemu_ret_excp_count++; #endif LOG_INT("kqemu: exception v=%02x e=%04x:\n", env->exception_index, env->error_code); LOG_INT_STATE(env); return 1; } else if (ret == KQEMU_RET_INTR) { #ifdef CONFIG_PROFILER kqemu_ret_intr_count++; #endif LOG_INT_STATE(env); return 0; } else if (ret == KQEMU_RET_SOFTMMU) { #ifdef CONFIG_PROFILER { unsigned long pc = env->eip + env->segs[R_CS].base; kqemu_record_pc(pc); } #endif LOG_INT_STATE(env); return 2; } else { cpu_dump_state(env, stderr, fprintf, 0); fprintf(stderr, "Unsupported return value: 0x%x\n", ret); exit(1); } return 0; }
1threat
QEMUFile *qemu_fopen(const char *filename, const char *mode) { QEMUFile *f; f = qemu_mallocz(sizeof(QEMUFile)); if (!f) return NULL; if (!strcmp(mode, "wb")) { f->is_writable = 1; } else if (!strcmp(mode, "rb")) { f->is_writable = 0; } else { goto fail; } f->outfile = fopen(filename, mode); if (!f->outfile) goto fail; f->is_file = 1; return f; fail: if (f->outfile) fclose(f->outfile); qemu_free(f); return NULL; }
1threat
query = 'SELECT * FROM customers WHERE email = ' + email_input
1threat
Is there any other way to print mysql table in html like a matrix from? : i am currently working on a college project.The requirement is to print the data(subject ,class,section) to the corresponding day and hour in html table.I tried my best to achieve the requirement but the html table just prints again and prints the next value where i want all my data to be printed in a single table to corresponding day and hour . here is the image of my database : https://imgur.com/a/G4ylbV5 And here is my output which am not satisfied with: https://imgur.com/a/oa8OLyT Here is my code: https://imgur.com/a/2rAT1Ax i expect the output to be a single table with all the respected data in the corresponding place.
0debug
Building a Card Stack : <p>I am developing an app that is centered around a card stack. I am struggling to find a way to implement this particular stack (the stacking itself is a problem e.g. being able to swipe through each card) but I am mainly trying to figure out how to style the card so that only parts of it is colored (the yellow being kept at the top and bottom). Any direction on how to implement this style would be appreciated! </p> <p><a href="https://i.stack.imgur.com/K364J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K364J.png" alt="enter image description here"></a></p>
0debug
Questions in using eclipse : when I use eclipse if neon to type javascript file ,I often come to white color which covers the words I typing as this pictures[enter image description here][1] I have to close this file and open again ,It will be disappear,but it will appear soon. how should I solve this question? [1]: http://i.stack.imgur.com/7zn6l.png
0debug
c- displaying CPU info using kernel module : I've recently learned about kernel modules and I was thinking on how to create one that does what cat /proc/cpuinfo does. Is it possible to do this without opening/reading the file directly (fread)? Thanks in advance!
0debug
Include another perl script in my parent perl script : How can I include another perl script in my base perl script. For example, I have test.pl which is parent script. I want to include config.pl in my parent script i.e., in test.pl. What is the standard method to achieve this in perl.
0debug
encode a string to a lenght of {n < 150} signs and decode it later? : <p>I would like to encode a string to another string with a lenght of &lt; or = 150 I know that sha-1 can do that but here is the point: I want to decode it later (without a supercomputer!)</p> <p>I am searching for an algorithm. My favourite languages are: java and python but when i know the algorithm i could implement it...</p>
0debug
TypeScript A computed property name in a type literal must directly refer to a built-in symbol : <blockquote> <p>ERROR in ...component.ts (..,..): A computed property name in a type literal must directly refer to a built- in symbol. ...: Cannot find name 'any'.</p> </blockquote> <p>I'm looking forward an object which contains strings which have other string, i.e:</p> <pre><code>{ abc: 'xyz' } </code></pre> <p>What I did:</p> <pre><code>foo: { [string]: string }; </code></pre>
0debug
static int load_dtb(target_phys_addr_t addr, const struct arm_boot_info *binfo) { #ifdef CONFIG_FDT uint32_t *mem_reg_property; uint32_t mem_reg_propsize; void *fdt = NULL; char *filename; int size, rc; uint32_t acells, scells, hival; filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, binfo->dtb_filename); if (!filename) { fprintf(stderr, "Couldn't open dtb file %s\n", binfo->dtb_filename); return -1; } fdt = load_device_tree(filename, &size); if (!fdt) { fprintf(stderr, "Couldn't open dtb file %s\n", filename); g_free(filename); return -1; } g_free(filename); acells = qemu_devtree_getprop_cell(fdt, "/", "#address-cells"); scells = qemu_devtree_getprop_cell(fdt, "/", "#size-cells"); if (acells == 0 || scells == 0) { fprintf(stderr, "dtb file invalid (#address-cells or #size-cells 0)\n"); return -1; } mem_reg_propsize = acells + scells; mem_reg_property = g_new0(uint32_t, mem_reg_propsize); mem_reg_property[acells - 1] = cpu_to_be32(binfo->loader_start); hival = cpu_to_be32(binfo->loader_start >> 32); if (acells > 1) { mem_reg_property[acells - 2] = hival; } else if (hival != 0) { fprintf(stderr, "qemu: dtb file not compatible with " "RAM start address > 4GB\n"); exit(1); } mem_reg_property[acells + scells - 1] = cpu_to_be32(binfo->ram_size); hival = cpu_to_be32(binfo->ram_size >> 32); if (scells > 1) { mem_reg_property[acells + scells - 2] = hival; } else if (hival != 0) { fprintf(stderr, "qemu: dtb file not compatible with " "RAM size > 4GB\n"); exit(1); } rc = qemu_devtree_setprop(fdt, "/memory", "reg", mem_reg_property, mem_reg_propsize * sizeof(uint32_t)); if (rc < 0) { fprintf(stderr, "couldn't set /memory/reg\n"); } if (binfo->kernel_cmdline && *binfo->kernel_cmdline) { rc = qemu_devtree_setprop_string(fdt, "/chosen", "bootargs", binfo->kernel_cmdline); if (rc < 0) { fprintf(stderr, "couldn't set /chosen/bootargs\n"); } } if (binfo->initrd_size) { rc = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-start", binfo->loader_start + INITRD_LOAD_ADDR); if (rc < 0) { fprintf(stderr, "couldn't set /chosen/linux,initrd-start\n"); } rc = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-end", binfo->loader_start + INITRD_LOAD_ADDR + binfo->initrd_size); if (rc < 0) { fprintf(stderr, "couldn't set /chosen/linux,initrd-end\n"); } } cpu_physical_memory_write(addr, fdt, size); return 0; #else fprintf(stderr, "Device tree requested, " "but qemu was compiled without fdt support\n"); return -1; #endif }
1threat
static void audio_detach_capture (HWVoiceOut *hw) { SWVoiceCap *sc = hw->cap_head.lh_first; while (sc) { SWVoiceCap *sc1 = sc->entries.le_next; SWVoiceOut *sw = &sc->sw; CaptureVoiceOut *cap = sc->cap; int was_active = sw->active; if (sw->rate) { st_rate_stop (sw->rate); sw->rate = NULL; } LIST_REMOVE (sw, entries); LIST_REMOVE (sc, entries); qemu_free (sc); if (was_active) { audio_recalc_and_notify_capture (cap); } sc = sc1; } }
1threat
How can I force 2 fields in a Django model to share the same default value without repeating populating method? : <p>I have a Django model <code>MyModel</code> as shown below. </p> <p>It has two fields of type DateTimeField: <code>my_field1</code>, <code>my_field2</code></p> <pre><code>from django.db import models from datetime import datetime class MyModel(models.Model): my_field1 = models.DateTimeField(default=datetime.utcnow, editable=False) my_field2 = models.DateTimeField() </code></pre> <p>I want both fields to default to the value of <code>datetime.utcnow()</code>. But I want to save <strong><em>the same</em></strong> value for both. It seems wasteful to call <code>utcnow()</code> twice.</p> <p>How can I set the default value of <code>my_field2</code> so that it simply copies the default value of <code>my_field1</code>?</p> <p>I tried adding an <code>__init__()</code> method to <code>MyModel</code> like this:</p> <pre><code>def __init__(self, **kwargs): super(MyModel, self).__init__(**kwargs) if self.my_field2 is None: self.my_field2 = self.my_field1 </code></pre> <p>But doing so broke the model as you can see here:</p> <pre><code>&gt;&gt;&gt; MyModel.objects.all() Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "MYvirtualenv/lib/python2.7/site-packages/django/db/models/query.py", line 138, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "MYvirtualenv/lib/python2.7/site-packages/django/db/models/query.py", line 162, in __iter__ self._fetch_all() File "MYvirtualenv/lib/python2.7/site-packages/django/db/models/query.py", line 965, in _fetch_all self._result_cache = list(self.iterator()) File "MYvirtualenv/src/django-cache-machine-master/caching/base.py", line 118, in __iter__ obj = iterator.next() File "MYvirtualenv/lib/python2.7/site-packages/django/db/models/query.py", line 255, in iterator obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end]) File "MYvirtualenv/lib/python2.7/site-packages/django/db/models/base.py", line 489, in from_db new = cls(*values) TypeError: __init__() takes exactly 1 argument (2 given) </code></pre> <p>What is the proper remedy? I need the value of <code>my_field2</code> to default to the value of <code>my_field1</code> (without calling the repeating the call to the default function that populated <code>my_field1</code>)</p>
0debug
Queries reagding basics of PCA : I want to use PCA for the feature selection with CNN features. From the theory of PCA, the data should correlated. After extracting the features from CNN the features are organized is this way [f1 f2 f3 f4 f5 f6] and the corresponding labels are [L1 L1 L2 L2 L3 L3]. How can I check my data is correlated? and if the data is not correlated than how can I make one?
0debug
How to add a redirect to https? : <p>I already have a redirect to the main page of the site:</p> <pre><code>RewriteEngine On RewriteRule ^$ index.php [QSA] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php/$1 [QSA,L] </code></pre> <p>But if you type <code>domain.com</code>, then the redirection will be to <code>example.com/index.php</code> But I need to redirect immediately to <code>https://example.com/index.php</code></p>
0debug
indicate if an element can be found in another vector in R : <p>two vectors (a,b) of type integer. 'b' is smaller than 'a'. I need a logical vector for 'a', indicating if a specific element of 'a' is part of 'b'. </p> <p>Is there a economic solution similar to '%in%' (which can not serve here)? Thanks in advance!</p>
0debug